NotifyIcon not showing - c#

I am writing a simple application that I would like to control with a notifyIcon rather than a form, I have follwed examples I found through Google, but my notifyIcon will not show up. What am I doing wrong?
static class MainEntryClass
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
C2F TestApp = new C2F();
Application.Run();
TestApp.Dispose();
}
}
class C2F
{
public C2F()
{
InitializeComponent();
loadSettings();
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(C2F));
this.niC2F = new System.Windows.Forms.NotifyIcon(this.components);
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.separatorToolStripMenuItem = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStrip1.SuspendLayout();
//
// niC2F
//
this.niC2F.BalloonTipText = "MyApp";
this.niC2F.Icon = ((System.Drawing.Icon)(Clipboard2File.Properties.Resources.ResourceManager.GetObject("MyIcon.ico")));
this.niC2F.Text = "MyApp";
this.niC2F.ContextMenuStrip = this.contextMenuStrip1;
this.niC2F.ShowBalloonTip(5);
this.niC2F.Visible = true;
this.niC2F.MouseClick += new System.Windows.Forms.MouseEventHandler(this.niC2F_MouseClick);
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.settingsToolStripMenuItem,
this.separatorToolStripMenuItem,
this.exitToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(153, 76);
//
// settingsToolStripMenuItem
//
this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem";
this.settingsToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.settingsToolStripMenuItem.Text = "Settings";
this.settingsToolStripMenuItem.Click += new System.EventHandler(this.settingsToolStripMenuItem_Click);
//
// separatorToolStripMenuItem
//
this.separatorToolStripMenuItem.Name = "separatorToolStripMenuItem";
this.separatorToolStripMenuItem.Size = new System.Drawing.Size(149, 6);
this.separatorToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// exitToolStripMenuItem1
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem1";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.exitToolStripMenuItem.Text = "Exit";
}
private System.ComponentModel.IContainer components = null;
private Form1 frmSettings = new Form1();
private Settings C2FSettings = new Settings();
private System.Windows.Forms.NotifyIcon niC2F;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator separatorToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
}

I actually just finished a project that started as a NotifyIcon. Your code (I'm guessing you just provided a snippet) is incredibly similar to mine.
I checked your code, and the only change I had to make to get it to work was changing the way you called the icon to:
this.niC2F.Icon = new System.Drawing.Icon(#"C:\PathToIcon\iconfile.ico");
Below is a working sample with a right-click menu and double-click functionality:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace TestApp
{
static class MainEntryClass
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
C2F TestApp = new C2F();
Application.Run();
}
}
class C2F
{
System.ComponentModel.Container component;
System.Drawing.Icon icon;
ContextMenuStrip rightClickMenu = new ContextMenuStrip();
NotifyIcon trayIcon;
ToolStripMenuItem options = new ToolStripMenuItem();
ToolStripMenuItem restore = new ToolStripMenuItem();
ToolStripMenuItem exit = new ToolStripMenuItem();
ToolStripSeparator seperator = new ToolStripSeparator();
public C2F()
{
InitializeComponent();
}
private void InitializeComponent()
{
icon = new System.Drawing.Icon(#"C:\PathToIcon\iconfile.ico");
component = new System.ComponentModel.Container();
trayIcon = new NotifyIcon(component);
trayIcon.Text = "Bill Reminder";
trayIcon.Icon = icon;
trayIcon.Visible = true;
trayIcon.DoubleClick += new EventHandler(trayIcon_DoubleClick);
trayIcon.ContextMenuStrip = rightClickMenu;
rightClickMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[]
{
options,
seperator,
restore,
exit
});
options.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
options.Text = "Options";
options.Click += new EventHandler(options_Click);
restore.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
restore.Text = "Restore Window";
restore.Click += new EventHandler(restore_Click);
exit.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
exit.Text = "Exit";
exit.Click += new EventHandler(exit_Click);
}
void exit_Click(object sender, EventArgs e)
{
Application.Exit();
}
void restore_Click(object sender, EventArgs e)
{
FormName showWindow = new FormName();
showWindow.Show();
}
void options_Click(object sender, EventArgs e)
{
Settings_Window settings = new Settings_Window();
settings.Show();
}
void trayIcon_DoubleClick(object sender, EventArgs e)
{
FormName showWindow = new FormName();
showWindow.Show();
}
}
}
Hope this helps you, let me know if you have any questions!

One more reason why NotifyIcon is not shown is if Windows Explorer is running with elevated privileges while your tray application isn't (only on systems with UAC of course).
This can happen if explorer.exe crashed or was killed, and then user manually restarted it from the elevated Task Manager.
NotifyIcon control uses Shell_NotifyIcon native method inside, but doesn't check for the return value. If Shell_NotifyIcon returns FALSE, you won't be ever notified.
I had to breakpoint with WinDbg on Shell_NotifyIcon and GetLastError gave me ERROR_ACCESS_DENIED. So I realized that there's a permission issue, and it might be caused by restarted explorer elevation. Further tests confirmed this assumption.
However this is rather rare case.

