How to get form when it is which is not visible? - c#

I want to get form which is open but hidden. I have tried by this. I get the form but in this case form show and hide within fraction of second. If I skip mfrm.Show(), I don't get MailSynchronize form in Application.OpenForms.
MailSynchronize mfrm = new MailSynchronize();
mfrm.Show();
mfrm.Hide();
I get form by following method.
foreach (Form f in Application.OpenForms) //it will return all the open forms
{
if (f.Name == "MailSynchronize")
{
mfrm = (MailSynchronize)f;
break;
}
}
Can anybody please suggest me how to get open form which is hidden by default and I can get in Application.OpenForms?

If I Hide a form, does it exist in Application.OpenForms?
No, unfortunately if you Hide a form, it will not be present in Application.OpenForms
So how can I open an invisible Form? Also I want it to exists in Application.OpenForms.
If you want to open an invisible Form, and you want it want it to exists in Application.OpenForms, you can use this code instead of simply Show():
var f = new MailSynchronize();
f.Opacity = 0;
f.ShowInTaskbar = false;
f.Show();
How to find that form again?
To get the open instance of form you can use Application.OfType<MailSynchronize>()
var f= Application.OpenForms.OfType<MailSynchronize>()
.FirstOrDefault();
When I found it, How to show it again?
f.Opacity = 1;
f.ShowInTaskbar = true;
f.Show();
How to hide it again?
You should not call Hide() to hide the form because it makes the form to get out of Application.OpenForms, instead you should use this way:
f.Opacity = 0;
f.ShowInTaskbar = false;
Is there another way?
Yes, for example you can create an static property in a class, for example in Program.cs this way:
public static MailSynchronize MailSynchronizeInstance { get; set; }
and the first time you want to open your form, you can assign the instance to this property, and then you can use it using Program.MailSynchronizeInstance to show or hide and you don't need to look in Application.OpenForms or perform a workaround.
Also you can make this property in a singletone way.

EDIT
This should work for your specific case now:
this.Opacity = 0;
this.ShowInTaskbar = false;
When you add these 2 codelines in your MailSynchronize constructor the form will start minimized but will not show in your taskbar, which is essentially the effect you were looking for. Also the form will now popup in your Application.OpenForms Collection.

When form initiallize.
MailSynchronize mfrm = new MailSynchronize();
mfrm.Opacity = 0;
mfrm.Show();
mfrm.Hide();
How to find that form again?
foreach (Form f in Application.OpenForms) //it will return all the open forms
{
if (f.Name == "MailSynchronize")
{
mfrm = (MailSynchronize)f;
break;
}
}
When I found it, How to show it again?
mfrm.Opacity = 1;
mfrm.Show();
Hide again by Button.
mfrm.Hide(); //It will not show form in Application.OpenForms if I hide again by mfrm.Opacity = 0;

use f.Visible (return type is bool)
if it returns false, it means form is hidden. If it returns true then form is visible.

Related

How can I write a generic method to add any form to a tab control and set properties on those forms?

I am trying to write a generic method which would allow me to add a form as the contents of a Tab on a tab control, however I am only able to figure out how to add it when specifying the exact form I wish to add.
Suppose I have three forms Form1, Form2, and Form3 where Form1 contains the tab control tabControl1, and Form2 inherits Form, where Form3 inherits MetroForm. Following is the method I am currently using :
private void AddFormAsTab() {
Form3 f = new Form3()
{
TopLevel = false,
ShowInTaskbar = false,
ControlBox = false,
SizeGripStyle = SizeGripStyle.Hide,
Visible = false,
Text = string.Empty,
FormBorderStyle = FormBorderStyle.None,
Dock = DockStyle.Fill,
MinimizeBox = false,
MaximizeBox = false,
ShadowType = MetroFormShadowType.None,
Movable = false
};
TabPage tab = new TabPage();
tab.Controls.Add( f );
tabControl1.TabPages.Add( tab );
f.Visible = true;
}
What I would like to do, is modify this method so that AddFormAsTab() accepts any form type and sets the properties as necessary (to ensure they are set as I am lazy and do not wish to change all those properties on every form I design perpetually when recycling this component)
I have seen this done in other controls such as Telerik, and DevExpress where the control accepts a generic and modifies it to 'fit' the purpose. In my case, I am changing the properties of the form so that it fills the tabpage, has no border, title bar, etc.
I have considered using (typeof(T))obj type code, but this generates pre-compile errors where those properties do not exist in obj which prevent it from being built, even though in theory, this should work.
I have also tried stuff like Form f = new Form1(), however this doesn't work as Form is not the same type as Form1 which happens to inherit Form.
What can I do to make this happen, to allow any form to be set without hardcoding those specific forms classes into the AddFormAsTab() method, but still delegate responsibility to set the required properties to that method ?
Ideally, something like :
private void AddFormAsTab<T>(T obj) { ... }
You can use either of these options:
public void AddFormAsTab<T>() where T : Form, new()
{
var f = new T();
f.TopLevel = false;
//...
}
Usage:
AddFormAsTab<Form1>();
Or
public void AddFormAsTab(Form f)
{
f.TopLevel = false;
//...
}
Usage:
AddFormAsTab(new Form1());

