I am creating a c# piano which when clicking on a music key, an image of the music note is outputted on the form, however no image is being outputted. I am sure that the image path for the bitmap images is correct so I am not sure whether I have done something wrong in the code or I need to add some events to the form itself.Can somebody help me with this please ?
This is the Form class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
using System.Threading;
namespace NewPiano
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SoundPlayer sp = new SoundPlayer();
int count;
private Control mn;
int xLoc = 50;
int yLoc = 30;
List<MusicNote> notes = new List<MusicNote>();
private void Form1_Load(object sender, System.EventArgs e)
{
MusKey mk;
BlackMusKey bmk;
int[] whitePitch = { 1, 3, 5, 6, 8, 10, 12, 13, 15, 17, 18, 20, 22, 24 };
int[] blackPitch = new int[] { 2, 4, 7, 9, 11, 14, 16, 19, 21, 23 };
int[] xPos = new int[] { 10, 30, 70, 90, 110, 150, 170, 210, 230, 250 };
for (int k = 0; k < 7; k++)
{
int iNote = whitePitch[k];
int xpos = k * 40;
mk = new MusKey(iNote, xpos + 225, 300);
mk.MouseDown += new System.Windows.Forms.MouseEventHandler(this.button1_MouseDown);
mk.MouseUp += new System.Windows.Forms.MouseEventHandler(this.button1_MouseUp);
this.panel1.Controls.Add(mk);
}
int xOffs = 20;
for (int k = 0; k < 5; k++)
{
int iNote = blackPitch[k];
int xpos = xPos[k] * 2;
bmk = new BlackMusKey(iNote, xpos + 225, 300);
bmk.MouseDown += new System.Windows.Forms.MouseEventHandler(this.button1_MouseDown);
bmk.MouseUp += new System.Windows.Forms.MouseEventHandler(this.button1_MouseUp);
this.panel1.Controls.Add(bmk);
this.panel1.Controls[this.panel1.Controls.Count - 1].BringToFront();
}
}
private void button1_MouseDown(object sender, MouseEventArgs e)
{
foreach(MusKey mk in this.panel1.Controls.OfType<MusKey>())
{
if(sender == mk)
{
if(e.Button == MouseButtons.Left)
{
timer1.Enabled = true;
count = 0;
timer1.Start();
sp.SoundLocation = #"C:/Users/Kim/Desktop/Notes-Sound files/mapped/" + mk.musicNote + ".wav"; //change this to the location of your "mapped" folder
sp.Load();
sp.Play();
}
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
count ++;
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
foreach(MusKey mk in this.panel1.Controls.OfType<MusKey>())
{
if (sender == mk)
{
if (e.Button == MouseButtons.Left)
timer1.Enabled = false;
textBox1.Text = count.ToString();
sp.Stop();
string bNoteShape = null;
int duration = 0;
//Insert note lengths
if (count >= 16)
{
bNoteShape = "SemiBreve";
duration = (16 + 20) / 2;
}
else if ((count >= 11) && (count <= 15))
{
bNoteShape = "DotMin";
duration = (11 + 15) / 2; //average
}
else if ((count >= 6) && (count <= 10))
{
bNoteShape = "Minim";
duration = (6 + 10) / 2; //average
}
else if ((count >= 3) && (count <= 5))
{
bNoteShape = "Crotchet";
duration = (3 + 5) / 2; //average
}
else if ((count == 2))
{
bNoteShape = "Quaver";
duration = 2; //average
}
else if ((count >= 0) || (count <= 1))
{
bNoteShape = "SemiQuaver";
duration = 1;
}
//copied from handout
MusicNote mn = new MusicNote(mk.musicNote, duration, bNoteShape, xLoc);
notes.Add(mn);
mn.Location = new Point(xLoc, yLoc);
this.panel1.Controls.Add(this.mn);
xLoc = xLoc + 40;
}
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Graphics graphicsObj;
graphicsObj = this.panel1.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Black, 1);
for (int k = 0; k < 5; k++)
{
int ypos = (k * 15) + 20;
graphicsObj.DrawLine(myPen, 20, ypos, 550, ypos);
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (MusicNote mn in notes)
{
sp.SoundLocation = #"C:/Users/Kim/Desktop/Notes-Sound files/mapped/" + mn.pitch + ".wav"; //change this to the location of your "mapped" folder
sp.Play();
Thread.Sleep(mn.duration * 150);
}
}
}
}
This is the Music Note class:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NewPiano
{
public class MusicNote : PictureBox
{
Boolean isDragging = false;
public int pitch = 0;
public string noteshape = "";
public int duration = 0;
internal Point Location;
public int xLocation = 0;
public MusicNote(int notePitch, int duration, string bNoteShape, int xLoc) : base()
{
this.noteshape = bNoteShape;
this.duration = duration;
this.pitch = notePitch;
Location = new Point(xLoc, pitch);
this.Size = new Size(30, 30);
Bitmap bmp = new Bitmap(#"C:/Users/Kim/Desktop/Notes-Images/" + noteshape + ".bmp");
this.Image = bmp;
this.MouseDown += new MouseEventHandler(StartDrag);
this.MouseUp += new MouseEventHandler(StopDrag);
this.MouseMove += new MouseEventHandler(NoteDrag);
}
private void StartDrag(object sender, MouseEventArgs e) {
if(e.Button == MouseButtons.Left) {
isDragging = true;
pitch = e.Y;
this.Location = new Point(this.Location.X, pitch);
}
}
private void StopDrag(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDragging = false;
pitch = e.Y;
}
}
private void NoteDrag(object sender, MouseEventArgs e)
{
if (isDragging)
{
this.Top = this.Top + (e.Y - this.pitch);
}
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
}
}
Related
I'm giving my panels inside another panel (this panel is in a usercontrol) a fixed location and a maximum size that changes with the size of the panel there in. Neither the resize or location works properly. The resize does happen but its to quickly. The location is fine if you only have 1 pinpanel for output and input. When you have more then 1 the locations are fixed but you need to resize the panel to resize to see the other panels. Could you point me in the right direction if you see the problem?
I have a panel drawPanel in this case that i use as a sort of background for the usercontrol. Inside this drawPanel i'm placing pinpanels. I want these pinpanels to resize with the usercontrol and give them a fixed location
private void OnClickPinPanel(object source, EventArgs e)
{
if (source is PinPanel p)
{
int index;
if ((index = Array.IndexOf(inputPins, p)) >= 0)
{
ClickedPinPanel?.Invoke(index, true);
}
else
{
ClickedPinPanel?.Invoke(Array.IndexOf(outputPins, p), false);
}
}
//else log here
}
private void CreatePinPanels(bool isInput)
{
int x = 0;
int y = -(int)(this.Width * 0.05)/2;
if (isInput)
{
for (int i = 0; i < inputPins.Length; i++)
{
y += (i + 1) * (this.Height / inputPins.Length + 1);
inputPins[i] = new PinPanel()
{
Location = new Point(x, y),
Size = new Size((int)(this.Width * 0.05), (int)(this.Width * 0.05)),
Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right,
};
inputPins[i].Click += OnClickPinPanel;
}
}
else
{
x += this.Width - (int)(this.Width * 0.1);
for (int i = 0; i < outputPins.Length; i++)
{
y += (i + 1) * (this.Height / inputPins.Length+1);
outputPins[i] = new PinPanel()
{
Size = new Size((int)(this.Width * 0.1), (int)(this.Width * 0.1)),
Location = new Point(x, y),
Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right
};
outputPins[i].Click += OnClickPinPanel;
}
}
}
The result i get now is that the pinpanels get a fixed location but when you have more then 1 pinpanel, the location is wrong its like if he thinks that the usercontrol is bigger then it is Reality. In order to see all the pins i have to resize and get this After resize
I want it to look like this
expectations
Try something like this out.
Here is my test rig:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
numericUpDown1.Value = someChip1.NumberInputPins;
numericUpDown2.Value = someChip1.NumberOutputPins;
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
someChip1.NumberInputPins = (int)numericUpDown1.Value;
}
private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
someChip1.NumberOutputPins = (int)numericUpDown2.Value;
}
}
Sample chip with 5 inputs and 3 outputs:
Here is my PinPanel UserControl (just draws an ellipse/pin the size of the control):
public partial class PinPanel : UserControl
{
public PinPanel()
{
InitializeComponent();
}
private void PinPanel_Paint(object sender, PaintEventArgs e)
{
Rectangle rc = new Rectangle(new Point(0, 0), new Size(this.ClientRectangle.Width - 1, this.ClientRectangle.Height - 1));
e.Graphics.DrawEllipse(Pens.Black, rc);
}
private void PinPanel_SizeChanged(object sender, EventArgs e)
{
this.Refresh();
}
}
And finally, my SomeChip UserControl:
public partial class SomeChip : UserControl
{
public event PinPanelClick ClickedPinPanel;
public delegate void PinPanelClick(int index, bool input);
private PinPanel[] inputPins;
private PinPanel[] outputPins;
private int _NumberInputPins = 2;
public int NumberInputPins
{
get {
return _NumberInputPins;
}
set
{
if (value > 0 && value != _NumberInputPins)
{
_NumberInputPins = value;
CreatePinPanels();
this.Refresh();
}
}
}
private int _NumberOutputPins = 1;
public int NumberOutputPins
{
get
{
return _NumberOutputPins;
}
set
{
if (value > 0 && value != _NumberOutputPins)
{
_NumberOutputPins = value;
CreatePinPanels();
this.Refresh();
}
}
}
public SomeChip()
{
InitializeComponent();
}
private void SomeChip_Load(object sender, EventArgs e)
{
CreatePinPanels();
RepositionPins();
}
private void SomeChip_SizeChanged(object sender, EventArgs e)
{
this.Refresh();
}
private void SomeChip_Paint(object sender, PaintEventArgs e)
{
int PinHeight;
// draw the input pin runs
if (inputPins != null)
{
PinHeight = (int)((double)this.Height / (double)_NumberInputPins);
for (int i = 0; i < NumberInputPins; i++)
{
int Y = (i * PinHeight) + (PinHeight / 2);
e.Graphics.DrawLine(Pens.Black, 0, Y, this.Width / 4, Y);
}
}
// draw the output pin runs
if (outputPins != null)
{
PinHeight = (int)((double)this.Height / (double)_NumberOutputPins);
for (int i = 0; i < NumberOutputPins; i++)
{
int Y = (i * PinHeight) + (PinHeight / 2);
e.Graphics.DrawLine(Pens.Black, this.Width - this.Width / 4, Y, this.Width, Y);
}
}
//draw the chip itself (takes up 50% of the width of the UserControl)
Rectangle rc = new Rectangle(new Point(this.Width / 4, 0), new Size(this.Width / 2, this.Height - 1));
using (SolidBrush sb = new SolidBrush(this.BackColor))
{
e.Graphics.FillRectangle(sb, rc);
}
e.Graphics.DrawRectangle(Pens.Black, rc);
RepositionPins();
}
private void CreatePinPanels()
{
if (inputPins != null)
{
for (int i = 0; i < inputPins.Length; i++)
{
if (inputPins[i] != null && !inputPins[i].IsDisposed)
{
inputPins[i].Dispose();
}
}
}
inputPins = new PinPanel[_NumberInputPins];
for (int i = 0; i < inputPins.Length; i++)
{
inputPins[i] = new PinPanel();
inputPins[i].Click += OnClickPinPanel;
this.Controls.Add(inputPins[i]);
}
if (outputPins != null)
{
for (int i = 0; i < outputPins.Length; i++)
{
if (outputPins[i] != null && !outputPins[i].IsDisposed)
{
outputPins[i].Dispose();
}
}
}
outputPins = new PinPanel[_NumberOutputPins];
for (int i = 0; i < outputPins.Length; i++)
{
outputPins[i] = new PinPanel();
outputPins[i].Click += OnClickPinPanel;
this.Controls.Add(outputPins[i]);
}
}
private void OnClickPinPanel(object sender, EventArgs e)
{
PinPanel p = (PinPanel)sender;
if (inputPins.Contains(p))
{
ClickedPinPanel?.Invoke(Array.IndexOf(inputPins, p), true);
}
else if (outputPins.Contains(p))
{
ClickedPinPanel?.Invoke(Array.IndexOf(inputPins, p), false);
}
}
private void RepositionPins()
{
int PinRowHeight, PinHeight;
if (inputPins != null)
{
PinRowHeight = (int)((double)this.Height / (double)_NumberInputPins);
PinHeight = (int)Math.Min((double)(PinRowHeight / 2), (double)this.Height * 0.05);
for (int i = 0; i < inputPins.Length; i++)
{
if (inputPins[i] != null && !inputPins[i].IsDisposed)
{
inputPins[i].SetBounds(0, (int)((i * PinRowHeight) + (PinRowHeight /2 ) - (PinHeight / 2)), PinHeight, PinHeight);
}
}
}
if (outputPins != null)
{
PinRowHeight = (int)((double)this.Height / (double)_NumberOutputPins);
PinHeight = (int)Math.Min((double)(PinRowHeight / 2), (double)this.Height * 0.05);
for (int i = 0; i < outputPins.Length; i++)
{
if (outputPins[i] != null && !outputPins[i].IsDisposed)
{
outputPins[i].SetBounds(this.Width - PinHeight, (int)((i * PinRowHeight) + (PinRowHeight / 2) - (PinHeight / 2)), PinHeight, PinHeight);
}
}
}
}
}
I was making a simple Pong game and wanted to play a sound when the ball hits walls. Code is ready even the place is ready where i must place sound.play function. I tried doing it but when ball hits the wall Form Application just freezes and i have to force close visual studio. Any suggestion why this happens?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
namespace P3_7_26_2016_Pong
{
public partial class Form1 : Form
{
public int speed_left = 4;
public int speed_top = 4;
public int points = 0;
/* PLAYER INITIALIZED HERE */
private SoundPlayer Player = new SoundPlayer();
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
Cursor.Hide();
this.FormBorderStyle = FormBorderStyle.None;
this.TopMost = true;
this.Bounds = Screen.PrimaryScreen.Bounds;
pong.Top = playground.Bottom - (playground.Bottom / 10);
gameoverLabel.Left = (playground.Width / 2) - (gameoverLabel.Width / 2);
gameoverLabel.Top = (playground.Height / 2) - (gameoverLabel.Height / 2);
gameoverLabel.Visible = false;
//SOUND SET HERE
Player.SoundLocation = #"C:\Users\bacon\Desktop\click.wav";
}
private void timer1_Tick(object sender, EventArgs e)
{
pong.Left = Cursor.Position.X - (pong.Width / 2);
ball.Left += speed_left;
ball.Top += speed_top;
if(ball.Bottom >= pong.Top && ball.Bottom <= pong.Bottom && ball.Left >= pong.Left && ball.Right <= pong.Right)
{
speed_left += 2;
speed_top += 2;
//speed_left = -speed_left;
speed_top = -speed_top;
points += 1;
pointsLabel.Text = points.ToString();
Random r = new Random();
playground.BackColor = Color.FromArgb(r.Next(150, 255), r.Next(150, 255), r.Next(150, 255));
/* SOUND PLAYED HERE */
Player.Play();
}
if(ball.Left <= playground.Left)
{
speed_left = -speed_left;
}
if(ball.Right >= playground.Right)
{
speed_left = -speed_left;
}
if(ball.Top <= playground.Top)
{
speed_top = -speed_top;
}
if(ball.Bottom >= playground.Bottom)
{
timer1.Enabled = false;
gameoverLabel.Visible = true;
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape) { this.Close(); }
if (e.KeyCode == Keys.F1)
{
ball.Top = 50;
ball.Left = 50;
speed_left = 4;
speed_top = 4;
points = 0;
pointsLabel.Text = "";
timer1.Enabled = true;
gameoverLabel.Visible = false;
playground.BackColor = Color.White;
}
}
}
}
I've a txt file with a 360 numbers, I must read all of these and draw a kind of Disc made of FillPie eachone colored in scale of grey due to the value of the list. Until here everything is quite simple.I made a class with the data(value in the txt and degree) of one single fillpie with a Paint method that draw it of the correct color.
this is the code of the class:
class DatoDisco
{
int valoreSpicchio;
int gradi;
public DatoDisco(int valoreTastatore, int gradiLettura)
{
valoreSpicchio = valoreTastatore;
gradi = gradiLettura;
}
public void Clear()
{
valoreSpicchio = 0;
gradi = 0;
}
private int ScalaGrigi()
{
int grigio = 0;
if (valoreSpicchio <= 0)
{
grigio = 125 + (valoreSpicchio / 10);
if (grigio < 0)
grigio = 0;
}
if (valoreSpicchio > 0)
{
grigio = 125 + (valoreSpicchio / 10);
if (grigio > 230)
grigio = 230;
}
return grigio;
}
public void Paint (Graphics grafica)
{
try
{
Brush penna = new SolidBrush(Color.FromArgb(255, ScalaGrigi(), ScalaGrigi(), ScalaGrigi()));
grafica.FillPie(penna, 0, 0, 400, 400, gradi, 1.0f);
}
catch
{
}
}
public int ValoreSpicchio
{
get
{
return valoreSpicchio;
}
}
public int Gradi
{
get
{
return gradi;
}
}
}
here is where I draw everything:
public partial class Samac : Form
{
libnodave.daveOSserialType fds;
libnodave.daveInterface di;
libnodave.daveConnection dc;
int rack = 0;
int slot = 2;
int scalaGrigi = 0;
int angolatura = 0;
List<int> valoriY = new List<int>();
//Disco disco = new Disco();
List<DatoDisco> disco = new List<DatoDisco>();
float[] valoriTastatore = new float[360];
public Samac()
{
InitializeComponent();
StreamReader dataStream = new StreamReader("save.txt");
textBox1.Text = dataStream.ReadLine();
dataStream.Dispose();
for (int i = 0; i <= 360; i++ )
chart1.Series["Series2"].Points.Add(0);
//AggiornaGrafico(textBox1.Text, chart1);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
}
string indirizzoIpPlc
{
get
{
FileIniDataParser parser = new FileIniDataParser();
IniData settings = parser.LoadFile("config.ini");
return settings["PLC_CONNECTION"]["PLC_IP"];
}
}
private void AggiornaGrafico(string nomeFile, Chart grafico, bool online)
{
int max = 0;
int min = 0;
grafico.Series["Series1"].Points.Clear();
grafico.Series["Series2"].Points.Clear();
grafico.Series["Series3"].Points.Clear();
grafico.Series["Series4"].Points.Clear();
grafico.ChartAreas[0].AxisX.Maximum = 360;
grafico.ChartAreas[0].AxisX.Minimum = 0;
grafico.ChartAreas[0].AxisY.Maximum = 500;
grafico.ChartAreas[0].AxisY.Minimum = -500;
String file = nomeFile;
valoriY.Clear();
disco.Clear();
if (online == false)
{
System.IO.File.WriteAllText("save.txt", nomeFile);
}
StreamReader dataStreamGrafico = new StreamReader(file);
StreamReader dataStreamScheda = new StreamReader("Scheda.sch");
string datasample;
string[] scheda = new string[56];
for (int i = 0; i < 56; i++)
{
scheda[i] = dataStreamScheda.ReadLine();
}
dataStreamScheda.Close();
int gradi = 1;
while ((datasample = dataStreamGrafico.ReadLine()) != null)
{
grafico.Series["Series2"].Points.Add(0);
grafico.Series["Series2"].Color = Color.Red;
grafico.Series["Series2"].BorderWidth = 3;
grafico.Series["Series3"].Points.Add(Convert.ToInt32(float.Parse(scheda[5])));
grafico.Series["Series3"].Color = Color.Green;
grafico.Series["Series3"].BorderWidth = 3;
grafico.Series["Series4"].Points.Add(Convert.ToInt32(-float.Parse(scheda[5])));
grafico.Series["Series4"].Color = Color.Green;
grafico.Series["Series4"].BorderWidth = 3;
grafico.Series["Series1"].Points.Add(int.Parse(datasample));
grafico.Series["Series1"].BorderWidth = 5;
valoriY.Add(int.Parse(datasample));
//disco.Add(int.Parse(datasample));
disco.Add(new DatoDisco(int.Parse(datasample), gradi));
gradi++;
}
dataStreamGrafico.Close();
max = Convert.ToInt32(chart1.Series["Series1"].Points.FindMaxByValue().YValues[0]);
min = Convert.ToInt32(chart1.Series["Series1"].Points.FindMinByValue().YValues[0]);
lblCampanatura.Text = (((float)max + min) / 2000.0).ToString();
lblSbandieramento.Text = (((float)max - min) / 1000.0).ToString();
if ((Math.Abs(max) > 800) || (Math.Abs(min) > 800))
{
if (Math.Abs(max) >= Math.Abs(min))
{
chart1.ChartAreas[0].AxisY.Maximum = max + 200;
chart1.ChartAreas[0].AxisY.Minimum = -(max + 200);
}
else
{
chart1.ChartAreas[0].AxisY.Maximum = min + 200;
chart1.ChartAreas[0].AxisY.Minimum = -(min + 200);
}
}
else
{
chart1.ChartAreas[0].AxisY.Maximum = 800;
chart1.ChartAreas[0].AxisY.Minimum = -800;
}
boxGraficaDisco.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
if (result == DialogResult.OK)
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
ToolTip tooltip = new ToolTip();
private int lastX;
private int lastY;
private void chart1_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
int cursorX = Convert.ToInt32(chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));
tooltip.Show("X:" + cursorX.ToString("0.00") + "Y:" + Convert.ToInt32(chart1.Series[0].Points[cursorX].YValues[0]).ToString(), this.chart1, e.Location.X + 20, e.Location.Y + 20);
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
private void button1_Click_1(object sender, EventArgs e)
{
int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5]))+1;
if (File.Exists(textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt"))
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt";
try
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
catch
{
MessageBox.Show("Il File non esiste");
}
}
else
{
MessageBox.Show("Il File non esiste");
}
}
private void btnGrafMeno_Click(object sender, EventArgs e)
{
int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5])) - 1;
if (indice >= 0)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt";
try
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
catch
{
MessageBox.Show("Il File non esiste");
}
}
else
{
MessageBox.Show("Prima lettura disco");
}
}
private void btnConnetti_Click(object sender, EventArgs e)
{
fds.rfd = libnodave.openSocket(102, indirizzoIpPlc);
fds.wfd = fds.rfd;
if (fds.rfd > 0)
{
di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
di.setTimeout(1000000);
dc = new libnodave.daveConnection(di, 0, rack, slot);
int res = dc.connectPLC();
timer1.Start();
// AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
else
{
MessageBox.Show("Impossibile connettersi");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
int res;
res = dc.readBytes(libnodave.daveDB, 21, 40, 1, null);
if (res == 0)
{
var letturaDati = (dc.getS8At(0) & (1 << 0)) != 0;
if (letturaDati == true)
{
int puntatore = 30;
StreamWriter datiDisco = new StreamWriter("DatiDaPlc.csv");
datiDisco.WriteLine("X;" + "C;" + "Z;");
while (puntatore <= 10838)
{
res = dc.readBytes(libnodave.daveDB, 3, puntatore, 192, null);
if (res == 0)
{
for (int i = 0; dc.getU32At(i) != 0; i = i + 12)
{
datiDisco.Write(dc.getU32At(i).ToString() + ";");
datiDisco.Write(dc.getU32At(i + 4).ToString() + ";");
datiDisco.WriteLine(dc.getFloatAt(i + 8).ToString() + ";");
}
}
puntatore = puntatore + 192;
}
datiDisco.Close();
StreamReader lettura = new StreamReader("DatiDaPlc.csv");
StreamWriter scritt = new StreamWriter("Disco.csv");
var titolo = lettura.ReadLine();
var posizioneLettura = lettura.ReadLine();
var posX = posizioneLettura.Split(';');
int minX = Convert.ToInt32(posX[0]) - 5;
int maxX = Convert.ToInt32(posX[0]) + 5;
int contatore = 0;
while (!lettura.EndOfStream)
{
var line = lettura.ReadLine();
var values = line.Split(';');
if ((Convert.ToInt32(values[1]) >= contatore && Convert.ToInt32(values[1]) < contatore + 1000) && (Convert.ToInt32(values[0]) > minX && Convert.ToInt32(values[0]) <= maxX))
{
scritt.WriteLine(Convert.ToInt32(float.Parse(values[2]) * 1000).ToString());
contatore += 1000;
}
}
lettura.Close();
scritt.Close();
AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
}
else
{
timer1.Stop();
MessageBox.Show("Disconnesso");
dc.disconnectPLC();
di.disconnectAdapter();
fds.rfd = libnodave.closeSocket(102);
fds.wfd = fds.rfd;
}
}
}
private void btnDisconnetti_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
dc.disconnectPLC();
di.disconnectAdapter();
fds.rfd = libnodave.closeSocket(102);
fds.wfd = fds.rfd;
timer1.Stop();
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
private void Samac_FormClosing(object sender, FormClosingEventArgs e)
{
if (timer1.Enabled == true)
{
dc.disconnectPLC();
di.disconnectAdapter();
libnodave.closeSocket(102);
timer1.Stop();
}
}
private void button1_Click_2(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
else
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
private void chart2_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
int cursorX = Convert.ToInt32(chart2.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));
int cursorY = Convert.ToInt32(chart2.ChartAreas[0].AxisY.PixelPositionToValue(e.Location.Y));
//tooltip.Show("X:" + chart2.Series[0].Points[cursorX].XValue.ToString() + "Y:" + chart2.Series[0].Points[cursorX].YValues[0].ToString(), this.chart2, e.Location.X + 20, e.Location.Y + 20);
tooltip.Show("X:" + cursorX.ToString() + "Y:#VALY" , this.chart2, e.Location.X + 20, e.Location.Y + 20);
//chart2.Series[0].ToolTip="#VALY";
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
private void boxGraficaDisco_Paint(object sender, PaintEventArgs e)
{
Graphics grafica = e.Graphics;
//disco.Paint(grafica);
foreach (DatoDisco d in disco)
{
d.Paint(grafica);
}
}
private void boxGraficaDisco_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
foreach (DatoDisco d in disco)
{
}
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
}
Now I need that when i go with the mouse over the drawn disc, a tooltip show me the data of the fillPie(degree and value of txt) but i can't figure out how.
Anyone can help me?
this is an image of the disc
Eventually it looks as if all you want is a function to get the angle between the mouse position and the center of the disc..
Here is a function to calculate an angle given two points:
double AngleFromPoints(Point pt1, Point pt2)
{
Point P = new Point(pt1.X - pt2.X, pt1.Y - pt2.Y);
double alpha = 0d;
if (P.Y == 0) alpha = P.X > 0 ? 0d : 180d;
else
{
double f = 1d * P.X / (Math.Sqrt(P.X * P.X + P.Y * P.Y));
alpha = Math.Acos(f) * 180d / Math.PI;
if (P.Y > 0) alpha = 360d - alpha;
}
return alpha;
}
I am doing a program with Emgu.CV in C#
and i receive this error when compiling
An unhandled exception of type 'System.IO.FileNotFoundException'
occurred in InAirSignature.exe
Additional information: Could not load file or assembly 'Emgu.CV.UI,
Version=2.9.0.1922, Culture=neutral, PublicKeyToken=7281126722ab4438'
or one of its dependencies. The system cannot find the file specified.
any ideas how to solve?
for my coding, a webcam is needed.
below is my coding.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.GPU;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.UI;
using Emgu.CV.CvEnum;
using System.Diagnostics;
using System.Windows.Forms.DataVisualization.Charting;
using Emgu.CV.ML.Structure;
using Emgu.CV.ML;
using System.IO;
namespace InAirSignature
{
public partial class Main : Form
{
private Capture capture;
private Rectangle roi;
private Bgr redOrGreen;
private const int NUMBERS_OF_FRAMES = 90,
NUMBERS_OF_SIGN = 6,
NUMBERS_OF_FEATURES = 3, // X Y Averange
FEATURE_X = 0,
FEATURE_Y = 1,
TEST = NUMBERS_OF_SIGN - 1,
NUMBERS_OF_NEURONS = 15;
private const int frameHeight = 640;
private const int frameWidth = 480;
private List<Image<Gray, Byte>> imgGrayBuffer = new List<Image<Gray, Byte>>();
private List<int> pointX = new List<int>();
private List<int> pointY = new List<int>();
private int[][][] pointsOfSign, distanceBetweenPoints;
private double[] finalAverage;
private int[][] pointsOfSignReference;
private int[] distanceBetweenPointsForRefenceAndTest;
private int[] classes = {0,0,0,0,1,1,1,1,1,1};
private int resultMode = 0;
private int recordSign = 0;
private bool record = false;
private int counter = 0;
private Stopwatch stopWatch;
private const string SYSTEM_MESSAGE = "System Message: ",
WELCOME_MESSAGE = "Welcome! ";
Matrix<int> layerSize;
MCvANN_MLP_TrainParams parameters;
ANN_MLP network;
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Form /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Form
public Main()
{
InitializeComponent();
#region Initialize graph
chartX.Series.Add("X1");
chartX.Series.Add("X2");
chartX.Series.Add("X3");
chartX.Series.Add("X4");
chartX.Series.Add("X5");
chartX.Series.Add("Xtest");
chartX.Series.Add("Xref");
chartY.Series.Add("Y1");
chartY.Series.Add("Y2");
chartY.Series.Add("Y3");
chartY.Series.Add("Y4");
chartY.Series.Add("Y5");
chartY.Series.Add("Ytest");
chartY.Series.Add("Yref");
chartX.Series["X1"].Color = Color.Blue;
chartX.Series["X2"].Color = Color.Green;
chartX.Series["X3"].Color = Color.Red;
chartX.Series["X4"].Color = Color.Pink;
chartX.Series["X5"].Color = Color.Purple;
chartX.Series["Xtest"].Color = Color.Aqua;
chartX.Series["Xref"].Color = Color.BlueViolet;
chartY.Series["Y1"].Color = Color.Blue;
chartY.Series["Y2"].Color = Color.Green;
chartY.Series["Y3"].Color = Color.Red;
chartY.Series["Y4"].Color = Color.Pink;
chartY.Series["Y5"].Color = Color.Purple;
chartY.Series["Ytest"].Color = Color.Aqua;
chartY.Series["Yref"].Color = Color.BlueViolet;
chartX.Series["X1"].ChartType = SeriesChartType.FastLine;
chartX.Series["X2"].ChartType = SeriesChartType.FastLine;
chartX.Series["X3"].ChartType = SeriesChartType.FastLine;
chartX.Series["X4"].ChartType = SeriesChartType.FastLine;
chartX.Series["X5"].ChartType = SeriesChartType.FastLine;
chartX.Series["Xtest"].ChartType = SeriesChartType.FastLine;
chartX.Series["Xref"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y1"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y2"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y3"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y4"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y5"].ChartType = SeriesChartType.FastLine;
chartY.Series["Ytest"].ChartType = SeriesChartType.FastLine;
chartY.Series["Yref"].ChartType = SeriesChartType.FastLine;
#endregion
#region Initialize Neural Network
layerSize = new Matrix<int>(new int[] { NUMBERS_OF_FEATURES, NUMBERS_OF_NEURONS, 1 });
parameters = new MCvANN_MLP_TrainParams();
parameters.term_crit = new MCvTermCriteria(10, 1.0e-8);
parameters.train_method = Emgu.CV.ML.MlEnum.ANN_MLP_TRAIN_METHOD.BACKPROP;
parameters.bp_dw_scale = 0.1;
parameters.bp_moment_scale = 0.1;
network = new ANN_MLP(layerSize, Emgu.CV.ML.MlEnum.ANN_MLP_ACTIVATION_FUNCTION.SIGMOID_SYM, 1.0, 1.0);
#endregion
#region Initialize camera
capture = new Capture();
capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, frameHeight);
capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, frameWidth);
#endregion
initializeData();
roi = new Rectangle(338, 2, 300, 300);
redOrGreen = new Bgr(Color.Red);
lblSM.Text = SYSTEM_MESSAGE + WELCOME_MESSAGE;
updateResult();
updateGraph();
Application.Idle += processFrame;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
capture.Stop();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Button /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Button
private void btnSign_Click(object sender, EventArgs e)
{
stopWatch = Stopwatch.StartNew();
record = true;
redOrGreen = new Bgr(Color.LightGreen);
if (sender == btnSign1)
recordSign = 1;
else if (sender == btnSign2)
recordSign = 2;
else if (sender == btnSign3)
recordSign = 3;
else if (sender == btnSign4)
recordSign = 4;
else if (sender == btnSign5)
recordSign = 5;
else
recordSign = 6;
}
private void btnPredict_Click(object sender, EventArgs e)
{
float predicted = predict(new int[,] { { distanceBetweenPointsForRefenceAndTest[0], distanceBetweenPointsForRefenceAndTest[1], distanceBetweenPointsForRefenceAndTest[2] } }, network);
string result;
if (predicted < Convert.ToDouble(lblThreshold.Text))
result = "Success";
else
result = "Fail";
lblSM.Text = SYSTEM_MESSAGE + "Matching result - " + result + ", value: " + predicted.ToString();
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (tbId.Text == "")
throw new Exception();
saveSignReference();
network.Save(tbId.Text);
lblSM.Text = SYSTEM_MESSAGE + "Saved";
}
catch
{
lblSM.Text = SYSTEM_MESSAGE + "ID blank";
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
if (tbId.Text == "")
throw new Exception();
loadSignReference();
network.Load(tbId.Text);
lblSM.Text = SYSTEM_MESSAGE + "Loaded";
btnVerify.Enabled = true;
btnSave.Enabled = true;
cbAuto.Enabled = true;
updateGraph();
}
catch
{
lblSM.Text = SYSTEM_MESSAGE + "Invalid ID";
}
}
private void btnTrainNN_Click(object sender, EventArgs e)
{
btnVerify.Enabled = true;
btnSave.Enabled = true;
cbAuto.Enabled = true;
trainNN();
}
private void btnClear_Click(object sender, EventArgs e)
{
initializeData();
updateGraph();
updateResult();
calculateResult();
rbS1.PerformClick();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Check Box /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Check Box
private void cbBinaryImage_CheckedChanged(object sender, EventArgs e)
{
ibBinaryImage.Visible = !ibBinaryImage.Visible;
}
private void cbResult_CheckedChanged(object sender, EventArgs e)
{
pnlResult.Visible = !pnlResult.Visible;
}
private void cbSign_CheckedChanged(object sender, EventArgs e)
{
if (sender == cbSign1)
{
chartX.Series["X1"].Enabled = !chartX.Series["X1"].Enabled;
chartY.Series["Y1"].Enabled = !chartY.Series["Y1"].Enabled;
}
else if (sender == cbSign2)
{
chartX.Series["X2"].Enabled = !chartX.Series["X2"].Enabled;
chartY.Series["Y2"].Enabled = !chartY.Series["Y2"].Enabled;
}
else if (sender == cbSign3)
{
chartX.Series["X3"].Enabled = !chartX.Series["X3"].Enabled;
chartY.Series["Y3"].Enabled = !chartY.Series["Y3"].Enabled;
}
else if (sender == cbSign4)
{
chartX.Series["X4"].Enabled = !chartX.Series["X4"].Enabled;
chartY.Series["Y4"].Enabled = !chartY.Series["Y4"].Enabled;
}
else if (sender == cbSign5)
{
chartX.Series["X5"].Enabled = !chartX.Series["X5"].Enabled;
chartY.Series["Y5"].Enabled = !chartY.Series["Y5"].Enabled;
}
else if (sender == cbSignRefer)
{
chartX.Series["Xref"].Enabled = !chartX.Series["Xref"].Enabled;
chartY.Series["Yref"].Enabled = !chartY.Series["Yref"].Enabled;
}
else
{
chartX.Series["Xtest"].Enabled = !chartX.Series["Xtest"].Enabled;
chartY.Series["Ytest"].Enabled = !chartY.Series["Ytest"].Enabled;
}
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Radio Button /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Radio Button
private void rbS_CheckedChanged(object sender, EventArgs e)
{
if (sender == rbS1)
resultMode = 0;
else if (sender == rbS2)
resultMode = 1;
else if (sender == rbS3)
resultMode = 2;
else if (sender == rbS4)
resultMode = 3;
else
resultMode = 4;
updateResult();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Text Box /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Text Box
private void tbId_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
btnLoad.PerformClick();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Function /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
private void processFrame(object sender, EventArgs arg)
{
Image<Bgr, Byte> frame = capture.QueryFrame().Flip(FLIP.HORIZONTAL);
Image<Bgr, Byte> frameCrop = frame.Copy(new Rectangle(338, 2, 300, 300)); // copy a crop
Image<Gray, Byte> frameBinary;
if (counter == (NUMBERS_OF_FRAMES - 2))
redOrGreen = new Bgr(Color.Red);
frame.Draw(roi, redOrGreen, 2);
frameBinary = ImageProcessing.getSkin(frameCrop);
if (record == true)
{
imgGrayBuffer.Add(frameBinary);
counter++;
if (counter == NUMBERS_OF_FRAMES)
{
while (imgGrayBuffer.Count() > 0)
{
Point point = ImageProcessing.getHighestPoint(imgGrayBuffer.ElementAt(0));
imgGrayBuffer.RemoveAt(0);
pointX.Add(point.X);
pointY.Add(point.Y);
}
pointsOfSign[recordSign - 1][FEATURE_X] = pointX.ToArray();
pointsOfSign[recordSign - 1][FEATURE_X] = normalizeSize(pointsOfSign[recordSign - 1][FEATURE_X]);
pointsOfSign[recordSign - 1][FEATURE_X] = normalizePosition(pointsOfSign[recordSign - 1][FEATURE_X]);
pointsOfSign[recordSign - 1][FEATURE_Y] = pointY.ToArray();
pointsOfSign[recordSign - 1][FEATURE_Y] = normalizeSize(pointsOfSign[recordSign - 1][FEATURE_Y]);
pointsOfSign[recordSign - 1][FEATURE_Y] = normalizePosition(pointsOfSign[recordSign - 1][FEATURE_Y]);
pointX.Clear();
pointY.Clear();
calculateResult();
updateResult();
updateGraph();
record = false;
stopWatch.Stop();
lblSM.Text = SYSTEM_MESSAGE + "Time taken => " + stopWatch.Elapsed.TotalSeconds.ToString() + " seconds.";
if (cbAuto.Checked == true && recordSign == 6)
btnVerify.PerformClick();
recordSign = 0;
counter = 0;
}
}
ibMain.Image = frame;
if(cbBinaryImage.Checked == true)
ibBinaryImage.Image = frameBinary;
}
private int[] normalizePosition(int[] position)
{
int min = int.MaxValue,
max = int.MinValue;
for (int i = 0; i < position.Count(); i++)
{
if (position[i] > max)
max = position[i];
if (position[i] < min)
min = position[i];
}
int midPoint = (min + max) / 2;
for (int i = 0; i < position.Count(); i++)
position[i] -= midPoint;
return position;
}
private int[] normalizeSize(int[] position)
{
const int targetSize = 300;
int min = int.MaxValue,
max = int.MinValue;
for (int i = 0; i < position.Count(); i++)
{
if (position[i] > max)
max = position[i];
if (position[i] < min)
min = position[i];
}
int height = max - min;
if (height != 0)
height = targetSize / height;
for (int i = 0; i < position.Count(); i++)
position[i] *= height;
return position;
}
private void updateGraph()
{
foreach (var series in chartX.Series)
series.Points.Clear();
foreach (var series in chartY.Series)
series.Points.Clear();
for (int i = 0; i < NUMBERS_OF_FRAMES; i++)
{
chartX.Series["X1"].Points.AddXY
(i, pointsOfSign[0][FEATURE_X][i]);
chartX.Series["X2"].Points.AddXY
(i, pointsOfSign[1][FEATURE_X][i]);
chartX.Series["X3"].Points.AddXY
(i, pointsOfSign[2][FEATURE_X][i]);
chartX.Series["X4"].Points.AddXY
(i, pointsOfSign[3][FEATURE_X][i]);
chartX.Series["X5"].Points.AddXY
(i, pointsOfSign[4][FEATURE_X][i]);
chartX.Series["Xref"].Points.AddXY
(i, pointsOfSignReference[0][i]);
chartX.Series["Xtest"].Points.AddXY
(i, pointsOfSign[5][FEATURE_X][i]);
chartY.Series["Y1"].Points.AddXY
(i, pointsOfSign[0][FEATURE_Y][i]);
chartY.Series["Y2"].Points.AddXY
(i, pointsOfSign[1][FEATURE_Y][i]);
chartY.Series["Y3"].Points.AddXY
(i, pointsOfSign[2][FEATURE_Y][i]);
chartY.Series["Y4"].Points.AddXY
(i, pointsOfSign[3][FEATURE_Y][i]);
chartY.Series["Y5"].Points.AddXY
(i, pointsOfSign[4][FEATURE_Y][i]);
chartY.Series["Yref"].Points.AddXY
(i, pointsOfSignReference[1][i]);
chartY.Series["Ytest"].Points.AddXY
(i, pointsOfSign[5][FEATURE_Y][i]);
}
}
private void calculateResult()
{
int average = 0;
for (int i = 0; i < NUMBERS_OF_SIGN - 1; i++)
for (int j = 0; j < NUMBERS_OF_SIGN - 1; j++)
{
for (int k = 0; k < NUMBERS_OF_FEATURES - 1; k++)
{
distanceBetweenPoints[i][j][k] = DTW.Distance(pointsOfSign[i][k], pointsOfSign[j][k]);
average += distanceBetweenPoints[i][j][k];
}
distanceBetweenPoints[i][j][NUMBERS_OF_FEATURES - 1] = average / 2;
average = 0;
}
for (int i = 0; i < NUMBERS_OF_SIGN -1; i++)
{
finalAverage[i] = 0.0;
for (int j = 0; j < NUMBERS_OF_SIGN; j++)
finalAverage[i] += distanceBetweenPoints[i][j][NUMBERS_OF_FEATURES - 1];
finalAverage[i] /= NUMBERS_OF_SIGN - 2;
}
average = 0;
for (int k = 0; k < NUMBERS_OF_FEATURES - 1; k++)
{
distanceBetweenPointsForRefenceAndTest[k] = DTW.Distance(pointsOfSignReference[k], pointsOfSign[TEST][k]);
average += distanceBetweenPointsForRefenceAndTest[k];
}
distanceBetweenPointsForRefenceAndTest[NUMBERS_OF_FEATURES - 1] = average / 2;
}
private void updateResult()
{
tbResult1X.Text = distanceBetweenPoints[resultMode][0][0].ToString();
tbResult1Y.Text = distanceBetweenPoints[resultMode][0][1].ToString();
tbResult1A.Text = distanceBetweenPoints[resultMode][0][2].ToString();
tbResult2X.Text = distanceBetweenPoints[resultMode][1][0].ToString();
tbResult2Y.Text = distanceBetweenPoints[resultMode][1][1].ToString();
tbResult2A.Text = distanceBetweenPoints[resultMode][1][2].ToString();
tbResult3X.Text = distanceBetweenPoints[resultMode][2][0].ToString();
tbResult3Y.Text = distanceBetweenPoints[resultMode][2][1].ToString();
tbResult3A.Text = distanceBetweenPoints[resultMode][2][2].ToString();
tbResult4X.Text = distanceBetweenPoints[resultMode][3][0].ToString();
tbResult4Y.Text = distanceBetweenPoints[resultMode][3][1].ToString();
tbResult4A.Text = distanceBetweenPoints[resultMode][3][2].ToString();
tbResult5X.Text = distanceBetweenPoints[resultMode][4][0].ToString();
tbResult5Y.Text = distanceBetweenPoints[resultMode][4][1].ToString();
tbResult5A.Text = distanceBetweenPoints[resultMode][4][2].ToString();
tbTotalA.Text = finalAverage[resultMode].ToString();
tbRatX.Text = distanceBetweenPointsForRefenceAndTest[0].ToString();
tbRatY.Text = distanceBetweenPointsForRefenceAndTest[1].ToString();
tbRatA.Text = distanceBetweenPointsForRefenceAndTest[2].ToString();
}
private float predict(int[,] testingSetInt, ANN_MLP network)
{
Matrix<float> testingSet = new Matrix<float>(Utility.arrayIntToFloat(testingSetInt)),
prediction = new Matrix<float>(1, 1);
network.Predict(testingSet, prediction);
return prediction.Data[0, 0];
}
private ANN_MLP trainNN(int[] trainingClassesInt, int[,] trainingSetInt)
{
int numbers_of_training_set = 4,
numbers_of_data = trainingSetInt.GetUpperBound(0) + 1;
Matrix<float> trainingSet = new Matrix<float>(Utility.arrayIntToFloat(trainingSetInt)),
trainingClasses = new Matrix<float>(Utility.arrayIntToFloat(trainingClassesInt));
Matrix<float> trainingSetPositive = trainingSet.GetRows(0, numbers_of_training_set, 1);
Matrix<float> trainingSetNegative = trainingSet.GetRows(numbers_of_training_set, numbers_of_data, 1);
Matrix<float> trainClassesPositive = trainingClasses.GetRows(0, numbers_of_training_set, 1);
Matrix<float> trainClassesNegative = trainingClasses.GetRows(numbers_of_training_set, numbers_of_data, 1);
ANN_MLP network = new ANN_MLP(layerSize, Emgu.CV.ML.MlEnum.ANN_MLP_ACTIVATION_FUNCTION.SIGMOID_SYM, 1.0, 1.0);
network.Train(trainingSet, trainingClasses, null, (Matrix<int>)null, parameters, Emgu.CV.ML.MlEnum.ANN_MLP_TRAINING_FLAG.DEFAULT);
return network;
}
private void trainNN()
{
// Getting the most closest signature
int index = 0;
for (int i = 1; i < NUMBERS_OF_SIGN - 1; i++)
if (finalAverage[index] > finalAverage[i])
index = i;
lblSM.Text = SYSTEM_MESSAGE + "Sign # no." + (index + 1).ToString() + " is the reference now!";
for (int i = 0; i < NUMBERS_OF_FEATURES - 1; i++)
pointsOfSignReference[i] = pointsOfSign[index][i];
int total_training_data = 10; // 4 positive, 6 negative
int total_features_for_training = 3; // dtw of x, dtw of y, width of sign
int[,] trainingSet = new int[total_training_data, total_features_for_training];
// Get the distance (x and y) between closest signature and the rest of signature into training set
// Feature 0 and 1 => dtw of x, dtw of y
for (int i = 0, current = 0; i < NUMBERS_OF_SIGN - 1; i++)
{
if (i != index)
{
for (int j = 0; j < NUMBERS_OF_FEATURES; j++)
trainingSet[current, j] = distanceBetweenPoints[i][index][j];
current++;
}
}
// Generate negative data
int[] max_value = new int[NUMBERS_OF_FEATURES];
int[] min_value = new int[NUMBERS_OF_FEATURES];
for (int i = 0; i < NUMBERS_OF_SIGN - 1; i++)
{
for (int j = 0; j < NUMBERS_OF_FEATURES && i != index; j++)
{
if (max_value[j] < distanceBetweenPoints[i][index][j])
max_value[j] = distanceBetweenPoints[i][index][j];
if (min_value[j] > distanceBetweenPoints[i][index][j])
min_value[j] = distanceBetweenPoints[i][index][j];
}
}
Random random = new Random();
In your project, right click on the References, then look for the Emgu.CV.UI assembly and select it.
I am working on an application for WP8, in my code I want to assign indexes to buttons like in arrays. Reason is that I want to operate buttons with buttons (i.e one button that is pressed activate other buttons)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class LEDButton : Button
{
public const int LEDWidth = 50;
public const int LEDHeight = 30;
public LEDButton()
{
BackColor = Color.Tan;//inner color
//BackColor = Color.FromArgb(0, 64, 0);
ForeColor = Color.Yellow;//outline
FlatStyle = FlatStyle.Popup;//Button style
Size = new Size(LEDWidth, LEDHeight);
UseVisualStyleBackColor = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
LEDButton[,] b = new LEDButton[4, 4];
for (int y = 0; y < b.GetUpperBound(0); y++)
{
for (int x = 0; x < b.GetUpperBound(1); x++)
{
b[y, x] = new LEDButton()
{
//put button properties here
Name = "button" + y.ToString() + x.ToString(),//String.Format("Button{0}{1}", y, x),
TabIndex = 10 * y + x,
Text = y.ToString() + x.ToString(),
Location = new Point(LEDButton.LEDWidth * x + 20, LEDButton.LEDHeight * y + 20)
};
// b[y, x].Click += button_Click;
}
}
// add buttons to controls
for (int y = 0; y < b.GetUpperBound(0); y++)
for (int x = 0; x < b.GetUpperBound(1); x++)
this.Controls.Add(b[y, x]);
}
}
}
If I have understood your question properly, you should rely on an array of delegates. Here you have a correction of your code assigning dynamically 4 different methods to 4 different buttons:
namespace test2
{
public partial class Form1 : Form
{
public delegate void button_click(object sender, EventArgs e);
public static button_click[] clickMethods = new button_click[4];
public Form1()
{
InitializeComponent();
}
public class LEDButton : Button
{
public const int LEDWidth = 50;
public const int LEDHeight = 30;
public LEDButton()
{
BackColor = Color.Tan;//inner color
//BackColor = Color.FromArgb(0, 64, 0);
ForeColor = Color.Yellow;//outline
FlatStyle = FlatStyle.Popup;//Button style
Size = new Size(LEDWidth, LEDHeight);
UseVisualStyleBackColor = false;
}
}
private void Form1_Load(object sender, EventArgs e)
{
clickMethods[0] = buttonGeneric_Click_1;
clickMethods[1] = buttonGeneric_Click_2;
clickMethods[2] = buttonGeneric_Click_3;
clickMethods[3] = buttonGeneric_Click_4;
}
private void buttonGeneric_Click_1(object sender, EventArgs e)
{
}
private void buttonGeneric_Click_2(object sender, EventArgs e)
{
}
private void buttonGeneric_Click_3(object sender, EventArgs e)
{
}
private void buttonGeneric_Click_4(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
LEDButton[,] b = new LEDButton[4, 4];
for (int y = 0; y < b.GetUpperBound(0); y++)
{
for (int x = 0; x < b.GetUpperBound(1); x++)
{
b[y, x] = new LEDButton()
{
//put button properties here
Name = "button" + y.ToString() + x.ToString(),//String.Format("Button{0}{1}", y, x),
TabIndex = 10 * y + x,
Text = y.ToString() + x.ToString(),
Location = new Point(LEDButton.LEDWidth * x + 20, LEDButton.LEDHeight * y + 20)
};
if (y <= 3)
{
b[y, x].Click += new System.EventHandler(clickMethods[y]);
}
}
}
// add buttons to controls
for (int y = 0; y < b.GetUpperBound(0); y++)
for (int x = 0; x < b.GetUpperBound(1); x++)
this.Controls.Add(b[y, x]);
}
}
}
--- loop ---
Button abc = new Button();
abc.Name = loopCounter.ToString();
--- loop ---
This will help you to assigning indexes,
Don't use array of Button, it is useless!