Show MessageBox immediately in Windows Forms? - c#

Is there any way to have a messagebox immediately pop up when a form opens? I just want to display a short message about how to use the form when it opens. I tried
private void myForm_Load(object sender, EventArgs e)
{
DialogResult dialogOpen = MessageBox.Show("Use the navigation menu to get started.", "Welcome!", MessageBoxButtons.OK);
}
but it doesn't work.

Showing a MessageBox during Form_Load works just fine for me. I literally copy/pasted the code from your original post, and it worked. I'm on .NET Framework 4.5 on Windows 8.1.
Are you sure your Load event handler is getting called? Perhaps the it's not hooked up to the Load event properly.

I don't see why it wouldn't work in Form_Load. Definitely try doing as others have pointed out by putting it beneath form initialization.
Though, given that you're just showing a message box, I don't think there is any reason to store the result, so a simple MessageBox.Show(message); Should do the trick.
As #s.m. said, from a UX point of view, having a notification thrown in your face as soon as the app starts would be very obnoxious, at least if you have it EVERY time. Personally, I would create a boolean Settings variable, set it to true the first time the message is displayed, and only display it when the setting is false, i.e. the first time the message is displayed.
private boolean splashShown = Properties.Settings.Default.splashShown;
private void Form_Load(object sender, EventArgs e)
{
if (!splashShown)
{
MessageBox.Show("message");
myForm.Properties.Settings.Default.splashShown = true;
myForm.Properties.Settings.Default.Save();
}
}
And set up the splashShown Setting in your form properties.
If the problem is that your Form_Load() method isn't actually attached to your Form.Load() event, you can double click the form window in the designer and it will automatically created the Form_Load() base method for you and attach it to the Form.Load() event

Is there a reason to use the Load method of the form? If not you could to it in the constructor of form. If you want it to show up immediately after your form loads, you should do it in the constructor after the form is initialized. It should look something like this:
public partial class myForm : Form
{
public myForm()
{
InitializeComponent();
DialogResult dialogOpen = MessageBox.Show("Use the navigation menu to get started.", "Welcome!", MessageBoxButtons.OK);
}
}
The constructor (public myForm()) and the InitializeComponent(); should be automatically added to the form by Visual Studio after creating it.

Form_Load event occurs before the form is really visible.
I use:
static private bool splashShown = false;
private void Form1_Activated(object sender, System.EventArgs e)
{
if (!splashShown)
{
MessageBox.Show("message");
splashShown = true;
}
}

I have used this and it works fine. App start brings up messagebox first before all else.
InitializeComponent();
MessageBox.Show("put your message here");

Related

Access Form - instantiate it once

After closing a form, I can't access it anymore, because the object does not exist anymore.
Is there a way to avoid this kind of behaviour, without initiating the object everytime I perform an event?
This is the first Form called status, it's not the only one I need to create, that's why Iam asking.
This does not work: After closing the form and click on the menu item I get an reference error "Object does not exist", and therefor can't be accessed.
public partial class Main : Form
{
StatusForm statusForm = new StatusForm();
public Main()
{
InitializeComponent();
statusForm.MdiParent = this;
}
private void statusToolStripMenuItem_Click(object sender, EventArgs e)
{
statusForm.Show();
}
private void Main_Load(object sender, EventArgs e)
{
statusForm.Show();
}
}
If you use Close to close a form, it is unusable after that point. You have to create a new one.
However, if you want a persistent Form object, just call Form.Hide instead. This hides the form but leaves it "open".
MSDN notes this as well:
When the Close method is called on a Form displayed as a modeless
window, you cannot call the Show method to make the form visible,
because the form's resources have already been released. To hide a
form and then make it visible, use the Control.Hide method.

Run code when window closes