Is there any other way to access open forms in C#?

Application.OpenForms["formname"];
Is there any other way to access an open form. My application doesn't see this form although it is opened. I dont know why.
Isn't really necessary a name to get an open form.
You can get the form you want by index:
Form frm = Application.OpenForms[0] //Will get the main form
Form frm = Application.OpenForms[1] //Will get the first child
Forms in the OpenForms collection are ordered in the same way that you create it
Otherwise, an alternative is to save a reference to the form and then accessing it by this reference.
//Where you want to save the reference:
Form theForm;
//Where you create the form:
myClass.theForm = new MyForm();
//Where you want to get that form:
MessageBox.Show(myClass.theForm.Caption);
(myClass is the class that will hold your reference to the form, supposing you are accessing it from different classes)
(Also, see if you are affected by this: Application.OpenForms.Count = 0 always)
I recommend you to firstly debug your code to check what is the Form actual name which you want to load:
foreach (Form form in Application.OpenForms) {
string name = form.Name; //check out this name!!
//print, or anything else will do, you only want to get the name
//note that you should be able to get any form as long as you get its name correct
}
And then, once you know what is wrong with your code, simply do:
Form form = Application.OpenForms[name]; //use the same name as whatever is available according to your debug
To get your form.
To check more on the possible bugs, See Hans Passant's Post
You have to instanciate first a Form. after that you have access to it:
Form1 formname = new Form1();
Application.Run(formname);
// access to form by formname.yourproperty
To access the form using this property your form must have a Name.
Remember its not the instance name nor the the form Text:
Form1 f1 = new Form1(); //not "f1" is the "Name"
f1.Text = "it is title of the form"; //neither "Text" is the "Name"
f1.Name= "its the name"; //it is the "Name"
Sample:
frm_myform form1 = new frm_myform();
frm_myform.Name = "form1";

C# Can't change labels and button properties from a dialogbox

