C# 在C中使用SetForegroundWindow和SendKeys激活窗口并发送输入
我要做的是激活另一个应用程序,并向它发送一个按键输入来触发一个按钮。然而,这段代码似乎不起作用。它看起来可以找到应用程序,但它没有激活它,也没有发送密钥C# 在C中使用SetForegroundWindow和SendKeys激活窗口并发送输入,c#,input,sendkeys,setforegroundwindow,C#,Input,Sendkeys,Setforegroundwindow,我要做的是激活另一个应用程序,并向它发送一个按键输入来触发一个按钮。然而,这段代码似乎不起作用。它看起来可以找到应用程序,但它没有激活它,也没有发送密钥 [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] publ
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
private void debugButton_Click(object sender, EventArgs e)
{
//GetProcess by Class
IntPtr rightNowHandle = FindWindow("WindowsForms10.Window.8.app.0.24dc298_r17_ad2", null);
//Get Handle by Process
Process proc = Process.GetProcessesByName("RightNow.CX")[0];
IntPtr ptrFF = proc.MainWindowHandle;
//Get a handle for the Calculator Application main window
if (rightNowHandle == IntPtr.Zero)
{
MessageBox.Show("Could Not Find Right Now");
return;
}
SetForegroundWindow(rightNowHandle); //Activate Handle By Class
//SetForegroundWindow(ptrFF); //Activate Handle By Process
SendKeys.SendWait("{F1}");
}
这是我用Window Spy做的
任何帮助都将不胜感激。谢谢。解决了我的问题
如果应用程序被最小化,SetForeGroundIndow将不显示该应用程序,这正是我所期望的
接下来,我使用发送输入,而不是发送键
这是我最后使用的代码
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
private const int SW_RESTORE = 9;
private void debugButton_Click(object sender, EventArgs e)
{
//GetProcess by Class
IntPtr rightNowHandle = FindWindow("WindowsForms10.Window.8.app.0.24dc298_r17_ad2", null);
//Get Handle by Process
Process proc = Process.GetProcessesByName("RightNow.CX")[0];
IntPtr ptrFF = proc.MainWindowHandle;
//Get a handle for the Calculator Application main window
if (rightNowHandle == IntPtr.Zero)
{
MessageBox.Show("Could Not Find Right Now");
return;
}
SetForegroundWindow(ptrFF); //Activate Handle By Process
ShowWindow(ptrFF, SW_RESTORE); //Maximizes Window in case it was minimized.
//SetForegroundWindow(rightNowHandle); //Activate Handle By Class
InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.LMENU, VirtualKeyCode.VK_A); //Send Left Alt + A
}
不要使用rightNowHandle,尝试使用您根本没有使用的ptrFF。@Cistoran是您的进程的32位进程,RighNow.CX.exe是64位进程吗?@JonathanCarroll它们都是64位机器上的32位进程。@Gusman两者都不起作用。我两个都试过了。可能你没有正确的类/名称,很久以前我通常使用这些api,有时发现rght窗口是一个噩梦,可能是窗口中的窗口,或者它有一个代理窗口,等等。试一件事,将你得到的句柄与Spy++给出的句柄进行比较,如果是相同的,那么您确定这不是正确的类/名称。