getting text entered in textbox of other applications using c# - c#

I want to get the text which is in textbox of other application. It may be a textbox of gtalk client or a soap UI screen.
Based on my research most of the forums suggested winapi is the concept that I've to use to achieve this. I didn't get any good examples to implement this.

Here is an example of how to grab all the text from a window by it's window title.
Please see the comments for an explanation on how this works.
public class GetWindowTextExample
{
// Example usage.
public static void Main()
{
var allText = GetAllTextFromWindowByTitle("Untitled - Notepad");
Console.WriteLine(allText);
Console.ReadLine();
}
// Delegate we use to call methods when enumerating child windows.
private delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
private static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, [Out] StringBuilder lParam);
// Callback method used to collect a list of child windows we need to capture text from.
private static bool EnumChildWindowsCallback(IntPtr handle, IntPtr pointer)
{
// Creates a managed GCHandle object from the pointer representing a handle to the list created in GetChildWindows.
var gcHandle = GCHandle.FromIntPtr(pointer);
// Casts the handle back back to a List<IntPtr>
var list = gcHandle.Target as List<IntPtr>;
if (list == null)
{
throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
}
// Adds the handle to the list.
list.Add(handle);
return true;
}
// Returns an IEnumerable<IntPtr> containing the handles of all child windows of the parent window.
private static IEnumerable<IntPtr> GetChildWindows(IntPtr parent)
{
// Create list to store child window handles.
var result = new List<IntPtr>();
// Allocate list handle to pass to EnumChildWindows.
var listHandle = GCHandle.Alloc(result);
try
{
// Enumerates though all the child windows of the parent represented by IntPtr parent, executing EnumChildWindowsCallback for each.
EnumChildWindows(parent, EnumChildWindowsCallback, GCHandle.ToIntPtr(listHandle));
}
finally
{
// Free the list handle.
if (listHandle.IsAllocated)
listHandle.Free();
}
// Return the list of child window handles.
return result;
}
// Gets text text from a control by it's handle.
private static string GetText(IntPtr handle)
{
const uint WM_GETTEXTLENGTH = 0x000E;
const uint WM_GETTEXT = 0x000D;
// Gets the text length.
var length = (int)SendMessage(handle, WM_GETTEXTLENGTH, IntPtr.Zero, null);
// Init the string builder to hold the text.
var sb = new StringBuilder(length + 1);
// Writes the text from the handle into the StringBuilder
SendMessage(handle, WM_GETTEXT, (IntPtr)sb.Capacity, sb);
// Return the text as a string.
return sb.ToString();
}
// Wraps everything together. Will accept a window title and return all text in the window that matches that window title.
private static string GetAllTextFromWindowByTitle(string windowTitle)
{
var sb = new StringBuilder();
try
{
// Find the main window's handle by the title.
var windowHWnd = FindWindowByCaption(IntPtr.Zero, windowTitle);
// Loop though the child windows, and execute the EnumChildWindowsCallback method
var childWindows = GetChildWindows(windowHWnd);
// For each child handle, run GetText
foreach (var childWindowText in childWindows.Select(GetText))
{
// Append the text to the string builder.
sb.Append(childWindowText);
}
// Return the windows full text.
return sb.ToString();
}
catch (Exception e)
{
Console.Write(e.Message);
}
return string.Empty;
}
}

You are correct. You will need to use the Windows API. For example:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
But first, you'll probably need to use FindWindow or FindWindowEx(?) recursively from the desktop down to where the text box is in the window hieracrchy to get the right window handle.
It looks like http://www.pinvoke.net/ has a good database of Win API's.
Hope that helps.

One option would be to use TestStack.White, a UI automation framework. It's based on project white, and the original documentation is here.

Related

Control's parent handle points to WindowsFormsParkingWindow using p/invoke

