Close Form 2 from Form 1 C# - c#

I'm trying to build an application with a form window that needs to open and close another form by pressing a button. I want the same button to be used to open and close the same window.
private void button1_Click(object sender, EventArgs e)
{
//GameBoard gameBoard = new GameBoard(); is written outside the private void as global variable.
if (gameBoard == open)
{
gameBoard Close();
}
else
{
gameBoard.Show();
}
}
Thanks for any help.

Start off with your form reference set to null.
Then you can do something like:
private GameBoard gameBoard = null;
private void button1_Click(object sender, EventArgs e)
{
if (gameBoard == null || gameBoard.IsDisposed)
{
gameBoard = new GameBoard();
gameBoard.Show();
}
else
{
gameBoard.Close();
gameBoard = null;
}
}

Related

How to allocate two different functions to the same button?

I am working on Winforms with C#.
I have a problem with the logic, there are two different methods that I need to call, so that if I click the button, the first action should get applied and if I click the same button again, the second action should get applied.
This is not the exact code but I have an idea something like this:
private void button1_Click(object sender, EventArgs e)
{
if(button1.click==true)
{
fileNumber = 1;
ImgSave();
}
else
{
ImgSave.exit();
}
}
Here I have two problems regarding whether the button is already clicked:
If it's not clicked the Imgsave() should get activated.
If button is clicked the Imgsave() should get closed.
Can anyone please help me with this? Thanks.
You need to keep state somewhere. You can do this:
private bool buttonClicked = false;
private void button1_Click(object sender, EventArgs e)
{
if(!buttonClicked)
{
buttonClicked = true;
fileNumber = 1;
ImgSave();
}
else
{
ImgSave.exit();
}
}
This assumes you never going to click it a third time. If you are, you would need to handle that in some way.
I'd have either a class level variable track the number of times a button is clicked:
private bool _unclicked = false;
private void button1_Click(object sender, EventArgs e)
{
if(!_unclicked)
{
_unclicked = true; //toggle so next time the ELSE will be performed
fileNumber = 1;
ImgSave();
}
else
{
_unclicked = false; //toggle it off again
ImgSave.exit();
}
}
, or I'd store it in the .Tag of the button:
private void button1_Click(object sender, EventArgs e)
{
if(!button1.Tag.ToString() == "unclicked")
{
button1.Tag = "clicked"; //toggle so next time the ELSE will be performed
fileNumber = 1;
ImgSave();
}
else
{
button1.Tag = "unclicked"; //toggle it off again
ImgSave.exit();
}
}
You could also remove one event handler and add another:
private void button1_FirstClick(object sender, EventArgs e)
{
button1.Clicked -= button1_FirstClick;
button1.Clicked += button1_SecondClick;
fileNumber = 1;
ImgSave();
}
private void button1_SecondClick(object sender, EventArgs e)
{
button1.Clicked -= button1_SecondClick;
button1.Clicked += button1_FirstClick;
ImgSave.exit();
}
I've always been less of a fan of adding and removing event handlers to achieve things like this but it's quite a clean solution
You should save your state in a variable. Your state will change after first click and you can change the state of Clicking button with calling ConditionChanger() method anytime.
For example you may need change the state of variable when you clicked a second button.
private void ConditionChanger(){
myState = !myState;
}
Your variable :
private bool myState = false;
And your click event :
private void button1_Click(object sender, EventArgs e)
{
if(!myState)
{
myState = true;
fileNumber = 1;
ImgSave();
}
else
{
ImgSave.exit();
}
}

