2013-03-09 5 views
5

TextBox에서 키 스트로크를 억제하고 싶습니다. 누른 키가 백 스페이스 때TextBox에서 백 스페이스 키 스트로크를 방지하는 방법은 무엇입니까?

private void KeyBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) 
    { 
     e.Handled = true; 
    } 

그러나, 난 단지 키 입력을 억제 할 : 백 스페이스를 제외한 모든 키 입력을 억제하기 위해, 나는 다음과 같은 사용합니다. 다음을 사용합니다 :

 if (e.Key == System.Windows.Input.Key.Back) 
     { 
      e.Handled = true; 
     } 

그러나 이것은 작동하지 않습니다. 선택 시작 뒤에있는 문자는 계속 삭제됩니다. 출력에서 "TRUE"를 얻으므로 뒤로 키가 인식됩니다. 백 스페이스를 누르지 못하게하려면 어떻게해야합니까? (이유는 글자 대신에 단어를 지우고 싶기 때문에 자신이 직접 키를 눌러야합니다.)

+0

"PreviewKeyDown"과 같은 이벤트가 없습니까? –

+0

Windows Phone 용 Silverlight는 PreviewKeyDown 구현을 수행하지 않습니다. –

답변

0

이 시나리오를 처리하는 쉬운 방법은 없지만 가능합니다.

KeyDown, TextChanged 및 KeyUp 이벤트 사이를 건너 뛸 때 입력 텍스트, 커서 위치 및 뒤로 키 눌림 상태를 저장하려면 클래스에 일부 멤버 변수를 만들어야합니다.

코드는 다음과 같이 보일 것이다 :

string m_TextBeforeTheChange; 
    int m_CursorPosition = 0; 
    bool m_BackPressed = false; 

    private void KeyBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) 
    { 
     m_TextBeforeTheChange = KeyBox.Text; 
     m_BackPressed = (e.Key.Equals(System.Windows.Input.Key.Back)) ? true : false; 
    } 

    private void KeyBox_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     if (m_BackPressed) 
     { 
      m_CursorPosition = KeyBox.SelectionStart; 
      KeyBox.Text = m_TextBeforeTheChange; 
     } 
    } 

    private void KeyBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e) 
    { 
     KeyBox.SelectionStart = (m_BackPressed) ? m_CursorPosition + 1 : KeyBox.SelectionStart; 
    } 
+0

고맙습니다. 좋은 해결 방법입니다. – msbg

+0

허용되는 솔루션이 최선이 아닙니다. 더 나은 제안 [아래] (http : // stackoverflow.eSuppressKeyPress를 사용하여 텍스트 상자/18062836 # 18062836)/질문/15316179/back-to-prevent-a-backspace-key-stroke – tofo

3

실버 라이트에서는 시스템 키 이벤트를 처리 할 방법이 없습니다. 백 스페이스와 같은 따라서이를 감지 할 수는 있지만 수동으로 처리 할 수는 없습니다.

0
string oldText = ""; 
    private void testTextBlock_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     if (testTextBlock.Text.Length < oldText.Length) 
     { 
      testTextBlock.Text = oldText; 
      testTextBlock.SelectionStart = oldText.Length; 
     } 
     else 
     { 
      oldText = testTextBlock.Text; 
     } 
    } 
0

이것은 우리가 키 다운 이벤트 전에 텍스트 상자의 값을 저장해야합니다. 유감스럽게도 백 스페이스는 이벤트가 시작되기 전에 처리되므로 먼저 이벤트를 캡처해야합니다. 그런 다음 키 업 이벤트가 처리 된 후에 다시 업데이트 할 수 있습니다.

