【问题标题】:how to fire a keydown or keypress event如何触发 keydown 或 keypress 事件
【发布时间】:2015-06-13 14:30:14
【问题描述】:

我希望在用户不按任何键的情况下触发按键事件。 所以我用

InputSimulator.SimulateKeyPress(VirtualKeyCode.VK_U);

还有

System.Windows.Forms.SendKeys.Send("a");

那不是原因 所以我用

    var key = Key.Insert;                    // Key to send
    var target = Keyboard.FocusedElement;    // Target element
    var routedEvent = Keyboard.KeyDownEvent; // Event to send

    target.RaiseEvent(
      new KeyEventArgs(
        Keyboard.PrimaryDevice,
        PresentationSource.FromVisual(target),
        0,
        key) { RoutedEvent = routedEvent }
    );

导致以下错误 当前上下文中不存在名称“Key” 我用

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Windows.Input;
using WindowsInput; 

我在Form1_Load

上写下这段代码

【问题讨论】:

  • "我在 Form1_Load 上编写此代码" Load() 事件发生在表单显示之前,因此您的击键被发送到任何应用程序在程序运行之前聚焦(如果您从 IDE 运行,可能是 Visual Studio)。将您的测试代码移至Shown() 事件,您可能会得到更好的结果...
  • @Idle_Mind 谢谢。它有效。

标签: c# winforms events keypress keydown


【解决方案1】:

@Idle_Mind 谢谢。它有效。

发表评论作为答案:

我在 Form1_Load 上写下这段代码

Load() 事件在窗体显示之前发生,因此您的击键将被发送到在程序运行之前具有焦点的任何应用程序(如果您从 IDE 运行,可能是 Visual Studio)

将您的测试代码移至Shown() 事件,您可能会得到更好的结果...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 2016-09-21
    • 2023-03-23
    • 2013-08-23
    • 1970-01-01
    • 2011-11-17
    相关资源
    最近更新 更多