2016.5.30让窗口处于最顶层的方法

一、需要始终置顶时

最方便的方法是设置TopMost=true,当该属性必须在窗体完全显示完成后才有作用,否则置顶状态会不稳定。

应当设置在Shown事件中 (2020.2.4)

窗体事件执行顺序是 窗体构造函数(包含InitializeComponent事件) — Load事件 — Shown事件

API.SetWindowPos(this.Handle, -1, 0, 0, 0, 0, 0x001 | 0x002 | 0x040);也类似

 

二、一次性置顶

最简单的方法 Form. Activate() 

稍复杂的方法用API,目前没有看出比Activate方法有什么好处(可操作其它窗口,这就是好处2016.7.31)

 [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]

public static extern bool SetForegroundWindow(IntPtr hWnd);//设置此窗体为活动窗体

SetForegroundWindow(frmAltPro.Handle);

 

[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)]

public static extern IntPtr GetForegroundWindow(); //获得本窗体的句柄

GetForegroundWindow() //获取当前置顶窗体的句柄

原文地址:https://www.cnblogs.com/mol1995/p/5965001.html