Simulating CTRL+C with Sendkeys fails

让人想犯罪 __ 提交于 2019-12-01 06:50:32

问题


I have an odd problem with Sendkeys, what my application basically should do is that, when I press ALT+ J, it'll simulate a CTRL+C operation (on any windows) to copy some highlighted text, however the CTRL+C simulation is not working.

[DllImport("user32.dll", SetLastError = true)]  
[return: MarshalAs(UnmanagedType.Bool)]  
static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

private void Form1_Load(object sender, EventArgs e)
{
 RegisterHotKey(this.Handle,
 this.GetType().GetHashCode(), 1, (int)'J'); // Here it's waiting for the ALT+J 
}

protected override void WndProc(ref Message m) // Function to c
{
 if (m.Msg == 0x0312) // If ALT+J pressed
 {
     Copier(); // .. Simulate CTRL+C (but doesn't work)
 }
 base.WndProc(ref m);
}

public void Copier() // Function to simulate the CTRL+C
{
 Debug.WriteLine("Ok ");
 InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_C); // First way
 SendKeys.Send("^(c)"); // Second way
}

回答1:


I think this is happening because when you send CTRL+C you already have pressed the ALT modifier of ALT+J.

If you put

Thread.Sleep(1000);

just before send keys, you'll have time to release ALT+J and then CTRL+C will work.

Also, if you plan to check when your hotkey is released, check this.



来源:https://stackoverflow.com/questions/15308166/simulating-ctrlc-with-sendkeys-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!