This answer explains how to get a Word.Application object from hwnd, which means that we can scroll through all the active Word processes and check that their Word.Application matches our own Word.Application object. Thus, you do not need to do anything with the window label.
Please note that you can only get the process of opening Word.Application and open one or more documents (in the latter case, the code opens a temporary empty document):
using System; using System.Linq; using System.Text; using Word = NetOffice.WordApi; using System.Runtime.InteropServices; using System.Reflection; using System.Diagnostics; namespace WordHwnd { class Program { static void Main(string[] args) { using (var app = new Word.Application() { Visible = true }) { Console.WriteLine(WordGetter.GetProcess(app).MainWindowHandle); } Console.ReadLine(); } } class WordGetter { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("00020400-0000-0000-C000-000000000046")] private interface IDispatch { } private const uint OBJID_NATIVEOM = 0xFFFFFFF0; private static Guid IID_IDispatch = new Guid("{00020400-0000-0000-C000-000000000046}"); [DllImport("Oleacc.dll")] private static extern int AccessibleObjectFromWindow(int hwnd, uint dwObjectID, byte[] riid, out IDispatch ptr); private delegate bool EnumChildCallback(int hwnd, ref int lParam); [DllImport("User32.dll")] private static extern bool EnumChildWindows(int hWndParent, EnumChildCallback lpEnumFunc, ref int lParam); [DllImport("User32.dll")] private static extern int GetClassName(int hWnd, StringBuilder lpClassName, int nMaxCount); private static bool Find_WwG(int hwndChild, ref int lParam) { if (GetClassName(hwndChild) == "_WwG") { lParam = hwndChild; return false; } return true; } private static string GetClassName(int hwndChild) { var buf = new StringBuilder(128); GetClassName(hwndChild, buf, 128); return buf.ToString(); } public static Process GetProcess(Word.Application app) { Word.Document tempDoc = null;
I use NetOffice in this example, but you can easily change it to work with standard interop libraries by editing the using statement and making Marshal.ReleaseComObject () instead of Word.Application.Dispose ().
source share