gpt4 book ai didi

c# - 如何防止上下键在 c# windows 窗体中将文本框中的插入符号/光标左右移动。

转载 作者:行者123 更新时间:2023-11-30 14:27:48 25 4
gpt4 key购买 nike

我目前正在尝试将光标的索引增加 1。例如,如果我闪烁的光标在 210 中的 2 和 1 之间,它会将值增加到 220。

这是我现在使用的代码的一部分。我试图让光标在按下后留在原处,并向右移动。我尝试将 SelectionStart 设置回 0,但该框默认将其增加 1(我的文本框的第一个插入符号索引从最左侧开始)。

        TextBox textBox = (TextBox)sender;
int box_int = 0;
Int32.TryParse(textBox.Text, out box_int);
if (e.KeyCode == Keys.Down)
{
if(textBox.SelectionStart == 0)
{
box_int -= 10000;
textBox.Text = box_int.ToString();
textBox.SelectionStart= 0;
return;
}
}

最佳答案

为了防止插入符(不是光标)移动,您应该在事件处理程序中设置 e.Handled = true;。当按下向上或向下箭头时,此代码更改插入符号右侧的数字。如果按下向上或向下箭头,e.Handled 将设置为 true 以防止插入符号移动。此代码未经过全面测试,但似乎有效。我还将文本框 ReadOnly 属性设置为 true 并将值预设为“0”。

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{

TextBox textBox = (TextBox)sender;

//Only change the digit if there is no selection
if (textBox.SelectionLength == 0)
{
//Save the current caret position to restore it later
int selStart = textBox.SelectionStart;

//These next few lines determines how much to add or subtract
//from the value based on the caret position in the number.
int box_int = 0;
Int32.TryParse(textBox.Text, out box_int);

int powerOf10 = textBox.Text.Length - textBox.SelectionStart - 1;
//If the number is negative, the SelectionStart will be off by one
if (box_int < 0)
{
powerOf10++;
}

//Calculate the amount to change the textbox value by.
int valueChange = (int)Math.Pow(10.0, (double)powerOf10);

if (e.KeyCode == Keys.Down)
{
box_int -= valueChange;
e.Handled = true;
}
if (e.KeyCode == Keys.Up)
{
box_int += valueChange;
e.Handled = true;
}

textBox.Text = box_int.ToString();
textBox.SelectionStart = selStart;
}
}

关于c# - 如何防止上下键在 c# windows 窗体中将文本框中的插入符号/光标左右移动。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31522848/

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