Cómo leer el texto resaltado/seleccionado de cualquier ventana usando C#.Capturar texto resaltado de cualquier ventana con C#
intenté 2 enfoques.
- Enviar "^ c" cuando el usuario seleccione algo. Pero en este caso mi portapapeles está inundado con muchos datos innecesarios. En algún momento copió las contraseñas también.
así que cambie mi enfoque al segundo método, envíe el método del mensaje.
ver este código de ejemplo
[DllImport("user32.dll")]
static extern int GetFocus();
[DllImport("user32.dll")]
static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
[DllImport("kernel32.dll")]
static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);
[DllImport("user32.dll") ]
static extern int GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern int SendMessage(int hWnd, int Msg, int wParam, StringBuilder lParam);
// second overload of SendMessage
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hWnd, uint Msg, out int wParam, out int lParam);
const int WM_SETTEXT = 12;
const int WM_GETTEXT = 13;
private string PerformCopy()
{
try
{
//Wait 5 seconds to give us a chance to give focus to some edit window,
//notepad for example
System.Threading.Thread.Sleep(5000);
StringBuilder builder = new StringBuilder(500);
int foregroundWindowHandle = GetForegroundWindow();
uint remoteThreadId = GetWindowThreadProcessId(foregroundWindowHandle, 0);
uint currentThreadId = GetCurrentThreadId();
//AttachTrheadInput is needed so we can get the handle of a focused window in another app
AttachThreadInput(remoteThreadId, currentThreadId, true);
//Get the handle of a focused window
int focused = GetFocus();
//Now detach since we got the focused handle
AttachThreadInput(remoteThreadId, currentThreadId, false);
//Get the text from the active window into the stringbuilder
SendMessage(focused, WM_GETTEXT, builder.Capacity, builder);
return builder.ToString();
}
catch (System.Exception oException)
{
throw oException;
}
}
este código funciona bien en el Bloc de notas. Pero si intento capturar desde otras aplicaciones como Mozilla firefox o Visual Studio IDE, no devuelve el texto.
¿Alguien puede ayudarme, donde estoy haciendo mal? En primer lugar, he elegido el enfoque correcto?
Firefox no implementa la automatización de la interfaz de usuario, probé la versión 3.0 y no funcionó, espero que sea compatible en el futuro. –
¿Podemos hacer algo para mejorar mi primer enfoque? Eso está funcionando muy bien, excepto copias innecesarias ........ – Dinesh