Praetorian
Praetorian

Reputation: 109269

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?

Upvotes: 1

Views: 2117

Answers (4)

This works (you might have to change the path):

public static void StartOutlookIfNotRunning()
{
    string OutlookFilepath = @"C:\Program Files (x86)\Microsoft Office\Office12\OUTLOOK.EXE";
    if (Process.GetProcessesByName("OUTLOOK").Count() > 0) return;
    Process process = new Process();
    process.StartInfo = new ProcessStartInfo(OutlookFilepath);
    process.Start();
}

Upvotes: 2

Praetorian
Praetorian

Reputation: 109269

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" );

Upvotes: 6

Why not try spawning Outlook as a new process? I believe it is a single-entry application (I'm forgetting my proper terminology here), so that if it is already open, it will just bring that one to forefront.

Upvotes: 2

Daniel Walker
Daniel Walker

Reputation: 770

I've seen SetForegroundWindow fail on occasion. Try using the SetWindowPos function

Upvotes: 0

Related Questions