Centering OK button within a MessageBox in winforms - c#

I am learning C#, and as a part of it I wrote small app that consists of form with two groups of buttons, two buttons each. Button for closing of app is added as well. And everything works ok. Also there is MessageBox, showing that the app is going to be closed. And here is little problem that bugs me: OK button within that MessageBox is NOT centered horizontally. I guess there is a method to align that button, but what puzzles me is why it's is not centered by default? As illustration here are screenshots:
Here is code as well:
using System;
using System.Drawing;
using System.Windows.Forms;
public class myForm : Form
{
private GroupBox gboxGrp1;
private GroupBox gboxGrp2;
private RadioButton butn1a;
private RadioButton butn1b;
private RadioButton butn2a;
private RadioButton butn2b;
private Button btnClose;
public myForm()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.btnClose = new Button();
this.gboxGrp1 = new GroupBox();
this.gboxGrp2 = new GroupBox();
this.butn1a = new RadioButton();
this.butn1b = new RadioButton();
this.butn2a = new RadioButton();
this.butn2b = new RadioButton();
//myForm
this.Text = "My Form";
this.StartPosition = FormStartPosition.CenterScreen;
this.Height = 350;
this.Width = 200;
//btnClose
this.Controls.Add(btnClose);
this.btnClose.Text = "Close";
this.btnClose.Location = new Point(60, 260);
this.btnClose.Click += new EventHandler(btnClose_Click);
//gboxgrp1
this.gboxGrp1.Location = new Point(20, 20);
this.gboxGrp1.Text = "Group Box 1";
this.gboxGrp1.Width = 150;
this.gboxGrp1.Height = 100;
//gboxgrp2
this.gboxGrp2.Text = "Group Box 2";
this.gboxGrp2.Location = new Point(20, 130);
this.gboxGrp2.Width = 150;
this.gboxGrp2.Height = 100;
//Radio buttons
this.butn1a.Text = "Radio 1a";
this.butn1a.Location = new Point(30, 30);
this.butn1a.Size = new Size(90, 15);
this.butn1b.Text = "Radio 1b";
this.butn1b.Location = new Point(30, 60);
this.butn1b.Size = new Size(90, 15);
this.butn2a.Text = "Radio 2a";
this.butn2a.Location = new Point(30, 30);
this.butn2a.Size = new Size(90, 15);
this.butn2b.Text = "Radio 2b";
this.butn2b.Location = new Point(30, 70);
this.butn2b.Size = new Size(90, 15);
//Controls
this.Controls.Add(gboxGrp1);
this.Controls.Add(gboxGrp2);
this.gboxGrp1.Controls.Add(butn1a);
this.gboxGrp1.Controls.Add(butn1b);
this.gboxGrp2.Controls.Add(butn2a);
this.gboxGrp2.Controls.Add(butn2b);
}
private void btnClose_Click(object sender, EventArgs e)
{
MessageBox.Show("Closing Application");
Application.Exit();
}
}
public class MyApp
{
public static void Main()
{
Application.Run(new myForm());
}
}

You can't restyle the default MessageBox as that's completely depends on the windows OS theme. However you could create your own message box by simply creating a new form and then call it by using newMessagebox.ShowDialog();

Related

How to create custom message in C#?

