[英]How do I make KeyPress event handler available to all forms?
我已經創建了一個KeyPress事件處理程序,可以防止在任何子文檔輸入控件中輸入除數字,小數和退格之外的任何內容。 問題是處理程序僅可用於創建它的表單。 不是將事件處理程序復制到每個表單,有沒有辦法使其成為全局 - 以便任何表單上的任何輸入控件的按鍵事件都可以訂閱它。
謝謝。
另一個面向對象的解決方案是繼承TextBox控件並覆蓋KeyPress事件,創建自己的自定義TextBox類型。
class NumericTextBox : System.Windows.Forms.TextBox
{
protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (true /* insert your conditions */)
e.Handled = true;
}
}
然后在需要的地方使用此控件代替常規TextBox控件。
將其設置為公共和靜態,您應該將其移動到“Utilities”類型類。 (或者它自己的班級)
namespace GlobalKeyPress
{
public class GlobalKeyPress
{
public static void KeyPressFilter(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != '.')
e.Handled = true;
}
}
}
委托是普通對象,因此,您可以從方法返回它們。
具體來說,您需要創建一個KeyPressEventHandler
委托
public static class Utilities
{
private static KeyPressEventHandler handler = KeyPressed;
public static void KeyPressed(Object sender, KeyPressEventArgs e)
{
// Your logic here
}
public static KeyPressEventHandler getKeyPressHandler() {
return handler;
}
}
注意:我沒有測試過這個。 根據Using Delegates和KeyPressEventHandler
上的頁面,它看起來是正確的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.