我已经成功地编写了一个应用程序来按下另一个应用程序中的按钮。现在,我试图在一个循环中重复按下按钮,但我的应用程序挂起,但我不明白为什么。
上下文
我有一个对我很有帮助的应用程序,但是开发它的人并没有想到所有的事情。在应用程序中的某个时刻,会打开一个对话框,要求确认用上传的数据替换现有数据。我需要点击OK 来表示同意,但问题是我上传了很多数据到这个应用程序并且它没有“应用到所有”复选框。所以我必须反复点击OK。因此,我正在开发一个应用程序,它将为我按下 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);
最佳答案
你的循环永远不会退出:
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);
关于c# - 在循环中按下另一个应用程序中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18907439/