Cancel form load - c#

I have the following code :
This call the second form
private void updateToolStripMenuItem_Click(object sender, EventArgs e)
{
Update fm = new Update();
fm.ShowDialog();
}
This is the constructor
public Update()
{
InitializeComponent();
}
This is the load
private void Update_Load(object sender, EventArgs e)
{
String ver = checkver();
if (ver == "update")
{
if (RemoteFileExists(dlUrl) == true)
{
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(dlUrl), "");
}
else
MessageBox.Show("An error occurred. Please try later.");
}
else if (ver == "newest")
{
MessageBox.Show("You are currently using the newest version.");
this.Close();
}
else
{
this.Close();
}
}
My problem is, that when the function result is 2 or 3 the form show up for millisecond and then close (flashing). I want the form to not flash. Is it possible?
I tried to use this.Hide(), this.Visible = False but nothing helped.
EDIT: I put the original code
EDIT2: Put more code

You can hide the form before loading and then set it back to visible in your if else conditions. e.g:
MyForm myForm = new MyForm();
myForm.Opacity = 0;
myForm.Show();
And then:
if (ver == "update")
{
if (RemoteFileExists(dlUrl) == true)
{
myForm.Opacity = 100;
...
}
else
MessageBox.Show("An error occurred. Please try later.");
}
else if (ver == "newest")
{
MessageBox.Show("You are currently using the newest version.");
this.Close();
}
else
{
this.Close();
}

The best way to do so :
private void Form_Load(object sender, EventArgs e)
{
switch(funct())
{
case 2:
this.BeginInvoke(new MethodInvoker(this.Close));
break;
case 3:
this.BeginInvoke(new MethodInvoker(this.Close));
break;
default:
MessageBox.Show("Something");
}
}

You should probably do whatever check you're performing before you choose to open the form in the first place.
So something like:
if(funct() == "1")
{
var form = new Form();
form.ShowDialog();
}

I assume Update_Load is your FormLoad Handler? That is called after your form has been displayed. If you don't want to display it, that's too late. Change your updateToolStripMenuItem_Click to this:
String ver = checkver();
if (ver == "update")
{
if (RemoteFileExists(dlUrl))
{
Update fm = new Update();
fm.ShowDialog();
}
else
MessageBox.Show("An error occurred. Please try later.");
}
else if (ver == "newest")
{
MessageBox.Show("You are currently using the newest version.");
}
And change your Update_Load to:
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(dlUrl), "");

Maybe hide it first, then only show it if funct() == "1":
private void Form_Load(object sender, EventArgs e)
{
this.Close();
if (funct() == "1")
MessageBox.Show("Something");
}

try this
private void Form_Load(object sender, EventArgs e)
{
switch(funct())
{
case 2:
this.Close();
break;
case 3:
this.Close();
break;
default:
MessageBox.Show("Something");
}
}

Related

{again} C# MessageBox created more than once

