C# 取消选择 COM 对象 WordDocument
本文关键字:对象 WordDocument COM 选择 取消 | 更新日期: 2023-09-27 18:34:39
在Visual Studio中,我创建了一个Word 2016 Document项目。在本文档中,我添加了一个自定义操作窗格控件。此控件执行的唯一操作是将纯文本内容控件添加到活动文档。
if (Globals.ThisDocument.Content.Application.ActiveDocument == null) return;
var tagControl = Globals.ThisDocument.Controls.AddPlainTextContentControl(Guid.NewGuid().ToString());
tagControl.PlaceholderText = @"PLACEHOLDER";
tagControl.LockContents = true;
这一切都工作正常,在Word文档中添加和选择纯文本控件。但我想要的是添加控件,并且光标将跳到控件的末尾,以便用户可以直接开始键入。将自动选择新添加的控件。我该如何打开它?
我已经尝试过:
var range = Globals.ThisDocument.Content;
range.Application.Selection.Collapse();
谁能在这里帮我?谢谢。
编辑:阿尔斯尝试了这个解决方案。
private static IntPtr documentHandle;
public delegate bool EnumChildProc(IntPtr hwnd, int lParam);
[DllImport("user32.dll")]
public static extern System.IntPtr SetFocus(System.IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int EnumChildWindows(IntPtr hWndParent, EnumChildProc callback, int lParam);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder title, int count);
private static bool EnumChildWindow_Handle(IntPtr handle, int lparam)
{
StringBuilder s = new StringBuilder(50);
GetWindowText(handle, s, 50);
Debug.WriteLine(s.ToString());
if (s.ToString() == "Microsoft Word-document")
{
documentHandle = handle;
}
return true;
}
private void MoveCursorToEndOfLastAddedTag(PlainTextContentControl ctrl)
{
EnumChildProc EnumChildWindow = new EnumChildProc(EnumChildWindow_Handle);
EnumChildWindows(Process.GetCurrentProcess().MainWindowHandle, EnumChildWindow, 0);
SetFocus(documentHandle);
}
这也行不通。
我终于成功了。这不是最干净的方式,但它就像一个魅力。我制作的唯一代码是这样的:
private void MoveCursorToEndOfLastAddedTag(PlainTextContentControl ctrl)
{
System.Windows.Forms.SendKeys.Send("{F10}");
System.Windows.Forms.SendKeys.Send("{F10}");
System.Windows.Forms.SendKeys.Send("{RIGHT}");
}
它发送 F2 键的 10 倍。第一次将焦点设置为功能区时,第二次将焦点返回文档。使用正确的键,我从纯文本内容控件中删除选择。
谢谢大家的帮助。