//首先要說明的是與TopMost的效果不同,TopMost是屬性定義,而且設置True后,如果不設為Flase則一直置頂,效果很差,
//以下方法解決了TopMost使用上的不足
//調用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 Handle1;
//在窗體加載的時候給變量賦值,即將當前窗體的句柄賦給變量
void Form1_Load(object sender, EventArgs e)
{
Handle1 = this.Handle;
timer2.Enabled = true;
}
//加載一個定時器控件,驗證當前WINDOWS句柄是否和本窗體的句柄一樣,如果不一樣,則激活本窗體
private void timer2_Tick(object sender, EventArgs e)
{
if (Handle1 != GetForegroundWindow()) //持續使該窗體置為最前,屏蔽該行則單次置頂
{
SetForegroundWindow(Handle1);
//timer2.Stop();//此處可以關掉定時器,則實現單次置頂
}
}
示例代碼:
namespace WinFormsApp_GetForegroundWindowTest
{
public partial class Form1 : Form
{
//調用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 Handle1;
Timer timer2 = new Timer();
public Form1()
{
InitializeComponent();
}
Form Form2;
//在窗體加載的時候給變量賦值,即將當前窗體的句柄賦給變量
void Form1_Load(object sender, EventArgs e)
{
Handle1 = this.Handle;
timer2.Tick += new EventHandler(timer2_Tick);
timer2.Interval = 1000;
}
//加載一個定時器控件,驗證當前WINDOWS句柄是否和本窗體的句柄一樣,如果不一樣,則激活本窗體
private void timer2_Tick(object sender, EventArgs e)
{
//if (Handle1 != GetForegroundWindow()) //持續使該窗體置為最前,屏蔽該行則單次置頂
//{
SetForegroundWindow(Handle1);
timer2.Stop();//此處可以關掉定時器,則實現單次置頂
//}
}
private void btnSetForm2ToTop_Click(object sender, EventArgs e)
{
if (Form2 == null) return;
timer2.Enabled = true;
Handle1 = Form2.Handle;
}
private void btn_OpenForm2_Click(object sender, EventArgs e)
{
Form2 = new Form();
Form2.Text = "Form2";
Form2.Show();
}
}
}