在另一个应用程序中模拟按键和按键释放? [英] Simulating a keypress AND keyrelease in another application?

查看:26
本文介绍了在另一个应用程序中模拟按键和按键释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要与正在运行的外部应用程序交互,并发送特定的按键和发布.我尝试使用 SendKeys 类,但它只完成了一半的工作,因为按键被立即释放到外部应用程序.

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.

我需要能够为外部应用模拟按住键".我现在正在尝试使用 SendMessage 的东西,但现在它根本不起作用:(而且我什至没有收到错误.

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.

推荐答案

好的,问题解决了.我实际上安装了 VC++ 来尝试核心 keybd_event() 函数,在它工作之后,我能够在 C# 中明智地使用它.

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

这是代码,令人惊讶的是它非常简单.您需要将其添加到您的代码中才能导入 dll:using System.Runtime.InteropServices;

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;

此代码将按住1"按钮 3 秒钟,然后松开 1 秒钟并重复该过程.

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

(代码高亮搞砸了:/,从 'namespace ...' 复制到最后一个括号 '}')

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

这篇关于在另一个应用程序中模拟按键和按键释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