vbams-accessoperating-systemwindows-10clipboard

Why does VBA code example on Microsoft's website destroy the clipboard for the rest of the computer?


I was trying to learn how to use the Windows API in Visual Basic to use system calls. This tutorial shows how to use the clipboard to retrieve text that the user copied with Ctrl+C.

Out of curiosity, and under the assumption that all user input is bad input, I tried pressing Print Screen and then running the code to see what would happen. I got some error message (can't remember what) but the clipboard no longer worked. Any attempt to paste after a cut or copy, either did nothing or returned an error message in the program being used.

Why did this happen? I did reboot and that fixed it.

Yes, it's my fault for intentionally trying to break the code example, but let's be honest - there's no excuse for the OS to fall apart so easily. I'm running Windows 10.

Settings won't let me clear the clipboard, and when I try to view the clipboard history, it shows nothing is there. Unfortunately I wasn't able to screenshot the clipboard history because it closes by itself when I try to open Snipping Tool. enter image description here


Solution

  • Sounds like you've missed a CloseClipboard(), keeping the clipboard locked since Windows thinks a program is reading to it or writing from it. This will prevent other programs from working with the clipboard, since only one program can access it at a time. If Access is still open, you can try running CloseClipboard in the immediate window, else, I recommend a reboot.

    On code like this, always add an error handler that calls CloseClipboard() to prevent leaving the clipboard open if something unexpected happens. Note that when working with WinAPI, you might encounter hard crashes that may not call the error handler, so always triple-check your pointers and expect crashes and reboots.

    The code you've found is also not adjusted for 64-bit use, so beware. If you've got it to work by just slapping PtrSafe on the functions, you may end up with invalid pointers which can crash Access, leaving the clipboard open and unusable.

    The code you've found, while written by Microsoft, is not of particularly good quality. I recommend first checking if there's text on the clipboard using EnumClipboardFormats, then only requesting text if there actually is text on the clipboard.

    Beware that using WinAPI through VBA is tough, it's not beginner stuff, especially regarding the clipboard.

    Note that there's no excuse for the OS to fall apart so easily is not the attitude to have when working with WinAPI. You're directly interfacing with the OS without any of the securities that managed languages offer, and manually working with pointers. It can and will break if you do something invalid. There's a reason most people use libraries that abstract the dangerous stuff away, if you don't, all bets are off.