当用户控件在C#winform中加载时,将焦点放在文本框中

use*_*370 1 c# user-controls load winforms

加载用户控件时如何在文本框上设置焦点?

在winforms中,我写道textbox1.focus(),usercontrol.load()但它没有用.

G G*_* Gr 11

请尝试使用.Select()方法.

textBox1.Select();
Run Code Online (Sandbox Code Playgroud)

要么

private void Form1_Load(object sender, EventArgs e)
{
    this.ActiveControl = textBox1;
}
Run Code Online (Sandbox Code Playgroud)

或者你可以试试:

private TextBox TextFocusedFirstLoop()
{
    // Look through all the controls on this form.
    foreach (Control con in this.Controls)
    {
    // Every control has a Focused property.
    if (con.Focused == true)
    {
        // Try to cast the control to a TextBox.
        TextBox textBox = con as TextBox;
        if (textBox != null)
        {
        return textBox; // We have a TextBox that has focus.
        }
    }
    }
    return null; // No suitable TextBox was found.
}

private void SolutionExampleLoop()
{
    TextBox textBox = TextFocusedFirstLoop();
    if (textBox != null)
    {
    // We have the focused TextBox.
    // ... We can modify or check parts of it.
    }
}
Run Code Online (Sandbox Code Playgroud)