【问题标题】:C# Hotkey Box (AHK Hotkey Style)C# 热键框(AHK 热键样式)
【发布时间】:2018-01-10 09:47:36
【问题描述】:

我正在 C# 中尝试创建与 AHK 中类似的热键功能。就像在任何视频游戏中一样,您单击一个框,按下热键并注册它。 这就是我试图用 textBox 做的事情:

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;

namespace Keybinder
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            KeyPreview = true;
            textBox1.ReadOnly = true;
            textBox1.Focus();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = "HELLO";
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            char key = e.KeyChar;
            string keystring = Char.ToString(key);
            textBox1.Text = keystring;
        }
    }
}

但是,问题是,我需要关闭文本框的基本功能,但我不知道怎么做。例如:光标仍然处于活动状态,我可以突出显示其中的文本。

【问题讨论】:

    标签: c# forms textbox autohotkey key-bindings


    【解决方案1】:

    你可以将文本框的属性Enabled设置为false,然后把背景颜色设置为白色,字体设置为黑色,这样看起来并没有被禁用,但是你不能聚焦也不能点击ir。

    textBox1.Enabled = false;
    

    顺便说一句,我有一个非常简单的库,可能有用。

    https://github.com/PabloHorno/HotKeyDialog

    一旦你引用了这个库,你就可以像这样使用它 或者更简单的方式

    var hotKey = new HotKey();
    
    hotKey = HotKeyMessageBox.Show("Title", "A little description");
    
    hotKey.ToString();
    

    或者你可以检查用户是否关闭了盒子

     HotKey hotkey = new HotKey();
    
     if (HotKeyMessageBox.Show("Title", "Please press the key combination", out hotkey) == DialogResult.OK)
         label.Text = "You have pressed the keys: " + hotkey.ToString();
     else
         label.Text = "You have closed the dialog. There is no input";
    

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      如果您不需要 TextBox 的功能,为什么还要使用它?

      您可以创建一个简单的自定义控件并将其放在表单上,​​而不是关闭它的功能。比如:

      public class KeyInput : UserControl
      {
          public string KeyString { get; set; } = "HELLO";
      
          public KeyInput() : base()
          {
              BorderStyle = BorderStyle.Fixed3D;
          }
      
          protected override void OnKeyPress(KeyPressEventArgs e)
          {
              base.OnKeyPress(e);
      
              KeyString = e.KeyChar.ToString();
              Invalidate();
          }
      
          protected override void OnPaint(PaintEventArgs e)
          {
              base.OnPaint(e);
      
              e.Graphics.DrawString(KeyString, Font, SystemBrushes.ControlText, 0, 0);
          }
      }
      

      【讨论】:

      • 没有任何方法可以动态实现 UserControl 而不是使用额外的类吗?
      • @dewey,实际上,如果需要,您可以直接在表单上放置一个 UserControl 实例并订阅其 KeyPress 和 Paint 事件。但是,在我看来,这不是一个很好的方法。
      猜你喜欢
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多