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

-2

I am trying to send keys combination to another program like that:

// 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); 

To the last line I have an error (look at the image below).

I send the same commands as in Spy++. So firstly I automatically tried to click CTRL+S on a window then checked what I get in Spy++ and wrote the same commands.

Error:

System.OverflowException: 'Arithmetic operation resulted in an overflow.'
  • Okay, I use not Spy++, but Window Detective to be honest.

Image with my commands, commands from Window Detective and received error

c#
winapi
window
sendkeys
sendmessage
asked on Stack Overflow May 27, 2020 by Eugenio Uglov • edited May 27, 2020 by Remy Lebeau

1 Answer

1

There is not much point in faking the WM_KEYDOWN/WM_KEYUP messsages, only send the message they generated. Just the two WM_CHAR messages.

Please use SendKeys.Send(String) Method instead.

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".

The following sample works for me:

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)");
            }
        }
    }
}
answered on Stack Overflow May 28, 2020 by Strive Sun - MSFT • edited May 28, 2020 by Strive Sun - MSFT

User contributions licensed under CC BY-SA 3.0