private string textBeforeChange; 

    private void TextBox1_OnKeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.Back) 
     { 
      e.Handled = true; 
      textBox1.Text = textBeforeChange; 
     } 
    } 

    private void TextBox1_OnKeyUp(object sender, KeyEventArgs e) 
    { 
     textBeforeChange = textBox1.Text; 
    } 

    private void MainPage_OnLoaded(object sender, RoutedEventArgs e) 
    { 
     textBox1.AddHandler(TextBox.KeyDownEvent, new KeyEventHandler(TextBox1_OnKeyDown), true); 
     textBox1.AddHandler(TextBox.KeyUpEvent, new KeyEventHandler(TextBox1_OnKeyUp), true); 
     textBox1.AddHandler(TextBox.ManipulationStartedEvent, new EventHandler<ManipulationStartedEventArgs>(TextBox1_OnManipulationStarted), true); 
    } 

    private void TextBox1_OnManipulationStarted(object sender, ManipulationStartedEventArgs e) 
    { 
     textBeforeChange = textBox1.Text; 
    } 
12

키 입력을 억제하려면 e.SuppressKeyPress = true (KeyDown 이벤트에서)로 설정하십시오. 예, 방지하려면 다음 코드를 사용하여 텍스트 상자에 텍스트를 변경 백 스페이스 키 : 나는 삭제 이전 (Ctrl 키백 스페이스)과 다음 단어 해낸

private void textBox1_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.KeyCode == Keys.Back) 
    { 
     e.SuppressKeyPress = true; 
    } 
} 
0

이것은을 (Ctrl 키 삭제), 여러 이후의 공백 문자 (은 0x09, 0x20에, 0xA0에) 처리 : e.SuppressKeyPress = true;에 대한 후이 구엔에

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 DeleteWord 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void textBox1_KeyDown(object sender, KeyEventArgs e) 
     { 
      // Tab, space, line feed 
      char[] whitespace = {'\x09', '\x20', '\xA0'}; 
      string text = textBox1.Text; 
      int start = textBox1.SelectionStart; 

      if ((e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete) && textBox1.SelectionLength > 0) 
      { 
       e.SuppressKeyPress = true; 
       textBox1.Text = text.Substring(0, start) + text.Substring(start + textBox1.SelectionLength); 
       textBox1.SelectionStart = start; 
       return; 
      } 

      else if (e.KeyCode == Keys.Back && e.Control) 
      { 
       e.SuppressKeyPress = true; 

       if (start == 0) return; 

       int pos = Math.Max(text.LastIndexOfAny(whitespace, start - 1), 0); 

       while (pos > 0) 
       { 
        if (!whitespace.Contains(text[pos])) 
        { 
         pos++; 
         break; 
        } 
        pos--; 
       } 

       textBox1.Text = text.Substring(0, pos) + text.Substring(start); 
       textBox1.SelectionStart = pos; 
      } 
      else if (e.KeyCode == Keys.Delete && e.Control) 
      { 
       e.SuppressKeyPress = true; 

       int last = text.Length - 1; 

       int pos = text.IndexOfAny(whitespace, start); 
       if (pos == -1) pos = last + 1; 

       while (pos <= last) 
       { 
        if (!whitespace.Contains(text[pos])) break; 
        pos++; 
       } 

       textBox1.Text = text.Substring(0, start) + text.Substring(pos); 
       textBox1.SelectionStart = start; 
      } 
     } 

     protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
     { 
      if (keyData == Keys.Tab) 
      { 
       textBox1.Paste("\t"); 
       return true; 
      } 
      else if (keyData == (Keys.Shift | Keys.Tab)) 
      { 
       textBox1.Paste("\xA0"); 
       return true; 
      } 
      return base.ProcessCmdKey(ref msg, keyData); 
     } 

    } 
} 

감사합니다!

이, 선택의 모두 삭제하고 백 스페이스

(당신은 Ctrl 키을 보유하기위한 못생긴 사각형 문자를받지 않습니다) 변경 키에 관계없이 선택을 삭제하기로 같은 문자를 위해 작동하는 것 같다 경우 글쎄,별로 의미가 없을 수도 있지만 (이 문자는 전체 단어가 아닌가?)