C# 运行时添加的文本框将无法获得焦点
我在运行时创建了一个用户身份验证表单,该表单在加载时应该具有焦点。我想把焦点放在用户名的第一个文本框上,但是当表单加载时,表单和文本框都没有焦点。如果单击表单,则焦点将设置为相应的文本框C# 运行时添加的文本框将无法获得焦点,c#,forms,winforms,textbox,focus,C#,Forms,Winforms,Textbox,Focus,我在运行时创建了一个用户身份验证表单,该表单在加载时应该具有焦点。我想把焦点放在用户名的第一个文本框上,但是当表单加载时,表单和文本框都没有焦点。如果单击表单,则焦点将设置为相应的文本框 Form frm = Variables.FormCntrls.fmAuth; frm.Width = 315; frm.Height = 175; frm.StartPosition = FormStartPosition.Center
Form frm = Variables.FormCntrls.fmAuth;
frm.Width = 315;
frm.Height = 175;
frm.StartPosition = FormStartPosition.CenterScreen;
frm.FormBorderStyle = FormBorderStyle.None;
frm.TopMost = true;
frm.BackColor = Color.Black;
frm.ShowInTaskbar = false;
frm.Opacity = .9;
frm.Name = "userAuthentication";
frm.ShowInTaskbar = false;
frm.KeyPreview = true;
frm.Visible = true;
frm.Enabled = true;
Label lb = new Label()
{
Text = "User Authentication",
Width = frm.Width - 20,
Height = 30,
TextAlign = ContentAlignment.MiddleCenter,
Left = 10,
Top = 10,
ForeColor = Color.White,
Font = new Font("Arial", 16, FontStyle.Bold | FontStyle.Underline)
};
frm.Controls.Add(lb);
lb = new Label()
{
Text = "Username: ",
AutoSize = true,
TextAlign = ContentAlignment.MiddleCenter,
Left = 10,
Top = lb.Bottom + 20,
ForeColor = Color.White,
Font = new Font("Arial", 10, FontStyle.Bold)
};
frm.Controls.Add(lb);
TextBox tb = new TextBox()
{
Name = "user",
Width = 200,
Left = lb.Right + 2,
Top = lb.Top,
ForeColor = Color.Black,
TabIndex = 1,
};
frm.Controls.Add(tb);
tb.Select();
lb = new Label()
{
Text = "Password: ",
AutoSize = true,
TextAlign = ContentAlignment.MiddleCenter,
Left = lb.Left,
Top = lb.Bottom + 20,
ForeColor = Color.White,
Font = new Font("Arial", 10, FontStyle.Bold)
};
frm.Controls.Add(lb);
tb = new TextBox()
{
Name = "pass",
Width = tb.Right - (lb.Right + 2),
Left = lb.Right + 2,
Top = lb.Top,
ForeColor = Color.Black,
PasswordChar = '*',
TabIndex = 2,
};
frm.Controls.Add(tb);
Button btn = new Button()
{
Name = "UserAuthenticationBtn",
Width = 75,
Height = 30,
Left = tb.Right - 75,
Top = tb.Bottom + 15,
Text = "Login",
BackColor = default(Color),
UseVisualStyleBackColor = true,
TabIndex = 3,
};
btn.Click += new EventHandler(controlActions.btnActions.btnAuthorize);
frm.Controls.Add(btn);
btn = new Button()
{
Name = "Cancel",
Width = 75,
Height = 30,
Left = btn.Left - 85,
Top = tb.Bottom + 15,
Text = "Cancel",
BackColor = default(Color),
UseVisualStyleBackColor = true,
TabIndex = 4,
};
btn.Click += new EventHandler(controlActions.btnActions.btnCancle);
frm.Controls.Add(btn);
}
}
这方面的任何帮助都会很好。我确信我只是在某个地方遗漏了一个简单的细节。在创建控件时尝试以下操作:
tb.Focus();
tb.Select();
创建控件时请尝试以下操作:
tb.Focus();
tb.Select();
无法重现您的问题。你的代码很有魅力,我可以立即在第一个文本框中输入。虽然我改变了frm=Variables.FormCntrls.fmAuth代码>至
表格frm=新表格()代码>无法重现您的问题。你的代码很有魅力,我可以立即在第一个文本框中输入。虽然我改变了frm=Variables.FormCntrls.fmAuth代码>至表格frm=新表格()代码>我已经试过了,但它不起作用。我认为问题在于表单加载后由于某种原因没有焦点。如果我点击表单,它将聚焦到所需的文本框。我已经尝试过了,但它无法正常工作。我认为问题在于表单加载后由于某种原因没有焦点。如果我点击表单,它将聚焦到所需的文本框。