寻找屏幕分辨率会产生线程问题

本文关键字:线程 问题 屏幕 分辨率 寻找 | 更新日期: 2023-09-27 18:16:19

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

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();
        }

当我改变int WindowWidth &int WindowHeightScreen.GetBounds(Form1.ActiveForm).X or 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;
        }

寻找屏幕分辨率会产生线程问题

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

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