I have a similar question as last time, but no matter how much I hit my head against the wall, solution is not coming. The problem is that the message box gets created too many times, when it should only open once, unsubscribe from documentCompleted and then exit. Thanks again!
private void textBox4_TextChanged(object sender, EventArgs e)
{
if (textBox4.Text.Length >= 3)
{
timer1.Enabled = true;
}
}
private void timer1_Tick_1(object sender, EventArgs e)
{
if (textBox4.Text != "")
{
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.Navigate("https://worldofwarcraft.com/en-gb/search?q=" + textBox4.Text);
webBrowser1.DocumentCompleted += GetImg; //sub here
}
}
private void GetImg(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string img_url = "";
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
{
if (el.GetAttribute("className") == "Avatar-image")
{
img_url = (el.OuterHtml).Substring(el.OuterHtml.IndexOf("https"));
img_url = img_url.Substring(0, img_url.IndexOf(")"));
pictureBox1.ImageLocation = img_url;
}
else if (el.GetAttribute("className") == "Character-level")
{
textBox5.Visible = true;
label7.Visible = true;
string lvl_url = "";
lvl_url = (el.InnerHtml).Substring(3);
lvl_url = lvl_url.Substring(0, lvl_url.IndexOf("<"));
textBox5.Text = lvl_url;
DialogResult YESNO = MessageBox.Show("Is this your character?", "Select your char", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (YESNO == DialogResult.Yes)
{
// clean up
webBrowser1.DocumentCompleted -= GetImg; //unsub here
pictureBox1.Enabled = false;
timer1.Dispose();
break;
}
}
}
}
You need to either set timer1.Enabled to false or call timer1.Stop() as soon as you enter the timer1_Tick_1 method, or the timer will keep firing and calling your method every time.

how to exit from application on click of (red X ) button right top on winform

i have two forms in my application. frmLogin and frmDash. after login. i am hiding frmLogin on click of login button. ad showing frmDash.
in frmDash, there is LogOut button. on click of LogOut, i am using this.Close() and showing login form. but now if i click (red X) button of frmLogin whole application is not terminating. plz give some suggestions.
i have tried this.:
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
this.Hide();
string Log_API = "http://api.retailbutton.co/WS/Service.php?Service=employeeLogin";
if (LoginUser(Log_API))
{
logIn_Status = "true";
GlolbalUtil.LogIn_Status = logIn_Status;
frmDash frmDash = new frmDash();
frmDash.Owner = this;
frmDash.Show();
txtUsername.Text = "";
txtPassword.Text = "";
//GlolbalUtil.accept_status = "1";
}
else
{
MessageBox.Show("Please Check Username and password");
FrmLogin frmLogin = new FrmLogin();
frmLogin.Owner = this;
frmLogin.Show();
}
}
code for Logout button of frmDash:
private void button1_Click(object sender, EventArgs e)
{
GlolbalUtil.LogIn_Status = "false";
this.Close();
FrmLogin fl = new FrmLogin();
fl.Show();
}
You create a new instance of frmDash when you log in and hide the form.
Then when you are logging out, you say this.close() and create another new instance of FrmLogin. Not going back to the original instance of FrmLogin.
This means that you will always will have the hidden instance which you started with.
(If you close the new instance of FrmLogin, the hidden FrmLogin still exists.)
You can add the following in btnLogin_Click:
frmDash.ParentForm = this;
and button1_Click should look like this:
private void button1_Click(object sender, EventArgs e){
GlolbalUtil.LogIn_Status = "false";
FrmLogin fl = (FrmLogin)this.Parent; //Prior it said ParentForm
this.Close();
fl.Show();
}
If you implement this, you will show the initial login form and when you close it, you close the initial instance of the login form.
#Edit 10:52 25-06-2015
ParentForm cannot be assigned and is read only. A solution is to assign it to Parent or the following can also be applied in btnLogin_Click:
frmDash.Owner = this;
and button1_Click:
private void button1_Click(object sender, EventArgs e){
GlolbalUtil.LogIn_Status = "false";
FrmLogin fl = (FrmLogin)this.Owner
this.Close();
fl.Show();
}
#Edit 08:16 29-06-2015 (Next question)
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string Log_API = "http://api.retailbutton.co/WS/Service.php?Service=employeeLogin";
if (LoginUser(Log_API))
{
logIn_Status = "true";
GlolbalUtil.LogIn_Status = logIn_Status;
frmDash frmDash = new frmDash();
frmDash.Owner = this;
////If you hide here, you do not have to make
//a new instance when the if statement is not true.////
this.Hide();
frmDash.Show();
txtUsername.Text = "";
txtPassword.Text = "";
//GlolbalUtil.accept_status = "1";
}
else
{
MessageBox.Show("Please Check Username and password");
////Delete following////
//FrmLogin frmLogin = new FrmLogin();
//frmLogin.Owner = this;
//frmLogin.Show();
}
}
If you are using a custom button, do this
private void QuitButton_Click(object sender, EventArgs e)
{
DialogResult DialogResult = MessageBox.Show("Do you really want to exit?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
if (DialogResult == DialogResult.Yes)
Application.Exit();//Here is the code to close everything
else
//Do stuff
}
If you are using the X button, add a FormClosing Event and the code look like this:
private void Form1_FormClosing(object sender, FormClosingEventArgs e){
DialogResult DialogResult = MessageBox.Show("Do you really want to exit?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
if (DialogResult == DialogResult.Yes)
Application.Exit();//Here is the code to close everything
else
//Do stuff
}
use Application.Exit(); method when your button clicked
Add this to your Designer.cs
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.SampleClassName_FormClosed);
then right click the SampleClassName_FormClosed and click "Go to Definition".
then inside the created class call the form that you want to close.
Try the following on your 2. Form:
public partial class Form2 : Form
{
private bool ForceClose = true;
public Form2()
{
InitializeComponent();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (ForceClose)
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
GlolbalUtil.LogIn_Status = "false";
ForceClose = false;
this.Close();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();//close the whole program using x (red)button
}

ShowDialogue not generating DialogueResult.OK

I'm writing a program that's supposed to download something off GitHub. It has a link to a raw file on GitHub. I'm using DownloadDataAsync to download it, and I have a progress bar to track how far it is in the download. It always gets to 100%, but then it does nothing.
I've been following a tutorial for a C# updater by BetterCoder (The beginning starts here and the most relevant part would be Part 9 of the series).
This is the part where it stops working properly:
private void DownloadUpdate(SaveyourUpdateXML update)
{
SharpUpdateDownloadForm form = new SharpUpdateDownloadForm(update.Uri, update.MD5, this.applicationInfo.ApplicationIcon);
Debug.WriteLine("form created");
DialogResult result = form.ShowDialog(this.applicationInfo.Context);
Debug.WriteLine("got result");
if (result == DialogResult.OK)
{
String currentPath = this.applicationInfo.ApplicationAssembly.Location;
String newPath = Path.GetDirectoryName(currentPath) + "\\" + update.FileName;
UpdateApplication(form.TempFilePath, currentPath, newPath, update.LaunchArgs);
Application.Exit();
}
}
It never gets to the "got result" part unless I cancel it. Also, this.applicationInfo.Context returns a form. However, it does say "form created".
I think there's something wrong with the way ShowDialog is used or something, but I'm not really sure what.
Edit: This is what happens when a SharpUpdateDownloadForm is created.
internal SharpUpdateDownloadForm(Uri location, String md5, Icon programIcon)
{
InitializeComponent();
if (programIcon != null)
{
this.Icon = programIcon;
}
tempFile = Path.GetTempFileName();
this.md5 = md5;
webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
try
{
webClient.DownloadDataAsync(location, this.tempFile);
}
catch
{
this.DialogResult = DialogResult.No;
this.Close();
}
}
This is what should happen when a download is completed:
private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
this.DialogResult = DialogResult.No;
this.Close();
}
else if (e.Cancelled)
{
this.DialogResult = DialogResult.Abort;
this.Close();
}
else
{
lblProgress.Text = "Verifying Download...";
progressBar.Style = ProgressBarStyle.Marquee;
bgWorker.RunWorkerAsync(new string[] {this.tempFile, this.md5});
}
}
This is bgWorker_RunWorkerCompleted
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.DialogResult = (DialogResult)e.Result;
this.Close();
}
And bgWorker_DoWork
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
String file = ((string[])e.Argument)[0];
String updateMD5 = ((string[])e.Argument)[1];
if (Hasher.HashFile(file, HashType.MD5) != updateMD5)
e.Result = DialogResult.No;
else
e.Result = DialogResult.OK;
}
When webClient.DownloadDataAsync completes, it fires DownloadDataCompleted event, not DownloadFileCompleted - the one you registered.
The fix is, if you use webClient.DownloadDataAsync, register the DownloadDataCompleted event; Note that the 2nd argument to webClient_DownloadDataCompleted is different.
webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(webClient_DownloadDataCompleted);
...
private void webClient_DownloadDataCompleted(Object sender, DownloadDataCompletedEventArgs e)
{
...
}

