Hook to detect Minimize Window C#

流过昼夜 提交于 2019-12-11 03:05:43

问题


Hi all How can I detect in C # that the user clicked on the minimize button of an external program (eg notepad)? Thanks


回答1:


This should work:

    public class myClass
    {
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);

    const UInt32 SW_HIDE =         0;
    const UInt32 SW_SHOWNORMAL =       1;
    const UInt32 SW_NORMAL =       1;
    const UInt32 SW_SHOWMINIMIZED =    2;
    const UInt32 SW_SHOWMAXIMIZED =    3;
    const UInt32 SW_MAXIMIZE =     3;
    const UInt32 SW_SHOWNOACTIVATE =   4;
    const UInt32 SW_SHOW =         5;
    const UInt32 SW_MINIMIZE =     6;
    const UInt32 SW_SHOWMINNOACTIVE =  7;
    const UInt32 SW_SHOWNA =       8;
    const UInt32 SW_RESTORE =      9;

    public myClass()
    {
        var proc = Process.GetProcessesByName("notepad");
        if (proc.Length > 0)
        {
            bool isNotepadMinimized = myClass.GetMinimized(proc[0].MainWindowHandle);

            if (isNotepadMinimized)
                Console.WriteLine("Notepad is Minimized!");
        }
    }

    private struct WINDOWPLACEMENT
    {
        public int length;
        public int flags;
        public int showCmd;
        public System.Drawing.Point ptMinPosition;
        public System.Drawing.Point ptMaxPosition;
        public System.Drawing.Rectangle rcNormalPosition;
    }

    public static bool GetMinimized(IntPtr handle)
    {
        WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
        placement.length = Marshal.SizeOf(placement);
        GetWindowPlacement(handle, ref placement);
        return placement.flags == SW_SHOWMINIMIZED;
    }
}

Edit: Just re-read you question and noticed you wanted to be notified when Notepad get minimized. Well you could use the code above in a timer to poll the status change.




回答2:


As Hans Passant said you cannot get the event of it being minimized.

Although, I believe you can store the states of windows and see if they are minimized at a later interval. by using the GetWindowPlacement Function.




回答3:


The answer above has an error.

You need to check placement.showCMD, not placement.flags

WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
placement.length = Marshal.SizeOf(placement);
GetWindowPlacement(_hwnd, ref placement);
return placement.showCmd == SW_SHOWMINIMIZED;

Please see https://msdn.microsoft.com/en-us/library/windows/desktop/ms632611(v=vs.85).aspx



来源:https://stackoverflow.com/questions/5318037/hook-to-detect-minimize-window-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!