C# WINFORM 强制让窗体获得焦点
//调用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 han;
在窗体加载的时候给变量赋值,即将当前窗体的句柄赋给变量
void Form1_Load(object sender, EventArgs e)
{
han = this.Handle;
timer2.Enabled = true;
}
//加载一个定时器控件,验证当前WINDOWS句柄是否和本窗体的句柄一样,如果不一样,则激活本窗体
private void timer2_Tick(object sender, EventArgs e)
{
if (han != GetForegroundWindow())
{
SetForegroundWindow(han);
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步