I can't understand why this code is not working. (C#) - c#

I'm new with C# and to learn, I'm watching and trying exemple from the web.
I saw this exemple:
using System;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Speech.Recognition;
namespace MouseController
{
public partial class Form1 : Form
{
SpeechRecognitionEngine recognitionEngine;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Initialize();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
recognitionEngine.RecognizeAsyncStop();
}
private void Initialize()
{
recognitionEngine = new SpeechRecognitionEngine();
recognitionEngine.SetInputToDefaultAudioDevice();
recognitionEngine.SpeechRecognized += (s, args) =>
{
string line = "";
foreach (RecognizedWordUnit word in args.Result.Words)
{
if (word.Confidence > 0.5f)
line += word.Text + " ";
}
string command = line.Trim();
switch (command)
{
case "left":
MoveMouse(Cursor.Position.X - 50, Cursor.Position.Y);
break;
case "right":
MoveMouse(Cursor.Position.X + 50, Cursor.Position.Y);
break;
case "up":
MoveMouse(Cursor.Position.X, Cursor.Position.Y - 50);
break;
case "down":
MoveMouse(Cursor.Position.X, Cursor.Position.Y + 50);
break;
}
txtOutput.Text += line;
txtOutput.Text += Environment.NewLine;
};
recognitionEngine.UnloadAllGrammars();
recognitionEngine.LoadGrammar(CreateGrammars());
recognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
}
private Grammar CreateGrammars()
{
Choices commandChoices = new Choices("left", "right", "up", "down");
GrammarBuilder grammarBuilder = new GrammarBuilder();
grammarBuilder.Append(commandChoices);
return new Grammar(grammarBuilder);
}
private void MoveMouse(int x, int y)
{
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(x, y);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
}
}
But nothing happens when I say "up", "down", "left" or "right"...
I also tried this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Speech.Recognition;
namespace SpeechRecognitionExample
{
public partial class Form1 : Form
{
private SpeechRecognitionEngine recognitionEngine;
public Form1()
{
InitializeComponent();
recognitionEngine = new SpeechRecognitionEngine();
recognitionEngine.SetInputToDefaultAudioDevice();
recognitionEngine.SpeechRecognized += (s, args) =>
{
foreach (RecognizedWordUnit word in args.Result.Words)
{
if (word.Confidence > 0.8f)
txtOutput.Text += word.Text + " ";
}
txtOutput.Text += Environment.NewLine;
};
recognitionEngine.LoadGrammar(new DictationGrammar());
}
private void btnStart_Click(object sender, EventArgs e)
{
recognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
}
private void btnStop_Click(object sender, EventArgs e)
{
recognitionEngine.RecognizeAsyncStop();
}
}
}
And it's not working...
In both of these codes I don't get any errors from Visual Studio.
Why isn't it working?
I checked my microphone and it's working.

Set a breakpoint at the beginning of Initialize() and also on the lambda statement where it says string line = "";. Step through each line to and watch the values of the variables. If you don't get any hits on these breakpoints, then there is something wrong with the engine settings or the input device, I would guess.
Also, you note that you are concatenating multiple words on line and then looking for a single word on the switch statement. If you get multiple words like "up up", it won't match any of your case conditions.
Let us know what you find and we might be able to help you better.

Related

how can use sender and tags together in c#?

