C# - 如何以编程方式最小化最顶层的窗口?

时间:2016-12-02 08:51:04

标签: c# windows user-interface window

我做了一些研究,但我发现的大多数/所有答案都会最小化所有窗口或带有known window name/process name的窗口(链接覆盖两者)。

但是,如果我只想最小化最顶层的窗口怎么办?我该怎么做呢?我不知道从哪里开始。

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情。

  [DllImport("user32.dll")]
  private static extern IntPtr GetForegroundWindow();

  [DllImport("user32.dll")]
  internal static extern short GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);

  [DllImport("user32.dll")]
  internal static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);

  public struct RECT
  {
    public RECT(int l, int t, int r, int b)
    {
      Left = l;
      Top = t;
      Right = r;
      Bottom = b;
    }

    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
  }

  public struct POINT
  {
    public POINT(int x, int y)
    {
      X = x;
      Y = y;
    }

    public int X;
    public int Y;

  }



  public struct WINDOWPLACEMENT
      {
        public int length;
        public int flags;
        public ShowWindowEnum showCmd;
        public POINT ptMinPosition;
        public POINT ptMaxPosition;
        public RECT rcNormalPosition;
      }

     public enum ShowWindowEnum : uint
     {
        /// <summary>
        /// Activates the window and displays it as a minimized window.
        /// </summary>
        SW_SHOWMINIMIZED = 2,
     }

     private void MinimizeForegroundWindow()
     {
        WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
        GetWindowPlacement(_handle, ref placement);
        if (placement.showCmd != ShowWindowEnum.SW_SHOWMINIMIZED)
        {
            ShowWindow(_handle, ShowWindowEnum.SW_SHOWMINIMIZED);
        }
     }