我已经成功编写了一个应用程序来按下另一个应用程序中的按钮。现在我试图在循环中重复按下按钮,我的应用程序挂起,但我不明白为什么。
上下文
我有一个对我很有帮助的应用程序,但开发它的人并没有想到一切。在应用程序中的某个时刻,会打开一个对话框,要求确认用已上载的数据替换现有数据。我需要点击确定同意,但问题是我将大量数据上传到此应用程序,并且它没有“全部适用”复选框。所以我必须反复点击确定。因此,我正在处理一个应用程序,它会按下 OK 按钮,直到对话框停止显示。
代码
单击按钮一次的代码(这可行)...
private void btnOKloop_Click(object sender, System.EventArgs e)
{
int hwnd=0;
IntPtr hwndChild = IntPtr.Zero;
//Get a handle for the Application main window
hwnd = FindWindow(null, "Desired MessageBox");
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "OK");
//send system message
if (hwnd != 0)
{
SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);
}
else
{
MessageBox.Show("Button Could Not Be Found!", "Warning", MessageBoxButtons.OK);
}
}
代码单击循环中的按钮(此挂起)...
private void btnOKloop_Click(object sender, System.EventArgs e)
{
int hwnd=0;
IntPtr hwndChild = IntPtr.Zero;
hwnd = FindWindow(null, "Desired MessageBox");
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "OK");
do
{
SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);
} while (hwnd != 0);
答案 0 :(得分:1)
你的循环永远不会退出:
hwnd = FindWindow(null, "Desired MessageBox");
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "OK");
do
{
SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);
} while (hwnd != 0);
您已将hwnd
变量设置在循环之外,然后循环,直到值变为0.但由于您未在循环中设置该值,因此永远不会更改。您可以通过在循环中移动变量赋值语句来解决此问题:
do
{
hwnd = FindWindow(null, "Desired MessageBox");
if (hwnd != 0) {
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "OK");
SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);
}
} while (hwnd != 0);
你可能会遇到一些麻烦....它可能移动得太快,试图在对话框有机会打开之前找到下一个对话框。我建议你添加一个小延迟并将其调整到适当的时间段以允许打开下一个窗口:
do
{
hwnd = FindWindow(null, "Desired MessageBox");
if (hwnd != 0) {
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "OK");
SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);
}
System.Threading.Thread.Sleep(250); // 250 milliseconds: 0.25 seconds between clicks.
} while (hwnd != 0);