-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuiProxy.cs
More file actions
279 lines (213 loc) · 8.32 KB
/
GuiProxy.cs
File metadata and controls
279 lines (213 loc) · 8.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace lbsa71.GuiProxy
{
internal static class WinFormExtensions
{
/// <summary>
/// Helper extension method to make calling lambdas on UI thread and wait for completion simpler.
/// </summary>
/// <param name="control">What control should govern the invoke</param>
/// <param name="action">What to do</param>
public static Task Invoke(this Control control, Action action)
{
TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
Action innerAction = () =>
{
action();
taskCompletionSource.SetResult(true);
};
control.Invoke(innerAction);
return taskCompletionSource.Task;
}
}
public class GuiProxy
{
public delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
private const uint BM_CLICK = 0x00F5;
private const uint WM_SETTEXT = 0x000C;
private const uint WM_GETTEXT = 0xD;
private const uint WM_GETTEXTLENGTH = 0xE;
private static readonly string processName = "DummyApp";
private Form marshallingForm;
private IntPtr targetApplicationWindowHandle;
private List<IntPtr> children;
private IEnumerable<string> childClassnames;
private IEnumerable<string> childTexts;
private void SetText(int index, string str)
{
WithControl(index, () =>
{
var control = children[index];
SendMessage(control, WM_SETTEXT, IntPtr.Zero, str);
});
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern bool SendMessage(IntPtr hWnd, uint msg, int wParam, StringBuilder lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, uint msg,
IntPtr wParam, string lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr processId);
[DllImport("user32.dll")]
private static extern IntPtr AttachThreadInput(IntPtr idAttach,
IntPtr idAttachTo, bool fAttach);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
private static bool EnumWindow(IntPtr handle, IntPtr pointer)
{
var gch = GCHandle.FromIntPtr(pointer);
var list = gch.Target as List<IntPtr>;
if (list == null)
{
throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
}
list.Add(handle);
// You can modify this to check to see if you want to cancel the operation, then return a null here
return true;
}
public static List<IntPtr> GetChildWindows(IntPtr parent)
{
var result = new List<IntPtr>();
var listHandle = GCHandle.Alloc(result);
try
{
var childProc = new EnumWindowsProc(EnumWindow);
EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
}
finally
{
if (listHandle.IsAllocated)
{
listHandle.Free();
}
}
return result;
}
private string GetText(int index)
{
return GetText(children[index]);
}
private string GetText(IntPtr control)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(255); // or length from call with GETTEXTLENGTH
marshallingForm.Invoke(() =>
{
var result = SendMessage(
control,
WM_GETTEXT,
sb.Capacity,
sb);
}).Wait();
return sb.ToString();
}
private void WithControl(int index, Action action)
{
var control = children[index];
marshallingForm.Invoke(() =>
{
SetForegroundWindow(targetApplicationWindowHandle);
var activeWindowThread = GetWindowThreadProcessId(targetApplicationWindowHandle, IntPtr.Zero);
var thisWindowThread = GetWindowThreadProcessId(marshallingForm.Handle, IntPtr.Zero);
AttachThreadInput(activeWindowThread, thisWindowThread, true);
SetFocus(control);
AttachThreadInput(activeWindowThread, thisWindowThread, false);
action();
}).Wait();
}
private void PressButton(int i)
{
var buttonToClick = children[i];
SendMessage(buttonToClick, BM_CLICK, (IntPtr)0, (IntPtr)0);
}
private static void InvokeSendKeys(string str)
{
SendKeys.SendWait(str);
}
public bool Start()
{
KillAllTargetProcesses();
var process = Process.Start(processName + ".exe");
SleepUntil(TimeSpan.FromSeconds(5), () =>
{
targetApplicationWindowHandle = process.MainWindowHandle;
return targetApplicationWindowHandle != (IntPtr) 0;
});
TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
Task.Run(() =>
{
marshallingForm = new Form();
marshallingForm.Show();
taskCompletionSource.SetResult(true);
Application.Run(marshallingForm);
});
taskCompletionSource.Task.Wait();
marshallingForm.Invoke(() =>
{
children = GetChildWindows(targetApplicationWindowHandle);
childClassnames = children.Select(l =>
{
var sb = new StringBuilder(256);
GetClassName(l, sb, 256);
return sb.ToString();
});
childTexts = children.Select(GetText);
}).Wait();
return true;
}
private bool SleepUntil(TimeSpan timeout, Func<bool> func)
{
var cancelBy = DateTime.Now + timeout;
do
{
var completed = func();
if (completed)
{
return true;
}
else
{
Thread.Sleep(100);
}
} while (DateTime.Now < cancelBy);
return false;
}
public override bool OnStop()
{
KillAllTargetProcesses();
marshallingForm.Invoke(() => { marshallingForm.Hide(); });
marshallingForm = null;
return true;
}
private static void KillAllTargetProcesses()
{
var processes = Process.GetProcessesByName(processName);
if (processes.Any())
{
foreach (var process in processes)
{
process.Kill();
}
}
}
}
}