Accessing getter from another class - c#

Hey I have two classes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BMIcalculator
{
class BmrCalculator
{
BMIcalculator BMICalc = new BMIcalculator();
private int age;
private double BMR;
private Gender Gender;
private double weight;
private double height;
public void setWeight(double weight)
{
this.weight = weight;
}
public void setHeight(double height)
{
this.height = height;
}
public double GetWeight()
{
return weight;
}
public double GetHeight()
{
return height;
}
public void SetGender(Gender Gender)
{
this.Gender = Gender;
}
public Gender GetGender()
{
return this.Gender;
}
public double CalculateBMR()
{
if (Gender == Gender.Female)
{
BMR = (10 * weight) + (6.25 * height) - (5 * age) - 161;
}
else
{
BMR = (10 * BMICalc.getWeight()) + (6.25 * BMICalc.getHeight()) - (5 * age) + 5;
}
return BMR;
}
public void SetAge(int age)
{
this.age = age;
}
}
}
2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BMIcalculator
{
class BMIcalculator
{
private double height;
private double weight;
private UnitTypes unit;
public BMIcalculator()
{
unit = UnitTypes.Metric;
}
#region Setters and getters
public double getHeight()
{
return height;
}
public void setHeight(double height)
{
if(height >= 0.0)
this.height = height;
}
public double getWeight()
{
return weight;
}
public void setWeight(double weight)
{
if (weight >= 0.0)
this.weight = weight;
}
public UnitTypes getUnit()
{
return unit;
}
public void setUnit(UnitTypes unit)
{
this.unit = unit;
}
#endregion
}
}
Main form:
namespace BMIcalculator
{
public partial class MainForm : Form
{
private string name = string.Empty; // instance variable
BMIcalculator bmiCalc = new BMIcalculator();
BmrCalculator bmrCalc = new BmrCalculator();
public MainForm()
{
InitializeComponent();
InitializeGUI();
}
private void InitializeGUI()
{
rbtnMetric.Checked = true;
lblBmr.Text = String.Empty;
}
private void MainForm_Load(object sender, EventArgs e)
{
CenterToScreen();
}
#region BMICalculator
private void UpdateHeightText()
{
if(rbtnMetric.Checked == true)
{
lblHeight.Text = "Height (Cm)";
lblWeight.Text = "Weight (Kg)";
}
else
{
lblHeight.Text = "Height (Ft)";
lblWeight.Text = "Weight (lbs)";
}
}
private void rbtnMetric_CheckedChanged(object sender, EventArgs e)
{
UpdateHeightText();
}
private void rbtnImperial_CheckedChanged(object sender, EventArgs e)
{
UpdateHeightText();
}
private bool ReadInputBMI()
{
ReadUnit();
bool weightOK = ReadWeight();
bool heightOK = ReadHeight();
return weightOK && heightOK;
}
private void ReadUnit() // this void looks which one is checked
{
if(rbtnMetric.Checked)
{
bmiCalc.setUnit(UnitTypes.Metric);
}
else
{
bmiCalc.setUnit(UnitTypes.Imperial);
}
}
private bool ReadWeight()
{
double weight = 0.0;
bool ok = double.TryParse(txtWeight.Text, out weight);
if (!ok)
{
MessageBox.Show("Invalid weight value , error");
}
bmiCalc.setWeight(weight);
return ok;
}
private bool ReadHeight()
{
double height = 0.0;
bool ok = double.TryParse(txtCmFt.Text, out height);
if (!ok)
{
MessageBox.Show("Invalid height value , error");
}
double inch = 0.0;
// cm -> m ft -> inches
if(bmiCalc.getUnit() == UnitTypes.Metric)
{
height = height / 100; // cm -> m
}
else
{
height = height * 12.0 + inch; // ft -> inch
}
bmiCalc.setHeight(height);
return ok;
}
#endregion
#region BMRCalculator
private void UpdateGenderStatus()
{
if(rbtnFemale.Checked)
{
bmrCalc.SetGender(Gender.Female);
}
else
{
bmrCalc.SetGender(Gender.Male);
}
}
private void rbtnFemale_CheckedChanged(object sender, EventArgs e)
{
UpdateGenderStatus();
}
private void rbtnMale_CheckedChanged(object sender, EventArgs e)
{
UpdateGenderStatus();
}
private void ReadAge()
{
int age;
bool ok = int.TryParse(txtAge.Text , out age);
if(!ok)
{
MessageBox.Show("Error Wrong Age");
}
else
{
bmrCalc.SetAge(age);
}
}
#endregion
private void btnCalculateBMR_Click(object sender, EventArgs e)
{
double weight = double.Parse(txtWeight.Text);
double height = double.Parse(txtCmFt.Text);
bmrCalc.setWeight(weight);
bmrCalc.setHeight(height);
ReadAge();
//bmrCalc.CalculateBMR();
lblBmr.Text = bmrCalc.CalculateBMR().ToString();
}
}
}
designer:
namespace BMIcalculator
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lblHeight = new System.Windows.Forms.Label();
this.txtCmFt = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.rbtnMetric = new System.Windows.Forms.RadioButton();
this.lblWeight = new System.Windows.Forms.Label();
this.txtWeight = new System.Windows.Forms.TextBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.btnCalculateBMR = new System.Windows.Forms.Button();
this.groupBox6 = new System.Windows.Forms.GroupBox();
this.lblBmr = new System.Windows.Forms.Label();
this.txtAge = new System.Windows.Forms.TextBox();
this.lblAge = new System.Windows.Forms.Label();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.rbtnMale = new System.Windows.Forms.RadioButton();
this.rbtnFemale = new System.Windows.Forms.RadioButton();
this.groupBox1.SuspendLayout();
this.groupBox4.SuspendLayout();
this.groupBox6.SuspendLayout();
this.groupBox5.SuspendLayout();
this.SuspendLayout();
//
// lblHeight
//
this.lblHeight.AutoSize = true;
this.lblHeight.Location = new System.Drawing.Point(27, 39);
this.lblHeight.Name = "lblHeight";
this.lblHeight.Size = new System.Drawing.Size(54, 20);
this.lblHeight.TabIndex = 1;
this.lblHeight.Text = "Height";
//
// txtCmFt
//
this.txtCmFt.Location = new System.Drawing.Point(165, 32);
this.txtCmFt.Name = "txtCmFt";
this.txtCmFt.Size = new System.Drawing.Size(51, 27);
this.txtCmFt.TabIndex = 3;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.rbtnMetric);
this.groupBox1.Location = new System.Drawing.Point(319, 23);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(163, 88);
this.groupBox1.TabIndex = 6;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Unit";
//
// rbtnMetric
//
this.rbtnMetric.AutoSize = true;
this.rbtnMetric.Location = new System.Drawing.Point(26, 35);
this.rbtnMetric.Name = "rbtnMetric";
this.rbtnMetric.Size = new System.Drawing.Size(121, 24);
this.rbtnMetric.TabIndex = 0;
this.rbtnMetric.TabStop = true;
this.rbtnMetric.Text = "Metric(kg,cm)";
this.rbtnMetric.UseVisualStyleBackColor = true;
this.rbtnMetric.CheckedChanged += new System.EventHandler(this.rbtnMetric_CheckedChanged);
//
// lblWeight
//
this.lblWeight.AutoSize = true;
this.lblWeight.Location = new System.Drawing.Point(27, 77);
this.lblWeight.Name = "lblWeight";
this.lblWeight.Size = new System.Drawing.Size(56, 20);
this.lblWeight.TabIndex = 9;
this.lblWeight.Text = "Weight";
//
// txtWeight
//
this.txtWeight.Location = new System.Drawing.Point(165, 70);
this.txtWeight.Name = "txtWeight";
this.txtWeight.Size = new System.Drawing.Size(125, 27);
this.txtWeight.TabIndex = 10;
//
// groupBox4
//
this.groupBox4.Controls.Add(this.btnCalculateBMR);
this.groupBox4.Controls.Add(this.groupBox6);
this.groupBox4.Controls.Add(this.txtAge);
this.groupBox4.Controls.Add(this.lblAge);
this.groupBox4.Controls.Add(this.groupBox5);
this.groupBox4.Location = new System.Drawing.Point(27, 130);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(392, 314);
this.groupBox4.TabIndex = 15;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "BMR calculator";
//
// btnCalculateBMR
//
this.btnCalculateBMR.Location = new System.Drawing.Point(68, 274);
this.btnCalculateBMR.Name = "btnCalculateBMR";
this.btnCalculateBMR.Size = new System.Drawing.Size(212, 29);
this.btnCalculateBMR.TabIndex = 4;
this.btnCalculateBMR.Text = "Calculate BMR";
this.btnCalculateBMR.UseVisualStyleBackColor = true;
this.btnCalculateBMR.Click += new System.EventHandler(this.btnCalculateBMR_Click);
//
// groupBox6
//
this.groupBox6.Controls.Add(this.lblBmr);
this.groupBox6.Location = new System.Drawing.Point(177, 55);
this.groupBox6.Name = "groupBox6";
this.groupBox6.Size = new System.Drawing.Size(185, 213);
this.groupBox6.TabIndex = 3;
this.groupBox6.TabStop = false;
this.groupBox6.Text = "how many calories you need";
//
// lblBmr
//
this.lblBmr.AutoSize = true;
this.lblBmr.Location = new System.Drawing.Point(45, 67);
this.lblBmr.Name = "lblBmr";
this.lblBmr.Size = new System.Drawing.Size(58, 20);
this.lblBmr.TabIndex = 5;
this.lblBmr.Text = "label10";
//
// txtAge
//
this.txtAge.Location = new System.Drawing.Point(98, 182);
this.txtAge.Name = "txtAge";
this.txtAge.Size = new System.Drawing.Size(50, 27);
this.txtAge.TabIndex = 2;
//
// lblAge
//
this.lblAge.AutoSize = true;
this.lblAge.Location = new System.Drawing.Point(31, 185);
this.lblAge.Name = "lblAge";
this.lblAge.Size = new System.Drawing.Size(36, 20);
this.lblAge.TabIndex = 1;
this.lblAge.Text = "Age";
//
// groupBox5
//
this.groupBox5.Controls.Add(this.rbtnMale);
this.groupBox5.Controls.Add(this.rbtnFemale);
this.groupBox5.Location = new System.Drawing.Point(17, 42);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(131, 125);
this.groupBox5.TabIndex = 0;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Gender";
//
// rbtnMale
//
this.rbtnMale.AutoSize = true;
this.rbtnMale.Location = new System.Drawing.Point(14, 63);
this.rbtnMale.Name = "rbtnMale";
this.rbtnMale.Size = new System.Drawing.Size(63, 24);
this.rbtnMale.TabIndex = 1;
this.rbtnMale.TabStop = true;
this.rbtnMale.Text = "Male";
this.rbtnMale.UseVisualStyleBackColor = true;
this.rbtnMale.CheckedChanged += new System.EventHandler(this.rbtnMale_CheckedChanged);
//
// rbtnFemale
//
this.rbtnFemale.AutoSize = true;
this.rbtnFemale.Location = new System.Drawing.Point(14, 33);
this.rbtnFemale.Name = "rbtnFemale";
this.rbtnFemale.Size = new System.Drawing.Size(78, 24);
this.rbtnFemale.TabIndex = 0;
this.rbtnFemale.TabStop = true;
this.rbtnFemale.Text = "Female";
this.rbtnFemale.UseVisualStyleBackColor = true;
this.rbtnFemale.CheckedChanged += new System.EventHandler(this.rbtnFemale_CheckedChanged);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(512, 484);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.txtWeight);
this.Controls.Add(this.lblWeight);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.txtCmFt);
this.Controls.Add(this.lblHeight);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.MaximizeBox = false;
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Form1";
this.Load += new System.EventHandler(this.MainForm_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.groupBox6.ResumeLayout(false);
this.groupBox6.PerformLayout();
this.groupBox5.ResumeLayout(false);
this.groupBox5.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label lblHeight;
private TextBox txtCmFt;
private GroupBox groupBox1;
private RadioButton rbtnMetric;
private Label lblWeight;
private TextBox txtWeight;
private GroupBox groupBox4;
private Button btnCalculateBMR;
private GroupBox groupBox6;
private TextBox txtAge;
private Label lblAge;
private GroupBox groupBox5;
private RadioButton rbtnMale;
private RadioButton rbtnFemale;
private Label lblBmr;
}
}
The problem is i cant acess another class by creating new BMIcalculator(); because then its empty or 0.
So my question is how can i access the getter from the BMIcalculator without creating new object. I want to get access to instance variables height and weigh and then use it in Bmrcalculator.
I have very similar problem to this one: Call Methods from another class c#
but i still cant solve it. I began programming 2 weeks ago, sorry if its an obvious question.

