The best way to cleanly close an application running through another
I couldn't find any close answers to this question, so I'm advising SO users experience:
Scenario:
I have two small C # winforms applications where one behaves like a server or host and the other behaves like a client. They use data through SQL Server in terms of configuration settings.
I am currently starting a client application (which should only run intermittently) from the server application through Process.Start()
and terminating it with Process.CloseMainWindow()
(after finding it in the process list).
While it seems clean enough, I wondered if there is a better way.
Question:
What would be the best way to instruct the client application to close:
- Continue using Process.CloseMainWindow ()?
- Implement WCF between applications? (I need help on how to do this.)
- Set a variable in SQL that the client application checks?
- Another way?
a source to share
Considering that Process.Start(string)
The new Process component associated with the process resource, or null if the process resource has not been started (for example, if an existing process is being reused).
Process myProcess = Process.Start("client.exe");
Then you can use that value to call CloseMainWindow
:
myProcess.CloseMainWindow();
The only overload that does not return a component Process
is parameterless .
(BTW I haven't read the comments on this question until after I posted this answer)
a source to share
Given that the Process.CloseMainWindow () process indicates that both programs are running on the same computer. Given that a true service cannot run programs visible on the desktop, more indicates that your server program is running like a normal user application.
It makes no sense to have separate programs now. Just create a visible window by the server. The interoperability is trivial since everything runs in one program and has access to all the states of that program.
If server processing interferes with saving the client window, then display that window in the stream. This helper class does its job:
using System;
using System.Threading;
using System.Windows.Forms;
static class ClientView {
private static Form mView;
public static void Start(Form view) {
if (Busy) throw new InvalidOperationException("View already running");
mView = view;
mView.FormClosed += (o, e) => { mView = null; }
Thread t = new Thread(() => Application.Run(view));
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public static void Stop() {
if (Busy) mView.Invoke(new MethodInvoker(() => mView.Close()));
}
public static bool Busy { get { return mView != null; } }
}
Sample usage:
ClientView.Start(new ClientForm());
a source to share