SetWindowPos函数

有一天,用户突然对我说,你这个窗口能不能放到最顶端,这样操作和打开文件就很不方便了。这个功能就需要改变窗口的属性了。比如大家使用QQ时,就有一个功能,设置QQ的窗口在最顶端,不管你选择了什么窗口,QQ的界面永远都在最前面。又像FlashGet的状态查看窗口,一直保持在窗口的最前端,让你看到当前下载的流量程况。现在股票那么火爆,很多人一边工作,一边查看股票,如果错失了机会,又少了很多钱的啊!面对这样的需求,就需要把一些窗口永远摆在最前面,这样起到提示用户的作用。因此,学会使用SetWindowPos函数,就成为能否让软件满足客户需求的关键了。与MoveWindow函数相比,SetWindowPos函数的功能比较强大一点。

函数SetWindowPos声明如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// C# Signature:

[DllImport("user32.dll", SetLastError=true)]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);

// VB.NET Signature:

<DllImport("user32.dll", SetLastError:=True)> _
Private Shared Function SetWindowPos(ByVal hWnd As IntPtr, ByVal hWndInsertAfter As IntPtr, ByVal X As Integer, ByVal Y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal uFlags As SetWindowPosFlags) As Boolean
End Function

// VB Signature

Public Declare Function SetWindowPos Lib "user32.dll" _
(ByVal hWnd As Long, _
ByVal hWndInsertAfter As Long, _
ByVal X As Long, _
ByVal Y As Long, _
ByVal cx As Long, _
ByVal cy As Long, _
ByVal wFlags As Long) As Long

hWnd是窗口的句柄。

hWndInsertAfter是窗口Z顺序属性。

X是窗口在X轴的位置。

Y是窗口在Y辆的位置。

cx是窗口的宽度。

cy是窗口的高度。

uFlags是选择设置的标志。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// C# Constants:

static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
static readonly IntPtr HWND_TOP = new IntPtr(0);
static readonly IntPtr HWND_BOTTOM = new IntPtr(1);

public static class HWND
{
public static IntPtr
NoTopMost = new IntPtr(-2),
TopMost = new IntPtr(-1),
Top = new IntPtr(0),
Bottom = new IntPtr(1);
}

public static class SWP
{
public static readonly int
NOSIZE = 0x0001,
NOMOVE = 0x0002,
NOZORDER = 0x0004,
NOREDRAW = 0x0008,
NOACTIVATE = 0x0010,
DRAWFRAME = 0x0020,
FRAMECHANGED = 0x0020,
SHOWWINDOW = 0x0040,
HIDEWINDOW = 0x0080,
NOCOPYBITS = 0x0100,
NOOWNERZORDER = 0x0200,
NOREPOSITION = 0x0200,
NOSENDCHANGING = 0x0400,
DEFERERASE = 0x2000,
ASYNCWINDOWPOS = 0x4000;
}

//VB.NET Constants:

Private ReadOnly HWND_BOTTOM As New IntPtr(1)
Private ReadOnly HWND_NOTOPMOST As New IntPtr(-2)
Private ReadOnly HWND_TOP As New IntPtr(0)
Private ReadOnly HWND_TOPMOST As New IntPtr(-1)

调用这个函数的例子如下:

1
2
3
4
5
6
7
8
9
10
public static void MoveWindowToMonitor(int monitor)
{
var windowHandler = GetActiveWindowHandle();

var windowRec = GetWindowRect(windowHandler);
// When I move a window to a different monitor it subtracts 16 from the Width and 38 from the Height, Not sure if this is on my system or others.
SetWindowPos(windowHandler, (IntPtr)SpecialWindowHandles.HWND_TOP, Screen.AllScreens[monitor].WorkingArea.Left,
Screen.AllScreens[monitor].WorkingArea.Top, windowRec.Size.Width + 16, windowRec.Size.Height + 38,
SetWindowPosFlags.SWP_SHOWWINDOW);
}