5

I have a c# application which I want to instruct to shutdown nicely, from a different process. I also want to be able to ask it to open its main window. I have a reference to its main window handle.

I know I can do it using elaborate schemes such as remoting or WCF. the question is can I do it using simpler mechanisms such as window messages, or the OnClose event handlers of the window in the c# application

Aviad Rozenhek
  • 2,259
  • 3
  • 21
  • 42

4 Answers4

7

Pinvoke SendMessage() to send the WM_CLOSE message to the app's main window. Asking it to open its main window is probably going to be quite difficult, you cannot obtain the window handle until the window is created. Process.Start() would be the normal way.

A low cost alternative to WCF and superior to pinvoke is a named pipe or a socket to interface with the app. This requires being able to modify the source code of the app.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    in the end, I went with this, approach, combined with two helpful answers in other questions: 1. [how to handle window messages in wpf](http://stackoverflow.com/questions/624367/how-to-handle-wndproc-messages-in-wpf) 2. [how to broadcast a message to all windows, including ones that are closed/invisible](http://stackoverflow.com/questions/1777668/send-message-to-a-windows-process-not-its-main-window) – Aviad Rozenhek Dec 09 '10 at 11:04
3

Process.CloseMainWindow

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.closemainwindow.aspx

Madhur Ahuja
  • 22,211
  • 14
  • 71
  • 124
2

I think that you could probably use FindWindow to find the correct child window and then SendMessage or PostMessage to send a WM_CLOSE.

Here's another StackOverflow question that deals with doing this in C#.

Edit: Though as the other answer says in that question, you might be able to use Process.CloseMainWindow instead.

Community
  • 1
  • 1
Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
0

I would first make my target application "aware" of the fact that some other process might like to trigger its closing or opening of a window or doing any action. This should be implemented similar to calling any method on another process through the target app's api or public methods. ..unless you are trying to do something with 3rd party applications, I think you shouldn't attempt to directly send them messages to close or shutdown.