Andre Kraemer
Andre Kraemer

Reputation: 2761

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:

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

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

Any help would be appreciated!

Upvotes: 3

Views: 2043

Answers (3)

Sebastian Brand
Sebastian Brand

Reputation: 547

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.

Upvotes: 3

Guish
Guish

Reputation: 5160

I haven't been able to reproduce the problem with your code. I've used Microsoft.Office.Interop.Outlook version 14.0.0.0 and in every tests i've done the mail window get the focus.

As you state,

Everything works fine, when: •I'm running my app from Visual Studio. •Or my app has the focus.

Maybe trying to focus your form and/or making your application sleep before opening the mail window would work

private void textBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    this.Focus();
    System.Threading.Thread.Sleep(500);
    OpenOutlookMail(textBox1.Text);
}

Interops often have weird behaviors. :s

Upvotes: 1

Woodman
Woodman

Reputation: 1137

You can try to use Dispatcher.BeginInvoke(...) with some low priority in your textBox1_MouseDoubleClick(...) method to call OpenOutlookMail(). It often helps to workaround focus management issues like this one.

Upvotes: 3

Related Questions