C# 设置窗体文本框焦点

Winform中的TextBox如何设置焦点,想实现载入窗体时,文本框自动获取到输入焦点。可是调用this.txtID.Focus()无法获取焦点CanFocus属性是false并且为只读,请问Winform中的TextBox可以设置焦点的吗?如何设置

TextBox是可以获得焦点的. 有几个前提.

1. TextBox所属的窗体(Form)在可操作(Active)状态. 即用户选中了Form.
2. TextBox的Enable属性,Visiable属性为True.

你在窗体加载时调用Focus()函数时, TextBox还未能成功的被显示到界面上.
所以导致了失败.

应修改为, 在Form的Activated事件中添加this.txtID.Focus(), 即可获得焦点.

我给你个示例.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Activated(object sender, EventArgs e)
{
textBox1.Focus();
}
}
}

希望对你有帮助.
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-01-01
你在OnShown的时候执行this.txtID.Focus()就没问题了。
protected override void OnShown(EventArgs e)
{
this.txtID.Focus();
base.OnShown(e);
}
相似回答