Related

Unity UI Toolkit: Custom Tool Tip on entering Element shows only the text not the whole UI

I have a problem with my Custom-"Item Tip".
When I am with my mouse at the "start of the Tip, it's showing only text and not the whole UI.
When I am only in the Inventory Item but not at the Tool Tip:
When I am between being in it and not(I changed the color of the text to read so you can see it better):
MyCode:
public class InventorySlot : VisualElement
{
public Image Icon;
public string ItemGuid = "";
public string itemName = "";
public Seltenheit itemSeltenheit = 0;
public List<WerteType> stats = new List<WerteType>();
//Visual Element Dinge
private UIDocument tip;
private VisualElement ve;
private Label name, seltenheit, schaden, schaden1, schaden2;
private float top, left;
public InventorySlot(Sprite sprite, UIDocument tooltip, float top, float left)
{
tip = tooltip;
this.top = top;
this.left = left;
var rootElement = tip.rootVisualElement;
ve = rootElement.Q<VisualElement>("tooltip");
name = rootElement.Q<Label>("name");
seltenheit = rootElement.Q<Label>("seltenheit");
schaden = rootElement.Q<Label>("schaden");
ve.style.display = DisplayStyle.None;
Icon = new Image();
Add(Icon);
Icon.style.paddingBottom = 15;
Icon.style.paddingTop = 15;
Icon.style.paddingLeft = 15;
Icon.style.paddingRight = 15;
Icon.style.flexGrow = 1;
style.width = 64;
style.height = 64;
style.marginBottom = 5;
style.marginTop = 5;
style.marginLeft = 5;
style.marginRight = 5;
style.backgroundImage = new StyleBackground(sprite);
RegisterCallback<PointerDownEvent>(OnPointerDown);
RegisterCallback<PointerLeaveEvent>(OnPointerLeave);
RegisterCallback<PointerEnterEvent>(OnPointerEnter);
}
private void OnPointerLeave(PointerLeaveEvent evt)
{
ve.style.display = DisplayStyle.None;
ToolTipDatenLeeren();
}
private void OnPointerEnter(PointerEnterEvent evt)
{
ToolTipDaten();
ToolTipAufrufen();
}
private void ToolTipAufrufen()
{
var coordinaten = worldBound.center;
ve.transform.position = new Vector2(coordinaten.x - left, (coordinaten.y - top));
ve.style.backgroundColor = new StyleColor(Color.red);
ve.style.display = DisplayStyle.Flex;
}
private void ToolTipDaten()
{
name.text = itemName;
seltenheit.text = itemSeltenheit.ToString();
if (stats == null)
stats = new List<WerteType>();
if (stats.Count > 0)
schaden.text = stats.ToString();
}
private void ToolTipDatenLeeren()
{
name.text = "";
seltenheit.text = "";
schaden.text = "";
stats = null;
}
#region HoldItem
private void OnPointerDown(PointerDownEvent evt)
{
//Not the left mouse button
if (evt.button != 0 || ItemGuid.Equals(""))
{
return;
}
//Clear the image
Icon.image = null;
//Start the drag
Inventar.StartDrag(evt.position, this);
}
public void HoldItem(Item item)
{
Icon.sprite = item.Icon;
ItemGuid = item.GUID;
itemName = item.Name;
itemSeltenheit = item.seltenheit;
AusruestungsItems aItem = (AusruestungsItems)item;
if (aItem != null)
stats = aItem.stats;
}
public void DropItem()
{
ItemGuid = "";
Icon.sprite = null;
}
#endregion
}

