windows - access clipboard from service in c++

2019-09-10 10:36发布

问题:

I have a Windows service written in C++ that needs to access the clipboard and read data from/paste data to it. I'm considering only textual data.

From MSDN's documentation, I can use OpenClipboard, EmptyClipboard and SetClipboardData to achieve what I want to.

I would have to pass NULL to OpenClipboard since I don't have any UI and hence no window handles. However, this would mean -

If an application calls OpenClipboard with hwnd set to NULL, EmptyClipboard sets the clipboard owner to NULL; this causes SetClipboardData to fail.

which would mean I can't set data on the clipboard.

What would be the correct way to get around this problem? Is it possible without using any windows?

回答1:

You definitely CAN access the clipboard from a non-GUI application. Windows even included a command-line app (clip.exe) to do it.
However, before you spend too much time working on this...... The clipboard isn't shared among users on the same system. Suppose you have two users logged in. You can't copy data from one session, switch users (from the lock screen) and paste that same data. So presumably, your service would act like another user session, and your app would only be able to see data that was copied earlier within that same instance of the service.