using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace findwindow
{
public partial class Form1 : Form
{
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
public Form1()
{
InitializeComponent();
this.ShowInTaskbar = false;
}
private void button1_Click(object sender, EventArgs e)
{
//如找到目标窗口显示对应句柄;找不到显示0
IntPtr hwnd = FindWindow("CalcFrame", "计算器"); //
if (hwnd != IntPtr.Zero)
{
txt.AppendText("发现目示窗口,其句柄是:" + hwnd + "\n");
}
else
{
txt.AppendText("没有找到目标窗口" + "\n");
}
IntPtr sonhwnd = FindWindowEx(hwnd,IntPtr.Zero,"Button", "9");//获取名为“9”的按钮句柄
if (sonhwnd != IntPtr.Zero)
{
txt.AppendText("找到按钮");
}
else
{
txt.AppendText("句柄号为:" + sonhwnd.ToString() + " 没有找到目标句柄" + "\n");
}
}
}
}
建议你用spy++找一下这个9的class和caption,第三个第四个参数就是这两个,另外第二个参数是子窗口句柄,而且必须是parent的直接子窗口,如果你不知道可以写NULL。
最后可以多看看MSDN:https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-findwindowexa
你的用法没有问题,只是计算器中的那些按钮,包括9,是没有caption的,所以你最有一个参数输入9就找不到了。