How do I copy from, erase, then paste back into the clipboard?
I have to automate a program that is outside of my control. The way I'm doing this is to use SendKeys.SendWait("keys")
to the other program. The problem is, there are multiple fields that might be active and no way to select a single one with confidence. The fields are all different lengths, so my solution is to copy something really long, copy it to the clipboard, and look at the last character that made it though, so I know which field is selected in the other program. This overrides the clipboard, unfortunately.
So, I need to do these things.
- Copy the clipboard contents, which could be anything, into a v开发者_如何学Pythonariable.
- Send a bunch of things to the other program and copy it. Then use that to do other things.
- Copy the first variable back to the clipboard.
Ideally, it would be able to copy anything from the clipboard (images, text, rich text) and place it back just like nothing happened. Here's what I've got so far, but it erases whatever is in the clipboard, or replaces it with something special that can't be pasted back into notepad.
AppActivate("OtherProgram")
Dim oldClipboard As IDataObject = Clipboard.GetDataObject
//'Type long stuff, select all, cut to clipboard
SendKeys.SendWait("{ESC}{F3}1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "+{HOME}^x")
Dim selectedFieldText As String = Clipboard.GetText
Dim lastChar As String = selectedFieldText.Substring(selectedFieldText.Length - 1, 1)
Select Case lastChar
Case "4"
//'do nothing. We're in the correct field.
Case "J"
SendKeys.SendWait("+{TAB}")
Case "O"
SendKeys.SendWait("+{TAB}+{TAB}")
//'...and so on
End Select
//'Send data to the correct field in "OtherProgram"
Clipboard.SetDataObject(oldClipboard)
If you haven't done much coding on this project yet, I'd highly recommend AutoIt.
It is a programming language built just for automation of existing programs. Since you are using vb.net, it has a familiar BASIC syntax.
It will click buttons, handle the clipboard and and generates native executable.
Building nice guis in it is very easy. It is mature, stable and free!
Really, do yourself a favor and check it out.
The UI Automation name space may contain a solution for you. I'd test it against the object because not everything complies but almost everything complies with the automation. The text automation has the ability to see the length. http://msdn.microsoft.com/en-us/library/system.windows.automation.textpattern.getselection.aspx Also use the UI Spy.exe http://msdn.microsoft.com/en-us/library/ms727247.aspx to see how the forms are layed out for interacting using the UI Automation.
Luck.
You cannot faithfully restore the clipboard to its prior state, and as you attempt to do so, you're going to be causing unpredictable mayhem with other apps that monitor clipboard events. See my prior answer to this question: How do I safely and correctly create a backup of the Windows clipboard?
精彩评论