【问题标题】:Emulating of keyboard events not working C#模拟键盘事件不起作用 C#
【发布时间】:2023-03-23 05:51:02
【问题描述】:

我正在尝试使用 WinAPI 模拟一些关键事件。我想按 WIN 键,但我的代码不起作用。在示例中,我为每个 proc 使用 VK_F1。

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ConsoleApplication69
{
    class Program
    {
        const UInt32 WM_KEYDOWN = 0x0100;
        const UInt32 WM_KEYUP = 0x0101;
        const int VK_F1 = 112;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

        static void Main(string[] args)
        {
            Process[] processes = Process.GetProcesses();

            foreach (Process proc in processes)
            {
                SendMessage(proc.MainWindowHandle, WM_KEYDOWN, new IntPtr(VK_F1), IntPtr.Zero);
                SendMessage(proc.MainWindowHandle, WM_KEYUP, new IntPtr(VK_F1), IntPtr.Zero);
            }
        }
    }
}

【问题讨论】:

  • 我一直用PostMessage而不是SendMessage,也许它也适合你。

标签: c# .net windows winapi pinvoke


【解决方案1】:

要模拟键盘输入,请使用SendInput。这正是这个 API 所做的。 “将 F1 发送到每个窗口”不是一个好主意,因为您将击键发送到没有键盘焦点的窗口。谁知道他们会如何回应。

键盘输入的细微差别比您想象的要多得多; See this question for considerations about emulating keyboard input.

【讨论】:

    【解决方案2】:

    所以我使用了这个网址中的代码:SendKeys.Send and Windows Key

    而且效果很好!

    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    
    namespace ConsoleApplication69
    {
        class Program
        {
            static void Main(string[] args)
            {
                KeyboardSend.KeyDown(Keys.LWin);
                KeyboardSend.KeyUp(Keys.LWin);
            }
        }
    
        static class KeyboardSend
        {
            [DllImport("user32.dll")]
            private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
    
            private const int KEYEVENTF_EXTENDEDKEY = 1;
            private const int KEYEVENTF_KEYUP = 2;
    
            public static void KeyDown(Keys vKey)
            {
                keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY, 0);
            }
    
            public static void KeyUp(Keys vKey)
            {
                keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
    
    
     }
    
    
    }
    

    }

    tnx 帮助大家!

    【讨论】:

      猜你喜欢
      • 2011-05-19
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多