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 API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,512 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,623 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 83,101 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

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Andrea Nagar 1 Reputation point
    2022-09-15T19:56:02.487+00:00

    There's one thing that I noticed.
    It looks like the function is not returning the proper coordinates if I'm working on a HighDPI monitor.
    It seems that it's working differently based on the application. In particular, it's not reporting the proper position in Chrome, Word and Edge.

    Has anyone noticed that?

    Thank you.