Search code examples
outlookvstooutlook-addinoffice-addinscustomtaskpane

VSTO Outlook: Getting Screen.FromControl(this).Bounds makes message preview not be displayed in the explorer


I have a custom task pane (ctp) at the top of my VSTO Outlook Add-in. I create it as below:

this.myHostControl = new myHostControl();
this.myCtp = Globals.ThisAddIn.CustomTaskPanes.Add(myHostControl, "My Toolbar");
this.myCtp .DockPosition = Microsoft.Office.Core.MsoCTPDockPosition.msoCTPDockPositionTop;
this.myCtp .DockPositionRestrict = Microsoft.Office.Core.MsoCTPDockPositionRestrict.msoCTPDockPositionRestrictNoChange;
this.myCtp.Height = DEFAULT_CTP_HEIGHT;
this.myCtp.Visible = true;

I am embedding a WPF User Control in the ctp.

The winforms user control, myHostControl, is like below (only showing relevant parts to understand my issue):

public partial class myHostControl: System.Windows.Forms.UserControl
{
    private Rectangle? myScreenBounds = null;

    public myHostControl()
    {
        InitializeComponent();

        // Gets the current screen bounds for the current screen.
        MyScreenBounds = System.Windows.Froms.Screen.FromControl(this).Bounds;
    }

    public myHostControl(int param1, int param2):this()
    {
        this.ElementHostCtl.Parent = this;

        // Gets the WPF view
        this.WpfView = new WpfView();

        // Sets wpf view as child of elementhost
        this.ElementHostCtl.Child = this.WpfView;

        // Sets the datacontext
        this.WpfView.DataContext = new WpfViewModel();
    }

    private Rectangle? MyScreenBounds 
    {
        get => myScreenBounds;

        set
        {
            if (myScreenBounds!= value)
            {
                myScreenBounds= value;
            }
        }
    }

   // More stuff
}


public partial class WpfView : System.Windows.Controls.UserControl
{
    public WpfView ()
    {
        InitializeComponent();
    }

    // more stuff
}

I have noticed that line below in the constructor:

MyScreenBounds = System.Windows.Froms.Screen.FromControl(this).Bounds;

makes that when I select a message from the message list in the explorer window, it does not load its content (message body) in the preview area, instead it is shown as an empty white area.

If I remove that line from the constructor, then it works, i mean, when i select a message from the messages list in the explorer its content is correctly displayed in the preview area.

Why Screen.FromControl(this).Bounds is causing the content of the messages not being shown in the preview area? If I double click on a message, the inspector window opens and then i can see the message body.


Solution

  • Make sure you call that code after your CTP is already visible and is correctly parented - otherwise its window handle can get created prematurely.