如何在WinForms中取消TextBox的焦点?

133

我需要移除多个文本框的焦点。我尝试过使用:

textBox1.Focused = false;

它的ReadOnly属性值为true

接着我尝试将焦点设置在表单上,以便从所有的文本框中移除它,但这也无法生效:

this.Focus();

当选中文本框时,该函数返回false

那么,我该如何将焦点从文本框中移除?

20个回答

2

看起来我不需要将焦点设置到其他元素。在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

这对我有用,但我不知道为什么你不能使用它 :/


1
    //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();
                });
            }
        }
    }

0
使用 System.Windows.Input。
Keyboard.ClearFocus();

1
请不要仅仅发布代码作为答案,还要提供解释您的代码是如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同。 - Tyler2P

0

虽然已经是2022年了,但我发现这里的解决方案都不适用于我(不知道为什么),我使用的是.Net_6.0_windows。因此,我想出了以下解决方案:

Label focusoutLabel = new Label() { 
    Text = "",
    Name = "somegenericplaceholdernamethatwillneverbeusedinmyprogram",
    Visible = false,
};
this.Controls.Add(focusoutLabel);
this.ActiveControl = focusoutLabel;

将此代码放置在您的表单加载处理程序中


0
请尝试将未被聚焦的视图控件的TabStop属性设置为False
例如:
txtEmpID.TabStop = false;

0

我解决这个问题的方法是将所有的winform控件都放置好。我将所有的标签和不可选择的winform控件设置为tab order 0,然后将我的第一个控件设置为tab order 2,接着逐个增加每个可选择控件的顺序,如3、4、5等......

这样,在我的Winforms启动时,第一个文本框就不会获得焦点!


0

你可以通过两种方法来实现这个:

  • 将所需文本框的 "TabStop" 属性设置为 false,即使只有一个文本框,它也不会获得焦点。
  • 拖动两个文本框

    1. 使其中一个可见,即你不想让其获得焦点的文本框1
    2. 使第二个文本框不可见,并进入该文本框的属性并选择

将textbox2的tabindex值设置为0

  1. 将textbox1的tabindex设置为1,现在它不会获得焦点了。

0

如果你只想要文本框没有蓝色选择覆盖其内容的视觉效果,只需选择无文本:

textBox_Log.SelectionStart = 0;
textBox_Log.SelectionLength = 0;
textBox_Log.Select();

之后,当使用.Text += "..."添加内容时,将不会显示蓝色选择。


0

你可以尝试:

textBox1.Enable = false;

-1
在包含文本框的窗体或用户控件的构造函数中编写以下代码:
SetStyle(ControlStyles.Selectable, false);

在InitializeComponent()之后;

示例:

public partial class Main : UserControl
{

    public Main()
    {
        InitializeComponent();
        SetStyle(ControlStyles.Selectable, false);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接