I believe it is possible to run code when the close button is pressed in Windows Forms application in C#. Its a child form of the main window. I want to save some user settings when the user closes the window.
private void fileTypeDialog_FormClosing(Object sender, FormClosingEventArgs e)
{
int ArraySize = fileTypesData.Items.Count;
string[] fileTypesToSaveArray = new string[ArraySize];
for (int i = 0; i < ArraySize; i++)
{
fileTypesToSaveArray[i] = fileTypesData.Items[i].ToString();
}
string fileTypesToSave = String.Join(",", fileTypesToSaveArray);
MessageBox.Show(fileTypesToSave.ToString());
Properties.Settings.Default.fileTypes = fileTypesToSave;
Properties.Settings.Default.Save();
}
I have done this before i think, but i simply cannot remember how i did it. Can you guys assist me?
Your event isn't wired up. If you don't create the event with the designer, then you need to add it manually, usually in the constructor:
public Form1() {
InitializeComponent();
this.FormClosing += fileTypeDialog_FormClosing;
}
But a form shouldn't have to listen to its own events since it has access to its protected event methods. So simply start typing "override OnForm" and select "OnFormClosing" from intellisense. Your code block would look like this:
protected override void OnFormClosing(FormClosingEventArgs e) {
// your code here
base.OnFormClosing(e);
}
When overriding a base method, always include the base call as shown unless you have a specific reason not to.
Try to use FormClosed instead of FormClosing, I tried and worked very well for me :) Hope helped you :)

Show/Refresh Button working properly

I have a checkbox in form1, when it is checked it makes a PictureBox in form2 visible but when I uncheck I want to refresh form2 so that the PictureBox is not visible. This code is in form1. It is a button that opens up the form if one if not open but if a form is open it refreshes it. The problem is that it is not refreshing. Can anyone tell me what is wrong?
private tuesday _FavoritesForm;
public void startbutton_Click(object sender, EventArgs e)
{
if (_FavoritesForm == null)
{
_FavoritesForm = new tuesday();
_FavoritesForm.Closed += new EventHandler(_FavoritesForm_Closed);
_FavoritesForm.Show();
}
else
{
_FavoritesForm.Refresh();
}
}
Calling Refresh on a form merely forces it to be repainted. There isn't any reason to assume that it will repaint differently. You would have to override the OnPaint() method in that form. Clearly you are not using OnPaint to draw an image, you are using a PictureBox. Setting that control's Visible property to false will make the image disappear, no additional help is needed.
I would add a public method on the secondary form to Show/Hide the picture because it appears the second form has no idea of the first form. Then the click / checkbox setting on the first form to instead of doing a "REFRESH" on the second, create the form if its not already done so. Once created, call whatever method you expose on the secondary form to specifically make visible or not as needed.
EDIT FOR CLARIFICATION
#a13xy, actually the reverse... The second form has no idea of the first, but yes, have a method that is public on the 2nd. Then on the FIRST form, in the click / value changed event of your checkbox, you just call the method from that... such as your sample code...
public void startbutton_Click(object sender, EventArgs e)
{
if (_FavoritesForm == null)
{ _FavoritesForm = new tuesday();
_FavoritesForm.Closed += new EventHandler(_FavoritesForm_Closed);
_FavoritesForm.Show();
}
else
{ _FavoritesForm.Refresh();
}
_FavoritesForm.ShowHide( IsCurrentForms.CheckBox.IsCheckedValue );
}
Not positive of your checkbox controls name, or its Checked value property, just call the second form's method directly with whatever your forms value is and the method in the SECOND form could be something like...
public void ShowHide( Boolean ShowTheImage )
{
// value provided as a direct parameter from the first form,
// THISform knows about its own Picture property and can directly
// set the visibility within its scoped control.
this.YourPicture.Visible = ShowTheImage
}

When to make a form flash and stop flashing?