How to make Form Visible in C#

I am trying to design a piano for an assignment in C#. I have created a MusicKey class which stores music keys (as well as a BlackMusicKey class). I am populating the panel, 'panel1' with music keys like this:
this.panel1.Controls.Add(bmk);
In the music key constructor, I am setting a location and size for each music key, as well as ensuring that Visibility is set to true. However, when I run the form, it is completely blank.
Is there something that I am missing? I am quite sure that there is nothing wrong with the visibility of the music keys, so surely there is something that I am missing with regards to making the panel visible.
Any help will be appreciated, thanks!
Note: I have also tried using panel1.Show() which still did not work.
All relevant code can be found down below:
MusicKeyClass:
class MusKey : System.Windows.Forms.Button
{
private int musicNote; //determines the pitch mapped to number
public MusKey(int iNote, int x, int y) : base()
{
musicNote = iNote;
this.Location = new System.Drawing.Point(x, y);
this.Size = new System.Drawing.Size(20, 80);
this.Visible = true;
}
public int getMusicNote()
{
return musicNote;
}
}
Form1 Class:
public partial class Form1 : Form
{
int count = 0;
int xLoc = 50;
int yLoc = 30;
int[] whitePitch = { 1, 3, 5, 6, 8, 10, 12, 13, 15, 17, 18, 20, 22, 24 };
Panel panel1 = new Panel();
System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
Button button1 = new Button();
private void Form1_Load(object sender, EventArgs e)
{
this.Paint += new PaintEventHandler(function);
MusKey mk;
BlackMusKey bmk;
for (int k = 0; k < 14; k++)
{
int pitch = whitePitch[k];
int ixPos = k * 20;
mk = new MusKey(pitch, ixPos, yLoc);
mk.MouseDown += new MouseEventHandler(this.button1_MouseDown);
mk.MouseUp += new MouseEventHandler(this.button1_MouseUp);
this.panel1.Controls.Add(mk);
}
int xOffs = 20;
int[] blackPitch = { 2, 4, 7, 9, 11, 14, 16, 19, 21, 23 };
int[] xPos = { 10, 30, 70, 110, 150, 170, 210, 230, 250 };
const int yPosBlack = 50;
for (int k = 0; k < 10; k++)
{
int pitch = blackPitch[k];
int ixPos = xPos[k];
bmk = new BlackMusKey(pitch, ixPos, yPosBlack);
bmk.MouseDown += new System.Windows.Forms.MouseEventHandler(this.button1_MouseDown); //create event MouseDown
bmk.MouseUp += new System.Windows.Forms.MouseEventHandler(this.button1_MouseUp); //create event MouseUp
this.panel1.Controls.Add(bmk);
this.panel1.Controls[this.panel1.Controls.Count - 1].BringToFront();
}
}
SoundPlayer sp = new SoundPlayer();
int count1;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
foreach (MusKey mk in this.panel1.Controls)
{
if (sender == mk)
{ //true for the specific key pressed on the Music Keyboard
if (e.Button == MouseButtons.Left)
{
timer1.Enabled = true; //variable of the Timer component
count = 0; //incremented by the timer1_Tick event handler
timer1.Start();
sp.SoundLocation = (mk.getMusicNote() + ".wav"); //might need to convert ToString() ??
sp.Play();
}
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
count = count++;
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
foreach (MusKey mk in this.panel1.Controls)
{
if (sender == mk) //true for the specific key pressed on the Music Keyboard
{
if (e.Button == MouseButtons.Left)
{
timer1.Enabled = false;
sp.Stop();
string bNoteShape = null;
int duration = 0;
if (count >= 16)
{
bNoteShape = "SemiBreve";
duration = 16;
}
if (count >= 8 && count <= 15)
{
bNoteShape = "DotMinim";
duration = (8 + 15) / 2;
}
if (count >= 4 && count <= 7)
{
bNoteShape = "Crotchet";
duration = (4 + 7) / 2;
}
if (count >= 2 && count <= 3)
{
bNoteShape = "Quaver";
duration = (2 + 3) / 2;
}
if (count >= 1)
{
bNoteShape = "Semi-Quaver";
duration = 1;
}
MusicNote mn = new MusicNote(mk.getMusicNote(), duration, bNoteShape); //music note construction
// mn.Location = new Point(xLoc, yLoc);
//this.panel2.Controls.Add(this.mn); //adding MusicNote component to MusicStaff (panel2) collection
xLoc = xLoc + 15;
}
}
}
}
private void function(object sender, PaintEventArgs e)
{
panel1.Show();
panel1.Visible = true;
panel1.BackColor = Color.Blue;
panel1.Size = new Size(5, 5);
panel1.Location = new Point(3, 3);
this.Controls.Add(panel1);
this.Controls.Add(button1);
}
private void Form1_Load_1(object sender, EventArgs e)
{
}
}
Form 1 [designer] Class:
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load_1);
this.ResumeLayout(false);
}
#endregion
}
Music Note Class
class MusicNote
{
public int notepitch;
public String noteshape;
public int noteduration;
enum accid { sharp, flat, sole };
bool dragging = false;
System.Timers.Timer timer1 = new System.Timers.Timer();
public MusicNote(int iNotepitch, int iDuration, String iBnoteShape)
{
notepitch = iNotepitch;
noteduration = iDuration;
noteshape = iBnoteShape;
}
bool timeron = false;
bool changenote = false;
public static int start = 0;
//public void click(object sender, MouseEventArgs e) { }
//public void RightPress(object sender, MouseEventArgs e) { }
}
}
Black Music Key Class
class BlackMusKey : MusKey
{
public BlackMusKey(int iNote, int x, int y) : base(iNote, x, y)
{
this.BackColor = Color.Black;
this.Size = new System.Drawing.Size(20, 60);
}
}
Program Class
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());
}
}
According to Form1 class code, there is constructor missing. Please add proper constructor with InitializeComponent() method call. It can be added anywhere in class body.
Code snippet:
public partial class Form1 : Form
{
[...] //your objects declarations
public Form1()
{
InitializeComponent();
}
[...] //rest of your code
}

