Lately I needed to communicate with Microsoft Word from C#. Well most programmers would use a reference to the COM library which is provided by Microsoft. For some reasons I don't want to use these libraries. One reason is the version problem. Let's say I'm linking the COM library which was implemented for MS Word 2007 and use it's interfaces etc. I won't be able to run this program on a machine having MS Word 2003 or MS Word 2010 installed.
To keep the whole story short, I'd like to show you a way how you can communicate with Microsoft Office without linking the COM libraries. The following sample shows how to search for a specific string in a Word document.
Because I don't want to break the explanation of how the code works, I'll just post all DllImports, interface and class declarations here.
static readonly Guid IID_IDispatch=new Guid("{00020400-0000-0000-C000-000000000046}");
[Guid("00020962-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IWordWindow
{
}
[DllImport("oleacc.dll")]
public static extern int AccessibleObjectFromWindow(IntPtr hwnd, uint dwObjectID, byte[] riid, out IWordWindow ptr);
[DllImport("user32.dll")]
public static extern int BringWindowToTop(IntPtr hwnd);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
[DllImport("user32.dll")]
public static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
public delegate bool EnumChildCallback(IntPtr hwnd, ref IntPtr lParam);
[DllImport("user32.dll")]
public static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildCallback lpEnumFunc, ref IntPtr lParam);
The interface IWordWindow is the IDispatch COM interface for the Word COM object. If you want to use another Office Program, you'll have to adapt the Guid attribute (see
MSDN).
First of all we need the process of Word