using ShowWindow() unable to show window

false74

Well-known member
Joined
Aug 4, 2010
Messages
76
Programming Experience
Beginner
I am writing a simple code that will hide a window, or show a window if it has been hidden. I am using showwindow() to do so.

VB.NET:
    Private Declare Function ShowWindow Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nCmdShow As SHOW_WINDOW) As Boolean
    <Flags()> Private Enum SHOW_WINDOW As Integer
        SW_HIDE = 0
        SW_SHOWNORMAL = 1
        SW_NORMAL = 1
        SW_SHOWMINIMIZED = 2
        SW_SHOWMAXIMIZED = 3
        SW_MAXIMIZE = 3
        SW_SHOWNOACTIVATE = 4
        SW_SHOW = 5
        SW_MINIMIZE = 6
        SW_SHOWMINNOACTIVE = 7
        SW_SHOWNA = 8
        SW_RESTORE = 9
        SW_SHOWDEFAULT = 10
        SW_FORCEMINIMIZE = 11
        SW_MAX = 11
    End Enum

        For Each p As Process In Process.GetProcessesByName("notepad")
            ShowWindow(p.MainWindowHandle, SHOW_WINDOW.SW_HIDE)
        Next p
the above works great, as it hides the window from view completely

VB.NET:
        For Each p As Process In Process.GetProcessesByName("notepad")
            ShowWindow(p.MainWindowHandle, SHOW_WINDOW.SW_SHOW)
        Next p
however the above will not bring/show the window that has been hidden

I assume showwindow works differently than how I expect to make it work? what is the proper way?
 
The problem is that p.MainWindowsHandle reports handle 0 when window is hidden and there are no other visible top level windows for that process. As such the MainWindowsHandle property is fragile when called repeatedly, you can't rely on getting the same handle or any handle at all. What you can do is to store the window handles that you Hide and use the same handles later to Show.
Another thing to beware of is that the process may be closed in the mean time, and the process id may be reused, in that case the window is also closed and the window handle may also be reused by any process. There is a couple of options to verify this, for example by tracking when process closes, and if it does the corresponding window handle is invalidated. The other is to keep both process id and window handle, and later before showing verify that the given window handle still belongs to same process id (GetWindowThreadProcessId).
 
Ahh, yes that worked. storing the handle to the window before it has been hidden. I knew it was something like this that was preventing it from showing, thanks! And thanks for pointing out the problem with closing and reusing window handles.
 
Back
Top