How to move panels up/down on keysDown event in c#

I've 4 panels, having same Y and different X, that are created at the program start on a picturebox. When I click on a panel, it sets the focus and is ready to get a keysDown event so i.e. if I click on up arrow key the panel moves up.
This is the code:
public partial class FormView : Form
{
List<CircleButton> myPanels = new List<CircleButton>(); // array of panels CircleButton
Point[] arrayPoints_milestones; // array of X,Y
int index;
public FormView()
{
InitializeComponent();
arrayPoints_milestones = new Point[4];
for (int i = 0; i < 4; i++ )
{
arrayPoints_milestones[i] = new Point { X = 20, Y = 20 };
}
test();
}
protected void panel_Click(object sender, EventArgs e)
{
myPanels[index].PreviewKeyDown -= new PreviewKeyDownEventHandler(panel_KeyDown);
CircleButton panel = sender as CircleButton;
index = (int)panel.Tag;
myPanels[index].Focus(); //panel.Focus();
myPanels[index].PreviewKeyDown += new PreviewKeyDownEventHandler(panel_KeyDown);
}
private void panel_KeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
myPanels[index].Centre = new Point(myPanels[index].Centre.X, myPanels[index].Centre.Y - 10);
MessageBox.Show("" + myPanels[index].Centre.Y);
Invalidate();
}
if (e.KeyCode == Keys.Down)
{
myPanels[index].Centre = new Point(myPanels[index].Centre.X, myPanels[index].Centre.Y + 10);
MessageBox.Show("" + myPanels[index].Centre.Y);
Invalidate();
}
}
private void test()
{
//for (int i = 0; i < 4; i++)
int i=0;
foreach(var value in arrayPoints_milestones)
{
CircleButton panel = new CircleButton();
panel.Tag = i;
panel.Centre = new Point(arrayPoints_milestones[i].X + i * 10, arrayPoints_milestones[i].Y);
panel.Radius = 10;
panel.BackColor = Color.Red;
panel.Message = "Index: " + panel.Tag.ToString();
myPanels.Add(panel); // qui aggiungo il pannello alla lista di pannelli myPanels
pictureBox1.Controls.Add(myPanels[i]);
myPanels[i].Click += new EventHandler(panel_Click);
i++;
}
}
}
and this is the custom panel class:
public class CircleButton : Panel
{
//Properties to draw circle
float radius;
public float Radius
{
get { return radius; }
set
{
radius = value;
this.Size = new Size((int)Radius, (int)Radius);
}
}
public string Name
{
get;
set;
}
Point centre;
public Point Centre
{
get { return centre; }
set
{
centre = value;
this.Location = Centre;
}
}
public string Message { get; set; }
public CircleButton()
{
//Default Values
Name = "panel_base";
this.BackColor = Color.Black;
Radius = 1;
Centre = new Point(0, 0);
this.DoubleBuffered = true;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
//Defines a graphic path and set it as the panel's region
//For custom region use different path's
if (centre != null)
{
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, radius, radius);
this.Region = new Region(path);
path.Dispose();
}
}
}
Each time you click a panel, a PreviewKeyDownEventHandler is added - so 3 clicks will trigger 3 (different) eventhandlers with the same invocation target, and each will move your panel for 10 pixels up/down:
protected void panel_Click(object sender, EventArgs e) {
CircleButton panel = sender as CircleButton;
index = (int)panel.Tag;
myPanels[index].Focus(); //panel.Focus();
myPanels[index].PreviewKeyDown += new PreviewKeyDownEventHandler(panel_KeyDown);
}
Updated code for FormView:
public partial class FormView : Form {
List<CircleButton> myPanels = new List<CircleButton>(); // local use only in my example
Point[] arrayPoints_milestones; //not needed anymore
int index; //not needed anymore
public FormView() {
InitializeComponent();
this.Load += FormView_Load;
}
void FormView_Load(object sender, EventArgs args) {
Point panelOffset = new Point(20, 20);
for (int i = 0; i < 4; i++) {
var panel = new CircleButton() {
Name = "panel" + i, //Attention! You have hidden the property "Name" in "Control" with a re-declaration in "CircleButton"
Tag = i, //not needed anymore, right?
Centre = new Point(panelOffset.X + i * 10, panelOffset.Y),
Radius = 10,
BackColor = Color.Red,
Message = "Index: " + i.ToString(),
};
panel.Click += (s, e) => {
panel.Focus();
};
panel.PreviewKeyDown += (s, e) => {
if(e.KeyCode == Keys.Up) {
Point centre = panel.Centre; //copy value
centre.Y -= 10;
panel.Centre = centre; //assign modified copy
Invalidate();
}
if(e.KeyCode == Keys.Down) {
Point centre = panel.Centre; //copy value
centre.Y += 10;
panel.Centre = centre; //assign modified copy
Invalidate();
}
};
myPanels.Add(panel);
pictureBox1.Controls.Add(panel);
}
}
}

