So I have a background program that starts with Windows, minimized to system tray icon. Once it loads I need it to constantly start checking if a process has started (for example VLC). Once the process has started, It must wait for it to close in order to start doing stuff and then get back to check if it has started. I've been trying to do this for a while now, but I just can't figure out how.
How would I constantly check if a program has started?
One way would be to have the Background Deamon look for aprogramm of a specific name. Unfortunately this not overly reliable (due to name overlaps), would require a lot of polling and runs the risk of race conditions (the process starting when your deamon is still working).
What would be reliable, is if it is the Deamon that actually starts the foreground process. That way it could do work before Process.Start() and after Process.WaitForExit(), with full information when both states happen: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process?view=netcore-3.1
Steam is a good example. It is a single-instance process, so any further requests can be relayed to the running instance. The desktop links to programms/games are actually weblinks - not programm links. Those links use the :steam protocoll, wich is associated with the steam processes. So it goes like this:
user klicks on a WebLink with :steam procotoll
Windows resolves to hand this into a commandline call to the steam programm
A instance is started with the proper order in via commandline. Single instancing will not allow a 2nd instanc to start, but hand the request over a already running one
the already or now suddenly running instance calls the programm, having full data on when it starts and ends - being the actuall logical caller
Related
What I thought would be pretty easy is quickly defeating me. I'm not a native C# programmer, but was asked to create a WinForm application that has a single instance. I''ve seen the Mutex examples already on StackOverflow, but the one thing that eludes me is the ability to pass parameters to window on the command line, parse the values and repaint the form with the new values.
Anyone have an example of this? The main thing that seems to be tripping me up is the threading. I want to run my.exe and show the window. Each time the form is run, I don't want a new form -- just to get the new parameters and show them in the form.
Any/All replies are appreciated!
When you starting another instance of your application, you are running same code, but on different process. So, you need to look on passing data between processes. Something like Named Pipes or Remoting.
#lazyberezovsky is right. Invoking again the application from the command line will spawn a different, unrelated process and you would require inter-process communication to forward the new parameters to the previously running app instance, before quitting the new process being invoked.
IMHO, the easiest way (not the best certainly) to communicate between these two processes would be using the Windows Registry, as this is already thread-safe and the API is very simple.
First, when the application runs, before showing the main form, I would perform a check to see if another instance of the app is running.
If false, it is the first time the app runs and I would process the command line and show the form as regular. I would also clear the registry key used for inter-process communication (see below).
If true, then I would store the command line in the registry on a specific key that will serve for inter-process communication and then I would terminate the application without even showing the main form.
Your running application (the first instance) will require to start a polling mechanism (could be a Windows timer firing once each second) that regularly examines the registry key where a new command line is expected . It would normally find and empty string and do nothing, but if the retrieved value is not empty, then it would mean the user spawned again the application with a different set of parameters, then you can proceed to decode your command line and repaint the window as necessary. After this, make sure you clear the registry entry again, so the polling mechanism resumes and detects the next time the application is invoked by the user.
Named pipes, WCF, .remoting or TCP sockets are IPC mechanisms that can be used and won't require a polling mechanism, that may be frowned upon by some. ;)
Hope this helps!
At my consulting company, we use some very expensive simulation software. I need a means to monitor the usage of these applications/processes (in the background, using C#). The idea is that when someone runs a particular application, they are prompted to enter the job name. Then, when they close the program, the amount of time they used it is sent to a database residing on the network. This way we can recoup the costs of the software by charging our clients on a $/min basis. Aside from the prompt, the program must be nearly invisible to users.
I have thought of a few ways of doing this, but I'm not sure what's best:
Have a program that runs on startup, with only a tray icon. I suppose then I would have to have a backgroundworker monitoring the processes continuously, perhaps sleeping the thread, and checking the processes every 5 minutes or so.
Use something like Quartz.net, on startup and with a tray icon. If this is even applicable on a minute-by-minute basis. I am not very familiar with Quartz.net, but from my research it looks maybe do-able.
Use some kind of Windows Service. This one I am least familiar with.
Which method would be most fruitful? Thanks
You could write a simple C# program that upon execution collects the required information and start time.
Then by using the Process class you execute the simulation software.
Wait for the process to end using WaitForExit() and do whatever is needed with the execution time etc.
So essentially you end up with an application that simply collects the required information, launches the main application, waits for the application to end and does whatever is needed with the total execution time. As far as being invisible to the user, you could just minimize the main window ( which also acts as the form for collecting the needed info ) while waiting for the application to end.
Here is a small example of starting an executable within C#.
private void LaunchApp()
{
Process proc = new Process();
/* we are going to assume wordpad is installed on workstation */
/* collect needed info and time */
proc.StartInfo.FileName = "Wordpad.exe";
proc.StartInfo.Arguments = "SomeFile.txt";
proc.Start();
proc.WaitForExit();
/* App has ended. Now process execution time etc. */
}
Some explanation: for a project I'm working on I have to write a program that is running in the background, detects changes to files, and uploads the modified files to a web service to make it available to others. Quite simple synchronization if it were not for the case when a user modifies a big file and decides to shutdown its computer right after the edit.
I could cancel the upload and wait for the next reboot to do the upload, but I can imagine the user downloading the file from the web to another computer the next morning and don't understanding why his changes from last night aren't there.
So my idea was to detect when the users logs off or reboots Windows, and if I'm in the middle of an upload, just asking the user "We're still synchronizing file Foo.txt that you just changed. Are you sure you want to reboot ? You're changes won't be available to others until you restart your computer !". If the users says no, I'd need to cancel the reboot/loging off
Is this possible?
There is a static class called SystemEvents that exposes this behaviour:
http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.aspx
However, it cannot differentiate between certain actions and doesn't pause the OS process time-out guard. I used it once, but the default time-out as configured in the registry is a little short so will likely need increasing.
To cut a long story short, it all felt a little hackish.
To add to #Adam's answer, if you need to tell the difference between logoff and shutdown/reboot, you can handle the WM_QUERYENDSESSION message.
"Shutdown Changes for Windows Vista" is a useful article for understanding the shutdown timeout.
Trying to block a shutdown is a lossy proposition these days, it's no longer possible to do so in Vista and up. A prompt isn't readable nor reachable. Using a service is highly indicated here, lets you survive a user log-off. And a reboot, your service will start running again automatically, letting you complete the job.
Is there any good way to handle a forced exit in C#?
I have a formless C# application that talks to an LCD over serial. Once the application is running, the only way to kill it is with task manager. The trouble with this is that the program needs to turn the LCD off when it is done, and it doesn't look as if my Application.ApplicationExit event is ever fired in this condition.
Any ideas?
Once the application is running, the only way to kill it is with task manager.
My big idea would be to change this.
Stick an icon in the notification area that the user can use to shut your app down properly, or set it up so that running the app again will instead shut down an already-running instance if one exists, or any other way that sounds like a good idea.
Requiring a user to use Task Manager to shut down your application screams poor design.
Write a code in your program loop (with a timer perhaps) to read a file or a registry key. For example if a file at C:\YOURPROGRAM\CLOSEME contains text "closeme", close your program gracefully. Write another program that write that C:\YOURPROGRAM\CLOSEME file. So, whenever you want to shutdown your program, don't use taskmanager, instead, open second program.
Some options:
Write a separate process with a GUI that can start and stop the main process. For example, when you install the Apache web server on Windows the server itself is installed as a service. It can be started and stopped from the system services management panel, but it also comes with a "monitor" process that sits in the notification area, tells you whether Apache is running and lets you start or stop it manually.
If it's acceptable for your use-case, make the application a console application. You can register a handler for when the user presses CTRL+C (see Console.CancelKeyPress) that performs your cleanup before your process exits. This still won't let you handle someone killing the process from Task Manager, but it's very easy to do and might be good enough depending on your situation.
I have a windows form application which needs to be the TopMost. I've set my form to be the TopMost and my application works as I'd like it to except for in one case.
There is a 3rd party application (referred to as player.exe) that displays SWF movie files on a portion of the screen that popup on top of my application.
Using Process Monitor I determined that player.exe application calls
flash.exe <PositionX> <PositionY> <Width> <Height> <MovieFile>
in my case:
flash.exe 901 96 379 261 somemovie.swf
Since flash.exe is being spawned in a new process after my form has been set to the TopMost it is appearing on top of my application.
First thing I did was make my application minimize the player.exe main application window hoping that this would prevent the Flash from appearing also. But, unfortunately it doesn't... even with the window minimized whenever the flash movie starts it shows up at the pixel location (901,96). I then tried creating a timer to keep setting the form.TopMost property to true every 10ms. This sort of works but you still see a very quick blip of the swf file.
Is there some type of Windows API call which can be used to temporarily prevent player.exe from spawning child processes which are visible? I admit it sounds a little far fetched. But, curious if anyone else has had a similar problem.
Addendum:
This addendum is to provide a reply to some of the suggestions layed out in Mathew's post below.
For the emergency situation described in the comments, I would look at possible solutions along these lines:
1) How does the third party application normally get started and
stopped? Am I permitted to close it
the same way? If it is a service, the
Service Control Manager can stop it.
If it is a regular application,
sending an escape keystroke (with
SendInput() perhaps) or WM_CLOSE
message to its main window may work.
Easiest way to close the app is to CTRL-ALT-DEL, then kill process. -OR-
The proper way is to Hold ESC while clicking the left mouse button... then input your username and password, navigate some menu's to stop the player.
There is no PAUSE command... believe it or not.
I don't think using WM_CLOSE will help since minimizing the application doesn't. Would that kill the process also? If not, how do you reopen it.
2) If I can't close it nicely, am I permitted to kill it? If so,
TerminateProcess() should work.
I can't kill the process for two reasons. 1) Upon relaunch you need to supply username/password credentials... There may be a way to get around this since it doesn't prompt when the machine is rebooted but... 2) Whenever I kill the process in task manager it doesn't die gracefully and asks if you want to send an error report.
3) If I absolutely have to leave the other process running, I would try
to see if I can programmatically
invoke fast user switching to take me
to a different session (in which there
will be no competing topmost windows).
I don't know where in the API to start
with this one. (Peter Ruderman
suggests SwitchDesktop() for this
purpose in his answer.)
I got really excited by this idea... I found this article on CodeProject which provides a lot of the API Wrapper methods. I stopped implementing it because I think that in order for desktop's to work you must have explorer.exe running (which I do not).
EDIT2: On second thought... maybe explorer.exe isn't needed. I'll give it a try and report back.
Edit3: Was unable to get the code in that article working. Will have to put this on hold for a moment.
Answer Summary
As one might have expected, there is no simple answer to this problem. The best solution would be to problematically switch to a different desktop when you need to guarantee nothing will appear over it. I was unable to find a simple C# implementation of desktop switching that worked and I had a looming doubt that I would just be opening a whole new set of worms once it was implemented. Therefore, I decided not to implement the desktop switching. I did find a C++ Implementation that works well. Please post working C# virtual desktop implementations for others.
Setting the TopMost property (or adding the WS_EX_TOPMOST style to a window) does not make it unique in the system. Any number of topmost windows may be created by any number of applications; the only guarantee is that all topmost windows will be drawn 'above' all non-topmost windows. If there are two or more topmost windows, the Z-order still applies. From your description, I suspect that flash.exe is also creating a topmost window.
Aside from periodically forcing your window to the top of the Z-order, I think there is little you can do. Be warned, however, that this approach is dangerous: if two or more windows are simultaneously trying to force themselves to the top of the Z-order, the result will be a flickering mess that the user will likely have to use the task manager to escape.
I recommend that your program not attempt to meddle with other processes on the computer (unless that is its explicit purpose, e.g. a task manager clone). The computer belongs to the user, and he may not value your program more highly than all others.
Addendum:
For the emergency situation described in the comments, I would look at possible solutions along these lines:
How does the third party application normally get started and stopped? Am I permitted to close it the same way? If it is a service, the Service Control Manager can stop it. If it is a regular application, sending an escape keystroke (with SendInput() perhaps) or WM_CLOSE message to its main window may work.
If I can't close it nicely, am I permitted to kill it? If so, TerminateProcess() should work.
If I absolutely have to leave the other process running, I would try to see if I can programmatically invoke fast user switching to take me to a different session (in which there will be no competing topmost windows). I don't know where in the API to start with this one. (Peter Ruderman suggests SwitchDesktop() for this purpose in his answer.)
You can use the Process class to start flash.exe directly - and use an appropriate ProcessStartInfo settings to show the window in a hidden state - or with a WindowStyle of hidden or minimized.
You could also consider using the SetWindowsHookEx API to intercept the process start API calls, and when the process is flash.exe run some code to restore you window to top-most status.
Matthew's answer is excellent, but I suspect you may be asking the wrong question. Why does your application need to be topmost? If you're trying to create a kiosk or some such, then topmost is not the way to go.
Edit: After reading your response to Matthew's comment, I'd suggest creating a new desktop and switching to it before displaying your alert. (See CreateDesktop and SwitchDesktop in MSDN.)