C# 查找屏幕分辨率会产生线程问题

C# 查找屏幕分辨率会产生线程问题,c#,windows,winforms,C#,Windows,Winforms,我试图找到显示器的分辨率,我以前很容易做到这一点,但当我尝试在这里使用它时,它突然产生: Exception thrown: 'System.InvalidOperationException' in System.Windows.Forms.dll Additional information: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was cr

我试图找到显示器的分辨率,我以前很容易做到这一点,但当我尝试在这里使用它时,它突然产生:

Exception thrown: 'System.InvalidOperationException' in System.Windows.Forms.dll

Additional information: Cross-thread operation not valid: Control ''
accessed from a thread other than the thread it was created on.

If there is a handler for this exception, the program may be safely continued.
以下是我的项目代码:

public partial class Form1 : Form
{
    //Global Variables/Objects
    int SelectedTool = 1, WindowWidth, WindowHeight; //Here I create the variables 
    bool isMouseDown = false;
    Pen UserPen = new Pen(Color.Black, 10);
    Graphics CanvasGraphics;
    Point LastMousePosition = new Point(0, 0);

    //Initialize Components
    public Form1()
    {
        InitializeComponent();

        //Find Screen Resolution
        WindowWidth = Screen.GetBounds(Form1.ActiveForm).X; //Problem Occurs Here
        WindowHeight = Screen.GetBounds(Form1.ActiveForm).Y; // And Here

            //Set Siz    
            Form1.ActiveForm.MaximumSize = new Size(WindowWidth, WindowHeight);

            //Create Graphics Object
            CanvasGraphics = canvas.CreateGraphics();
            CanvasGraphics.Clear(Color.White);

            //Start Threads
            Painter.RunWorkerAsync();
            Updater.RunWorkerAsync();

            label1.Text = Form1.ActiveForm.Location.X.ToString();
        }
当我将
intwindowwidth
intwindowheight
的值更改为
Screen.GetBounds(Form1.ActiveForm).X或Y

我也尝试过其他方法来寻找解决方案,但没有任何效果。我认为我做错了什么,导致了这个错误,但问题背后的原因是我无法理解的

更改后:

private void Form1_SizeChanged(object sender, EventArgs e) //Resize Window
        {
            Form1.ActiveForm.Size = new Size(WindowWidth, WindowHeight); //Doesn't Work
        }
        private void Form1_Activated(object sender, EventArgs e) //Form Activated
        {
        WindowWidth = Screen.FromControl(this).WorkingArea.Size.Width;
        WindowHeight = Screen.FromControl(this).WorkingArea.Size.Height;
        }

在构造函数中,表单尚未显示,因此
表单.ActiveForm
可能不是您的表单。其次,使用
Screen.WorkingArea
,除非您想忽略任务栏等

protected override void OnShown(EventArgs e)
{
    base.OnShown(e);
    Size resolution = Screen.FromControl(this).WorkingArea.Size;
}

表单还没有完全初始化,这意味着它到现在还没有激活,您正在尝试查找高度和宽度。在
Form\u activated()上尝试此操作event@MohitShrivastava,这将是表单的
显示
事件,在第一次显示表单后立即引发一次。这是一件小事,但访问派生类型上的静态成员是错误的
ActiveForm
Form
类的静态属性,因此应该在
Form
类上调用它。@jmchilney:您完全正确
显示的
将是正确的事件,因为它只调用一次。现在我无法编辑我的评论:好吧,这管用!我刚想出来。谢谢大家。