Visual Studio won't open my new form

I'm having a tiny issue here.. It's a little annoying.. I can't debug my application because of this..
My problem is.. When I try to open a new form automatically by code. It will not open other form. But when you click the button yourself on the form. It will open.. And I think this is a little weird.. Because it uses the same code...
Here is my button code that opens the new form(And it works great.):
private void button1_Click(object sender, EventArgs e)
{
label4.Text = "Login in... Please wait.";
Properties.Settings.Default.username = usernameText.Text;
if (checkBox1.Checked == true)
{
Properties.Settings.Default.check1 = true;
Properties.Settings.Default.password = passwordText.Text;
if (checkBox2.Checked == true)
{
Properties.Settings.Default.check2 = true;
}
}
Properties.Settings.Default.Save();
button1.Enabled = false;
checkBox1.Enabled = false;
checkBox2.Enabled = false;
startLoginWorker();
}
Here is the other code that opens it automatically:
private void loginForm_Load(object sender, EventArgs e)
{
String appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString();
String gpsPath = appDataFolder + "/GameProfileSaver";
label4.Text = "Checking files...";
if (!File.Exists(gpsPath + #"\ICSharpCode.SharpZipLib.dll") || !File.Exists(gpsPath + #"\ICSharpCode.SharpZipLib.dll"))
{
//startDownload("dll");
button1.Enabled = true;
}
else
{
button1.Enabled = true;
label4.Text = "File check complete. Ready for login.";
progressBar1.Value = 100;
}
if (checkBox2.Checked == true)
{
button1.PerformClick();
}
The "button1.PerformClick()" Just clicks the button by code right? Shouldn't be any difference....
And I have even tried to just put that code into that if statement.. Still nothing.
This is the code that gets run out of it all:
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(oppenMainForm));
t.SetApartmentState(ApartmentState.STA);
t.Start();
Openmainform:
private void oppenMainForm()
{
Application.Run(new Form1(usernameText.Text));
}
If anyone have any suggestions... Please help me... It's frustrating.

Creating a new form, switching focus between the new and the old form with a button

I have a form and I want to get an instance of the same form as stated in the code below. And I have a button: every time I press this button, if a new form is created, I want it to focus to that window, if not, I want to create a new form.
I managed to create a new form but if I want to focus on it, the code did not work, any ideas?
private void btn_Click(object sender, EventArgs e)
{
if (opened == false)
{
Text = "form1";
var form = new myformapp();
form.Show();
opened = true;
form.Text = "form2";
}
else
{
if (Application.OpenForms[1].Focused)
{
Application.OpenForms[0].BringToFront();
Application.OpenForms[0].Focus();
}
if (Application.OpenForms[0].Focused)
{
Application.OpenForms[1].BringToFront();
Application.OpenForms[1].Focus();
}
}
}
You can try shortening your code without the need to introduce more variables with this example:
void button1_Click(object sender, EventArgs e) {
bool found = false;
for (int i = 0; i < Application.OpenForms.Count; ++i) {
if (Application.OpenForms[i].GetType() == typeof(myformapp) &&
Application.OpenForms[i] != this) {
Application.OpenForms[i].Select();
found = true;
}
}
if (!found) {
myformapp form = new myformapp();
form.Show();
}
}
Updated code from Francesco Baruchelli's comment.
If I understand correctly what you are trying to do, you can keep a static List with the opened forms. Everytime an instance of your Form is opened you add it to the List, and everytime it is closed you remove it. The when you press the button you can check the size of the List. If it is 1 you create a new Form, open it and set the focus on it. If the size is already 2, you look in the List for the instance which is different from the one executing the click event. The code could be something like this:
private static List<Form1> openForms = new List<Form1>();
private void button1_Click(object sender, EventArgs e)
{
Form1 frm = null;
if (openForms.Count == 2)
{
foreach (Form1 aForm in openForms)
if (aForm != this)
{
frm = aForm;
break;
}
}
else
{
frm = new Form1();
frm.Show();
}
frm.Focus();
}
private void Form1_Load(object sender, EventArgs e)
{
openForms.Add(this);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
openForms.Remove(this);
}

Categories

Resources