How to disable multi clicks in the c# application programming? - c#

In the c sharp application program, if a button is clicked then a dialog box will be opened but if the user clicked more than one time then more dialog boxes are opened. How to overcome it?
Please give me the solution regarding this issue.

If its a desktop application use Modal Dialogs.

use ShowDialog function:
using (Form2 frm = new Form2())
{
frm.ShowDialog();
}
This will disable the current form and only make the new form usable.
Alternatively, you can disable the button to prevent it from being clicked again.
button1.Enabled = false;
But make sure you enable the button when it should be accessible again.

Furquan has a good answer. Edit: as does Fun.
If you can't or don't want your dialog to be modal, you can add extra state to see if the subdialog is already open. Here's some example pseudo-code (it probably won't compile):
class MyForm : Form
{
public void OnButtonClick()
{
if(!isSubDialogOpen)
{
isSubDialogOpen = true;
ShowSubDialog();
}
}
private void OnSubDialogClose()
{
isSubDialogOpen = false;
}
private void ShowSubDialog()
{
SubDialog subDialog = new SubDialog(this);
subDialog.OnClose += OnSubDialogClose;
subDialog.Show();
}
private bool isSubDialogOpen;
}
class SubDialog : Form
{
// ...
}

Related

How to go back to the previous form with no loss of data

I have a first form where the user designs a hotel for himself/herself. After clicking on a created room from the created floor, the user introduces information to a second form which opens from the first form in order to reserve that room. When a button is clicked on the second form the form should disappear sending the data to the first form then save it to a file in the first form.
My issue is that when I am trying to hide or to close the second form, it either exits the application or it just hides the tab.
Could anyone tell me how to close the second form an get back to the first form without losing any data, any buttons, any text or any information example in a combo box.
Code wise that is what I have in the Program.cs:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 myStart = new Form1();
if (myStart.ShowDialog() == DialogResult.OK)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
Application.Exit();
}
}
And that is what I tried to put in the button that closes the second form, but it does not work :
Form2Reservations f2 = new Form2Reservations();
f2.Close();
and I also tried :
var main = new Form1();
main.Show();
main.BringToFront(); , but it gives me a new Form1 and I do not want to lose everything that I already had in Form1.
and I also tried this.Close(); and this.Hide(); , but the first one closes the whole application and the second one just puts both tabs on the toolbar.
Also, I am a beginner in C#, I have not taken any University level courses, I am just self-teaching myself with the help of the internet and tutorials.
Thank you.
SECOND EDIT:
When I open up my second form I use this code in form 1:
Form2Reservations f2 = new Form2Reservations();
f2.receiveDataFromForm1(typeOfRoom, numberOfTheRoom, floor);
f2.ShowDialog();
this.Hide();
The edited changeRoom_Click looks like this :
private void changeRoomButton_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
And the Program.cs code with static void Main() still looks the same.
My idea is the following : Is there any chance that I am not opening the second form correctly, so when I want to close the second form, it closes both of them, because somehow they are closely connected and this.Close() is referring to both forms ? Is that possible ? Would my mistake be in the first form when I call the opening of the second form ?
You are checking if the DialogResult is set on 'OK'. But you aren't setting the DialogResult before Closing the form, which is why it will return False on the If statement and exits the application.
You need to add
this.DialogResult = System.Windows.Forms.DialogResult.OK;
before closing the Form in changeRoomButton_Click.
--EDIT:
Lets give it another try.
You are calling receiveDataFromForm1 before you actually have showed the form, therefor it probably isn't going to return anything. Also, you don't need the hide the existing form when calling ShowDialog as it will stay on top until you close it.
Your code is a real mess so I'll just throw something together as an example to help you progress;
In Program.cs:
frmReservations reservations = new frmReservations();
if (reservations.ShowDialog() == DialogResult.OK)
{
string result = reservations.yourDesiredResult;
Application.Run(new frmMain(result));
}
else
{
Application.Exit();
}
Now, inside frmReservations:
public partial class frmReservations : Form
{
public string yourDesiredResult = string.Empty;
private void btnClose_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.yourDesiredResult = "I've been set!";
this.Close();
}
}
Now inside frmMain you will have to receive that value again we've received from frmReservations and set in Program.cs:
public partial class frmMain : Form
{
public frmMain(string resultFromReservations)
{
InitializeComponent();
//resultFromReservations holds the string: I've been set
}
}
This is just an example to show you one of the many ways to do this, you will now have to implement it inside your program.
I found my bug. It was in Program.cs :
I had :
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 myStart = new Form1();
Form2Reservations myLogin = new Form2Reservations();
if (myStart.ShowDialog() == DialogResult.OK)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(myLogin);
}
else
{
Application.Exit(); // here was the mistake
}
}
All I had to do is to change Application.Exit(); to Application.Run(myStart);
, but I also needed to include this line in my second form button that closes the second form :
this.DialogResult = System.Windows.Forms.DialogResult.OK;
Thank you guys for help. I could not have fixed it without your help.

