Search code examples
c#visual-studio-2015vstoselectionoffice-interop

C# Deselect COMobject WordDocument


In Visual Studio I've created a Word 2016 Document project. To this document I've added a custom ActionsPane control. The only thing this control does is adding a PlainTextContentControl to the active document.

if (Globals.ThisDocument.Content.Application.ActiveDocument == null) return;
        var tagControl = Globals.ThisDocument.Controls.AddPlainTextContentControl(Guid.NewGuid().ToString());
tagControl.PlaceholderText = @"PLACEHOLDER";
tagControl.LockContents = true;

This all works fine, the plaintextcontrol is added and selected in the Word document. But what I want is that the control is added and that the cursor will jump to the end of the control so a user can directly start typing. The newly added control is automatically selected. How can I turn this of?

I have already tried:

var range = Globals.ThisDocument.Content;
range.Application.Selection.Collapse();

Can anyone help me out here? Thanks.

Edit: Als tried this solution.

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);
}

This also doesn't work.


Solution

  • Finally I have success. It's not the most clean way, but it works like a charm. The only code I made is this:

    private void MoveCursorToEndOfLastAddedTag(PlainTextContentControl ctrl)
    {
        System.Windows.Forms.SendKeys.Send("{F10}");
        System.Windows.Forms.SendKeys.Send("{F10}");
        System.Windows.Forms.SendKeys.Send("{RIGHT}");
    }
    

    It sends 2 times the F10 key. First time the focus is set to the ribbon, the second time the focus is given back to the document. With the right key I remove the selection from the PlainTextContentControl.

    Thank you all for your help.