how to close a window from a different process

谁都会走 提交于 2019-12-23 10:19:09

问题


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


回答1:


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.




回答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.




回答3:


Process.CloseMainWindow

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




回答4:


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.



来源:https://stackoverflow.com/questions/4387933/how-to-close-a-window-from-a-different-process

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