VB本身不允许你将一个Form、UserControl或PictureBox上的完整图片复制到剪贴板。如果你使用Clipboard.SetData,将只复制被载入这个对象的位图。通过使用API方法,你可以超越这个限制,保证全部内容都被复制,包括你刚刚画上的任何图形。
开始一个新项目,在窗体上放置一个Command和一个PictureBox。将PictureBox的Autoredraw属性设为1。然后添加一个标准模块,把以下代码复制进去。
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
'GDI函数:
Private Declare Function BitBlt Lib "gdi32" (ByVal hDestDC As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc As Long, ByVal dwRop As Long) As Long
Private Const SRCCOPY = &HCC0020 ' (DWORD) dest = source
'创建一个memory DC:
Declare Function CreateCompatibleDC Lib "gdi32" (ByVal hDC As Long) As Long
'在memory中建立一个位图:
Declare Function CreateCompatibleBitmap Lib "gdi32" (ByVal hDC As Long, ByVal nWidth As Long, ByVal nHeight As Long) As Long
'把一个GDI对象放入DC,返回原先的那个:
Declare Function SelectObject Lib "gdi32" (ByVal hDC As Long, ByVal hObject As Long) As Long
'删除GDI对象:
Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long
'剪贴板函数:
Private Declare Function OpenClipboard Lib "USER32" (ByVal hWnd As Long) As Long
Private Declare Function CloseClipboard Lib "USER32" () As Long
Private Declare Function SetClipboardData Lib "USER32" (ByVal wFormat As Long, ByVal hMem As Long) As Long
Private Declare Function EmptyClipboard Lib "USER32" () As Long
Private Const CF_BITMAP = 2
Public Function CopyEntirePicture(ByRef objFrom As Object) As Boolean
Dim lhDC As Long
Dim lhBMP As Long
Dim lhBMPOld As Long
'在内存中建立一个指向我们将要复制对象的DC:
lhDC = CreateCompatibleDC(objFrom.hDC)
If (lhDC <> 0) Then
'建立一张指向将要复制对象的位图:
lhBMP = CreateCompatibleBitmap(objFrom.hDC, objFrom.ScaleWidth \ Screen.TwipsPerPixelX, objFrom.ScaleHeight \ Screen.TwipsPerPixelY)
If (lhBMP <> 0) Then
'把位图选入我们刚才建立的DC中,并贮存原先在那里的老位图:
lhBMPOld = SelectObject(lhDC, lhBMP)
'把objFrom的内容复制到建立的位图里:
BitBlt lhDC, 0, 0, objFrom.ScaleWidth \ Screen.TwipsPerPixelX, objFrom.ScaleHeight \ Screen.TwipsPerPixelY, objFrom.hDC, 0, 0, SRCCOPY
'恢复DC中的内容:
SelectObject lhDC, lhBMPOld
'现在把位图装入剪贴板:
EmptyClipboard
OpenClipboard 0
SetClipboardData CF_BITMAP, lhBMP
CloseClipboard
'我们在这里不用删除建立的位图——
'它现在属于剪贴板,当剪贴板变化时,Windows将为我们删除它。
End If
'清除刚才建立的DC:
DeleteObject lhDC
End If
End Function
为了试验这个方法,把这些代码加入窗体:
Private Sub Command1_Click()
CopyEntirePicture Picture1
End Sub
Private Sub Form_Load()
Dim i As Long
'在PictureBox中画些东西:
With Picture1.Font
.Name = "Arial"
.Bold = True
.Size = 12
End With
For i = 1 To 20
Picture1.ForeColor = QBColor(i Mod 15)
Picture1.Print "http://www.archtide.com"
Next i
End Sub
窗体加载后,PictureBox中将会有一些文本。当你点击Command后,PictureBox中的全部内容都将会被复制到剪贴板里,你可以把它粘贴到别的程序里,比如画笔、Word等等。