(C#)How do I, upon pressing a button, Make a new form window appear? One that i can drag other buttons and text boxes onto

I'm new to C# and I need this function for a program im working on for school. I need to make a new window pop up when i click a button, not a message box though like a forms window, one that i can design with text boxes and buttons. What is on the new pop up window depends on the previous window but i can figure that out.
Also I need a way to close the previous window once the new one appears
Here's my code:`
// This makes sure only one box is checked
private void MulCB_CheckedChanged(object sender, EventArgs e)
{
if( MulCB.Checked == true)
{
DivCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void DivCB_CheckedChanged(object sender, EventArgs e)
{
if (DivCB.Checked == true)
{
MulCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void AddCB_CheckedChanged(object sender, EventArgs e)
{
if (AddCB.Checked == true)
{
DivCB.Checked = false;
SubCB.Checked = false;
MulCB.Checked = false;
}
}
private void SubCB_CheckedChanged(object sender, EventArgs e)
{
if (SubCB.Checked == true)
{
DivCB.Checked = false;
AddCB.Checked = false;
MulCB.Checked = false;
}
}
private void oneDCB_CheckedChanged(object sender, EventArgs e)
{
if(oneDCB.Checked == true)
{
twoDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void twoDCB_CheckedChanged(object sender, EventArgs e)
{
if ( twoDCB.Checked == true)
{
oneDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void threeDCB_CheckedChanged(object sender, EventArgs e)
{
if (threeDCB.Checked == true)
{
oneDCB.Checked = false;
twoDCB.Checked = false;
}
}
// ends here
// Button operation
private void button8_Click(object sender, EventArgs e)
{
var form = new Form();
}
}
}
`
Thanks a lot!
Sal
The project is im supposed to make a quizzing program for kids. They should be able to choose 1 operation and the amount of digits the numbers will have. It then has to out put 10 random questions according to the selection made by the kid, then once they have completed the quiz, it should display their results and which questions they got wrong.
Assuming that the design of the window doesn't have to be completely dynamic, you can design it in Visual Studio (I'm assuming you did so with the first one). Then you can pass the results to the window. Like:
// Note: Form2 ist the name of your designed From
Form2 myform = new Form2();
this.Hide();
//You could pass the question settings like this
// 1 is for multiplication, 2 for division,3 for addition, 4 for substraction
myform.operation=1;
myform.digits=2
myform.Show();
And in the code of Form2:
namespace Yournamespace {
public partial class Form2: Form {
//Add these two lines about here
public static int operation;
public static int digits;
public Form2() {
InitializeComponent();
}
}
}
Then you can use the variables in Form2 and fill in the textbox or other elements you might design.
Also: You cloud use radio buttons instead of checkboxes as you then won't have you worry about unchecking the other checkboxes.

GMap.NET and polygon names not getting passed from second form

So basically im trying to make polygons with a name entered from Form2, called Apgabala_nosaukums (it's in my language, sorry for that). I have been trying to debug this, first 2 times the name entered from Form2 did get read and i was able to see that the name was added to the Polygon. But now it is not getting in the fromVisibleChanged anymore, ending in that the polygon is not getting name. Meaning that I cannot get the bool to true, so I could add 4 points and make a square or rectangle area out of them. Any ideas? Basically the btnAdd_Click function is not working properly, rest is working fine. Any ideas?
Form1 (Main form):
namespace GMapTest
{
public partial class Form1 : Form
{
GMapOverlay polygons = new GMapOverlay("polygons");
List<PointLatLng> points = new List<PointLatLng>();
double lat;
double lng;
int clicks = 0;
bool add = false;
string nosaukums;
public Form1()
{
InitializeComponent();
}
private void gMapControl1_Load(object sender, EventArgs e)
{
gmap.MapProvider = GoogleMapProvider.Instance;
GMaps.Instance.Mode = AccessMode.ServerOnly;
gmap.SetPositionByKeywords("Riga, Latvia");
gmap.ShowCenter = false;
gmap.Overlays.Add(polygons);
}
private void gmap_MouseDown(object sender, MouseEventArgs e)
{
if (add == true)
{
if (e.Button == MouseButtons.Left)
{
lat = gmap.FromLocalToLatLng(e.X, e.Y).Lat;
lng = gmap.FromLocalToLatLng(e.X, e.Y).Lng;
clicks += 1;
points.Add(new PointLatLng(lat, lng));
}
if (clicks == 4)
{
GMapPolygon polygon = new GMapPolygon(points, nosaukums);
polygons.Polygons.Add(polygon);
clicks = 0;
points.Clear();
add = false;
}
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
Apgabala_nosaukums addName = new Apgabala_nosaukums();
addName.ShowDialog();
addName.VisibleChanged += formVisibleChanged;
if (nosaukums != null)
{
this.add = true;
}
}
private void formVisibleChanged(object sender, EventArgs e)
{
Apgabala_nosaukums frm = (Apgabala_nosaukums)sender;
if (!frm.Visible)
{
this.nosaukums = (frm.ReturnText);
frm.Dispose();
}
}
}
}
Form2 (Apgabala_nosaukums):
namespace GMapTest
{
public partial class Apgabala_nosaukums : Form
{
public string ReturnText { get; set; }
public Apgabala_nosaukums()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.ReturnText = this.txtName.Text;
this.Visible = false;
}
}
}
The problem is in your btnAdd_Click function. When you call ShowDialog your other form is shown and the next line, addName.VisibleChanged += formVisibleChanged; isn't called until you close the new form. ShowDialog shows the form modally, you can't interact with the parent until you close the new form.
There are a couple ways you could fix this.
1) Subscribe to the VisibleChanged event before you show the form,
addName.VisibleChanged += formVisibleChanged;
addName.ShowDialog();
2) Call addName.Show() instead of addName.ShowDialog(). This shows the form in a non-modal way. The event will get subscribed to because execution continues in btnAdd_Click before the new form is closed. But, the parent form will be interactable, not sure if this is desired or not.
3) You could also get rid of the VisibleChanged event stuff and instead do ShowDialog and read the property after. This is what I'd recommend from seeing the code.
private void btnAdd_Click(object sender, EventArgs e)
{
Apgabala_nosaukums addName = new Apgabala_nosaukums();
addName.ShowDialog();
this.nosaukums = addName.ReturnText;
addName.Dispose();
}

C# how to get mouse position after INSERT key if pressed, after button click?

I need to know how to get mouse position when I press a key (insert).
This is what I trying to do:
I have a form1 with one buuton, when you press that button it call another form. But before call the form2 i need to get mouse position from an external application. To do this, the user must hover the cursor over requested position and press 'INSERT'.
public partial class _CalibrateGeneralStep2 : Form
{
public _CalibrateGeneralStep2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
///// HERE I NEED TO WAIT UNTIL USER PRESS 'INSERT' KEY BEFORE CALL _CalibrateGeneralStep3 /////
_CalibrateGeneralStep3 frm = new _CalibrateGeneralStep3();
frm.Show();
}
}
I try with keypress and keydown but I dont know use it well.
Thanks... sorry if my english is not good...
You can use
System.Windows.Forms.Cursor.Position: "It represents the current cursor position in screen co-ordinates"
Note: Please refer to the example to see how it works
You can use the KeyDown Event of the form (You can add it from the Designer to be sure it's wired properly)
Since you cannot just wait for the key press event inside your button2_Click, I've used a private field to store the fact that the button have been pressed. Now each time the user press Insert, you check if the button have been pressed and the cursor position. If both are correct, generate the new form.
I've defined the needed cursor position with the 2 constants at the top of the class, and you should also choose a better name for "hasButton2BeenClicked", depending of your business context haha.
public partial class _CalibrateGeneralStep2 : Form
{
private const int NEEDED_X_POSITION = 0;
private const int NEEDED_Y_POSITION = 0;
private bool hasButton2BeenClicked = false;
public _CalibrateGeneralStep2()
{
InitializeComponent();
KeyPreview = true;
}
private void button1_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void button2_Click(object sender, EventArgs e)
{
hasButton2BeenClicked = true;
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert && IsCursorAtTheCorrectPosition() && hasButton2BeenClicked)
{
GoToNextStep();
}
}
private bool IsCursorAtTheCorrectPosition()
{
return Cursor.Position.X == NEEDED_X_POSITION && Cursor.Position.Y == NEEDED_Y_POSITION;
}
private void GoToNextStep()
{
this.Hide();
new _CalibrateGeneralStep3().Show();
}
}

Making more than an event on a button

Please, I want to know how to make two events on one button like: when I first click on the button display an image and while still in debugging mode the second time I click
display another image. What are some ways to do this?
You can make something like:
protected void Button1Click(object sender, EventArgs e)
{
if (Img1.Visible == false)
{
Img1.Visible = true;
}
else
{
Img2.Visible = true;
}
}
I don't think you need two (or more) events to do what you want, you only need to trace how many times you clicked the button, for example using an instance variable.
private int clicks = 0;
protected void myButton_Click(object sender, EventArgs e)
{
if(clicks == 1)
{
// do something
}
if(clicks == 2)
{
// do other things
}
if(clicks > 2)
{
// something else
}
clicks++;
}
What about something like this: just make sure to declare the counter outside the button
int clickedCount = 0;
private void button1_Click(object sender, EventArgs e)
{
clickedCount++;
if (clickedCount % 2 == 0) { pictureBox1.ImageLocation = #"path"; } else { pictureBox1.ImageLocation = #"path"; }
}

Categories

Resources