让窗体获得焦点,一定会有您用到的时候
開發(fā)環(huán)境:Visual Studio .NET 2005 下的Windows Form Application
?
應(yīng)用場景: 當(dāng)我們有個窗體中的數(shù)據(jù)發(fā)生了變化而此窗體又沒有獲得焦點(不是用戶操作的當(dāng)前窗口)的時候,我們希望它獲得焦點,這樣用戶就可以立刻發(fā)現(xiàn)它上面的數(shù)據(jù)發(fā)生了變化。
?
新建一個Window應(yīng)用程序,會建立Form1,再添加一個Timer(timer1),設(shè)置如下屬性:
?
?
然后添加timer1的Tick事件函數(shù),完整代碼如下:
?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
?
namespace Test
{
??? public partial class PlayVoice : Form
??? {
??????? public PlayVoice()
??????? {
??????????? InitializeComponent();
??????? }
??????? [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "GetForegroundWindow", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)]
??????? public static extern IntPtr GetF();???????????? //獲得本窗體的句柄
??????? [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
??????? public static extern bool SetF(IntPtr hWnd);??? //設(shè)置此窗體為活動窗體
?
??????? private void timer1_Tick(object sender, EventArgs e)
??????? {
??????????? if (this.Handle != GetF())?????????? //如果本窗口沒有獲得焦點
??????????????? SetF(this.Handle);??????????????? //設(shè)置本窗口獲得焦點
??????? }
??? }
}
?
運行看看,你會發(fā)現(xiàn)當(dāng)Tick事件發(fā)生時,本窗口總會跳出來告訴你--我獲得焦點了
總結(jié)
以上是生活随笔為你收集整理的让窗体获得焦点,一定会有您用到的时候的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: select 和epoll模型区别
- 下一篇: 串口流控