开发者

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 ) {
开发者_JS百科  // 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?


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


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.


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();
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