Copy & Paste Using Drag and Drop With MS VB? - copy

I'm looking to copy and paste from a windows form. I'm writing this program in Microsoft Visual Basic. I'm stuck. I can't seem to get copy files that have been dragged into the windows form.
I'm Asking for help, As I started 3 months ago with MS VB.

if you are using VB6 then
you can retrieve file names from Data.Files() object
Private Sub Form_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single)
dim fname
for each fname in Data.Files
'...
next
End Sub
don't forget to set OleDropMode property of the form to Manual (1)

Related

Windows Explorer (Context Menu)

This is a two part questions for Windows Explorer (context menu).
First, I have this code in VBScript that gives back to me in a string of all the selected files in an instance of Windows Explorer. I plan to convert this VBScript code to PowerShell. Is there a better way of doing this in PowerShell? Otherwise, I will convert it and use the same COMObject "Shell.Application".
Private Function GetSelectedFiles() 'Returns paths as array of strings
Dim strData
Dim oShell
Set oShell = CreateObject("Shell.Application")
With oShell
Dim oWindow
For Each oWindow In .Windows
Dim oSelectedItem
For Each oSelectedItem In oWindow.Document.SelectedItems
strData = strData & oSelectedItem.Path & vbCRLF
Next
Exit For 'Exit after the first looping so that it does not pickup the other Windows Explorer instances.
Next
End With
Set oShell = Nothing
If Right(strData, Len(vbCRLF)) = vbCRLF Then strData = Left(strData, Len(strData) - Len(vbCRLF))
GetSelectedFiles = strData
End Function
Second, with the above code, I can save it into a script and bind the script to a registry entry "HKEY_CLASSES_ROOT\Folder\shell". This will allow me to right-click on a folder and select on the entry to get the selected files. However, I would like to do it similar to WinRar where I can right-click on any selected files/folders and run the script to get the selected files/folders.
Notice, this is not the same as "HKEY_CLASSES_ROOT\*\shell" since it will run multiple instances of the same script. For example, if I select multiple text files and right-click select Notepad, it would open multiple instances of Notepad for each text file. This is not what I am looking for.
I am looking for similar to WinRar, PowerISO, etc..., it would run only one instance but captured all selected files and feed it to the script or program.
Do I have to build the object in C# or something? Or is there another way of doing this without building an object in C#?
I was able to resolve my second question by adding the shortcut of the script to SendTo folder which is located at:
C:\Users\UserName\AppData\Roaming\Microsoft\Windows\SendTo
I also found this tool but I rather use the above because I don't like to install additional stuffs if I can avoid it.
https://www.thewindowsclub.com/add-customize-send-to-menu-windows

programmatically press an enter key after starting .exe file in Matlab

