如何在 c# 中转换这段代码以使其在 c++ 中工作?

问题描述

我的目标是使用 c++/cli 捕获 windows 窗体的屏幕。下面是捕获窗口的代码,但是,它是用 C# 编写的。我必须对代码进行哪些更改才能在 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,s);

我的尝试: 我已经尝试在 C++ 中使用下面的代码,但是,我在 ** ** 中的部分出现错误错误表示预期为 ;尺寸后,即尺寸; s = 这个->大小;这对我来说没有意义

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,s);

解决方法

您的代码看起来基本正确。

  • 我认为 Size s 被混淆了,因为 Size 既是类型的名称,也是该对象上的属性的名称。它认为您正在尝试检索 Size 属性并丢弃结果。要解决此问题,请使用声明类型的全名:System.Drawing.Size s = this->Size;。 (您也可以使用 auto,或完全删除局部变量,只需多次调用 this->Size。)
  • System.Drawing.Size 是一个值结构,而不是一个引用类。它是值类型,而不是引用类型,因此您需要执行 s.Widths.Height
    • 这类似于 Location:Location 返回一个 Point,它是一种值类型,并且您已经在执行 Location.X,而不是 Location->X