How to get caret position in ANY application from C#?

Andrey Nasonov 21 Reputation points
2022-04-20T03:49:25.773+00:00

Like Clipboard in Windows 10/11 (Win + V) - it always know current caret position on the page in Google Chrome or MS Edge, also in other applications - WPF, WinForms, UWP, etc.

I'm trying to get caret position in windows. Even if it's not native.

Tried to use Win32 API GetCaretPos function (https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getcaretpos), and it's worked, but only for WPF/WinForms processes. In case if application has own caret implementation (like Google Chrome browser) that function doesn't work.

var hFore = GetForegroundWindow();
var idAttach = GetWindowThreadProcessId(hFore, out uint id);
var curThreadId = GetCurrentThreadId();

// To attach to current thread
var sa = AttachThreadInput(idAttach, curThreadId, true);

var caretPos = WindowsKeyboard.GetCaretPos(out POINT caretPoint);

ClientToScreen(hFore, ref caretPoint);

// To dettach from current thread
var sd = AttachThreadInput(idAttach, curThreadId, false);

var data = string.Format("X={0}, Y={1}", caretPoint.X, caretPoint.Y);

But caretPoint correct only for WPF/Win32/WinForms apps. Also, I noticed that solution https://www.codeproject.com/Articles/34520/Getting-Caret-Position-Inside-Any-Application doesn't work for some Windows Desktop apps like Google Chrome or VS Code, Slack, etc.

I expect to get cursor position to determine where to show popup window like it made by Microsoft with Clipboard History (Win + V) on Windows 10 or Windows 11.

Windows development | Windows API - Win32
Developer technologies | C#
{count} votes

Accepted answer
  1. Castorix31 90,686 Reputation points
    2022-04-20T11:30:27.31+00:00

    I did a quick test with MS Edge (Search TextBox on this page) on Windows 10 21H1 and it worked with
    GetForegroundWindow + GetGUIThreadInfo to get hwndFocus, then AccessibleObjectFromWindow with OBJID_CARET, then IAccessible.accLocation

    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Denis Valjean 0 Reputation points
    2025-05-06T13:41:52.85+00:00

    Trying here, but cant make it work on google docs, vscode and other editor.. the ideal method would be how the topic author described: Like Clipboard in Windows 10/11 (Win + V) - it always know current caret position on the page in Google Chrome or MS Edge, also in other applications - WPF, WinForms, UWP, etc.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.