I have some code in my main form which loads another form as soon as the project launches:
private void Form1_Load(object sender, EventArgs e)
{
Updating upd = new Updating();
upd.Show();
}
This new form (currently) just contains this code:
private void Updating_Load(object sender, EventArgs e)
{
this.BackgroundImage = Properties.Resources.updating1;
Stopwatch dw = new Stopwatch();
dw.Start();
bool qsdf = true;
while (qsdf)
{
if (dw.ElapsedMilliseconds >= 3000) qsdf = false; dw.Stop();
}
this.BackgroundImage = Properties.Resources.updating2;
Stopwatch sw = new Stopwatch();
sw.Start();
qsdf = true;
while (qsdf)
{
if (sw.ElapsedMilliseconds >= 3000) qsdf = false; sw.Stop();
}
this.Close();
Now, for some reason, the form being called (form called Updating) doesn't show at all. All that currently happens is I get nothing at all for 6 seconds (as noted by the stopwatch) before I get my main form to show, not seeing the Updating form even once.
Note: this is the code in my Updating.Designer.cs which draws all the components:
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::BossCraftLauncher.Properties.Resources.updating1;
this.ClientSize = new System.Drawing.Size(300, 100);
this.ControlBox = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Updating";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "BCL Update";
this.Load += new System.EventHandler(this.Updating_Load);
this.ResumeLayout(false);
Your loop is blocking the UI thread. As the load event fires.. your loop stops it from continuing it's message queue.
The easiest option for you (as you're using WinForms) is to use a Timer control and put your code in the Tick event.
Why are you closing the Updating form on the updating_Load?? "this.Close();"
If you write the close() function in the formload,after loading the screen the form will be closed.
Related
I am a beginner in C#, so please bear with me. I have a form where I have a tab control, this tab control has 3 tabs. I am trying to show a form with each tab page. I am able to show a form on the first tab, but for some reason, the other two tabs do not load the forms. This is the code that I have. Am I doing something wrong? Do you have any suggestions?
private void MainTab_Load(object sender, EventArgs e)
{
HomeScreen fHome = new HomeScreen();
fHome.TopLevel = false;
fHome.Visible = true;
fHome.FormBorderStyle = FormBorderStyle.None;
fHome.Dock = DockStyle.Fill;
MainOptions.TabPages[0].Controls.Add(fHome);
}
private void CustomerTab_Click(object sender, EventArgs e)
{
CustomerScreen fCustomer = new CustomerScreen();
fCustomer.TopLevel = false;
fCustomer.Visible = true;
fCustomer.FormBorderStyle = FormBorderStyle.None;
fCustomer.Dock = DockStyle.Fill;
MainOptions.TabPages[1].Controls.Add(fCustomer);
}
edit:
More:
Also, in the tabcontrol- InitializeComponent I have the following
// HomeTab
//
this.HomeTab.Location = new System.Drawing.Point(4, 22);
this.HomeTab.Name = "HomeTab";
this.HomeTab.Size = new System.Drawing.Size(677, 452);
this.HomeTab.TabIndex = 0;
this.HomeTab.Text = "Home";
this.HomeTab.UseVisualStyleBackColor = true;
this.HomeTab.Click += new System.EventHandler(this.MainTab_Load);
//
// CustomerTab
//
this.CustomerTab.Location = new System.Drawing.Point(4, 22);
this.CustomerTab.Name = "CustomerTab";
this.CustomerTab.Padding = new System.Windows.Forms.Padding(3);
this.CustomerTab.Size = new System.Drawing.Size(677, 452);
this.CustomerTab.TabIndex = 1;
this.CustomerTab.Text = "Customer";
this.CustomerTab.UseVisualStyleBackColor = true;
this.CustomerTab.Click += new System.EventHandler(this.CustomerTab_Click);
I think you're just missing the Show() method...
And a suggestion: I don't know what kind of Pattern you're using, but as a beginner, you should declare your forms outside those methods, as a variable within the class scope, so you can access then later...
private HomeScreen fHome = new HomeScreen();
private CustomerScreen fCustomer = new CustomerScreen();
private void MainTab_Load(object sender, EventArgs e)
{
fHome.TopLevel = false;
fHome.Visible = true;
fHome.FormBorderStyle = FormBorderStyle.None;
fHome.Dock = DockStyle.Fill;
MainOptions.TabPages[0].Controls.Add(fHome);
fHome.Show(); // add this
}
private void CustomerTab_Click(object sender, EventArgs e)
{
fCustomer.TopLevel = false;
fCustomer.Visible = true;
fCustomer.FormBorderStyle = FormBorderStyle.None;
fCustomer.Dock = DockStyle.Fill;
MainOptions.TabPages[1].Controls.Add(fCustomer);
fCustomer.Show(); // add this
}
There's a lot to improve here, but that's a start.
I create a simple Windows Form with a text box, and Set button and a Toggle button. When I click the Toggle button, a thread is created setting text to the text box repeatedly. When I click the button again, the thread stops. When I click the Set button, a text is set to the text box once. Deadlock occurs if I do the following:
Run the app (in debug mode).
Click the Toggle button to let text run in the text box.
Click Set button. -> Deadlock occurs in this step.
Can you explain why and how deadlock occurs in this situation? How to avoid it?
Below is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace DeadLockTest
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace DeadLockTest
{
public class Form1 : Form
{
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private int counter;
private Thread thread;
private bool cancelRequested;
private string content;
private object lockKey = new object();
public Form1()
{
InitializeComponent();
}
protected void UpdateContent()
{
this.textBox1.Text = this.content;
}
protected void InvokeUpdateContent()
{
lock (this.lockKey)
{
if (InvokeRequired)
{
Invoke(new Action(UpdateContent));
}
else
{
UpdateContent();
}
}
}
protected void SetText(string text)
{
this.content = text;
InvokeUpdateContent();
}
protected void StressTest()
{
int localCounter = 0;
while (!this.cancelRequested)
{
SetText(string.Format("{0}", localCounter++));
}
this.cancelRequested = false;
this.thread = null;
}
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Location = new System.Drawing.Point(12, 12);
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(260, 20);
this.textBox1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 38);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Set";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(93, 38);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "Toggle";
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(284, 262);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
private void button1_Click(object sender, EventArgs e)
{
SetText(string.Format("{0}", this.counter++));
}
private void button2_Click(object sender, EventArgs e)
{
if (this.thread == null)
{
this.thread = new Thread(new ThreadStart(StressTest));
thread.Start();
}
else
{
this.cancelRequested = true;
}
}
}
}
Can you explain why and how deadlock occurs in this situation?
Sure...the deadlock occurs because of the lock()/Invoke() combination.
While the secondary thread is running and updating, it obtains a lock on the object. Then the secondary thread calls Invoke(), which is a synchronous call. It is key to realize that the secondary thread actually waits for the main UI thread to update the TextBox before continuing.
When you click the Set button, it attempts to update but must wait for the lock to be released by the secondary thread. At this point the main UI actually stops and freezes at the lock() line waiting for the secondary thread to release the lock. While waiting for the lock to be released, the main UI thread cannot process any messages.
But what is the secondary thread doing? It currently has the lock and is waiting for the main UI thread to service its synchronous Invoke() call. Since the main UI thread is waiting for the lock to be released, though, it cannot service any requests (including Invoke() requests) and bam...DEADLOCK! They are both waiting for each other.
How to avoid it?
Never use lock() from the main UI thread. In some scenarios, switching from Invoke() to BeginInvoke() can solve the problem since BeginInvoke() is asynchronous.
I've googled this problem for the past week, it's killing my peace! Please help... EventArrivedEventHandler is stuck in a loop, and if I stop it, then it won't catch events. But when I use a handler method, the thread is still concentrating on the loop, and won't give attention to the new form I'm trying to make in the handler! Strange thing is, if I just use something small, like a MessageBox, it doesn't cause an issue, just trying to instantiate a form causes the buttons to NOT draw. Then shortly after the program stops responding. In case you're wondering where the form code is, it's just a standard form made by .NET, that works everywhere else in the code except for in the event handler.
Thanks!
class MainClass
{
public static void Main()
{
TaskIcon taskbarIcon;
EventWatch myWatcher;
taskbarIcon = new TaskIcon();
taskbarIcon.Show();
myWatcher = new EventWatch();
myWatcher.Start();
Application.Run();
}
}
public class TaskIcon
{
public void Show()
{
NotifyIcon notifyIcon1 = new NotifyIcon();
ContextMenu contextMenu1 = new ContextMenu();
MenuItem menuItem1 = new MenuItem();
MenuItem menuItem2 = new MenuItem();
contextMenu1.MenuItems.AddRange(new MenuItem[] { menuItem1, menuItem2 });
menuItem1.Index = 0;
menuItem1.Text = "Settings";
menuItem1.Click += new EventHandler(notifyIconClickSettings);
menuItem2.Index = 1;
menuItem2.Text = "Exit";
menuItem2.Click += new EventHandler(notifyIconClickExit);
notifyIcon1.Icon = new Icon("app.ico");
notifyIcon1.Text = "Print Andy";
notifyIcon1.ContextMenu = contextMenu1;
notifyIcon1.Visible = true;
}
private static void notifyIconClickSettings(object Sender, EventArgs e)
{
MessageBox.Show("Settings Here");
}
private static void notifyIconClickExit(object Sender, EventArgs e)
{
//taskbarIcon.Visible = false; // BONUS QUESTION: Why can't I hide the tray icon before exiting?
Application.Exit();
}
}
public class EventWatch
{
public void Start()
{
string thisUser = WindowsIdentity.GetCurrent().Name.Split('\\')[1];
WqlEventQuery query = new WqlEventQuery();
query.EventClassName = "__InstanceCreationEvent";
query.Condition = #"TargetInstance ISA 'Win32_PrintJob'";
query.WithinInterval = new TimeSpan(0, 0, 0, 0, 1);
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += new EventArrivedEventHandler(showPrintingForm);
watcher.Start();
}
void showPrintingForm(object sender, EventArrivedEventArgs e)
{
// MessageBox.Show("This will draw just fine");
Form1 myForm;
myForm = new Form1();
myForm.Show(); // This causes a hangup
}
}
My guess would be that the ManagementEventWatcher calls the EventArrived handler from a different thread than the UI thread. Then your showPrintingForm is executed on that thread and accessing UI from a different thread than the UI thread is bad. You need to marshal your code back onto the UI thread.
I am building a kids learning application, where clicking on a button on panel, I want to show different forms in the same place of the panel. Can you please help with any walk-through or tutorial links?
This question should have been posted on Stackoverflow website rather than here.
But you can use this approach to handle the case.
subForm = new SubFormYouWantToLoad();
subForm.TopLevel = false;
subForm.FormBorderStyle = FormBorderStyle.None;
ContainerPanel.Controls.Add(subForm , 0, 1);
subForm .Visible = true;
You can add this code when you click on the specific button.
Here each subform is added to the Panel as a Control. You should remove the subform from the panel's control list before adding another subform. For this ,it is better to remove,close and dispose the first one.
ContainerPanel.Controls.Remove(activeform);
activeform.Close();
activeform.Dispose();
Instead of Forms use user controls and load them in to panels
Sample if you want to show usercontrol1
panel1.Controls.Clear();
panel1.Visible = true;
UserControl1 usr1 = new UserControl1();
usr1.Show();
panel1.Controls.Add(usr1);
If usercontrol2
panel1.Controls.Clear();
panel1.Visible = true;
UserControl1 usr2 = new UserControl2();
usr2.Show();
panel1.Controls.Add(usr2);
You could create a number of forms as user controls or a control that inheriets from a panel. Then have a parent form with a panel to hold the user controls. You can then change the active user control in the container when the panel needs to be changed.
There is a tutorial on msdn for creating user controls.
http://msdn.microsoft.com/en-us/library/a6h7e207(v=vs.71).aspx
I used this code to close the form on the panel but not worked..
private void button12_Click(object sender, EventArgs e)
{
dontShowPANEL();
//ActiveForm.Close();
MainImaginCp kj = new MainImaginCp();
//kj.Visible = false;
kj.panel2.Controls.Clear();
panel1.Visible = true;
EngABCLearning usr1 = new EngABCLearning();
usr1.Show();
kj.panel2.Controls.Add(usr1);
//kj.Focus();
}
And I used the following code to show the form in the panel.
private void toolStripMenuItem1_LR_ENG_Click(object sender, EventArgs e)
{
//kids.Form2 hj = new kids.Form2();
//hj.Show();
EngABCLearning gh = new EngABCLearning();
//gh.Show();
gh.TopLevel = false;
gh.FormBorderStyle = FormBorderStyle.None;
//Panel2.Controls.Add(subForm, 0, 1);
panel2.Controls.Add(gh);
gh.Visible = true;
}
This is closing my main form and exiting the application.
try this out i have loaded two forms inside a single panel
private void Form1_Load(object sender, EventArgs e)
{
Form2 f1 = new Form2();
f1.TopLevel = false;
f1.AutoScroll = true;
panel1.Controls.Add(f1);
f1.Dock = DockStyle.Left;
f1.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f1.Show();
//form2
Form3 f2 = new Form3();
f2.TopLevel = false;
f2.AutoScroll = true;
panel1.Controls.Add(f2);
f2.Dock = DockStyle.Left;
f2.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f2.Show();
}
try this i used this method to load multiple forms at one panel
private Form activeForm = null;
public void FormLoad(Form childForm)
{
if (activeForm != null)
{
activeForm.Close();
}
activeForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
panelName.Controls.Add(childForm);
childForm.Visible = true;
}
private void YourBtn1_Click(object sender, EventArgs e)
{
FormLoad(new youWantToLoadForm1Name());
}
private void YourBtn2_Click(object sender, EventArgs e)
{
FormLoad(new youWantToLoadForm2Name());
}
I'm new to C# and WinForms so please excuse me is this is a bit of a newbie question.
I'm trying to add a tooltip to my TrackBar control which shows the current value of the bar as you drag it. I've instantiated a ToolTip object and tried the following handler code but it doesn't show any tooltip:
private void trackBar1_Scroll(object sender, EventArgs e)
{
toolTip1.SetToolTip(trackBar1, trackBar1.Value.ToString());
}
Adam I've just implemented a very simple version of this and it works exactly as expected...
Here's the init code for comparison
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.trackBar1 = new System.Windows.Forms.TrackBar();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
this.SuspendLayout();
//
// trackBar1
//
this.trackBar1.Location = new System.Drawing.Point(12, 166);
this.trackBar1.Name = "trackBar1";
this.trackBar1.Size = new System.Drawing.Size(268, 42);
this.trackBar1.TabIndex = 1;
this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.trackBar1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
toolTip1.SetToolTip(trackBar1, trackBar1.Value.ToString());
}
And it works as I move the ticker to each additional increment...
How did you initialise the toolTip1 class? The way you set the tool tip text looks ok, maybe you have so set some general properties before the component does the job?
MSDN says
// Create the ToolTip and associate with the Form container.
ToolTip toolTip1 = new ToolTip();
// Set up the delays for the ToolTip.
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
// Force the ToolTip text to be displayed whether or not the form is active.
toolTip1.ShowAlways = true;