Perform click event on another application using C#

We will need the following methods:
SendMessage, FindWindowEx,
GetWindowTextLength, GetWindowText,


[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);


[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);


[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern int GetWindowTextLength(IntPtr hWnd);


[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);


[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);

The rest of the code:

//We are going to find Window and Control by their names.
private delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam);
private const int BM_CLICK = 0x00F5;
public List<IntPtr> GetAllChildrenHandles(IntPtr handle)
	List<IntPtr> _childrenHandlesList = new List<IntPtr>();
	GCHandle _gcchildrenHandlesList = GCHandle.Alloc(_childrenHandlesList);
	IntPtr _pchildrenHandlesList = GCHandle.ToIntPtr(_gcchildrenHandlesList);
		EnumWindowProc _childProc = new EnumWindowProc(EnumWindow);
		EnumChildWindows(handle, _childProc, _pchildrenHandlesList);
	return _childrenHandlesList;
private bool EnumWindow(IntPtr hWnd, IntPtr lParam)
	GCHandle _childrenHandles = GCHandle.FromIntPtr(lParam);
	if (_childrenHandles == null || _childrenHandles.Target == null)
		return false;
	List<IntPtr> _childrenHandlesList = _childrenHandles.Target as List<IntPtr>;
	return true;
//inside a method put the following code
//replace window_title and control_name with your strings
//you can perform click events for more than one controls 
//by placing more strings in the String List
IntPtr hWnd = IntPtr.Zero;
foreach (Process pp in Process.GetProcesses())
    if (pp.MainWindowTitle.Contains(window_title))
	List<IntPtr> l = GetAllChildrenHandles(pp.MainWindowHandle);
	foreach (IntPtr hndl in l)
            StringBuilder stringBuilder = new StringBuilder(GetWindowTextLength(new HandleRef(this, hndl)) * 2);
            GetWindowText(new HandleRef(this, hndl), stringBuilder, stringBuilder.Capacity);
            if ((Array.IndexOf(new List<String> { "control_name" }.ToArray(), stringBuilder.ToString()) >= 0))
                SendMessage(hndl, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
%d bloggers like this: