Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Integer, _
ByVal lParam As Long) As Long
Declare Function FindWindow Lib "user32" Alias _
"FindWindowA" (ByVal lpClassName As String, ByVal _
lpWindowName As String) As Long
Declare Function LockWindowUpdate Lib "user32" (ByVal hwndLock As Long) As Long
Private Const WM_SETREDRAW = &HB
Private Sub tryThis()
Dim h As Long
h = FindWindow("xlMain", vbNullString)
LockWindowUpdate Application.VBE.MainWindow.hwnd
Call SendMessage(h, WM_SETREDRAW, 0, 0)
Application.SendKeys "Range", True
Application.SendKeys "~", True
Application.Goto Reference:="tryThis"
On Error Resume Next 'in case it's not there
With ThisWorkbook.VBProject.VBComponents("Module2").CodeModule
.DeleteLines 1, .CountOfLines
End With
Call SendMessage(h, WM_SETREDRAW, 1, 0)
Application.VBE.MainWindow.Visible = False
LockWindowUpdate 0
ThisWorkbook.Close True
End Sub
FindWindow(
lpClassName, {窗口的类名}
lpWindowName: PChar {窗口的标题}
): HWND; {返回窗口的句柄; 失败返回 0}
//FindWindowEx 比 FindWindow 多出两个句柄参数:
FindWindowEx(
Parent: HWND; {要查找子窗口的父窗口句柄}
Child: HWND; {子窗口句柄}
ClassName: PChar; {}
WindowName: PChar {}
): HWND;
{
如果 Parent 是 0, 则函数以桌面窗口为父窗口, 查找桌面窗口的所有子窗口;
如果 是 HWND_MESSAGE, 函数仅查找所有消息窗口;
子窗口必须是 Parent 窗口的直接子窗口;
如果 Child 是 0, 查找从 Parent 的第一个子窗口开始;
如果 Parent 和 Child 同时是 0, 则函数查找所有的顶层窗口及消息窗口.
}
//测试1: 试着找找新建程序主窗口的句柄
var
h: HWND;
begin
{现在我们知道窗口的标题是: Form1、窗口的类名是: TForm1}
h := FindWindow('TForm1', 'Form1');
ShowMessage(IntToStr(h)); {656180; 这是随机, 每次启动窗口肯定不一样}
{假如不知道类名}
h := FindWindow(nil, 'Form1');
ShowMessage(IntToStr(h)); {656180}
{假如不知道标题名}
h := FindWindow('TForm1', nil);
ShowMessage(IntToStr(h)); {656180}
{其实这个窗口的句柄不就是 Self.Handle 吗}
ShowMessage(IntToStr(Handle)); {656180}
end;
//测试2: 找计算器窗口的句柄(先打开计算器)
var
h: HWND;
begin
{如果不是简体中文系统, 这样可能不灵}
h := FindWindow(nil, '计算器');
ShowMessage(IntToStr(h)); {1508334}
{最好这样, 但你得提前知道计算器窗口的类名是: SciCalc}
h := FindWindow('SciCalc', nil);
ShowMessage(IntToStr(h)); {1508334}
end;