I want develop a calculator by using c#, and I do not use method click for all button from 0 to 9 I want I have just one method and if I click the each button wrote in textbox by using sender and tags.
best regards
enter code here
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 Final
{
public partial class Form1 : Form
{
bool names;
int counter;
string name;
double ans, num;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void button6_Click(object sender, EventArgs e)
{
textBox1.Text += "1";
counter++;
again();
}
private void button7_Click(object sender, EventArgs e)
{
textBox1.Text += "2";
counter++;
again();
}
private void button8_Click(object sender, EventArgs e)
{
textBox1.Text += "3";
counter++;
again();
}
You can have just one handler for all digit buttons, and then you can extract its value like this:
int num = int.Parse(((Button)sender).Text);
This assumes that you set the Text property of the buttons to: 0,1,2..9
You can access the Tag property just like the Text:
var txt = ((Button)sender).Tag).ToString();
textBox1.Text += txt;
Set .Tag to correspondent value and then retrieve it from sender by casting it to Button type.
private void button_Click(object sender, EventArgs e)
{
var button = (Button)sender;
textBox1.Text += button.Tag.ToString();
counter++;
again();
}
public Form1()
{
InitializeComponent();
button1.Tag = 1;
button1.Click += button_Click;
button2.Tag = 2;
button2.Click += button_Click;
// and so on for other buttons
}

Writing to CSV File in C#

I am creating a clock for clocking into a business. Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
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.IO;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
String Code;
String Name;
String InOut;
Boolean Luke = true;
String csvPath = "C:/users/luke/documents/C#/csvProject.csv";
StringBuilder Header = new StringBuilder();
StringBuilder csvData = new StringBuilder();
public Form1()
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
TopMost = true;
Header.AppendLine("Timestamp, Name");
File.AppendAllText(csvPath, Header.ToString());
textBox1.Font = new Font("Arial", 30, FontStyle.Bold);
}
private void button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
Code = Code + button.Text;
textBox1.Text = Code;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
FormBorderStyle = FormBorderStyle.Sizable;
WindowState = FormWindowState.Normal;
TopMost = false;
}
}
private void button13_Click(object sender, EventArgs e)
{
//clear
Code = null;
textBox1.Text = Code;
}
private void button10_Click(object sender, EventArgs e)
{
//in or out
DateTime timeStamp = DateTime.Now;
if (Code == "123")
{
Name = "Luke";
}
Button button = (Button)sender;
csvData.AppendLine(timeStamp + "," + Name + "," + button.Text);
File.AppendAllText(csvPath, csvData.ToString());
Code = null;
textBox1.Text = Code;
}
private void button14_Click(object sender, EventArgs e)
{
}
}
}
My layout consists of a number pad, in button, and out button. When the user presses the in button after they enter their code, the program should write in the CSV file: Timestamp, Name, In. When I tested the code by clocking in, the program writes one row correctly. When I clock in and then clock out, it creates two rows of me clocking in and one row of me clocking out. I was wondering if anyone could help me find what is going wrong in the code. Thanks.
You need to empty csvData after writing it to the file.

How can i print a listbox list in c# windows form app?

I'm currently having issues with my code in terms of getting a printing option to show up when thy click a specific button.
I am making a reminder program and was just experimenting. Also would like to know the most efficient way to add a daily notification system to my program
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.Net.Mail;
using System.IO;
using System.Drawing.Printing;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
namespace simpleapp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add("Reminder: " + textBox1.Text);
}
private void input_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
listBox1.Items.Add("Reminder: " + textBox1.Text );
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int rmd = listBox1.SelectedIndices.Count - 1; rmd >= 0; rmd--)
{
listBox1.Items.RemoveAt(listBox1.SelectedIndices[rmd]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.SelectionMode = SelectionMode.MultiExtended;
}
private void button6_Click(object sender, EventArgs e)
{
FAQ faqs = new FAQ();
faqs.Show();
}
// When the Button is Clicked the List is saved in a ".txt file format for the user to view later
private void button3_Click(object sender, EventArgs e)
{
var Savingfileas = new SaveFileDialog();
Savingfileas.Filter = "Text (*.txt)|*.txt ";
if (Savingfileas.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (var Reminder = new StreamWriter(Savingfileas.FileName, false))
foreach (var item in listBox1.Items)
Reminder.Write(item.ToString() + Environment.NewLine);
MessageBox.Show("File has been successfully saved"+ '\n' + "Thank you for using the Remindr program");
}
}
private void button4_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
Email_Client emc = new Email_Client();
emc.Show();
}
}
}
You have a few options. One is to graphically layout a print document and iterate through your listbox while drawing the text in the textbox using x and y coordinates. A better way would be to get your listbox items into a dataset and use it to generate a report. Are you storing these items in a database for retrieval? Here's a link that should help you get started. The tutorial is in VB.Net but there's only a small amount of code to this and should be easy to repeat using C# code.
Here is an absolutely minimal example of printing a ListBox.
It assumes your ListBox contains strings and shows a PrintPreviewDialog; it sets the page unit to mm, do pick a unit you are comfortable with..!
Of course you may chose one or more different fonts etc..
private PrintDocument document = new PrintDocument();
private void printButton_Click(object sender, EventArgs e)
{
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = document;
ppd.Document.DocumentName = "TESTING";
document.PrintPage += document_PrintPage;
ppd.ShowDialog();
}
void document_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
int leading = 5;
int leftMargin = 25;
int topMargin = 10;
// a few simple formatting options..
StringFormat FmtRight = new StringFormat() { Alignment = StringAlignment.Far};
StringFormat FmtLeft = new StringFormat() { Alignment = StringAlignment.Near};
StringFormat FmtCenter = new StringFormat() { Alignment = StringAlignment.Near};
StringFormat fmt = FmtRight;
using (Font font = new Font( "Arial Narrow", 12f))
{
SizeF sz = e.Graphics.MeasureString("_|", Font);
float h = sz.Height + leading;
for (int i = 0; i < listBox1.Items.Count; i++)
e.Graphics.DrawString(listBox1.Items[i].ToString(), font , Brushes.Black,
leftMargin, topMargin + h * i, fmt);
}
}
The actual printing is triggered when the user clicks the printer symbol in the dialog.
Note that there are more StringFormat options!

