C#WINFORM强制让窗体获得焦点的方法代码
//调用API
[System.Runtime.InteropServices.DllImport("user32.dll",CharSet=System.Runtime.InteropServices.CharSet.Auto,ExactSpelling=true)]
publicstaticexternIntPtrGetForegroundWindow();//获得本窗体的句柄
[System.Runtime.InteropServices.DllImport("user32.dll",EntryPoint="SetForegroundWindow")]
publicstaticexternboolSetForegroundWindow(IntPtrhWnd);//设置此窗体为活动窗体
//定义变量,句柄类型
publicIntPtrhan;
在窗体加载的时候给变量赋值,即将当前窗体的句柄赋给变量
voidForm1_Load(objectsender,EventArgse)
{
han=this.Handle;
timer2.Enabled=true;
}
//加载一个定时器控件,验证当前WINDOWS句柄是否和本窗体的句柄一样,如果不一样,则激活本窗体
privatevoidtimer2_Tick(objectsender,EventArgse)
{
if(han!=GetForegroundWindow())
{
SetForegroundWindow(han);
}
}
相关文章