private void SetWindowBottommost(bool value) { IntPtr hWnd = new WindowInteropHelper(this).Handle; IntPtr hWndDesktop = FindDesktopWindow(); if (hWndDesktop == IntPtr.Zero) return; RECT desktopRect = new RECT(); WINDOWPLACEMENT wp = new WINDOWPLACEMENT(); if (GetWindowRect(hWndDesktop, out desktopRect) == false) return; if (NativeMethods.GetWindowPlacement(hWnd, out wp) == false) return; Debug.Write("DesktopRect=(" + desktopRect.Left + ", " + desktopRect.Top + ", " + desktopRect.Right + ", " + desktopRect.Bottom + "), "); Debug.Write("[Before]WindowRect=(" + wp.normalPosition.Left + ", " + wp.normalPosition.Top + ", " + wp.normalPosition.Right + ", " + wp.normalPosition.Bottom + "), "); if (value) { // WS_CHILDを追加 var wl = GetWindowLongPtr(hWnd, (int)WindowLongFlags.GWL_STYLE); wl = (UIntPtr)(wl.ToUInt32() | (uint)WindowStyles.WS_CHILD); SetWindowLongPtr(hWnd, (int)WindowLongFlags.GWL_STYLE, wl); // Desktopウィンドウの子ウィンドウにして最背面に配置する SetParent(hWnd, hWndDesktop); // ウィンドウの位置を調整 AdjustWindowPosition(ref wp, -desktopRect.Left, -desktopRect.Top); } else { // Desktopウィンドウから切り離す SetParent(hWnd, IntPtr.Zero); // WS_CHILDを削除 var wl = GetWindowLongPtr(hWnd, (int)WindowLongFlags.GWL_STYLE); wl = (UIntPtr)(wl.ToUInt32() & ~(uint)WindowStyles.WS_CHILD); SetWindowLongPtr(hWnd, (int)WindowLongFlags.GWL_STYLE, wl); // ウィンドウの位置を調整 AdjustWindowPosition(ref wp, desktopRect.Left, desktopRect.Top); } NativeMethods.SetWindowPlacement(hWnd, ref wp); Debug.Write("[After]WindowRect=(" + wp.normalPosition.Left + ", " + wp.normalPosition.Top + ", " + wp.normalPosition.Right + ", " + wp.normalPosition.Bottom + ")\r\n"); }
public static extern bool GetWindowPlacement( IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);
private static void AdjustWindowPosition(ref WINDOWPLACEMENT wp, int offsetX, int offsetY) { wp.normalPosition.Left += offsetX; wp.normalPosition.Top += offsetY; wp.normalPosition.Right += offsetX; wp.normalPosition.Bottom += offsetY; }