C# / 发送组合键 (CTRL+S) 到另一个 window

C# / Send keys combination (CTRL+S) to another window

我正在尝试将组合键发送到另一个类似的程序:

// keydown ctrl
SendMessage(windowBracketsKeyListener, 0x100, (IntPtr)VK_CONTROL, (IntPtr)0x001D0001); 
// keydown S
SendMessage(windowBracketsKeyListener, 0x100, (IntPtr)VK_S, (IntPtr)0x001F0001); 
SendMessage(windowBracketsKeyListener, 0x102, (IntPtr)115, (IntPtr)0); 
// keyup ctrl 
SendMessage(windowBracketsKeyListener, 0x101, (IntPtr)VK_CONTROL, (IntPtr)0xC01D0001); 

到最后一行我有一个错误(看下图)。

我发送与 Spy++ 中相同的命令。所以首先我自动尝试在 window 上单击 CTRL+S 然后检查我在 Spy++ 中得到的内容并编写相同的命令。

错误:

System.OverflowException: 'Arithmetic operation resulted in an overflow.'

伪造 WM_KEYDOWN/WM_KEYUP 消息没有多大意义,只发送它们生成的消息。只有两条 WM_CHAR 消息。

use SendKeys.Send(String) Method代替。

To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses. For example, to specify to hold down SHIFT while E and C are pressed, use "+(EC)". To specify to hold down SHIFT while E is pressed, followed by C without SHIFT, use "+EC".

以下示例适合我:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Test
{
    static class Program
    {
        [DllImport("user32.dll")]
        public static extern int SetForegroundWindow(IntPtr hWnd);
        static void Main()
        {

            Process[] processes = Process.GetProcessesByName("notepad"); //notepad used be test

            foreach (Process proc in processes)
            {
                SetForegroundWindow(proc.MainWindowHandle);
                SendKeys.SendWait("^(s)");
            }
        }
    }
}