2017-06-16 82 views
-1

我希望TextBox只通過使用KeyDown事件接受某些特定字符。我已經有了它,除了一個字符,單引號。爲了得到要寫的字符,我使用(char)e.KeyValue,它適用於除引號外的所有字符(它給出了Û)。我知道我可以使用e.KeyCode,但它的價值是Keys.Oem4,其中AFAIK可能在不同系統中有所不同。在KeyDown事件中檢測單引號鍵

是否有任何方法一貫檢測單引號按鍵?

代碼片段:

char c = (char)e.KeyValue; 
char[] moves = { 'r', 'u', ..., '\'' }; 

if (!(moves.Contains(c) || e.KeyCode == Keys.Back || e.KeyCode == Keys.Space)) 
{ 
    e.SuppressKeyPress = true; 
} 
+0

的'KeyPress'事件(我認爲[是WM_CHAR](https://msdn.microsoft.com/en-us/library/windows/desktop/ms646276(V = vs.85)的.aspx ))使用'KeyPressEventArgs',它具有您正在查找的'KeyChar'屬性。如果該事件能夠滿足您的需求,您可以使用它。 –

+0

@EdPununkett說什麼。 'KeyDown'和'KeyEventArgs'只給你虛擬鍵碼,而不是真正的字符(它們經常在值中重合,所以演員的作品就是這樣:巧合)。生成單引號的鍵的虛擬鍵代碼因佈局而異。問題不在於'KeyCode'; 'KeyValue'也不通用。 –

+0

@EdPlunkett這樣做,但我需要禁止按鍵,這隻能在'KeyDown'事件中實現。 – Pipe

回答

-1

由於@EdPlunkett建議,this answer作品對我來說:

[DllImport("user32.dll")] 
static extern bool GetKeyboardState(byte[] lpKeyState); 

[DllImport("user32.dll")] 
static extern uint MapVirtualKey(uint uCode, uint uMapType); 

[DllImport("user32.dll")] 
static extern IntPtr GetKeyboardLayout(uint idThread); 

[DllImport("user32.dll")] 
static extern int ToUnicodeEx(uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszBuff, int cchBuff, uint wFlags, IntPtr dwhkl); 


public static string KeyCodeToUnicode(System.Windows.Forms.Keys key) 
{ 
    byte[] keyboardState = new byte[255]; 
    bool keyboardStateStatus = GetKeyboardState(keyboardState); 

    if (!keyboardStateStatus) 
    { 
     return ""; 
    } 

    uint virtualKeyCode = (uint)key; 
    uint scanCode = MapVirtualKey(virtualKeyCode, 0); 
    IntPtr inputLocaleIdentifier = GetKeyboardLayout(0); 

    StringBuilder result = new StringBuilder(); 
    ToUnicodeEx(virtualKeyCode, scanCode, keyboardState, result, (int)5, (uint)0, inputLocaleIdentifier); 

    return result.ToString(); 
} 
1

我一直在用這個很長一段時間。它處理單引號就好了。 e.KeyChar == 39'\''和e.Handled = true的行爲與您所期望的完全相同。我使用KeyPress事件對其進行了測試,並在那裏工作。

protected override void OnKeyPress(KeyPressEventArgs e) 
    { 
     base.OnKeyPress(e); 
     if (e.KeyChar == (char)8) // backspace 
      return; 
     if (e.KeyChar == (char)3) // ctrl + c 
      return; 
     if (e.KeyChar == (char)22) // ctrl + v 
      return; 
     typedkey = true; 
     if (_allowedCharacters.Count > 0) // if the string of allowed characters is not empty, skip test if empty 
     { 
      if (!_allowedCharacters.Contains(e.KeyChar)) // if the new character is not in allowed set, 
      { 
       e.Handled = true; // ignoring it 
       return; 
      } 
     } 
     if (_disallowedCharacters.Count > 0) // if the string of allowed characters is not empty, skip test if empty 
     { 
      if (_disallowedCharacters.Contains(e.KeyChar)) // if the new character is in disallowed set, 
      { 
       e.Handled = true; // ignoring it 
       return; 
      } 
     } 
    }