Related

c# How to swap between forms

My application has a need to hide an initial form and open any one of four new forms. I can hide the initial and open the selected form with:
private void btn_Option1_Click(object sender, EventArgs e){
Visible = false;
Application x = new Application();
x.show();
}
My question is how to close the second form and reopen the original form? Or I suppose it would be plausible to close each form on each form opening, but that seems wasteful.
It sounds like you need the FormClosed event.
When you create instances of the new Form from your initial Form you can subscribe to the new Form's FormClosed event and show your initial Form from the handler.
This way, whenever one of your new Forms close, the event handler will fire and your initial Form will become visible again.
// This is a method that you would add to your initial Form.
private void SubForm_Closed(object sender, FormClosedEventArgs e)
{
Visible = true;
}
private void btn_Option1_Click(object sender, EventArgs e)
{
Visible = false;
Application x = new Application();
x.FormClosed += SubForm_Closed;
x.show();
}
If you use Hide(), the form "essentially" disappears, you won't even see it in the taskbar. Then you can open by Showing it from one of the subsequent forms. I threw the below together and only tested it quickly so YMMV, you'll need to clean it up and make it work for you, but it should illustrate the point. Create a Windows Form Application. Call it "WindowsFormsApp2" since that's what I used. Paste in the below code:
using System;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 form2;
Form3 form3;
Form4 form4;
Form5 form5;
private void button1_Click_1(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
form2 = new Form2(this);
form2.Show();
}
if (checkBox2.Checked)
{
form3 = new Form3(this);
form3.Show();
}
if (checkBox3.Checked)
{
form4 = new Form4(this);
form4.Show();
}
if (checkBox4.Checked)
{
form5 = new Form5(this);
form5.Show();
}
this.Hide();
}
}
}
Paste the below code into the Form1 designer:
namespace WindowsFormsApp2
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.checkBox2 = new System.Windows.Forms.CheckBox();
this.checkBox3 = new System.Windows.Forms.CheckBox();
this.checkBox4 = new System.Windows.Forms.CheckBox();
this.button1 = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.checkBox4);
this.groupBox1.Controls.Add(this.checkBox3);
this.groupBox1.Controls.Add(this.checkBox2);
this.groupBox1.Controls.Add(this.checkBox1);
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(274, 73);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Forms";
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(17, 32);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(55, 17);
this.checkBox1.TabIndex = 0;
this.checkBox1.Text = "Form2";
this.checkBox1.UseVisualStyleBackColor = true;
//
// checkBox2
//
this.checkBox2.AutoSize = true;
this.checkBox2.Location = new System.Drawing.Point(78, 32);
this.checkBox2.Name = "checkBox2";
this.checkBox2.Size = new System.Drawing.Size(55, 17);
this.checkBox2.TabIndex = 1;
this.checkBox2.Text = "Form3";
this.checkBox2.UseVisualStyleBackColor = true;
//
// checkBox3
//
this.checkBox3.AutoSize = true;
this.checkBox3.Location = new System.Drawing.Point(139, 32);
this.checkBox3.Name = "checkBox3";
this.checkBox3.Size = new System.Drawing.Size(55, 17);
this.checkBox3.TabIndex = 2;
this.checkBox3.Text = "Form4";
this.checkBox3.UseVisualStyleBackColor = true;
//
// checkBox4
//
this.checkBox4.AutoSize = true;
this.checkBox4.Location = new System.Drawing.Point(200, 32);
this.checkBox4.Name = "checkBox4";
this.checkBox4.Size = new System.Drawing.Size(55, 17);
this.checkBox4.TabIndex = 3;
this.checkBox4.Text = "Form5";
this.checkBox4.UseVisualStyleBackColor = true;
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 91);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(199, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Open Selected Forms";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click_1);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.button1);
this.Controls.Add(this.groupBox1);
this.Name = "Form1";
this.Text = "Form1";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox checkBox4;
private System.Windows.Forms.CheckBox checkBox3;
private System.Windows.Forms.CheckBox checkBox2;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.Button button1;
}
}
Add 4 Windows Forms: Form2, Form3, Form4 and Form5.
Paste in the below code to each and just change the form name on each to it's correct name (Form3, Form4, Form5):
using System;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form2 : Form
{
public Form2(Form1 Form1In)
{
InitializeComponent();
form1 = Form1In;
}
Form1 form1;
private void button1_Click(object sender, EventArgs e)
{
form1.Show();
}
}
}
Finally paste in the below code to the designer of each form and change the name for the forms other than Form2 to their respective name:
namespace WindowsFormsApp2
{
partial class Form2
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(22, 21);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(104, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Show Form1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.button1);
this.Name = "Form2";
this.Text = "Form2";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
}
}
Then run it.
Here's a shiny new wheel. It concentrates all the logic in a Manager class.
A SubForm Base Class
First, we'll create a base class for all the sub forms. This way, you don't need to put the form switching logic into every form.
Create a new Form in your project, name it ShowHideFormBase , change to the "View Code" view and change the boilerplate so it looks like this:
public partial class ShowHideFormBase : Form
{
public ShowHideFormManager Manager { get; private set; }
public ShowHideFormBase()
{
Manager = null;
InitializeComponent();
}
public void SetManager (ShowHideFormManager manager)
{
Manager = manager;
}
}
We'll create the Manager class in a bit
I really wanted to have a constructor on ShowHideFormBase that took a ShowHideFormManager instance as a parameter. The Windows Forms designer really doesn't like having forms base classes with non-default constructors. Such is life.
In the designer for this form, show the properties of the form, and change to the Events view (the lightening bolt icon). Double-click on the FormClosing event. That will add this code for a ShowHideWindowBase_FormClosing handler to your base class. Change it so it looks like this.
private void ShowHideWindowBase_FormClosing(object sender, FormClosingEventArgs e)
{
Debug.Assert(Manager != null); //Make sure that SetManager was called
e.Cancel = true;
Manager.HideAll();
}
The e.Cancel=true; says "I know someone tried to close this form, don't let it close". Instead, we'll cause all the sub forms to be hidden including this one.
That class is done. Now let's do the manager class.
The Manager
Create a new class in your project name ShowHideFormManager. Use this code:
public class ShowHideFormManager
{
private Dictionary<string, ShowHideFormBase> _forms = new Dictionary<string, ShowHideFormBase>();
private Form _mainForm;
public ShowHideFormManager(Form mainForm)
{
_mainForm = mainForm;
}
// This will add a sub form to be managed
public void Add(string windowsName, ShowHideFormBase form)
{
_forms.Add(windowsName, form);
}
// This will hide all managed sub forms and show the main form
public void HideAll()
{
_mainForm.Show();
foreach (var formPair in _forms)
{
formPair.Value.Hide();
}
}
// this will hide the main form and show the named sub form
public void Show(string formToShowName)
{
_mainForm.Hide();
foreach (var formPair in _forms)
{
if (formPair.Key != formToShowName)
{
formPair.Value.Hide();
}
}
if (_forms.TryGetValue(formToShowName, out var formToShow))
{
formToShow.Show();
}
}
}
Note that the shiny new wheel is up to about 75 or 80 lines of code.
The Application's Main Form
I'm assuming that you have a form named Form1 in your application (the one that gets created when you create your application.
Add this private field:
private ShowHideFormManager _manager = null;
and this public method:
public void SetManager(ShowHideFormManager manager)
{
_manager = manager;
}
Drop three buttons on the main form, set their Name properties to "SubForm1Btn", "SubForm2Btn", and "SubForm3Btn" and set the Text properties to something useful. In the click handlers do something like this for each button:
private void SubForm1Btn_Click(object sender, EventArgs e)
{
_manager.Show("Sub Form 1");
}
changing the numbers, obviously
The Sub Forms
Now create three new forms in your project. Name the classes SubForm1, SubForm2 and SubForm3.
Note, I create three sub forms, not 4 - creating the fourth would be easy
Open the code view for each form. The only change we are going to make to these three forms is to change the class declaration and constructor to:
public partial class SubForm1 : ShowHideFormBase
{
public SubForm1(ShowHideFormManager manager)
{
InitializeComponent();
SetManager(manager);
}
}
For all three forms: 1, 2, and 3, obviously
This changes the base class from Form to ShowHideFormBase. It also makes it so each of these forms must be initialized with a ShowHideFormManager instance, and we call SetManager (which is a base class method) to initialize the form with the manager.
Finally, changes to Program.cs
Finally, we'll make some minor changes to the Main method in Program.cs. These changes:
Create the Manager
Instantiate the main form as well as the three sub forms.
And call the normal Application.Run method
Here's the new Main method:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var mainForm = new Form1();
var manager = new ShowHideFormManager(mainForm);
mainForm.SetManager(manager);
var subForm1 = new SubForm1(manager);
var subForm2 = new SubForm2(manager);
var subForm3 = new SubForm3(manager);
manager.Add("Sub Form 1", subForm1);
manager.Add("Sub Form 2", subForm2);
manager.Add("Sub Form 3", subForm3);
Application.Run(mainForm);
}
Important: The strings you use in the manager.Add call (e.g. "Sub Form 1") must exactly match the string you pass in each of the calls to _manager.Show("Sub Form 1"); in the button handlers. When I finished this, I decided that I should have used an enum, but everything was working.
How it Works
Press F5 and the main form (with three buttons on it) should pop up. Press any of the buttons and the corresponding form will pop up (and the main form will hide). Close the sub form, and the main form will re-open letting you press that button again or another button.
While you are looking at this, notice that there are almost no changes to the Main Form or the Sub Forms. The magic is all in the form base class and the manager class. You can do whatever you want with any of the forms (as long as you get those minimal changes in the right places.

Variable not updating on closing a new pop up form after clicking button

I am trying to make a button that when clicked pops up a new form with a yes and no button and then make an if statement based on what button is pressed. Here is my current code:
private YesNoMessageBoxResized newBoxResized;
private string buttonClickResult;
public void YesNoNewMessageBox(string title, string message,string buttonYes, string buttonNo)
{
YesNoMessageBoxResized msgResized = new YesNoMessageBoxResized(title, message, buttonYes, buttonNo);
msgResized.StartPosition = FormStartPosition.CenterScreen;
msgResized.TopMost = true;
Button yesButtonResize = new Button();
Button noButtonResize = new Button();
//yes button
yesButtonResize.Text = buttonYes;
yesButtonResize.Size = new Size(150, 80);
yesButtonResize.Font = new Font("Arial", 26);
yesButtonResize.Location = new Point(100, 150);
//no button
noButtonResize.Text = buttonNo;
noButtonResize.Size = new Size(150, 80);
noButtonResize.Font = new Font("Arial", 26);
noButtonResize.Location = new Point(300, 150);
//make a copy of the current form
newBoxResized = msgResized;
//eventhandlers
yesButtonResize.Click += YesButtonResizeClicked;
noButtonResize.Click += noButtonResizeClicked;
newBoxResized.Controls.Add(yesButtonResize);
newBoxResized.Controls.Add(noButtonResize);
msgResized.Show();
}
private void YesButtonResizeClicked(object o, EventArgs sEA)
{
this.buttonClickResult = "true";
this.newBoxResized.Close();
}
private void noButtonResizeClicked(object o, EventArgs sEA)
{
this.buttonClickResult = "false";
this.newBoxResized.Close();
}
private void buttonRestoreDefaults_Click(object sender, EventArgs e)
{
YesNoNewMessageBox("Restore Defaults?", "Restore Defaults?", "Yes", "No");
if (this.buttonClickResult == "true")
this.restoreDefaults();
}
My problem is that after hitting yes and closing the form that pops up, buttonClickResult is not seen as true and therefore the restore default function I am calling is not called. Only when clicking on the "RestoreDefaults" button again is the function called. So, it seems that the onclick event for buttonRestoreDefaults_Click isn't reconizing the onclick for the yes or no buttons in the form that popups until clicking on it again. Is there a way around this or some sort of implementation to fix this? Thank you.
Also, here is the code for the class. I was thinking about using delegates and event handlers, but I am not sure if I actually need that since what I have works, but just doesn't update the variable on closing correctly:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class YesNoMessageBoxResized : Form
{
private Label labelMessage;
//no default button specified
public YesNoMessageBoxResized(string title, string message, string buttonYes, string buttonNo)
{
InitializeComponent();
this.Text = title;
this.labelMessage.Text = message;
this.Deactivate += MyDeactivateHandler;
}
public YesNoMessageBoxResized()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.labelMessage = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// labelMessage
//
this.labelMessage.AutoSize = true;
this.labelMessage.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelMessage.Location = new System.Drawing.Point(12, 31);
this.labelMessage.Name = "labelMessage";
this.labelMessage.Size = new System.Drawing.Size(165, 29);
this.labelMessage.TabIndex = 3;
this.labelMessage.Text = "labelMessage";
//
// YesNoMessageBoxResized
//
this.ClientSize = new System.Drawing.Size(572, 268);
this.Controls.Add(this.labelMessage);
this.Name = "YesNoMessageBoxResized";
this.ResumeLayout(false);
this.PerformLayout();
}
protected void MyDeactivateHandler(object sender, EventArgs e)
{
this.Close();
}
public delegate void buttonYes_ClickResultEvent(object o, EventArgs sEA);
public event buttonYes_ClickResultEvent choiceResult;
}
public class buttonYes_ClickResultEvent : EventArgs
{
public buttonYes_ClickResultEvent(bool choice)
{
this.buttonResult = choice;
}
public bool buttonResult;
}
**I posted this on codereview, but then they told me to post it here since it deals with solving a problem.
just for a test, try using a global variable and set that to true within your yesbuttonresizedclicked event.
something like
public static bool yestest = false;
private void YesButtonResizeClicked(object o, EventArgs sEA)
{
yestest = true;
}
I sort of fixed it by adding a function that had the if statement withing the other button events. I am open to other solutions though:
private YesNoMessageBoxResized newBoxResized;
private string buttonClickResult;
public void YesNoNewMessageBox(string title, string message,string buttonYes, string buttonNo)
{
YesNoMessageBoxResized msgResized = new YesNoMessageBoxResized(title, message, buttonYes, buttonNo);
msgResized.StartPosition = FormStartPosition.CenterScreen;
msgResized.TopMost = true;
Button yesButtonResize = new Button();
Button noButtonResize = new Button();
//yes button
yesButtonResize.Text = buttonYes;
yesButtonResize.Size = new Size(150, 80);
yesButtonResize.Font = new Font("Arial", 26);
yesButtonResize.Location = new Point(100, 150);
//no button
noButtonResize.Text = buttonNo;
noButtonResize.Size = new Size(150, 80);
noButtonResize.Font = new Font("Arial", 26);
noButtonResize.Location = new Point(300, 150);
//make a copy of the current form
newBoxResized = msgResized;
//eventhandlers
yesButtonResize.Click += YesButtonResizeClicked;
noButtonResize.Click += noButtonResizeClicked;
newBoxResized.Controls.Add(yesButtonResize);
newBoxResized.Controls.Add(noButtonResize);
newBoxResized.Show();
}
private void YesButtonResizeClicked(object o, EventArgs sEA)
{
this.buttonClickResult = "true";
this.DoIfStatement();
this.newBoxResized.Close();
}
private void noButtonResizeClicked(object o, EventArgs sEA)
{
this.buttonClickResult = "false";
this.DoIfStatement();
this.newBoxResized.Close();
}
private void DoIfStatement()
{
if (buttonClickResult == "true")
this.restoreDefaults();
}
private void buttonRestoreDefaults_Click(object sender, EventArgs e)
{
YesNoNewMessageBox("Restore Defaults?", "Restore Defaults?", "Yes", "No");
}
I think I need it to be more modular though. I don't always want the same if statement there. So, I don't always want to be a yes and no with regards to restore defaults. I may want it to do something else with another function call and have yes and no buttons do something else.
You can just use MessageBox to do this for you:
if (MessageBox.Show("Yes or no?", "", MessageBoxButtons.YesNo)
== DialogResult.Yes)
You could change the form to a modal dialog form. Make the Accept and Cancel buttons properties equal the appropriate button. Then change the dialog result of each button to the appropriate value. Now when you use the ShowDialog the form will return the appropriate DialogResult.

