2017-08-03 152 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事件。但是,我認爲這不是一個好方法。 –