2017-08-03 130 views
1

我想在C#中创建一个类似于AHK的热键功能。就像在任何视频游戏中一样,你点击一个盒子,按下你的热键并获得注册。 这就是我想用文本框做:C#热键框(AHK热键风格)

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

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

回答

0

为什么使用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); 
    } 
} 
+0

是不是有没有办法实现一个UserControl动态,而不是一个额外的类? – dewey

+0

@dewey,实际上,如果需要,您可以直接在窗体上放置UserControl实例并订阅其KeyPress和Paint事件。但是,我认为这不是一个好方法。 –