Panel visibility not changing in C# visual studio 2010

I'm trying to do something that i would think to be rather simple. I have 2 toolstrip items.
test1: ToolStripMenuItem which should show panel -> test_panel_1
test2: ToolStripMenuItem which should show panel -> panel1
test_panel_1 contains button -> panel_1_button1 which should hide test_panel_1 and show test_panel_2
panel1 contains button -> button1 which should hide test_panel2 and then show panel2
However, when I run the code and click on test1ToolStripMenuItem it shows test_panel_1 like it's supposed to, then when i click on panel_1_button_1 it just clears test_panel_1 and doesn't show test_panel_2. And regardless of what I click first, test2ToolStripMenuItem doesn't show panel1 at all.
Here's my code...
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 panel_test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel_1_button1_Click(object sender, EventArgs e)
{
test_panel2.Visible = true;
test_panel_1.Visible = false;
}
private void test1ToolStripMenuItem_Click(object sender, EventArgs e)
{
test_panel_1.Visible = true;
panel1.Visible = false;
}
private void button1_click(object sender, EventArgs e)
{
test_panel_1.Visible = false;
test_panel2.Visible = true;
}
private void test2ToolStripMenuItem_Click(object sender, EventArgs e)
{
test_panel2.Visible = false;
panel1.Visible = true;
}
private void button1_Click_1(object sender, EventArgs e)
{
this.panel1.Visible = false;
this.panel2.Visible = true;
}
}
}
and, not sure if this helps, but...
namespace panel_test
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.testToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.test1ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.test2ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.test3ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.test_panel_1 = new System.Windows.Forms.Panel();
this.panel1 = new System.Windows.Forms.Panel();
this.button1 = new System.Windows.Forms.Button();
this.panel2 = new System.Windows.Forms.Panel();
this.label3 = new System.Windows.Forms.Label();
this.test_panel2 = new System.Windows.Forms.Panel();
this.label2 = new System.Windows.Forms.Label();
this.panel_1_button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.menuStrip1.SuspendLayout();
this.test_panel_1.SuspendLayout();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.test_panel2.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.testToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(467, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// testToolStripMenuItem
//
this.testToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.test1ToolStripMenuItem,
this.test2ToolStripMenuItem,
this.test3ToolStripMenuItem});
this.testToolStripMenuItem.Name = "testToolStripMenuItem";
this.testToolStripMenuItem.Size = new System.Drawing.Size(38, 20);
this.testToolStripMenuItem.Text = "test";
//
// test1ToolStripMenuItem
//
this.test1ToolStripMenuItem.Name = "test1ToolStripMenuItem";
this.test1ToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.test1ToolStripMenuItem.Text = "test1";
this.test1ToolStripMenuItem.Click += new System.EventHandler(this.test1ToolStripMenuItem_Click);
//
// test2ToolStripMenuItem
//
this.test2ToolStripMenuItem.Name = "test2ToolStripMenuItem";
this.test2ToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.test2ToolStripMenuItem.Text = "test2";
this.test2ToolStripMenuItem.Click += new System.EventHandler(this.test2ToolStripMenuItem_Click);
//
// test3ToolStripMenuItem
//
this.test3ToolStripMenuItem.Name = "test3ToolStripMenuItem";
this.test3ToolStripMenuItem.Size = new System.Drawing.Size(99, 22);
this.test3ToolStripMenuItem.Text = "test3";
//
// test_panel_1
//
this.test_panel_1.Controls.Add(this.test_panel2);
this.test_panel_1.Controls.Add(this.panel_1_button1);
this.test_panel_1.Controls.Add(this.label1);
this.test_panel_1.Location = new System.Drawing.Point(44, 28);
this.test_panel_1.Name = "test_panel_1";
this.test_panel_1.Size = new System.Drawing.Size(442, 317);
this.test_panel_1.TabIndex = 1;
this.test_panel_1.Visible = false;
//
// panel1
//
this.panel1.Controls.Add(this.button1);
this.panel1.Location = new System.Drawing.Point(218, 187);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(328, 318);
this.panel1.TabIndex = 1;
this.panel1.Visible = false;
//
// button1
//
this.button1.Location = new System.Drawing.Point(86, 155);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "panel 3 to 4";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click_1);
//
// panel2
//
this.panel2.Controls.Add(this.panel1);
this.panel2.Controls.Add(this.label3);
this.panel2.Location = new System.Drawing.Point(95, 194);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(398, 260);
this.panel2.TabIndex = 1;
this.panel2.Visible = false;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(86, 118);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(71, 13);
this.label3.TabIndex = 0;
this.label3.Text = "this is panel 4";
//
// test_panel2
//
this.test_panel2.Controls.Add(this.panel2);
this.test_panel2.Controls.Add(this.label2);
this.test_panel2.Location = new System.Drawing.Point(154, 101);
this.test_panel2.Name = "test_panel2";
this.test_panel2.Size = new System.Drawing.Size(358, 237);
this.test_panel2.TabIndex = 3;
this.test_panel2.Visible = false;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(70, 118);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(71, 13);
this.label2.TabIndex = 0;
this.label2.Text = "this is panel 2";
//
// panel_1_button1
//
this.panel_1_button1.Location = new System.Drawing.Point(86, 155);
this.panel_1_button1.Name = "panel_1_button1";
this.panel_1_button1.Size = new System.Drawing.Size(75, 23);
this.panel_1_button1.TabIndex = 2;
this.panel_1_button1.Text = "button1";
this.panel_1_button1.UseVisualStyleBackColor = true;
this.panel_1_button1.Click += new System.EventHandler(this.panel_1_button1_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(28, 21);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(42, 13);
this.label1.TabIndex = 0;
this.label1.Text = "panel 1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(467, 357);
this.Controls.Add(this.test_panel_1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "Form1";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.test_panel_1.ResumeLayout(false);
this.test_panel_1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.test_panel2.ResumeLayout(false);
this.test_panel2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem testToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem test1ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem test2ToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem test3ToolStripMenuItem;
private System.Windows.Forms.Panel test_panel_1;
private System.Windows.Forms.Panel test_panel2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button panel_1_button1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button button1;
}
}
I've toyed with Usercontrols a little, and i like the way i can edit and view them much better than panels; however, i don't know how to control hiding and showing them.
Thanks for the help. I know this must be coding 101, but it's something i haven't quite fully figured out yet.
It looks like your test_panel_2 is a child of test_panel_1. panel1 is a child of panel2. This is likely not what you intended. What's happening is that, because test_panel_2 is inside test_panel_1, hiding test_panel_1 also hides test_panel_2. There's a hierarchy there.
There's one or two spots where you set the visibility to false again - I'm not sure if those are correct.

C# - Update textbox on forms created in code

I have a main form called mainForm - this runs my entire app.
In this form I create other forms like this:
......
......
Form[] formMessage = new Form[10];
int formNumber = 0;
System.Windows.Forms.Button btnCancel;
System.Windows.Forms.Button btnClose;
System.Windows.Forms.Label lblTimer;
System.Windows.Forms.Button btnOK;
System.Windows.Forms.Panel panel1;
System.Windows.Forms.Label lblMessage;
System.Windows.Forms.PictureBox pictureBox1;
System.Windows.Forms.Label lblTitle;
......
......
public void CreateForm(Form form2)
{
this.btnCancel = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.lblTimer = new System.Windows.Forms.Label();
this.btnOK = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.lblMessage = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.lblTitle = new System.Windows.Forms.Label();
//
........
//
// lblTimer
//
this.lblTimer.AutoSize = true;
this.lblTimer.BackColor = System.Drawing.Color.Transparent;
this.lblTimer.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblTimer.Location = new System.Drawing.Point(9, 120);
this.lblTimer.Name = "lblTimer";
this.lblTimer.Size = new System.Drawing.Size(0, 16);
this.lblTimer.Visible = Show_Timer;
this.lblTimer.TabIndex = 4;
form2.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
form2.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
form2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
form2.ClientSize = new System.Drawing.Size(400, 142);
form2.ControlBox = false;
form2.Controls.Add(this.pictureBox1);
form2.Controls.Add(this.panel1);
form2.Controls.Add(this.btnOK);
form2.Controls.Add(this.lblTimer);
form2.Controls.Add(this.btnCancel);
form2.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
form2.Opacity = 0.98;
form2.ShowInTaskbar = false;
form2.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
form2.Tag = formNumber;
form2.Paint += new System.Windows.Forms.PaintEventHandler(this.MyMessageBox_Paint);
}
private void FNeventTrigger(System.Object sender, System.EventArgs e)
{
formMessage[formNumber] = new Form();
CreateForm(formMessage[formNumber]);
formMessage[formNumber].Show();
formNumber++;
if (formNumber == 10)
formNumber = 0;
}
public void lbl_timer_UpdateText()
{
this.lblTimer.Text = newText
}
I use the FNeventRigger to create my form, and I can have upto 10 of them open at each given time - I use this for showing count down timers.
The problem I have is how do I show the count down timer of each form?
If I use : this.lblTimer.Text = newText, then only the newest form that was opened displays the correct timer.... the other forms lblTimer.Text stop functioning.
Is there a way to address all the lblTimer.Text on all forms opened on the array?
Thanks,
Create your own form class which defines the Label an a method to update this method.
and then initiate all your forms using this new MyBaseForm
public MyBaseForm : Form
{
private Label lblTimer;
public MyBaseForm()
{
lblTimer = new Label();
Controls.Add(lblTimer);
}
public void UpdateTimerText(string text)
{
lblTimer.Text = text;
}
}

