I'm getting my way around c# slowly but surely lol in this code:
// create an instance of the main form
public formMain _formMain;
public void btnDynaDotCheck_Click(object sender, EventArgs e)
{
if (_formMain.bgWorker.IsBusy != true)
{
this.btnDynaDotCheck.Enabled = false;
_formMain.bgWorker.RunWorkerAsync("dr_begin_dd_check");
}
else
{
_formMain.returnMessage("Please wait untill the current task is finished...");
return;
}
}
I'm trying to access the background worker in formMain.cs from anotherForm.cs there is no errors in VS, but when run i get
"An unhandled exception of type 'System.NullReferenceException'
occurred in " and "Additional information: Object reference not set to
an instance of an object."
On this line:
if (_formMain.bgWorker.IsBusy != true)
So i'm not really getting access in this case eh?
Use dependency injection to inject a reference to your mainform into the otherone : somewhere in your mainform code do the following :
anotherForm _anotherForm = new anotherForm(this);
_anotherForm.Show();
assuming you are creating anotherform from code within the mainform, this is actually referring to the mainform.
In the constructor of anotherFrom do this :
public anotherForm(MainForm formMain){
_formMain = formMain;
}
This is by far the most elegant way to solve this issue. Because it makes clear that there is a dependency from one form to the other and makes the design intention clear.
Using a parent is also fine, but only if the mainform is really a parent of the other form.
Going via Application object will work, but the application object is a global and you hide your dependency that way.
_formMain = Application.OpenForms["formMain"];
Add this code in button click and try it.
When accessing _formMain from anotherForm:
I assume anotherForm is instantiated and called from _formMain like this:
anotherForm _anotherForm = new anotherForm();
_anotherForm.Show();
there's now several ways to access _formMain from _anotherForm but the easiest I think is to set _formMain as the parent of _anotherForm:
_anotherForm.Parent = this; // insert before _anotherForm.Show()
this way you can get hold of it in _anotherForm like this
public void btnDynaDotCheck_Click(object sender, EventArgs e)
{
...
formMain _formMain = this.Parent as formMain;
if(_formMain != null)
{
... // do whatever ever you have to do
}
}
but be careful... getting your BackgroundWorker in _formMain requires public methods you can call and return your BackgroundWorker.
Hope this helps!
Thanks for the help guys :)
I now have:
// create an instance of the formMain
formMain _formMain = new formMain();
public void btnDynaDotCheck_Click(object sender, EventArgs e)
{
if (_formMain.bgWorker.IsBusy != true)
{
this.btnDynaDotCheck.Enabled = false;
_formMain.bgWorker.RunWorkerAsync("dr_begin_dd_check");
}
else
{
_formMain.returnMessage("Please wait untill the current task is finished...");
return;
}
}
Which works :) it gets through to the main form:
public void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
// action to string format
string action = e.Argument as string;
if (action == "dr_begin_dd_check")
{
BeginInvoke((Action)(() =>
{
statusLabel.Text = "Access the bgw...";
}
));
} // dr_begin_dd_check
I'm now getting the error in the formMain:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
I'm not sure where the error lies in my above code or actually in the formMain section, or should i open a new question? :)
cheers guys
Graham
Related
Wierd behaviour when passing values to and from second form.
ParameterForm pf = new ParameterForm(testString);
works
ParameterForm pf = new ParameterForm();
pf.testString="test";
doesn't (testString defined as public string)
maybe i'm missing something? Anyway I'd like to make 2nd variant work properly, as for now - it returns null object reference error.
Thanks for help.
Posting more code here:
calling
Button ParametersButton = new Button();
ParametersButton.Click += delegate
{
ParameterForm pf = new ParameterForm(doc.GetElementById(ParametersButton.Tag.ToString()));
pf.ShowDialog(this);
pf.test = "test";
pf.Submit += new ParameterForm.ParameterSubmitResult(pf_Submit);
};
definition and use
public partial class ParameterForm : Form
{
public string test;
public XmlElement node;
public delegate void ParameterSubmitResult(object sender, XmlElement e);
public event ParameterSubmitResult Submit;
public void SubmitButton_Click(object sender, EventArgs e)
{
Submit(this,this.node);
Debug.WriteLine(test);
}
}
result:
Submit - null object reference
test - null object reference
pf.ShowDialog(this); is a blocking call, so pf.Submit += new ParameterForm.ParameterSubmitResult(pf_Submit); is never reached: switch the order.
Submit(this,this.node); throws a null object reference because no event is assigned to it (see above). Generally, you should always check first: if (Submit != null) Submit(this,this.node);
You should change ``pf.ShowDialog(this);topf.Show(this);` so that your main form isn't disabled while your dialog box is open, if that's what you want, or use the model below (typical for dialog boxes.)
I'm not sure what pf_Submit is supposed to do, so this might not be the best way to go about it in your application, but it's how general "Proceed? Yes/No" questions work.
Button ParametersButton = new Button();
ParametersButton.Click += delegate
{
ParameterForm pf = new ParameterForm(testString);
pf.ShowDialog(this); // Blocks until user submits
// Do whatever pf_Submit did here.
};
public partial class ParameterForm : Form
{
public string test; // Generally, encapsulate these
public XmlElement node; // in properties
public void SubmitButton_Click(object sender, EventArgs e)
{
Debug.WriteLine(test);
this.Close(); // Returns from ShowDialog()
}
}
When you want to use your second variant, you have to use a getString()-Method, where you can put the e.g. "testString". The way you wrote it, "testString" should be a method (and got brackets).
EDIT (a bit more precise):
You could write:
pf.getString(testString);
, if "pf" is an instance of your own class, otherwise you had to look up, whether you can retrieve a String in this class.
the thing was in line order :)
pf.Submit += new ParameterForm.ParameterSubmitResult(pf_Submit);
and
pf.Test = "test";
should have been set before
pf.ShowDialog(this);
my mistake thingking that parameter can be passed after 2nd form was displayed
thnx for answers
I am having an odd problem with protecting a section of code. My application is a tray app. I create a NotifyIcon inside my class (ApplicationContext). I have assigned a balloon click handler and a double click handler to the NotifyIcon object. there is also a context menu but I am not showing all code. Only important pieces.
public class SysTrayApplicationContext: ApplicationContext
{
private NotifyIcon notifyIcon;
private MainForm afDashBoardForm;
public SysTrayApplicationContext()
{
this.notifyIcon = new NotifyIcon();
this.notifyIcon.BalloonTipClicked += notifyIcon_BalloonTipClicked;
this.notifyIcon.MouseDoubleClick += notifyIcon_MouseDoubleClick;
// ... more code
}
Both handlers launch or create/show my form:
private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
openDashboard();
}
}
private void notifyIcon_BalloonTipClicked(object sender, EventArgs e)
{
openDashboard();
}
private void openDashboard()
{
if (dashBoardForm != null)
{
log.Debug("Dashboard form created already, so Activate it");
dashBoardForm.Activate();
}
else
{
log.Debug("Dashboard form does not exist, create it");
dashBoardForm = new MainForm();
dashBoardForm.Show();
}
}
There is a problem with the above code. Maybe more than 1. Issue: it is possible to display 2 dashboard forms which is not what I want. If user double clicks on tray icon while balloon message is displaying causes a race condition in openDashboard. I can reproduce this easily. So I added a lock around the code in openDashboard code and, to my surprise, that did NOT prevent 2 dashboard forms from displaying. I should not be able to create 2 MainForms. Where am I going wrong here?
here is the updated code with lock statement:
private void openDashboard()
{
lock (dashBoardFormlocker)
{
if (dashBoardForm != null)
{
log.Debug("Dashboard form created already, so Activate it");
dashBoardForm.Activate();
}
else
{
log.Debug("Dashboard form does not exist, create it");
dashBoardForm = new MainForm();
dashBoardForm.Show();
}
}
}
Note: lock object was added to the class and initialized in constructor.
private object dashBoardFormlocker;
UPDATE: Showing more code. this is how code gets started :
static void Main()
{
if (SingleInstance.Start())
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
XmlConfigurator.Configure();
// For a system tray application we don't want to create
// a form, we instead create a new ApplicationContext. The Run method takes
Application.Run(new SysTrayApplicationContext());
SingleInstance.Stop();
SingleInstance.Dispose();
}
}
}
UPDATE 2: Provide more code for clarity
public partial class MainForm : Form
{
public MainForm()
{
log.Trace("MainForm constructor...");
InitializeComponent();
// ... code not shown
this.label_OSVersion.Text = getOSFriendlyName();
// .. more code
}
private string getOSFriendlyName()
{
try
{
string result = string.Empty;
var mgmtObj = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().OfType<ManagementObject>()
select x.GetPropertyValue("Caption")).FirstOrDefault();
result = mgmtObj != null ? mgmtObj.ToString() : string.Empty;
OperatingSystem os = Environment.OSVersion;
String sp = os.ServicePack ?? string.Empty;
return !string.IsNullOrWhiteSpace(result) ? result + sp : "Unknown";
}
catch (System.Exception ex)
{
log.Error("Error trying to get the OS version", ex);
return "Unknown";
}
}
}
The main UI thread must always pump a message loop to support communication from COM components.
So when you do a blocking operation from the UI thread like locking or joining a thread, (EDIT: edited based on Peter Duniho's fix) the UI thread will enter an 'alertable' state, allowing COM to dispatch certain type of messages, which in turn can cause re-entrancy issues like in your scenario.
Look at the answer to this question (Why did entering a lock on a UI thread trigger an OnPaint event?) for a much more accurate explanation.
Looking at the source code of ManagementObjectSearcher.Get there is a lock (inside Initialize), and since you call it from the constructor of your form, it may lead to the second event triggering while the form's constructor has not finished. The assignment to the dashBoardFormlocker variable only happens after the constructor finishes, so that would explain why it was null on the second entry.
The moral of the story is never do blocking operations on the UI thread.
Without a good, minimal, complete code example that reliably reproduces the problem, it's impossible to know for sure what the problem is. But the guess by answerer tzachs seems reasonable. If so, you can fix your problem by changing your method to look like this:
private bool _dashboardOpen;
private void openDashboard()
{
if (_dashboardOpen)
{
if (dashBoardForm != null)
{
log.Debug("Dashboard form created already, so Activate it");
dashBoardForm.Activate();
}
}
else
{
log.Debug("Dashboard form does not exist, create it");
_dashboardOpen = true;
dashBoardForm = new MainForm();
dashBoardForm.Show();
}
}
In that way, any re-entrant attempt to open the window will be detected. Note that you still need the check for null before actually activating; you can't activate a window that hasn't actually finished being created yet. The subsequent call to Show() will take care of activation anyway, so ignoring the activation in the re-entrant case shouldn't matter.
In my program on the WindowsForms I have a MainForm, which contains ProgressBar. In the ChildForm I want to change it's value, but I'm getting an error:
"int" does not contain a definition for "Value". Unable to find an extension method "Value", taking first argument of type "int" (missing a using directive or an assembly reference?)
Main Form:
public int ProgressBar5
{
get { return progressBar5.Value; }
set { progressBar5.Value = value; }
}
Child Form:
static MainForm mainForm = new MainForm();
private void button1_Click(object sender, EventArgs e)
{
mainForm.ProgressBar5.Value++; // Error
}
Edit1:
In the main form the value of the progressBar5 is always equals 1. What can be reason of it? I thought, that static can fix it.
Main Form:
private void button9_Click(object sender, EventArgs e)
{
Child child = new Child();
child.ShowDialog();
MessageBox.Show(progressBar5.Value.ToString()); // All time Value = 1
}
Your ProgressBar5 property already takes care of accessing the Value property of the progress bar. It doesn't return the progress bar, but rather the current progress. This means that the caller doesn't need to access the Value property of the result (since there is none).
Just write:
mainForm.ProgressBar5++;
Of course, for clarity's sake, it would probably be better to call such a property CurrentProgress rather than ProgressBar because it doesn't return a progress bar, it returns (or sets) the current progress.
Of course, better still would be for the child for to have no knowledge of the main form at all. Rather than passing in the main form itself the child form can accept an IProgress instance. It can then report progress to whomever is creating this form, whether that be your main form, or anything else. The main form is then responsible for doing whatever it wants when progress is reported, which it can define in either an event handler or a delegate passed into the Progress constructor.
The problem is that you have two variables with similar names, causing quite a bit of confusion. When you try and access the ProgressBar5 variable you are actually getting the int property you declared in the first snippet.
Since int does not have a Value property, you get the compile time error. Change your code to:
static MainForm mainForm = new MainForm();
private void button1_Click(object sender, EventArgs e)
{
mainForm.ProgressBar5++; // Fixed!
}
I have two forms.
One of them is the main form (let's call it MainForm)
the other one is for showing some warning (let's call it dialogForm)
. dialogForm has a label in it. When i click a button in MainForm, dialogForm opens.
But label in dialogForm is blank. It doesn't have time to load actually. I want to check if the dialogForm fully loaded then proccess can continue in MainForm.
For example:
dialogForm tempFrm = new dialogForm();
tempFrm.Show(); // I want to wait till the dialogForm is fully loaded. Then continue to "while" loop.
while(..)
{
...
}
Why not create a boolean value, and a method to access it..
private bool Ready = false;
public ConstructorMethod()
{
// Constructor code etc.
Ready = true;
}
public bool isReady()
{
return Ready;
}
you can try the following
private bool Is_Form_Loaded_Already(string FormName)
{
foreach (Form form_loaded in Application.OpenForms)
{
if (form_loaded.Text.IndexOf(FormName) >= 0)
{
return true;
}
}
return false;
}
you can also look in this
Notification when my form is fully loaded in C# (.Net Compact Framework)?
So you need to consume the forms Shown event:
tempFrm.Shown += (s, e) =>
{
while(..)
{
}
}
But you're going to have another problem. It's going to block the thread. You need to run this while loop on another thread by leveraging a BackgroundWorker or Thread.
Your while(...) blocks the UI thread so child form will never got messages and will not be loaded.
To achive you goal you should subscribe to the Load event and continue your code in the handler.
void Click()
{
var tempFrm = new dialogForm();
tempFrm.Load += frmLoad;
tempFrm.Show();
}
void frmLoad(object s, EventArgs ea)
{
// form loaded continue your code here!
}
You can use Form.IsActive property.
Or just;
public bool IsFormLoaded;
public MyForm()
{
InitializeComponent();
Load += new System.EventHandler(FormLoaded);
}
private void FormLoaded(object sender, EventArgs e)
{
IsFormLoaded = true;
}
and check if YourForm.IsFormLoaded, true or false
I just want a c# application with a hidden main window that will process and respond to window messages.
I can create a form without showing it, and can then call Application.Run() without passing in a form, but how can I hook the created form into the message loop?
Is there another way to go about this?
Thanks in advance for any tips!
Excellent! That link pointed me in the right direction. This seems to work:
Form f = new Form1();
f.FormBorderStyle = FormBorderStyle.FixedToolWindow;
f.ShowInTaskbar = false;
f.StartPosition = FormStartPosition.Manual;
f.Location = new System.Drawing.Point(-2000, -2000);
f.Size = new System.Drawing.Size(1, 1);
Application.Run(f);
To keep it from showing up in Alt-Tab, you need it to be a tool window. Unfortunately, this prevents it from starting minimized. But setting the start position to Manual and positioning it offscreen does the trick!
In the process of re-writing a VC++ TaskTray App, in C# .NET, I found the following method truly workable to achieve the following.
No initial form dislayed at startup
Running Message Loop that can be used with Invoke/BeginInvoke as needed as IsWindowHandle is true
The steps I followed:
Used an ApplicationContext in Application.Run() Instead of a form. See http://www.codeproject.com/Articles/18683/Creating-a-Tasktray-Application for the example I used.
Set the Form's ShowInTaskbar property to true within the GUI Designer. (This seems counter productive but it works)
Override the OnLoad() method in your Form Class setting Visible and ShowInTaskbar to false as shown below.
protected override void OnLoad(EventArgs e)
{
Visible = false;
ShowInTaskbar = false;
base.OnLoad(e);
}
I know this is old question, but it ranks well in google, so I will provide my solution anyway.
I do two things:
private void Form_Load(object sender, EventArgs e)
{
Opacity = 0;
}
private void Form_Shown(object sender, EventArgs e)
{
Visible = false;
Opacity = 100;
}
The best way is to use the following 1-2 lines in the constuctor:
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false; // This is optional
You can even set the Minimized property in the VS Property window.
You can create a class that inherits from System.Windows.Forms.NativeWindow (which provides basic message loop capability) and reference the Handle property in its constructor to create its handle and hook it into the message loop. Once you call Application.Run, you will be able to process messages from it.
I solved the problem like this:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Main main = new Main();
Application.Run();
//Application.Run(new Main());
}
This code resides in the Program.cs file, and you can see the original Application.Run method call commented out. I just create a Main class object (my main form class is named Main) and start application message loop w/o any parameters. This starts the application, initializes any form components but doesn't show the form.
Note: you have to have some method to get your window showing (like system tray icon, hotkey or timer or anything you might like).
public partial class Form1 : Form
{
private bool _isApplicationRun;
public Form1(bool applicationRun)
{
InitializeComponent();
_isApplicationRun = applicationRun;
}
protected override void SetVisibleCore(bool value)
{
if (_isApplicationRun)
{
_isApplicationRun = false;
base.SetVisibleCore(false);
return;
}
base.SetVisibleCore(value);
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.Run(new Form1(true));
}
}
Why can't you just pass the form when you call Application.Run? Given that it's clearly a blocking call, on what event do you want to show the form? Just calling form.Show() should be enough.
Using Kami's answer as an inspiration, I created a more complete concept. If you use this solution, don't ever show the hidden window. If you do, the user might close it and then you've lost the ability to control the application exit in an orderly way. This approach can be used to manage a Timer, NotifyIcon, or any other component that is happy living on an invisible form.
using System;
using System.Windows.Forms;
namespace SimpleHiddenWinform
{
internal class HiddenForm : Form
{
private Timer _timer;
private ApplicationContext _ctx;
public HiddenForm(ApplicationContext ctx)
{
_ctx = ctx;
_timer = new Timer()
{
Interval = 5000, //5 second delay
Enabled = true
};
_timer.Tick += new EventHandler(_timer_Tick);
}
void _timer_Tick(object sender, EventArgs e)
{
//tell the main message loop to quit
_ctx.ExitThread();
}
}
static class Program
{
[STAThread]
static void Main()
{
var ctx = new ApplicationContext();
var frmHidden = new HiddenForm(ctx);
//pass the application context, not the form
Application.Run(ctx);
}
}
}
Form1 f1=new Form1();
f1.WindowState = FormWindowState.Minimized;
f1.ShowInTaskbar = false;
in the Form1 code file add this.Visible = false; to the constructor.
This will hide the window but it will flash for a sec before it is hidden. Alternatively you can write your own Application.Run command.
for more info http://social.msdn.microsoft.com/forums/en-US/winforms/thread/dece45c8-9076-497e-9414-8cd9b34f572f/
also you may want to set the this.ShowInTaskbar to false.
You should look at creating a 'service' as this is an application without a form.
See http://support.microsoft.com/kb/816169