C#實現讓窗體獲得焦點的方法示例。本站提示廣大學習愛好者:(C#實現讓窗體獲得焦點的方法示例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#實現讓窗體獲得焦點的方法示例正文
作者:JoeBlackzqq
這篇文章主要介紹了C#實現讓窗體獲得焦點的方法,涉及C#窗體事件相關操作技巧,需要的朋友可以參考下本文實例講述了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#相關內容感興趣的讀者可查看本站專題:《C#窗體操作技巧匯總》、《C#數據結構與算法教程》、《C#常見控件用法教程》、《C#面向對象程序設計入門教程》及《C#程序設計之線程使用技巧總結》
希望本文所述對大家C#程序設計有所幫助。