c# label not updating

I have Label in Panel. In timer.Tick new value write in Label.Text, but in form not change.
Program.cs:
static void Main(string[] args)
{
MainForm mainForm = new MainForm();
Engine engine = new Engine(mainForm);
Application.Run(mainForm);
}
MainForm.cs
public partial class MainForm : Form
{
public MatchesPanel panel;
public MainForm()
{
InitializeComponent();
this.Load += MainForm_Load;
this.panel = new MatchesPanel("panel", new System.Drawing.Point(0, 52));
this.panel.Name = "panel";
this.panel.TabIndex = 8;
this.Controls.Add(this.panel);
}
}
MatchesPanel.cs
public class MatchesPanel : Panel
{
public string Name;
int VWheelSize = 0;
Dictionary<string, Label> Items = new Dictionary<string, Label>();
Label InFocus = null;
public MatchesPanel(string name, Point location)
{
Name = name;
this.BackColor = System.Drawing.SystemColors.GradientActiveCaption;
this.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Location = location;
this.Margin = new System.Windows.Forms.Padding(0);
this.Size = new System.Drawing.Size(400, 323);
this.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.MouseWheel += This_MouseWheel;
this.Click += This_Click;
this.Invalidated += MatchesPanel_Invalidated;
}
void Label_Click(object s, EventArgs e)
{
Label l = (Label)s;
l.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
l.BackColor = System.Drawing.Color.MediumTurquoise;
if (InFocus != null && InFocus != l)
{
InFocus.BorderStyle = System.Windows.Forms.BorderStyle.None;
InFocus.BackColor = System.Drawing.SystemColors.GradientActiveCaption;
}
InFocus = l;
l.Focus();
}
public void SetText(string key, string text)
{
Label l = Items[key];
l.Text = text;
}
public void Add(string key, string text)
{
Label label = new Label();
label.AllowDrop = true;
label.BackColor = System.Drawing.SystemColors.GradientActiveCaption;
label.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
label.Location = new Point(0, Items.Count * 37 + VWheelSize);
label.Margin = new System.Windows.Forms.Padding(0);
label.Padding = new System.Windows.Forms.Padding(3);
label.Size = new System.Drawing.Size(400, 37);
label.Text = text;
label.Click += Label_Click;
label.LostFocus += Label_LostFocus;
label.MouseLeave += Label_MouseLeave;
label.MouseMove += Label_MouseMove;
this.Controls.Add(label);
Items.Add(key, label);
}
public void UpdateMatches(Dictionary<string, Match> Matches)
{
string newStr;
// calculate newStr...
// in debugger i check newStr value and this right
// but text not updating
this.SetText(key, newStr);
}
}
Engine.cs
public class Engine
{
System.Windows.Forms.Timer timer = null;
public Dictionary<string, Match> Matches;
MainForm MainForm = null;
public Engine(MainForm mainForm)
{
MainForm = mainForm;
Matches = new Dictionary<string, Match>();
timer = new System.Windows.Forms.Timer();
timer.Tick += timer_Tick;
timer.Interval = 1000;
timer.Start();
}
public void timer_Tick(object s, EventArgs e)
{
System.Windows.Forms.Timer timer = (System.Windows.Forms.Timer)s;
timer.Stop();
Proc();
timer.Start();
}
public async void Proc()
{
// do something...
MainForm.Invoke((System.Windows.Forms.MethodInvoker)delegate()
{
MainForm.panel.UpdateMatches(Matches);
});
}
}
I try use:
Label.Update();
Label.Refresh();
Label.Invalidate();
but it not work.
If I click in label, when it not in focus (InFocus != sourceLabel in clickHandler), text value updating in sourceLabel one time.
Help me pls. I read another topics and not find solve.
If need more code, tell me.
Thx.
[EDIT]
I simplified my code.
Program.cs:
static void Main(string[] args)
{
MainForm mainForm = new MainForm();
Engine engine = new Engine(mainForm);
Application.Run(mainForm);
}
MatchesPanel.cs
public class MatchesPanel : Panel
{
Dictionary<string, Label> Items = new Dictionary<string, Label>();
public MatchesPanel(Point location)
{
this.BackColor = System.Drawing.SystemColors.GradientActiveCaption;
this.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Location = location;
this.Margin = new System.Windows.Forms.Padding(0);
this.Size = new System.Drawing.Size(400, 323);
this.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
}
public void SetText(string key)
{
Label l = Items[key];
l.Text = DateTime.Now.ToString();
}
public void Add(string key)
{
Label label = new Label();
label.Name = key;
label.AllowDrop = true;
label.BackColor = System.Drawing.SystemColors.GradientActiveCaption;
label.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
label.Location = new Point(0, Items.Count * 37 + VWheelSize);
label.Margin = new System.Windows.Forms.Padding(0);
label.Padding = new System.Windows.Forms.Padding(3);
label.Size = new System.Drawing.Size(400, 37);
label.Text = DateTime.Now.ToString();
this.Controls.Add(label);
Items.Add(key, label);
}
}
Engine.cs
public class Engine
{
System.Windows.Forms.Timer timer = null;
public MatchesPanel panel = null;
MainForm MainForm = null;
public Engine(MainForm mainForm)
{
MainForm = mainForm;
timer = new System.Windows.Forms.Timer();
timer.Tick += timer_Tick;
timer.Interval = 1000;
timer.Start();
}
public void timer_Tick(object s, EventArgs e)
{
System.Windows.Forms.Timer timer = (System.Windows.Forms.Timer)s;
timer.Stop();
MainForm.Invoke((System.Windows.Forms.MethodInvoker)delegate()
{
if (panel == null)
{
panel = new MatchesPanel(new System.Drawing.Point(0, 52));
panel.Name = "key1";
// add label in main form
panel.Add("key1");
MainForm.Controls.Add(panel);
}
panel.SetText("key1");
});
timer.Start();
}
}
Problem:
Label.Text not updating.
Solve:
public class UpdatableLabel : Button
{
public UpdatableLabel() : base()
{
FlatAppearance.BorderSize = 0;
FlatStyle = System.Windows.Forms.FlatStyle.Flat;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Pen pen = new Pen(FlatAppearance.BorderColor, 1);
Rectangle rectangle = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1);
e.Graphics.DrawRectangle(pen, rectangle);
}
}
Now my "label" is updated.

