C++ 的 GetScreenSize 函数; “没有合适的用户定义转换”Winforms

问题描述

尝试用 C++ 编写一个 Winforms 程序,到目前为止一切正常,虽然我无法自动获取屏幕大小,有没有人知道如何解决这个问题?

  // Utility to get screen size of the user using the application
  public:
      static int GetScreenSize() 
      {
          int x_min,y_min,x_max,y_max;
          x_min = y_min = int::MaxValue;
          x_max = y_max = int::MaxValue;

          for each(Screen screen in Screen::AllScreens)
          {
              // equiv of 'var' (C#) is 'auto' in C++
              auto bounds = screen.Bounds;
              x_min = Math::Min(x_min,bounds.X);
              y_min = Math::Min(y_min,bounds.Y);
              x_max = Math::Max(x_max,bounds.X);
              y_max = Math::Max(y_max,bounds.Y);
          }
      }

Automatic Screen size function

Error; "no suitable user-defined conversion from "System::Windows::Forms::Screen ^" to "System::Windows::Forms::Screen" exists"

解决方法

正如其他人所建议的,我们应该使用 Screen^ screen 替换 Screen screen 来解决错误。

您可以尝试以下代码来获取使用该应用程序的用户的屏幕尺寸。

public:
        static String^ GetScreenSize()
        {
            int x_min,y_min,x_max,y_max;
            x_min = y_min = int::MaxValue;
            x_max = y_max = int::MaxValue;

            for each (Screen^ screen in Screen::AllScreens)
            {
                // equiv of 'var' (C#) is 'auto' in C++
                auto bounds = screen->Bounds;
                x_min = Math::Min(x_min,bounds.X);
                y_min = Math::Min(y_min,bounds.Y);
                x_max = Math::Max(x_max,bounds.X);
                y_max = Math::Max(y_max,bounds.Y);
            }
            String^ result= String::Format("X min is {0},Y min is {1},X max is {2},Y max is {3}",x_min,y_max);
            return result;
        }
#pragma endregion
    private: System::Void button1_Click(System::Object^ sender,System::EventArgs^ e) {
        String^ result=GetScreenSize();
        MessageBox::Show(result);
    }

注意:我把返回类型从int改为string,这样就可以得到结果了。

结果:

enter image description here