Search code examples
visual-studioc++-cli

How do I convert this piece of code in c# to make it work in c++?


my aim is to capture the screen of a windows form using c++/cli. Below is the code to capture the window, however, it is in C#. What changes do I have to make to the code for it to work in c++?

Graphics myGraphics = this.CreateGraphics();
       Size s = this.Size;
       memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
       Graphics memoryGraphics = Graphics.FromImage(memoryImage);
       memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);

What I've tried: I've tried using the code below in c++, however, I get errors for the part in ** **. The error says expected a ; after Size i.e. Size; s = this->Size; which does not make sense to me

Graphics^ myGraphics = this->CreateGraphics();
    Size **s** = this->Size;
    memoryImage = gcnew Bitmap(**s**->Width, s->Height, myGraphics);
    Graphics^ memoryGraphics = Graphics::FromImage(memoryImage);
    memoryGraphics->CopyFromScreen(this->Location.X, this->Location.Y, 0, 0, s);

Solution

  • Your code looks mostly correct.

    • I think that Size s is getting confused because Size is both the name of a type, and the name of a property on this object. It thinks you're trying to retrieve the Size property and throw away the result. To fix this, use the full name of the type for the declaration: System.Drawing.Size s = this->Size;. (You could also use auto, or remove the local variable entirely and just call this->Size several times.)
    • System.Drawing.Size is a value struct, not a ref class. It's a value type, not a reference type, so you need to do s.Width and s.Height.
      • This is similar to Location: Location returns a Point, which is a value type, and you're already doing Location.X, not Location->X.