creating form object of another form issue? - c#

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.

Related

How to prevent loss of Image quality when saving a bitmap image as a .JPG using Winforms

I'm a student working on a GUI using C# Winforms, where the user is able to load an image, paint on it and then save the edited image to his system.
Bitmap b = new Bitmap(imgList);
image.DrawImage(b, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(btm, Point.Empty);
My issue is when I save the edited image from the picturebox it's quality is reduced and it has the heightXwidth of that of the picturebox. I've provided my Form.cs below for reference. Is there any way I can make the edited image to maintain the image quality of the original image?
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SIP_UI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
imagelst = new ImageList();
}
//Declared Variables
private Graphics g;
private Graphics image;
private Bitmap btm;
private SolidBrush c;
private bool drawing = false;
private ImageList imagelst;
private string[] imglst;
private int imgCnt = 1;
private bool saveNxtWasClicked = false;
private bool savePrevWasClicked = false;
private void Form1_Load(object sender, EventArgs e)
{
g = pictureBox1.CreateGraphics();
btm = new Bitmap(pictureBox1.Width, pictureBox1.Height);
image = Graphics.FromImage(btm);
image.Clear(Color.White);
//Status color on default load
pnlStatus.BackColor = Color.DarkGray;
chkbxImageInfo.Checked = false;
if (chkbxImageInfo.Checked == false)
{
txtTestRep.Enabled = false;
txtBoard.Enabled = false;
cmbxPosition.Enabled = false;
}
btnNext.Enabled = true;
btnPrev.Enabled = false;
txtImgNum.Text = "0";
lblTotl.Text = "#";
using (StreamReader streamReaderOpen = new StreamReader("OpenLocation.txt"))
{
string strOpen = streamReaderOpen.ReadLine();
//Check path validity
if (System.IO.Directory.Exists(strOpen))
{
txtOpnPath.Text = strOpen;
}
else
{
txtOpnPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
}
}
using (StreamReader streamReaderSave = new StreamReader("SaveLocation.txt"))
{
string strSave = streamReaderSave.ReadLine();
//Check path validity
if (System.IO.Directory.Exists(strSave))
{
txtSavPath.Text = strSave;
}
else
{
txtSavPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
}
}
using (StreamReader streamReaderCsv = new StreamReader("CsvLocation.txt"))
{
string strCsv = streamReaderCsv.ReadLine();
//Check path validity
if (System.IO.Directory.Exists(strCsv))
{
txtCsvPath.Text = strCsv;
}
else
{
txtCsvPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
}
//Open images from previous folder
if (txtOpnPath.Text.Length > 0)
{
int i = 0;
int numImgs = Directory.GetFiles(txtOpnPath.Text, "*.PNG").Length;
imglst = new string[numImgs];
lblTotl.Text = Convert.ToString(numImgs);
txtImgNum.Text = Convert.ToString(1);
//foreach (var file in Directory.GetFiles(txtOpnPath.Text).Where(f => extensions.Contains(Path.GetExtension(f).ToUpper())))
foreach (var file in Directory.GetFiles(txtOpnPath.Text, "*.PNG"))
{
imglst[i++] = file;
}
if (imglst.Length > 0)
{
drawImage(imglst[0]);
//Added new
bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[0]) + "_MSKD*").Any();
if (exist)
{
pnlStatus.BackColor = Color.Red;
}
else
{
pnlStatus.BackColor = Color.Green;
}
}
else
{
MessageBox.Show("SELECT ANOTHER LOCATION", "NO SUPPORTED IMAGES FOUND", MessageBoxButtons.OK);
txtImgNum.Text = "0";
}
}
}
//Function to draw image into picturebox
private void drawImage(string imgList)
{
Bitmap b = new Bitmap(imgList);
image.DrawImage(b, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(btm, Point.Empty);
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
drawing = false;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
drawing = true;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (drawing)
{
c = new SolidBrush(Color.Gray);
image.FillEllipse(c, e.X - (trackBar1.Value / 2), e.Y - (trackBar1.Value / 2), (trackBar1.Value * 15), (trackBar1.Value * 15));
g.DrawImage(btm, Point.Empty);
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
btnNext.Enabled = true;
lblTotl.Text = "#";
var fd = new System.Windows.Forms.FolderBrowserDialog();
if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int i = 0;
txtOpnPath.Text = fd.SelectedPath;
int numImgs = Directory.GetFiles(txtOpnPath.Text, "*.PNG").Length;
imglst = new string[numImgs];
lblTotl.Text = Convert.ToString(numImgs);
foreach (var file in Directory.GetFiles(txtOpnPath.Text, "*.PNG"))
{
imglst[i++] = file;
}
if (imglst.Length > 0)
{
drawImage(imglst[0]);
txtImgNum.Text = "1";
//Added new
bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[0]) + "_MSKD*").Any();
if (exist)
{
pnlStatus.BackColor = Color.Red;
}
else
{
pnlStatus.BackColor = Color.Green;
}
}
else
{
MessageBox.Show("SELECT ANOTHER LOCATION", "NO SUPPORTED IMAGES FOUND", MessageBoxButtons.OK);
pictureBox1.Image = null;
txtImgNum.Text = "0";
}
using (StreamWriter streamWriter = new StreamWriter("OpenLocation.txt"))
{
streamWriter.WriteLine(txtOpnPath.Text);
}
}
}
private void btnSaveFdr_Click(object sender, EventArgs e)
{
var savFoldr = new System.Windows.Forms.FolderBrowserDialog();
if (savFoldr.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtSavPath.Text = savFoldr.SelectedPath;
using (StreamWriter streamWriter = new StreamWriter("SaveLocation.txt"))
{
streamWriter.WriteLine(txtSavPath.Text);
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
saveNxtWasClicked = true;
savePrevWasClicked = true;
int count = 1;
imgCnt = Convert.ToInt32(txtImgNum.Text);
string imgPath = imglst[imgCnt - 1];
string fileName = Path.GetFileNameWithoutExtension(imgPath) + "_MSKD";
string fileExtnsn = Path.GetExtension(imgPath);
string filePath = txtSavPath.Text + "\\" + fileName + fileExtnsn;
while (File.Exists(filePath))
{
string tempFileName = string.Format("{0}({1})", fileName, count++);
filePath = Path.Combine(txtSavPath.Text, tempFileName + fileExtnsn);
}
btm.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
//Writing to CSV
string csvPath = txtCsvPath.Text + "\\CSVSpec.csv";
if (chkbxImageInfo.Checked == true)
{
if (File.Exists(csvPath))
{
// Initialise stream object with file
using (var wr = new StreamWriter(csvPath, true, Encoding.UTF8))
{
// Collection of image details
var row = new List<string>();
row.Add(Path.GetFileNameWithoutExtension(imgPath));
row.Add(txtTestRep.Text);
row.Add(txtBoard.Text);
row.Add(cmbxPosition.Text);
var sb = new StringBuilder();
foreach (string value in row)
{
// Add a comma before each string
if (sb.Length > 0)
{
sb.Append(",");
}
sb.Append(value);
}
wr.WriteLine(sb.ToString());
}
}
else
{
MessageBox.Show("Please add CSVSpec.csv file in specified location to save Image Information.", "MISSING: TEMPLATE FILE", MessageBoxButtons.OK);
}
}
else
{
}
DialogResult result = MessageBox.Show("IMAGE SAVED", "SAVE DIALOGUE", MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
if (imgCnt != imglst.Length)
{
drawImage(imglst[imgCnt]);
imgCnt++;
txtImgNum.Text = Convert.ToString(imgCnt);
txtTestRep.Text = string.Empty;
txtBoard.Text = string.Empty;
cmbxPosition.SelectedIndex = 0;
saveNxtWasClicked = false;
}
else
{
btnNext.Enabled = false;
}
}
}
private void btnPrev_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtImgNum.Text);
btnNext.Enabled = true;
if (a > 1)
{
a = a - 2;
drawImage(imglst[a]);
txtImgNum.Text = Convert.ToString(a + 1);
txtTestRep.Text = string.Empty;
txtBoard.Text = string.Empty;
cmbxPosition.SelectedIndex = 0;
bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[a]) + "_MSKD*").Any();
if (exist)
{
pnlStatus.BackColor = Color.Red;
}
else
{
pnlStatus.BackColor = Color.Green;
}
}
else
{
btnPrev.Enabled = false;
}
}
private void btnNext_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtImgNum.Text);
btnPrev.Enabled = true;
if (imglst != null && a < imglst.Length)
{
drawImage(imglst[a++]);
txtImgNum.Text = Convert.ToString(a);
txtTestRep.Text = string.Empty;
txtBoard.Text = string.Empty;
cmbxPosition.SelectedIndex = 0;
bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[a - 1]) + "_MSKD*").Any();
if (exist)
{
pnlStatus.BackColor = Color.Red;
}
else
{
pnlStatus.BackColor = Color.Green;
}
}
else
{
btnNext.Enabled = false;
}
}
private void txtImgNum_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
int imgNum = Convert.ToInt32(txtImgNum.Text) - 1;
drawImage(imglst[imgNum]);
}
}
private void chkbxImageInfo_CheckedChanged(object sender, EventArgs e)
{
if (chkbxImageInfo.Checked)
{
txtTestRep.Enabled = true;
txtBoard.Enabled = true;
cmbxPosition.Enabled = true;
}
else
{
txtTestRep.Enabled = false;
txtBoard.Enabled = false;
cmbxPosition.Enabled = false;
}
}
private void btnClear_Click(object sender, EventArgs e)
{
int imgNum = Convert.ToInt32(txtImgNum.Text) - 1;
drawImage(imglst[imgNum]);
}
private void btnCsv_Click(object sender, EventArgs e)
{
var csvFoldr = new System.Windows.Forms.FolderBrowserDialog();
if (csvFoldr.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtCsvPath.Text = csvFoldr.SelectedPath;
using (StreamWriter streamWriter = new StreamWriter("CsvLocation.txt"))
{
streamWriter.WriteLine(txtCsvPath.Text);
}
}
}
}
}

