I have a C# WinForms application and when I give the executable to different users the application displays in different sizes (based on their screen resolution). Some of the parts of the application can't be seen.
how can I set absolute 1280X800 for my forms and make sure that the form size will not be changed whatever resolution is!
You can use Control.ScaleControl and Control.Scale
private void MainForm_Load( object sender, EventArgs e )
{
float width_ratio = (Screen.PrimaryScreen.Bounds.Width / 1280);
float heigh_ratio = (Screen.PrimaryScreen.Bounds.Height / 800f);
SizeF scale = new SizeF(width_ratio, heigh_ratio);
this.Scale(scale);
//And for font size
foreach (Control control in this.Controls)
{
control.Font = new Font("Microsoft Sans Serif", c.Font.SizeInPoints * heigh_ratio * width_ratio);
}
}
Hope this helps.
Use the MaximumSize property of the form.
form.MaximumSize = new Size(1280, 800);
You can also set a MinimumSize if you don't want the user to make it smaller than a desired size.
You can instead design the GUI so it scrolls up and down more easily.You can make use of the following
Layout Managers
Docking
Anchors
The property
Screen.PrimaryScreen.WorkingArea
is very useful for form sizing and positioning. For example this code:
this.Width = Screen.PrimaryScreen.WorkingArea.Width/2;
this.Height = Screen.PrimaryScreen.WorkingArea.Height/2;
this.Top = (Screen.PrimaryScreen.WorkingArea.Top + Screen.PrimaryScreen.WorkingArea.Height)/4;
this.Left = (Screen.PrimaryScreen.WorkingArea.Left + Screen.PrimaryScreen.WorkingArea.Width)/4;
will place the form in which it is executed in the middle of the screen and size it to half the screen.
The WorkingArea var is used to exclude stuff like the task bar and other docked items on the desktop when calculating the size of the screen.
Hope this helps.
Related
I have a dynamic window with labels on it. The window is a HUD and changes size depending on its parent window. However, one of the labels becomes distorted when resized.
The font of the labels are resized according to the screen size like so:
float fontSize = this.Width / 128 /getScalingFactor();
and the scaling factor is calculated as follows:
//Gets the scaling factor of the current dpi settings
protected float getScalingFactor()
{
Graphics g = Graphics.FromHwnd(IntPtr.Zero);
IntPtr desktop = g.GetHdc();
int LogicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.VERTRES);
int PhysicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.DESKTOPVERTRES);
int logpixelsy = GetDeviceCaps(desktop, (int)DeviceCap.LOGPIXELSY);
float screenScalingFactor = (float)PhysicalScreenHeight / (float)LogicalScreenHeight;
float dpiScalingFactor = (float)logpixelsy / (float)96;
return dpiScalingFactor; // 1.25 = 125%
//return screenScalingFactor;
}
And the designer code for the labels. There are labels that holds numbers as well and they are using identical settings. However, they don't get distorted but the username label does.
this.labelUsername.AutoSize = true;
this.tableLayoutPanel1.SetColumnSpan(this.labelUsername, 2);
this.labelUsername.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelUsername.ForeColor = System.Drawing.Color.White;
this.labelUsername.Location = new System.Drawing.Point(3, 0);
this.labelUsername.Name = "labelUsername";
this.labelUsername.Size = new System.Drawing.Size(56, 14);
this.labelUsername.TabIndex = 3;
this.labelUsername.Text = "Username";
this.labelUsername.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
I've tried changing some numbers of the font size and scaling factor. I've tried changing some of the settings in the designer code as well. Unfortunately no success so far.
Maybe someone recognize the issue and can point me to what causes this. I'm assuming there is some mis-match with the label and window DPI perhaps. But that doesn't explain why the numbers doesn't get the same problem.
First a clarification. I'm building on a open source project which I'm not 100% familiar with.
So after poking around some more I realized that there is another function which also controls the HUD colors. Unless I added a forecolor to my label there as well, I got that distorted looking text.
I'm assuming that this method is called everytime the window is resizing and when my label wasn't updated with a color there, it got a transparent color. However, because the forecolor had been set at startup it showed as a border around the transparent text because it wasn't resized.
I have a label with text inside i can change the label size or the label font size each time and check many times but maybe there is a way to calculate it:
label18.Text = "מכם מזג האוויר איננו פעיל כרגע";
This is how i see the text now:
The text in red is in hebrew this is the text i want to change it's size and also to put it in the middle according to the picturebox1 top not on the left like it is now.
And i did a black circle just to show what i mean by " the distance from the top of pictureBox1 and almost the top of form1 ".
I mean this gray area from the above the pictureBox1 and the form1 white area on the top only this gray area i want to make the text in this height and in the middle.
How can i calculate this two values ?
I tried this but it's not in the exact middle:
SizeF size = label18.CreateGraphics().MeasureString(label18.Text, label18.Font);
label18.Left = (pictureBox1.Width / 2) - (((int)size.Width) / 2) + pictureBox1.Left;
label18.Top = pictureBox1.Top - 20;
You don't need graphics or to measure anything. Just set in designer text align = middlecenter and autosize = true
label18.Location = new Point(pictureBox1.Location.X + (pictureBox1.Width / 2 - label18.Width / 2,
pictureBox1.Location.Y - label18.Height);
To center a label you need it get it actual size, then to center it using another control use some simple math to get the coordinate for the control (see below Example 1). I don't know what control the grey bar is but you could center in that by using the size.Width property and doing the same type of calculation.
If you want to fill the grey bar I have added Example 2.
Example 1:
private void CenterLabel()
{
//get the size of the text (you could do this before hand if needed)
SizeF size = label18.CreateGraphics().MeasureString(label18.Text, label18.Font);
//center over picture box control and slightly above
label18.Left = (pictureBox1.Width / 2) - (((int)size.Width) / 2) + pictureBox1.Left;
label18.Top = pictureBox1.Top - 20;
}
Example 2
private void CenterLabel()
{
int fontHeightPixels = (int)(greyBar.Height * .85);
Font font = new System.Drawing.Font("Arial", fontHeightPixels, FontStyle.Regular, GraphicsUnit.Pixel);
string text = "I am centered";
//get the size of the text (you could do this before hand if needed)
SizeF size = label18.CreateGraphics().MeasureString(text, font);
label18.Font = font;
label18.Text = text;
//center over picture box control and slightly above
label18.Left = (pictureBox1.Width / 2) - (((int)size.Width) / 2) + pictureBox1.Left;
label18.Top = (greyBar.Height / 2) - (((int)size.Height) / 2) + greyBar.Top;
}
This is relatively simple with Windows forms:
Dock your label to the top of the form by setting the appropriate property in the Forms designer. The property you want to set is Dock and it should be set to Top.
Change the label's AutoSize property to false.
Change the label's height as desired.
Change the label's TextAlign property to MiddleCentre.
That should do it.
There's more then one way to achieve this goal.
I would suggest the following:
First calculate the width of the picturebox (picturebox.Width)
Find the coordinates on the form where the picturebox resides (picturebox.Location) property of the picturebox)
Then you change the location of your label control --> to Label.Location.X = (picturebox.Width /2) and Label.Location.Y = picturebox.Location.Y ==> now you have the label correctly placed .
Next Set the Height of the Label Control to the Top(distance between the edge of the form and picturebox) value of the Picturebox.
No visual studion from where i am typing so cannot do full code example.
You're done.
I have the following function in my WPF application that I use to resize a window to the primary screen's working area (the whole screen minus the taskbar):
private void Window_Loaded(object sender, RoutedEventArgs e)
{
int theHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
int theWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
this.MaxHeight = theHeight;
this.MinHeight = theHeight;
this.MaxWidth = theWidth;
this.MinWidth = theWidth;
this.Height = theHeight;
this.Width = theWidth;
this.Top = 0;
this.Left = 0;
}
This works very well, as long as the machine's DPI is set at 100%. However, if they have the DPI set higher, then this doesn't work, and the window spills off the screen. I realize that this is because WPF pixels aren't the same as "real" screen pixels, and because I'm using a WinForms property to get the screen dimensions.
I don't know of an WPF equivalent to Screen.PrimaryScreen.WorkingArea. Is there something I can use for this that would work regardless of DPI setting?
If not, then I guess I need to some sort of scaling, but I'm not sure how to determine how much to scale by.
How can I modify my function to account for different DPI settings?
By the way, in case you're wondering why I need to use this function instead of just maximizing the window, it's because it's a borderless window (WindowStyle="None"), and if you maximize this type of window, it covers the taskbar.
You get the transformed work area size from the SystemParameters.WorkArea property:
Top = 0;
Left = 0;
Width = System.Windows.SystemParameters.WorkArea.Width;
Height = System.Windows.SystemParameters.WorkArea.Height;
In WPF, you can use the SystemParameters.PrimaryScreenWidth and SystemParameters.PrimaryScreenHeight properties to find out the primary screen dimensions:
double width = SystemParameters.PrimaryScreenWidth;
double height = SystemParameters.PrimaryScreenHeight;
If you wanna get the dimensions of both Screens you simply can use:
var primaryScreen =
System.Windows.Forms
.Screen
.AllScreens
.Where(s => s.Primary)
.FirstOrDefault();
var secondaryScreen =
System.Windows.Forms
.Screen
.AllScreens
.Where(s => !s.Primary)
.FirstOrDefault();
After this you can reach Width, Height etc. by using
primaryScreen.Bounds.Width
So Long ;)
I work on VS 2008 with C#. This below code does not work for me. My form was designed in 1024 x 768 resolution.
Our clients laptop is in 1366 x 768 resolution. To solve this problem, I set below code in Form Load event:
this.Location = new Point(0, 0);
this.Size = Screen.PrimaryScreen.WorkingArea.Size;
but the form does not resize as per screen resolution and bottom of my form gets hidden or cut or I miss the scroll bar.
Is there any way to solve this problem? Please show me the syntax.
Can't you start maximized?
Set the System.Windows.Forms.Form.WindowState property to FormWindowState.Maximized
If you want to set the form size programmatically, set the form's StartPosition property to Manual. Otherwise the form's own positioning and sizing algorithm will interfere with yours. This is why you are experiencing the problems mentioned in your question.
Example: Here is how I resize the form to a size half-way between its original size and the size of the screen's working area. I also center the form in the working area.
On computers with multiple monitors, the user probably expects the form to open on the same screen that the mouse pointer is on. We can get it with Screen.FromPoint(Cursor.Position).
public MainView()
{
InitializeComponent();
StartPosition = FormStartPosition.Manual;
Rectangle screen = Screen.FromPoint(Cursor.Position).WorkingArea;
int w = Width >= screen.Width ? screen.Width : (screen.Width + Width) / 2;
int h = Height >= screen.Height ? screen.Height : (screen.Height + Height) / 2;
Location = new Point(screen.Left + (screen.Width - w) / 2, screen.Top + (screen.Height - h) / 2);
Size = new Size(w, h);
}
Note that setting WindowState to FormWindowState.Maximized alone does not change the size of the restored window. So the window might look good as long as it is maximized, but when restored, the window size and location can still be wrong. So I suggest setting size and location even when you intend to open the window as maximized.
Probably a maximized Form helps, or you can do this manually upon form load:
Code Block
this.Location = new Point(0, 0);
this.Size = Screen.PrimaryScreen.WorkingArea.Size;
And then, play with anchoring, so the child controls inside your form automatically fit in your form's new size.
Set the form property to open in maximized state.
this.WindowState = FormWindowState.Maximized;
int h = Screen.PrimaryScreen.WorkingArea.Height;
int w = Screen.PrimaryScreen.WorkingArea.Width;
this.ClientSize = new Size(w , h);
You can simply set the window state
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
simply set Autoscroll = true for ur windows form.. (its not good solution but helpful)..
try for panel also(Autoscroll property = true)
You can always tell the window to start in maximized... it should give you the same result... Like this: this.WindowState = FormWindowState.Maximized;
P.S. You could also try (and I'm not recommending this) to subtract the taskbar height.
I have noticed that some applications change their controls' positions to fit themselves as much as possible in the current resolution. For example, if the window is maximized, the controls are set in such a way that the overall GUI looks balanced.
Is it possible to make or implement this functionality in Visual studio 2010 using C#?
Use Dock and Anchor properties. Here is a good article. Note that these will handle changes when maximizing/minimizing. That is a little different that if the screen resolution changes, but it will be along the same idea.
Use combinations of these to get the desired result:
Set Anchor property to None, the controls will not be resized, they only shift their position.
Set Anchor property to Top+Bottom+Left+Right, the controls will be resized but they don't change their position.
Set the Minimum Size of the form to a proper value.
Set Dock property.
Use Form Resize event to change whatever you want
I don't know how font size (label, textbox, combobox, etc.) will be affected in (1) - (4), but it can be controlled in (5).
float widthRatio = Screen.PrimaryScreen.Bounds.Width / 1280;
float heightRatio = Screen.PrimaryScreen.Bounds.Height / 800f;
SizeF scale = new SizeF(widthRatio, heightRatio);
this.Scale(scale);
foreach (Control control in this.Controls)
{
control.Font = new Font("Verdana", control.Font.SizeInPoints * heightRatio * widthRatio);
}
..and to detect a change in resolution to handle it (once you're using Docking and Anchoring like SwDevMan81 suggested) use the SystemEvents.DisplaySettingsChanged event in Microsoft.Win32.
sorry I saw the question late,
Here is an easy programmatically solution that works well on me,
Create those global variables:
float firstWidth;
float firstHeight;
after on load, fill those variables;
firstWidth = this.Size.Width;
firstHeight = this.Size.Height;
then select your form and put these code to your form's SizeChange event;
private void AnaMenu_SizeChanged(object sender, EventArgs e)
{
float size1 = this.Size.Width / firstWidth;
float size2 = this.Size.Height / firstHeight;
SizeF scale = new SizeF(size1, size2);
firstWidth = this.Size.Width;
firstHeight = this.Size.Height;
foreach (Control control in this.Controls)
{
control.Font = new Font(control.Font.FontFamily, control.Font.Size* ((size1+ size2)/2));
control.Scale(scale);
}
}
I hope this helps, it works perfect on my projects.
Here I like to use https://www.netresize.net/index.php?c=3a&id=11#buyopt. But it is paid version.
You also can get their source codes if you buy 1 Site License (Unlimited Developers).
How ever I am finding the nuget package solution.
add this code at page load do for all control or add all control in containers
int x;
Point pt = new Point();
x = Screen.PrimaryScreen.WorkingArea.Width - 1024;
x = x / 2;
pt.Y = groupBox1.Location.Y + 50;
pt.X = groupBox1.Location.X + x;
groupBox1.Location = pt;
in the form load event add this line
this.WindowState = FormWindowState.Maximized;
private void MainForm_Load( object sender, EventArgs e )
{
this.Size = Screen.PrimaryScreen.WorkingArea.Size
}
this.WindowState = FormWindowState.Maximized;