[SuppressUnmanagedCodeSecurity] internalstaticpartialclassNativeMethods { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internalstaticexternboolSetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")] [SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist", Justification = "Entry point does exist on 64-bit Windows.")] internalstaticextern IntPtr SetWindowLongPtr64(IntPtr hWnd, Int32 nIndex, IntPtr dwNewLong);
[DllImport("user32.dll")] internalstaticextern Int32 GetWindowLong(IntPtr hWnd, int nIndex); }
需要用到的数据类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
[StructLayout(LayoutKind.Sequential)] internalstruct APPBARDATA { publicint cbSize; public IntPtr hWnd; publicint uCallbackMessage; publicint uEdge; public RECT rc; publicbool lParam; }
[StructLayout(LayoutKind.Sequential)] internalclassMONITORINFO { publicint cbSize = Marshal.SizeOf(typeof(MONITORINFO)); public RECT rcMonitor = new RECT(); public RECT rcWork = new RECT(); publicint dwFlags = 0; }
internalvoidFixWindowSize() { var mHwnd = new WindowInteropHelper(this).Handle; var monitor = NativeMethods.MonitorFromWindow(mHwnd, MONITOR_DEFAULTTONEAREST);
var pData = new APPBARDATA(); pData.cbSize = Marshal.SizeOf(pData); pData.hWnd = mHwnd;
// 判断任务栏是否自动隐藏 if (Convert.ToBoolean(NativeMethods.SHAppBarMessage((int)ABMsg.ABM_GETSTATE, ref pData))) { if (monitor != IntPtr.Zero) { // 获取当前屏幕大小 var monitorInfo = new MONITORINFO(); NativeMethods.GetMonitorInfo(monitor, monitorInfo); int x = monitorInfo.rcWork.left; int y = monitorInfo.rcWork.top; int cx = monitorInfo.rcWork.right - x; int cy = monitorInfo.rcWork.bottom - y;
// 获取任务栏位置 NativeMethods.SHAppBarMessage((int)ABMsg.ABM_GETTASKBARPOS, ref pData); var uEdge = GetEdge(pData.rc);
switch (uEdge) { case ABEdge.ABE_TOP: y++;break; case ABEdge.ABE_BOTTOM: cy--;break; case ABEdge.ABE_LEFT: x++;break; case ABEdge.ABE_RIGHT: cx--;break; } // 设置窗体大小 NativeMethods.SetWindowPos(mHwnd, new IntPtr(Constants.HWND_NOTOPMOST), x, y, cx, cy,SWP_SHOWWINDOW);