简体   繁体   中英

Unable to use SendKeys or SendMessage for programmatically pasting non-text objects

I am using the RegisterHotKey Win32 API to listen to the Ctrl_V key combination and using the WndProc method to handle this hot key notification. Now, even if I don't perform any operations in this method apart from calling base.WndProc(ref mesg), the Paste operation doesnt seem to be getting passed onto Windows and hence, paste is not working. I managed to get paste of text working by explicitly calling SendKeys("^V") but it is not working for non-text data. I also tried SendMessage Win32 API as below

SendMessage(foregroundWindowHandle, 0x302, 0, 0);

but even this is not working.

I am unable to figure out how to execute my code and then let Windows perform the paste for images, files etc. Any help in resolving this will be very timely and highly appreciated.

UPDATE: I figured out the problem was that the window where the Paste command was being generated wasnt getting the focus back. After correcting this, Paste is working fine for Notepad. Also, I am using Alt_Shift_V as the hot key now to avoid clashing with the default paste command. So pasting non-text data works fine. However, pasting text into Visual studio and Office applications is not working. SendKeys("^V") seems to be interpreted in a different way in these applications. Any idea on how to get this working?

Instead of registering a hotkey, register a global hook.

I have used global hooks to do something similar to what you are doing in the past and it works quite well.

Code for a simple and handy global hook implementation can be found at:

http://www.codeproject.com/KB/cs/globalhook.aspx

This would not interfere with the pasting operation :)

I think you should intercept the Ctrl-V Key message (through WndProc), do what you need and then let the base.WndProc handle the key message. You could also handle the OnKeyDown event. In WinForms, you can set Form.KeyPreview to true in order to see messages before child controls.

Registering a hotkey isn't the solution if you just want to take some action and then pass on the message. It sounds like you'd need a keyboard hook instead (the SetWindowsHookEx API).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM