If you need the parent window in a Word Add-In, you can't use FindWindow as the actual Word caption is not the title you set. It adds " - Microsoft Word" to it. If it is used in Outlook, it doesn't add anything. And if it's a non-English version of Word, it's something else.
So here is code that will find it. This is written in C# which added a couple of other wrinkles like passing a pointer to an int as the lParam:
private const string CAPTION = "F076B0EA-FEE3-40E0-A576-4E68D13F57CA";
/// <summary>
/// Return the HWND of the parent app.
/// </summary>
/// <returns>The window handle.</returns>
public static IWin32Window GetParentWindow(Application app)
{
string saveCaption = app.Caption;
app.Caption = CAPTION;
CallBack myCallBack = new CallBack(Report);
IntPtr hwnd = (IntPtr)0;
EnumWindows(myCallBack, ref hwnd);
if (hwnd != (IntPtr)0)
{
app.Caption = saveCaption;
return new HWnd(hwnd);
}
hwnd = (IntPtr) FindWindow("OpusApp", CAPTION);
app.Caption = saveCaption;
return new HWnd(hwnd);
}
private static bool Report(int hwnd, ref IntPtr lParam)
{
string lpText = new string((char) 0, 100);
GetWindowText(new IntPtr(hwnd), lpText, lpText.Length);
if (lpText.IndexOf(CAPTION) == -1)
return true;
// walk up the chain (never seen it actually happen)
int par = hwnd;
while (par != 0)
{
hwnd = par;
par = GetParent(par);
}
lParam = (IntPtr)hwnd;
return false;
}
private class HWnd : IWin32Window
{
private IntPtr _hwnd;
public HWnd(IntPtr handle)
{
_hwnd = handle;
}
public IntPtr Handle
{
get { return _hwnd; }
}
}



Comments