VB.NET BitBlt将位图复制到屏幕

时间:2012-03-07 00:29:50

标签: vb.net bitblt

编辑:修复后,我为图形对象创建了一个compatibleDC,并为位图创建了一个句柄(使用b.gethbitmap),然后使用GDI中的SelectObject函数选择那两个,并使用compatibleDC而不是BitBlt函数中的hDc

我一直在尝试在屏幕上绘制一个位图(设备0),但是我在使用BitBlt复制图形时遇到了问题。

最初,我使用SetPixel(gdi32)直接绘制到桌面,但速度很慢,所以现在我设置位图对象的像素,然后从该对象创建图形,并将图形的hdc复制到屏幕。

我的猜测是我将图形对象的HDC添加到一个intptr,它实际上给了我图形对象容器的HDC,这不是我需要的。尽管如此,我还没有找到任何关于如何将位图复制到设备而不是使用BitBlt的信息。

这是我当前的代码(Windows窗体应用程序,文本框,按钮)文本框是要复制到的设备,按钮启动它。出于测试目的,将文本框文本设置为0,然后按按钮。你应该在屏幕的左上角看到一个黑盒子(50x50px)。如果工作正常,颜色应为蓝色:

Public Class Form1
Declare Function GetDC Lib "user32.dll" (ByVal hwnd As Int32) As Int32
Declare Function ReleaseDC Lib "user32.dll" (ByVal hwnd As Int32, ByVal hdc As Int32) As Int32
Declare Function SetPixel Lib "gdi32.dll" (ByVal hdc As Integer, ByVal x As Integer, ByVal y As Integer, ByVal crColor As Integer) As Integer
Declare Function BitBlt Lib "gdi32.dll" (ByVal hdcDest As IntPtr, ByVal nXDest As Integer, ByVal nYDest As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal hdcSrc As IntPtr, ByVal nXSrc As Integer, ByVal nYSrc As Integer, ByVal dwRop As Int32) As Boolean
Declare Function CreateCompatibleBitmap Lib "gdi32.dll" (ByVal hdc As IntPtr, ByVal nWidth As Integer, ByVal nHeight As Integer) As IntPtr
Declare Function CreateCompatibleDC Lib "gdi32.dll" (ByVal hdc As IntPtr) As IntPtr
Dim x As Integer
Sub setpx(ByVal location As Point, ByVal color As Color)
    b.SetPixel(location.X, location.Y, color)
End Sub
Sub drawrectangle(ByVal device As Integer, ByVal location As Point, ByVal size As Point, ByVal color As Color)
    b = New Bitmap(size.X, size.Y)
    For i = location.X To size.X - 1
        For z = location.Y To size.Y - 1
            setpx(New Point(i, z), color)
        Next
    Next
    g = Graphics.FromImage(b)
    Dim hDc As IntPtr = g.GetHdc
    BitBlt(GetDC(device), location.X, location.Y, size.X, size.Y, hDc, location.X, location.Y, 13369376)
    ReleaseDC(device, GetDC(device))
End Sub
Dim b As Bitmap
Dim g As Graphics
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Buttnon1.Click
    Dim r As New Random
    Dim timestart As Integer = Now.TimeOfDay.TotalMilliseconds
    drawrectangle(TextBox1.Text, New Point(1, 1), New Point(50, 50), Color.Blue)
    MsgBox(Now.TimeOfDay.TotalMilliseconds - timestart)
End Sub
End Class

它的工作方式是调用函数setpx,给定一个循环内的位置和颜色,迭代一个框中的所有像素(在我的代码中为50x50)。然后setpx函数将调用位图b上的setpixel函数。这部分工作正常。

接下来,它将从位图定义图形对象g,并使用BitBlt将g的hdc(g.gethdc)复制到屏幕。这样做不正确,这是正确的做法吗?

1 个答案:

答案 0 :(得分:0)

您正在将Textbox1.text作为设备描述符传递,这将无效...您需要textbox1.hwnd