我需要移除多个文本框的焦点。我尝试过使用:
textBox1.Focused = false;
它的ReadOnly
属性值为true
。
接着我尝试将焦点设置在表单上,以便从所有的文本框中移除它,但这也无法生效:
this.Focus();
当选中文本框时,该函数返回false
。
那么,我该如何将焦点从文本框中移除?
看起来我不需要将焦点设置到其他元素。在Windows Phone 7应用中,我一直在使用Focus方法取消文本框的焦点。
执行以下命令将焦点设置为空:
void SearchBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
Focus();
}
}
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx
这对我有用,但我不知道为什么你不能使用它 :/
//using System;
//using System.Collections.Generic;
//using System.Linq;
private void Form1_Load(object sender, EventArgs e)
{
FocusOnOtherControl(Controls.Cast<Control>(), button1);
}
private void FocusOnOtherControl<T>(IEnumerable<T> controls, Control focusOnMe) where T : Control
{
foreach (var control in controls)
{
if (control.GetType().Equals(typeof(TextBox)))
{
control.TabStop = false;
control.LostFocus += new EventHandler((object sender, EventArgs e) =>
{
focusOnMe.Focus();
});
}
}
}
Keyboard.ClearFocus();
虽然已经是2022年了,但我发现这里的解决方案都不适用于我(不知道为什么),我使用的是.Net_6.0_windows。因此,我想出了以下解决方案:
Label focusoutLabel = new Label() {
Text = "",
Name = "somegenericplaceholdernamethatwillneverbeusedinmyprogram",
Visible = false,
};
this.Controls.Add(focusoutLabel);
this.ActiveControl = focusoutLabel;
将此代码放置在您的表单加载处理程序中
TabStop
属性设置为False
。txtEmpID.TabStop = false;
我解决这个问题的方法是将所有的winform控件都放置好。我将所有的标签和不可选择的winform控件设置为tab order 0,然后将我的第一个控件设置为tab order 2,接着逐个增加每个可选择控件的顺序,如3、4、5等......
这样,在我的Winforms启动时,第一个文本框就不会获得焦点!
你可以通过两种方法来实现这个:
拖动两个文本框
将textbox2的tabindex值设置为0
如果你只想要文本框没有蓝色选择覆盖其内容的视觉效果,只需选择无文本:
textBox_Log.SelectionStart = 0;
textBox_Log.SelectionLength = 0;
textBox_Log.Select();
之后,当使用.Text += "..."
添加内容时,将不会显示蓝色选择。
你可以尝试:
textBox1.Enable = false;
SetStyle(ControlStyles.Selectable, false);
在InitializeComponent()之后;
示例:
public partial class Main : UserControl
{
public Main()
{
InitializeComponent();
SetStyle(ControlStyles.Selectable, false);
}