如何在vba中用GDI函数LineTo在屏幕上画线?

api 中的gdi  函数 LineTo 可以在屏幕上画线。

它的语法如下:

BOOL LineTo(
  _In_ HDC hdc,
  _In_ int nXEnd,
  _In_ int nYEnd
);

它将直接连接当前位置和nXEnd和nYEnd所代表的结束位置两点成线。如果运行成功,结束位置将成为下一个当前位置。

代码如下:

Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hdc As Long) As Long
Declare Function LineTo Lib "gdi32" (ByVal hdc As Long, ByVal nXEnd As Long, ByVal nYEnd As Long) As Long
Sub QQ1722187970()
    Dim hdc As Long
    hdc = GetDC(0)
    LineTo hdc, 500, 500
    ReleaseDC 0, hdc
End Sub

GetDC(0)获得是整个屏幕的DC,它的当前位置是屏幕的左上角。

由于 LineTo 函数的起始位置默认位于屏幕或者客户区的左上角,如果要改变默认的起始位置,可以使用MoveToEx函数,设置一个起始位置的坐标。

它的语法如下:

BOOL MoveToEx(
  _In_  HDC     hdc,
  _In_  int     X,
  _In_  int     Y,
  _Out_ LPPOINT lpPoint
);

其中lpPoint参数是point结构,存储的是上一个位置的坐标。

以下代码是用MoveToEx函数和LineTo函数在屏幕上画长方形的代码:

Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hdc As Long) As Long
Declare Function LineTo Lib "gdi32" (ByVal hdc As Long, ByVal nXEnd As Long, ByVal nYEnd As Long) As Long
Declare Function MoveToEx Lib "gdi32" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, lpPoint As POINTAPI) As Long
Type POINTAPI
    x As Long
    y As Long
End Type
Sub QQ1722187970()
    Dim hdc As Long
    Dim oP As POINTAPI
    hdc = GetDC(0)
    MoveToEx hdc, 500, 500, oP
    LineTo hdc, 500, 700
    LineTo hdc, 1000, 700
    LineTo hdc, 1000, 500
    LineTo hdc, 500, 500
    ReleaseDC 0, hdc
End Sub
       

发表评论