如何在不产生任何垃圾的情况下获得C中的像素

How to get pixel in C without generating any trash

本文关键字:情况下 像素 任何垃      更新时间:2023-10-16

我需要每秒至少检查五次屏幕上的四个像素。此外,这些像素不在应用程序中。如果可能的话,我想要一个不使用任何外部库的解决方案(换句话说,使用graphics.h、windows.h或winusers.h(。如果该解决方案使用C++库也没关系。我试着使用GetPixel((,但它在audiodg.exe中产生了大量垃圾。如果你知道SFML或其他外部库的解决方案,请在这里回答。

以下是如何使用GetPixel()

#include <Windows.h>
#include <iomanip>
#include <iostream>
void disp_colorref(COLORREF c) {
std::cout << std::setw(2) << static_cast<unsigned>(GetRValue(c)) 
<< std::setw(2) << static_cast<unsigned>(GetGValue(c))
<< std::setw(2) << static_cast<unsigned>(GetBValue(c));
}
int main()
{
HDC dt = GetDC(nullptr);          // get screen DC
if (dt == nullptr) return 1;      // error getting DC
COLORREF c = GetPixel(dt, 0, 0);  // get the pixel color at  0, 0
if (c == CLR_INVALID) return 2;   // error getting pixel
std::cout << std::hex;
disp_colorref(c);                 // display the pixel's RGB value
ReleaseDC(nullptr, dt);           // release the DC
}

但是,如果GetPixel失败,上面的内容将泄漏DC资源,因此您可以将资源放入RAII包装中,这样在处理完ReleaseDC后也无需手动调用它。示例:

#include <Windows.h>
#include <iomanip>
#include <iostream>
#include <utility>
// a RAII wrapper for a HDC
class dc_t {
public:
dc_t(HDC DC) : 
dc(DC) 
{
if (dc == nullptr) throw std::runtime_error("invalid DC");
}
dc_t(const dc_t&) = delete;
dc_t(dc_t&& rhs) noexcept :
dc(std::exchange(rhs.dc, nullptr))
{}
dc_t& operator=(const dc_t&) = delete;
dc_t& operator=(dc_t&& rhs) noexcept {
dc = std::exchange(rhs.dc, nullptr);
return *this;
}
~dc_t() {
if(dc) ReleaseDC(nullptr, dc);
}
operator HDC () { return dc; }
private:
HDC dc;
};
void disp_colorref(COLORREF c) {
std::cout << std::setw(2) << static_cast<unsigned>(GetRValue(c)) 
<< std::setw(2) << static_cast<unsigned>(GetGValue(c))
<< std::setw(2) << static_cast<unsigned>(GetBValue(c));
}
int main()
{
dc_t dt = GetDC(nullptr);
COLORREF c = GetPixel(dt, 0, 0);
if (c == CLR_INVALID) return 2;
std::cout << std::hex;
disp_colorref(c);
}
相关文章: