我正在尝试从活动文档 MS word 的当前可见屏幕(页面)中获取文本和范围。
我尝试了下面的代码,该代码适用于新文档。
IntPtr h = Process.GetCurrentProcess().MainWindowHandle;
h = NativeMethodsActiveScreen.FindWindowExW(h, new IntPtr(0), "_WwF", "");
h = NativeMethodsActiveScreen.FindWindowExW(h, new IntPtr(0), "_WwB", null);
h = NativeMethodsActiveScreen.FindWindowExW(h, new IntPtr(0), "_WwG", null);
NativeMethodsActiveScreen.tagRECT t = new NativeMethodsActiveScreen.tagRECT();
NativeMethodsActiveScreen.GetWindowRect(h, out t);
Range r1 = Globals.ThisAddIn.Application.ActiveWindow.RangeFromPoint(t.left, t.top);
Range r2 = Globals.ThisAddIn.Application.ActiveWindow.RangeFromPoint(t.right, t.bottom);
Range r = Globals.ThisAddIn.Application.ActiveDocument.Range(r1.Start, r2.Start);
//here r1 and r2 return wrong value in open document case as describe bellow
这是我使用过的本地 mwthod
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct tagRECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "FindWindowExW")]
public static extern System.IntPtr
FindWindowExW([System.Runtime.InteropServices.InAttribute()]
System.IntPtr hWndParent, [System.Runtime.InteropServices.InAttribute()]
System.IntPtr hWndChildAfter, [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")]
public static extern System.IntPtr GetWindowRect([System.Runtime.InteropServices.InAttribute()]
System.IntPtr hWndParent, out tagRECT lpRect);
当我打开保存的文档并尝试获取可见区域文本时出现问题。那时 每次都ActiveWindow.RangeFromPoint(x,y)
返回 for r1
:range 0,0)
和 for r2
: range 1,1)
(如上所列)。
谁能帮我解决这个问题?