C# GUI macro libraries or general approaches? - c#

In a C# WinForms application (on .NET 3.5, probably 4.0 soonish), how would you go about allowing the user to define their own macros? For instance, a user could want the key press CTRL+K to mean clicking a certain item in the menu, and entering some text in the dialog opened by the menu, before pressing "Ok" to close the dialog.
Ideally, our software could provide a macro-recording functionality, that would enable a user to just start recording, perform the desired tasks, and the stop recording to have a macro available. This a feature that they are used to from the old version of the software, that was written in FoxPro, a tool that has such capabilities built-in.
The best option for us would clearly be acquiring and utilizing a tried and tested third party library of some sorts, but ideas for rolling our own version are also appreciated.

If I were working on something like this, I would perhaps integrate a general purpose eventhandler to log events that you want to be recordable ( perhaps either as an individual handler added to available buttons or by creating a RecordedEventHandler class to extend EventHandler and then subclassing all your event handling from that - these are just top-of-the-head ideas so I haven't looked into which would be most viable ) and just use the "record macro" button as a switch for that. There are only likely to be a few different types of event that need to be recorded - button clicks, keyboard input on any text fields, keyboard shortcuts and mouse input on any mouse-input fields so it's not an enormously taxing task although of course working out how to store and bind macros and how to facilitate import and export if you were inclined to do so is time consuming but not technically challenging. I don't know of any libraries for this purpose ( although I expect some exist ) and thinking about it I'm not sure how easy it would be to integrate something like that because most peoples' needs in terms of macros are likely to be different.
If you needed to be able to log events around your application then you may find the ManagedWinApi to be helpful.

I have good experience with "command design pattern" for macro-recording functionaly. Every command fire some application-wide (static for example) event with informations abou parameters etc... The recorder listen to this event and persist the sequence of command calling.

Related

How to keep focus on more than one window for input devices

The idea is to do something like what a keystroke catcher does, but with multiple input devices. I want a window to record input from devices even if the focus is on another window. What libraries or methodologies would allow me to accomplish this?
This is typically handled via a low level Hook. There is no C# library which will handle this directly, though there is a Microsoft KB article showing How to set a Windows hook in Visual C# .NET.

How do I reliably invoke clipboard copy/paste actions in other apps without messing with input queue

A while ago I wrote a simple app, which surrounds selected text in any input field in any application with some unicode symbols when user presses some hotkey. Basically, app's logic is as follows:
Register global hotkey.
Hotkey fired, now set clipboard monitor and invoke clipboard copy to see if some text was selected.
If clipboard has changed and now contains text, surround said text with symbols and then invoke clipboard paste, so input field will be updated with modified text.
The problem is, I can't get copy/paste functionality from other apps in a reliable way. What I have tried to date:
If I send WM_COPY/WM_PASTE, it's more often ignored than not, depending on the application.
If I use SendInput, keybd_event or any other keyboard-messing stuff to press/unpress usual clipboard hotkeys, it will often tamper with user-pressed keys: copy/paste uses control or shift, which are also quite popular for all generic hotkeys in all apps, my app included.
If I use Journal Hook to directly inject keyboard messages into system input queue, sometimes it will work fine, and sometimes weird glitches will occur. Also, other applications may be using JournalHook for themselves, and that will mess my app badly. Not to mention that default security policies make journal hook hard to use.
I've been trying to get/set text in the input fields using Windows UI automation instead of clipboard magic, but it rarely works.
So, if you know other ways to make other applications reliably use copy/paste functionality, or can even devise entirely different approach, I'd really appreciate you telling me :)
I think your approach isn't that bad, maybe you can start with WM_DRAWCLIPBOARD so you can monitor the clipboard. A nice sample code can be found here.
Next I'd take a look at SendKeys class - Attention: Flush, Buffer, etc. Use this to send ctrl+c/v instead of a windows message! You should get a notification from your monitor if it worked.
Now I'd use the Cliboard class to maniplulate the Data and paste it back.
Oh, it seems that I could only find more or less reliable way of invoking copy-paste without SendInput or journal hook, but I have to deal with it :-) So here it is, in case someone find it useful:
Remember and reset keyboard modifiers via AttachThreadInput(yourAppThreadId, targetAppThreadId) + SetKeyboardState(keyStateWithoutKeyboardModifiers).
Set Ctrl key modifier via SetKeyboardState(keyStateWithControl) for Ctrl+C/V hotkey.
Then PostMessage to focused control handle with WM_KEYDOWN message for C or V key, whether you want it to copy or paste.
Call Thread.CurrentThread.Join(20) to let other app process messages — and that's the most retarded moment in the whole deal, since I couldn't find the sure way to know when other app will have empty message queue.
Restore remembered keyboard modifiers.
Also, every time you do SetKeyboardState, call SetForegroundWindow(focusedControlHandle) and SetFocus(focusedControlHandle) afterwards.

