Cannot access a disposed object - c#

Cannot access a disposed object
Anyone know why I would get this error "Cannot access a disposed object" on this line of code
Invoke(new UpdateTimerDelegate(UpdateTimer), new object[] { null });
Hit start over then either accept / reject / or close the form -- seems to happen when closing the form
the error happens when you bring the form up again
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TimerTester
{
public class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void StartOverBtn_Click(object sender, EventArgs e)
{
ShowForm2();
}
private void Form1_Load(object sender, EventArgs e)
{
ShowForm2();
}
private void ShowForm2()
{
Form2 f2;
f2 = new Form2(10000);
f2.Owner = this;
switch (f2.ShowDialog())
{
case DialogResult.Yes:
break;
case DialogResult.No:
break;
default:
break;
}
}
/// <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.StartOverBtn = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// StartOverBtn
//
this.StartOverBtn.Location = new System.Drawing.Point(33, 33);
this.StartOverBtn.Name = "StartOverBtn";
this.StartOverBtn.Size = new System.Drawing.Size(75, 23);
this.StartOverBtn.TabIndex = 0;
this.StartOverBtn.Text = "Start Over";
this.StartOverBtn.UseVisualStyleBackColor = true;
this.StartOverBtn.Click += new System.EventHandler(this.StartOverBtn_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.StartOverBtn);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button StartOverBtn;
}
}
form2
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;
using System.Diagnostics;
namespace TimerTester
{
public class Form2 : Form
{
public Form2(int timeoutSecondsForAcceptCall)
{
this.timeoutSecondsForAcceptCall = timeoutSecondsForAcceptCall;
InitializeComponent();
tUpdateTimer = new System.Threading.Timer(new System.Threading.TimerCallback(UpdateTimer), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
DateTime dtCreate = DateTime.Now;
int timeoutSecondsForAcceptCall = 99999;
System.Threading.Timer tUpdateTimer;
private delegate void UpdateTimerDelegate(object obj);
void UpdateTimer(object obj)
{
if (InvokeRequired == true)
{
Invoke(new UpdateTimerDelegate(UpdateTimer), new object[] { null });
}
else
{
TimeSpan ts = DateTime.Now - dtCreate;
if (ts.TotalSeconds > timeoutSecondsForAcceptCall)
{
DialogResult = DialogResult.Cancel;
return;
}
TimeSpan timeleft = TimeSpan.FromSeconds(timeoutSecondsForAcceptCall) - ts;
label1.Text = FormatTimeSpan(timeleft);
}
}
private string FormatTimeSpan(TimeSpan ts)
{
return ((int)ts.TotalMinutes).ToString().PadLeft(2, '0') + ":" + ((int)ts.Seconds).ToString().PadLeft(2, '0');
}
private void btnAccept_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Yes;
}
private void btnReject_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.No;
}
/// <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.btnAccept = new System.Windows.Forms.Button();
this.btnReject = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnAccept
//
this.btnAccept.Location = new System.Drawing.Point(31, 30);
this.btnAccept.Name = "btnAccept";
this.btnAccept.Size = new System.Drawing.Size(75, 23);
this.btnAccept.TabIndex = 0;
this.btnAccept.Text = "Accept";
this.btnAccept.UseVisualStyleBackColor = true;
this.btnAccept.Click += new System.EventHandler(this.btnAccept_Click);
//
// btnReject
//
this.btnReject.Location = new System.Drawing.Point(140, 29);
this.btnReject.Name = "btnReject";
this.btnReject.Size = new System.Drawing.Size(75, 23);
this.btnReject.TabIndex = 1;
this.btnReject.Text = "Reject";
this.btnReject.UseVisualStyleBackColor = true;
this.btnReject.Click += new System.EventHandler(this.btnReject_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(31, 80);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 2;
this.label1.Text = "label1";
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(240, 117);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnReject);
this.Controls.Add(this.btnAccept);
this.Name = "Form2";
this.Text = "Form2";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnAccept;
private System.Windows.Forms.Button btnReject;
private System.Windows.Forms.Label label1;
}
}

Your form is disposed by the time invoke() message is processed by the message loop. I donot think so there is a way to avoid it. You can put a check e.g
if(!yourForm.IsDisposed)
yourForm.Invoke(...)
But that may not work sometime as the invoke is posted to UI thread and by the time it is process form may already be disposed and you will still get that exception. You have to fix your program in a way to avoid this situation by making sure invoke is not posted on a disposed or disposing form. This is a fatal error and your program will exit after this. I think suppressing it via try{}catch{} will not work as framework already start to unload when catch block is executed.
You can fix the problem in two ways.
1. Just drop a timer component from toolbox i.e. System.Windows.Forms.Timer and use that.
Designer will automatically add it to component collection and dispose it before form is disposed.
2. Manually over OnDispose(bool disposing) in your form and perform
if(disposing)
yourTimer.Dispose()
So now your timer is dispose before your form so no subsequent invoke() will be posted to your form after its disposed.

You see this error, because your System.Threading.Timer is not component of form. Thus it doesn't get disposed when form is closed. I'd recommend you to use System.Windows.Forms.Timer instead. Because this is a component, which you can place on your Form and it will be disposed with other form's components (just drag it from toolbox in designer).
public class Form2 : Form
{
DateTime dtCreate = DateTime.Now;
int timeoutSecondsForAcceptCall = 99999;
public Form2(int timeoutSecondsForAcceptCall)
{
this.timeoutSecondsForAcceptCall = timeoutSecondsForAcceptCall;
InitializeComponent();
timer1.Interval = 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan ts = DateTime.Now - dtCreate;
if (ts.TotalSeconds > timeoutSecondsForAcceptCall)
{
DialogResult = DialogResult.Cancel;
return;
}
TimeSpan timeleft = TimeSpan.FromSeconds(timeoutSecondsForAcceptCall) - ts;
label1.Text = FormatTimeSpan(timeleft);
}
// other code
}
BTW another benefit of using System.Windows.Forms.Timer is that it's Tick event handler executed on UI thread. Thus you don't need to verify if invoke required.

I've had this problem before. There are a couple things you should be doing.
1) When you close your program, you should be removing handlers and/or shutting down timers or other code that will run as the program is exiting. You are still left with the problem of how many timer handlers will still run after shutting down the timer. One possible solution is to set a "stop running" flag after you turn off the Timer. Check the flag in the handler and don't run the code if it is set. The flag could be a bool marked as volatile or a long using Interlocked to avoid concurrency issues, especially if your timer is really short.
2) Wrap a try/catch around your Invoke statement, also put one in the GUI editing code (the part where InvokeRequired == false).

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.

How can I get the HTML from a Microsoft.Toolkit WebView?

I am using Microsoft.Toolkit.Forms.UI.Controls.WebView, available from https://www.nuget.org/packages/Microsoft.Toolkit.Forms.UI.Controls.WebView
I have added the WebView into my WinForms application - Designer code:
namespace Testing
{
partial class TestForm
{
/// <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.pnlWebPage = new System.Windows.Forms.Panel();
this.webView = new Microsoft.Toolkit.Forms.UI.Controls.WebView();
this.pnlWebPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.webView)).BeginInit();
this.SuspendLayout();
//
// pnlWebPage
//
this.pnlWebPage.Controls.Add(this.webView);
this.pnlWebPage.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlWebPage.Location = new System.Drawing.Point(0, 101);
this.pnlWebPage.Margin = new System.Windows.Forms.Padding(4);
this.pnlWebPage.Name = "pnlWebPage";
this.pnlWebPage.Size = new System.Drawing.Size(1205, 624);
this.pnlWebPage.TabIndex = 3;
//
// webView
//
this.webView.Dock = System.Windows.Forms.DockStyle.Fill;
this.webView.Location = new System.Drawing.Point(0, 0);
this.webView.Margin = new System.Windows.Forms.Padding(4);
this.webView.MinimumSize = new System.Drawing.Size(27, 25);
this.webView.Name = "webView";
this.webView.Size = new System.Drawing.Size(1205, 624);
this.webView.Source = new System.Uri("https://www.bbc.com", System.UriKind.Absolute);
this.webView.TabIndex = 0;
this.webView.NavigationCompleted += new System.EventHandler<Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT.WebViewControlNavigationCompletedEventArgs>(this.webView_NavigationCompleted);
//
// TestForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1505, 725);
this.Controls.Add(this.pnlWebPage);
this.Margin = new System.Windows.Forms.Padding(4);
this.Name = "TestForm";
this.Text = "TestForm";
this.pnlWebPage.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.webView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel pnlWebPage;
private Microsoft.Toolkit.Forms.UI.Controls.WebView webView;
}
}
Once a website has loaded into the WebView, I want to be able to extract the page's HTML and store it as a string or similar.
I've added the following method, which is called when the WebView's NavigationCompleted event happens.
private async void wvLI_NavigationCompleted(object sender, Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT.WebViewControlNavigationCompletedEventArgs e)
{
\\ HTML extraction to go here
}
I can't see a way to access the HTML however - there doesn't seem to be a property or similar for it. When researching how to do this I can only find questions and answers relating to Android or Xamarin - and none of the solutions for those work for the Microsoft Toolkit WebView. Does anyone know how I can achieve this?
You can invoke the JavaScript eval() function by calling InvokeScriptAsync (or InvokeScript) to get the outerHTML (or innerHTML or whatever you need) as follows:
private async void wvLI_NavigationCompleted(object sender, Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT.WebViewControlNavigationCompletedEventArgs e)
{
string html = await webView.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" });
}
It is important that this goes in the NavigationCompleted event, rather than, say, DOMContentLoaded, as the page is only fully loaded at the point of NavigationCompleted firing

Code executing after the form it is in has been closed and disposed

I have a Windows Forms App that is functioning in a way that I do not understand. I have created a simple app to reproduce the functionality to minimum logic for clarity. It has two forms.
Form1:
There is a button1 that when clicked adds rows to a datatable.
There is a button2 that displays a form and sends the datatable to the form.
Form2:
Form2 creates a dataview from the datatable and binds the dataview to a listbox. Form2 also has a button1 that does a this.Close() on the form. I read that anything opened with formName.Show() will be disposed of during .Close.
Here is where things are get weird. Form1 button1 can be clicked over and over each time clearing out the datatable and adds the rows again. Once from1 button2 is clicked and the form2 is displayed and then closed, going back to form1 and clicking button1 raises an error. The error is from the form2 (which has been closed) listBox1_SelectedIndexChanged event.
The question is, why is an event firing for a control that is gone on a form that is gone?
I have found several ways to avoid this but I am wanting to understand why it is happening such as setting the listbox datasource = null but would like to know what is going on.. Spent half a day trying to figure this out. SO community, please educate me here.
Form1 code
public partial class Form1 : Form
{
Boolean bInitialLoad = true;
DataTable dtHardware = new DataTable("Hardware");
Form2 multiServerView = new Form2();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dtHardware.Clear();
if (bInitialLoad == true)
{
dtHardware.Columns.Add("ServerName", typeof(String));
dtHardware.Columns.Add("Environment", typeof(String));
}
DataRow drNewRow = dtHardware.NewRow();
drNewRow["ServerName"] = "SomeName";
drNewRow["Environment"] = "SomeEnvironment";
dtHardware.Rows.Add(drNewRow);
drNewRow = dtHardware.NewRow();
drNewRow["ServerName"] = "SomeName2";
drNewRow["Environment"] = "SomeEnvironment2";
dtHardware.Rows.Add(drNewRow);
bInitialLoad = false;
}
private void button2_Click(object sender, EventArgs e)
{
OpenMultiServerView();
}
private void OpenMultiServerView()
{
multiServerView = new Form2(dtHardware);
this.AddOwnedForm(multiServerView);
multiServerView.Show();
}
}
Form1 Designer
namespace WindowsFormsApp4
{
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.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(308, 390);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(107, 34);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(437, 296);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(102, 33);
this.button2.TabIndex = 1;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(679, 482);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
}
}
Form2 code
public partial class Form2 : Form
{
DataView dvServers = null;
public Form2()
{
InitializeComponent();
}
public Form2(DataTable dt1)
{
InitializeComponent();
dvServers = new DataView(dt1);
}
private void Form2_Load(object sender, EventArgs e)
{
listBox1.DisplayMember = "ServerName";
listBox1.DataSource = dvServers;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
System.Windows.Forms.FormCollection fc = Application.OpenForms;
foreach (System.Windows.Forms.Form frm in fc)
{
if (frm.Name == "Form2")
{
return;
}
}
MessageBox.Show("I am the listbox event from Form2");
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
Form2 Designer
namespace WindowsFormsApp4
{
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.dataGridView1 = new System.Windows.Forms.DataGridView();
this.listBox1 = new System.Windows.Forms.ListBox();
this.button1 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(23, 113);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(749, 287);
this.dataGridView1.TabIndex = 0;
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(291, 31);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(171, 69);
this.listBox1.TabIndex = 1;
this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
//
// button1
//
this.button1.Location = new System.Drawing.Point(653, 415);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(118, 25);
this.button1.TabIndex = 2;
this.button1.Text = "button1";
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.Controls.Add(this.listBox1);
this.Controls.Add(this.dataGridView1);
this.Name = "Form2";
this.Text = "Form2";
this.Load += new System.EventHandler(this.Form2_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Button button1;
}
}
It's because the instance of Form2 isn't actually gone. You are correct in assuming that it has been disposed, since you called Show, but it has not been collected by the garbage collector. In fact, it can't be collected because in the code example provided Form1 has two references to the instance of Form2 that it created.
The first is in Form1.OwnedForms. The second is the field Form1.multiServerView.
You said you had a few ways to fix it, such as breaking the binding when Form2 closes, but I thought I'd just throw out this suggestion. If you don't actually need to create a new instance of Form2 every time you show it, you could just create one instance of it in the constructor of Form1, handle Form2.Closing and just hide Form2 when the user closes it.
So, something like...
public partial class Form1 : Form
{
//Removed bInitialLoad, we'll set up the data table in the constructor.
DataTable dtHardware = new DataTable("Hardware");
Form2 multiServerView; //No longer initalizing here, we'll do that in the constructor.
public Form1()
{
InitializeComponent();
dtHardware.Columns.Add("ServerName", typeof(String));
dtHardware.Columns.Add("Environment", typeof(String));
multiServerView = new Form2(dtHardware);
AddOwnedForm(multiServerView);
}
private void button1_Click(object sender, EventArgs e)
{
dtHardware.Clear();
//Removed the check of bInitialLoad.
DataRow drNewRow = dtHardware.NewRow();
drNewRow["ServerName"] = "SomeName";
drNewRow["Environment"] = "SomeEnvironment";
dtHardware.Rows.Add(drNewRow);
drNewRow = dtHardware.NewRow();
drNewRow["ServerName"] = "SomeName2";
drNewRow["Environment"] = "SomeEnvironment2";
dtHardware.Rows.Add(drNewRow);
//Removed setting bInitialLoad.
}
private void button2_Click(object sender, EventArgs e)
{
OpenMultiServerView();
}
private void OpenMultiServerView()
{
multiServerView.Show(); //Just show it.
}
}
public partial class Form2 : Form
{
DataView dvServers = null;
//Removed the empty constructor since Form1 no longer needs it.
public Form2(DataTable dt1)
{
InitializeComponent();
dvServers = new DataView(dt1);
}
private void Form2_Load(object sender, EventArgs e)
{
listBox1.DisplayMember = "ServerName";
listBox1.DataSource = dvServers;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("I am the listbox event from Form2");
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form2_Closing(object sender, FormClosingEventArgs e)
{
//Don't forget to wire it up in the designer!
//If the user clicks "button1" or the "X" then just hide the form.
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
Hide();
}
}
}
This way, there is only ever one instance of Form2 for Form1. You don't have to worry about instances of Form2 that are disposed but not collected yet triggering events when something on Form1 alters the data source.

InvalidOperationalException base.Dispose(disposing)

I creating diagnostic application for PLCs. I have one form and a few Controls, which was inherited of UserControl. This Controls I switch. One view is Dashboard, Graph, and so on. When the graph is running, exception is occured. Exception is showed on line "base.Dispose(disposing)" in Form1.Designer.cs. Do you have any idea, how I can fix it? Thanks for any ideas.
This is code of Form1.Designer.cs. Error is show on line base.Dispose(disposing). Basicaly I don't know what this part of code do. That I can't repair it. Can somebody tell me, how it works? When is this part called? I don't find any use of method Dispose() in my program, only override methodes in each Control (inherited from UserControl). Thanks
namespace WindowsFormsApplication1
{
partial class Form1
{
///
/// Required designer variable.
///
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)
{
/*Updated 8.4.2013*/
//try
//{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
//}
//catch { }
}
#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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.btn_ChangeLanguage = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.Zobraz_Palubka = new System.Windows.Forms.Button();
this.Zobraz_Verzi = new System.Windows.Forms.Button();
this.Zobraz_error = new System.Windows.Forms.Button();
this.Zobraz_Nastaveni = new System.Windows.Forms.Button();
this.Zobraz_TestIO = new System.Windows.Forms.Button();
this.Zobraz_monitor = new System.Windows.Forms.Button();
this.statusStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1});
resources.ApplyResources(this.statusStrip1, "statusStrip1");
this.statusStrip1.Name = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
resources.ApplyResources(this.toolStripStatusLabel1, "toolStripStatusLabel1");
//
// btn_ChangeLanguage
//
this.btn_ChangeLanguage.Image = global::WindowsFormsApplication1.Properties.Resources.flag_cze_mini;
resources.ApplyResources(this.btn_ChangeLanguage, "btn_ChangeLanguage");
this.btn_ChangeLanguage.Name = "btn_ChangeLanguage";
this.btn_ChangeLanguage.UseVisualStyleBackColor = true;
this.btn_ChangeLanguage.Click += new System.EventHandler(this.btn_ChangeLanguage_Click);
this.btn_ChangeLanguage.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.btn_ChangeLanguage.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.Transparent;
this.pictureBox1.Image = global::WindowsFormsApplication1.Properties.Resources.trojuhelnik;
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// Zobraz_Palubka
//
this.Zobraz_Palubka.Image = global::WindowsFormsApplication1.Properties.Resources.tachometr_mini;
resources.ApplyResources(this.Zobraz_Palubka, "Zobraz_Palubka");
this.Zobraz_Palubka.Name = "Zobraz_Palubka";
this.Zobraz_Palubka.UseVisualStyleBackColor = true;
this.Zobraz_Palubka.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_Palubka.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_Palubka.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Zobraz_Verzi
//
this.Zobraz_Verzi.Image = global::WindowsFormsApplication1.Properties.Resources.info_mini;
resources.ApplyResources(this.Zobraz_Verzi, "Zobraz_Verzi");
this.Zobraz_Verzi.Name = "Zobraz_Verzi";
this.Zobraz_Verzi.UseVisualStyleBackColor = true;
this.Zobraz_Verzi.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_Verzi.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_Verzi.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Zobraz_error
//
this.Zobraz_error.Image = global::WindowsFormsApplication1.Properties.Resources.error1_mini;
resources.ApplyResources(this.Zobraz_error, "Zobraz_error");
this.Zobraz_error.Name = "Zobraz_error";
this.Zobraz_error.UseVisualStyleBackColor = true;
this.Zobraz_error.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_error.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_error.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Zobraz_Nastaveni
//
this.Zobraz_Nastaveni.Image = global::WindowsFormsApplication1.Properties.Resources.settings_mini;
resources.ApplyResources(this.Zobraz_Nastaveni, "Zobraz_Nastaveni");
this.Zobraz_Nastaveni.Name = "Zobraz_Nastaveni";
this.Zobraz_Nastaveni.UseVisualStyleBackColor = true;
this.Zobraz_Nastaveni.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_Nastaveni.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_Nastaveni.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Zobraz_TestIO
//
this.Zobraz_TestIO.Image = global::WindowsFormsApplication1.Properties.Resources.testIO_mini;
resources.ApplyResources(this.Zobraz_TestIO, "Zobraz_TestIO");
this.Zobraz_TestIO.Name = "Zobraz_TestIO";
this.Zobraz_TestIO.UseVisualStyleBackColor = true;
this.Zobraz_TestIO.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_TestIO.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_TestIO.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Zobraz_monitor
//
this.Zobraz_monitor.Image = global::WindowsFormsApplication1.Properties.Resources.line_graph_icon_mini;
resources.ApplyResources(this.Zobraz_monitor, "Zobraz_monitor");
this.Zobraz_monitor.Name = "Zobraz_monitor";
this.Zobraz_monitor.UseVisualStyleBackColor = true;
this.Zobraz_monitor.Click += new System.EventHandler(this.Zobraz_Click);
this.Zobraz_monitor.MouseEnter += new System.EventHandler(this.Zobraz_Nastaveni_MouseEnter);
this.Zobraz_monitor.MouseLeave += new System.EventHandler(this.Zobraz_Nastaveni_MouseLeave);
//
// Form1
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.btn_ChangeLanguage);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.Zobraz_Palubka);
this.Controls.Add(this.Zobraz_Verzi);
this.Controls.Add(this.Zobraz_error);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.Zobraz_Nastaveni);
this.Controls.Add(this.Zobraz_TestIO);
this.Controls.Add(this.Zobraz_monitor);
this.Name = "Form1";
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button Zobraz_monitor;
private System.Windows.Forms.Button Zobraz_Nastaveni;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.Button Zobraz_TestIO;
private System.Windows.Forms.Button Zobraz_error;
private System.Windows.Forms.Button Zobraz_Verzi;
private System.Windows.Forms.Button Zobraz_Palubka;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Button btn_ChangeLanguage;
}
}
Here is exception detail:
System.InvalidOperationException was unhandled by user code
Message=Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Form.UpdateMenuHandles(MainMenu menu, Boolean forceRedraw)
at System.Windows.Forms.Form.UpdateMenuHandles()
at System.Windows.Forms.Form.MenuChanged(Int32 change, Menu menu)
at System.Windows.Forms.Form.Dispose(Boolean disposing)
at WindowsFormsApplication1.Form1.Dispose(Boolean disposing) in c:__Projects__\C#\RailJay Diagnostic SW\20130408\Motor\Motor\Form1.Designer.cs:line 23
at System.ComponentModel.Component.Dispose()
at System.Windows.Forms.ApplicationContext.Dispose(Boolean disposing)
at System.Windows.Forms.Application.ThreadContext.DisposeThreadWindows()
InnerException:
It appears that you're calling Dispose from a thread other than the GUI thread. You can't do that.
You need to be more specific - perhaps adding some code to what you are trying to do, where?
[EDIT]
As Jim mentioned, you are referencing a form from a seperate thread;
Here is exception detail:
System.InvalidOperationException was unhandled by user code
Message=Cross-thread operation not valid: Control 'Form1' accessed
from a thread other than the thread it was created on
This means that you are trying to dispose Form1 from a thread that it was not created on.
Have you got sperate threads running in the application, if so, this is the first place to look.
Are you closing the Form1 anywhere within code?

ContextMenu Will Not Stay Open C# .Net 4.0 Client Profile WinForms

I have been unable to figure out how to keep a context menu open after handling a click event past the first level. Here is an example of where I have a context menu with a menu of checkable menus. I open up the context menu after handling the click event, but I have to manually return to the inner menu. Is there a way to open up the outer menu programmatically or to prevent the inner menu from closing?
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 NoCloseContextMenu
{
public partial class Form1 : Form
{
bool[] store_checks = new bool[8];
public Form1()
{
InitializeComponent();
richTextBox1.AppendText("http://");
richTextBox1.LinkClicked += new LinkClickedEventHandler(richTextBox1_LinkClicked);
}
void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
{
MenuItemExtended[] inner_menuitems = new MenuItemExtended[8];
for (int i = 0; i < store_checks.Length; i++)
{
MenuItemExtended inner_menuitem = new MenuItemExtended("Check #" + i.ToString());
inner_menuitem.menuitem_index = i;
inner_menuitem.contextmenu_point = this.PointToClient(Cursor.Position);
inner_menuitem.Checked = store_checks[i];
inner_menuitem.Shortcut = (Shortcut)(131120 + i); //Ctrl+i = 131120+i
inner_menuitem.ShowShortcut = true;
inner_menuitem.Click += new EventHandler(inner_menuitem_Click);
inner_menuitems[i] = inner_menuitem;
}
MenuItem outer_menu = new MenuItem("Outer Menu", inner_menuitems);
ContextMenu context_menu = new ContextMenu(new MenuItem[] { outer_menu });
context_menu.Show(this, this.PointToClient(Cursor.Position));
}
void inner_menuitem_Click(object sender, EventArgs e)
{
MenuItemExtended sender_menu = (MenuItemExtended)sender;
store_checks[sender_menu.menuitem_index] = !store_checks[sender_menu.menuitem_index];
sender_menu.Checked = !sender_menu.Checked;
sender_menu.GetContextMenu().Show(this, sender_menu.contextmenu_point);
}
/// <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.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(13, 13);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(100, 96);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox richTextBox1;
}
public class MenuItemExtended : MenuItem
{
public int menuitem_index;
public Point contextmenu_point;
public MenuItemExtended(string text)
{
this.Text = text;
}
}
}
Also, is there any way to get the "Control + number" shortcuts to work and activate the click event? Thanks in advance for the help!
I did not find any way to prevent the context menu from closing so instead I used ContextMenuStrip and ToolStripMenuItem. This also fixed the problem I had with shortcuts not working before. I handle the Closing event of the menu containing the checkable items and cancel closing if the items were clicked/checked.
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 NoCloseContextMenu
{
public partial class Form1 : Form
{
bool[] store_checks = new bool[8];
public Form1()
{
InitializeComponent();
richTextBox1.AppendText("http://");
richTextBox1.LinkClicked += new LinkClickedEventHandler(richTextBox1_LinkClicked);
}
void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
{
ToolStripMenuItem[] inner_menuitems = new ToolStripMenuItem[8];
for (int i = 0; i < store_checks.Length; i++)
{
ToolStripMenuItem inner_menuitem = new ToolStripMenuItem("Check #" + i.ToString());
inner_menuitem.Checked = store_checks[i];
inner_menuitem.CheckOnClick = true;
inner_menuitem.ShortcutKeys = Keys.Control | (Keys)(48 + i); //Di = 48 + i
inner_menuitem.ShowShortcutKeys = true;
inner_menuitem.Click += new EventHandler(inner_menuitem_Click);
inner_menuitem.Tag = i.ToString();
inner_menuitems[i] = inner_menuitem;
}
ToolStripMenuItem outer_menu = new ToolStripMenuItem("Outer Menu", null, inner_menuitems);
outer_menu.DropDown.Closing += new ToolStripDropDownClosingEventHandler(DropDown_Closing);
ContextMenuStrip context_menu = new ContextMenuStrip();
context_menu.Items.Add(outer_menu);
context_menu.Show(this, this.PointToClient(Cursor.Position));
}
void DropDown_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked)
{
e.Cancel = true;
((ToolStripDropDownMenu)sender).Invalidate();
}
}
void inner_menuitem_Click(object sender, EventArgs e)
{
ToolStripMenuItem sender_menu = (ToolStripMenuItem)sender;
int index = int.Parse(sender_menu.Tag.ToString());
store_checks[index] = !store_checks[index];
}
/// <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.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(13, 13);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(100, 96);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox richTextBox1;
}
}
You can also select certain buttons from within your unclosable submenu to cause the context menu to close normally. For a specific ToolStripMenuItem to close the menu normally, give it a different event method to call:
inner_menuitem.Click += new EventHandler(inner_menuitem_Can_Close);
And use the following code in the method (works regardless of how deep the menus go):
void inner_menuitem_Can_Close(object sender, EventArgs e)
{
ToolStripMenuItem castSender = (ToolStripMenuItem)sender;
object owner = castSender.OwnerItem;
while (owner is ToolStripMenuItem)
{
if (((ToolStripMenuItem)owner).Owner is ContextMenuStrip)
((ContextMenuStrip)((ToolStripMenuItem)owner).Owner).Close();
owner = ((ToolStripMenuItem)owner).OwnerItem;
}
}
I would advise strongly against handling click events on 'parent' context menu items - let the OS handle this for you.

Categories