Interaction between components of 2 forms

At first i disable a Toolstrip menu item so that when a user click the "Enable" button, the Toolstrip menu item can be enablem like:
private System.Windows.Forms.ToolStripMenuItem QLKHTSM;
The QLKHTSM is disable on the forms.
The problem is the Enable button is on the other form, so i tried to interact between 2 forms by this code(under the same form of that ToolStripMenuItem)
public static void enabletoolstrip()
{
QLKHTSM.enable = true;
}
but the problem is with static, the QLKHTSM is unavailable, and without static, i can't call it in the other form.
Please help. Thanks.
In the form where QLKTHSM is, Go to be Properties of QLKTHSM and change the Modifier property to Public. Then go to the second form and use.
public void enabletoolstrip()
{
FirstForm f1 = (FirstForm)Application.OpenForms["FirstForm"];
f1.QLKHTSM.Enabled = true;
}
If the form with QLKHTSM is not yet shown then you can create a global object.
FirstForm f1 = new FirstForm();
Then in your enable tool strip
public void enabletoolstrip()
{
f1.QLKHTSM.Enabled = true;
}
Then wherever you want to show the form you use
f1.Show();

C# Handle a dialog's button click in another form

I have a form. In that I got to show a dialog (on some circumstances) with Text and a Cancel button. I want to catch the event of that button in my form Or know if that cancel button was clicked.
How can this be done ? I believe this should be possible but can't make out how ?
From my mainForm I have BackgroundWorker. When the backgroundWorker is started I open a childForm (with a Label and a button) and when the background task is over, I close the childForm. What I want more is : when the button of childForm is clicked the ongoing task of backgroundWorker should be cancelled.
SOLUTION
In my childForm I have set CancelButton property as cancelBtn for the form. The othe code is :
private bool cancel;
public bool Cancel
{
get { return cancel; }
set { cancel = value; }
}
// Set the flag as true to indicate that Cancel button was actually pressed
private void cancelBtn_Click(object sender, EventArgs e)
{
Cancel = true;
}
In mainForm :
childDlg = new ChildDialog();
// wHILE cALLING
backgroundWorker1.RunWorkerAsync();
msg = "Connecting...";
childDlg .set(msg, "");
if (!childDlg .IsAccessible)
{
// This is caught even when the dialog is closed
if (childDlg .ShowDialog() == DialogResult.Cancel) {
if (childDlg.Cancel == true) { // Was really cancelBtn pressed
// NOW ONLY do my stuff
}
}
}
I had tried using #DeveloperX technique i.e. EventHandler in parent class, but the parent class method was nver being called. Tried a lot but couldn't success. Then tried of #RobinJ's technique and it worked. I just had to add flag to identify was really cancel button pressed or jjst windw was closed normally.
Thanks to all of you for tryig to help me out. I really appreciate your help.
Thanks
Set DialogResult property to either DialogResult.Ok or DialogResult.Cancel
Then in the parent form:
Form form = new Form();
DialogResult results = form.DialogResult;
if(results == DialogResult.Ok)
{
... make magic
}
else
{
...
}
Put this in the form that should catch the event:
frmDialog.ShowDialog();
And this in the btnCancel_Click event of the dialog:
return DialogResult.Cancel();
Sorry if I'm confusing VB and C# here, but it's pretty much the same.
Simply you can create an event for the form that shows the dialog
and handle this event in parent form
in case the user clicks on ok fire event with specefic parameter and for cancel another parameter (such dialogresult.cancel)
an pseudo implementation can be like this
public class FormChild : System.Windows.Forms.Form
{
public event EventHandler DialogCanceled;
public event EventHandler DialogConfirmed;
public void ShowDialog()
{
using (var dialogForm = new FormDialog())
{
if (dialogForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (DialogConfirmed != null)
DialogConfirmed(this,new EventArgs());
}
else
{
if (DialogCanceled != null)
DialogCanceled(this,new EventArgs());
}
}
}
}
public class ParentForm : System.Windows.Forms.Form
{
public void callChild()
{
using (var f = new FormChild())
{
f.DialogCanceled += new EventHandler(f_DialogCanceled);
f.DialogConfirmed += new EventHandler(f_DialogConfirmed);
f.ShowDialog();
}
}
void f_DialogConfirmed(object sender, EventArgs e)
{
throw new NotImplementedException();
}
void f_DialogCanceled(object sender, EventArgs e)
{
throw new NotImplementedException();
}
}
You should be using the ShowDialog method on the form you need to show as a dialog and then use the DialogResult property to communicate to the parent form the result of the dialog operation.
This way you handle the button click on the form that owns the button but set the DialogResult to DialogResult.Cancel to specify that the user pressed the cancel button.
A dialog is usually a blocking event, where eventhandling by the parent form would make no sense at all.
If it isn't a modal dialog, you can always create one or several public events in the popup form, that are triggered when the buttons are clicked. These events can then be caught by the parent form.
Don't expose your buttons to the parent form, it would be terrible oo-programming.
Use the following:
Form form = new Form();
switch (form.ShowDialog())
{
case DialogResult.Ok:
{
....
Break;
}
case DialogResult.Cancel:
{
....
Break;
}
}
Set the Form.AcceptButton and Form.CancelButton properties to the appropriate buttons.
Refer to the following:
Form.ShowDialog Method
DialogResult Enumeration
Form.AcceptButton Property
Form.CancelButton Property