C# issue: How do I manipulate a Textbox on one form from another form?

I'm trying to create my own error window for the project I am working on. When I show my error window I have no way to pass the error message, and user message to the Error window because the "ErrorMessage.Text" cannot be seen in the classes I make.
I went into the form designer generated code and tried to make the TextBox static, but that just breaks things. Can I make a TextBox public / static so I can change it from another form?
How do I make a TextBox Static Public so I can manipulate it across other forms, or is there another method for doing this?
EDIT:
Okay, for more information...
I have my own Form created. It is called "formErrorWindow." I need to display the form that i've pre-designed with the message set from another form. The only way I can do this is if I create a Function in the windows designer area for the form, and I set the variables with "this.errorMsg.text = error." The only way I can see that function is if I set it to static. If I set the function to Static, when I try and put "this.errorMsg.Text = error" I get this error: An object reference is required for the non-static field, method, or property.
Here is what I've attempted:
namespace LCR_ShepherdStaffupdater_1._0
{
partial class formErrorWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
public System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
///
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
// ********* HERE IS THE FUNCTION THAT IVE ADDED BELOW. THIS WOULD WORK BUT.... *********
public static void showError(string errorTitle, string usrMsg, string errorMsg)
{
formErrorWindow errorWindow = new formErrorWindow();
errorMsgItem.Text = errorMsg;
errorTitleItem.Text = "Error! : " + errorTitle;
usrMsgItem.Text = usrMsg;
errorWindow.ShowDialog();
}
// ********* HERE IS THE FUNCTION THAT IVE ADDED ABOVE. THIS WOULD WORK BUT.... *********
// ********* I get an error: "An object reference is required for the non-static field, method, or property." *********
public void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(formErrorWindow));
this.usrMsgItem = new System.Windows.Forms.TextBox();
this.errorTitleItem = new System.Windows.Forms.Label();
this.errorMsgItem = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.label2 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// usrMsgItem
//
this.usrMsgItem.Enabled = false;
this.usrMsgItem.Location = new System.Drawing.Point(13, 37);
this.usrMsgItem.Multiline = true;
this.usrMsgItem.Name = "usrMsgItem";
this.usrMsgItem.Size = new System.Drawing.Size(334, 81);
this.usrMsgItem.TabIndex = 0;
this.usrMsgItem.Text = "Undefined";
//
// errorTitleItem
//
this.errorTitleItem.AutoSize = true;
this.errorTitleItem.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.errorTitleItem.ForeColor = System.Drawing.Color.Red;
this.errorTitleItem.Location = new System.Drawing.Point(12, 9);
this.errorTitleItem.Name = "errorTitleItem";
this.errorTitleItem.Size = new System.Drawing.Size(152, 20);
this.errorTitleItem.TabIndex = 1;
this.errorTitleItem.Text = "Error! : Undefined";
//
// errorMsgItem
//
this.errorMsgItem.Enabled = false;
this.errorMsgItem.Location = new System.Drawing.Point(0, 21);
this.errorMsgItem.Multiline = true;
this.errorMsgItem.Name = "errorMsgItem";
this.errorMsgItem.Size = new System.Drawing.Size(329, 101);
this.errorMsgItem.TabIndex = 2;
this.errorMsgItem.Text = "Undefined";
//
// button1
//
this.button1.Location = new System.Drawing.Point(272, 256);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Continue";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.errorMsgItem);
this.panel1.Location = new System.Drawing.Point(12, 124);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(335, 126);
this.panel1.TabIndex = 4;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(68, 1);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(189, 17);
this.label2.TabIndex = 3;
this.label2.Text = "Technical Error Message";
//
// formErrorWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.ClientSize = new System.Drawing.Size(359, 290);
this.Controls.Add(this.panel1);
this.Controls.Add(this.button1);
this.Controls.Add(this.errorTitleItem);
this.Controls.Add(this.usrMsgItem);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "formErrorWindow";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Error!";
this.VisibleChanged += new System.EventHandler(this.formErrorWindow_VisibleChanged);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label2;
public System.Windows.Forms.TextBox usrMsgItem;
public System.Windows.Forms.Label errorTitleItem;
public System.Windows.Forms.TextBox errorMsgItem;
}
}
Look for the function I've added above. How do I get that to compile and do what I want it to do WITHOUT that error I keep getting: An object reference is required for the non-static field, method, or property.
I would just pass the message as a constructor parameter.
MyMessageBox messageBox = new MyMessageBox("My error message");
messageBox.Show();
Yes! have a function made public that can receive this text:
pseudo: public void updateTextBox(string new_text)
and have the function update the textbox from there.
don't mix UI with logic.
public partial class Form1 : Form
{
private static TextBox box;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// box
box = new TextBox();
box.Location = new System.Drawing.Point(87, 230);
box.Name = "box";
box.Size = new System.Drawing.Size(100, 20);
box.TabIndex = 1;
this.Controls.Add(box);
}
}
You can make the TextBox public first of.
Second make a static form(name of your form) variable and put the form there each time its loaded...
This is not a good solution in my eyes but without knowing more about your design its the best i can come up with...
Allowing public access to an object contained in your class may be a design. How about writing a property in the error window class called ErrorText and inside that property set the ErrorMessage.Text to the passed string? Or am I missing something?
If you really want to go with accessing the controls directly:
public Form2(Form1 form1)
{
InitializeComponent();
Owner = form1;
_form1 = form1;
}
now you can access the controls on form1 this way:
_form1.theForm1ControlName
You could create a method in the Error window's class which could be something like:
public void SetErrorText(string errorText)
{
this.ErrorMessage.Text = errorText; // assuming the TextBox' ID is ErrorMessage.
}
Sounds like you're on the right track by adding the public function you did, but you shouldn't have to make it static. As a general rule, if you have to go into the Designer Generated Code, something isn't right, so let's get out of there - it doesn't mean you can't add code to the form, obviously, but don't do it in that section :)
The error you're getting I believe originates from having a non-instantiated object (i.e. creating the error form like:
formErrorWindow myErrorWindow;
as opposed to instantiating it / creating an instance of it like so:
formErrorWindow myErrorWindow = new formErrorWindow();
You've made the function static, so you can see it from anywhere, however that function can't actually do anything because the form that it runs on doesn't exist yet until you use " = new formErrorWindow();".
So if I'm in a form called "MainForm" and I want to show an error, using the name of the function you provided it would be done like this:
formErrorWindow myErrorWindow = new formErrorWindow();
myErrorWindow.showError("Title", "User Message Here", "Error Message Here");
myErrorWindow.ShowDialog();
The key is to make sure nothing is static and then make sure you're initializing the formErrorWindow with = new formErrorWindow();
Pass the TextBox to the function/method like so
public static void myFunc(TextBox textBox1)
{
textBox1.Text = "do stuff";
{

Categories