Show or Show Dialog block other forms C# - c#

I have 2 forms. First is a simple notepad, and i make a find function. Is works very good, but i add this.Close(); to get the resultate. If i don't close the FindForm, the action of Find button not work. I see the first form is blocked and i can't write another text. if i delete this.close() and i close FindForm after i press Find is work.
How i can open the FindForm in a new thread? i use FindForm f = new FindForm(); and f.showDialog();
If i make a Thread Th; and i use this thread to open the FindForm, my function will not work anymore. Is any method to open other form without block first form?
FindForm
public FindDialog()
{
InitializeComponent();
}
private void button_Find_Click_1(object sender, EventArgs e)
{
Form1.FindText = textBox_Text.Text;
this.Close();
}
MainForm
public void findNewToolStripMenuItem_Click(object sender, EventArgs e)
{
FindDialog gtl = new FindDialog();
gtl.Show();
richTextBox1.Select();
if (FindText != null)
{
k = richTextBox1.Find(FindText);
}
}

Calling ShowDialog will block the caller until the dialog is closed (i.e. it is modal) - if you don't want this behaviour then call Show which will open the child form modelessly (i.e. the calling code can continue)
For example, you could do something like:
public void findNewToolStripMenuItem_Click(object sender, EventArgs e)
{
FindDialog gtl = new FindDialog();
gtl.Show(); // Execution will continue immediately
richTextBox1.Select();
if (FindText != null)
{
k = richTextBox1.Find(FindText);
}
}

Related

How to fix an instance when trying to access a button of another winform?

hello i have this code here (Owner as ReadBarCodeInMenu).btnContainerInquiry.Enabled = true; it keeps me throwing an instance whenever i tried to access a button of another page it tried this code in a test 2 forms and it works perfectly fine but when i put it in system i gave me an error.Please help me
edit:
form ReadBarCodeInMenu
private void btnContainerInquiry_Click(object sender, EventArgs e)
{
inquiry.Owner = this;
btnContainerInquiry.Enabled = false;
}
form ContainerInquiry
private void logoutBtn_Click(object sender, EventArgs e)
{
(Owner as ReadBarCodeInMenu).btnContainerInquiry.Enabled = true;
error// {"Object reference not set to an instance of an object."}
close.
}
this is how i access the bottom of an another form if i do this in new 2 form it works with no error.
Assuming that you open form ContainerInquiry from withing form ReadBarCodeInMenu, you can do the following. In form ContainerInquiry, add a parameter to the constructor, accepting a reference to the first form
private ReadBarCodeInMenu _readBarCodeInMenu;
public ContainerInquiry(ReadBarCodeInMenu readBarCodeInMenu)
{
InitializeComponent();
_readBarCodeInMenu = readBarCodeInMenu;
}
private void logoutBtn_Click(object sender, EventArgs e)
{
_readBarCodeInMenu.btnContainerInquiry.Enabled = true;
}
Also, change the accessibility of btnContainerInquiry from private to internal (or public).
Then in form ReadBarCodeInMenu
// Pass a reference of ReadBarCodeInMenu to ContainerInquiry.
var frm = new ContainerInquiry(this);
...
You cannot access the UI from another thread than the UI thread. If try to do so, you are getting the exception
Cross-thread operation not valid: Control 'btnContainerInquiry' accessed from a thread other than the thread it was created on.
In this case you must invoke the control or form you are accessing. This mechanism passes a delegate to the right thread and executes it there.
var btn = _readBarCodeInMenu.btnContainerInquiry;
if (btn.InvokeRequired) {
btn.Invoke(new Action(() => btn.Enabled = true));
} else {
btn.Enabled = true;
}
You could also create an extension method that automates this process as shown here: https://stackoverflow.com/a/12179408/880990

Windows form application sequential ShowDialog()s

