Issue with MessageBox template - c#

I have this template for MessageBox. I have changed so you can have a scrollbar, the only problem I have now is that the title is very separate from the message and I do not know how to unite them. Try everything, but I can not.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Point = System.Drawing.Point;
using Size = System.Drawing.Size;
namespace WpfApplication2.xDialog
{
class MsgBox : Form
{
private const int CS_DROPSHADOW = 0x00020000;
private static MsgBox _msgBox;
private readonly Panel _plHeader = new Panel();
private readonly Panel _plButton = new Panel();
private readonly Panel _plIcon = new Panel();
private readonly PictureBox _picIcon = new PictureBox();
private readonly FlowLayoutPanel _flpButtons = new FlowLayoutPanel();
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
private readonly Label _lblTitle;
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
private readonly RichTextBox _lblMessage;
private readonly List<Button> _buttonCollection = new List<Button>();
private static DialogResult _buttonResult;
private static Timer _timer;
private static Point _lastMousePos;
//[DllImport("user32.dll", CharSet = CharSet.Auto)]
//private static extern bool MessageBeep(uint type);
private MsgBox()
{
FormBorderStyle = FormBorderStyle.None;
BackColor = Color.FromArgb(190, 190, 190);
//BackColor = Color.DarkGreen;
StartPosition = FormStartPosition.CenterScreen;
//Padding = new Padding(3);
//Width = 400;
_lblTitle = new Label
{
ForeColor = Color.Black,
TextAlign = ContentAlignment.MiddleLeft,
Font = new Font("Segoe UI", 15),
BackColor = Color.Red,
AutoSize = true
};
_lblMessage = new RichTextBox
{
ForeColor = Color.Black,
Font = new Font("Segoe UI", 12),
Multiline = true,
WordWrap = true,
Dock = DockStyle.Fill,
ReadOnly = true,
BackColor = Color.Yellow,
BorderStyle = BorderStyle.None
};
_flpButtons.FlowDirection = FlowDirection.RightToLeft;
_flpButtons.Dock = DockStyle.Fill;
//PANEL DEL TITULO
_plHeader.Dock = DockStyle.Top;
_plHeader.Controls.Add(_lblTitle);
// PANEL DE LOS BOTONES
_plButton.Dock = DockStyle.Bottom;
_plButton.Padding = new Padding(20);
_plButton.BackColor = Color.FromArgb(170, 170, 170);
_plButton.Height = 80;
_plButton.Controls.Add(_flpButtons);
// ICONO
_picIcon.Width = 32;
_picIcon.Height = 32;
_picIcon.Location = new Point(20, 60);
// PANEL DEL ICONO
_plIcon.Dock = DockStyle.Left;
_plIcon.Padding = new Padding(20);
_plIcon.Width = 70;
_plIcon.BackColor = Color.Blue;
_plIcon.Controls.Add(_picIcon);
var controlCollection = new List<Control>
{
this,
_lblTitle,
_flpButtons,
_plHeader,
_plButton,
_plIcon,
_picIcon
};
foreach (var control in controlCollection)
{
control.MouseDown += MsgBox_MouseDown;
control.MouseMove += MsgBox_MouseMove;
}
Controls.Add(_lblMessage);
Controls.Add(_plHeader);
Controls.Add(_plIcon);
Controls.Add(_plButton);
}
public override sealed Color BackColor
{
get { return base.BackColor; }
set { base.BackColor = value; }
}
private static void MsgBox_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_lastMousePos = new Point(e.X, e.Y);
}
}
private static void MsgBox_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return;
_msgBox.Left += e.X - _lastMousePos.X;
_msgBox.Top += e.Y - _lastMousePos.Y;
}
public static DialogResult Show(string message)
{
_msgBox = new MsgBox { _lblMessage = { Text = message } };
InitButtons(Buttons.OK);
_msgBox.ShowDialog();
return _buttonResult;
}
public static DialogResult Show(string message, string title)
{
_msgBox = new MsgBox
{
_lblMessage = { Text = message },
_lblTitle = { Text = title },
Size = MessageSize(message, title)
};
InitButtons(Buttons.OK);
_msgBox.ShowDialog();
return _buttonResult;
}
public static DialogResult Show(string message, string title, Buttons buttons)
{
_msgBox = new MsgBox { _lblMessage = { Text = message }, _lblTitle = { Text = title } };
_msgBox._plIcon.Hide();
InitButtons(buttons);
_msgBox.Size = MessageSize(message, title);
_msgBox.ShowDialog();
return _buttonResult;
}
public static DialogResult Show(string message, string title, Buttons buttons, Icon icon)
{
_msgBox = new MsgBox { _lblMessage = { Text = message }, _lblTitle = { Text = title } };
InitButtons(buttons);
InitIcon(icon);
_msgBox.Size = MessageSize(message, title);
_msgBox.ShowDialog();
//MessageBeep(0);
return _buttonResult;
}
public static DialogResult Show(string message, string title, Buttons buttons, Icon icon, AnimateStyle style)
{
_msgBox = new MsgBox { _lblMessage = { Text = message }, _lblTitle = { Text = title }, Height = 0 };
InitButtons(buttons);
InitIcon(icon);
_timer = new Timer();
var formSize = MessageSize(message, title);
switch (style)
{
case AnimateStyle.SlideDown:
_msgBox.Size = new Size(formSize.Width, 0);
_timer.Interval = 1;
_timer.Tag = new AnimateMsgBox(formSize, style);
break;
case AnimateStyle.FadeIn:
_msgBox.Size = formSize;
_msgBox.Opacity = 0;
_timer.Interval = 20;
_timer.Tag = new AnimateMsgBox(formSize, style);
break;
case AnimateStyle.ZoomIn:
_msgBox.Size = new Size(formSize.Width + 100, formSize.Height + 100);
_timer.Tag = new AnimateMsgBox(formSize, style);
_timer.Interval = 1;
break;
}
_timer.Tick += timer_Tick;
_timer.Start();
_msgBox.ShowDialog();
//MessageBeep(0);
return _buttonResult;
}
static void timer_Tick(object sender, EventArgs e)
{
var timer = (Timer)sender;
var animate = (AnimateMsgBox)timer.Tag;
switch (animate.Style)
{
case AnimateStyle.SlideDown:
if (_msgBox.Height < animate.FormSize.Height)
{
_msgBox.Height += 17;
_msgBox.Invalidate();
}
else
{
_timer.Stop();
_timer.Dispose();
}
break;
case AnimateStyle.FadeIn:
if (_msgBox.Opacity < 1)
{
_msgBox.Opacity += 0.1;
_msgBox.Invalidate();
}
else
{
_timer.Stop();
_timer.Dispose();
}
break;
case AnimateStyle.ZoomIn:
if (_msgBox.Width > animate.FormSize.Width)
{
_msgBox.Width -= 17;
_msgBox.Invalidate();
}
if (_msgBox.Height > animate.FormSize.Height)
{
_msgBox.Height -= 17;
_msgBox.Invalidate();
}
break;
}
}
private static void InitButtons(Buttons buttons)
{
switch (buttons)
{
case Buttons.AbortRetryIgnore:
_msgBox.InitAbortRetryIgnoreButtons();
break;
case Buttons.OK:
_msgBox.InitOkButton();
break;
case Buttons.OKCancel:
_msgBox.InitOkCancelButtons();
break;
case Buttons.RetryCancel:
_msgBox.InitRetryCancelButtons();
break;
case Buttons.YesNo:
_msgBox.InitYesNoButtons();
break;
case Buttons.YesNoCancel:
_msgBox.InitYesNoCancelButtons();
break;
}
foreach (var btn in _msgBox._buttonCollection)
{
btn.ForeColor = Color.FromArgb(170, 170, 170);
btn.ForeColor = Color.Black;
btn.Font = new Font("Segoe UI", 8);
btn.Padding = new Padding(3);
btn.FlatStyle = FlatStyle.Flat;
btn.Height = 30;
btn.FlatAppearance.BorderColor = Color.FromArgb(99, 99, 98);
_msgBox._flpButtons.Controls.Add(btn);
}
}
private static void InitIcon(Icon icon)
{
switch (icon)
{
case Icon.Application:
_msgBox._picIcon.Image = SystemIcons.Application.ToBitmap();
break;
case Icon.Exclamation:
_msgBox._picIcon.Image = SystemIcons.Exclamation.ToBitmap();
break;
case Icon.Error:
_msgBox._picIcon.Image = SystemIcons.Error.ToBitmap();
break;
case Icon.Info:
_msgBox._picIcon.Image = SystemIcons.Information.ToBitmap();
break;
case Icon.Question:
_msgBox._picIcon.Image = SystemIcons.Question.ToBitmap();
break;
case Icon.Shield:
_msgBox._picIcon.Image = SystemIcons.Shield.ToBitmap();
break;
case Icon.Warning:
_msgBox._picIcon.Image = SystemIcons.Warning.ToBitmap();
break;
}
}
private void InitAbortRetryIgnoreButtons()
{
var btnAbort = new Button { Text = #"Abortar" };
btnAbort.Click += ButtonClick;
CancelButton = btnAbort;
var btnRetry = new Button { Text = #"Reintentar" };
btnRetry.Click += ButtonClick;
btnRetry.Width = 80;
var btnIgnore = new Button { Text = #"Ignorar" };
btnIgnore.Click += ButtonClick;
_buttonCollection.Add(btnIgnore);
_buttonCollection.Add(btnAbort);
_buttonCollection.Add(btnRetry);
}
private void InitOkButton()
{
var btnOk = new Button { Text = #"OK" };
btnOk.Click += ButtonClick;
CancelButton = btnOk;
_buttonCollection.Add(btnOk);
}
private void InitOkCancelButtons()
{
var btnOk = new Button { Text = #"OK" };
btnOk.Click += ButtonClick;
var btnCancel = new Button { Text = #"Cancelar" };
btnCancel.Click += ButtonClick;
CancelButton = btnCancel;
_buttonCollection.Add(btnCancel);
_buttonCollection.Add(btnOk);
}
private void InitRetryCancelButtons()
{
var btnRetry = new Button { Text = #"Reintentar" };
btnRetry.Click += ButtonClick;
var btnCancel = new Button { Text = #"Cancelar" };
btnCancel.Click += ButtonClick;
CancelButton = btnCancel;
_buttonCollection.Add(btnCancel);
_buttonCollection.Add(btnRetry);
}
private void InitYesNoButtons()
{
var btnYes = new Button { Text = #"Sí" };
btnYes.Click += ButtonClick;
var btnNo = new Button { Text = #"No" };
btnNo.Click += ButtonClick;
CancelButton = btnNo;
_buttonCollection.Add(btnNo);
_buttonCollection.Add(btnYes);
}
private void InitYesNoCancelButtons()
{
var btnYes = new Button { Text = #"Sí" };
btnYes.Click += ButtonClick;
var btnNo = new Button { Text = #"No" };
btnNo.Click += ButtonClick;
var btnCancel = new Button { Text = #"Cancelar" };
btnCancel.Click += ButtonClick;
CancelButton = btnCancel;
_buttonCollection.Add(btnCancel);
_buttonCollection.Add(btnNo);
_buttonCollection.Add(btnYes);
}
private static void ButtonClick(object sender, EventArgs e)
{
var btn = (Button)sender;
switch (btn.Text)
{
case "Abortar":
_buttonResult = DialogResult.Abort;
break;
case "Reintentar":
_buttonResult = DialogResult.Retry;
break;
case "Ignorar":
_buttonResult = DialogResult.Ignore;
break;
case "OK":
_buttonResult = DialogResult.OK;
break;
case "Cancelar":
_buttonResult = DialogResult.Cancel;
break;
case "Sí":
_buttonResult = DialogResult.Yes;
break;
case "No":
_buttonResult = DialogResult.No;
break;
}
_msgBox.Dispose();
}
private static Size MessageSize(string message, string title)
{
var g = _msgBox.CreateGraphics();
var width = 320;
var height = 320;
var messageSize = g.MeasureString(message, new Font("Segoe UI", 10));
var titleSize = g.MeasureString(title, new Font("Segoe UI", 15));
if (message.Length < 150)
{
if ((int)messageSize.Width > 350 || (int)titleSize.Width > 350)
{
width = (messageSize.Width > titleSize.Width)
? (int)messageSize.Width
: (int)(titleSize.Width + titleSize.Width / 4);
}
}
else
{
//var groups = (from Match m in Regex.Matches(message, ".{1,180}") select m.Value).ToArray();
//var lines = groups.Length + 1;
width = 775;
height += (int)(messageSize.Height + 50);
if (height > 575)
height = 575;
}
return new Size(width, height);
}
protected override CreateParams CreateParams
{
get
{
var cp = base.CreateParams;
cp.ClassStyle |= CS_DROPSHADOW;
return cp;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var g = e.Graphics;
var rect = new Rectangle(new Point(0, 0), new Size(Width - 1, Height - 1));
var pen = new Pen(Color.FromArgb(0, 151, 251));
g.DrawRectangle(pen, rect);
}
public enum Buttons
{
AbortRetryIgnore = 1,
// ReSharper disable once InconsistentNaming
OK = 2,
// ReSharper disable once InconsistentNaming
OKCancel = 3,
RetryCancel = 4,
YesNo = 5,
YesNoCancel = 6
}
public new enum Icon
{
Application = 1,
Exclamation = 2,
Error = 3,
Warning = 4,
Info = 5,
Question = 6,
Shield = 7,
Search = 8
}
public enum AnimateStyle
{
SlideDown = 1,
FadeIn = 2,
ZoomIn = 3
}
//private void InitializeComponent()
//{
// SuspendLayout();
// //
// // MsgBox
// //
// ClientSize = new Size(300, 375);
// Name = "MsgBox";
// ResumeLayout(false);
//}
}
class AnimateMsgBox
{
public Size FormSize;
public readonly MsgBox.AnimateStyle Style;
public AnimateMsgBox(Size formSize, MsgBox.AnimateStyle style)
{
FormSize = formSize;
Style = style;
}
}
}

You need to set the Height property of _plHeader
If you need to change the height dynamically you can use Graphics.MeasureString, TextRenderer.MeasureText or an auto resize TextBox to get the required height of the panel

Related

Close button also save values

I have a dialog where the user can input two integers with OK button. The entered values are saved to variables. However, if I close it from the close button it also save the last entered values, which means not only the OK button save them. what am I doing wrong here?
The dialog:
namespace WindowsFormsApplication1
{
public static class inputBoxDialog
{
public static void ShowDialog(string text1, string text2, string caption, int[] lastValue)
{
Form prompt = new Form();
prompt.Width = 500;
prompt.Height = 250;
prompt.Text = caption;
prompt.StartPosition = FormStartPosition.CenterScreen;
//input 1
Label textLabel = new Label() { Left = 50, Top = 20, Text = text1 };
NumericUpDown inputBox1 = new NumericUpDown() { Left = 50, Top = 50, Width = 400 };
inputBox1.Value = lastValue[0];
//input 2
Label textLabe2 = new Label() { Left = 50, Top = 100, Text = text2 };
NumericUpDown inputBox2 = new NumericUpDown() { Left = 50, Top = 130, Width = 400 };
inputBox2.Value = lastValue[1];
Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 170 };
confirmation.Click += (sender, e) => { prompt.Close();};
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.Controls.Add(inputBox1);
prompt.Controls.Add(textLabe2);
prompt.Controls.Add(inputBox2);
prompt.ShowDialog();
lastValue[0] = (int)inputBox1.Value;
lastValue[1] = (int)inputBox2.Value;
}
}
}
I call the dialog here:
namespace WindowsFormsApplication1
{
public partial class MainWindow : Form
{
public MainWindow()
{
InitializeComponent();
}
int[] loopParams = new int[2] { 0, 0 };
private void button1_Click(object sender, EventArgs e)
{
inputBoxDialog.ShowDialog("For Loop Begin: ", "For Loop End: ", "Popup", loopParams);
//display the result
label1.Text = "1:- " + loopParams[0]+"\r\n2:- " + loopParams[1];
}
}
}
As pointed out by Jimi, you need to set the OK buttons DialogResult property to DialogResult.OK:
Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 170, DialogResult = DialogResult.OK };
And to check the returned DialogResult value from the prompt.ShowDialog() method:
if (prompt.ShowDialog() == DialogResult.OK)
{
lastValue[0] = (int)inputBox1.Value;
lastValue[1] = (int)inputBox2.Value;
}
Here is your code with the above additions:
public static void ShowDialog(string text1, string text2, string caption, int[] lastValue)
{
Form prompt = new Form();
prompt.Width = 500;
prompt.Height = 250;
prompt.Text = caption;
prompt.StartPosition = FormStartPosition.CenterScreen;
//input 1
Label textLabel = new Label() { Left = 50, Top = 20, Text = text1 };
NumericUpDown inputBox1 = new NumericUpDown() { Left = 50, Top = 50, Width = 400 };
inputBox1.Value = lastValue[0];
//input 2
Label textLabe2 = new Label() { Left = 50, Top = 100, Text = text2 };
NumericUpDown inputBox2 = new NumericUpDown() { Left = 50, Top = 130, Width = 400 };
inputBox2.Value = lastValue[1];
Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 170, DialogResult = DialogResult.OK };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.Controls.Add(inputBox1);
prompt.Controls.Add(textLabe2);
prompt.Controls.Add(inputBox2);
if (prompt.ShowDialog() == DialogResult.OK)
{
// OK
lastValue[0] = (int)inputBox1.Value;
lastValue[1] = (int)inputBox2.Value;
}
else
{
// Cancel
}
}
Checking the prompt.DialogResult in the prompt.FormClosed event:
prompt.FormClosed += (sender, e) =>
{
if (prompt.DialogResult == DialogResult.OK)
{
// OK
}
else
{
// Cancel
}
};

How to add and remove rows in a UITableview dynamically in xamarin.ios

I am new in xamarin.ios ,I want to add rows into the UITableView in a button click, and remove the row when clicking the particular button also.
Please help me...
my viewcontroller.cs
public partial class ViewController : UIViewController
{
public static UITableView table;
public ViewController(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
table = new UITableView(new CGRect(0, 0, 500, 500));
View.AddSubview(table);
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("Cell"), OnChange, this);
contentdata _cnt = new contentdata();
table.AddSubview(_cnt);
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
}
private void Addmore_TouchUpInside(object sender,
EventArgs e)
{
NSNotificationCenter.DefaultCenter.PostNotificationName("Cell", new NSString("Add"));
}
public class contentdata : UIView
{
public contentdata()
{
this.Frame = new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, 50);
nfloat width = UIScreen.MainScreen.Bounds.Width / 3;
UITextField title = new UITextField();
title.Placeholder = " Enter title";
title.TextColor = UIColor.Black;
title.TextAlignment = UITextAlignment.Left;
title.Font = UIFont.SystemFontOfSize(20);
title.Layer.BorderColor = UIColor.Black.CGColor;
title.Layer.BorderWidth = 1;
title.Frame = new CGRect(10, 0, width, 75);
this.Add(title);
UIView _view2 = new UIView(new CGRect(0,5,10,10));
_view2.BackgroundColor = UIColor.White;
_view2.Layer.BorderColor = UIColor.Black.CGColor;
_view2.Layer.BorderWidth = 1;
_view2.Frame = new CGRect(width, 0, UIScreen.MainScreen.Bounds.Width / 3, 75);
this.Add(_view2);
nfloat _view2Width = _view2.Frame.Width;
nfloat _view2Height = _view2.Frame.Height;
UIButton _browse = new UIButton(new CGRect(15, 10,100, 30));
_browse.SetTitle("Browse", UIControlState.Normal);
// _browse.SizeToFit();
_browse.SetTitleColor(UIColor.Black, UIControlState.Normal);
_browse.Layer.CornerRadius = 13;
_browse.Layer.BorderWidth = 2;
_browse.Layer.BorderColor = UIColor.FromRGB(25, 106, 155).CGColor;
// _browse.TouchUpInside += _browse_TouchUpInside;
_view2.AddSubview(_browse);
UILabel _text = new UILabel(new CGRect(5, (_view2Height/2)+5, 150, 30));
_text.Text = "No file selected";
_text.TextAlignment = UITextAlignment.Justified;
_text.TextColor = UIColor.Black;
_text.Font = _text.Font.WithSize(15);
_text.LineBreakMode = UILineBreakMode.WordWrap;
_view2.AddSubview(_text);
UIView _view3 = new UIView();
_view3.BackgroundColor = UIColor.White;
_view3.Layer.BorderColor = UIColor.Black.CGColor;
_view3.Layer.BorderWidth = 1;
_view3.Frame = new CGRect(width * 2, 0, UIScreen.MainScreen.Bounds.Width / 3-10, 75);
this.Add(_view3);
UIButton _addmore = new UIButton(new CGRect(10, 15, 40, 40));
_addmore.SetTitle("+", UIControlState.Normal);
_addmore.BackgroundColor = UIColor.FromRGB(25, 106, 155);
_addmore.SetTitleColor(UIColor.White, UIControlState.Normal);
_addmore.TouchUpInside += Addmore_TouchUpInside;
_view3.AddSubview(_addmore);
UIButton _remove = new UIButton(new CGRect(65, 15, 40, 40));
_remove.BackgroundColor = UIColor.Red;
_remove.SetTitle("-", UIControlState.Normal);
_remove.SetTitleColor(UIColor.White, UIControlState.Normal);
_view3.AddSubview(_remove);
}
void OnChange(NSNotification notification)
{
string s = notification.Object as NSString;
if (s == "Add")
{
contentdata _cd = new AddMore.ViewController.contentdata();
table.AddSubview(_cd);
}
else
{
int index = (notification.Object as NSIndexPath).Row;
//tableItems.RemoveAt(index);
}
table.ReloadData();
}
}
}
I want to add rows in to the table when clicking the plus button, and remove the selected row when clicking the minus button.And after browsing a file, the filename is displayed in the label also.How can I do this
You can use NSNotification to operate the datasource , and then reload the TableView.
When click add button , datasource + 1, when click remove button, datasource will remove the specified one.
ViewController
void OnChange(NSNotification notification)
{
string s = notification.Object as NSString;
if(s is "Add")
{
tableItems.Add(new TableItem("Vegetables") { SubHeading = "65 items", ImageName = "Vegetables.jpg" });
}
else
{
int index = (notification.Object as NSIndexPath).Row;
tableItems.RemoveAt(index);
}
table.ReloadData();
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("Cell"), OnChange,this);
//xxx
}
UITableViewCell
private void _addmore_TouchUpInside(object sender, EventArgs e)
{
NSNotificationCenter.DefaultCenter.PostNotificationName("Cell", new NSString("Add"));
}
private void _remove_TouchUpInside(object sender, EventArgs e)
{
NSNotificationCenter.DefaultCenter.PostNotificationName("Cell", Cellindex);
}

How to use Click event in dynamic groupbox in C#

I have a form like this. You can see my dynamic groupbox (30 groupbox) in Flowlayout on the right, and a picturebox to show questions on the left.
I'm worndering that How to use Click event for each groupbox to show the question equivalent in Picturebox?
Here's my code of groupbox
public GroupBox gbx(String name, int s, string i, string msch)
{
this.Name = int.Parse(i);
this.sda = s;
this.MsCauHoi = msch;
// gb
//
if (s == 2)
{
gb.Controls.Add(cb1);
gb.Controls.Add(cb2);
}
if (s == 3)
{
gb.Controls.Add(cb1);
gb.Controls.Add(cb2);
gb.Controls.Add(cb3);
}
if (s == 4)
{
gb.Controls.Add(cb1);
gb.Controls.Add(cb2);
gb.Controls.Add(cb3);
gb.Controls.Add(cb4);
}
gb.Location = new System.Drawing.Point(219, 44);
gb.Margin = new System.Windows.Forms.Padding(1, 1, 1, 1);
gb.Name = name;
gb.Padding = new System.Windows.Forms.Padding(1, 1, 1, 1);
gb.Size = new System.Drawing.Size(120, 45);
gb.TabIndex = 7;
gb.TabStop = false;
gb.Text = i;
gb.BackColor = Color.Silver;
//
// cb1
//
cb1.AutoSize = true;
cb1.CheckAlign = System.Drawing.ContentAlignment.BottomCenter;
cb1.Location = new System.Drawing.Point(15, 13);
cb1.Margin = new System.Windows.Forms.Padding(0);
cb1.Name = "cb1";
cb1.Size = new System.Drawing.Size(17, 31);
cb1.TabIndex = 0;
cb1.Text = "1";
cb1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
cb1.UseVisualStyleBackColor = true;
cb1.CheckedChanged += delegate (object sender, EventArgs e)
{
CheckBox b = new CheckBox();
b = (CheckBox)sender;
if (b.Checked == true)
{
gb.BackColor = Color.Turquoise;
}
};
//
// cb2
//
cb2.AutoSize = true;
cb2.CheckAlign = System.Drawing.ContentAlignment.BottomCenter;
cb2.Location = new System.Drawing.Point(35, 13);
cb2.Name = "cb2";
cb2.Size = new System.Drawing.Size(17, 31);
cb2.TabIndex = 1;
cb2.Text = "2";
cb2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
cb2.UseVisualStyleBackColor = true;
cb2.CheckedChanged += delegate (object sender, EventArgs e)
{
CheckBox b = new CheckBox();
b = (CheckBox)sender;
if (b.Checked == true)
{
gb.BackColor = Color.Turquoise;
}
};
//
// cb3
//
cb3.AutoSize = true;
cb3.CheckAlign = System.Drawing.ContentAlignment.BottomCenter;
cb3.Location = new System.Drawing.Point(58, 13);
cb3.Name = "cb3";
cb3.Size = new System.Drawing.Size(17, 31);
cb3.TabIndex = 2;
cb3.Text = "3";
cb3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
cb3.UseVisualStyleBackColor = true;
cb3.CheckedChanged += delegate (object sender, EventArgs e)
{
CheckBox b = new CheckBox();
b = (CheckBox)sender;
if (b.Checked == true)
{
gb.BackColor = Color.Turquoise;
}
};
//
// cb4
//
cb4.AutoSize = true;
cb4.CheckAlign = System.Drawing.ContentAlignment.BottomCenter;
cb4.Location = new System.Drawing.Point(81, 13);
cb4.Name = "cb4";
cb4.Size = new System.Drawing.Size(17, 31);
cb4.TabIndex = 3;
cb4.Text = "4";
cb4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
cb4.UseVisualStyleBackColor = true;
cb4.CheckedChanged += delegate (object sender, EventArgs e)
{
CheckBox b = new CheckBox();
b = (CheckBox)sender;
if (b.Checked == true)
{
gb.BackColor = Color.Turquoise;
}
};
return gb;
}
And here's the code of FormLoad
private void FrmThi_Load(object sender, EventArgs e)
{
droptable();
this.CauDaLam = 0;
if (dethi == null) setdethi();
Screen scr = Screen.PrimaryScreen; //đi lấy màn hình chính
this.Left = (scr.WorkingArea.Width - this.Width) / 2;
this.Top = (scr.WorkingArea.Height - this.Height) / 2;
int i = 0;
foreach (DataRow row in this.dethi.Rows)
{
String myValue = row["SoDA"].ToString();
String msch = row["MaCH"].ToString();
ptl = new FrmPhieuTraLoi();
pn_DeThi.Controls.Add(ptl.gbx("cau" + (i + 1).ToString(), int.Parse(myValue), (i + 1).ToString(), msch));
listptl.Add(ptl);
i++;
}
loadcauhoi(this.CauDangLam);
listptl[CauDangLam].setBackColorCDL();
Random r = new Random();
lbmade1.Text = r.Next(1, 4).ToString();
txt = lbSatHachBangLai.Text;
len = txt.Length;
lbSatHachBangLai.Text = "";
timer1.Start();
this.timer2.Start();
}
This is an example code:
private void Form1_Load(object sender, EventArgs e)
{
for(int idx = 0; idx < 5; idx++)
{
var gBox = new GroupBox();
gBox.Height = 50;
gBox.Width = 50;
gBox.Text = "Box: " + idx;
gBox.Tag = idx;
gBox.MouseClick += GBox_MouseClick;
this.Controls.Add(gBox);
}
}
private void GBox_MouseClick(object sender, MouseEventArgs e)
{
//var ctrl = sender as Control; -- Not required
int questionIdx = (int)(sender as Control).Tag;
}
I would extend the GroupBox control and add a property for the Question ID (Add new Item > Custom Control) and change the class to look like this:
public partial class QuestionGroupBox : GroupBox
{
public string QuestionID;
public QuestionGroupBox()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
}
Then populate your flowlayout and set the QuestionID and Click EventHandler, similar to this:
var gb = new QuestionGroupBox{ QuestionID = "44"};
gb.Click += new System.EventHandler(this.questionGroupBox_Click);
//add add to your flow layout
Finally create your event handler to get and display the question
private void questionGroupBox_Click(object sender, EventArgs e)
{
var questionID = ((QuestionGroupBox)sender).QuestionID;
//display your question
}

How to create semi-transparent form win apps

i want to create a semi transparent form for overlay effect. the form should be see through.
this is the way i try to do it but it is not getting semi-transparent form. so please help me.
Form mMask = new Form();
mMask.FormBorderStyle = FormBorderStyle.None;
mMask.BackColor = Color.DarkGray;
mMask.Opacity = 0.10;
mMask.Height = this.ClientRectangle.Height;
mMask.Width = this.ClientRectangle.Width;
mMask.Top = 0;
mMask.Left = 0;
mMask.Text = this.Text;
mMask.AllowTransparency = true;
mMask.ShowInTaskbar = false;
mMask.StartPosition = FormStartPosition.Manual;
mMask.TopLevel = false;
this.Controls.Add(mMask);
mMask.Show();
mMask.BringToFront();
please guide me thanks.
i modify this routine and now it is as follow
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace dialog
{
public class MaskedDialog : Form
{
static MaskedDialog mask;
static Form frmContainer;
private Form dialog;
private UserControl ucDialog;
private MaskedDialog(Form parent, Form dialog)
{
this.dialog = dialog;
this.FormBorderStyle = FormBorderStyle.None;
this.BackColor = System.Drawing.Color.Black;
this.Opacity = 0.50;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.Manual;
this.Size = parent.ClientSize;
this.Location = parent.PointToScreen(System.Drawing.Point.Empty);
parent.Move += AdjustPosition;
parent.SizeChanged += AdjustPosition;
}
private MaskedDialog(Form parent, UserControl ucDialog)
{
this.ucDialog = ucDialog;
this.FormBorderStyle = FormBorderStyle.None;
this.BackColor = System.Drawing.Color.Black;
this.Opacity = 0.50;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.Manual;
this.Size = parent.ClientSize;
this.Location = parent.PointToScreen(System.Drawing.Point.Empty);
parent.Move += AdjustPosition;
parent.SizeChanged += AdjustPosition;
}
private void AdjustPosition(object sender, EventArgs e)
{
Form parent = sender as Form;
this.Location = parent.PointToScreen(System.Drawing.Point.Empty);
this.ClientSize = parent.ClientSize;
}
public static DialogResult ShowDialog(Form parent, Form dialog)
{
mask = new MaskedDialog(parent, dialog);
dialog.StartPosition = FormStartPosition.CenterParent;
mask.Show();
DialogResult result = dialog.ShowDialog(mask);
mask.Close();
return result;
}
public static DialogResult ShowDialog(Form parent, UserControl dialog)
{
mask = new MaskedDialog(parent, dialog);
frmContainer = new Form();
frmContainer.ShowInTaskbar = false;
frmContainer.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
frmContainer.StartPosition = FormStartPosition.CenterParent;
frmContainer.Height = dialog.Height;
frmContainer.Width = dialog.Width;
frmContainer.Controls.Add(dialog);
mask.Show();
DialogResult result = frmContainer.ShowDialog(mask);
frmContainer.Close();
mask.Close();
return result;
}
public static void CloseDialog()
{
if (frmContainer != null)
{
frmContainer.Close();
}
}
}
}
calling technique 1 with form
Form d = new Form();
d.Width = 400;
d.Height = 300;
MaskedDialog.ShowDialog(this, d);
calling technique 2 with form
UserControl1 uc = new UserControl1();
uc.CloseClicked += new UserControl1.CloseComplete(OnCloseClicked);
MaskedDialog.ShowDialog(this, uc);
void OnCloseClicked()
{
MaskedDialog.CloseDialog();
}
void Main()
{
var f = new Form
{
Width = 800,
Height = 600
};
var d = new Form
{
Width = 400,
Height = 300
};
var tb = new TextBox
{
Width = 250,
Height = 250,
Multiline = true,
Text = "Hello World",
Dock = DockStyle.Top
};
var b = new Button
{
Text = "Display Masked Dialog",
Dock = DockStyle.Top
};
b.Click += (s, e) =>
{
MaskedDialog.ShowDialog(f, d);
};
f.Controls.AddRange(new Control[] { tb, b } );
Application.Run(f);
}
public class MaskedDialog : Form
{
private Form dialog;
private MaskedDialog(Form parent, Form dialog)
{
this.dialog = dialog;
this.FormBorderStyle = FormBorderStyle.None;
this.BackColor = System.Drawing.Color.Black;
this.Opacity = 0.50;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.Manual;
this.Size = parent.ClientSize;
this.Location = parent.PointToScreen(System.Drawing.Point.Empty);
parent.Move += AdjustPosition;
parent.SizeChanged += AdjustPosition;
}
private void AdjustPosition(object sender, EventArgs e)
{
Form parent = sender as Form;
this.Location = parent.PointToScreen(System.Drawing.Point.Empty);
this.ClientSize = parent.ClientSize;
}
public static DialogResult ShowDialog(Form parent, Form dialog)
{
var mask = new MaskedDialog(parent, dialog);
dialog.StartPosition = FormStartPosition.CenterParent;
mask.Show();
var result = dialog.ShowDialog(mask);
mask.Close();
return result;
}
}

How to customize message box

I am doing C# application, and I want to change the style of a message box. Is it possible or not?
Example: change button style, fore color, etc.
You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:
FormBorderStyle FixedToolWindow
ShowInTaskBar False
StartPosition CenterScreen
To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:
MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
// etc
}
It would be advisable to add your own Show method that takes the text and other options you require:
public DialogResult Show(string text, Color foreColour)
{
lblText.Text = text;
lblText.ForeColor = foreColour;
return this.ShowDialog();
}
MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
Here is the code needed to create your own message box:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyStuff
{
public class MyLabel : Label
{
public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Label l = new Label();
l.Text = Text;
l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
l.AutoSize = true;
return l;
}
}
public class MyButton : Button
{
public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Button b = new Button();
b.Text = Text;
b.Width = Width;
b.Height = Height;
b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
return b;
}
}
public class MyImage : PictureBox
{
public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
{
PictureBox i = new PictureBox();
if (ImagePath != null)
{
i.BackgroundImageLayout = ImageLayout.Zoom;
i.Location = new Point(9, 9);
i.Margin = new Padding(3, 3, 2, 3);
i.Size = new Size(Width, Height);
i.TabStop = false;
i.Visible = true;
i.BackgroundImage = Image.FromFile(ImagePath);
}
else
{
i.Visible = true;
i.Size = new Size(0, 0);
}
return i;
}
}
public partial class MyMessageBox : Form
{
private MyMessageBox()
{
this.panText = new FlowLayoutPanel();
this.panButtons = new FlowLayoutPanel();
this.SuspendLayout();
//
// panText
//
this.panText.Parent = this;
this.panText.AutoScroll = true;
this.panText.AutoSize = true;
this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
//this.panText.Location = new Point(90, 90);
this.panText.Margin = new Padding(0);
this.panText.MaximumSize = new Size(500, 300);
this.panText.MinimumSize = new Size(108, 50);
this.panText.Size = new Size(108, 50);
//
// panButtons
//
this.panButtons.AutoSize = true;
this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.panButtons.FlowDirection = FlowDirection.RightToLeft;
this.panButtons.Location = new Point(89, 89);
this.panButtons.Margin = new Padding(0);
this.panButtons.MaximumSize = new Size(580, 150);
this.panButtons.MinimumSize = new Size(108, 0);
this.panButtons.Size = new Size(108, 35);
//
// MyMessageBox
//
this.AutoScaleDimensions = new SizeF(8F, 19F);
this.AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new Size(206, 133);
this.Controls.Add(this.panButtons);
this.Controls.Add(this.panText);
this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.Margin = new Padding(4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new Size(168, 132);
this.Name = "MyMessageBox";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.CenterScreen;
this.ResumeLayout(false);
this.PerformLayout();
}
public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(Label);
return Show(Labels, Title, Buttons, Image);
}
public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(MyLabel.Set(Label));
return Show(Labels, Title, Buttons, Image);
}
public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
if (Labels == null) Labels = new List<Label>();
if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
if (Buttons == null) Buttons = new List<Button>();
if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
List<Button> buttons = new List<Button>(Buttons);
buttons.Reverse();
int ImageWidth = 0;
int ImageHeight = 0;
int LabelWidth = 0;
int LabelHeight = 0;
int ButtonWidth = 0;
int ButtonHeight = 0;
int TotalWidth = 0;
int TotalHeight = 0;
MyMessageBox mb = new MyMessageBox();
mb.Text = Title;
//Image
if (Image != null)
{
mb.Controls.Add(Image);
Image.MaximumSize = new Size(150, 300);
ImageWidth = Image.Width + Image.Margin.Horizontal;
ImageHeight = Image.Height + Image.Margin.Vertical;
}
//Labels
List<int> il = new List<int>();
mb.panText.Location = new Point(9 + ImageWidth, 9);
foreach (Label l in Labels)
{
mb.panText.Controls.Add(l);
l.Location = new Point(200, 50);
l.MaximumSize = new Size(480, 2000);
il.Add(l.Width);
}
int mw = Labels.Max(x => x.Width);
il.ToString();
Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
//Buttons
foreach (Button b in buttons)
{
mb.panButtons.Controls.Add(b);
b.Location = new Point(3, 3);
b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
b.Click += new EventHandler(mb.Button_Click);
}
ButtonWidth = mb.panButtons.Width;
ButtonHeight = mb.panButtons.Height;
//Set Widths
if (ButtonWidth > ImageWidth + LabelWidth)
{
Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
}
TotalWidth = ImageWidth + LabelWidth;
//Set Height
TotalHeight = LabelHeight + ButtonHeight;
mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);
mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
mb.ShowDialog();
return mb.Result;
}
private FlowLayoutPanel panText;
private FlowLayoutPanel panButtons;
private int ScrollBarWidth(List<Label> Labels)
{
return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
}
private void Button_Click(object sender, EventArgs e)
{
Result = ((Button)sender).Text;
Close();
}
private string Result = "";
}
}

Categories

Resources