I can\'t seem to figure out how to do this, I have searched on google and found two code examples, one from a github screen capture library and another on a posting group and ne
From the OpenCV documentation
data – Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, i.e. no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, user should take care of it.
I think this is the point, using this constructor does not copy the buffer you are passing to the constructor, so you should not free this data until you no longer need the cv::Mat. Also I know next to nothing about this stuff, but why are you passing the BITMAPINFOHEADER and BITMAPFILEHEADER to your cv::Mat object, that doesn't seem right at all.
I don't know what it is, but the minute I ask a question, I get obssesed with finding the answer. Anyway, part of this issue is actually solved by the answer to this question:
OpenCV 2.0 C++ API using imshow: returns unhandled exception and "bad-flag"
In Visual C++:
go to Project->Properties (or Alt-F7) Configuration Properties->Linker->Input->Additional Dependencies
replace the usual " cv210.lib cxcore210.lib highgui210.lib" by " cv210d.lib cxcore210d.lib highgui210d.lib" - which are the debugging libraries.
highgui still shows grey and doesn't work, but reading from the HBITMAP using the above method now works. and I don't really need highgui, it was just for testing anyway.
I wrote my own function to do something similar, hopefully it can help you: How to capture the desktop in OpenCV (ie. turn a bitmap into a Mat)?