axWindowsMediaPlayer Crashes Program

I am trying to make a MP3 player with playlist functionality, I have googled everywhere, tried examples, but nothing works. Where the code freezes up at is when p[ListBox1.SelectedIndex + 1]; is called, and I have no idea why it locks up the program. I have tried making an array and selecting the next song through that, but that also didn't work.
I think this is the easiest way to do this. But it locks up the program for some reason.
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.Threading;
using System.Collections;
namespace MusicPlayer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] f, p;
ArrayList playlist = new ArrayList();
private int current_index = 0;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if(openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK){
f = openFileDialog1.SafeFileNames;
p = openFileDialog1.FileNames;
for (int i = 0; i < f.Length; i++)
{
listBox1.Items.Add(f[i]);
}
foreach (string d in open.FileNames)
{
listBox1.Items.Add(d);
}
}
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
axWindowsMediaPlayer1.URL = p[listBox1.SelectedIndex];
}
private void Form1_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.PlayStateChange += new AxWMPLib._WMPOCXEvents_PlayStateChangeEventHandler(MediaPlayer_PlayStateChange);
}
public void MediaPlayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
switch (axWindowsMediaPlayer1.playState)
{
// Locks up here
case WMPLib.WMPPlayState.wmppsReady:
axWindowsMediaPlayer1.URL = p[listBox1.SelectedIndex + 1];
break;
case WMPLib.WMPPlayState.wmppsStopped:
axWindowsMediaPlayer1.URL = p[listBox1.SelectedIndex + 1];
break;
default:
break;
}
}
}
}
EDIT:
I updated my code and this is what it looks like:
public void MediaPlayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
switch (axWindowsMediaPlayer1.playState)
{
case WMPLib.WMPPlayState.wmppsReady:
axWindowsMediaPlayer1.BeginInvoke(new Action(change_song));
break;
case WMPLib.WMPPlayState.wmppsStopped:
axWindowsMediaPlayer1.BeginInvoke(new Action(change_song));
break;
default:
break;
}
}
void change_song()
{
axWindowsMediaPlayer1.URL = p[listBox1.SelectedIndex + 1];
}
But when I run this, it gets stuck at "Media Changing" and eventually does nothing.

creating form object of another form issue?

