【发布时间】:2019-11-19 09:02:10
【问题描述】:
我正在尝试从活动文档 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) 每次都会返回r1:range 0,0) 和r2:range 1,1)(如上所述)。
谁能帮我解决这个问题?
【问题讨论】:
标签: c# ms-word word-addins word-interop