well I have a funny problem with closing dialog forms.
here is the problem:
I run application and open second form (through menu strip) as showdialog(); and then from second form open third form. When I open third form by button 1 and then close it everything is alright, but when I open the third form by button 2 and then close it, third form will be closed and then it closes the second form also. !!! In second form when I show a messageBox and close it also the second form will be closed.
here is my codes:
open second form from first form codes:
private void settingsToolMenu_Click(object sender, EventArgs e)
{
settingsForm s1 = new settingsForm(this);
s1.ShowDialog();
}
open third form from second by button 1 form codes:
private void addReportButton_Click(object sender, EventArgs e)
{
addReport a1 = new addReport(this);
a1.ShowDialog();
}
open third form from second by button 2 form codes:
private void editReportButton_Click(object sender, EventArgs e)
{
addReport a2 = new addReport(this);
a2.ShowDialog();
}
as you see there is no differences between button 1 and button 2
here is a video from application running.
Not sure what's happening out there, but there should be .Show() method, which runs a window in a different way including closing strategy. Try it out.
Try This
Instead of
addReport a2 = new addReport(this);
a2.ShowDialog();
Use
addReport a2 = new addReport();
a2.ShowDialog(this);
Then on click of Exit / Close button of dialog window
private void BtnExit_Click(object sender, EventArgs e)
{
this.Dispose();
}
Hope this will solve your issue.
I used this code and it worked. I have 3 forms, the first form is opened when running the app, the second form is opened with a button (can be menustrip, doesn't matter), then the third is opened like that too, after closing the third form the second form remains open.
FormN fm = new FormN();
fm.ShowDialog();
Use that piece of code in every method that is called from clicking on a button and it should work fine. Just change the "FormN" for whatever your forms are named. Also, if you need to pass any form's attributes into the next form you can do this:
Code at first form:
public string mytext; //Variable I want to use later, in Form2.
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
mytext = tb1.Text;
Form2 fm = new Form2(this);
fm.ShowDialog();
}
Notice how I save "tb1"'s (TextBox1) value in a variable before calling "fm.ShowDialog();", so I can use the TextBox1 value later inside the Form2.
Code at second form, having main form's variables (such as "mytext" value).
Form1 mfm;
public Form2(Form1 mainfm)
{
InitializeComponent();
mfm = mainfm;
}
public void button2_Click(object sender, EventArgs e)
{
//In this method I use the variable "mytext" wich is a Form1 attribute.
//You can see how I declare it in the first form's code (see above).
textBox1.Text = mfm.mytext;
}
With this you have created an object of your main form ("Form1 mfm;") with all the variables it contained before calling the second form, which can be used for the third form too.
in second form formClosing() event i wrote these codes:
private void settingsForm_FormClosing(object sender, FormClosingEventArgs e)
{
if(e.CloseReason != CloseReason.UserClosing)
{
e.Cancel = true;
}
}
and nothing can close the second form except user!

ShowDialog() is not preventing the originating form from being clickable

I have a winform with the following code that opens an external program when the form is opened. If the program closes, a dialog box is suppose to pop up with an option to return that a button was clicked. This will close the dialog box and return to the initial form and then run the function to open the external program again.
Here is the problem, the original form is STILL clickable AND the function is not running. Any ideas?
public Manager()
{
InitializeComponent();
ExternalProgramOpen();
}
private void ExternalProgramOpen()
{
Process startProgram = Process.Start("program.exe", Program.ConnectionArg);
startProgram.EnableRaisingEvents = true;
startProgram.Exited += this.PrematureClose;
}
private void PrematureClose(object sender, EventArgs e)
{
ManagerWarning messagepopup = new ManagerWarning();
messagepopup.ShowDialog();
using (var ManagerWarning = new ManagerWarning())
{
if (ManagerWarning.ShowDialog() == DialogResult.Retry)
{
ExternalProgramOpen();
}
}
}
The reason for this effect is probably that the Exited event is not raised in the same UI thread that started the process.
When you call ShowDialog() from another thread, the new window will not use and block the original UI thread.
To solve this, check if InvokeRequired is true and use Invoke:
private void PrematureClose(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action(() => PrematureClose(sender, e)));
return;
}
// your code here
// ...
}

Execute function on another, already open, form

I have a form with a datagridview inside of it.
When you doubleclick on a row from the datagridview, another form will open, which is basically a form where you can edit the data you just double-clicked.
There are a 3 buttons in this "edit" form, a delete, update and a return to main form button.
When finished with what you were supposed to do on this form, it closes.
My question is;
When this form closes, I want the data that is inside of the datagridview in the main form to refresh, how can I call that function on the main form from the edit form.
Keep in mind that I already have a reload function, let's say it's called refreshData();.
if you open the edit form as a modal window, the ShowDialog() call is blocking, so if you put the refreshData call after that it will execute after the edit form is closed:
var editForm = new EditForm(...);
var result = editForm.ShowDialog();
if (result == DialogResult.OK)
{
refreshData();
}
If you used .ShowDialog(), then just put the refresh function under this line of code.
The program will continue with the
private void cell1_DoubleClick(object sender, System.EventArgs e)
function.
So your code will look similair to this;
private void cell1_DoubleClick(object sender, System.EventArgs e)
{
//Your previous code ....
//The part where you open the EditForm
MyEditForm.ShowDialog();
//After it has been closed the program will continue to execute this function(if it has not been ended yet)
RefreshData();
//Since this function is running from your main form, the function RefreshData() will be executed on your main form aswell
}
No need to check some dialog results at all.
I think this will work:
Add a property DatagridviewForm of type DatagridviewForm (you have probably an other name/type) to AnotherForm. In the part where you call anotherForm.ShowDialog, add the following code:
anotherForm = new AnotherForm();
anotherForm.DatagridviewForm = this;
anotherForm.ShowDialog();
anotherForm.Dispose();
In the close handler of AnotherForm, update or refresh the data:
private void AnotherForm_FormClosed(object sender, FormClosedEventArgs e)
{
DatagridviewForm.refreshData();
}
You can access the data when the form is closing
Form MyEditForm;
private void cell1_DoubleClick(object sender, System.EventArgs e)
{
if (MyEditForm==null)
{
MyEditForm=new MyEditForm();
MyEditForm.FormClosing += refreshData;
}
MyEditForm.ShowDialog();
}
private void refreshData(object sender, EventArgs e)
{
var myDataObj=MyEditForm.getData();
}

