UIAutomation FlaUI - Detect Both Closing and Opening Windows at the Application Level - wpf

I have successfully used the solution for detecting opening windows described here: UIAutomation FlaUI - Detect opening windows on application level.
However, I would also like to also detect closing window events in addition to opening window events.
I duplicated the code in order to detect the second event:
AutomationElement root = automation.GetDesktop();
UIA3AutomationEventHandler automationOpenEventHandler = new UIA3AutomationEventHandler(
root.FrameworkAutomationElement,
automation.EventLibrary.Window.WindowOpenedEvent,
HandleOpenEvents);
automation.NativeAutomation.AddAutomationEventHandler(
automation.EventLibrary.Window.WindowOpenedEvent.Id,
root.ToNative(),
(Interop.UIAutomationClient.TreeScope)TreeScope.Descendants,
null,
automationOpenEventHandler);
UIA3AutomationEventHandler automationCloseEventHandler = new UIA3AutomationEventHandler(
root.FrameworkAutomationElement,
automation.EventLibrary.Window.WindowClosedEvent,
HandleCloseEvents);
automation.NativeAutomation.AddAutomationEventHandler(
automation.EventLibrary.Window.WindowClosedEvent.Id,
root.ToNative(),
(Interop.UIAutomationClient.TreeScope)TreeScope.Descendants,
null,
automationCloseEventHandler);
However, only one of the two (I believe the second one declared above) actually works.
Note that if I declare just one of the handlers above, either the open or close, it works fine. I just don't know how to get both going.
Any help would be appreciated!

Related

X11 window-close button when using single thread serving multiple windows

In a large application using X11 I recently switched from one thread per window to single thread serving all windows.
Now the problem is that clicking the window-close button causes all windows to disappear.
I know about the option to disable the window-manager's handling completely (XSetWMProtocols) but I don't want to do that because I would need to implement my own window-decoration, -resize...
I am setting callbacks with XSetErrorHandler and XSetIOErrorHandler,
Previously only the single window of a thead disappeared and I used above-mentioned callbacks to do a long-jump, properly cleaning resources, then ending the thread. The other windows/threads continued running.
However those callbacks are not even reached now:
I have a breakpoint in those callbacks and on _XIOError but at that point all windows have disappeared already.
#0 0x00007ffff7a62300 in _XIOError () from /lib/x86_64-linux-gnu/libX11.so.6.3.0
#1 0x00007ffff7a5fa0d in _XEventsQueued () from /lib/x86_64-linux-gnu/libX11.so.6.3.0
#2 0x00007ffff7a51211 in XPending () from /lib/x86_64-linux-gnu/libX11.so.6.3.0
#3 0x00005555555dcf54 in xwin4gRunI (T=0x7ffff7b832e8, Xwin4g=0x7ffff7b831b0) at ../xwin4/xwin4.c:257
From _XEventsQueued's source:
while((response = poll_for_response(dpy)))
handle_response(dpy, response, False);
if(xcb_connection_has_error(dpy->xcb->connection)) {
_XIOError(dpy);
return 0;
}
I have libx11-dev and libx11-xcb-dev installed but I guess it is not being used:
(gdb) f 1
#1 0x00007ffff7a5fa0d in _XEventsQueued () from /lib/x86_64-linux-gnu/libX11.so.6.3.0
(gdb) p response
No symbol "response" in current context.
So I took a look into poll_for_response: nothing that looked like window-unmap/destroy.
And into handle_response. It has:
case X_Error:
handle_error(...)...
A breakpoint in handle_error is not reached. But that could be due to it failing to use the libx11-xcb-dev debug-build.
It is possible that I forgot to move something from the giant old part of code to the less-giant new part of the code. Is there some XSetWMProtocols needed to let the above-mentioned callbacks be called before the windows disappear?
After two more hours of searching I found that indeed another XSetWMProtocols call was needed. For those who run into the same problem: use it with WM_DELETE_WINDOW.

Detect Win+Tab Task View