Dynamically changing the text of items in a Winforms ComboBox

I have a Winforms ComboBox that contains instances of a custom class. When the items are first added to the Items collection of the ComboBox, the ToString method is call on each of them.
However when the user changes the language the application is running in, the result of the ToString method changes.
Therefore how can I get the ComboBox to call the ToString method on all items again without having to remove all items from the ComboBox and adding them back in?
Thanks svick, RefreshItems() work, however as it is protected (so can only be called by a subclass) I had to do
public class RefreshingComboBox : ComboBox
{
public new void RefreshItem(int index)
{
base.RefreshItem(index);
}
public new void RefreshItems()
{
base.RefreshItems();
}
}
I have just had to do the same for a ToolStripComboBox, however it was a bit harder as you can not subclass the Combro box it contains, I did
public class RefreshingToolStripComboBox : ToolStripComboBox
{
// We do not want "fake" selectedIndex change events etc, subclass that overide the OnIndexChanged etc
// will have to check InOnCultureChanged them selfs
private bool inRefresh = false;
public bool InRefresh { get { return inRefresh; } }
public void Refresh()
{
try
{
inRefresh = true;
// This is harder then it shold be, as I can't get to the Refesh method that
// is on the embebed combro box.
//
// I am trying to get ToString recalled on all the items
int selectedIndex = SelectedIndex;
object[] items = new object[Items.Count];
Items.CopyTo(items, 0);
Items.Clear();
Items.AddRange(items);
SelectedIndex = selectedIndex;
}
finally
{
inRefresh = false;
}
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
if (!inRefresh)
{
base.OnSelectedIndexChanged(e);
}
}
}
I had to do the same trip to stop unwanted events for the normal CombroBox, by overriding OnSelectedValueChanged, OnSelectedItemChanged and OnSelectedIndexChanged, as the code is the same as for the ToolStripComboBox I have not included it here.
You should be able to do this by calling the RefreshItems() method.
I use this extension:
/// <summary>
/// Recreates the items
/// </summary>
public static void RefreshItems(this ComboBox cb)
{
var selectedIndex = cb.SelectedIndex;
cb.SelectedIndex = -1;
MethodInfo dynMethod = cb.GetType().GetMethod("RefreshItems", BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(cb, null);
cb.SelectedIndex = selectedIndex;
}
svick is right. However, as Ian Ringrose mentions, a subclass is necessary.
RefreshItems is a protected method for System.Windows.Forms.ComboBox.
A Forms application below provides an example of the behavior, and the RefreshItems method updating the ComboBox:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public class Form1 : Form
{
private List<HelloWorld> helloWorlds;
#region Form1.Designer.cs
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose( bool disposing )
{
if ( disposing && (components != null) )
{
components.Dispose();
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.comboBox1 = new RefreshingComboBox();
this.comboBox2 = new RefreshingComboBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// comboBox1
//
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point( 76, 12 );
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size( 115, 21 );
this.comboBox1.TabIndex = 0;
//
// comboBox2
//
this.comboBox2.FormattingEnabled = true;
this.comboBox2.Location = new System.Drawing.Point( 250, 12 );
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size( 218, 21 );
this.comboBox2.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point( 12, 15 );
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size( 58, 13 );
this.label1.TabIndex = 2;
this.label1.Text = "Language:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point( 213, 15 );
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size( 31, 13 );
this.label2.TabIndex = 3;
this.label2.Text = "Text:";
//
// button1
//
this.button1.Location = new System.Drawing.Point( 34, 42 );
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size( 75, 23 );
this.button1.TabIndex = 4;
this.button1.Text = "Set All";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler( this.button1_Click );
//
// button2
//
this.button2.Location = new System.Drawing.Point( 116, 42 );
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size( 75, 23 );
this.button2.TabIndex = 5;
this.button2.Text = "Set Random";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler( this.button2_Click );
//
// button3
//
this.button3.Location = new System.Drawing.Point( 393, 42 );
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size( 75, 23 );
this.button3.TabIndex = 6;
this.button3.Text = "Refresh!";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler( this.button3_Click );
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F );
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size( 556, 77 );
this.Controls.Add( this.button3 );
this.Controls.Add( this.button2 );
this.Controls.Add( this.button1 );
this.Controls.Add( this.label2 );
this.Controls.Add( this.label1 );
this.Controls.Add( this.comboBox2 );
this.Controls.Add( this.comboBox1 );
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout( false );
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.ComboBox comboBox2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
#endregion
public Form1()
{
InitializeComponent();
comboBox1.DataSource = new HelloWorld().GetLanguages();
helloWorlds = new List<HelloWorld>();
while ( helloWorlds.Count < 10 )
{
helloWorlds.Add( new HelloWorld() );
}
comboBox2.DataSource = helloWorlds;
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
Application.Run( new Form1() );
}
private void changeAllLanguages()
{
HelloWorld.LanguageValue newLang = (HelloWorld.LanguageValue) comboBox1.SelectedValue;
helloWorlds.ForEach(
delegate( HelloWorld hw )
{
hw.Language = newLang;
} );
}
private void changeRandomLanguage()
{
int index = new Random().Next( helloWorlds.Count );
HelloWorld.LanguageValue newLang = (HelloWorld.LanguageValue) comboBox1.SelectedValue;
helloWorlds[index].Language = newLang;
}
private void button1_Click( object sender, EventArgs e )
{
changeAllLanguages();
}
private void button2_Click( object sender, EventArgs e )
{
changeRandomLanguage();
}
private void button3_Click( object sender, EventArgs e )
{
(comboBox2 as RefreshingComboBox).RefreshItems();
}
}
public class RefreshingComboBox : System.Windows.Forms.ComboBox
{
public new void RefreshItem(int index)
{
base.RefreshItem(index);
}
public new void RefreshItems()
{
base.RefreshItems();
}
}
public class HelloWorld
{
public enum LanguageValue
{
English,
日本語,
Deutsch,
Français,
Český
}
private LanguageValue language;
public LanguageValue Language
{
get
{
return language;
}
set
{
language = value;
}
}
public Array GetLanguages()
{
return Enum.GetValues( typeof( LanguageValue ) );
}
Dictionary<LanguageValue, string> helloWorlds;
public HelloWorld()
{
helloWorlds = new Dictionary<LanguageValue, string>();
helloWorlds[LanguageValue.English] = "Hello, world!";
helloWorlds[LanguageValue.日本語] = "こんにちは、世界!";
helloWorlds[LanguageValue.Deutsch] = "Hallo, Welt!";
helloWorlds[LanguageValue.Français] = "Sallut, monde!";
helloWorlds[LanguageValue.Český] = "Ahoj svět!";
}
public override string ToString()
{
return helloWorlds[language];
}
}
}

Categories

Resources