Search code examples
c++screenshotc++builderfiremonkeyvcl

How to take a screenshot with C++ Builder?


I know that there are a lot of answers about my question, but I never understand what I showld do.

I just need to take a screenshot of part of my Form in any OS, for example:

Take a screenshot from the position X=30 until X=80 and Y=30 until Y=200 So, in this case the image should have 50x170px, but I want a solution that works with any resolution.

The format of the image can be JPEG, GIF, PNG or BMP (Bitmap). Is just it...

Currently I'm using FMX library, but if you have a code that works with VCL I can try to change it according to my necessity. If there is another question like this please, don't take mine as a "bad question", I'm still a newbie wanting to learn aa little bit more.

PS.: I'm trying to make it with any device/OS, so I want to avoid using APIs.

Thanks a LOT!


Solution

  • FireMonkey's TForm class has a PaintTo() method. Create two TBitmap objects, pass the first bitmap's Canvas to PaintTo(), then call CopyFromBitmap() on the second bitmap specifying the coordinates you want, then you can use the second bitmap as needed. For example:

    void __fastcall TMyForm::GrabScreenshot()
    {
        TRect r(30, 30, 80, 200);
    
        TBitmap *bmp1 = new TBitmap;
        bmp1->SetSize(ClientWidth, ClientHeight);
        PaintTo(bmp1->Canvas);
    
        TBitmap *bmp2 = new TBitmap;
        bmp2->SetSize(r.Width, r.Height);
        bmp2->CopyFromBitmap(bmp1, r, 0, 0);
        delete bmp1;
    
        // use bmp2 as needed...
        delete bmp2;
    }