I am trying to pass a string from Form2.cs to Form1.cs and then display it in a message box. For some reason, the variable in the string is not showing but the rest of the text is.
Form1.cs
Form2 otherForm = new Form2();
public void getOtherTextBox()
{
otherForm.TextBox1.Text = player1;
}
private void labelClick(object sender, EventArgs e)
{
Label clickedLabel = (Label)sender;
if (clickedLabel.BackColor != Color.Transparent)
{
return;
}
clickedLabel.BackColor = isBlackTurn ? Color.Black : Color.White;
isBlackTurn = !isBlackTurn;
Color? winner = WinCheck.CheckWinner(board);
if (winner == Color.Black)
{
MessageBox.Show( player1 + " is the winner!");
}
else if (winner == Color.White)
{
MessageBox.Show("White is the winner!");
}
else
{
return;
}
Form2.cs
public TextBox TextBox1
{
get
{
return textBox1;
}
}
this might work .. u need to call the function somewhere to make it work.
I fixed it by calling it in the label click;
so u need to click the label to update the value in the other form.
u can add this function to events like a timer event which ensures that it's always updated within a perfect time.
public void getOtherTextBox()
{
otherForm.TextBox1.Text = player1;
}
private void labelClick(object sender, EventArgs e)
{
Label clickedLabel = (Label)sender;
getOtherTextBox();
if (clickedLabel.BackColor != Color.Transparent)
{
return;
}
clickedLabel.BackColor = isBlackTurn ? Color.Black : Color.White;
isBlackTurn = !isBlackTurn;
Color? winner = WinCheck.CheckWinner(board);
if (winner == Color.Black)
{
MessageBox.Show( player1 + " is the winner!");
}
else if (winner == Color.White)
{
MessageBox.Show("White is the winner!");
}
else
{
return;
}
}
You can create a property in Form1 to hold the player name, and then in Form2, when the input of player name changed, you will update the property of Form1. See the code:
public class Form1()
{
//Code
private string PlayerName { get; set; }
private void labelClick(object sender, EventArgs e)
{
Label clickedLabel = (Label)sender;
if (clickedLabel.BackColor != Color.Transparent)
return;
clickedLabel.BackColor = isBlackTurn ? Color.Black : Color.White;
isBlackTurn = !isBlackTurn;
Color? winner = WinCheck.CheckWinner(board);
if (winner == Color.Black)
MessageBox.Show(this._playerName + " is the winner!");
else if (winner == Color.White)
MessageBox.Show("White is the winner!");
}
//More code
}
public class Form2()
{
private Form1 _frm;
public Form2()
{
this._frm = new Form1();
}
public void ShowFormWinner()
{
_frm.PlayerName = textBox1.Text;
_frm.Show();
}
public void OnPlayerNameChanged(object sender, EventArgs e)
{
_frm.PlayerName = textBox1.Text;
_frm.Show();
}
}
Related
I use dragging control by mouse
Problem is if Control.Enabled = false. Dragging can't work? Is there any method to overload to prevent this behavior?
static void control_MouseEnter(object sender, EventArgs e)
{
(sender as Control).Enabled = false;
(sender as Control).Cursor = Cursors.SizeAll;
}
static void control_MouseLeave(object sender, EventArgs e)
{
(sender as Control).Enabled = true;
// (sender as Control).Cursor = Cursors.Default;
}
static void control_MouseDown(object sender, MouseEventArgs e)
{
mouseLocation = e.Location;
// turning on dragging
draggables[(Control)sender] = true;
}
static void control_MouseUp(object sender, MouseEventArgs e)
{
// turning off dragging
draggables[(Control)sender] = false;
}
static void control_MouseMove(object sender, MouseEventArgs e)
{
// only if dragging is turned on
if (draggables[(Control)sender] == true)
{
var control = (sender as Control);
control.Left = e.X + control.Left - mouseLocation.X;
control.Top = e.Y + control.Top - mouseLocation.Y;
}
}
You could use IMessageFilter to trap WM_MOUSEMOVE.
Here I'm changing the caption of the form when the mouse is moved within pictureBox1. It also tells you whether the left mouse button is down:
public partial class Form1 : Form
{
private MyFilter mf;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Enabled = false;
mf = new MyFilter();
mf.PreFilterMouseMove += Mf_PreFilterMouseMove;
Application.AddMessageFilter(mf);
}
private void Mf_PreFilterMouseMove()
{
Point pt = pictureBox1.PointToClient(Cursor.Position);
if (pictureBox1.ClientRectangle.Contains(pt))
{
bool leftDown = (Control.MouseButtons == MouseButtons.Left);
this.Text = "leftDown = " + leftDown + " : position = " + pt.ToString();
}
else
{
this.Text = "...not within pictureBox1...";
}
}
}
public class MyFilter : IMessageFilter
{
private const int WM_MOUSEMOVE = 0x200;
public delegate void dlgMouseMove();
public event dlgMouseMove PreFilterMouseMove;
public bool PreFilterMessage(ref Message m)
{
switch (m.Msg)
{
case WM_MOUSEMOVE:
if (PreFilterMouseMove != null)
{
PreFilterMouseMove();
}
break;
}
return false;
}
}
I appear to have all of the things necessary for Drag-n-Drop to be working, yet my code is not called when I attempt to drag something from one control to another.
I created a Test Class to use to create data:
class TestClass
{
public TestClass()
{
Name = "Blank";
Id = -1;
}
public String Name { get; set; }
public int Id { get; set; }
public object Data { get; set; }
public override String ToString()
{
return String.Format("{0}: {1}", Id, Name);
}
}
I created an empty form with 2 List View controls, listView1 and listView2:
I created event handlers for all of the Drag-n-Drop methods and put breakpoints on them:
private void Form_DragDrop(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
if (e.Data.GetDataPresent(typeof(TestClass)))
{
var item = e.Data.GetData(typeof(TestClass)) as TestClass;
if (item != null)
{
// ?
}
}
}
private void Form_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
if (sender.Equals(listView2))
{
e.Effect = DragDropEffects.All;
if (e.Data != null)
{
var format = GetString(e);
Console.WriteLine("{0} has a(n) {1} entering it.", listView2.Name, format);
}
}
}
private void Form_DragLeave(object sender, EventArgs e)
{
if (sender.Equals(listView2))
{
}
}
private void Form_DragOver(object sender, DragEventArgs e)
{
// Code Project Article 9017 says DragOver fires repeatedly, even if the mouse does not move.
if ((e.X != _lastX) || (e.Y != _lastY))
{
_lastX = e.X;
_lastY = e.Y;
if (e.Data.GetDataPresent(typeof(TestClass)))
{
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
private void Form_GiveFeedback(Object sender, GiveFeedbackEventArgs e)
{
if (sender.Equals(listView2))
{
// ?
}
}
private void Form_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
{
var listView = sender as ListView;
if (listView != null)
{
}
}
private String GetString(DragEventArgs e)
{
var result = String.Empty;
if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
{
var formats = e.Data.GetFormats();
foreach (var format in formats)
{
Console.WriteLine("Data is in the format of [{0}].", format);
result = format;
}
}
return result;
}
I wired both controls up after the constructor's InitializeComponent();:
public ListViewsForm()
{
InitializeComponent();
// Setup ListView 1:
listView1.AllowDrop = true;
listView1.DragDrop += Form_DragDrop;
listView1.DragEnter += Form_DragEnter;
listView1.DragLeave += Form_DragLeave;
listView1.DragOver += Form_DragOver;
listView1.GiveFeedback += Form_GiveFeedback;
listView1.QueryContinueDrag += Form_QueryContinueDrag;
listView1.Dock = DockStyle.Fill;
listView1.View = View.List;
// Setup ListView 2:
listView2.AllowDrop = true;
listView2.DragDrop += Form_DragDrop;
listView2.DragEnter += Form_DragEnter;
listView2.DragLeave += Form_DragLeave;
listView2.DragOver += Form_DragOver;
listView2.GiveFeedback += Form_GiveFeedback;
listView2.QueryContinueDrag += Form_QueryContinueDrag;
listView2.Dock = DockStyle.Fill;
// Create some data:
var group1 = new ListViewGroup("Known Colors");
foreach (KnownColor known in Enum.GetValues(typeof(KnownColor)))
{
var item = new TestClass()
{
Name = known.ToString(),
Id = (int)known,
Data = known,
};
var color = Color.FromKnownColor(known);
var lvi = new ListViewItem(item.ToString(), group1) {
BackColor = Color.FromArgb(color.ToArgb() ^ 0xffffff),
ForeColor = color,
Tag = item,
};
listView1.Items.Add(lvi);
}
}
Whenever I run the project, everything loads up fine, but any attempt to drag an item from the LEFT side to the RIGHT side does nothing. None of my break points are hit. Nothing happens.
What have I left out?
You are missing a handy event and the method that starts the dragging operation:
listView1.ItemDrag += listView1_ItemDrag;
void listView1_ItemDrag(object sender, ItemDragEventArgs e) {
DoDragDrop(e.Item, DragDropEffects.Copy);
}
My problem is that memory is increased 5MB flicker form each time a call per second .
I made window flicker effect window form
[flicker form]
public partial class WarningBoxControls : Form
{
bool _isShadow;
public WarningBoxControls(WarningBoxType _Type)
{
InitializeComponent();
this.FormClosing += WarningBox_FormClosing;
this.VisibleChanged +=WarningBoxControls_VisibleChanged;
if (_Type == WarningBoxType.WarningBox_Speed)
{
MessageTitle.Text = "속력 경고";
MessageContent.Text = "자동차 속도를 줄여주세요!";
this.BackColor = Color.SkyBlue;
pictureBox1.Image = Properties.Resources.warning_speed;
}
else
{
MessageTitle.Text = "Logger 오류";
MessageContent.Text = "Logger가 활성화되지 않았습니다!";
this.BackColor = Color.MediumVioletRed;
pictureBox1.Image = Properties.Resources.warning_error;
}
}
private void WarningBoxControls_VisibleChanged(object sender, EventArgs e)
{
this.Opacity = 0.01;
if(this.Visible == true)
{
timer1.Start();
}
else
{
timer1.Stop();
}
}
private void WarningBox_FormClosing(object sender, FormClosingEventArgs e)
{
if (pictureBox1.Image != null)
{
pictureBox1.Image = null;
pictureBox1.Dispose();
}
if (timer1.Enabled == true)
{
timer1.Stop();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (_isShadow == false)
{
if (this.Opacity <= 1.0)
{
this.Opacity += 0.8;
if (this.Opacity >= 1.0)
{
_isShadow = true;
}
}
}
else
{
if (this.Opacity >= 0.01)
{
this.Opacity -= 0.08;
if (this.Opacity <= 0.01)
{
_isShadow = false;
}
}
}
}
}
And I created the class to load flicker effect form.
[load ficker form]
public class WarningBox
{
WarningBoxControls _control;
Form owner;
public WarningBox(IWin32Window _owner, WarningBoxType _Type)
{
if (_owner != null)
{
owner = (Form)_owner;
_control = new WarningBoxControls(_Type);
_control.StartPosition = FormStartPosition.Manual;
_control.Padding = new Padding(0, 0, 0, 0);
_control.ControlBox = false;
_control.ShowInTaskbar = false;
_control.Size = new Size(owner.Size.Width - 40, _control.Height - 20);
}
}
public void Show()
{
_control.Location = new Point(owner.Location.X + 20, owner.Location.Y + ((owner.Height - _control.Height) / 2));
//_control.ShowDialog();
//_control.BringToFront();
if(_control.Visible != true)
{
_control.Show();
_control.BringToFront();
}
}
public void Hide()
{
if(_control.Visible != false)
{
//_control.Visible = false;
_control.Hide();
}
}
~WarningBox()
{
if(_control != null)
{
_control.Dispose();
_control = null;
}
}
}
[Call a second method]
private void timer1_Tick(object sender, EventArgs e)
{
if (NetworkInterface.GetIsNetworkAvailable())
{
ReadLoggerStatus();
}
private void ReadLoggerStatus()
{
if (_Lights != null)
{
if (_Lights.ERR == 0) // 에러 없을때
{
pb_error.Image = Properties.Resources.none;
_WarningBox.Hide();
btn_stop.Enabled = true;
btn_start.Enabled = false;
}
else
{
pb_error.Image = Properties.Resources.error;
_WarningBox.Show();
btn_stop.Enabled = false;
btn_start.Enabled = true;
}
}
}
And Check the one error per second , call the Show() and Hide() of WarningBox. however here(ReadLoggerStatus()) is some of a problem.
my problem is that the memory each time it is called once per second increased by 5MB.
I want to know it is solve the best way.
please let me know excellent answer.
In advance, I would greetings of thanks.
Have a good day!
First, sorry for my English, it's not my first language.
I'm on the first grade of high school, and at my college we have a certificate program of three years in system analysis and development, along with the normal classes.
We are just starting learning c# at the course, but since we have some free time at the lab we started "playing" with winforms. I prefer to look at the code or google the error instead of asking, but this time i really can't figure what's wrong.
When i was using only one form, to get the input and show all users' information in real time (without a combobox, just labels), it all worked fine. What I want to do is, take input of five users, and , if the fields are filled correctly, add the first name of the user as an item to the combobox, and he can see the name/sex/age of previous users browsing the combobox items.
The Form1's code:
public partial class Form1 : Form
{
Form2 frm2 = new Form2();
public Form1()
{
InitializeComponent();
}
private void label9_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
variaveis.i++;
variaveis.nome[variaveis.i] = textBox1.Text;
variaveis.sobrenome[variaveis.i] = textBox2.Text;
variaveis.sexo[variaveis.i] = comboBox1.Text;
if (textBox3.Text != null)
variaveis.idade[variaveis.i] = textBox3.Text;
double num;
bool isnum = double.TryParse(variaveis.idade[variaveis.i], out num);
Form2 frm2 = new Form2();
frm2.Update();
if (variaveis.nome[variaveis.i]!=null && variaveis.sobrenome!=null && variaveis.idade[variaveis.i] != null && isnum)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
frm2.comboBox1.Items.Add(variaveis.nome[variaveis.i]); //Only works with the first input
if (variaveis.i == 1)
{
frm2.Show();
frm2.Location = new Point(this.Left + this.Width, this.Top);
frm2.Height = this.Height;
frm2.label6.Text = variaveis.nome[variaveis.i];
frm2.label7.Text = variaveis.sobrenome[variaveis.i];
frm2.label8.Text = variaveis.sexo[variaveis.i];
frm2.label9.Text = variaveis.idade[variaveis.i];
}
}
else
{
variaveis.i--;
MessageBox.Show("Preencha todos os campos",
"Erro");
}
if (variaveis.i >= 5)
{
button1.Enabled = false;
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
}
}
The Form2's code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label6.Text = variaveis.nome[comboBox1.SelectedIndex + 1]; // i don't even know if i can use an array like this
label7.Text = variaveis.sobrenome[comboBox1.SelectedIndex + 1];
label8.Text =variaveis.sexo[comboBox1.SelectedIndex + 1];
label9.Text = variaveis.idade[comboBox1.SelectedIndex + 1];
}
The variables class (I thought would be easier to work this way if I'm using multiple forms, if I'm wrong, correct me):
class variaveis
{
public static string[] nome = new string[5]; //name
public static string[] sobrenome = new string[5]; //last name
public static string[] sexo = new string[5]; //gender
public static string[] idade = new string[5]; //age(string, checked with tryparse)
public static int i = 0;
}
Sorry if it's a noob question or if the error is obvious, but I started working with WinForms a couple weeks ago.
EDIT:
So the problems now are:
-Sometimes the program throw me the error even when all conditions are apparently fulfilled.
-Can't add items to a combobox in another form. Tried this:
public void AddItem(object item)
{
comboBox1.Items.Add(variaveis.nome[variaveis.i]);
}
Calling it in Form1:
frm2.AddItem(variaveis.nome[variaveis.i]);
The syntax seems correct, but nothing happens.
If you set it up like this, i think it is easier to address your data.
public class Person
{
public string Nome {get; set;}
public string Sobrenome {get; set;}
public string Sexo {get; set;}
public string Idade {get; set;}
}
public class Variaveis
{
public Person[] People {get; set;}
public Variaveis
{
People = new Person[5];
}
}
Now you can access the data like so:
var myName = Variaveis.People[2].Nome;
I edited some things and solved the "if" problem . The new code:
public partial class Form1 : Form
{
public string[] nome = new string[5];
public string[] sobrenome = new string[5];
public string[] sexo = new string[5];
public string[] idade = new string[5];
public int i = 1;
public Form1()
{
InitializeComponent();
}
private void label9_Click(object sender, EventArgs e)
{
}
public void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(this);
nome[i] = textBox1.Text;
sobrenome[i] = textBox2.Text;
sexo[i] = comboBox1.Text;
idade[i] = textBox3.Text;
double num;
bool isnum = double.TryParse(idade[i], out num);
if (textBox1.Text !=null && textBox2.Text!=null && textBox3 != null && isnum == true)
{
frm2.comboBox1.Items.Add(textBox1.Text);
frm2.comboBox1.Update();
comboBox1.Update();
textBox4.Text = Convert.ToString(i); // just to check the variable's value, since they dont appear in the debugger tool
if (i == 1)
{
frm2.Show();
frm2.Location = new Point(this.Left + this.Width, this.Top);
frm2.Height = this.Height;
}
frm2.label6.Text = nome[i];
frm2.label7.Text = sobrenome[i];
frm2.label8.Text = sexo[i];
frm2.label9.Text = idade[i];
frm2.comboBox1.SelectedIndex = frm2.comboBox1.SelectedIndex + 1;
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
++i;
}
if(isnum == false && textBox1.Text == null && textBox2.Text == null && textBox3 == null)
{
MessageBox.Show("Preencha todos os campos", "Erro");
}
if (i >= 5)
{
button1.Enabled = false;
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
}
private void Form1_Load(object sender, EventArgs e)
{
}
I've noticed that all controls(not just combobox1) only respond to the first command coming from another form. If i put a textbox in form2 and call:
frm2.textBox1.Text = i;
it's going to show "1" forever. How do i solve this?
Solved the problem by myself, by adding this:
public partial class Form2 : Form
{
Form1 f1;
public Form2(Form1 f1)
{
InitializeComponent();
this.f1 = f1;
This:
public partial class Form1 : Form
{
private Form2 frm2;
and this:
public Form1()
{
InitializeComponent();
frm2 = new Form2(this);
}
The complete code with some improvements:
Form1:
public partial class Form1 : Form
{
private Form2 frm2;
public string[] nome = new string[6];
public string[] sobrenome = new string[6];
public string[] sexo = new string[6];
public string[] idade = new string[6];
public int i = 0;
public Form1()
{
InitializeComponent();
frm2 = new Form2(this);
}
public void button1_Click(object sender, EventArgs e)
{
++i;
nome[i] = textBox1.Text;
sobrenome[i] = textBox2.Text;
sexo[i] = comboBox1.Text;
idade[i] = textBox3.Text;
double num;
bool isnum = double.TryParse(idade[i], out num);
if (textBox1.Text !=null && textBox2.Text!=null && textBox3 != null && isnum == true)
{
frm2.comboBox1.Items.Add(textBox1.Text);
frm2.comboBox1.Update();
comboBox1.Update();
if (i == 1)
{
frm2.Show();
frm2.Location = new Point(this.Left + this.Width, this.Top);
frm2.Height = this.Height;
}
frm2.label6.Text = nome[i] + " " + sobrenome[i];
frm2.label8.Text = sexo[i];
frm2.label9.Text = idade[i];
frm2.comboBox1.SelectedIndex = frm2.comboBox1.SelectedIndex + 1;
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}
if(isnum == false && textBox1.Text == null && textBox2.Text == null && textBox3 == null)
{
MessageBox.Show("Preencha todos os campos", "Erro");
--i;
}
if (i >= 5)
{
button1.Enabled = false;
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.Refresh();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
Form2:
public partial class Form2 : Form
{
Form1 f1;
public Form2(Form1 f1)
{
InitializeComponent();
this.f1 = f1;
comboBox1.Items.Add("Usuários");
}
private void Form2_Load(object sender, EventArgs e)
{
}
public void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != 0)
{
label6.Text = f1.nome[comboBox1.SelectedIndex] + " " + f1.sobrenome[comboBox1.SelectedIndex];
label8.Text = f1.sexo[comboBox1.SelectedIndex];
label9.Text = f1.idade[comboBox1.SelectedIndex];
}
else
{
label6.Text = " ";
label8.Text = " ";
label9.Text = " ";
}
}
}
Thanks for the help anyway.
I'm new to c# and I tried making a simple program. After I click the button, the values won't update with their actual value, so I have to click twice to make them actually work. Here's my code:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private static int p;
private static int money;
public Form1()
{
InitializeComponent();
p = 0;
money = 100;
}
private void button1_Click(object sender, EventArgs e)
{
m.Text = money.ToString();
ex.Text = p.ToString();
if (checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("You cannot select both.", "Nope");
}
else if (checkBox1.Checked)
{
p += 2;
}
else if (checkBox2.Checked)
{
money -= 50;
p += 10;
}
else
{
return;
}
}
}
}
You need to update the text after updating the value
if (checkBox1.Checked & checkBox2.Checked)
{
MessageBox.Show("You cannot select both.", "Nope");
}
....
m.Text = money.ToString();
ex.Text = p.ToString();