Search code examples
c#.net-3.5outlookoutlook-2010

Programmatically activate Outlook


I have an application which needs to activate Outlook (if it is running) when the user clicks on a button. I have tried the following but it isn't working.

Declared in the window class:

[DllImport( "user32.dll" )]
private static extern bool SetForegroundWindow( IntPtr hWnd );
[DllImport( "user32.dll" )]
private static extern bool ShowWindowAsync( IntPtr hWnd, int nCmdShow );
[DllImport( "user32.dll" )]
private static extern bool IsIconic( IntPtr hWnd );

Within the button Click handler:

// Check if Outlook is running
var procs = Process.GetProcessesByName( "OUTLOOK" );

if( procs.Length > 0 ) {
  // IntPtr hWnd = procs[0].MainWindowHandle; // Always returns zero
  IntPtr hWnd = procs[0].Handle;

  if( hWnd != IntPtr.Zero ) {
    if( IsIconic( hWnd ) ) {
      ShowWindowAsync( hWnd, SW_RESTORE );

    }
    SetForegroundWindow( hWnd );

  }
}

This doesn't work irrespective of whether Outlook is currently minimized to taskbar or minimized to system tray or maximized. How do I activate the Outlook window?


Solution

  • I figured out a solution; instead of using any WINAPI calls I simply used Process.Start(). I'd tried this earlier too but it caused the existing Outlook window to resize, which was annoying. The secret is to pass the /recycle argument to Outlook, this instructs it to reuse the existing window. The call looks like this:

    Process.Start( "OUTLOOK.exe", "/recycle" );