I have my main form and a dialogbox which is called from main. In my main form I have a label and a button that which properties I can't change. I'm using Visual Studio 2015, not sure if there is a bug regarding this. I also made sure my label and button are set to public to modify.
Code: (this is from the dialog box, this has a list box the function is triggered at selectindexchange)
else if ((short)lbDiscountTypes.SelectedValue == 2) //Senior
{
frm_Main main = new frm_Main();
main.VAT = false;
main.labelStatus.Text = "NON-VAT (SENIOR)";
main.labelStatus.BackColor = System.Drawing.Color.IndianRed;
main.labelStatus.ForeColor = System.Drawing.Color.WhiteSmoke;
main.btnNonVat.Enabled = false;
main.btnNonVat.BackColor = System.Drawing.Color.SlateGray;
main.btnNonVat.ForeColor = System.Drawing.Color.Navy;
main.labelVatAmount.Text = 0.00m.ToString();
main.Dispose();
//INQUIRE DISCOUNT TYPES
var Discount = GC.CSHR_DiscountTypes.Where(Filter => Filter.DiscountCode == (short)lbDiscountTypes.SelectedValue);
decimal DP = 0.00m;
foreach (var item in Discount)
{
DP = item.DiscountPercentage;
}
foreach (var item in GC.CSHR_SORepo
.Where(Filter => Filter.Machine == MACHINE
&& Filter.SalesOrderNum == SALESORDERNUM
&& Filter.First_SRP == Filter.IMFSRP))
{
item.DiscountAmount = (item.SoldSRP * DP) / 100;
item.TotalAmount = (item.Quantity * item.SoldSRP) - item.DiscountAmount;
item.VATableSalesOnTotalAmount = (item.Quantity * item.SoldSRP) - item.DiscountAmount;
item.VATRate = 0.00m;
GC.SaveChanges();
}
Close();
}
The code below //INQUIRE DISCOUNT TYPES works well but not the one on top.
I've used debug mode to check if the lines are not being skipped over and they aren't.
You should pay attention to:
You are creating a new instance of your main form that you don't need (while it is open behind the dialog), so you need to get it not create a new instance
You are disposing the main form you created. main.Dispose();
In fact you are creating a new instance of main form and assigning values to those controls and then dispose it. While and instance of yor main form that you expect to see changes on it, is open and untouched behind your dialog.
To set value of those controls you can do one of these ways:
Option 1
Make your labelStatus and btnNonVat public. Open your main form in designer and select labelStatus and btnNonVat and in property grid, set Modifier to public. Then write this code:
//var main = Application.OpenForms.OfType<frm_Main>().FirstOrDefault();
var main = (frm_Main)Application.OpenForms["frm_Main"];
main.labelStatus.Text = "NON-VAT (SENIOR)";
main.labelStatus.BackColor = System.Drawing.Color.IndianRed;
main.labelStatus.ForeColor = System.Drawing.Color.WhiteSmoke;
main.btnNonVat.Enabled = false;
main.btnNonVat.BackColor = System.Drawing.Color.SlateGray;
main.btnNonVat.ForeColor = System.Drawing.Color.Navy;
main.labelVatAmount.Text = 0.00m.ToString();
Option 2
Pass an instance of your frm_Main to your dialog and work with it.
Option 3
After closing the dialog, use values from dialog and set values of your main form
Looks like you are trying to create new form using frm_Main main = new frm_Main(); syntax. All you need to do is get the instance of your current form.
var _currentMainForm= Application.OpenForms[0];
or if you have given name to your form
var _currentMainForm = Application.OpenForms["MainFormName"];
Once you get the reference you can perform all your label updates.
The code on top creates a new form, changes the labels and then disposes the form.
I think you should change the labels of the existing form.
Like in the other answer said you are setting properties of controls into a new Form object and not in the form where you come from.
You should pass the form object into the parameters of the dialog, something like:
void myDialog(frm_Main callingForm)
{
callingForm.Textbox1.Text = "abc";
}
And call it from you main form like this
...
myDialog(this);

Iterate for loop after user input

for (int i = 0; i < service.journeys.Count; i++)
{
var popup = new JourneyPopup();
// Fill out the form
popup.txtJourney.Text = service.journeys[i].journeyCode;
popup.txtDays.Text = service.journeys[i].daysOfWeek;
popup.txtDeparture.Text = service.journeys[i].departureTime;
popup.txtOrigin.Text = service.journeys[i].description;
popup.Show();
}
Inside my JourneyPopup form I have a button called 'done'. I need to iterate the for loop only after 'done' has been clicked. How can I do this?
You might try the .ShowDialog() function. It will not return until the dialog/form has closed.
I assume that it's a WinForm application and JourneyPopup is derived from Form.
Then, in the Forms designer, you can give the button a custom int value, that will be returned by the Form.Show() methods when the button was pressed.
At the end of your loop, you then can check this:
if (popup.ShowDialog() != <Returnvalue from button>)
{
break;
}

Docking mdi controls in c#

I have a main form in a panel on the left thats clickable, depending on what you click a new type of form opens. on the righti have another panel where i want to dock the forms that have been opened from clicking on the left.
How can i get the forms to add in a list under one another in the panel on the right? the issue with the code below is that it adds the first element fine. However when i add the second element they both dissapear behind the panel :/
private void addToPanel2(Form o)
{
if (o is Form)
{
if (panel2.Controls.Count == 0)
{
o.MdiParent = this;
panel2.Controls.Add(o);
o.Dock = DockStyle.Top;
o.Show();
}
else
{
//then we know that this is an addable data item
foreach (Form obj in panel2.Controls)
{
if(obj.GetType().Name.Equals(o.GetType().Name))
{
//we dont want to add it as the data type is already open
MessageBox.Show("This data item must already be open. Please Check.");
}
else
{
// add it as its not in there
Form f = (Form)obj;
f.MdiParent = this;
f.Dock = DockStyle.Top;
f.Show();
}
}
}
}
thanks
This is not possible, an MDI child form cannot be a child control of a panel. Adding a non-MDI form to a panel is an iffy proposition as well but is supported. Call its SetTopLevel() method, passing false, set its Visible property to true. You also have to set its FormBorderStyle property to None, it no longer behaves properly as a top-level window.
This just turns it into a UserControl. You are better off actually making it a UserControl, that uses a lot less resources and is much better documented.

Categories

Resources