Check if Windows Application is running (not process) - c#

I am hoping to check at the beginning of an automated test if an application is open. I can check if the process is running by doing the following
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.Contains(name))
{
return true;
}
}
However, the process I want to find starts up about a minute before the application actually opens and is ready to be used by the test methods (its a very slow starting application). The above code sample looks at all windows processes running, but I am wondering, is there a way to do a similar method but to look at windows applications running?

There is a method already in class Process that you can use to check if an app with a UI has fully started:
Process.WaitForInputIdle(int milliseconds)
This will wait up to milliseconds ms for the message loop to become idle (and returns a bool to indicate success status). Depending on the application you're waiting for, you might want to allow 30 seconds or longer.
This might work for you, but be aware that in my experience for some applications it is not totally reliable!
The Windows API documentation has more details about the Windows API function that WaitForInputIdle() calls behind the scenes.

When a process is started, you can say application has started.
What you want is to wait until application startup progress has completed or not.
This means, when process is started, application startup begins. When application startup is completed, is becomes ready for user input. So I think you should have a look at following question and its answers.
Programmatically, how does this application detect that a program is ready for input

Apllication is proces.
If you can modify app, at app start you can create file and at end delete it. So you can chceck file existance. If file exist app starting/started.
If you need info when main form is created use:
WINFORMS
Form.Shown event.
WPF Loaded Event

uITestControl.Exists did the trick for me.
This method will return a boolean value corresponding to the existence of the application window being open. This allows an if statement to be created that can open the application if not already open, or do nothing if its already open.

Related

Cannot wait for exit if app is a Microsoft app

I'm developing an aplication, that is opening a file with associated app for file extension(this part is provided by shellexecute), and wating for it to exit, and then continue to work on file. I know Process.Start(...) may return null e.g if there is an process of same up running, etc. I solved it by asking user to close all windows of default app before proceeding. I'm getting associated .exe path from FindExecutable(...) imported from shell32.dll and then calling in loop this and also checking if list lenght is 0.
var processList = new List<Process>(Process.GetProcessesByName(Path.GetFileNameWithoutExtension(defaultExecutablePath)));
And here I've met a wall I can't overcome. If default app is any kind of app from Microsoft(Edge, Photos, Movies) FindExecutable(...) returns empty string.
However Process.Start(...) somehow starts the right default app which for example is Microsoft Edge(for .pdf) but it returns null even if no instance of Microsoft Edge is running, so I can't wait for newly created process to exit. It all works nice with an exception in case if app is the one provided by Microsoft.
var newProcess = Process.Start(openPath);
if(newProcess == null)
{
throw new ProcessStartNullException();
}else
{
newProcess.WaitForExit();
}
Can I somehow exploit it or re-design awaiting for exit?
It's not because they are Microsoft apps, It because they are UWPs, and UWP is running in a container process called ApplicationFrameHost, so you need to figure out the real process under that ApplicationFrameHost then monitor it.
Also, many Win 10 UWP app's processes won't terminate immediately after users close their window so they can have a warm startup instead of cold startup for a better performance. It will first suspend the application and then later, if needed, terminate it.
So even you can find the real process, you can't always relay on it to determine if the UWP window is closed or not.

Is it possible to fire any event in c# application when the application is terminated from taskmanager's process?

I have a c# form application. when this form is closed from task-manager's process i have to do something in my Form application. is it possible?
I apologies if i mislead anything. but i need this solution.
No you can not. What you can do, in order to track this kind of situation, is on startup create some hidden file in directory where you guaranteed by the OS for write permit and on the close of your application, delete that file.
In this way, if on startup of your app, you will find hidden file, that will mean that application was closed non in normal way. So you can execute some actions accordingly.
Hope this helps.
The task manager will try to close your application gracefully first. You will get a normal close signal that you can act on. In a Forms Application that probably corresponds to the OnClose/Closing of the main window. If this signal is not used to end the application in time, the task manager will kill the process. You will not be able to intercept that or act upon it.
Based on what I know, Killing a process with Task Manager is immediate.
The application is not able to get informed in any way.
Task manager generally call the Windows API ExitProcess to kill the process.
On how to hook API, you can refer to:
http://www.codeproject.com/KB/system/hooksys.aspx
SOURCE
In alternatve, you could create an additional process which obsverve the main application and if he find that the application is closed then do something. If the main application is closed normally, then the process is killed from the main application. thiS could be an easy workaround.
"No you can't, what you can do though is do something just before the form is disposed. msdn.microsoft.com/en-us/library/…. What exactly are you trying to archieve? –"
UPDATE
Based on your response to my comment:
What if you do something else. Create a windows service (daemon) that checks when your form is open (windows name) and then monitors the form to check when it is closed, and when that happens it calls the web service you need.
Your windows service would be as simple as this:
Thread thread = new Thread(() =>
{
while (!formClosed)
{
if (!Process.GetProcesses().Any(x => x.MainWindow.Title.Contains(windowName)))
{
//form closed, call your web service
}
Thread.Sleep(5000);
}
});

How do i create a running windows process when a c# windows form loads?