C# how to fix this

I have a error that I don't no how to fix. I would perfer the answer in code. This is the error, Error 1 No overload for
'turnToVideoToolStripMenuItem_Click' matches delegate 'System.EventHandler'
C:\Users\kinoa\documents\visual studio 2013\Projects\Armored Animation Studio\Armored Animation Studio\main.Designer.cs 259 56 Armored Animation Studio.
This is the code,
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 NReco.VideoConverter;
using System.Diagnostics;
using System.IO;
namespace Armored_Animation_Studio
{
public partial class main : Form
{
public Point current = new Point();
public Point old = new Point();
public Graphics g;
public Pen p = new Pen(Color.Black, 5);
public List<Image> Animation = new List<Image>();
public main()
{
InitializeComponent();
g = panel1.CreateGraphics();
p.SetLineCap(System.Drawing.Drawing2D.LineCap.Round,
System.Drawing.Drawing2D.LineCap.Round,
System.Drawing.Drawing2D.DashCap.Round);
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
current = e.Location;
g.DrawLine(p, current, old);
old = current;
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
old = e.Location;
if(radioButton1.Checked)
{
p.Width = 1;
}
else if(radioButton2.Checked)
{
p.Width = 5;
}
else if (radioButton3.Checked)
{
p.Width = 10;
}
else if (radioButton4.Checked)
{
p.Width = 15;
}
else if (radioButton5.Checked)
{
p.Width = 30;
}
}
private void button1_Click(object sender, EventArgs e)
{
ColorDialog cd = new ColorDialog();
if (cd.ShowDialog() == DialogResult.OK)
p.Color = cd.Color;
}
private void button3_Click(object sender, EventArgs e)
{
panel1.Invalidate();
}
private void radioButton7_CheckedChanged(object sender, EventArgs e)
{
p.Color = System.Drawing.Color.White;
}
private void button2_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, panel1.Width,
panel1.Height));
Animation.Add(bmp);
}
private void turnToVideoToolStripMenuItem_Click(object sender, EventArgs
e, string [] args)
{
Process proc = new Process();
proc.StartInfo.FileName = "ffmpeg";
proc.StartInfo.Arguments = "-i " + args[0] + " " + args[1];
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
if (!proc.Start())
{
Console.WriteLine("Error starting");
return;
}
StreamReader reader = proc.StandardError;
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine("ffmpeg -i <imagefile> -vcodec mpeg4 out_movie");
}
proc.Close();
}
}
}
Thank you!
Change the method signature:
private void turnToVideoToolStripMenuItem_Click(object sender, EventArgs e, string [] args)
to:
private void turnToVideoToolStripMenuItem_Click(object sender, EventArgs e)
Would take care of the compiler error, but you are left with getting to the data that you expected to be in args. What are you expecting to be passed in that last parameter?

EmguCV VideoWriter creates huge save files?

With the following code I am recording and saving video from the webcam to the disk. But even a 3 second video saves with a file size of roughly 50 MB. I assume I am misusing the VideoWriter class. Any suggestions?
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.Structure;
namespace EmguCV_Webcam
{
public partial class Form1 : Form
{
#region Private variables
private Capture currentDevice;
private VideoWriter videoWriter;
private bool recording;
private int videoWidth;
private int videoHeight;
#endregion
#region Constructors
public Form1()
{
InitializeComponent();
InitializeVariables();
AttachButtonMacros();
StartVideoFeed();
}
#endregion
#region Methods
private void InitializeVariables()
{
currentDevice = new Capture(0);
recording = false;
videoWidth = currentDevice.Width;
videoHeight = currentDevice.Height;
}
private void StartVideoFeed()
{
currentDevice.Start();
currentDevice.ImageGrabbed += CurrentDevice_ImageGrabbed;
}
private void AttachButtonMacros()
{
StartRecordingButton.Click += StartRecordingButton_Click;
StopRecordingButton.Click += StopRecordingButton_Click;
}
private void CurrentDevice_ImageGrabbed(object sender, EventArgs e)
{
Mat m = new Mat();
currentDevice.Retrieve(m);
VideoPictureBox.Image = m.ToImage<Bgr, byte>().Bitmap;
if (recording && videoWriter != null)
{
videoWriter.Write(m);
}
}
private void StartRecordingButton_Click(object sender, EventArgs e)
{
recording = true;
SaveFileDialog dialog = new SaveFileDialog();
dialog.DefaultExt = ".avi";
dialog.AddExtension = true;
dialog.FileName = DateTime.Now.ToString();
DialogResult dialogResult = dialog.ShowDialog();
if(dialogResult != DialogResult.OK)
{
return;
}
videoWriter = new VideoWriter(dialog.FileName, 30, new Size(videoWidth, videoHeight), true);
}
private void StopRecordingButton_Click(object sender, EventArgs e)
{
recording = false;
if(videoWriter != null)
{
videoWriter.Dispose();
}
}
#endregion
}
}
You should use compression. Try this
VideoWriter.Fourcc('M', 'P', '4', 'V')
So change
videoWriter = new VideoWriter(dialog.FileName, 30, new Size(videoWidth, videoHeight), true);
with
videoWriter = new VideoWriter(dialog.FileName, VideoWriter.Fourcc('M', 'P', '4', 'V'), 30, new Size(videoWidth, videoHeight), true);

C# Saving from a Windows form after Creating the File

I believe the creating the file finished. I am having issues with saving to a file. What I am supposed to do is create the file initially then fill out the form and have it save to that file and separate them by commas in the file so that in my next assignment I can create a form to read the file and have that fill in the form and split by those commas and fill into text boxes.
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 FileExercise
{
public partial class frmscout : Form
{
private StreamWriter fileWriter;
public frmscout()
{
InitializeComponent();
btnsave.Enabled = false;
}
private void clickclear(object sender, EventArgs e)
{
tb40.Clear();
tbheight.Clear();
tbname.Clear();
tbposition.Clear();
tbreps.Clear();
tbverticle.Clear();
}
private void clickexit(object sender, EventArgs e)
{
Application.Exit();
}
private void clickselect(object sender, EventArgs e)
{
DialogResult result;
string fileName;
using (SaveFileDialog fileChooser = new SaveFileDialog())
{
fileChooser.CheckFileExists = false;
result = fileChooser.ShowDialog();
fileName = fileChooser.FileName;
}
if (result == DialogResult.OK)
{
if (fileName == string.Empty)
{
MessageBox.Show("Invalid File Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
try
{
FileStream flstrm = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
fileWriter = new StreamWriter( flstrm );
btnsave.Enabled = true;
btnopen.Enabled = false;
}
catch( IOException )
{enter code here
MessageBox.Show("Error opening file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
//FileStream outfile = new FileStream(fileName, FileMode.Append, FileAccess.Write);
}
private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
//}
}
}
}
you can do as below
private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
// you can get file name from `ShowDialog`,
//assume that file name is "filename.txt" then
System.IO.File.WriteAllLines("filename.txt",values);
}
You're creating a new instance of StreamWriter, and gathering your data onClick of the Save button, but nowhere are you calling StreamWriter.Write() or StreamWriter.WriteLine(). You need to insert at least one of those, as appropriate into your code, most likely in the clicksave function.
EDIT:
For example:
private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
fileWriter.WriteLine(String.Join(",",values));
fileWriter.Flush();
fileWriter.Close();
//}
}
Private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
fileWriter.WriteLine(String.Join(",",values));
fileWriter.Flush();
fileWriter.Close();
}
for joining of the string you can refer to the below link....as this is reference from Adrian Code..
http://www.dotnetperls.com/string-join

Need help getting listbox item text from secondary form to main form

I have been looking all over the Internet for this and have found similar, but none of it will work for me. Everything I have found assumes the listbox is on the main form and not the secondary form, or the code is for an older version of C# or Visual Studio (I am using VS2008).
I am creating a web browser that has a button on the main form (called frmMyBrowser) to open a dialog (frmBookmarks) with a listbox (lstBookmark) with bookmarked URLs. I need to be able to double click on an item (the bookmarked URL) and have the text pasted into the address bar (cmbAddress) of the main form.
Any help would be GREATLY appreciated.
I figured out that if I create the window at runtime, I can get it to work. In case anyone is interested, the code I used is below.
public void frmMyBrowser_ShowFavorites(object sender, EventArgs e)
{
frmFavorites.ShowIcon = false;
frmFavorites.ShowInTaskbar = false;
frmFavorites.MinimizeBox = false;
frmFavorites.MaximizeBox = false;
frmFavorites.ControlBox = false;
frmFavorites.Text = "Bookmarks";
frmFavorites.Width = 500;
frmFavorites.Height = 350;
frmFavorites.Controls.Add(lstFavorites);
frmFavorites.Controls.Add(btnRemoveFavorite);
frmFavorites.Controls.Add(btnAddFavorite);
frmFavorites.Controls.Add(btnCloseFavorites);
frmFavorites.Controls.Add(txtCurrentUrl);
lstFavorites.Width = 484;
lstFavorites.Height = 245;
btnRemoveFavorite.Location = new Point(8, 280);
btnAddFavorite.Location = new Point(8, 255);
btnCloseFavorites.Location = new Point(400, 255);
txtCurrentUrl.Location = new Point(110, 255);
txtCurrentUrl.Size = new Size(255, 20);
btnAddFavorite.Text = "Add";
btnRemoveFavorite.Text = "Remove";
btnCloseFavorites.Text = "Close";
txtCurrentUrl.Text = wbBrowser.Url.ToString();
btnAddFavorite.Click += new EventHandler(btnAddFavorite_Click);
btnRemoveFavorite.Click += new EventHandler(btnRemoveFavorite_Click);
frmFavorites.Load += new EventHandler(frmFavorites_Load);
btnCloseFavorites.Click += new EventHandler(btnCloseFavorites_Click);
lstFavorites.MouseDoubleClick += new MouseEventHandler(lstFavorites_MouseDoubleClick);
frmFavorites.Show();
}
public void btnCloseFavorites_Click(object sender, EventArgs e)
{
if (lstFavorites.Items.Count > 0)
{
using (StreamWriter writer = new System.IO.StreamWriter(#Application.StartupPath + "\\favorites.txt"))
{
for (int i = 0; i < lstFavorites.Items.Count; i++)
{
writer.WriteLine(lstFavorites.Items[i].ToString());
}
writer.Close();
}
}
frmFavorites.Hide();
}
public void btnAddFavorite_Click(object sender, EventArgs e)
{
string strFavoriteAddress = wbBrowser.Url.ToString();
if (!lstFavorites.Items.Contains(strFavoriteAddress))
{
lstFavorites.Items.Add(strFavoriteAddress);
MessageBox.Show("Favorite Added", "Message");
}
else if (lstFavorites.Items.Contains(strFavoriteAddress))
{
MessageBox.Show("This site already exists in your Favorites list!", "Error");
}
else
{
}
}
public void btnRemoveFavorite_Click(object sender, EventArgs e)
{
try
{
lstFavorites.Items.RemoveAt(lstFavorites.SelectedIndices[0]);
}
catch
{
MessageBox.Show("You need to select an item", "Error");
}
}
public void frmFavorites_Load(object sender, EventArgs e)
{
try
{
using (StreamReader reader = new System.IO.StreamReader(#Application.StartupPath + "\\favorites.txt"))
{
while (!reader.EndOfStream)
{
for (int i = 0; i < 4; i++)
{
string strListItem = reader.ReadLine();
if (!String.IsNullOrEmpty(strListItem))
{
lstFavorites.Items.Add(strListItem);
}
}
}
reader.Close();
}
}
catch
{
MessageBox.Show("An error has occured", "Error");
}
}
private void lstFavorites_MouseDoubleClick(object sender, MouseEventArgs e)
{
string strSelectedAddress = lstFavorites.Text.ToString();
cmbAddress.Text = strSelectedAddress;
wbBrowser.Navigate(strSelectedAddress);
frmFavorites.Hide();
}

Categories

Resources