使用者自訂控件:UCTextBox
using System;
using System.Windows.Forms;
namespace UCPressEnter
{
public class UCTextBox : TextBox
{
public event EventHandler PressEnter;
public void OnPressEnter()
{
PressEnter?.Invoke(this, new EventArgs());
}
// 方法一:透過 KeyDown 事件觸發
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
this.OnPressEnter();
base.OnKeyDown(e);
}
// 方法二:透過 ProcessCmdKey
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter || keyData == Keys.Return)
this.OnPressEnter();
return base.ProcessCmdKey(ref msg, keyData);
}
}
}
Form 內使用 UCTextBox 並註冊 PressEnter 事件來使用
using System;
using System.Windows.Forms;
namespace UCPressEnter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ucTextBox1_PressEnter(object sender, EventArgs e)
{
MessageBox.Show("PressEnter 事件觸發" , " PressEvent 事件" , MessageBoxButtons.OK , MessageBoxIcon.Information);
}
}
}
執行結果
沒有留言:
張貼留言