我正在尝试创建一个能够控制另一个程序(在Windows中)的程序。
我发现了这个代码:
// Get a handle to an application window.
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName,
string lpWindowName);
// Activate an application window.
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
//button event
private void button1_Click(object sender, EventArgs e)
{
// Get a handle to the Calculator application. The window class
// and window name were obtained using the Spy++ tool.
IntPtr calculatorHandle = FindWindow("CalcFrame", "Kalkulačka");
// Verify that Calculator is a running process.
if (calculatorHandle == IntPtr.Zero)
{
MessageBox.Show("Calculator is not running.");
return;
}
// Make Calculator the foreground application and send it
// a set of calculations.
SetForegroundWindow(calculatorHandle);
SendKeys.SendWait("111");
SendKeys.SendWait("*");
SendKeys.SendWait("11");
SendKeys.SendWait("=");
}
是否可以模拟点击按钮?怎样是否可以在后台点击程序?
你能给我举个例子吗?
你可以在其他帖子中找到答案:
在另一个窗口中以程序方式单击鼠标
或
将鼠标点击发送到另一个应用程序的X Y坐标
我希望他们能帮上忙。
您可以使用以下代码模拟鼠标点击:
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetCursorPos(int x, int y);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
public const int MOUSE_LEFTDOWN = 0x02;
public const int MOUSE_LEFTUP = 0x04;
public static void LeftMouseClick(int x, int y)
{
SetCursorPos(x, y);
mouse_event(MOUSE_LEFTDOWN, x, y, 0, 0);
mouse_event(MOUSE_LEFTUP, x, y, 0, 0);
}
方法LeftMouseClick
是在用户屏幕上获得表示坐标的两个参数x和y:
LeftMouseClick(400, 200);
或者你可以通过键盘来完成:链接
private void button2_Click(object sender, EventArgs e)
{
SendKeys.Send("{ENTER}");
}
基本上,这就是你在代码中所做的:
SendKeys.SendWait("111");
SendKeys.SendWait("*");
SendKeys.SendWait("11");
SendKeys.SendWait("=");
我认为没有其他方法可以做到这一点。