Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write a windows application that gets a notification when text is selected in another windows application?

I'm curious if it is possible to write a program that monitors my text selection. One possible use would be to write an editor/IDE agnostic code formatter:

  1. Application/Service, P, is launched and somehow hooks into windows such that it gets notified when text is selected in any window.
  2. Some other application, A, is launched.
  3. User selects text in A.
  4. P is notified with the text that is selected.

--> I'd be happy to get this far...

like image 689
Aaron Anodide Avatar asked Dec 16 '22 03:12

Aaron Anodide


2 Answers

This is not possible without specific knowledge of each control/application that will be in use as they can all handle/treat it differently.

like image 70
Deanna Avatar answered May 03 '23 01:05

Deanna


I don't think you can register any sort of hook. I think you'll need to constantly poll the "focused" or selected window.

You can probably use the Windows Automation API to do this, which is as far as I am aware superceeded the older Accesibility API: http://msdn.microsoft.com/en-us/library/ms747327.aspx

I have used this API to automate GUI tests. I am a bit rusty with it so I don't know for sure, but I am reasonably confident you could use it for what you are trying to do. Basically the API allows you to traverse the tree of automation objects with the root at the desktop. Each automation element tends to be a windows control of some kind and different controls implement different patterns. You can also get at elements beneath the mouse cursor and possibly you can get straight to the currently selected/focused element.

After that I notice the TextPattern class for example has a GetSelection() method which is documented as "Retrieves a collection of disjoint text ranges associated with the current text selection or selections.". I bet the automation object for textboxes implement the TextPattern. http://msdn.microsoft.com/en-us/library/system.windows.automation.textpattern.aspx

like image 29
anbob Avatar answered May 03 '23 03:05

anbob