What is Sendkeys alternative for closing an outdated application?

I want my C # program to close some kind of legacy application before continuing. A legacy application can be immediately disabled using ctrl + x. I could do this with Sendkeys, but I was told that sendkeys might be a little flaky. Is there an alternative way to send this key combination and close the legacy application?

+2
source share
3 answers

Other options: System.Diagnostics.Process.Kill
System.Diagnostics.Process.CloseMainWindow

If the latter works, use it. If not, and you don’t lose anything by killing the process directly, then Kill ().

+2
source

If you know that the window title is on the label bar, for example, β€œFoo”, you can use p / invoke to search for the window and get the β€œ FindWindow 'handle from it. Once you get the handle, you can use SendMessage ' for that handle. sending ' WM_KEYUP ' which stands for Ctrl + X together.

Hope this helps, Regards, Tom.

+3
source

If this is a GUI application. It can also respond to Alt + F4 via SendKeys.

Unlike ctrl + x, Alt + F4 does not depend on which window has focus. This is the standard accelerator for Windows applications, and most older graphics applications will support it. The main reason SendKey is considered flakey is because keystrokes fall into the focus window, which may or may not understand them. But Alt + F4 is an accelerator, so it should work no matter which window has focus.

If you can get the handle to the main window. (use FindWindow if you don't already have one). You can

 PostMessage(hwndApp, WM_SYSCOMMAND, SC_CLOSE, 0); 

This is equivalent to selecting the close option from the system menu in the window. SendMessage should also work, but PostMessage is more secure, since your application does not wait for the message to be delivered.

WM_SYSCOMMAND

+3
source

Source: https://habr.com/ru/post/1299505/


All Articles