Simulating a keypress AND keyrelease in another application?

后端 未结 4 1425
终归单人心
终归单人心 2020-12-10 21:21

I need to interact with an external application running, and send specific keypresses & releases. I\'ve tried to use the SendKeys class, but it does only half of the job

4条回答
  •  清歌不尽
    2020-12-10 22:01

    Ok, case solved. I actually installed VC++ to try the core keybd_event() function, and after it worked I was able to use it wisely in C#.

    Here's the code, and surprisingly it's very simple. You'll need to add this using to your code to be able to import dll's: using System.Runtime.InteropServices;

    This code will press and hold the '1' button for 3 secs, and then will release for 1 second and repeat the process.

    (the code highlight got messed up :/, copy from 'namespace ...' to the last bracket '}')

    public class Program 
    { 
        [DllImport("user32.dll")] 
        private static extern void keybd_event(byte bVk, byte bScan, 
            uint dwFlags, UIntPtr dwExtraInfo);
    
        private 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);
            }
        }
    }
    

提交回复
热议问题