Search code examples
c++-cli

Do screenshot in C++/CLI


I use windows 7 and VS2010. I write a piece of C++/CLI code to do measurements, during which I want to make screenshot.

I have tried screenshot method in C++ (using GDI library), but failed to compile the file. So I suppose the GDI library could not be used in C++/CLI. How to do screenshot and paste to a word in C++/CLI project?

Here is the code:

#include "stdafx.h"

using namespace System;
using namespace System::IO;

int main(array<System::String ^> ^args)
{

String^ fileName = "AP_result.doc";

StreamWriter^ sw = gcnew StreamWriter(fileName);
 ...
sw->Close();
 return 0;
}

I have tried Slawomir Orlowski's method but error occurs:

error


Solution

  • C++/CLI code for screen shot:

    using namespace System;
    using namespace System::Windows;
    using namespace System::Windows::Forms;
    using namespace System::Drawing;
    using namespace System::Drawing::Imaging;
    
    
    int main(array<System::String ^> ^args)
    {
        Screen^ r = System::Windows::Forms::Screen::PrimaryScreen;
        int width = r->Bounds.Width;
        int height = r->Bounds.Height;
    
        Bitmap^ bmp = gcnew Bitmap(width, height, PixelFormat::Format32bppArgb);
        Graphics^ screen = Graphics::FromImage(bmp);
        screen->CopyFromScreen(0,0,0,0, Size(width, height), CopyPixelOperation::SourceCopy);
        bmp->Save("screenshot.bmp");      
        return 0;
    }
    

    In your project you have to add few references: System.Drawing, System.Windows, System.Windows.Forms.