Simulate keystrokes and keyrelease in another application?

I need to interact with an external running application and send special keystrokes and releases. I tried to use the SendKeys class, but it only does half the job, because when you press a key, an instant press switches to external applications.

I need to simulate a "key hold" for an external application. Now I am trying to use SendMessage, but for now this will not work :( and I am not even getting errors.

+3
source share
4 answers

Okay, it's settled. I actually installed VC ++ to try the main keybd_event () function, and after working it, I was able to use it wisely in C #.

Here is the code, and surprisingly it is very simple. You will need to add this usage to your code in order to be able to import dll: using System.Runtime.InteropServices;

This code presses and holds the β€œ1” button for 3 seconds, and then it is released for 1 second and repeats the process.

(code allocation messed up: /, copying from the "namespace ..." to the last parenthesis "}")

namespace ConsoleApplication1 
{
class Program 
{ 
    [DllImport("user32.dll")] 
    static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,UIntPtr dwExtraInfo);

    static void Main(string[] args)
    {            
        while (true)
        {
            keybd_event((byte)0x31, (byte)0x02, 0, UIntPtr.Zero);
            Thread.Sleep(3000);

            keybd_event((byte)0x31, (byte)0x82, (uint)0x2, UIntPtr.Zero);
            Thread.Sleep(1000);
        }
    }
}

}
+3
source

Have you tried using PostMessage to send WM_KEYDOWNand WM_KEYUP?

Edit

( ++, PInvoke ..NET)

HWND hwnd = FindWindow(NULL,_T("Mywindow"));
PostMessage(hwnd,WM_KEYDOWN,VK_A,0);
+1

The official API SendInput.

+1
source

You can use WSH Scripting Shell for this:

        WshShell shell = new WshShellClass();
        object missing=System.Reflection.Missing.Value;

        shell.SendKeys("MOO!!!", ref missing);

All you have to do is add the COM link to the "Windows Scripting Host Object", version 1.0. Everything is in the namespace IWshRuntimeLibrary.

+1
source

Source: https://habr.com/ru/post/1723567/


All Articles