In Matlab I can start external .exe files that sometime have a pop up that requires an enter key pressed. For example:
system('C:\Program Files (x86)\WinZip\WINZIP32.EXE')
will start Winzip, and then in order to use it you need to pass the "buy now" pop up window by pressing enter.
Now my problem is not with winzip, I only gave it as an example (i use winrar anyway :).
How can I programmatically press an enter key in Matlab in such cases ? (I use win 7)
Can an event listener be used to solve that?
EDIT: The java.awt.Robot class indeed works on explorer, but not on any software that has a pop up window with an OK button that needs to be pressed. I don't know why it doesn't work for that. I gave the winzip example because I assume everybody has winzip/winrar installed in their machine. The actual software I have is different and irrelevant for the question.
There is a way using Java from Matlab, specifically the java.awt.Robot class. See here.
Apparently there are two types of programs, regarding the way they work when called from Matlab with system('...'):
For some programs, Matlab waits until the program has finished before running the next statement. This happens for example with WinRAR (at least in my Windows 7 machine).
For other programs this doesn't happen, and Matlab proceeds with the next statement right after the external program has been started. An example of this type is explorer (the standard Windows file explorer).
Now, it is possible to return execution to Matlab immediately even for type 1 programs: just add & at the end of the string passed to system. This is standard in Linux Bash shell, and it also works in Windows, as discussed here.
So, you would proceed as follows:
robot = java.awt.Robot;
command = '"C:\Program Files (x86)\WinRAR\WinRAR"'; %// external program; full path
system([command ' &']); %// note: ' &' at the end
pause(5) %// allow some time for the external program to start
robot.keyPress (java.awt.event.KeyEvent.VK_ENTER); %// press "enter" key
robot.keyRelease (java.awt.event.KeyEvent.VK_ENTER); %// release "enter" key
If your applications are only on Windows platform, you can try using .net objects.
The SendWait method of the SendKeys objects allows to send virtually any key, or key combination, to the application which has the focus, including the "modifier" keys like Alt, Shift, Ctrl etc ...
The first thing to do is to import the .net library, then the full syntax to send the ENTER key would be:
NET.addAssembly('System.Windows.Forms');
System.Windows.Forms.SendKeys.SendWait('{ENTER}'); %// send the key "ENTER"
If you only do it once the full syntax is OK. If you plan to make extensive use of the command, you can help yourself with an anonymous helper function.
A little example with notepad
%% // import the .NET assembly and define helper function
NET.addAssembly('System.Windows.Forms');
sendkey = #(strkey) System.Windows.Forms.SendKeys.SendWait(strkey) ;
%% // prepare a few things to send to the notepad
str1 = 'Hello World' ;
str2 = 'OMG ... my notepad is alive' ;
file2save = [pwd '\SelfSaveTest.txt'] ;
if exist(file2save,'file')==2 ; delete(file2save) ; end %// this is just in case you run the test multiple times.
%% // go for it
%// write a few things, save the file then close it.
system('notepad &') ; %// Start notepad, without matlab waiting for the return value
sendkey(str1) %// send a full string to the notepad
sendkey('{ENTER}'); %// send the {ENTER} key
sendkey(str2) %// send another full string to the notepad
sendkey('{! 3}'); %// note how you can REPEAT a key send instruction
sendkey('%(FA)'); %// Send key combination to open the "save as..." dialog
pause(1) %// little pause to make sure your hard drive is ready before continuing
sendkey(file2save); %// Send the name (full path) of the file to save to the dialog
sendkey('{ENTER}'); %// validate
pause(3) %// just wait a bit so you can see you file is now saved (check the titlebar of the notepad)
sendkey('%(FX)'); %// Bye bye ... close the Notepad
As explained in the Microsoft documentation the SendKeys class may have some timing issues sometimes so if you want to do complex manipulations (like Tab multiple times to change the button you actually want to press), you may have to introduce a pause in your Matlab calls to SendKeys.
Try without first, but don't forget you are managing a process from another without any synchronization between them, so timing all that can require a bit of trial and error before you get it right, at least for complex sequences (simple one should be straightforward).
In my case above for example I am running all my data from an external hard drive with an ECO function which puts it into standby, so when I called the "save as..." dialog, it takes time for it to display because the HDD has to wake up. If I didn't introduce the pause(1), sometimes the file path would be imcomplete (the first part of the path was send before the dialog had the focus).
Also, do not forget the & character when you execute the external program. All credit to Luis Mendo for highlighting it. (I tend to forget how important it is because I use it by default. I only omit it if I have to specifically wait for a return value from the program, otherwise I let it run on its own)
The special characters have a special code. Here are a few:
Shift +
Control (Ctrl) ^
Alt %
Tab {TAB}
Backspace {BACKSPACE}, {BS}, or {BKSP}
Validation {ENTER} or ~ (a tilde)
Ins Or Insert {INSERT} or {INS}
Delete {DELETE} or {DEL}
Text Navigation {HOME} {END} {PGDN} {PGUP}
Arrow Keys {UP} {RIGHT} {DOWN} {LEFT}
Escape {ESC}
Function Keys {F1} ... {F16}
Print Screen {PRTSC}
Break {BREAK}
The full list from Microsoft can be found here
There is a small javascript utility that simulates keystrokes like this on the Windows javascript interpreter.
Just create a js file with following code:
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
then call it from Matlab after the necessary timeout like this:
system('c:\my\js\file\script.js {Enter}');
Can't test here now, but I think this should work...
If you need to run a console-only program in a context that permits full DOS redirection, you can create a file called, say, CR.txt containing a carriage return and use the '<' notation to pipe the value into the program.
This only works if you can provide all the keyboard input can be recorded in the file. It fails dismally if the input has to vary based on responses.
An alternative is to duplicate the input (and possibly output) stream(s) for the program and then pipe data into and out of the program. This is more robust and can permit dynamic responses to the data, but will also likely require substantial effort to implement a robot user to the application.
Rog-O-Matic is an example of a large application completely controlled by a program that monitors screen output and simulates keyboard input to play an early (1980s) ASCII graphic adventure game.
The other responses will be required for GUI-based applications.
Python package pywinauto can wait any dialog and click buttons automatically. But it's capable for native and some .NET applications only. You may have problems with pressing WPF button (maybe QT button is clickable - not checked), but in such case code like app.DialogTitle.wait('ready').set_focus(); app.DialogTitle.type_keys('{ENTER}') may help. Your case is quite simple and probably some tricks with pywinauto are enough. Is your "app with popup" 64-bit or 32-bit?
wait and wait_not functions have timeout parameter. But if you need precisely listener with potentially infinite loop awaiting popups, good direction is global Windows hooks (pyHook can listen mouse and keybd events, but cannot listen dialog opening). I'll try to find my prototype that can detect new windows. It uses UI Automation API event handlers... and... ops... it requires IronPython. I still don't know how to set UI Automation handler with COM interface from standard CPython.
EDIT (2019, January): new module win32hooks was implemented in pywinauto a while ago. Example of usage is here: examples/hook_and_listen.py.

microsoft word: copy without formatting

