Tuesday, November 22, 2005

Hidden MessageBox and VSTO

When trying to display a Message box from VSTO code, the message box is some times hidden in the background. MessageBox's Show method takes a "owner" parameter of type IWin32Window, this makes the Message box to be displayed in front of the IWin32Window passed. Below is a code snippet from gotdotnet site to get the IWin32Window of the foreground window.


// Stephen Toub
// stoub@microsoft.com
//
// ActiveWindow.cs v1.0.0
// 8/28/02
//
// Implements IWin32Window where Handle returns the handle of the system's foreground window.
// Can be used with MessageBox to display the box in front of the active window, such as:
// MessageBox.Show(ActiveWindow.Active, "Hello, World!");
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Toub.Windows.Forms
{
/// Used to get an IWin32Window for the active window.
public class ActiveWindow : IWin32Window
{
#region Private Members
/// Static instance to use for factory pattern.
private static ActiveWindow _window = new ActiveWindow();
#endregion
#region Construction
/// Prevent external instantiation.
private ActiveWindow() {}
#endregion
#region Public Properties
/// Gets an IWin32Window for the active window.
public static IWin32Window Active { get { return _window; } }
#endregion
#region Private Functions
/// Finds the frontmost window using the Win32 API.
[DllImport("user32.dll")]
private static extern int GetForegroundWindow();
/// Gets a handle to the active window.
System.IntPtr IWin32Window.Handle
{
get { return new System.IntPtr(GetForegroundWindow()); }
}
#endregion
}
}

No comments: