C# AppActivate

I wanted to be able to activate an application using C#.

By using the following it will activate the application:

[DllImportAttribute("User32.dll")]
private static extern int SetForegroundWindow(int hWnd);
 
private bool AppActivate(string titleName) {
  var success = true;
  var process = Process.GetProcesses()
                .Where(p => p.MainWindowTitle.StartsWith(titleName))
                .FirstOrDefault();
  if (process != null) {
    SetForegroundWindow(process.MainWindowHandle.ToInt32());
  }
  else {
    success = false;
  }
  return success;
}

First parts setups method for call to User32.dll so SetForegroundWindow can be called from it.

Next is a method that is called to first get the process that starts with the title name passed to it and if found then calls SetForegroundWindow.

To call the Calculator app call AppActivate method as following:

var success = AppActivate("Calc");

Comments are closed.