Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

c# - Simulating a keypress AND keyrelease in another application?

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, as the keypress is being sent with an immediate keyrelease to the external applications.

I need to be able to simulate a "key hold down" for the external app. I'm now trying to use the SendMessage thing, but for now it won't work at all :( and I don't even get errors.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...