IntPtr handle = process.MainWindowHandle;
if (handle != IntPtr.Zero)
{
SetWindowPos(handle, 0, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
}
然后,当我在构造函数中调用SetWindowPos时,应该给它什么?处理很好,我知道应该是什么。但是所有的resr 0,0,0,0,0,0以及SWP_NOZORDER和SWP_NOSIZE的值应该是多少?
我要做的是将手柄置于屏幕的正面和中央。把它放到最前面我知道该怎么做,我正在使用
SetForegroundWindow(IntPtr hWnd);
,它工作正常。但是,如何使用SetWindowPos强制将其置于屏幕中央? 最佳答案
在居中之前,首先必须知道它有多大。这可以通过GetWindowRect() API来完成。之后,只需考虑屏幕大小即可计算中心位置:
public partial class Form1 : Form
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
private const int SWP_NOSIZE = 0x0001;
private const int SWP_NOZORDER = 0x0004;
private const int SWP_SHOWWINDOW = 0x0040;
[DllImport("user32.dll", SetLastError=true)]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
Process process;
public Form1()
{
InitializeComponent();
process = Process.GetProcessesByName("calc").FirstOrDefault();
}
private void button1_Click(object sender, EventArgs e)
{
if (process == null)
return;
IntPtr handle = process.MainWindowHandle;
if (handle != IntPtr.Zero)
{
RECT rct;
GetWindowRect(handle, out rct);
Rectangle screen = Screen.FromHandle(handle).Bounds;
Point pt = new Point(screen.Left + screen.Width / 2 - (rct.Right - rct.Left) / 2, screen.Top + screen.Height / 2 - (rct.Bottom - rct.Top) / 2);
SetWindowPos(handle, IntPtr.Zero, pt.X, pt.Y, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
}
}
}
关于c# - 如何使用SetWindowPos?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31271828/