I have this code which Show/open a new Form :
In the gkh_Keydown event when i click on Ctrl + M it's showing/opening the new Form .
Now i want to do that when i click again Ctrl + M it will close the new Form .
When i click once to open the new Form it's going to this Form first :
public MagnifierMainForm(bool showMain)
{
InitializeComponent();
if (showMain == true)
{
GetConfiguration();
//--- My Init ---
FormBorderStyle = FormBorderStyle.None;
TopMost = true;
StartPosition = FormStartPosition.CenterScreen;
mImageMagnifierMainControlPanel = Properties.Resources.magControlPanel20061222;
if (mImageMagnifierMainControlPanel == null)
throw new Exception("Resource cannot be found!");
Width = mImageMagnifierMainControlPanel.Width;
Height = mImageMagnifierMainControlPanel.Height;
HotSpot hsConfiguration = new HotSpot(new Rectangle(50, 15, 35, 30));
hsConfiguration.OnMouseDown += new HotSpot.MouseEventDelegate(hsConfiguration_OnMouseDown);
hsConfiguration.OnMouseUp += new HotSpot.MouseEventDelegate(hsConfiguration_OnMouseUp);
hsConfiguration.OnMouseMove += new HotSpot.MouseEventDelegate(hsConfiguration_OnMouseMove);
HotSpot hsMagnfier = new HotSpot(new Rectangle(10, 15, 30, 30));
hsMagnfier.OnMouseMove += new HotSpot.MouseEventDelegate(hsMagnfier_OnMouseMove);
hsMagnfier.OnMouseDown += new HotSpot.MouseEventDelegate(hsMagnfier_OnMouseDown);
hsMagnfier.OnMouseUp += new HotSpot.MouseEventDelegate(hsMagnfier_OnMouseUp);
HotSpot hsExit = new HotSpot(new Rectangle(95, 20, 15, 15));
hsExit.OnMouseUp += new HotSpot.MouseEventDelegate(hsExit_OnMouseUp);
mHotSpots.Add(hsConfiguration);
mHotSpots.Add(hsMagnfier);
mHotSpots.Add(hsExit);
ShowInTaskbar = false;
this.Show();
}
else
{
GetConfiguration();
int x = mLastCursorPosition.X;
int y = mLastCursorPosition.Y;
MagnifierForm magnifier = new MagnifierForm(mConfiguration, System.Windows.Forms.Cursor.Position);//mLastCursorPosition);
magnifier.Show();
}
}
And since i did false it's doing the else part :
GetConfiguration();
int x = mLastCursorPosition.X;
int y = mLastCursorPosition.Y;
MagnifierForm magnifier = new MagnifierForm(mConfiguration, System.Windows.Forms.Cursor.Position);//mLastCursorPosition);
magnifier.Show();
magnifier.Show(); do show the new Form .
Now i want that if i do Ctrl + M again it will close the Form magnifier.Show();
So in the Form in the gkh_KeyDown event in the else part i did :
magnifierform.Close();
Added a new variable this time only for magnifierform and try to close it.
So in magnifierform i did :
public MagnifierForm(Configuration configuration, Point startPoint)
{
InitializeComponent();
//--- My Init ---
mConfiguration = configuration;
FormBorderStyle = FormBorderStyle.None;
ShowInTaskbar = mConfiguration.ShowInTaskbar;
TopMost = mConfiguration.TopMostWindow;
Width = mConfiguration.MagnifierWidth;
Height = mConfiguration.MagnifierHeight;
// Make the window (the form) circular
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(ClientRectangle);
Region = new Region(gp);
mImageMagnifier = Properties.Resources.magnifierGlass;
mTimer = new Timer();
mTimer.Enabled = true;
mTimer.Interval = 20;
mTimer.Tick += new EventHandler(HandleTimer);
mScreenImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
mStartPoint = startPoint;
mTargetPoint = startPoint;
if (mConfiguration.ShowInTaskbar)
ShowInTaskbar = true;
else
ShowInTaskbar = false;
}
public MagnifierForm()
{
}
Added another instance that does nothing sincei only want to close it.
But it never closed .
magnifierform is a variable of the MagnifierForm form i want to close it directly and not as before i used the other form MagnifierMainForm.
I just want to close it but it never closed. I used a breakpoint on the line :
magnifierform.Close();
On second Ctrl + M it's getting there but it dosen't close the MagnifierForm . Just does nothing.
EDIT
Tried something else now in the MagnifierForm i added :
public MagnifierForm()
{
this.Close();
}
In Form1 in the gkh_KeyDown event in the else side i changed it to :
else
{
magnifierform = new MagnifierForm();
}
So the instance i'm doing it on the second Ctrl + M
And again the breakpoint stop there but when i do continue it's not closing the Form .
So, if MagnifierMainForm() is already open you want to close it?...otherwise create a new instance and show it? In your code that fires when Ctrl+M is pressed, do something like:
Form frmToClose = null;
foreach (Form frm in Application.OpenForms)
{
if (frm is MagnifierMainForm)
{
frmToClose = frm;
break;
}
}
if (frmToClose != null)
{
frmToClose.Close();
}
else
{
// create a new instance of MagnifierMainForm() and display it
}
use this method form.Dispose();
Related
In my windows form I create a tabpage and added controls to them. But when I close a particular tabpage and reopen it then the controls in it are incremented by one.
I mean to say, I only want to display one panelbox in tabpage when I close it and reopen it. the tabpage contains two panels.
Here is the code:
//onButtonClickEvent
TabPage tab1 = new TabPage();
tab1.Name = "CriminalRecord";
tab1.Text = "Criminal Record".ToString();
tab1.Visible = true;
tab1.BackColor = Color.Brown;
if (tabControl1.TabPages.Count != 0)
{
for (int i = 0; i <= tabControl1.TabCount; i++)
{
if (tabControl1.TabPages.Contains(tab1))
{
tabControl1.SelectTab(tab1);
}
else
{
tabControl1.Controls.Add(tab1);
tab1.Controls.Add(loadPanelBottom());
tab1.Controls.Add(loadPanel());
tab1.Controls.Add(loadPanelTop());
}
}
}
else
{
tabControl1.Controls.Add(tab1);
tab1.Controls.Add(loadPanelBottom());
tab1.Controls.Add(loadPanel());
tab1.Controls.Add(loadPanelTop());
}
Splitter loadPanel()
{
Splitter splitter1 = new Splitter();
splitter1.BackColor = SystemColors.ControlDarkDark;
splitter1.Cursor = Cursors.HSplit;
splitter1.Dock = DockStyle.Top;
splitter1.Location = new System.Drawing.Point(0, 0);
splitter1.Name = "splitter1";
splitter1.Size = new System.Drawing.Size(100, 5);
splitter1.TabIndex = 1;
return splitter1;
}
You should declare new tabpage into the form class
example
public partial class main:form
{
TabPage tab1;
}
and then
//onButtonClickEvent
TabPage tab1 = new TabPage();
tab1.Name = "CriminalRecord";
tab1.Text = "Criminal Record".ToString();
tab1.Visible = true;
tab1.BackColor = Color.Brown;
I want to change content of button1 on click event of button2 . But not able to get the object of grid's child Button class which is in List<> UiList.
Please Guide me in getting the right approach to look it and solve it . And also guide that if the object is build in runtime then how to access it ?
public partial class MainPage : PhoneApplicationPage
{
List<Grid> UIList = new List<Grid>();
Grid objGrid1 = null;
Button objButton1 = null;
Button objButton2 = null;
// Constructor
public MainPage()
{
InitializeComponent();
createGrid1("grid1");
createButton2("Button2");
}
public void createGrid1(string x)
{
objGrid1 = new Grid();
objGrid1.Height = 100;
objGrid1.Name = x;
objGrid1.Width = 200;
objGrid1.Margin = new Thickness(100, 100, 0, 0);
objGrid1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
objGrid1.VerticalAlignment = System.Windows.VerticalAlignment.Top;
objGrid1.Background = new SolidColorBrush(Colors.Orange);
createButton1("changename");
}
public void createButton1(string _name)
{
objButton1 = new Button();
objButton1.Height = 90;
objButton1.Name = _name;
objButton1.Content="Button1";
objButton1.FontSize = 20;
objButton1.Width = 190;
objButton1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
objButton1.VerticalAlignment = System.Windows.VerticalAlignment.Top;
objButton1.Background = new SolidColorBrush(Colors.Blue);
objButton1.Foreground = new SolidColorBrush(Colors.White);
objGrid1.Children.Add(objButton1);
LayoutRoot.Children.Add(objGrid1);
UIList.Add(objGrid1);
}
public void createButton2(string _name)
{
objButton2 = new Button();
objButton2.Margin = new Thickness(240, 300, 0, 0);
objButton2.Name = _name;
objButton2.Height = 90;
objButton2.Content = "Button2";
objButton2.FontSize = 20;
objButton2.Width = 190;
objButton2.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
objButton2.VerticalAlignment = System.Windows.VerticalAlignment.Top;
objButton2.Background = new SolidColorBrush(Colors.Blue);
objButton2.Foreground = new SolidColorBrush(Colors.White);
LayoutRoot.Children.Add(objButton2);
objButton2.Click += (s, e) =>
{
int c = UIList.ElementAt(0).Children.Count;
if (c == 1)
{
//logic to change content of Button1 on click of Button2
}
};
}
}
Assuming you cannot just keep a reference to the created control, such as in a class field, you can iterate through the Children property of the Grid and find the desired Button. If there are multiple buttons, you can differentiate them using the Tag property.
Once you find it, change the contents of the button using the Content property, as discussed in the contents above.
I have a dataset that returns questions and answers from the database, each answer in answer table is linked via a forgein key to the question table.
What I would like to achive is the following:
That a a single dynamic form is created on the first question with all the questions listed under it, meaning the FK_table_Answers = PK_table_Questions on the table_Answers:
(eg) This is Form for Question One:
Question One: How old are you?
Answer One (this is a radio button)
Answer Two (this is a radio button)
Answer Three (this is a radio button)
I have managed to get the above kind of working but the problem is my code keeps generating the forms (eg) 3 times becuase there are three answers, so can anyone point me in right direction how to generate the form dynamically but only ONCE - meaning each successive form is created only once as per the question and that particular questions answers under it.
Kind regards
UPDATED code:
private void LoadDataSets()
{
if (_dataSetQuestionnaire.tbl_QuestionnaireQuestion.Rows.Count == 0)
{
try
{
//Questionnaire:
DataSet1TableAdapters.tbl_QuestionnaireTableAdapter questionnaireAdapter =
new DataSet1TableAdapters.tbl_QuestionnaireTableAdapter();
questionnaireAdapter.Fill(_dataSetQuestionnaire.tbl_Questionnaire);
//Category:
DataSet1TableAdapters.tbl_QuestionnaireCategoryTableAdapter categoryAdapter =
new DataSet1TableAdapters.tbl_QuestionnaireCategoryTableAdapter();
categoryAdapter.Fill(_dataSetQuestionnaire.tbl_QuestionnaireCategory);
//QuestionnaireQuestion:
DataSet1TableAdapters.tbl_QuestionnaireQuestionTableAdapter questionnaireQuestionAdapter =
new DataSet1TableAdapters.tbl_QuestionnaireQuestionTableAdapter();
questionnaireQuestionAdapter.Fill(_dataSetQuestionnaire.tbl_QuestionnaireQuestion);
//QuestionnaieAnswer:
DataSet1TableAdapters.tbl_QuestionnaireAnswerTableAdapter questionnaireAnswerAdapter =
new DataSet1TableAdapters.tbl_QuestionnaireAnswerTableAdapter();
questionnaireAnswerAdapter.Fill(_dataSetQuestionnaire.tbl_QuestionnaireAnswer);
using (DataSet1 dSet = new DataSet1())
{
//Questionnaire:
dSet.Merge(_dataSetQuestionnaire.tbl_Questionnaire);
//Category:
dSet.Merge(_dataSetQuestionnaire.tbl_QuestionnaireCategory);
//QuestionnaireQuestion:
dSet.Merge(_dataSetQuestionnaire.tbl_QuestionnaireQuestion);
//QuestionnaieAnswer:
dSet.Merge(_dataSetQuestionnaire.tbl_QuestionnaireAnswer);
int primaryKeyQuestionnaire = Convert.ToInt32(_dataSetQuestionnaire.tbl_Questionnaire.Rows[0][0]);
foreach (DataSet1.tbl_QuestionnaireRow questionnaire
in _dataSetQuestionnaire.Tables["tbl_Questionnaire"].Select(String.Format("pk_tbl_Questionnaire = {0}", primaryKeyQuestionnaire)))
{
foreach (DataSet1.tbl_QuestionnaireCategoryRow category
in _dataSetQuestionnaire.Tables["tbl_QuestionnaireCategory"].Select(String.Format("fk_tbl_Questionnaire = {0}", questionnaire.pk_tbl_Questionnaire)))
{
foreach (DataSet1.tbl_QuestionnaireQuestionRow question
in _dataSetQuestionnaire.Tables["tbl_QuestionnaireQuestion"].Select(String.Format("fk_tbl_QuestionnaireCategory = {0}", category.pk_tbl_QuestionnaireCategory)))
{
int radiobuttonPosition = 0;
foreach (DataSet1.tbl_QuestionnaireAnswerRow answer
in _dataSetQuestionnaire.Tables["tbl_QuestionnaireAnswer"].Select(String.Format("fk_tbl_QuestionnaireQuestion = {0}", question.pk_tbl_QuestionnaireQuestion)))
{
//Gets the questins via the FK_questionnaireQuestion and fill the _dataSetRadioButtons to generate on dynamic form.
DataSet1TableAdapters.tbl_QuestionnaireAnswerTableAdapter a =
new DataSet1TableAdapters.tbl_QuestionnaireAnswerTableAdapter();
DataSet dSetRadioButtons = new DataSet();
dSetRadioButtons.Merge(a.GetDataByQuestionnaireQuestion(answer.fk_tbl_QuestionnaireQuestion));
_dataSetRadioButtons = dSetRadioButtons;
string theQuestion = question.tbl_QuestionnaireQuestion_Description.ToString();
Form form = new Form();
_form = form;
if(_form == null)
{
_form = new Form();
}
else
{
form.Height = 400;
form.Width = 550;
form.StartPosition = FormStartPosition.CenterScreen;
Label label = new Label();
label.Location = new System.Drawing.Point(5, 10);
label.Size = new System.Drawing.Size(450, 25);
label.Text = theQuestion;
Panel panel = new Panel();
panel.Size = new System.Drawing.Size(300, 200);
panel.Location = new System.Drawing.Point(15, 50);
panel.BackColor = Color.Yellow;
System.Windows.Forms.RadioButton[] radioButtons = new System.Windows.Forms.RadioButton[_dataSetRadioButtons.Tables["tbl_QuestionnaireAnswer"].Rows.Count];
for (int i = 0; i < _dataSetRadioButtons.Tables["tbl_QuestionnaireAnswer"].Rows.Count; i++)
{
radioButtons[i] = new RadioButton();
radioButtons[i].Text = _dataSetRadioButtons.Tables["tbl_QuestionnaireAnswer"].Rows[i]["tbl_QuestionnaireAnswer_Description"].ToString();
radioButtons[i].Location = new System.Drawing.Point(60, 20 + i * 20);
//panel.Controls.Add(radioButtons[i]);
radioButtons[i].Click += new EventHandler(Form1_Click);
Int64 item = Convert.ToInt64(_dataSetRadioButtons.Tables["tbl_QuestionnaireAnswer"].Rows[0].ItemArray[3].ToString());
panel.Controls.Add(radioButtons[i]);
}
Button nextButton = new Button();
nextButton.Text = "Next";
nextButton.Name = "button";
nextButton.Location = new System.Drawing.Point(200, 300);
nextButton.Size = new System.Drawing.Size(150, 25);
nextButton.Click += new EventHandler(nextButton_Click);
form.Controls.AddRange(new Control[] { panel, label, nextButton });
form.ShowDialog();
CreateBoxAndQuestion(form, panel, label);
//form.Dispose();
}
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("Error");
}
}
private void CreateBoxAndQuestion(Form f, Panel p, Label l)
{
for (int i = p.Controls.Count - 1; i >= 0; i--)
{
p.Controls.RemoveAt(i);
}
}
If I understand correctly, you call CreateBoxAndQuestion every time a new question is selected.
But you create (and destroy) the form each time your code enters in this method.
A first approach would be to keep the form, label, button and panel creation outside the method (perhaps in design mode) then passing these controls to the method as
EDIT: Somewhere in your code before entering the load of your next question:
frmQuestion _form = null; // Global
// Create a global instance and keep it without displaying
if(_form == null) _form = new frmQuestion(); // frmQuestion created with panel, label e button via FormDesigner
then when you need to populate _form call
CreateBoxAndQuestion(_form, _form.Panel, _form.Label, questionText);
In this example I pass the _form to CreateBoxAndQuestion, but this is not necessary because is a global. You could change CreateBoxAndQuestion to use directly the global instance.
private void CreateBoxAndQuestion(frmQuestion f, Panel p, Label l, string _label)
{
// Do not display your form here....
}
Now when entering the method clear every RadioButton controls in the panel.Controls collection
for (int i = p.Controls.Count - 1; i >= 0; i--)
{
p.Controls.RemoveAt(i);
}
the rest of the code should change only to reflect the new text assigned to the label and controls and the re-adding of the RadioButtons to the panel. No more creation and reinitialization for Form Label, Button.
label.Text = _label;
Don't forget to destroy _form at the end of your program with _form.Dispose();
It's been a mess to show a DialogBox at the center of its parent form. Here is a method to show a dialog.
I am positioning its parent to center but not able to center the DialogBox
private void OpenForm(Object point, Object height, Object width)
{
FormLoading frm = new FormLoading();
Point temp = (Point)point;
Point location = new Point(temp.X + (int)((int)width) / 2,
temp.Y + (int)((int)height) / 2);
frm.Location = location;
frm.ShowDialog();
}
private void btnView_Click(object sender, EventArgs e)
{
try
{
ThreadStart starter= delegate { OpenForm(currentScreenLocation,
this.Height, this.Width); };
Thread t = new Thread(starter);
t.Start();
////// Some functionality here...
t.Abort();
}
catch (Exception)
{
}
}
You might want to check the Form.StartPosition property.
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.startposition.aspx
something along the lines of:
private void OpenForm(Form parent)
{
FormLoading frm = new FormLoading();
frm.Parent = parent;
frm.StartPosition = FormStartPosition.CenterParent;
frm.ShowDialog();
}
This of course requires setting the form's parent.
form1.StartPosition = FormStartPosition.CenterScreen;
See http://msdn.microsoft.com/en-us/library/system.windows.forms.form.startposition(v=vs.110).aspx
if you are making a custom MessageBox,you can simply put this:
CenterToParent();
in your custom MessageBox formload() method.
In addition, if you want to set up arbitrary location you can use this
FormLoading frm = new FormLoading();
Point location = new Point(300, 400);
frm.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
frm.Location = location;
frm.ShowDialog();
NewForm.Show();
NewForm.Top = (this.Top + (this.Height / 2)) - NewForm.Height / 2;
NewForm.Left = (this.Left + (this.Width / 2)) - NewForm.Width / 2;
Is it possible to create my own custom MessageBox where I would be able to add images instead of only strings?
I also wanted this feature, so I created WPFCustomMessageBox, a WPF clone of the native Windows/.NET MessageBox which supports extra features like custom button text.
WPFCustomMessageBox uses static methods just like the standard .NET MessageBox, so you can plug-and-play the new library without modifying any code. Most importantly, I designed this control so it looks identical to the original MessageBox.
I created this library because I wanted to use verbs for my MessageBox buttons to help users better understand the functionality of the buttons. With this library, you can offer your users button descriptions like Save/Don't Save or Eject Fuel Rods/Don't do it! rather than the standard OK/Cancel or Yes/No (although you can still use those too, if you like).
The WPFCustomMessageBox message boxes return standard .NET MessageBoxResults. It also offers the same features as the original MessageBox like MessageBoxIcons and custom message box captions.
WPFCustomMessageBox is open source, so you can grab the code or make improvements here: https://github.com/evanwon/WPFCustomMessageBox
You can add WPFCustomMessage to your project via NuGet: https://www.nuget.org/packages/WPFCustomMessageBox/
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);
}
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 = "";
}
}
This took me 2 days to write. I hope it works for anyone that needs it.
I've implemented a WPF MessageBox fully customizable via standard WPF control templates:
http://blogs.microsoft.co.il/blogs/arik/archive/2011/05/26/a-customizable-wpf-messagebox.aspx
Features
The class WPFMessageBox has the exact same interface as the current WPF MessageBox class.
Implemented as a custom control, thus fully customizable via standard WPF control templates.
Has a default control template which looks like the standard MessageBox.
Supports all the common types of message boxes: Error, Warning, Question and Information.
Has the same “Beep” sounds as when opening a standard MessageBox.
Supports the same behavior when pressing the Escape button as the standard MessageBox.
Provides the same system menu as the standard MessageBox, including disabling the Close button when the message box is in Yes-No mode.
Handles right-aligned and right-to-left operating systems, same as the standard MessageBox.
Provides support for setting the owner window as a WinForms Form control.
Sure. I've done it by subclassing System.Windows.Window and adding the capacity to show various kinds of content (images, text and controls), and then calling ShowDialog() on that Window:
public partial class MyMessageBox : Window
{
// perhaps a helper method here
public static bool? Show(String message, BitmapImage image)
{
// NOTE: Message and Image are fields created in the XAML markup
MyMessageBox msgBox = new MyMessageBox() { Message.Text = message, Image.Source = image };
return msgBox.ShowDialog();
}
}
In the XAML, something like this:
<Window>
<DockPanel>
<Image Name="Image" DockPanel.Dock="Left" />
<TextBlock Name="Message" />
</DockPanel>
</Window>
I was in need like you and I have found this source and modified the way I wanted and you could get the most benefit out of it
here is the link
this is what it looks like by default: