'Get Form1 properties from class
I want to be able to get Form1 properties from within a class. Properties such as Width, Left, WindowState, and so on. So that I can then do this in the class: MessageBox.Show(Form1.Width); So I want to reference the whole Form1. How do I do that in code?
Solution 1:[1]
Example 1: Storing the instance in a global variable,
public static Form1 frm1;
//Form1 constructor
frm1 = this;
e.g.
public static Form1 frm1;
public Form1()
{
InitializeComponent();
frm1 = this;
MessageBox.Show(Form1.frm1.Width.ToString());
}
Example 2: You need to pass an instance to the class.
public class Class1
{
private Form1 _frm1;
public Class1(Form1 frm1)
{
this._frm1 = frm1;
}
}
e.g.
public class Class1
{
private Form1 _frm1;
public Class1(Form1 frm1)
{
this._frm1 = frm1;
MessageBox.Show(this._frm1.Width.ToString());
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |