private void btnControl_Click(object sender, EventArgs e)
{
IntPtr mainWindows = FindMainWindowHandle("Form1",100,25);
IntPtr needbtn = FindWindowEx(mainWindows, IntPtr.Zero,null, "button1"); //获取名字为button1的按钮
if(needbtn==IntPtr.Zero)
throw new Exception("没有找到名字为1的按钮");
else
{
PostMessage(needbtn,0x0201,0,0);
PostMessage(needbtn,0x0202,0,0);
MessageBox.Show("找到控件");
}
//PostMessage(needbtn, 0x0201, 0, 0);
//PostMessage(needbtn, 0x0202, 0, 0);
}
//获得待测程序主窗体句柄
private static IntPtr FindMainWindowHandle(string caption, int delay, int maxTries)
{
IntPtr mwh = IntPtr.Zero;
bool formFound = false;
int attempts = 0;
while (!formFound && attempts < maxTries)
{
if (mwh == IntPtr.Zero)
{
//MessageBox.Show("没有找到目标窗体", "错误提示");
Thread.Sleep(delay);
++attempts;
mwh = FindWindow(null, caption);
}
else
{
formFound = true;
}
}
if (mwh == IntPtr.Zero)
throw new Exception("Could not find main window");
else
return mwh;
}
这是本人要操作的Form1:

解决方案
20
同一时刻窗口标题为”Form1″的窗体是不是只有一个?有没有可能你是获取的另一个窗体,而这个窗体里没有button1?
假如你的目标窗体和你贴的代码在同一个程序里面,直接用XXForm.Handle来获取窗口句柄,代替mainWindows传递给函数试试看。
多用用Spy++,查找窗体、控件那叫一个爽
假如你的目标窗体和你贴的代码在同一个程序里面,直接用XXForm.Handle来获取窗口句柄,代替mainWindows传递给函数试试看。
多用用Spy++,查找窗体、控件那叫一个爽
10
和spy++对照下,看看你的句柄找的是不是不对。
10
最好用spy++检查一下这个按钮的标题是不是button1 或检查是不是桌面上有多个名为Form1的窗体