I need to create running windows process (the one seen on task manager) when a Windows form loads because I need this application to be monitored by nagios (http://www.nagios.org/).
So when the form loads, an exe will run in the background process, and when form closes, the process will have to stop too.
Update
So when the form loads, the current ApplicationName.exe will display in the Task Manager Processes Tab, and when form closes, the ApplicationName.exe will have to stop too.
I also found out that when you Start Without Debugging, the ApplicationName.exe will display in the Processes Tab of the Task Manager but if you Start Debugging (F5), you wont see the ApplicationName.exe in the Processess Tab. Now i want to make sure that even if I will Start Debugging it, I can still see the ApplicationName.exe in the Processes Tab. How do i do that?
Clarification needed: is the additional process that is running the Nagios monitor, or something else you create?
Either way, you can use Process.Start() to kick off a separate application from within your own:
//event handler for the form's Load event
public void MyWindow_FormLoad(object sender, EventArgs e)
{
//kick off the process you want
Process.Start(#"C:\Program Files\MyOtherApp\MyOtherApp.exe");
}
There are overloads allowing you to specify arguments, or customize the startup behavior of the process. But this is the basic call and (given a real program location) should kick off the separate EXE as a new process with default startup behavior (as if you'd double-clicked it in Windows Explorer).
Now, if you need more, like a way to have the two programs talk to each other, then you'll need to expand your question with the appropriate details.
EDIT FROM COMMENT: Ah. OK, that's slightly different.
Normally, any EXE that is running at any given time will appear in the Task Manager's processes list by default, with no special coding necessary. It's in fact very hard to get a proces to NOT show up in that list, because a process that doesn't want to be seen is one of the hallmarks of a virus.
However, when you run an app in Debug mode from Visual Studio, the code is compiled and run from within VS's process boundaries, and doesn't show as its own process. To get it to show up as its own process in Task Manager, the compiled application must be run from outside VS. You can still debug it, by "attaching" VS's debugger to the running process after you have started it. But, this means that the app must be stable and long-running enough for you to manually attach to it. A program that has finished most or all of its execution by the time it reaches a "resting" state will need some modification in order to wait for you to attach to it before doing whatever it was you wanted to debug.
I have Test.exe ,a sample winform app. and used it as Process
public Process process = new Process();
protected override void OnLoad(EventArgs e)
{
process.StartInfo.Verb = "open";
process.StartInfo.FileName = "Test.exe"; //Give your App or Process Name
process.StartInfo.WorkingDirectory = #"C:\Users\sali\Documents\Visual Studio2010\Projects\Test\Test\bin\Debug"; //Give your App or Process path
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.Start();
}
I hope it helps
Or if you require something different, feel free to ask
If you just want a Windows form application you have written to show up in the list of processes when it runs then you will find it does anyway. You do not need to do anything special for it to run in its own process. For example I made a simple out-of-the-box Windows form application in VS2010
And then ran it (without debugging) and here it is in the process list of Task Manager.
(N.B. I'm running Win8, so your Task Manager may look a little different.)
If however you need to know when a Windows form application not written by you is started and stopped by the user you'll need to look at Windows hooks as mentioned in the answers to this question or at the process creation/modify/shutdown events in the Windows Management Instrumentation(WMI) API.

C# Process automation

I'm starting a external application with System.Diagnostics.Process, this external process at one moment opens up a dialog where user has type something and then click OK. What i need is to wait with my application(the one where i started the external process) until the user has inserted something and clicked OK. After that OK i have to do some more task on that external process and then close it.
Yes, it's possible. There are a number of ways to get window information starting with a process handle and/or ID. See this question and responses for getting started. You will most likely end up using P/Invoke to the Win32 API to get this accomplished but there are dozens of good examples for getting this done.
Once you have the window handle you can use a timer polling scheme to test for the presence, or in your case, presence and then the disappearance of a window.
This is possible but there are some work behind it. First you need to run your code as unmanaged code as you will need to hook on Windows OS events with the Win32 API.
So an option would be to have a loop looking for the dialog to open, pause what ever your code are doing and continue when the dialog are gone.
If the application you are starting exists after the user interacts with the dialog, then you can just call Process.WaitFroExit() and your code will not continue until the process you started has quit.
There are quite a few helpful functions for interacting with processes in the System.Diagnostics.Process class (that I assume you are using to start this external application)

C# windows application not closing

I have a C# windows application. I placed it on a test server, whose set up is not controlled by my company and neither is the seurity context. I double click the exe. App runs and i see my form. I close the application, i open task manager and i still see a foot print of the applicatiion.
taskkill does not seem to remove it and it is still running in task manager.
how do i check if any resource is still being held?
The likely cause is that a background thread is still running after your application is closed. Depending on your framework and application configuration a background thread can cause a process to keep running even after the main window is closed.
Do you have any threads in your process? If so make sure to close them out when the main application window is closing. A good place to do this is in the OnClosing method of a Windows Form
Abusing Application.DoEvents() is another way to get into this kind of trouble. If you cannot kill the .exe from TaskMgr, your app is stuck waiting for a driver to finish an I/O request.

Categories