I have got the following error message when I trying to create the form object of another form.
any one can help me, What is the solution for this error?
the Training_form which needs to be created as object is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Emgu.CV.UI;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using System.IO;
using System.Drawing.Imaging;
using System.Xml;
using System.Threading;
namespace Face_Recognition
{
public partial class Training_Form : Form
{
#region Variables
//Camera specific
Capture grabber;
//Images for finding face
Image<Bgr, Byte> currentFrame;
Image<Gray, byte> result = null;
Image<Gray, byte> gray_frame = null;
//Classifier
CascadeClassifier Face;
//For aquiring 10 images in a row
List<Image<Gray, byte>> resultImages = new List<Image<Gray, byte>>();
int results_list_pos = 0;
int num_faces_to_aquire = 10;
bool RECORD = false;
//Saving Jpg
List<Image<Gray, byte>> ImagestoWrite = new List<Image<Gray, byte>>();
EncoderParameters ENC_Parameters = new EncoderParameters(1);
EncoderParameter ENC = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100);
ImageCodecInfo Image_Encoder_JPG;
//Saving XAML Data file
List<string> NamestoWrite = new List<string>();
List<string> NamesforFile = new List<string>();
XmlDocument docu = new XmlDocument();
//Variables
Form1 Parent;
#endregion
public Training_Form(Form1 _Parent)
{
InitializeComponent();
Parent = _Parent;
Face = Parent.Face;
//Face = new HaarCascade(Application.StartupPath + "/Cascades/haarcascade_frontalface_alt2.xml");
ENC_Parameters.Param[0] = ENC;
Image_Encoder_JPG = GetEncoder(ImageFormat.Jpeg);
initialise_capture();
}
private void Training_Form_FormClosing(object sender, FormClosingEventArgs e)
{
stop_capture();
Parent.retrain();
Parent.initialise_capture();
}
//Camera Start Stop
public void initialise_capture()
{
grabber = new Capture();
grabber.QueryFrame();
//Initialize the FrameGraber event
Application.Idle += new EventHandler(FrameGrabber);
}
private void stop_capture()
{
Application.Idle -= new EventHandler(FrameGrabber);
if (grabber != null)
{
grabber.Dispose();
}
//Initialize the FrameGraber event
}
//Process Frame
void FrameGrabber(object sender, EventArgs e)
{
//Get the current frame form capture device
currentFrame = grabber.QueryFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//Convert it to Grayscale
if (currentFrame != null)
{
gray_frame = currentFrame.Convert<Gray, Byte>();
//Face Detector
//MCvAvgComp[][] facesDetected = gray_frame.DetectHaarCascade(Face, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20)); //old method
Rectangle[] facesDetected = Face.DetectMultiScale(gray_frame, 1.2, 10, new Size(50, 50), Size.Empty);
//Action for each element detected
for(int i = 0; i< facesDetected.Length; i++)// (Rectangle face_found in facesDetected)
{
//This will focus in on the face from the haar results its not perfect but it will remove a majoriy
//of the background noise
facesDetected[i].X += (int)(facesDetected[i].Height * 0.15);
facesDetected[i].Y += (int)(facesDetected[i].Width * 0.22);
facesDetected[i].Height -= (int)(facesDetected[i].Height * 0.3);
facesDetected[i].Width -= (int)(facesDetected[i].Width * 0.35);
result = currentFrame.Copy(facesDetected[i]).Convert<Gray, byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
result._EqualizeHist();
face_PICBX.Image = result.ToBitmap();
//draw the face detected in the 0th (gray) channel with blue color
currentFrame.Draw(facesDetected[i], new Bgr(Color.Red), 2);
}
if (RECORD && facesDetected.Length > 0 && resultImages.Count < num_faces_to_aquire)
{
resultImages.Add(result);
count_lbl.Text = "Count: " + resultImages.Count.ToString();
if (resultImages.Count == num_faces_to_aquire)
{
ADD_BTN.Enabled = true;
NEXT_BTN.Visible = true;
PREV_btn.Visible = true;
count_lbl.Visible = false;
Single_btn.Visible = true;
ADD_ALL.Visible = true;
RECORD = false;
Application.Idle -= new EventHandler(FrameGrabber);
}
}
image_PICBX.Image = currentFrame.ToBitmap();
}
}
//Saving The Data
private bool save_training_data(Image face_data)
{
try
{
Random rand = new Random();
bool file_create = true;
string facename = "face_" + NAME_PERSON.Text + "_" + rand.Next().ToString() + ".jpg";
while (file_create)
{
if (!File.Exists(Application.StartupPath + "/TrainedFaces/" + facename))
{
file_create = false;
}
else
{
facename = "face_" + NAME_PERSON.Text + "_" + rand.Next().ToString() + ".jpg";
}
}
if(Directory.Exists(Application.StartupPath + "/TrainedFaces/"))
{
face_data.Save(Application.StartupPath + "/TrainedFaces/" + facename, ImageFormat.Jpeg);
}
else
{
Directory.CreateDirectory(Application.StartupPath + "/TrainedFaces/");
face_data.Save(Application.StartupPath + "/TrainedFaces/" + facename, ImageFormat.Jpeg);
}
if (File.Exists(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml"))
{
//File.AppendAllText(Application.StartupPath + "/TrainedFaces/TrainedLabels.txt", NAME_PERSON.Text + "\n\r");
bool loading = true;
while (loading)
{
try
{
docu.Load(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml");
loading = false;
}
catch
{
docu = null;
docu = new XmlDocument();
Thread.Sleep(10);
}
}
//Get the root element
XmlElement root = docu.DocumentElement;
XmlElement face_D = docu.CreateElement("FACE");
XmlElement name_D = docu.CreateElement("NAME");
XmlElement file_D = docu.CreateElement("FILE");
//Add the values for each nodes
//name.Value = textBoxName.Text;
//age.InnerText = textBoxAge.Text;
//gender.InnerText = textBoxGender.Text;
name_D.InnerText = NAME_PERSON.Text;
file_D.InnerText = facename;
//Construct the Person element
//person.Attributes.Append(name);
face_D.AppendChild(name_D);
face_D.AppendChild(file_D);
//Add the New person element to the end of the root element
root.AppendChild(face_D);
//Save the document
docu.Save(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml");
//XmlElement child_element = docu.CreateElement("FACE");
//docu.AppendChild(child_element);
//docu.Save("TrainedLabels.xml");
}
else
{
FileStream FS_Face = File.OpenWrite(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml");
using (XmlWriter writer = XmlWriter.Create(FS_Face))
{
writer.WriteStartDocument();
writer.WriteStartElement("Faces_For_Training");
writer.WriteStartElement("FACE");
writer.WriteElementString("NAME", NAME_PERSON.Text);
writer.WriteElementString("FILE", facename);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
}
FS_Face.Close();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
//Delete all the old training data by simply deleting the folder
private void Delete_Data_BTN_Click(object sender, EventArgs e)
{
if (Directory.Exists(Application.StartupPath + "/TrainedFaces/"))
{
Directory.Delete(Application.StartupPath + "/TrainedFaces/", true);
Directory.CreateDirectory(Application.StartupPath + "/TrainedFaces/");
}
}
//Add the image to training data
private void ADD_BTN_Click(object sender, EventArgs e)
{
if (resultImages.Count == num_faces_to_aquire)
{
if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
stop_capture();
if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error);
initialise_capture();
}
}
private void Single_btn_Click(object sender, EventArgs e)
{
RECORD = false;
resultImages.Clear();
NEXT_BTN.Visible = false;
PREV_btn.Visible = false;
Application.Idle += new EventHandler(FrameGrabber);
Single_btn.Visible = false;
count_lbl.Text = "Count: 0";
count_lbl.Visible = true;
}
//Get 10 image to train
private void RECORD_BTN_Click(object sender, EventArgs e)
{
if (RECORD)
{
RECORD = false;
}
else
{
if (resultImages.Count == 10)
{
resultImages.Clear();
Application.Idle += new EventHandler(FrameGrabber);
}
RECORD = true;
ADD_BTN.Enabled = false;
}
}
private void NEXT_BTN_Click(object sender, EventArgs e)
{
if (results_list_pos < resultImages.Count - 1)
{
face_PICBX.Image = resultImages[results_list_pos].ToBitmap();
results_list_pos++;
PREV_btn.Enabled = true;
}
else
{
NEXT_BTN.Enabled = false;
}
}
private void PREV_btn_Click(object sender, EventArgs e)
{
if (results_list_pos > 0)
{
results_list_pos--;
face_PICBX.Image = resultImages[results_list_pos].ToBitmap();
NEXT_BTN.Enabled = true;
}
else
{
PREV_btn.Enabled = false;
}
}
private void ADD_ALL_Click(object sender, EventArgs e)
{
for(int i = 0; i<resultImages.Count;i++)
{
face_PICBX.Image = resultImages[i].ToBitmap();
if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error);
Thread.Sleep(100);
}
ADD_ALL.Visible = false;
//restart single face detection
Single_btn_Click(null, null);
}
private void Training_Form_Load(object sender, EventArgs e)
{
}
}
}
the form which needs to create the object of Training_Form is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Runtime.InteropServices;
using System.Threading;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace Face_Recognition
{
public partial class mainwindow : Form
{
public mainwindow()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Form1 childf = new Form1();
childf.ShowDialog();
}
private void mainwindow_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
Training_Form TF = new Training_Form(this);
TF.Show();
}
}
}
It seems that this does not refer to an instance of Form1 but a different Form-type Face_Recognition. But the constructor of Training_Form only accepts Form1 as parameter. So you either have to pass an instance of Form1 if you have one or change the signature of the constructor.
Maybe it's sufficient to use a Form:
public Training_Form(Form _Parent)
{
InitializeComponent();
Parent = _Parent;
Face = Parent.Face;
//Face = new HaarCascade(Application.StartupPath + "/Cascades/haarcascade_frontalface_alt2.xml");
ENC_Parameters.Param[0] = ENC;
Image_Encoder_JPG = GetEncoder(ImageFormat.Jpeg);
initialise_capture();
}
If you need the Form1 you have to pass an instance. You are creating one in button2_Click but just as local variable. You could store it in a field:
Form1 childf = null;
private void button2_Click(object sender, EventArgs e)
{
if(childf == null) childf = new Form1();
childf.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
if(childf == null) childf = new Form1();
Training_Form TF = new Training_Form(childf);
TF.Show();
}
Your Training_Form expects a parameter of type Form1.
While in your code you are trying to supply it with the keyword this. this being the object you are currently in. Since you are calling it from mainwindow you are trying to put a mainwindow type in it, because in this case mainwindow is equal to this.
You probably, by reading your code, mean to put the childf in, or at least, that has the right type.
That would work, but you would have to declare the childf parameter more globally.
Or you should change the type you expect in your constructor to mainwindow that would work as well.
You are sending training form an argument of "this" from your program which is a reference to program so you are getting an invalid argument. You either need to make the call to display the TrainingForm from within Form1 or make Form1 a private instantiated member of the program so you can pass it into the TrainingForm constructor.

Categories

Resources