我已经启动了一个进程,并希望向其发布一个类似PageDown键的消息。
以下是运行该流程的代码。
Process.Start("chrome.exe", "D:/sample.htm");
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.ProcessName == "chrome" && p.MainWindowTitle == "sample.htm - Google Chrome")
{
//how to Send a pagedown key to process p
}
}
我创建了以下课程,但我不知道它为什么不起作用?
class KeyHandle
{
private static Int32 WM_KEYDOWN = 0x100;
private static Int32 WM_KEYUP = 0x101;
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, int Msg, System.Windows.Forms.Keys wParam, int lParam);
public static void SendKey(IntPtr hWnd, System.Windows.Forms.Keys key)
{
PostMessage(hWnd, WM_KEYUP, key, 0);
}
}
并以这种方式称呼
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.ProcessName == "chrome" && p.MainWindowTitle == "sample.htm - Google Chrome")
{
KeyHandle.SendKey(p.MainWindowHandle, Keys.PageDown);
}
}
答案 0 :(得分:1)
我使用SendKeys API重写您的代码。我测试它运作良好
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.ProcessName == "chrome" && p.MainWindowTitle == "sample.htm - Google Chrome" &&
p.MainWindowHandle != IntPtr.Zero)
{
SetForegroundWindow(p.MainWindowHandle);
SendKeys.SendWait("{PGDN}");
}
}
要声明函数SetForegroundWindow,请使用:
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
答案 1 :(得分:0)
Process.Start(“chrome.exe”,“D:/sample.htm”); foreach(System.Diagnostics.Process.GetProcesses()中的System.Diagnostics.Process p) { if(p.ProcessName ==“chrome”&& p.MainWindowTitle ==“sample.htm - Google Chrome”) { KeyHandle.SendKey(p.MainWindowHandle,Keys.PageDown); } } 你也需要这个班级
类KeyHandle { private static Int32 WM_KEYDOWN = 0x100; private static Int32 WM_KEYUP = 0x101;
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, int Msg, System.Windows.Forms.Keys wParam, int lParam);
public static void SendKey(IntPtr hWnd, System.Windows.Forms.Keys key)
{
PostMessage(hWnd, WM_KEYUP, key, 0);
}
}