I am writing an IM program, and I have the method to make a form flash and stop flashing... question is, how do I implement it?
When a message arrives, I can set the window flashing, but I need to make sure it doesn't have focus. Checking the focued method always seems to return false and so it flashes even when the form is open.
Also, which event to I need to handle to stop it flashing? When the user clicks the form to make it maximise, or switches focus to the form, I need a way of stopping it.
What's the best way?
You can handle the Activated and Deactivate events of your Form, and use them to change a Form-level boolean that will tell your code whether your form has the focus or not, like this:
private bool _IsActivated = false;
private void Form1_Activated(object sender, EventArgs e)
{
_IsActivated = true;
// turn off flashing, if necessary
}
private void Form1_Deactivate(object sender, EventArgs e)
{
_IsActivated = false;
}
When a message arrives, you check _IsActivated to determine if your Form is already the active window, and turn on flashing if it isn't. In the Activated event, you would turn off the flashing if it's on.
The Focused property of your form will always return false if it has any controls on it. This property refers to whether the control in question (the form, in this case) has the focus within your application's form, not whether the application itself has the focus within Windows.
Checking if the form is minimized or not:
if (this.WindowState == FormWindowState.Minimized)
{
MakeFormFlash();
}
else
{
MakeFormStopFlash();
}
Event to trigger when the form is activated by user or code:
this.Activated += new EventHandler(Form_Activated);
Well Focused should be the property to check, so you need to try and work out why that is always returning false.
As for what event to listen to, probably the GotFocus event, though that may not work until you can work out what is wrong with the Focused property.
There are a number of ways you can handle this. Probably the easiest would be to have a flag that you set whenever the form is flashing so this can be reset on re-activation of the form e.g.
Code for base IM window form
private bool IsFlashing;
....
// Code for IM windows
public void OnActivate(EventArgs e)
{
if (IsFlashing)
{
// stop flash
IsFlashing = false;
}
}
public void Flash()
{
// make flash
IsFlashing = true;
}
Then wherever you do your code to handle the new message you would just need to check that the particular conversation window (if you handle multiple ones) that the message is directed at is the current active one:
public void OnNewMessage(AMessage msg)
{
Form convoWindow = FindConvoWindow(msg.Sender);
if (Form.ActiveForm == convoWindow)
{
// update the conversation text
}
else
{
convoWindow.Flash();
}
}

Databinding Textbox to Form.Text (title)

I'm trying to bind a Textbox.Text to Form.Text (which sets the title of the form).
The binding itself works. But, the title isn't updated until I move the entire form.
How can I achieve Form.Text being updated without moving the form? I'd like Form.Text being updated directly when I type something in the Textbox.
Edit; I set the title of the Form in a TextChanged event which is fired by a ToolStripTextbox:
public partial class ProjectForm : Form
{
public ProjectForm()
{
// my code contains all sorts of code here,
// but nothing that has something to do with the text.
}
}
private void projectName_TextChanged_1(object sender, EventArgs e)
{
this.Text = projectName.TextBox.Text;
}
And the Databinding version:
public partial class ProjectForm : Form
{
public ProjectForm()
{
this.projectName.TextBox.DataBindings.Add("Text", this, "Text", true, DataSourceUpdateMode.OnValidation);
}
}
Edit 2: I see I forgot to mention something. Don't know if it adds anything, but my apllication is a MDI application. The part of the title that changes is:
ApplicationName [THIS CHANGES, BUT ONLY AFTER MOVING/RESIZING]
Classic problem, you're not updating the existing form's Text property but a new one that is not visible. Call the Show() method after you change the Text.
Source
You can also try invalidating your form in the TextChanged event so it will force a re-paint.
Edit 1: This StackOverflow question may provide an answer for you since you are a MDI application
Edit 2: It could be that this operation is not thread-safe and therefore the UI thread is blocking. Therefore, you need to invoke another function in order to cause it to update. I had a similar problem with StatusBar Labels a while back. Here is some example code if you do not know how to use delegates:
public delegate void updateFormTextD(string text);
private void formText(string text)
{
this.Text = text;
}
private void updateFormText(string text)
{
Invoke(new updateFormTextD(formText), text);
}
What about using the TextChanged event of the TextBox, like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.Text = this.textBox1.Text;
}
}
I had the same problem that almost freaks me out. Eventually I found that my form title update request by "this.text = " was blocked by the method "WndProc(ref Message message)". At the end of WndProc method I added "base.WndProc(ref message)", which passes along all messages to the base also. After that I could update successfully my form title by "this.text = ".
Therefore, I suggest you to look for a method that blocking your form title for being updated.
None of the traditional items worked (invalidate & refresh); nor was I able to readily determine where the message might have been blocked. However, sleeping the thread took care of this.
fForm1->Text = Title;
Thread::Sleep(0); //Allow release for title to update

Categories

Resources