Fah*_*die 2 c# process sendkeys
您好我正在尝试使用下面的代码向浏览器发送密钥,新的Chrome窗口为我打开,但它不会将密钥发送到浏览器.
当我调试我发现铬过程没有任何标题名称我怎么能解决这个问题?
Process.Start("chrome.exe", "https://labs.sketchfab.com/sculptfab/");
System.Threading.Thread.Sleep(2000);
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.ProcessName == "chrome" && p.MainWindowTitle == "SculptFab - SculptGL + Sketchfab" &&
p.MainWindowHandle != IntPtr.Zero)
{
System.Threading.Thread.Sleep(2000);
for (int i = 0; i < 50; i++)
{
KeyHandle.SetForeGround(p.MainWindowHandle);
SendKeys.Send("s");
System.Threading.Thread.Sleep(2000);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在上面提到的页面中,当键盘上按下"S"时,它会缩小我想要的对象,使用我的C#代码实现这一点
您可以创建一个Process使用它的新实例来发送您的击键.有关详细信息,请参阅/sf/answers/902462151/.
我做了一些研究,看来Chrome确实没有对该SendKeys.Send方法做出反应.但是,您可以使用Windows API调用该SendMessage函数并将Keydown/-up信号发送到窗口.这是一个在Chrome中使用的简单包装:
public class ChromeWrapper
{
// you might as well use those methods from your helper class
[DllImport("User32.dll")]
private static extern int SetForegroundWindow(IntPtr point);
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
// the keystroke signals. you can look them up at the msdn pages
private static uint WM_KEYDOWN = 0x100, WM_KEYUP = 0x101;
// the reference to the chrome process
private Process chromeProcess;
public ChromeWrapper(string url)
{
// i'm using the process class as it gives you the MainWindowHandle by default
chromeProcess = new Process();
chromeProcess.StartInfo = new ProcessStartInfo("chrome.exe", url);
chromeProcess.Start();
}
public void SendKey(char key)
{
if (chromeProcess.MainWindowHandle != IntPtr.Zero)
{
// send the keydown signal
SendMessage(chromeProcess.MainWindowHandle, ChromeWrapper.WM_KEYDOWN, (IntPtr)key, IntPtr.Zero);
// give the process some time to "realize" the keystroke
System.Threading.Thread.Sleep(100);
// send the keyup signal
SendMessage(chromeProcess.MainWindowHandle, ChromeWrapper.WM_KEYUP, (IntPtr)key, IntPtr.Zero);
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用这个类非常简单:
ChromeWrapper chrome = new ChromeWrapper("https://labs.sketchfab.com/sculptfab/");
System.Threading.Thread.Sleep(5000);
chrome.SendKey('S');
Run Code Online (Sandbox Code Playgroud)
适用于我的机器™(Windows 8.1 Pro N,谷歌浏览器42).
附加信息
此解决方案仅在尚未运行Chrome的情况下才有效,因为Chrome仅将新网址发送到其主要流程,然后打开它.因此,要么事先关闭其他Chrome实例,要么SendMessage在您使用的过程中使用该方法Process.GetProcesses
| 归档时间: |
|
| 查看次数: |
8605 次 |
| 最近记录: |