FindWindowEx函数

当你想控制一个现有的窗口程序时,就需要获取那个程序的窗口句柄。比如有一些黑客软件需要查找到窗口,然后修改窗口的标题。在外挂流行的今天,惊奇地发现它们也可以修改输入窗口的文字。这其中,就需要使用到FindWindowEx函数来定位窗口。下面就来使用这个函数来实现控制Windows里带的计算器程序。打开计算器程序,最小化在状态下面,运行本例子,点击创建按钮后,就可以点按钮,就会把计算器显示在最前面。

函数FindWindowEx声明如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//C#
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);

//VB
DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindowEx(ByVal parentHandle As IntPtr, _
ByVal childAfter As IntPtr, _
ByVal lclassName As String, _
ByVal windowTitle As String) As IntPtr
End Function

hWndParent是找查窗口的父窗口句柄,如果父窗口是桌面,就可以设置为NULL。

hWndChildAfter是子窗口开始位置。

lpszClass是窗口注册的类型。

lpszWindow是窗口的标题。

调用这个函数的例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
private IntPtr GetHandleToHorizontalScrollBar(Control parent)
{
// Locals
IntPtr childHandle;
string appDomainHexedHash;

// Get the hexadecimal value of AppDomain hash code.
// This value is dynamically appended to the window class name of the child window
// for .NET Windows Forms. This name is viewable via the Spy++ tool.
appDomainHexedHash = AppDomain.CurrentDomain.GetHashCode().ToString("x");

// Find window handle
childHandle = FindWindowEx(
parent.Handle, // Parent handle
IntPtr.Zero, // Child window after which to seek
"WindowsForms10.SCROLLBAR.app.0." + appDomainHexedHash, // Class name to seek (viewable in the Spy++ tool)
IntPtr.Zero); // Window title to seek

// Return handle
return childHandle;
}

private string GetUrlFromIE()
{
IntPtr windowHandle = GetForegroundWindow();
IntPtr childHandle;
String strUrlToReturn = "";

//try to get a handle to IE's toolbar container
childHandle = FindWindowEx(windowHandle,IntPtr.Zero,"WorkerW",IntPtr.Zero);
if(childHandle != IntPtr.Zero)
{
//get a handle to address bar
childHandle = FindWindowEx(childHandle,IntPtr.Zero,"ReBarWindow32",IntPtr.Zero);
if(childHandle != IntPtr.Zero)
{
// get a handle to combo boxex
childHandle = FindWindowEx(childHandle, IntPtr.Zero, "ComboBoxEx32", IntPtr.Zero);
if(childHandle != IntPtr.Zero)
{
// get a handle to combo box
childHandle = FindWindowEx(childHandle, IntPtr.Zero, "ComboBox", IntPtr.Zero);
if(childHandle != IntPtr.Zero)
{
//get handle to edit
childHandle = FindWindowEx(childHandle, IntPtr.Zero, "Edit", IntPtr.Zero);
if (childHandle != IntPtr.Zero)
{
strUrlToReturn = GetText(childHandle);
}
}
}
}
}
return strUrlToReturn;
}