【问题标题】:How to get pixel in C without generating any trash [closed]如何在C中获取像素而不产生任何垃圾[关闭]
【发布时间】:2020-06-07 05:16:32
【问题描述】:

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

【问题讨论】:

  • "它使用 audiodg.exe 产生了大量的垃圾" - 你能详细说明一下吗?我看不出GetPixel()audiodg.exe 是如何连接的。 垃圾是什么意思?
  • 当你使用 graphics.h 函数时,它会调用 audiodg.exe,但我不知道如何摆脱它产生的垃圾。例如,要调用 GetPixel,我需要调用 GetDC,它将内存分配给句柄(void*)。有 ReleaseDC,但我正在打电话,但它没有释放垃圾。我需要知道 windows.h 并且知道如何使用 DeleteObject、DeleteDC、ReleaseDC 的人的帮助......关于如何使用这些功能的内容少得惊人!所以,audiodg.exe 是一个程序,当您使用 graphics.h 函数并执行所要求的内容时调用它。

标签: c++ c performance graphics recycle-bin


【解决方案1】:

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);
}

【讨论】:

    猜你喜欢
    • 2011-07-26
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 2016-04-29
    相关资源
    最近更新 更多