进入窗口后默认聚焦到某个文本框,两种方法:
①设置tabindex
把该文本框属性里的tabIndex设为0,焦点就默认在这个文本框里了。
②Winform的Activated事件
在Form的Activated事件中添加textBox1.Focus(), 即可获得焦点。
private
void
Form1_Activated(
object
sender, EventArgs e)
{
textBox1.Focus();
}
|
TextBox是可以获得焦点的. 有几个前提:
1. TextBox所属的窗体(Form)在可操作(Active)状态. 即用户选中了Form.
2. TextBox的Enable属性,Visiable属性为True.
刚开始时原以为在Form的Load事件中添加textBox1.Focus(),测试失败
private
void
Form1_Load(
object
sender, EventArgs e)
{
textBox1.Focus();
}
|
因为在窗体加载时调用Focus()函数时, TextBox还未能成功的被显示到界面上。所以导致了失败。
上面经过验证时可行的;
下面还有一种方法,不过待验证:
form1.shown+=....
在注册时间里面可以写form1.focus();是可以有效获得焦点的,
另外也可以调用api flashwindow来单次置顶form1,然后在form1.focus();
//调用API
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow(); //获得本窗体的句柄
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
public static extern bool SetForegroundWindow(IntPtr hWnd);//设置此窗体为活动窗体
//定义变量,句柄类型
public IntPtr Handle1;
//在窗体加载的时候给变量赋值,即将当前窗体的句柄赋给变量
void Form1_Load(object sender, EventArgs e)
{
Handle1 = this.Handle;
timer2.Enabled = true;
}
//加载一个定时器控件,验证当前WINDOWS句柄是否和本窗体的句柄一样,如果不一样,则激活本窗体
private void timer2_Tick(object sender, EventArgs e)
{
if (Handle1 != GetForegroundWindow()) //持续使该窗体置为最前,屏蔽该行则单次置顶
{
SetForegroundWindow(Handle1);
//timer2.Stop();//此处可以关掉定时器,则实现单次置顶
}
}
转自:http://www.cnblogs.com/JuneZhang/archive/2011/04/19/2020585.html