Search code examples
c#outlookoffice-interopoffice-automation

Outlook New Mail Window opened from C# seems to have focus but my app still has it


I'm having a problem that I've been trying to solve for days now, but without luck!

On my Windows Forms Application I have a grid. One column contains an email address. When the user double clicks this column, I want to open a new E-Mail Window via Outlook automation. This window should have the focus and allow the user to type immediately.

Everything works fine, when:

  • I'm running my app from Visual Studio.
  • Or my app has the focus.

However, when I run my .exe and outlook has the focus when I double click the column, the following happens:

  • The new Mail window opens as expected
  • The cursor blinks in the new mail window (as expected)
  • when the user starts typing, the cursor still blinks in outlook but the typed text appears in the grid of my application, not in outlook.

I was able to reproduce the problem with a simple form that has a textbox on it.

I use the following code:

private void textBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
 OpenOutlookMail(textBox1.Text);
}

private void OpenOutlookMail(string to)
{
  MailItem item = OutlookApp.CreateItem(OlItemType.olMailItem) as MailItem;
  item.To = to;
  item.Subject = string.Empty;
  item.Body = string.Empty;

  item.Display();
}

protected Application OutlookApp
{
    get
    {
        if (mOutlookApp == null)
        {
            mOutlookApp = new Application();

        }
        return mOutlookApp;
     }
  }

What i already tried was to

  • Activate my current form via this.Activate() before the call to OpenOutlookMail
  • Activate the MailItem Inspector Object
  • Activate the ActiveWindow and ActiveExplorer of Outlook via Automation
  • Using AutoIt as explained here Similar Problem with MS Word on the MSDN Forum

Any help would be appreciated!


Solution

  • I wrote about focusing a background window some time ago:

    http://blog.sebastianbrand.com/2010/02/activate-form-in-background.html

    private void label1_Click(object sender, EventArgs e)
    {
      // mainform.BringToFront(); // doesn't work
      BeginInvoke(new VoidHandler(OtherFormToFront));
    }
    
    delegate void VoidHandler();
    
    private void OtherFormToFront()
    {
      mainform.BringToFront(); // works
    }
    

    If you do have an handle of the bad window, give that a try.