When I copy a text from Microsoft Word and the text is a heading in the clipboard I see it included a paragraph number. Then in another application I must remove the number manually.
Can I copy just a text without any additional information?
(The same is with Chrome when you copy a URL it adds a http:// automatically)
Method 1:-
one way is right mouse click and use this paste special option
Method 2:-
assign a shortcut(Ctrl+Shift+V) for this operation (Note: by default Ms word not set shortcut for it so we need to set it by own)
File > Options > Customize Ribbon > Keyboard shortcuts: Customize.
on Left Categories List section, click on All Commands
Under right Commands List, select for PasteTextOnly
then Set the keyboard shortcut for PasteTextOnly as Ctrl+Shift+V
Method 3 permanent/Default Settings
use this option which will each time paste as plain text by default
Try this
Sub FormatFreeTextCopy()
Dim ffText As DataObject
Set ffText = New DataObject
ffText.setText Selection.Text
ffText.PutInClipboard
End Sub
Note: You would have to Reference to Microsoft Forms Object Library
There is a generic "paste plain text" solution using autohotkey open-source automation software:
^+v:: ; Text–only paste from ClipBoard
Clip0 = %ClipBoardAll%
ClipBoard = %ClipBoard% ; Convert to text
Send ^v ; For best compatibility: SendPlay
Sleep 50 ; Don't change clipboard while it is pasted! (Sleep > 0)
ClipBoard = %Clip0% ; Restore original ClipBoard
VarSetCapacity(Clip0, 0) ; Free memory
Return
Save this code to paste_plain_text.ahk script
Install autohotkey
Execute your script
It will paste plain text using Ctrl+Shift+V shortcut. You can put your script at Startup directory so it loads on Windows startup.

microsoft word find and replace

From a word file , I want to replace alternate occurence of a character.By using Find & Replace all the occurences will be replaced.Is there any way to replace only alternate occurences?
Assuming you're using Microsoft Word, you can create a macro to do just that. You basically start recording and do those steps (assuming you copied the new character in the clipboard):
Press F3 to find next.
Ctrl-V to paste over.
Press F3 to ignore the next.
Stop recording and execute the macro until the end of the file is reached.
MS Word 2010 - http://www.dummies.com/how-to/content/how-to-make-a-macro-in-word-2010.html

How can I run a Perl script through an ActiveX Control within Excel?

I want to run a Perl script at the click of a button inside an Excel spreadsheet.
As the button is assigned to execute a VB macro, the macro should effectively execute the program.
As my first ever VB script, this is what I came up with, which throws up an irritating Run-time error '424': Object required error.
Sub RunPerlScript()
System.Diagnostics.process.Start ("perlscript.pl")
End Sub
How can I get this script to do what I want it to do?
I didn't write this snippet, but it would seem to be a good answer to your question.
From the article "How to execute a perl script from VBA":
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sub RunPerl()
MsgBox ("Start of macro")
Dim oWsc As Object
Set oWsc = CreateObject("WScript.Shell")
Dim oExec As Object
Set oExec = oWsc.Exec("perl C:\temp\myperl.pl StartParam")
While oExec.Status <> 1 ' Wait for process
Sleep 1000
Wend
MsgBox ("STDOUT" + oExec.StdOut.ReadAll())
MsgBox ("STDERR" + oExec.StdErr.ReadAll())
Set oWsc = Nothing
MsgBox ("End of macro")
End Sub
You might need to install ActivePerl first
You cannot use .NET classes in a VBA macro.
Use the VBA Shell function.
Shell "p:\ath\to\perlscript.pl"
The documentation:
Shell Function
Runs an executable program and returns
a Variant (Double) representing the
program's task ID if successful,
otherwise it returns zero.
Syntax
Shell(pathname[,windowstyle])
The Shell function syntax has these
named arguments:
Part Description pathname Required;
Variant (String). Name of the program
to execute and any required arguments
or command-line switches; may include
directory or folder and drive. On the
Macintosh, you can use the MacID
function to specify an application's
signature instead of its name. The
following example uses the signature
for Microsoft Word: Shell
MacID("MSWD") windowstyle Optional.
Variant (Integer) corresponding to the
style of the window in which the
program is to be run. If windowstyle
is omitted, the program is started
minimized with focus. On the Macintosh
(System 7.0 or later), windowstyle
only determines whether or not the
application gets the focus when it is
run.
The windowstyle named argument has
these values:
Constant Value Description vbHide 0
Window is hidden and focus is passed
to the hidden window. The vbHide
constant is not applicable on
Macintosh platforms. vbNormalFocus 1
Window has focus and is restored to
its original size and position.
vbMinimizedFocus 2 Window is displayed
as an icon with focus.
vbMaximizedFocus 3 Window is maximized
with focus. vbNormalNoFocus 4 Window
is restored to its most recent size
and position. The currently active
window remains active.
vbMinimizedNoFocus 6 Window is
displayed as an icon. The currently
active window remains active.
ActiveState's PDK has PerlCtrl which lets you package a perl script as an ActiveX control. It gathers up your script and all dependencies into a tidy DLL.