我试图找到我以前轻松完成的显示器的分辨率,但是当我尝试在这里使用它时会突然产生:
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 WindowHeight
至Screen.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;
}
答案 0 :(得分:2)
在构造函数中,表单尚未显示,因此Form.ActiveForm
可能不是您的表单。其次,请使用Screen.WorkingArea
,除非您要忽略任务栏等。
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
Size resolution = Screen.FromControl(this).WorkingArea.Size;
}