How to close form

Ok, so a Windows Forms class, WindowSettings, and the form has a "Cancel"-button. When the user clicks the button, the dialog DialogSettingsCancel will pop-up up and ask the user if he is sure he wants to perform the action. The dialog has 2 buttons, a "Yes"-button and a "No"-button. If the user clicks the "Yes"-button, I want both DialogSettingsCancel and WindowSettings to be closed.
My button_Click event handler in DialogSettingsCancel:
private void button1_Click(object sender, EventArgs e)
{
//Code to trigger when the "Yes"-button is pressed.
WindowSettings settings = new WindowSettings();
this.Close();
settings.Close();
}
When I run my application, and go to the settings form, and click the "Cancel"-button, and then click the "Yes"-button, only DialogSettingsCancel closes without closing WindowSettings.
Why won't it work?
I've also tried changing
this.Close();
settings.Close();
to
settings.Close();
this.Close();
But still the same result.
You need the actual instance of the WindowSettings that's open, not a new one.
Currently, you are creating a new instance of WindowSettings and calling Close on that. That doesn't do anything because that new instance never has been shown.
Instead, when showing DialogSettingsCancel set the current instance of WindowSettings as the parent.
Something like this:
In WindowSettings:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel();
dialogSettingsCancel.OwningWindowSettings = this;
dialogSettingsCancel.Show();
}
In DialogSettingsCancel:
public WindowSettings OwningWindowSettings { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.Close();
if(OwningWindowSettings != null)
OwningWindowSettings.Close();
}
This approach takes into account, that a DialogSettingsCancel could potentially be opened without a WindowsSettings as parent.
If the two are always connected, you should instead use a constructor parameter:
In WindowSettings:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel(this);
dialogSettingsCancel.Show();
}
In DialogSettingsCancel:
WindowSettings _owningWindowSettings;
public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
if(owningWindowSettings == null)
throw new ArgumentNullException("owningWindowSettings");
_owningWindowSettings = owningWindowSettings;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
_owningWindowSettings.Close();
}
You can also close the application:
Application.Exit();
It will end the processes.
new WindowSettings();
You just closed a brand new instance of the form that wasn't visible in the first place.
You need to close the original instance of the form by accepting it as a constructor parameter and storing it in a field.
Why not use the DialogResult method to close the form?
if(DialogSettingsCancel.ShowDialog() == DialogResult.Yes)
{
//this will close the form but will keep application open if your
//application type is "console" in the properties of the project
this.Close();
}
For this to work however you will need to do it inside your "WindowSettings" form while you call the DialogSettingsCancel form. Much the same way you would call the OpenFileDialog, or any other Dialog form.
Your closing your instance of the settings window right after you create it. You need to display the settings window first then wait for a dialog result. If it comes back as canceled then close the window. For Example:
private void button1_Click(object sender, EventArgs e)
{
Settings newSettingsWindow = new Settings();
if (newSettingsWindow.ShowDialog() == DialogResult.Cancel)
{
newSettingsWindow.Close();
}
}
send the WindowSettings as the parameter of the constructor of the DialogSettingsCancel and then on the button1_Click when yes is pressed call the close method of both of them.
public class DialogSettingsCancel
{
WindowSettings parent;
public DialogSettingsCancel(WindowSettings settings)
{
this.parent = settings;
}
private void button1_Click(object sender, EventArgs e)
{
//Code to trigger when the "Yes"-button is pressed.
this.parent.Close();
this.Close();
}
}
for example, if you want to close a windows form when an action is performed there are two methods to do it
1.To close it directly
Form1 f=new Form1();
f.close(); //u can use below comment also
//this.close();
2.We can also hide form without closing it
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
Form2 f2 = new Form2();
int flag = 0;
string u, p;
u = textBox1.Text;
p = textBox2.Text;
if(u=="username" && p=="pasword")
{
flag = 1;
}
else
{
MessageBox.Show("enter correct details");
}
if(flag==1)
{
f2.Show();
this.Hide();
}
}
There are different methods to open or close winform.
Form.Close() is one method in closing a winform.
When 'Form.Close()' execute , all resources created in that form are destroyed.
Resources means control and all its child controls (labels , buttons) , forms etc.
Some other methods to close winform
Form.Hide()
Application.Exit()
Some methods to Open/Start a form
Form.Show()
Form.ShowDialog()
Form.TopMost()
All of them act differently , Explore them !

Categories