A quick look at your code seems to have enough security checks to catch if there's anything wrong with the device creation and setup process. I'm afraid i have no more suggestions to your problem.
The worse bug that i can actually think of is if somewhere in your code is doing a buffer overflow and overwrites your graphics device context. I'm not sure if this can be detected with the use of _CrtSetDbgFlag() and _CrtDumpMemoryLeaks() but with those security checks that you have above i doubt you're doing this mistake somewhere in your code.
I hope someone here can help you out and i'm also eager to learn what exactly is the problem with your code and its fix.