本文實例講述了C#實現讓窗體獲得焦點的方法。分享給大家供大家參考,具體如下:
開發環境:Visual Studio .NET 2005 下的Windows Form Application
應用場景:當我們有個窗體中的數據發生了變化而此窗體又沒有獲得焦點(不是用戶操作的當前窗口)的時候,我們希望它獲得焦點,這樣用戶就可以立刻發現它上面的數據發生了變化。
新建一個Window應用程序,會建立Form1,再添加一個Timer(timer1),設置如下屬性:
然后添加timer1的Tick事件函數,完整代碼如下:
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); //設置此窗體為活動窗體 private void timer1_Tick(object sender, EventArgs e) { if (this.Handle != GetF()) //如果本窗口沒有獲得焦點 SetF(this.Handle); //設置本窗口獲得焦點 } }}
運行看看,你會發現當Tick事件發生時,本窗口總會跳出來告訴你--我獲得焦點了
希望本文所述對大家C#程序設計有所幫助。
新聞熱點
疑難解答