Get the text of the viewable area of a Word Document window

其实转的这几篇墙外香文章,这篇才是我正要找的,头几篇属于附带的记录下。

墙外香:http://aritrasaha.wordpress.com/2009/06/03/get-the-text-of-the-viewable-area-of-a-word-document-window/

The Office Addin which I had been working for the last few months, had a requirement to get the text the user is currently able to see (regardless of the cursor position or selected area – since, the user can scroll through the document without changing the insertion point or the selection).  VSTO did not cover this though, so I had to retort to the Windows Native methods.

The solution consisted of getting the current viewable Rectangle of the word document using the Windows API Method : GetWindowRect().  Then we constructed the Range object from the rectangle obtained using the RangefromPoint() method call of the active window. And finally, we can retrieve the text of the viewable area from the Range object constructed.

Code Snippet :

Native Methods

public partial class NativeMethods

    {

        [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "FindWindowExW")]

        public static extern System.IntPtrFindWindowExW([System.Runtime.InteropServices.InAttribute()] System.IntPtrhWndParent, [System.Runtime.InteropServices.InAttribute()] System.IntPtrhWndChildAfter, [System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]string lpszClass, [System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]string lpszWindow);

 

        [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "GetWindowRect")]

        [return: MarshalAs(UnmanagedType.Bool)]

        public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

}

Define a Structure for the Rectangle Object

public struct RECT

    {

        public int left;

        public int top;

        public int right;

        public int bottom;

    }

Fetch the text of the viewable area of the Word Document window

IntPtr h = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;

 

h = NativeMethods.FindWindowExW(h, new IntPtr(0), "_WwF", "");        
h = NativeMethods.FindWindowExW(h, new IntPtr(0), "_WwB",app.ActiveDocument.Name);

 

h = NativeMethods.FindWindowExW(h, New IntPtr(0), "_WwG", "Microsoft Word Document");       

 

RECT tagRect = new RECT();
NativeMethods.GetWindowRect(h, out tagRect);

WordInterop.Range r1 = (WordInterop.Range)app.ActiveWindow.RangeFromPoint(tagRect.left, tagRect.top); 

WordInterop.Range r2 = (WordInterop.Range)app.ActiveWindow.RangeFromPoint(tagRect.right, tagRect.bottom);

 

object objStart = r1.Start;

object objEnd = r2.Start;

WordInterop.Range r = app.ActiveDocument.Range(ref objStart, ref objEnd);

MessageBox.Show(r.Text);

posted @ 2012-03-26 20:51  BinSys  阅读(351)  评论(0编辑  收藏  举报