I am design a custom message box. This message box will show a list of string. But it's not work. Can you hep me to fix it.
You can see in the picture, I have a list with 7 items. When i click the "Grade Project", the Message box don't show any item.
And this is the result I need
//Main form
private void btnGrade_Click(object sender, EventArgs e)
{
List<string> result = new List<string>();
result.Add("True");
result.Add("False");
result.Add("True");
result.Add("False");
result.Add("True");
result.Add("False");
result.Add("False");
MsgBox.Show(result,"Project 1",MsgBox.Buttons.OK);
}
This is code in msgbox form
//MsgBox form
public partial class MsgBox : Form
{
private static MsgBox _msgBox;
// Header, Footer
private Panel _plHeader = new Panel();
private Label _lblTitle;
private Panel _plFooter = new Panel();
private Panel _plIcon = new Panel();
// Panel
private FlowLayoutPanel _flpButtons = new FlowLayoutPanel();
// button
private List<Button> _buttonCollection = new List<Button>();
// Kết quả
private static DialogResult _buttonResult;
// Message
private List<String> _lblMessage;
private MsgBox()
{
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.BackColor = Color.FromArgb(45, 45, 48);
this.StartPosition = FormStartPosition.CenterScreen;
this.Padding = new System.Windows.Forms.Padding(3);
this.Width = 800;
// Header
_lblTitle = new Label();
_lblTitle.ForeColor = Color.White;
_lblTitle.Font = new System.Drawing.Font("Segoe UI", 18);
_lblTitle.Dock = DockStyle.Top;
_lblTitle.Height = 60;
// Message
_lblMessage = new List<string>();
for (int i = 0; i < _lblMessage.Count; i++)
{
TextBox txt = new TextBox(); //Create Textbox có name txt
txt.Text = _lblMessage[i];
txt.ForeColor = Color.Red;
txt.Font = new System.Drawing.Font("Segoe UI", 30);
this.Controls.Add(txt); //add control txt
}
_flpButtons.FlowDirection = FlowDirection.RightToLeft;
_flpButtons.Dock = DockStyle.Fill;
_plHeader.Dock = DockStyle.Fill;
_plHeader.Padding = new Padding(20);
// _plHeader.Controls.Add(_lblMessage);
_plHeader.Controls.Add(_lblTitle);
_plFooter.Dock = DockStyle.Bottom;
_plFooter.Padding = new Padding(20);
_plFooter.BackColor = Color.FromArgb(37, 37, 38);
_plFooter.Height = 80;
_plFooter.Controls.Add(_flpButtons);
// Add controls vào form
this.Controls.Add(_plHeader);
//this.Controls.Add(_plIcon);
this.Controls.Add(_plFooter);
}
public static DialogResult Show(List<String> message, string title, Buttons buttons)
{
_msgBox = new MsgBox();
_msgBox._lblMessage = message;
_msgBox._lblTitle.Text = title;
_msgBox._plIcon.Hide();
MsgBox.InitButtons(buttons);
_msgBox.ShowDialog();
return _buttonResult;
}
Thank you for your watching.
Something wrong with your codes:
private MsgBox()
{
...
// Message
_lblMessage = new List<string>();
...
}
Your _lblMessage will always be an empty list so you see no message at all.
You can change your codes like this:
private MsgBox(List<String> messages)
{
...
// Message
_lblMessage = messages;
...
}
public static DialogResult Show(List<String> message, string title)
{
_msgBox = new MsgBox(message);
//_msgBox._lblMessage = message;
....
}
And also, you'd better set TextBox position otherwise all the TextBox will overlap with each other.

My code complies but doesn't show the ellipse in C#

So I am trying to make a red ellipse flash in the middle but for some reason my codes runs and complies but no ellipse is drawn
As you can see in the code part I have put the drawing part in the default constructor, I have also tried creating a private function that draws it and tried calling it in the default constructor but that didn't work either
using System;
using System.Drawing;
using System.Windows.Forms;
public class RedLuserinterface : Form
{
private Panel panelTop = new Panel();
private Panel panelMid = new Panel();
private Panel panelBot = new Panel();
private Label title = new Label();
private Button pauseBut = new Button();
private Button resumeBut = new Button();
private Button exitBut = new Button();
private Size minInterfaceSize = new Size(400, 600);
private Size maxInterfaceSize = new Size(400, 600);
public RedLuserinterface()
{ //Set the size of the user interface box.
MaximumSize = minInterfaceSize;
MinimumSize = maxInterfaceSize;
//Initialize text strings
Text = "Red Light Assignment";
title.Text = "Red Light Program";
pauseBut.Text = "Pause";
resumeBut.Text = "Resume";
exitBut.Text = "Exit";
//Set Sizes
Size = new Size(400, 600);
panelTop.Size = new Size(400, 30);
panelMid.Size = new Size(400, 160);
panelBot.Size = new Size(400, 50);
title.Size = new Size(120, 30);
pauseBut.Size = new Size(85, 30);
resumeBut.Size = new Size(85, 30);
exitBut.Size = new Size(85, 30);
//Set Locations
title.Location = new Point(140, 20);
panelTop.Location = new Point(0, 0);
panelMid.Location = new Point(0, 30);
panelBot.Location = new Point(0, 480);
pauseBut.Location = new Point(50, 500);
resumeBut.Location = new Point(40, 150);
exitBut.Location = new Point(250, 500);
//Add controls to the form
Controls.Add(title);
Controls.Add(panelTop);
Controls.Add(panelMid);
Controls.Add(panelBot);
Controls.Add(pauseBut);
Controls.Add(resumeBut);
Controls.Add(exitBut);
//Set Color
panelTop.BackColor = Color.Green;
panelMid.BackColor = Color.Blue;
panelBot.BackColor = Color.Yellow;
//Create solid brush and draw ellipse
SolidBrush redBrush = new SolidBrush(Color.Red);
Graphics circle = this.CreateGraphics();
circle.FillEllipse(redBrush, 0, 0, 200, 200);
//send some stuff to the back
panelTop.SendToBack();
panelMid.SendToBack();
panelBot.SendToBack();
pauseBut.Enabled = true;
resumeBut.Enabled = false;
exitBut.Click += new EventHandler(stoprun);
//dispose stuff
redBrush.Dispose();
circle.Dispose();
}
}
You need to paint your ellipse when the Form engine requires you to do it. The form engine will call the Paint event handler if you define one and will pass the Graphics object to use to paint the ellipse. So you should remove the lines in the form constructor and add the proper delegate for the Paint event, then in the Paint event draw the ellipse
public RedLuserinterface()
{
.....
// Remove these lines
// SolidBrush redBrush = new SolidBrush(Color.Red);
// Graphics circle = this.CreateGraphics();
// circle.FillEllipse(redBrush, 0, 0, 200, 200)
....
exitBut.Click += new EventHandler(stoprun);
this.Paint += onFormPaint;
// No more needed here
// redBrush.Dispose();
// circle.Dispose()
}
private void onFormPain(object sender, PaintEventArgs e)
{
SolidBrush redBrush = new SolidBrush(Color.Red);
e.Graphics.FillEllipse(redBrush, 50,250, 200, 200);
redBrush.Dispose();
}

C# Custom ComboBox - DropDown Position

I'm creating a ComboBox control using ToolStripControlHost and ToolStripDropDown that can host any kind of control in the DropDown window. For example, the DropDown window might display a listview or treeview or even another usercontrol.
I'm posting a simplified code below where dropdown host a usercontrol with a listview and a button like this:
The problem occurs when the control is positioned at the bottom of the screen in such a way that the dropdown window will extrapolate the lower boundary of the screen. When this occurs, the dropdown ends up hiding the control.
In this case, I'd like to fix the _dropDown.Show method call to show dropdown window as follows:
To repeat the problem, just run the code below and drag the window to the bottom of the screen and open the dropdown.
using System;
using System.Windows.Forms;
public class CustomComboBox : UserControl
{
ToolStripDropDown _dropDown;
public CustomComboBox()
{
var textbox = new TextBox();
textbox.Location = new System.Drawing.Point(0, 0);
textbox.Size = new System.Drawing.Size(this.Width - 22, 20);
textbox.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
this.Controls.Add(textbox);
var button = new Button();
button.Location = new System.Drawing.Point(this.Width - 22, -1);
button.Size = new System.Drawing.Size(22, 22);
button.Text = "\u2BC6";
button.Anchor = AnchorStyles.Right | AnchorStyles.Top;
button.Click += new System.EventHandler(this.Button_Click);
this.Controls.Add(button);
var dropDownControl = new DropDownControlTest();
var controlHost = new ToolStripControlHost(dropDownControl);
_dropDown = new ToolStripDropDown();
_dropDown.AutoSize = true;
_dropDown.Items.Add(controlHost);
}
void Button_Click(object sender, EventArgs e)
{
_dropDown.Show(this, 0, this.Height);
}
}
public class DropDownControlTest : UserControl
{
public DropDownControlTest()
{
var listview = new ListView();
listview.Location = new System.Drawing.Point(3, 1);
listview.Size = new System.Drawing.Size(400,300);
listview.View = View.Details;
listview.Columns.Add("Col 1",100);
listview.Columns.Add("Col 2",100);
this.Controls.Add(listview);
var button = new Button();
button.Location = new System.Drawing.Point(3, 305);
button.Text = "More...";
this.Controls.Add(button);
}
}
public class Form1 : Form
{
private static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public Form1 ()
{
CustomComboBox ccBox = new CustomComboBox();
ccBox.Location = new System.Drawing.Point(10, 10);
ccBox.Height = 20;
this.Text = "Test CustomComboBox";
this.Controls.Add(ccBox);
}
}
You can use the ToolStripDropDown.Show Method (Control, Point, ToolStripDropDownDirection) overload to control the drop direction. The code will need to perform bounds checking to decide whether to place the dropdown above or below the textbox.
The following is a simplistic method for doing the bounds checking and was only tested on a single screen configuration.
First, make textbox a class level variable.
private TextBox textbox;
public CustomComboBox()
{
//var textbox = new TextBox();
textbox = new TextBox();
The display logic is as follows.
void Button_Click(object sender, EventArgs e)
{
Point textBoxScreenLocation = textbox.PointToScreen(textbox.Location);
// try to position _dropDown below textbox
Point pt = textBoxScreenLocation;
pt.Offset(0, textbox.Height);
// determine if it will fit on the screen below the textbox
Size dropdownSize = _dropDown.GetPreferredSize(Size.Empty);
Rectangle dropdownBounds = new Rectangle(pt, dropdownSize);
if (dropdownBounds.Bottom <= Screen.GetWorkingArea(dropdownBounds).Bottom)
{ // show below
_dropDown.Show(pt, ToolStripDropDownDirection.BelowRight);
}
else
{ // show above
_dropDown.Show(textBoxScreenLocation, ToolStripDropDownDirection.AboveRight);
}
}
}
I can not comment that is why I am answering your question. You can use the reflection and then re-position you control. I have found a custom combobox control same as you developed. Please check this. At least, you will get some idea what you need to do.

Winforms: ComboBox height doesn't resize when resolution is changed

I have a basic combobox in a form. Compared to other controls(Button,label, etc) the height of the combobox doesn't change when the resolution is changed.
public partial class Form1 : Form
{
string result;
string fontInformation;
private bool scaleFactorKnown = false;
private SizeF scaleFactor;
public Form1()
{
SizeChanged += Form1_SizeChanged;
InitializeComponent();
label1.Location = new Point(12, 36);
label1.Size = new Size(100, 21);
label1.Scale(scaleFactor);
//
// textBox1
//
textBox1.Location = new Point(133, 33);
textBox1.Size = new Size(100, 21);
textBox1.Scale(scaleFactor);
//
// comboBox1
//
comboBox1.Location = new Point(250, 33);
comboBox1.Size = new Size(100, 21);
comboBox1.Scale(scaleFactor);
// button1
//
button1.Location = new Point(365, 32);
button1.Size = new Size(100, 21);
button1.Scale(scaleFactor);
//
// radioButton1
//
radioButton1.Location = new Point(480, 32);
radioButton1.Size = new Size(100, 21);
radioButton1.Scale(scaleFactor);
//
// checkBox1
//
checkBox1.Location = new Point(586, 33);
checkBox1.Size = new Size(100, 21);
checkBox1.Scale(scaleFactor);
//
// textBox2
//
textBox2.Location = new Point(26, 102);
textBox2.Size = new Size(660, 250);
textBox2.Scale(scaleFactor);
}
private void Form1_SizeChanged(object sender, EventArgs e)
{
if (!scaleFactorKnown)
{
scaleFactor = AutoScaleFactor;
scaleFactorKnown = true;
}
Size controlSize = new Size((int)(comboBox1.Width * scaleFactor.Width),
(int)(comboBox1.Height * scaleFactor.Height)); //use for sizing
//set bounds
comboBox1.Bounds = new Rectangle(comboBox1.Location, controlSize);
}
}
I have tried the method Scale() to scale all other controls, it works for other controls except for combobox. I also tried manually changing the bound but it didn't work. I also tried change the anchor and dock as well.
Expected result: Combobox height(At 150%)=42
Actual result: Combobox
height(At 150%)=28
Would appreciate any help on how to fix this issue.
You have to set the IntegralHeight property of the ComboBox to false:
comboBox1.Location = new Point(250, 33);
comboBox1.Size = new Size(100, 21);
comboBox1.Scale(scaleFactor);
comboBox1.IntegralHeight = false;

c# bringtofront() and senttoback() not working

I am new to c# and I'm trying to understand z-index concept. So far I have a simple form created using ConsoleApplication project in visual studio. There are 3 cs files. Here's the code:
In Algorithm.cs (inherited from UI.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
public class Algorithm : UI
{
private Timer refresh = new Timer();
//Ball settings
private const int offset = 25;
private const int rate = 200;
private int ball_bounding_box_x_coord;
private int ball_bounding_box_y_coord;
private int x;
private int y;
private const int width = 50;
private const int height = 50;
Brush brush = new SolidBrush(Color.Blue);
public bool isStartClicked = false;
Button test = new Button();
public Algorithm()
{
test.Text = "test";
test.Location = new Point(0, 800);
test.Size = new Size(100, 50);
test.TabIndex = 0;
bottom.Controls.Add(test);
test.BringToFront();
ball_bounding_box_x_coord = middle.Size.Width / 2 - width / 2;
ball_bounding_box_y_coord = middle.Size.Height / 2 - height / 2;
middle.Paint += new PaintEventHandler(Draw);
start.Click += new EventHandler(Start);
}
private void Calculate()
{
Graphics g = middle.CreateGraphics();
//g.FillEllipse(brush, )
}
private void Draw(object sender, PaintEventArgs e)
{
e.Graphics.FillEllipse(brush, ball_bounding_box_x_coord , ball_bounding_box_y_coord , width, height);
}
public void Start(object sender, EventArgs e)
{
MessageBox.Show("Button clicked");
}
}
In UI.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
public class UI : Form
{
//Window settings
private const int WINDOW_WIDTH = 1600;
private const int WINDOW_HEIGHT = 900;
private Panel top = new Panel();
public Panel middle = new Panel();
public Panel bottom = new Panel();
private Label title = new Label();
//Text box for degree input
private Label degree_input_label = new Label();
private TextBox degree_input = new TextBox();
public double input;
//Label to display x and y coordinates of the ball
public Label ball_x_coord = new Label();
public Label ball_y_coord = new Label();
//Buttons
public Button start = new Button();
private Button quit = new Button();
public UI()
{
//total height of 3 areas != window_height????????????????
//Setup window form
this.Width = WINDOW_WIDTH;
this.Height = WINDOW_HEIGHT;
this.Text = "Project 2";
//Add a badass title
title.Text = "Designed by Me";
title.AutoSize = true;
title.Location = new Point(600, 20);
title.Font = new Font(title.Font.Name, 24, FontStyle.Bold);
title.BackColor = Color.Red;
Controls.Add(title);
top.Location = new Point(0, 0);
top.Size = new Size(WINDOW_WIDTH, 80);
top.BackColor = Color.Red;
middle.Location = new Point(0, top.Location.Y + top.Size.Height);
middle.Size = new Size(WINDOW_WIDTH, 680);
middle.BackColor = Color.Cyan;
bottom.Location = new Point(0, top.Location.Y + top.Size.Height + middle.Size.Height);
bottom.Size = new Size(WINDOW_WIDTH, WINDOW_HEIGHT - top.Height - middle.Height);
bottom.BackColor = Color.Green;
degree_input_label.Text = "Enter a degree:";
degree_input_label.Location = new Point(100, bottom.Location.Y + 20);
degree_input_label.AutoSize = true;
Controls.Add(degree_input_label);
degree_input.Size = new Size(50, 50);
degree_input.Location = new Point(200, bottom.Location.Y + 20);
degree_input.Leave += new EventHandler(TextChange);
degree_input.TabIndex = 2;
Controls.Add(degree_input);
ball_x_coord.Text = "Ball X Coord";
ball_x_coord.Location = new Point(400, bottom.Location.Y + 20);
ball_x_coord.AutoSize = true;
Controls.Add(ball_x_coord);
ball_y_coord.Text = "Ball y coord";
ball_y_coord.Location = new Point(500, bottom.Location.Y + 20);
ball_y_coord.AutoSize = true;
Controls.Add(ball_y_coord);
start.Text = "Start";
start.Location = new Point(1100, bottom.Location.Y + 20);
start.Size = new Size(100, 50);
start.TabIndex = 1;
Controls.Add(start);
quit.Text = "Quit";
quit.Location = new Point(1400, bottom.Location.Y + 20);
quit.Size = new Size(100, 50);
quit.Click += new EventHandler(Quit);
Controls.Add(quit);
//ADD BACKGROUND CONTROLS
Controls.Add(top);
Controls.Add(middle);
Controls.Add(bottom);
}//end constructor
private void TextChange(object sender, EventArgs e)
{
if(degree_input.TextLength <= 0)
{
degree_input.Text = "0";
MessageBox.Show("Please enter a degree");
degree_input.Focus();
}else
{
input = double.Parse(degree_input.Text);
//MessageBox.Show(input.ToString());
}
}
void Quit(object sender, EventArgs e)
{
Application.Exit();
}
}
In Main.cs:
class Program
{
static void Main(string[] args)
{
Algorithm al = new Algorithm();
UI a = new UI();
//Application.Run(a);
Application.Run(al);
}
}
The problem I'm having is that the test button is not visible. If i remove the bottom panel and add the test button directly on the form then it is visible. Why doesn't it appear on the bottom panel even after I used bringtofront() ?
Why doesn't it appear on the bottom panel even after I used bringtofront() ?
Because you've placed it outside the visual boundary of the panel:
test.Location = new Point(0, 800);
That sets the position of the button to a horizontal offset of 0 and a vertical offset of 800. The bottom panel is only 140 pixels high, so 800 is well below the bottom of the visible area.
It's not really clear what you meant to do. Given that the window width is 1600 pixels and 800 is half that, maybe you just transposed the X and Y coordinates and meant this instead:
test.Location = new Point(800, 0);
That would place the button in the middle of the panel, aligned to the top.
Other than that, I can't imagine why if you wanted the button to be visible, you would hard-code a location for it that is not in a visible area.

Categories