开发者

Hook to detect Minimize Window C#

Hi all How can I detect in C # that the user clicked on the minimize button of an external program (eg开发者_StackOverflow中文版 notepad)? Thanks


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