Windorm和WPF等應(yīng)用程序想自己獲取焦點焦點那是不可能的,只能通過系統(tǒng)的API來實現(xiàn)
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow(); //獲得當(dāng)前活動窗體的句柄
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
public static extern bool SetForegroundWindow(IntPtr hWnd);//設(shè)置此窗體句柄的窗體為活動窗體
上面第一個函數(shù)獲取的是當(dāng)前窗體的句柄,? 如果窗體應(yīng)用要獲取自己的句柄的話就使用下面的方法獲取
private IntPtr ptr;
ptr = this.Handle;
拿到句柄的話我們就可以使用SetForegroundWindow將窗體設(shè)置為前臺應(yīng)用文章來源:http://www.zghlxwxcb.cn/news/detail-659474.html
這可以能還不夠,等它失去焦點的時候我們讓它重新獲取焦點文章來源地址http://www.zghlxwxcb.cn/news/detail-659474.html
// 添加焦點丟失監(jiān)聽
LostFocus += OnLostFocus;
private void OnLostFocus(object sender, EventArgs e)
{
new Thread(new ThreadStart(delegate {
Thread.Sleep(1000);
if(TopMost)
SetForegroundWindow(ptr);
})).Start();
}
到了這里,關(guān)于C# 應(yīng)用程序強制獲取焦點的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!