Consider the following unit test for WinApi functionality:
public class WinApiTest
{
[TestMethod]
public void WinApiFindFormTest_SimpleNesting()
{
var form = new Form();
form.Text = #"My form";
var button = new Button();
button.Text = #"My button";
form.Controls.Add(button);
//with below line commented out, the test fails
form.Show();
IntPtr actualParent = WinApiTest.FindParent(button.Handle);
IntPtr expectedParent = form.Handle;
//below 2 lines were added for debugging purposes, they are not part of test
//and they don't affect test results
Debug.WriteLine("Actual: " + WinApi.GetWindowTitle(actualParent));
Debug.WriteLine("Expected: " + WinApi.GetWindowTitle(expectedParent));
Assert.AreEqual(actualParent, expectedParent);
}
//this is a method being tested
//please assume it's located in another class
//I'm not trying to test winapi
public static IntPtr FindParent(IntPtr child)
{
while (true)
{
IntPtr parent = WinApi.GetParent(child);
if (parent == IntPtr.Zero)
{
return child;
}
child = parent;
}
}
}
Problem is that to make it work, I have to show the form, i.e. do form.Show(), otherwise, it fails with this output:
Actual: WindowsFormsParkingWindow
Expected: My form
Exception thrown: 'Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException' in Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
I read about this mysterious WindowsFormsParkingWindow, and it seems to be relevant only if there was no parent specified. So all controls without a parent live under this window. In my case, however, button was clearly specified to be part of form's controls.
Question: Is there a proper way to make this test pass? I'm trying to test FindParent method. In true spirit of unit tests, nothing should suddenly pop up in front of the user. It's possible to do Show and Hide sequence, but I think it's a rather hack-ish approach to solve the problem.
Code for WinApi class is provided below - it does not add much value to the question, but if you absolutely must see it, here it goes (major portion comes from this answer on SO):
public class WinApi
{
/// <summary>
/// Get window title for a given IntPtr handle.
/// </summary>
/// <param name="handle">Input handle.</param>
/// <remarks>
/// Major portition of code for below class was used from here:
/// https://stackoverflow.com/questions/4604023/unable-to-read-another-applications-caption
/// </remarks>
public static string GetWindowTitle(IntPtr handle)
{
if (handle == IntPtr.Zero)
{
throw new ArgumentNullException(nameof(handle));
}
int length = WinApi.SendMessageGetTextLength(handle, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
if (length > 0 && length < int.MaxValue)
{
length++; // room for EOS terminator
StringBuilder windowTitle = new StringBuilder(length);
WinApi.SendMessageGetText(handle, WM_GETTEXT, (IntPtr)windowTitle.Capacity, windowTitle);
return windowTitle.ToString();
}
return String.Empty;
}
const int WM_GETTEXT = 0x000D;
const int WM_GETTEXTLENGTH = 0x000E;
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessageGetTextLength(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
[DllImport("User32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessageGetText(IntPtr hWnd, int msg, IntPtr wParam, [Out] StringBuilder lParam);
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr GetParent(IntPtr hWnd);
}
When you access the Handle property, the window needs to be created. Child windows need to have a parent window, and if the parent window has not yet been created, the child window is created with the parking window as its parent. Only when the parent window is created, does the child window get re-parented.
IntPtr actualParent = WinApiTest.FindParent(button.Handle);
IntPtr expectedParent = form.Handle;
When you access button.Handle, the button's window is created, but since the form's window is not yet created, the parking window is the parent. The simplest way for you to handle this is to ensure that the form's window is created before the buttons's window. Make sure that you refer to form.Handle, before you call GetParent on the button's handle, for example in your test you could reverse the order of assignment:
IntPtr expectedParent = form.Handle;
IntPtr actualParent = WinApiTest.FindParent(button.Handle);
Obviously you'd want to comment this code so that a future reader knew that the order of assignment was critical.
I do wonder however why you feel the need to make a test like this however. I cannot imagine this sort of testing revealing a bug in your code.

Prevent Revit window from opening

I'm trying to intercept Revit and keep a window from opening. Specifically, I'm trying to apply a keynote to an object and then let the user create a keynote tag, however any way I do it it lets them place the keynote but then immediately gives them the dialog to select a keynote, but I don't want that dialog to come up because I already know what the selection should be. However every way I can think of isn't able to interrupt the process to apply the keynote before the user gets the dialog. Is it possible to perhaps monitor for the window to appear then close it via Windows API? or even better intercept when it's going to be shown and stop it from showing?
you can always delete warrnings with:failuresAccessor.DeleteWarning(fma);
this is what i use for my code
public class FloorPreProcessor : IFailuresPreprocessor
{
FailureProcessingResult
IFailuresPreprocessor.PreprocessFailures(
FailuresAccessor failuresAccessor)
{
IList<FailureMessageAccessor> fmas
= failuresAccessor.GetFailureMessages();
if (fmas.Count == 0)
{
return FailureProcessingResult.Continue;
}
// We already know the transaction name.
if (fmas.Count != 0)
{
foreach (FailureMessageAccessor fma in fmas)
{
// DeleteWarning mimics clicking 'Ok' button.
failuresAccessor.DeleteWarning(fma);
}
return FailureProcessingResult
.ProceedWithCommit;
}
return FailureProcessingResult.Continue;
}
}
I hope it will help
Try the following, it searches for a window name, button name, then clicks this button:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
private const uint BM_CLICK = 0x00F5;
public static bool clickButton (string popUpTitle, string ButtonName)
{
// Get the handle of the window
IntPtr windowHandle = FindWindow((string)null, popUpTitle);
if (windowHandle.ToInt32() == 0)
{
return false;
}
// Get button handle
IntPtr buttonHandle = FindWindowEx(windowHandle, IntPtr.Zero, (string)null, ButtonName);
if (buttonHandle.ToInt32() == 0)
{
return false;
}
// Send click to the button
SendMessage(buttonHandle, BM_CLICK, 0, 0);
return true;
}
You should set the popUpTitle (window name) and the ButtonName to click.
Call this into a timer event that waits for a window to pop-up.
Timer timer = new Timer();
timer.Start();
timer.Tick += new EventHandler(timer_Tick);
//when done call timer.Stop();
private void timer_Tick(object sender, EventArgs e)
{
//set your code to clickButton("","")
}
Try it and let me know.
Ok well since there was a new comment I will make this an official answer. The best I came up with is that you can call OverrideResult() on the dialog even though you can't cancel it. It sill flashes the dialog which isn't ideal but it's better than it was... If anyone has a better way I'd love to hear it :)

C# SendKeys to foreground window in Windows 7 not working

I'm trying to build a global hotkey application with C# in Visual Studio 2012 to run on Windows 7. I have everything working except the SendKeys are never showing in the application.
Here is the code I am using to send the keystrokes:
Updated to debug with GetFocusedWindow example.
StringBuilder className = new StringBuilder(256);
IntPtr hWnd = GetForegroundWindow();
GetClassName(hWnd, className, className.Capacity);
Debug.WriteLine("Foreground window: {0}={1}", hWnd.ToInt32().ToString("X"), className);
hWnd = GetFocusedWindow();
GetClassName(hWnd, className, className.Capacity);
Debug.WriteLine("Focused window: {0}={1}", hWnd.ToInt32().ToString("X"), className);
SendKeys.Send("Hello World");
When I debug the program, focus Notepad, and hit the hotkey I get the following debug message and the keystrokes are never inserted into Notepad:
Foreground Window: 4F02B6=Notepad
Focused Window: 1B6026A=WindowsForms10.Window.8.app.0.bf7d44_r11_ad1
How can I send keystrokes to the current foreground window?
Foreground windows doesn't necessary mean focused window. A child window of the top-level foreground window may have the focus, while you're sending keys to its parent.
Retrieving the focused child window from another process is a bit tricky. Try the following implementation of GetFocusedWindow, use it instead of GetForegroundWindow (untested):
static IntPtr GetFocusedWindow()
{
uint currentThread = GetCurrentThreadId();
IntPtr activeWindow = GetForegroundWindow();
uint activeProcess;
uint activeThread = GetWindowThreadProcessId(activeWindow, out activeProcess);
if (currentThread != activeThread)
AttachThreadInput(currentThread, activeThread, true);
try
{
return GetFocus();
}
finally
{
if (currentThread != activeThread)
AttachThreadInput(currentThread, activeThread, false);
}
}
[DllImport("kernel32.dll")]
static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern IntPtr GetFocus();
[DllImport("user32.dll", SetLastError = true)]
static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
Updated to address the comment:
When I use this function it sets the focus to my application window.
It's hard to tell what's wrong on your side, the following works for me when the focus is inside Notepad:
private async void Form1_Load(object sender, EventArgs e)
{
var className = new StringBuilder(200);
while (true)
{
await Task.Delay(500);
IntPtr focused = GetFocusedWindow();
GetClassName(focused, className, className.Capacity);
var classNameStr = className.ToString();
this.Text = classNameStr;
if (classNameStr == "Edit")
SendKeys.Send("Hello!");
}
}

RadioButton click on another form

We have a legacy program with a GUI that we want to use under control of a C# program to compute some values. We can successfully enter values in the numerical input controls, press the compute button, and read the produced answers from text display boxes.
But we can't seem to control a pair of radio buttons .
Calling CheckRadioButton() returns a code of success, but the control does not change state.
Sending a message of BM_CLICK does not change the state.
Attempts at sending WM_LBUTTONDOWN and WM_LBUTTONUP events haven't changed the state.
Has anyone been successful at "remote control" of radio buttons?
Portions of code to illustrate what we are doing:
[DllImport("user32.dll", EntryPoint="SendMessage")]
public static extern int SendMessageStr(int hWnd, uint Msg, int wParam, string lParam);
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, uint Msg, long wParam, long lParam);
[DllImport("user32.dll", EntryPoint="FindWindow", SetLastError=true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
[DllImport("user32.dll", EntryPoint="CheckRadioButton")]
public static extern bool CheckRadioButton(IntPtr hwnd, int firstID, int lastID, int checkedID);
static IntPtr GetControlById(IntPtr parentHwnd, int controlId) {
IntPtr child = new IntPtr(0);
child = GetWindow(parentHwnd, GetWindow_Cmd.GW_CHILD);
while (GetWindowLong(child.ToInt32(), GWL_ID) != controlId) {
child = GetWindow(child, GetWindow_Cmd.GW_HWNDNEXT);
if (child == IntPtr.Zero) return IntPtr.Zero;
}
return child;
}
// find the handle of the parent window
IntPtr ParenthWnd = new IntPtr(0);
ParenthWnd = FindWindowByCaption(IntPtr.Zero, "Legacy Window Title");
// set "N" to 10
IntPtr hwndN = GetControlById(ParenthWnd, 17);
SendMessageStr(hwndN.ToInt32(), WM_SETTEXT, 0, "10");
// press "compute" button (seems to need to be pressed twice(?))
int hwndButton = GetControlById(ParenthWnd, 6).ToInt32();
SendMessage(hwndButton, BM_CLICK, 0, 0);
SendMessage(hwndButton, BM_CLICK, 0, 0);
// following code runs succesfully, but doesn't toggle the radio buttons
bool result = CheckRadioButton(ParenthWnd, 12, 13, 12);
Send the BM_SETCHECK message. Be sure to use a tool like Spy++ to see the messages.
in this case i used another message BM_SETSTATE
SendMessage((IntPtr)hWnd, Win32Api.BM_SETSTATE, (IntPtr)newState, IntPtr.Zero);

Sending Keyboard Macro Commands to Game Windows

I wanna do a macro program for a game. But there is a problem with sending keys to only game application (game window). I am using keybd_event API for sending keys to game window. But I only want to send keys to the game window, not to explorer or any opened window while my macro program is running. When I changed windows its still sending keys. I tried to use Interaction.App with Visual Basic.dll reference. But Interaction.App only Focus the game window.
I couldn't find anything about my problem. Can anyone help me? Thanx
i fixed my problem.
in this field ;
PostMessage(hWnd, WM_KEYDOWN, key, {have to give lParam of the key});
otherwise it does not work.And we can control of ChildWindow Class with Spy++ tool of Microsoft.
Thanks everyone for helping.
Are you retrieving the handle of the window all the time, or are you remembering it?
If you use the FindWindow() API, you can simply store the Handle and use the SendMessage API to send key/mouse events manually.
FindWindow API:
http://www.pinvoke.net/default.aspx/user32.FindWindowEx
SendMessage API:
http://www.pinvoke.net/default.aspx/user32/SendMessage.html
VB
Private Const WM_KEYDOWN As Integer = &H100
Private Const WM_KEYUP As Integer = &H101
C#
private static int WM_KEYDOWN = 0x100
private static int WM_KEYUP = 0x101
class SendKeySample
{
private static Int32 WM_KEYDOWN = 0x100;
private static Int32 WM_KEYUP = 0x101;
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, int Msg, System.Windows.Forms.Keys wParam, int lParam);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
public static IntPtr FindWindow(string windowName)
{
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.MainWindowHandle != IntPtr.Zero && p.MainWindowTitle.ToLower() == windowName.ToLower())
return p.MainWindowHandle;
}
return IntPtr.Zero;
}
public static IntPtr FindWindow(IntPtr parent, string childClassName)
{
return FindWindowEx(parent, IntPtr.Zero, childClassName, string.Empty);
}
public static void SendKey(IntPtr hWnd, System.Windows.Forms.Keys key)
{
PostMessage(hWnd, WM_KEYDOWN, key, 0);
}
}
Calling Code
var hWnd = SendKeySample.FindWindow("Untitled - Notepad");
var editBox = SendKeySample.FindWindow(hWnd, "edit");
SendKeySample.SendKey(editBox, Keys.A);
If you want to communicate with a game, you typically will have to deal with DirectInput, not the normal keyboard API's.

Categories