gpt4 book ai didi

c# - 检测并替换值 Onkeydown

转载 作者:行者123 更新时间:2023-11-30 15:34:22 27 4
gpt4 key购买 nike

在我的旧项目中,我在 winform TextBox 中使用了 OnKeyPress 的覆盖来替换一些输入键

if(e.KeyChar == 'a')
e.KeyChar = 'b'; // just an example

但在 wpf 中我必须使用 OnKeyDown 并且 e.key 没有 setter !!

我必须在我的自定义 TextBox 中使用什么来更改某些按下的键?

最佳答案

这样的事情应该可行。

对于 WinForm:

 protected override void OnKeyPress(KeyPressEventArgs e)
{
//newChar will be passed to the base
char newChar = e.KeyChar;

if (e.KeyChar == 'a')
{
//handle the event and cancel the original key
e.Handled = true;

//get caret position
int tbPos = this.SelectionStart;

//insert the new text at the caret position
this.Text = this.Text.Insert(tbPos, "b");

//update the newChar
newChar = 'b';

//replace the caret back to where it should be
//otherwise the insertion call above will reset the position
this.Select(tbPos + 1, 0);
}

base.OnKeyPress(new KeyPressEventArgs(newChar));
}

根据评论更新(我会把上面的代码留给任何使用 WinForm 文本框的人)

对于 WPF:

protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
{
Key newKey = e.Key;

if (e.Key == Key.A)
{
//handle the event and cancel the original key
e.Handled = true;

//get caret position
int tbPos = this.SelectionStart;

//insert the new text at the caret position
this.Text = this.Text.Insert(tbPos, "b");

newKey = Key.B;

//replace the caret back to where it should be
//otherwise the insertion call above will reset the position
this.Select(tbPos + 1, 0);
}


base.OnKeyDown(new KeyEventArgs(e.KeyboardDevice, e.InputSource, e.Timestamp, newKey));
}

关于c# - 检测并替换值 Onkeydown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16168726/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com