Imports System.Runtime.InteropServices
Public Class Form1
' 导入 SetParent 函数
<DllImport("user32.dll", SetLastError:=True)>
Private Shared Function SetParent(ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As IntPtr
End Function
' 导入 MoveWindow 函数
<DllImport("user32.dll", SetLastError:=True)>
Private Shared Function MoveWindow(ByVal hwnd As IntPtr, ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal bRepaint As Boolean) As Boolean
End Function
' 导入 FindWindow 函数
<DllImport("user32.dll", SetLastError:=True)>
Private Shared Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
End Function
' 申明常量
Private Const WM_PAINT As Integer = &HF
' 引入 SendMessage 函数
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
' 查询窗口句柄
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim handle As IntPtr = FindWindow("WeChatMainWndForPC", Nothing)
If handle <> IntPtr.Zero Then
' 将句柄转换为十进制整数
Dim handleDecimal As Integer = handle.ToInt32()
' 将句柄值显示在文本框中
TextBox1.Text = handleDecimal.ToString()
Else
' 如果未找到窗口则弹出消息框
MessageBox.Show("未找到名为 ChatWnd 的窗口")
End If
End Sub
' 创建子窗口并将其嵌入到指定窗口中
' 声明一个私有的方法,按钮 Button1 的单击事件处理程序。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' 获取父窗口句柄:从 TextBox1 控件中读取文本内容,并将其转换为整数类型后创建一个 IntPtr 类型的句柄变量。
Dim parentHWND As IntPtr = New IntPtr(CInt(TextBox1.Text))
' 创建子窗口:声明一个名为 subForm 的新的 Form 实例。
Dim subForm As New Form()
' 设置子窗口标题为“子窗口”。
subForm.Text = "子窗口"
' 设置子窗口的边框样式为固定对话框。
subForm.FormBorderStyle = FormBorderStyle.FixedDialog
' 设置子窗口的启动位置为手动。
subForm.StartPosition = FormStartPosition.Manual
' 设置子窗口的大小为 400x300 像素。
subForm.Size = New Size(400, 300)
' 将子窗口的父句柄设置为父窗口句柄。
SetParent(subForm.Handle, parentHWND)
' 重绘句柄内的组件并显示在子窗口上。
SendMessage(parentHWND, WM_PAINT, IntPtr.Zero, IntPtr.Zero)
' 设置子窗口的位置和大小:通过 MoveWindow API 函数将子窗口移动到窗口的左上角,大小与子窗口相同。
subForm.Show()
MoveWindow(subForm.Handle, 0, 0, subForm.Width, subForm.Height, True)
End Sub
End Class