How to Link Different Form?

I got great help in my first question n hopefully someone will tell me or refer me to an earlier question about this topic.
I want to link different forms like I click on a button on first one and it opens the second one.Basically I'm going to make a Menu for cellphone functions like SMS,CALL etc. so I want that If I click on call a new form opens asking for Number to call etc.
void SomeInitializationFunction() {
button.Click += new System.EventHandler(buttonClick);
}
private void buttonClick(object sender, System.EventArgs e)
{
using(GetNumberForm getNumberForm = new GetNumberForm())
{
if(DialogResult.OK == getNumberForm.ShowDialog())
{
string phoneNumber = getNumberForm.PhoneNumber;
// do something with the user input.
}
}
}
var otherForm = new Form2();
otherForm.ShowDialog(); // To show a modal dialog, or...
otherForm.Show(); // To show it as a non-modal window

Single Form Hide on Startup

I have an application with one form in it, and on the Load method I need to hide the form.
The form will display itself when it has a need to (think along the lines of a outlook 2003 style popup), but I can' figure out how to hide the form on load without something messy.
Any suggestions?
I'm coming at this from C#, but should be very similar in vb.net.
In your main program file, in the Main method, you will have something like:
Application.Run(new MainForm());
This creates a new main form and limits the lifetime of the application to the lifetime of the main form.
However, if you remove the parameter to Application.Run(), then the application will be started with no form shown and you will be free to show and hide forms as much as you like.
Rather than hiding the form in the Load method, initialize the form before calling Application.Run(). I'm assuming the form will have a NotifyIcon on it to display an icon in the task bar - this can be displayed even if the form itself is not yet visible. Calling Form.Show() or Form.Hide() from handlers of NotifyIcon events will show and hide the form respectively.
Usually you would only be doing this when you are using a tray icon or some other method to display the form later, but it will work nicely even if you never display your main form.
Create a bool in your Form class that is defaulted to false:
private bool allowshowdisplay = false;
Then override the SetVisibleCore method
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(allowshowdisplay ? value : allowshowdisplay);
}
Because Application.Run() sets the forms .Visible = true after it loads the form this will intercept that and set it to false. In the above case, it will always set it to false until you enable it by setting allowshowdisplay to true.
Now that will keep the form from displaying on startup, now you need to re-enable the SetVisibleCore to function properly by setting the allowshowdisplay = true. You will want to do this on whatever user interface function that displays the form. In my example it is the left click event in my notiyicon object:
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
this.allowshowdisplay = true;
this.Visible = !this.Visible;
}
}
I use this:
private void MainForm_Load(object sender, EventArgs e)
{
if (Settings.Instance.HideAtStartup)
{
BeginInvoke(new MethodInvoker(delegate
{
Hide();
}));
}
}
Obviously you have to change the if condition with yours.
protected override void OnLoad(EventArgs e)
{
Visible = false; // Hide form window.
ShowInTaskbar = false; // Remove from taskbar.
Opacity = 0;
base.OnLoad(e);
}
At form construction time (Designer, program Main, or Form constructor, depending on your goals),
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
When you need to show the form, presumably on event from your NotifyIcon, reverse as necessary,
if (!this.ShowInTaskbar)
this.ShowInTaskbar = true;
if (this.WindowState == FormWindowState.Minimized)
this.WindowState = FormWindowState.Normal;
Successive show/hide events can more simply use the Form's Visible property or Show/Hide methods.
Try to hide the app from the task bar as well.
To do that please use this code.
protected override void OnLoad(EventArgs e)
{
Visible = false; // Hide form window.
ShowInTaskbar = false; // Remove from taskbar.
Opacity = 0;
base.OnLoad(e);
}
Thanks.
Ruhul
Extend your main form with this one:
using System.Windows.Forms;
namespace HideWindows
{
public class HideForm : Form
{
public HideForm()
{
Opacity = 0;
ShowInTaskbar = false;
}
public new void Show()
{
Opacity = 100;
ShowInTaskbar = true;
Show(this);
}
}
}
For example:
namespace HideWindows
{
public partial class Form1 : HideForm
{
public Form1()
{
InitializeComponent();
}
}
}
More info in this article (spanish):
http://codelogik.net/2008/12/30/primer-form-oculto/
I have struggled with this issue a lot and the solution is much simpler than i though.
I first tried all the suggestions here but then i was not satisfied with the result and investigated it a little more.
I found that if I add the:
this.visible=false;
/* to the InitializeComponent() code just before the */
this.Load += new System.EventHandler(this.DebugOnOff_Load);
It is working just fine.
but I wanted a more simple solution and it turn out that if you add the:
this.visible=false;
/* to the start of the load event, you get a
simple perfect working solution :) */
private void
DebugOnOff_Load(object sender, EventArgs e)
{
this.Visible = false;
}
You're going to want to set the window state to minimized, and show in taskbar to false. Then at the end of your forms Load set window state to maximized and show in taskbar to true
public frmMain()
{
Program.MainForm = this;
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
private void frmMain_Load(object sender, EventArgs e)
{
//Do heavy things here
//At the end do this
this.WindowState = FormWindowState.Maximized;
this.ShowInTaskbar = true;
}
Put this in your Program.cs:
FormName FormName = new FormName ();
FormName.ShowInTaskbar = false;
FormName.Opacity = 0;
FormName.Show();
FormName.Hide();
Use this when you want to display the form:
var principalForm = Application.OpenForms.OfType<FormName>().Single();
principalForm.ShowInTaskbar = true;
principalForm.Opacity = 100;
principalForm.Show();
This works perfectly for me:
[STAThread]
static void Main()
{
try
{
frmBase frm = new frmBase();
Application.Run();
}
When I launch the project, everything was hidden including in the taskbar unless I need to show it..
Override OnVisibleChanged in Form
protected override void OnVisibleChanged(EventArgs e)
{
this.Visible = false;
base.OnVisibleChanged(e);
}
You can add trigger if you may need to show it at some point
public partial class MainForm : Form
{
public bool hideForm = true;
...
public MainForm (bool hideForm)
{
this.hideForm = hideForm;
InitializeComponent();
}
...
protected override void OnVisibleChanged(EventArgs e)
{
if (this.hideForm)
this.Visible = false;
base.OnVisibleChanged(e);
}
...
}
Launching an app without a form means you're going to have to manage the application startup/shutdown yourself.
Starting the form off invisible is a better option.
This example supports total invisibility as well as only NotifyIcon in the System tray and no clicks and much more.
More here: http://code.msdn.microsoft.com/TheNotifyIconExample
As a complement to Groky's response (which is actually the best response by far in my perspective) we could also mention the ApplicationContext class, which allows also (as it's shown in the article's sample) the ability to open two (or even more) Forms on application startup, and control the application lifetime with all of them.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainUIForm mainUiForm = new MainUIForm();
mainUiForm.Visible = false;
Application.Run();
}
I had an issue similar to the poster's where the code to hide the form in the form_Load event was firing before the form was completely done loading, making the Hide() method fail (not crashing, just wasn't working as expected).
The other answers are great and work but I've found that in general, the form_Load event often has such issues and what you want to put in there can easily go in the constructor or the form_Shown event.
Anyways, when I moved that same code that checks some things then hides the form when its not needed (a login form when single sign on fails), its worked as expected.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form1 = new Form1();
form1.Visible = false;
Application.Run();
}
private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
Application.Exit();
}
Here is a simple approach:
It's in C# (I don't have VB compiler at the moment)
public Form1()
{
InitializeComponent();
Hide(); // Also Visible = false can be used
}
private void Form1_Load(object sender, EventArgs e)
{
Thread.Sleep(10000);
Show(); // Or visible = true;
}
In the designer, set the form's Visible property to false. Then avoid calling Show() until you need it.
A better paradigm is to not create an instance of the form until you need it.
Based on various suggestions, all I had to do was this:
To hide the form:
Me.Opacity = 0
Me.ShowInTaskbar = false
To show the form:
Me.Opacity = 100
Me.ShowInTaskbar = true
Why do it like that at all?
Why not just start like a console app and show the form when necessary? There's nothing but a few references separating a console app from a forms app.
No need in being greedy and taking the memory needed for the form when you may not even need it.
I do it like this - from my point of view the easiest way:
set the form's 'StartPosition' to 'Manual', and add this to the form's designer:
Private Sub InitializeComponent()
.
.
.
Me.Location=New Point(-2000,-2000)
.
.
.
End Sub
Make sure that the location is set to something beyond or below the screen's dimensions. Later, when you want to show the form, set the Location to something within the screen's dimensions.

Categories

Resources