方法一:
//調用API [System.Runtime.InteropServices.DllImport("user32", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)] public static extern IntPtr GetFocus(); //獲得本窗體的句柄 [System.Runtime.InteropServices.DllImport("user32", EntryPoint = "SetForegroundWindow")] public static extern bool SetFocus(IntPtr hWnd);//設置此窗體為活動窗體 // 定義變量,句柄類型 public IntPtr han; private void Form1_Load(object sender, EventArgs e){ //在窗體加載的時候給變量賦值,即將當前窗體的句柄賦給變量 han = this.Handle; } private void timer1_Tick(object sender, EventArgs e){ // 加載一個定時器控件,驗證當前WINDOWS句柄是否和本窗體的句柄一樣,如果不一樣,則激活本窗體 if (han != GetFocus()){ SetFocus(han); } this.WindowState = FormWindowState.Normal; }
c#本來就有Focus()方法,我沒用DllImport,試過下面幾個方法都不行
control.Activate();
control.TopMost = true;
control.Focus();
方法二:
[System.Runtime.InteropServices.DllImport("user32")] private static extern IntPtr GetActiveWindow();//獲取當前窗體的活動狀態 // 判斷當前窗口是否處於活動狀態的方法 private bool ThisIsActive(){ return (GetActiveWindow() == this.Handle);} private void timer1_Tick(object sender, EventArgs e){ if (!ThisIsActive()){ this.Activate(); } this.WindowState = FormWindowState.Normal; }
方法三:
[DllImport("user32")] private static extern IntPtr FindWindow(string lpClassName,string lpWindowName); [DllImport("user32")] private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); //在窗體On_Load事件中添加(Santos的代碼): IntPtr hDeskTop=FindWindow("Progman", "Program Manager"); SetParent(this.Handle,hDeskTop);
方法四:
[System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd);
拓展:
private void Form1_Load(object sender, EventArgs e) { this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.ShowInTaskbar = false; this.TopMost = true; this.timer1.Interval = 1; this.timer1.Enabled = true; this.WindowState = FormWindowState.Maximized; } private void timer1_Tick(object sender, EventArgs e) { SetForegroundWindow(this.Handle); }