On Windows 10, you can press Win+Tab to get a "Task View" view of all your windows. I'm trying to check if this is active at any given time. I have tried using a Low Level Keyboard Hook with WH_KEYBOARD_LL but this only allows me to detect the keypress, not if the switcher is active. I've looked at the Windows DWM API and haven't found anything else either.
I have also tried using EnumWindows() and EnumChildWindows(GetDesktopWindow(), ...) and did not find any difference in the output between having the task view shown and hidden.
Is there any accurate method to detect if this is being shown?
Here's a solution that works very consistently with my version of Windows (1709 build 16299.125) and doesn't require the processor-heavy approach of a call to EnumChildWindows:
bool isTaskView() {
//Get foreground window's name
HWND fgWindow = GetForegroundWindow();
TCHAR windowName[MAX_PATH] = L"";
GetWindowText(fgWindow, windowName, MAX_PATH);
//Compare with magic string name of Task View's window
std::wstring nameStr(windowName);
return nameStr == L"Task View";
}

Xlib and Firefox behavior

I'm trying to create a small window manager (just for fun), but I'm having problems in handling windows created by Firefox (only with that application, other apps works fine)
The problem is, after I launch Firefox, and add my decoration, it seems to work fine, but if for example I try to click on the menu button, the (sub)window doesn't appear.
What seems to happen is that after the click, a ClientMessage event is fired with the following values:
Data: (null)
Data: _NET_WM_STATE_HIDDEN
Data: (null)
Data: (null)
Data: (null)
Now the problem is that I don't know how to show the window, which window.
I tried with:
XRaiseWindow
XMapWindow
I tried to get the transient window and show it
But without success. What I don't understand is that if this client message is generated by the menu subwindow or not.
How should I show a window that is in _NET_WM_STATE_HIDDEN?
Another strange problem is that after receiving the ClientMessage, I always receive 2 UnMapNotify Events.
I also have another question, if I want to show the "File, Edit" menù (in Firefox it appears, if I remember correctly, when you press the Alt button.
Maybe Firefox creates a tree of windows?
This is the loop where I handle the events:
while(1){
XNextEvent(display, &local_event);
switch(local_event.type){
case ConfigureNotify:
configure_notify_handler(local_event, display);
break;
case MotionNotify:
motion_handler(local_event, display);
break;
case CreateNotify:
cur_win = local_event.xcreatewindow.window;
char *window_name;
XFetchName(display, cur_win, &window_name);
printf("Window name: %s\n", window_name);
if(window_name!=NULL){
if(!strcmp(window_name, "Parent")){
printf("Adding borders\n");
XSetWindowBorderWidth(display, cur_win, BORDER_WIDTH);
}
XFree(window_name);
}
break;
case MapNotify:
map_notify_handler(local_event,display, infos);
break;
case UnmapNotify:
printf("UnMapNotify\n");
break;
case DestroyNotify:
printf("Destroy Event\n");
destroy_notify_handler(local_event,display);
break;
case ButtonPress:
printf("Event button pressed\n");
button_handler(local_event, display, infos);
break;
case KeyPress:
printf("Keyboard key pressed\n");
keyboard_handler(local_event, display);
break;
case ClientMessage:
printf("------------ClientMessage\n");
printf("\tMessage: %s\n", XGetAtomName(display,local_event.xclient.message_type));
printf("\tFormat: %d\n", local_event.xclient.format);
Atom *atoms = (Atom *)local_event.xclient.data.l;
int i =0;
for(i=0; i<=5; i++){
printf("\t\tData %d: %s\n", i, XGetAtomName(display, atoms[i]));
}
int nchild;
Window *child_windows;
Window parent_window;
Window root_window;
XQueryTree(display, local_event.xclient.window, &root_window, &parent_window, &child_windows, &nchild);
printf("\tNumber of childs: %d\n", nchild);
break;
}
Now in the clientmessage actually I'm just trying to see collect some information to understand what is happening. And what I can see from the code above, is that the window that raised the event contains one child (again: is that the menu? or not?)
The code for the MapNotify event, where I add the decoration is the following:
void map_notify_handler(XEvent local_event, Display* display, ScreenInfos infos){
printf("----------Map Notify\n");
XWindowAttributes win_attr;
char *child_name;
XGetWindowAttributes(display, local_event.xmap.window, &win_attr);
XFetchName(display, local_event.xmap.window, &child_name);
printf("\tAttributes: W: %d - H: %d - Name: %s - ID %lu\n", win_attr.width, win_attr.height, child_name, local_event.xmap.window);
Window trans = None;
XGetTransientForHint(display, local_event.xmap.window, &trans);
printf("\tIs transient: %ld\n", trans);
if(child_name!=NULL){
if(strcmp(child_name, "Parent") && local_event.xmap.override_redirect == False){
Window new_win = draw_window_with_name(display, RootWindow(display, infos.screen_num), "Parent", infos.screen_num,
win_attr.x, win_attr.y, win_attr.width, win_attr.height+DECORATION_HEIGHT, 0,
BlackPixel(display, infos.screen_num));
XMapWindow(display, new_win);
XReparentWindow(display,local_event.xmap.window, new_win,0, DECORATION_HEIGHT);
set_window_item(local_event.xmap.window, new_win);
XSelectInput(display, local_event.xmap.window, StructureNotifyMask);
printf("\tParent window id: %lu\n", new_win);
put_text(display, new_win, child_name, "9x15", 10, 10, BlackPixel(display,infos.screen_num), WhitePixel(display, infos.screen_num));
}
}
XFree(child_name);
}
Now can someone help me with these problems? Unfortunately I already googled many times, but without success.
To sum up, my issues are two:
1. How to show subwindows from Firefox
2. How to show the File, Edit menu.
UPDATE
I noticed something strange testing Firefox with xev to understand what events are fired in order to show an application. I saw that using Firefox in unity, and using Firefox in another window manger, the events fired are completely different. In Unity I have only:
ClientMessage
UnmapNotify
Instead using Firefox, for example with xfce4, the xevents generated are more:
VisiblityNotify (more than one)
Expose event (more than one)
But if I try to enable VisibilityChangeMask in my wm, I receive the following events:
ConfigureNotify
ClientMessage
MapNotify
2 UnMapNotify
UPDATE 2
I tried to read the XWMhints properties in the ClientMessage window (probably the menù window) and the values are:
For the flags 67 = InputHint, StateHint, WIndowGroupHint
For the initial state NormalState
UPDATE 3
I tried to look how another window manager works, and I was looking at the source code of calmwm. What is my understanding is that, when the ClientMessage event arrives, with a _NET_WM_STATE message, it updates these properties, and in the case of _NET_WM_STATE_HIDDEN it clears this property, and the result will be that the property will be deleted. So I tried to update my code to delete that property, but it's still not working. Anyway the relevant updated code in client_message_handler now looks like this:
Atom *atoms = (Atom *)local_event.xclient.data.l;
int i =0;
for(i=0; i<=5; i++){
printf("\t\tData %d: %s\n", i, XGetAtomName(display, atoms[i]));
if(i==1){
printf("\t Deleting Property: _NET_WM_STATE_HIDDEN \n");
XDeleteProperty(display, cur_window, atoms[i]);
}
}
It is only a test, and I'm sure that i=1 in my case is the _NET_WM_STATE_HIDDEN property.
Here a link to calmwm source code: https://github.com/chneukirchen/cwm/blob/linux/xevents.c
So I'm still stuck at that point.
UPDATE 4
Really I don't know if it helps, but I tried to read the window attributes in the MapNotify Event, and the window map_state is IsViewable (2).
UPDATE 5
I found a similar problem here in SO, using xlib with python: Xlib python: cannot map firefox menus
The solution suggests to use XSetInputFocus, i tried that on my XMapNotify handler:
XSetInputFocus(display, local_event.xmap.window, RevertToParent, CurrentTime);
But it still doesn't help, the firefox menu still doesn't appear!!
And i have the same problem with right-click.
UPDATE 6
Playing with xconfigurenotify event and unmap event i found that the:
Xconfigure request has 2 window fields: window and above, and when the
the xconfigurerequest.window value is the same of xunmap.window value.
And also that the xconfigurerequest.above is always changing, but xconfigurerequest.window is always the same in all events.
It seems that the xconfigurerequest.above is related to what menu i'm trying to open. For example:
if right-click on a page i get an id (always the same for every subsequent click)
if i right-clik on a tab, the above value is another one
and the same happen if i left-click the firefox main menu
Still don't know if that helps.
Really don't know
Anyone got any idea?
This question is ancient but for the benefit of anyone who stumbles across it looking for an answer to this, here's an edited (chopped to bits) sample of how I solved this based on the hints above:
while (event = xcb_poll_for_event(connection)) {
uint8_t actual_event = event->response_type & 127;
switch (actual_event) {
case XCB_MAP_NOTIFY: ;
xcb_map_notify_event_t *map_evt = (xcb_map_notify_event_t *)event;
if (map_evt->override_redirect) {
xcb_get_property_cookie_t cookie = xcb_icccm_get_wm_transient_for(connection, map_evt->window);
xcb_window_t transient_for = 0;
xcb_icccm_get_wm_transient_for_reply(connection, cookie, &transient_for, NULL);
if (transient_for) {
xcb_set_input_focus(connection, XCB_INPUT_FOCUS_POINTER_ROOT, transient_for, XCB_CURRENT_TIME);
}
xcb_flush(connection);
}
break;
case XCB_CLIENT_MESSAGE: ;
xcb_client_message_event_t *message_evt = (xcb_client_message_event_t *)event;
xcb_get_atom_name_cookie_t name_cookie = xcb_get_atom_name(connection, message_evt->type);
xcb_get_atom_name_reply_t *name_reply = xcb_get_atom_name_reply(connection, name_cookie, NULL);
int length = xcb_get_atom_name_name_length(name_reply);
char *atom_name = malloc(length + 1);
strncpy(atom_name, xcb_get_atom_name_name(name_reply), length);
atom_name[length] = '\0';
free(atom_name);
free(name_reply);
if (message_evt->type == ewmh->_NET_WM_STATE) {
xcb_atom_t atom = message_evt->data.data32[1];
unsigned int action = message_evt->data.data32[0];
xcb_get_atom_name_cookie_t name_cookie = xcb_get_atom_name(connection, atom);
xcb_get_atom_name_reply_t *name_reply = xcb_get_atom_name_reply(connection, name_cookie, NULL);
int length = xcb_get_atom_name_name_length(name_reply);
char *atom_name = malloc(length + 1);
strncpy(atom_name, xcb_get_atom_name_name(name_reply), length);
atom_name[length] = '\0';
if (action == XCB_EWMH_WM_STATE_REMOVE) {
if (atom == ewmh->_NET_WM_STATE_HIDDEN) {
xcb_delete_property(connection, message_evt->window, ewmh->_NET_WM_STATE_HIDDEN);
}
}
free(atom_name);
free(name_reply);
}
break;
}
}
By way of explanation, the important events to handle are MapNotify and ClientMessage because there's two main things that have to be taken care of, the window has to have its hidden state removed on request (the xcb_delete_property call) and the parent window of the transient has to gain input focus (the xcb_set_input_focus call; note that the window that the transient is a transient for gains focus, not the transient itself) or Firefox will immediately hide the transient again.
It also seems to be important for the transients to be stacked above their parent so a WM should respect the ConfigureRequest events.
PS Even if this is the accepted answer, the code of it is for xcb, if you need the code for xlib check my answer below, with the code adapted for xlib, it does cover only the MapNotify event
Use xtruss — an easy-to-use X protocol tracing program
Overview
Any programmer accustomed to writing programs on Linux or System V-type Unixes will have encountered the program variously known as strace or truss, which monitors another program and produces a detailed log of every system call the program makes – in other words, all the program's interactions with the OS kernel. This is often an invaluable debugging tool, and almost as good an educational one.
When it's a GUI program (or rather, the GUI-related behaviour of a program) that you want to understand or debug, though, the level of interaction with the OS kernel is rarely the most useful one. More helpfully, one would like to log all the program's interactions with the X server in the same way.
Programs already exist that will do this. I'm aware of Xmon and Xtrace. But they tend to require a lot of effort to set up: you have to run the program to establish a listening server, then manually arrange for the target program to contact that instead of the real server – including some fiddly work with xauth. Ideally, you'd like tracing a program's X operations to be just as easy as tracing its kernel system calls: you'd like to type a command as simple as strace program-name arguments, and have everything automatically handled for you.
Also, the output of those programs is less easy to read than I'd have liked – by which I largely mean it's less like strace than I'd like it to be. strace has the nice property of putting each system call and its return value on the same line of output, so that you can see at a glance what each response was a response to. X protocol monitors, however, tend to follow the structure of the X protocol faithfully, meaning that each request and response is printed with a sequence number, and you have to match the two up by eye.
So this page presents xtruss, my own contribution to the field of X protocol loggers. It has a command-line syntax similar to strace – in its default mode, you just prefix "xtruss" to the same command line you would have run anyway – and its output format is also more like strace, putting requests and responses on the same line of output where reasonably possible.
strace also supports the feature of attaching to an already-running process and tracing it from the middle of its run – handy when something goes wrong with a long-running process that you didn't know in advance you were going to need to trace. xtruss supports this same feature, by means of the X RECORD extension (provided your X server supports it, which modern X.Org ones do); so in that mode, you can identify a window with the mouse (similarly to standard programs like xwininfo and xkill), and xtruss will attach to the X client program that owns the window you specified, and begin tracing it.
Description
xtruss is a utility which logs everything that passes between the X server and one or more X client programs. In this it is similar to xmon(1), but intended to combine xmon's basic functionality with an interface much more similar to strace(1).
Like xmon, xtruss in its default mode works by setting up a proxy X server, waiting for connections to that, and forwarding them on to the real X server. However, unlike xmon, you don't have to deal with any of that by hand: there's no need to start the trace utility in one terminal and manually attach processes to it from another, unless you really want to (in which case the -P option will do that). The principal mode of use is just to type xtruss followed by the command line of your X program; xtruss will automatically take care of adjusting the new program's environment to point at its proxy server, and (also unlike xmon) it will also take care of X authorisation automatically.
As an alternative mode of use, you can also attach xtruss to an already-running X application, if you didn't realise you were going to want to trace it until it had already been started. This mode requires cooperation from the X server – specifically, it can't work unless the server supports the RECORD protocol extension – but since modern X.Org servers do provide that, it's often useful.
Ok, i'm going to answer my own question after only 4.5 years and half.
I'm going to revise Mr Lightning Bolt answer, and adapt it for XLIB, keeping focused on what he said about the Transient window. The answer probably will not be complete, but at least with that code snippet, now i'm able to open firefox menus.
I will accept his question, since he proposed the correct solution.
As lightning bolt pointed the key is the MapNotify Event,so the window manager should accept that kind of events, and when it is generated it should:
grab any transient window with XGetTransientWindowForHint
if any transient window is found, we need then to set input focus to it using XSetInputFocus.
The complete code, in your MapNotifyHandler, should looks like:
Window trans = None;
XGetTransientForHint(display, local_event.xmap.window, &trans);
if(trans != None){
XSetInputFocus(display, trans, RevertToParent, CurrentTime);
}

Runtime debugging tips for Windows Service?

I have a Windows Service that monitors a COM port connected to a vendors hardware. This is a very busy piece of hardware that is constantly polling other devices on the wire (this is a twisted-pair RS485 "network"). My software needs to emulate X number of hardware devices on this wire, so I've got a multi-threaded thing going on with a multi-tiered state machine to keep track of where the communications protocol is at any moment.
Problem is with a Windows Service (this is my first one, BTW) is that you need some debugging to let you know if stuff is working properly. When I was first developing this state machine/multi-thread code I had a windows form with a RichTextBox that displayed the ASCII chars going back-n-forth on the line. Seems like I can't really have that GUI niceness with a service. I tried opening a form in the service via another program that sent the service messages that are received via the OnCustomCommand() handler but it didn't seem to work. I had "Allow service to interact with desktop" checked and everything. I was using the Show() and Hide() methods of my debug form.
I guess I don't need to see all of the individual characters going on the line but man that sure would be nice (I think I really need to see them :-) ). So does anyone have any crazy ideas that could help me out? I don't want to bog down the system with some IPC that isn't meant for the voluminous amount of data that is sure to come through. It will only be very short-term debugging though, just confirmation that the program, the RS485-to-USB dongle, and hardware is all working.
Use OutputDebugString to write to the debugging buffer and then use DebugView to watch it. If you're running on Windows XP or earlier, then you can use PortMon to see the raw bytes going through the serial port. The advantage over a log file is that there's very little overhead, particularly when you're not watching it. You can even run DebugView from another machine and monitor your service remotely.
I dunno if it will work for you, but I always build my services with a extra Main that build them as console app to get debug output.
Edit:
Some example:
class Worker : ServiceBase
{
#if(RELEASE)
/// <summary>
/// The Main Thread where the Service is Run.
/// </summary>
static void Main()
{
ServiceBase.Run(new Worker());
}
#endif
#if(DEBUG)
public static void Main(String[] args)
{
Worker worker = new Worker();
worker.OnStart(null);
Console.ReadLine();
worker.OnStop();
}
#endif
// Other Service code
}
You could write the output to a log file and then use another application to watch that file. This question about "tail" outlines several options for watching log files with windows.
What I usually do when working on a Windows Service is to create it so that it can be run either as a service, or as a plain old command-line application. You can easily check whether you are running as a service by checking Environment.UserInteractive. If this property is true, then you are running from the command line. If the property is false, then you are running as a service. Add this code to Program.cs, and use it where you would normally call ServiceBase.Run(servicesToRun)
/// <summary>Runs the provided service classes.</summary>
/// <param name="servicesToRun">The service classes to run.</param>
/// <param name="args">The command-line arguments to pass to the service classes.</param>
private static void RunServices(IEnumerable<ServiceBase> servicesToRun, IEnumerable args)
{
var serviceBaseType = typeof(ServiceBase);
var onStartMethod = serviceBaseType.GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (var service in servicesToRun)
{
onStartMethod.Invoke(service, new object[] { args });
Console.WriteLine(service.ServiceName + " started.");
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
var onStopMethod = serviceBaseType.GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (var service in servicesToRun)
{
onStopMethod.Invoke(service, null);
Console.WriteLine(service.ServiceName + " stopped.");
}
}
Now you can debug your service, set breakpoints, anything you want. When you run your application, you'll get a console window, appropriate for displaying console messages, and it will stay open until you hit a key.
I'm answering my own question here. I tried a couple of suggestions here but here's what I ended up doing...
I created a Windows Form application with a single Button and RichTextBox. This application constructed a NamedPipeServerStream on it's end. The Button's job was to send either "debug on" (command 128) or "debug off" (129) to the Windows Service. The initial value was "debug off". When the button was clicked, a command of 128 was sent to the Windows Service to turn debugging on. In the Windows Service this triggered an internal variable to be true, plus it connected to the Form application with a NamedPipeClientStream and started sending characters with a BinaryWriter as they were received or sent on the COM port. On the Form side, a BackgroundWorker was created to WaitForConnection() on the pipe. When it got a connection, a BinaryReader.ReadString() was used to read the data off of the pipe and shoot it to the RichTextBox.
I'm almost there. I'm breaking my pipe when I click the debug button again and a subsequent click doesn't correctly redo the pipe. All in all I'm happy with it. I can post any code if anyone is interested. Thanks for the responses!

How do I get the selected text from the focused window using native Win32 API?

My app. will be running on the system try monitoring for a hotkey; when the user selects some text in any window and presses a hotkey, how do I obtain the selected text, when I get the WM_HOTKEY message?
To capture the text on to the clipboard, I tried sending Ctrl + C using keybd_event() and SendInput() to the active window (GetActiveWindow()) and forground window (GetForegroundWindow()); tried combinations amongst these; all in vain. Can I get the selected text of the focused window in Windows with plain Win32 system APIs?
TL;DR: Yes, there is a way to do this using plain win32 system APIs, but it's difficult to implement correctly.
WM_COPY and WM_GETTEXT may work, but not in all cases. They depend on the receiving window handling the request correctly - and in many cases it will not. Let me run through one possible way of doing this. It may not be as simple as you were hoping, but what is in the adventure filled world of win32 programming? Ready? Ok. Let's go.
First we need to get the HWND id of the target window. There are many ways of doing this. One such approach is the one you mentioned above: get the foreground window and then the window with focus, etc. However, there is one huge gotcha that many people forget. After you get the foreground window you must AttachThreadInput to get the window with focus. Otherwise GetFocus() will simply return NULL.
There is a much easier way. Simply (miss)use the GUITREADINFO functions. It's much safer, as it avoids all the hidden dangers associated with attaching your input thread with another program.
LPGUITHREADINFO lpgui = NULL;
HWND target_window = NULL;
if( GetGUIThreadInfo( NULL, lpgui ) )
target_window = lpgui->hwndFocus;
else
{
// You can get more information on why the function failed by calling
// the win32 function, GetLastError().
}
Sending the keystrokes to copy the text is a bit more involved...
We're going to use SendInput instead of keybd_event because it's faster, and, most importantly, cannot be messed up by concurrent user input, or other programs simulating keystrokes.
This does mean that the program will be required to run on Windows XP or later, though, so, sorry if your running 98!
// We're sending two keys CONTROL and 'V'. Since keydown and keyup are two
// seperate messages, we multiply that number by two.
int key_count = 4;
INPUT* input = new INPUT[key_count];
for( int i = 0; i < key_count; i++ )
{
input[i].dwFlags = 0;
input[i].type = INPUT_KEYBOARD;
}
input[0].wVK = VK_CONTROL;
input[0].wScan = MapVirtualKey( VK_CONTROL, MAPVK_VK_TO_VSC );
input[1].wVK = 0x56 // Virtual key code for 'v'
input[1].wScan = MapVirtualKey( 0x56, MAPVK_VK_TO_VSC );
input[2].dwFlags = KEYEVENTF_KEYUP;
input[2].wVK = input[0].wVK;
input[2].wScan = input[0].wScan;
input[3].dwFlags = KEYEVENTF_KEYUP;
input[3].wVK = input[1].wVK;
input[3].wScan = input[1].wScan;
if( !SendInput( key_count, (LPINPUT)input, sizeof(INPUT) ) )
{
// You can get more information on why this function failed by calling
// the win32 function, GetLastError().
}
There. That wasn't so bad, was it?
Now we just have to take a peek at what's in the clipboard. This isn't as simple as you would first think. The "clipboard" can actually hold multiple representations of the same thing. The application that is active when you copy to the clipboard has control over what exactly to place in the clipboard.
When you copy text from Microsoft Office, for example, it places RTF data into the clipboard, alongside a plain-text representation of the same text. That way you can paste it into wordpad and notepad. Wordpad would use the rich-text format, while notepad would use the plain-text format.
For this simple example, though, let's assume we're only interested in plaintext.
if( OpenClipboard(NULL) )
{
// Optionally you may want to change CF_TEXT below to CF_UNICODE.
// Play around with it, and check out all the standard formats at:
// http://msdn.microsoft.com/en-us/library/ms649013(VS.85).aspx
HGLOBAL hglb = GetClipboardData( CF_TEXT );
LPSTR lpstr = GlobalLock(hglb);
// Copy lpstr, then do whatever you want with the copy.
GlobalUnlock(hglb);
CloseClipboard();
}
else
{
// You know the drill by now. Check GetLastError() to find out what
// went wrong. :)
}
And there you have it! Just make sure you copy lpstr to some variable you want to use, don't use lpstr directly, since we have to cede control of the contents of the clipboard before we close it.
Win32 programming can be quite daunting at first, but after a while... it's still daunting.
Cheers!
Try adding a Sleep() after each SendInput(). Some apps just aren't that fast in catching keyboard input.
Try SendMessage(WM_COPY, etc. ).

Resources