msb*_*sbg 5 c# keystroke backspace windows-phone-7 windows-phone
我想在TextBox中抑制一个键击.要禁止Backspace之外的所有击键,我使用以下内容:
private void KeyBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)
但是,当按下的键是Backspace时,我只想抑制键击.我使用以下内容:
if (e.Key == System.Windows.Input.Key.Back)
{
e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用.选择开始背后的字符仍然被删除.我在输出中得到"TRUE",因此正在识别Back键.如何阻止用户按退格键?(我的理由是我想在某些情况下删除单词而不是字符,所以我需要自己处理后退键).)
Huy*_*yen 14
如果要抑制击键,只需设置e.SuppressKeyPress = true(在KeyDown事件中).例如,使用以下代码阻止退格键更改文本框中的文本:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
e.SuppressKeyPress = true;
}
}
Run Code Online (Sandbox Code Playgroud)
确实,没有简单的方法来处理这种情况,但这是可能的。
当我们在 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14094 次 |
| 最近记录: |