Search code examples
c++windowsgdi+gdi

Drawing Overlays with gdiplus


Right now I am attempting to draw overlays in gdiplus, however when I start my program it is able to locate our window but it wont draw my overlay line. Am I missing something? The documentation suggests that I should be able to do this.

#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
#include <iostream>

using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")




VOID OnPaint(HDC hdc)
{
    Graphics graphics(hdc);
    Pen pen(Color(255, 0, 0, 0), 5);
    graphics.DrawLine(&pen, 0, 0, 200, 100);
}
ULONG_PTR gdiplusToken;

int main() {

    //Untitled - Notepad
    HWND hWnd = FindWindow(NULL, TEXT("*Untitled - Notepad"));
    // In top of main
    GdiplusStartupInput gdiplusStartupInput;
    GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
    if (hWnd == 0) {
        std::cout << "[-] - Unable to locate window!\n";
        return 0;
    }
    std::cout << "[+] - Located Window, starting hook.\n";
    HDC hdc = GetDC(FindWindowA(NULL, "*Untitled - Notepad"));
    PAINTSTRUCT ps;
    hdc = BeginPaint(hWnd, &ps);
    if (hdc == ERROR) {
        std::cout << "[-] - An error occured\n";
        return 0;
    }
    OnPaint(hdc);
    Sleep(3000);
    EndPaint(hWnd, &ps);
    std::cout << "Finished Drawing\n";

}

Solution

  • You are missing a call to GdiplusStartup.

    Also, take out that BeginPaint and EndPaint call. That's just going to erase the window so you won't see what you drew.

    Here's what works:

    #include <windows.h>
    #include <objidl.h>
    #include <gdiplus.h>
    #include <iostream>
    
    using namespace Gdiplus;
    #pragma comment (lib,"Gdiplus.lib")
    VOID OnPaint(HDC hdc)
    {
        Graphics graphics(hdc);
        Pen pen(Color(255, 0, 0, 0), 5);
        graphics.DrawLine(&pen, 0, 0, 200, 100);
    }
    
    int main() {
    
    
        // GDI+ startup incantation
        GdiplusStartupInput gdiplusStartupInput;
        ULONG_PTR gdiplusToken;
        GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
    
        //Untitled - Notepad
        HWND hWnd = FindWindow(NULL, TEXT("Untitled - Notepad"));
        if (hWnd == 0) {
            std::cout << "[-] - Unable to locate window!\n";
            return 0;
        }
        std::cout << "[+] - Located Window, starting hook.\n";
        HDC hdc;
        hdc = GetDC(hWnd);
        std::cout << hdc;
        OnPaint(hdc);
        std::cout << "Finished Drawing\n";
    
    }
    

    Proof:

    enter image description here