Any high level library or framework to hook all events in one's app in C#?

I know there's hook in Win32 but I don't need to hook the whole system and it's low level.
What I want is something easy like Wordpress framework but for Winform which allows me to hook all events in my own application for example detecting all textbox leave or all forms closing.
Does this exist ? Is it possible technically or only Microsoft can do so in .NET Version X.X ?
Have a look at ManagedSpy. It's an application very similar to Spy++, but for managed applications. It appeared in an MSDN Magazine issue several years ago.
When you run ManagedSpy, you can attach it to a running .Net process. It will reflect on the assemblies and find all kinds of events (there's some filtering ability to only see certain events), then it attaches to them and outputs the sequence of them firing.
There is also source code for ManagedSpy, so you can see how they did things and use those ideas to build what you need.
There is no easy way to do this as I am aware. There are external tools that can help (such as Spy++) but I believe they operate at the Windows message level rather than the .NET event level.
If you really need to do this level of monitoring in your application, you'll need to sign up event handlers on each object you wish to monitor. You could consider writing code that walks the control tree for each Form and signs up their events, so you could run it at startup after the forms are created.

Send keys to WPF Browser control

Can I programatically send [UserID]{TAB}[Password]{CARRIAGE RETURN} to a webbrowser control which has a userID, password and Sign-in button there. I wanted to use my own virtual keyboard in my application. Any tips here?
Sorry for the late answer but I've just finished a similar project and as part of the work am in the process of open sourcing two projects to Codeplex.
The first is the Windows Input Simulator which is a simple .NET wrapper around the Win32 SendInput written in C#.
The second is a very customisable on screen keyboard or touch screen keyboard control and toolkit called WpfKB and will be available as an initial release tomorrow. Hope these are of help to you or anyone else who comes across the projects.
I recently had to implement automatic authentication through a WPF browser control, and I looked into simulating keystrokes. I didn't need a full virtual keyboard so interacting with the DOM of the login page through IHTMLDocument2 ended up being the best approach, but I looked into keystroke automation before making that decision and found a few options.
You can raise the appropriate routed events on the control as described in Simulating basic keyboard events and Simulating text input. I don't know of any specific problems with this approach but I opted against it simply because I wasn't comfortable simulating input without looking at how the CLR handles the actual input, and without at least raising the complete lifetime (PreviewKeyDown, KeyDown, PreviewKeyUp, KeyUp) I was wary of unintended consequences.
Take a look at WOSK on CodePlex. It's a good example of how to invoke Win32 keybd_event and SendInput functions to generate the low-level input messages via Managed Windows API to simulate input. There's some unnecessary fluff (eg transparency) and some odd WPF usage, such as using a CommandParameter with a Click event instead of a Command on the buttons, but the general approach is sane and it's reasonably complete.
You can also invoke the windows on-screen keyboard as alluded to by Jeroen. I didn't try this because I didn't need a virtual keyboard, but if you're going to call into Win32 anyway, you might as well follow the WOSK model and build the UI the way you want it.

Windows Terminal - Windows Form to embed cmd

I'm looking for a way to embed a cmd "Shell" into a Form. I want to build a C# based application that acts as a Terminal, better than the Powershell window (no tabs) or cmd (no nothing). Just start these interpreters in the backend.
I guess MS never thought of doing this. Any ideas what From elements I could use?
Thanks,
i/o
That's not a trivial task you're undertaking. I know of one project (Console2) which basically polls the screen buffer of the underlying console window and displays in its own. You certainly will have trouble coping with interactive applications like Far and the like as they (a) rely on getting keyboard events and (b) on manipulating their screen buffer. Both are icky things if you want a suitable wrapper around the console window functionality. Mouse input is possible as well (unless Quick Edit mode is enabled) which could give you further headaches.
I doubt you can use a ready-made control for this. Basically you need to display a grid of cells each of which has a foreground and background color. You could probably use a RichTextBox for this but I'd guess it's far from ideal.
Also I don't think no one at MS ever thought of this. It's just that there's a limited budget for new features and every one of them needs to be specified, implemented, tested, tested more for regressions with millions of applications out there, etc. It's just a freaking expensive thing (if you don't want to misuse your customers as testers, which they aren't).
It would propably be the easiest to extend the Textbox class and add logic so that it behaves like a console (respond to the KeyPressed/KeyUp/KeyDown events or similar). You can also add events for those things that your console needs to respond to. For example, add a CommandEntered event.
Basing your new console on a TextBox gives you the editing and display features of the textbox "for free", so you do not need to re-implement that.
You could use a richtext box, and set the background to black and foreground to white. RTB instead of text box to handle larger amounts of data.
You would have to write an awful lot of code to simulate the terminal though.

Categories