-1

How can i check if another instance is running ?
Also if it is running how can I force my already opened instance to open a file ?
Also if it is possible can I force it to get focus? ( I need this seperate)

Mitcoc
  • 31
  • 1
  • 9
  • Please specify your question. What `instance` exactly do you want to check? – Clive DM Aug 16 '15 at 04:13
  • @CliveDM program instance. I mean if already my program is running then open file to the already opened instance (not the new). – Mitcoc Aug 16 '15 at 04:17

1 Answers1

1

How can i check if another instance is running ?

You could use Process.GetProcesses() to get a list of processes which are running on your machine. And simply do your compare with Process.Name. With rather simple name, you may need additional check for your application.

Also if it is running how can I force my already opened instance to open a file ?

If you want to communicate between 2 processes, I would recommend SendMessage method. See here.

Also if it is possible can I force it to get focus? ( I need this seperate)

You could use SetForgoundWindow method (also require P/Invoke). See here.

Community
  • 1
  • 1
Clive DM
  • 551
  • 4
  • 13
  • Better hope nobody else has the same process name. I've seen two totally unrelated programs with a conflict like this, although it's nastier--the offending program sends a close to the other program. – Loren Pechtel Aug 16 '15 at 04:53
  • About using `Process.GetProcesses()` @LorenPechtel has right. Now about communicating between 2 processes , the article that u linked me it says that I should better avoid using SendMessage method. – Mitcoc Aug 16 '15 at 05:04
  • @LorenPechtel Yes, it'll require some more check if the process's name is rather simple. – Clive DM Aug 16 '15 at 05:17
  • @Mitcoc I don't see any `avoid` there. As for the answer in that link, it recommends to use `event` to send and receive events, **in one program**. And your question is about communicate between 2 **different** programs (although it's the same `.exe` file you ran, but it do runs in different context), with absolutely no relate to each other. So the `event` could not be use under this circumstance. – Clive DM Aug 16 '15 at 05:24
  • @CliveDM I found a way to detect if another instance is running via `mutex`. About SendMessage you had right. Im going to use it. Thanks a lot !! – Mitcoc Aug 16 '15 at 06:00
  • @Mitcoc Glad to help. As for `mutex` do you mean the class `System.Threading.Mutex`? – Clive DM Aug 16 '15 at 06:08
  • @CliveDM [yes](http://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application?rq=1) – Mitcoc Aug 16 '15 at 06:40