我有一个表单,其中有 2 个文本框。其中之一是 MultiLine 和 ReadOnly。另一个用于输入命令,所以我希望它始终处于焦点状态。 是否可以将表单的 MouseWheel 事件转发到 TextBox,以便我可以在 TextBox 中滚动而不使其处于焦点? 如果没有,最好的解决方法是什么?
提前致谢。
您可以使用表单的鼠标滚轮事件来获取滚动值,然后使用 ScrollToCaret() 手动设置 TextBox 的滚动。
textBox.SelectionStart = scrollPosition;
textBox.ScrollToCaret();
要获取滚动值,请使用 MouseWheel 事件: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mousewheel(v=vs.71).aspx
您可以在 Form 构造函数中使用 textbox.MouseWheel+= 方法; 订阅文本框的鼠标滚轮事件,即使 TextBox 没有此类事件,因为它不是像 那样使用它的控件表单或面板或数字上下框。然后你可以使用 MouseEventArgs e.Delta 来根据滚轮的正向或负向 ScrollToCaret :
public Form1()
{
InitializeComponent();
textBoxWaitAppStart.MouseWheel += TextBoxWaitForApp_MouseWheelScrolled;
}
private void TextBoxWaitForApp_MouseWheelScrolled(object? sender, MouseEventArgs e)
{
if (int.TryParse(textBoxWaitAppStart.Text, out int currentValue))
{
// Determine scroll direction and update the value
if (e.Delta > 0) // Scrolled up
{
currentValue++;
}
else if (e.Delta < 0) // Scrolled down
{
currentValue--;
}
// Update the TextBox with the new value
textBoxWaitAppStart.Text = currentValue.ToString();
// Ensure the new currentValue is within the bounds of the text length
if (currentValue > textBoxWaitAppStart.Text.Length)
{
currentValue = textBoxWaitAppStart.Text.Length;
}
else if (currentValue < 0)
{
currentValue = 0;
}
// Set the selection start to the currentValue
textBoxWaitAppStart.SelectionStart = currentValue;
// Ensure the caret is visible
textBoxWaitAppStart.ScrollToCaret();
}
}
通过这种方式,您可以更改文本框,而无需直接聚焦它,只需将鼠标悬停在文本框上并根据滚轮事件进行更改