Process.CloseMainWindow not working?

J. Scott Elblein

Well-known member
Joined
Dec 14, 2006
Messages
166
Location
Chicago
Programming Experience
10+
G'day all

I am trying to write a very simple program to loop through all instances of a program with the same name, and close them 1) gracefully, and 2) if hanging, Kill it ungracefully.

I have tried two very slightly different versions of code that I found examples of on the net, and both of them appear to do absolutely nothing, even though the code actually does go through proc.closemainwindow code.

Here are the 2 versions I am using so far. Can someone please help shed some light? Thanks! :)

VB.NET:
For Each proc As Process In Process.GetProcessesByName("PDExplo")
        proc.CloseMainWindow()
Next

VB.NET:
        Dim processList() As Process

        processList = Process.GetProcessesByName("PStart")
        For Each proc As Process In processList
            If MsgBox("Terminate " & proc.ProcessName & "?", MsgBoxStyle.YesNo, "Terminate?") = MsgBoxResult.Yes Then
                proc.CloseMainWindow()
            End If
        Next

        MessageBox.Show("Done")
 
Does this process have a main window? If not then CloseMainWindow will do nothing. Does the program display a prompt or the like when closing? If so then calling CloseMainWindow will cause that prompt to be displayed and the process will not exit until the user confirms the prompt.
VB.NET:
For Each proc As Process In Process.GetProcessesByName("process name here")
    If proc.MainWindowHandle <> IntPtr.Zero Then
        proc.CloseMainWindow() 'ask the process to exit.
        proc.WaitForExit(10000) 'wait up to 10 seconds.
    End If

    If Not proc.HasExited Then
        proc.Kill() 'force the process to exit.
    End If
Next proc
 
Thank you for the code. :)

It's still behaving the same however (except of course when the .Kill command is called). Just so I am clear on the "Main Window" concept, does that mean the window has to specifically be open and on the screen? Or can the app be minimized to the tray still?

Either way, whether I have the window minimized to tray or on screen (I have tried with a small usb program called Pstart and Powerdesk) , when the CloseMainWindow command is called, nothing happens, then the kill command fires and they close (ungracefully). I don't mind if a closing prompt for the program pops which is why I really want the closemainwindow to work rather than just kill it (they aren't for these two proggies, but I want the user to have a chance to save work if needed anyway).

If it helps, I am running Vista Premium Home, but I think that shouldn't be an issue?
 
Back
Top