How to focus WPF windows application from App.xaml.cs
Question
I know this may not be good practice, but still it is something I would like to implement.
I have a WPF windows application that I only want to run one instance of. If the user tries to start the program again a messagebox will show telling that the program is already running. This check is performed in app.xaml.cs.
So far so good. Everything works as expected.
I would like to expand this functionality to give focus and bring the mainwindow of the program to the front of the users desktop, over other windows and applications. I have tried numerous approaches, but can not get it to work. This should also happen in app.xaml.cs where I test if the application is already running.
It is not possible to do this in WPF? I have tried pinvokes and other stuff, but nothing seems to work for me.
Best regards
Nicki
Solution 2
I found a solution.
Adding a reference to VisualBasic gives access to Interactive.AppActivate, which can activate any process given a processid, which I already had implemented.
This page gave me the solution AppActivate In C#
I check for running process in the following manner
Process currentProcess = Process.GetCurrentProcess();
var runningProcess = (from process in Process.GetProcesses()
where
process.Id != currentProcess.Id &&
process.ProcessName.Equals(
currentProcess.ProcessName,
StringComparison.Ordinal)
select process).FirstOrDefault();
if (runningProcess != null)
{
Microsoft.VisualBasic.Interaction.AppActivate(runningProcess.Id);
return;
}
OTHER TIPS
Have you tried activating it?
Application.Current.MainWindow.Activate();
Of course if you like it to stay on top at all times than:
Application.Current.MainWindow.Topmost = true;