Four methods in static class MyForms.cs (1) center and size a form (2) center a control on a form (3) center a control horizontally only on a form (4) change the font and font style of a control
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Drawing; | |
using System.Windows.Forms; | |
namespace com.williambryanmiller.forms { | |
class MyForms { | |
public static void centerAndSizeForm(Form f, int frm_width, int frm_height) { | |
/* Note: you may still need to set properties for .Show() and .TopMost if | |
you are going to be showing multiple forms simultaneously | |
SAMPLE USAGE: | |
* | |
MyForms.centerAndSizeForm(this, 600, 400); | |
Form f2 = new Form(); | |
f2.Text = "Form 2"; | |
f2.Show(); | |
MyForms.centerAndSizeForm(f2, 500, 300); | |
f2.TopMost = true; | |
Form f3 = new Form(); | |
f3.Text = "Form 3"; | |
f3.Show(); | |
MyForms.centerAndSizeForm(f3, 400, 200); | |
f3.TopMost = true; | |
Form f4 = new Form(); | |
f4.Text = "Form 4"; | |
f4.Show(); | |
MyForms.centerAndSizeForm(f4, 300, 130); | |
f4.TopMost = true; | |
* | |
*/ | |
f.Size = new Size(frm_width, frm_height); | |
System.Windows.Forms.Screen src = System.Windows.Forms.Screen.PrimaryScreen; | |
int src_height = src.Bounds.Height; | |
int src_width = src.Bounds.Width; | |
//put the form in the center of the screen | |
f.Left = (src_width - frm_width) / 2; | |
f.Top = (src_height - frm_height) / 2; | |
} | |
public static void centerCtrlOnForm(Form f, Control c) { | |
//centers a control on a form, both vertically and horizontally | |
int x = (f.Width - c.Width) / 2; | |
int y = (f.Height - c.Height) / 2; | |
c.Location = new Point(x, y); | |
} | |
public static void centerCtrlOnFormHorizontally(Form f, Control c) { | |
int x = (f.Width - c.Width) / 2; | |
c.Location = new Point(x, c.Location.Y); | |
} | |
public static void setFontOfControl(Control c, string fontname, int fontsize, bool bold, bool italics) { | |
FontStyle fs = new FontStyle(); | |
if (bold) { | |
if (italics) { | |
fs = FontStyle.Bold | FontStyle.Italic; | |
} else { | |
fs = FontStyle.Bold; | |
} | |
} else { | |
if (italics) { | |
fs = FontStyle.Italic; | |
} else { | |
fs = FontStyle.Regular; | |
} | |
} | |
// Surround the following with a try-catch, because user may pass invalid parameter for fontname or fontsize | |
try { | |
Font myFnt = new Font(fontname, fontsize, fs); | |
c.Font = myFnt; | |
} catch (Exception ex) { | |
MessageBox.Show(ex.Message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment