I have the following code so that I can search directories to find files. Now I want to add a way for users to Save the output to a text file?
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace RecursiveSearchCS
{
public class Form1 : System.Windows.Forms.Form
{
internal System.Windows.Forms.Button btnSearch;
internal System.Windows.Forms.TextBox txtFile;
internal System.Windows.Forms.Label lblFile;
internal System.Windows.Forms.Label lblDirectory;
internal System.Windows.Forms.ListBox lstFilesFound;
internal System.Windows.Forms.ComboBox cboDirectory;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.btnSearch = new System.Windows.Forms.Button();
this.txtFile = new System.Windows.Forms.TextBox();
this.lblFile = new System.Windows.Forms.Label();
this.lblDirectory = new System.Windows.Forms.Label();
this.lstFilesFound = new System.Windows.Forms.ListBox();
this.cboDirectory = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// btnSearch
//
this.btnSearch.Location = new System.Drawing.Point(608, 248);
this.btnSearch.Name = "btnSearch";
this.btnSearch.Size = new System.Drawing.Size(75, 23);
this.btnSearch.TabIndex = 0;
this.btnSearch.Text = "Search";
this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
//
// txtFile
//
this.txtFile.Location = new System.Drawing.Point(8, 40);
this.txtFile.Name = "txtFile";
this.txtFile.Size = new System.Drawing.Size(120, 20);
this.txtFile.TabIndex = 4;
this.txtFile.Text = "*.*";
//
// lblFile
//
this.lblFile.Location = new System.Drawing.Point(8, 16);
this.lblFile.Name = "lblFile";
this.lblFile.Size = new System.Drawing.Size(144, 16);
this.lblFile.TabIndex = 5;
this.lblFile.Text = "Search for files containing:";
//
// lblDirectory
//
this.lblDirectory.Location = new System.Drawing.Point(8, 96);
this.lblDirectory.Name = "lblDirectory";
this.lblDirectory.Size = new System.Drawing.Size(120, 23);
this.lblDirectory.TabIndex = 3;
this.lblDirectory.Text = "Look In:";
//
// lstFilesFound
//
this.lstFilesFound.Location = new System.Drawing.Point(152, 8);
this.lstFilesFound.Name = "lstFilesFound";
this.lstFilesFound.Size = new System.Drawing.Size(528, 225);
this.lstFilesFound.TabIndex = 1;
//
// cboDirectory
//
this.cboDirectory.DropDownWidth = 112;
this.cboDirectory.Location = new System.Drawing.Point(8, 128);
this.cboDirectory.Name = "cboDirectory";
this.cboDirectory.Size = new System.Drawing.Size(120, 21);
this.cboDirectory.TabIndex = 2;
this.cboDirectory.Text = "ComboBox1";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(688, 277);
this.Controls.Add(this.btnSearch);
this.Controls.Add(this.txtFile);
this.Controls.Add(this.lblFile);
this.Controls.Add(this.lblDirectory);
this.Controls.Add(this.lstFilesFound);
this.Controls.Add(this.cboDirectory);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The main entry point for the application
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
lstFilesFound.Items.Clear();
txtFile.Enabled = false;
cboDirectory.Enabled = false;
btnSearch.Text = "Searching...";
this.Cursor = Cursors.WaitCursor;
Application.DoEvents();
DirSearch(cboDirectory.Text);
btnSearch.Text = "Search";
this.Cursor = Cursors.Default;
txtFile.Enabled = true;
cboDirectory.Enabled = true;
}
private void Form1_Load(object sender, System.EventArgs e)
{
cboDirectory.Items.Clear();
foreach (string s in Directory.GetLogicalDrives())
{
cboDirectory.Items.Add(s);
}
cboDirectory.Text = "C:\\";
}
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, txtFile.Text))
{
lstFilesFound.Items.Add(f);
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
}
}
Here is also a screenshot of the Application Open:
Open Application Image
I am going to add a save button which saves to a specific location when clicked, how would I go about doing this.
If I am understanding it correctly, use a simple I/O operation.
using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
foreach (string item in lstFilesFound.Items)
{
writer.WriteLine(item.ToString());
}
}
Few extra pointers:
In DirSearch, create a variable for Directory.GetDirectories(sDir). Your present code is causing this thing to calculate in every loop. Look for some more similar refactoring code in other areas.
var dirs = Directory.GetDirectories(sDir);
foreach (string d in dirs)
{
var files = Directory.GetFiles(d, txtFile.Text);
foreach (string f in files)
{
lstFilesFound.Items.Add(f);
}
DirSearch(d);
}
Hope it helps.
I'm assuming it's the list of found files you're wanting to save to a text file, how about this on your save event (rough code so not extensively tested)?
using (FileStream fs = new FileStream("c:\\files.txt", FileMode.Create, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (string item in lstFilesFound.Items)
{
sw.WriteLine(item);
}
}
}
Related
I've been working on a bit of software in c# and it was going nicely but as of yesterday evening I noticed that it was throwing a memory exception error at the point when it loads an image.
I tried to decrease the image size but then realised that 'declaring rats' was being printed repeatedly to the console, where it should only occur once.
Digging a little deeper with some break points I found that it enters the drawing constructor at allRats = new Drawing(HousePicBox, DekuPicBox, BakuPicBox); //THIS HAS BECOME RECURSIVE, WTF
yet it doesn't seem to run the code within the constructor, but jumps back to the start of form1().
I have included all of the code within the files which the Program Counter touches.
//---------------------------------------------------FORM1.CS-------------------------------------------------------------
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;
// This is the code for your desktop app.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
namespace XMLRats5
{
public partial class Form1 : Form
{
// These are here as they are referred to by various functions for different reasons
string MazakSourceURL = "http://mtconnect.mazakcorp.com:5609"; // Gives us a human friendly reference to the HTML
string NISTSourceURL = "https://smstestbed.nist.gov/vds/current"; // Gives us a human friendly reference to the HTML
public PollTimer statusPoller;
public static Drawing allRats;
ImageRat Deku;
ImageRat Bakugo;
NISTDataSet CurrentNIST;
MazakDataSet CurrentMazak;
public Form1()
{
Console.WriteLine("Declaring Rats..."); // Is being called recursively :( ?????????????
ImageRat.Deku = new Rat(false, 0, 0, true, 0); // Declares Deku
ImageRat.Bakugo = new Rat(false, 800, 0, true, 0); // Declares Bakugo
Console.WriteLine("Initialising");
InitializeComponent(); // Constructs the graphics which make up the 'state 0'
Console.WriteLine("Declaring image");
allRats = new Drawing(HousePicBox, DekuPicBox, BakuPicBox); //THIS HAS BECOME RECURSIVE, WTF
Console.WriteLine("Clearing Image");
allRats.ClearRats();
Console.WriteLine("Displaying House");
HousePicBox.Show();
//allRats.DrawRats(ImageRat.deku.Awake, ImageRat.bakugo.Awake);
Console.WriteLine("Form 1 Initiated, please proceed.");
}
private void NISTDataLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// This link takes you to the 'current' NIST testbed data feed page
System.Diagnostics.Process.Start(NISTSourceURL);
}
private void MAZAKDataLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// This link takes you to the raw XML published by Mazaks HCN6800 labelled 5609
System.Diagnostics.Process.Start(MazakSourceURL);
}
public void StatusCheckButton_Click(object sender, EventArgs e) // Here we should check that the machine tools are feeding live data
{
// Clear the rat picture boxes as they 'stick' when already shown
DekuPicBox.Hide();
BakuPicBox.Hide();
string MazakStatus = "Unchecked";
string NISTStatus = "Unchecked";
try
{
CurrentMazak = MTFunctions.PollMazak();
MazakStatus = CurrentMazak.Status;
if (MazakStatus == "AVAILABLE") { ImageRat.Deku.Awake = true; }
}
catch (Exception MazakLookupFailed)
{
Console.WriteLine("Could not retrieve Mazak Data", MazakLookupFailed);
MazakStatus = "Lookup Failed"; // This will later refer to the xml path for running status
}
try
{
CurrentNIST = MTFunctions.PollNIST();
NISTStatus = CurrentNIST.Status;
if (NISTStatus == "AVAILABLE") { ImageRat.Bakugo.Awake = true; }
}
catch (Exception NISTLookupFailed)
{
Console.WriteLine("Could not Retrieve NIST Data: ", NISTLookupFailed);
NISTStatus = "Lookup Failed";
ImageRat.Bakugo.Awake = false;
}
string MessageString = " Mazak : " + MazakStatus + "\n NIST : " + NISTStatus;
if ((ImageRat.Deku.Awake == true) & (ImageRat.Bakugo.Awake == true)) // Both Online
{
HousePicBox.Image = XMLRats5.Properties.Resources.bothsleep; // SLeeping rat shows machine online but not feeding data
} // Empty Box
if ((ImageRat.Deku.Awake == true) & (ImageRat.Bakugo.Awake == false)) // NIST offline
{
HousePicBox.Image = XMLRats5.Properties.Resources.bakusleep;
DekuPicBox.Show(); // Not neccessary but prevents bugs
} // Put Bakug in box, deku out
if ((ImageRat.Deku.Awake == false) & (ImageRat.Bakugo.Awake == true)) // Mazak Offline
{
HousePicBox.Image = XMLRats5.Properties.Resources.dekuSleep;
BakuPicBox.Show(); // Not neccessary but prevents bugs
} // Put deku in box, bakugo out
if ((ImageRat.Deku.Awake == false) & (ImageRat.Bakugo.Awake == false)) // Both Offline
{
HousePicBox.Image = XMLRats5.Properties.Resources.nosleep;
} // Put rats in box
MessageBox.Show(MessageString, "Machine Status"); // We need to pass information gained through XPath to first argument
}
public void WakeRatsButton_Click(object sender, EventArgs e)
{
MessageBox.Show("This 'wakes the rats' (Begins data stream)");
// We need to poll Mazak and NIST here to determine which images to draw.
MazakDataSet checkM = MTFunctions.PollMazak();
NISTDataSet checkN = MTFunctions.PollNIST();
if (checkM.Status == "AVAILABLE")
{
ImageRat.Deku.Awake = true;
DekuPicBox.Show();
}
else { ImageRat.Deku.Awake = false; }
if (checkN.Status == "AVAILABLE")
{
BakuPicBox.Show();
ImageRat.Bakugo.Awake = true;
}
else { ImageRat.Bakugo.Awake = false; }
allRats.DrawRats(ImageRat.Deku.Awake, ImageRat.Bakugo.Awake); // Should move the boys out of the box
// Here the draw function successfully relocates the rats, so why does this not work from the timer?
statusPoller = new PollTimer(2000, true); //Initiate a timer driven function which polls the data sets
// Timer Driven function draws rats
}
public void DebugInstructionsLabel_Click(object sender, EventArgs e)
{ }
public void titleLabel_Click(object sender, EventArgs e) { }
public void SleepRatsButton_Click(object sender, EventArgs e)
{
MessageBox.Show("This 'puts the rats to bed' (Closes data stream)");
try // Stop Polling timer function
{
statusPoller.Stop();
statusPoller.Dispose();
Console.Write("Stream closed successfully");
}
catch { Console.WriteLine("Could not stop polling. Were the rats actually 'awake'?"); }
// Draw rats in house
DekuPicBox.Hide(); // Rat is no longer active
BakuPicBox.Hide(); // Rat is no longer active
HousePicBox.Image = XMLRats5.Properties.Resources.nosleep; // Show empty box
//allRats.Paint();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void HousePicBox_Click(object sender, EventArgs e)
{
}
private void DekuPicBox_Click(object sender, EventArgs e)
{
// Proves that problem with movement is because DekuPicBox needs to be changed, not allRats.dekuPic....
System.Drawing.Point DekuCoord = new System.Drawing.Point(ImageRat.Deku.PosX, ImageRat.Deku.PosY); // Create a 'System Point' for Deku
DekuPicBox.Location = DekuCoord;
Console.WriteLine("~~~~~~~~Deku moved to " + DekuCoord + " ~~~~~~~~");
}
private void BakuPicBox_Click(object sender, EventArgs e)
{
System.Drawing.Point BakuCoord = new System.Drawing.Point(ImageRat.Bakugo.PosX, ImageRat.Bakugo.PosY); // Create a 'System Point' for Deku
BakuPicBox.Location = BakuCoord;
Console.WriteLine("~~~~~~~~Bakugo moved to " + BakuCoord + " ~~~~~~~~");
}
public void Refresh(int boi) // Better bloody relocate those pics boii
{
if (boi == 0)
{
System.Drawing.Point BakuCoord = new System.Drawing.Point(ImageRat.Bakugo.PosX, ImageRat.Bakugo.PosY); // Create a 'System Point' for Deku
DekuPicBox.Location = BakuCoord;
}
else
{
System.Drawing.Point DekuCoord = new System.Drawing.Point(ImageRat.Deku.PosX, ImageRat.Deku.PosY); // Create a 'System Point' for Deku
DekuPicBox.Location = DekuCoord;
}
}
}
}
//----------------------------------------------FORM1.Designer.CS--------------------------------------------------------
namespace XMLRats5
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.MAZAKDataLinkLabel = new System.Windows.Forms.LinkLabel();
this.DebugInstructionsLabel = new System.Windows.Forms.Label();
this.StatusCheckButton = new System.Windows.Forms.Button();
this.TitleLabel = new System.Windows.Forms.Label();
this.WakeRatsButton = new System.Windows.Forms.Button();
this.SleepRatsButton = new System.Windows.Forms.Button();
this.NISTDataLinkLabel = new System.Windows.Forms.LinkLabel();
this.BakuPicBox = new System.Windows.Forms.PictureBox();
this.HousePicBox = new System.Windows.Forms.PictureBox();
this.DekuPicBox = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.BakuPicBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.HousePicBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.DekuPicBox)).BeginInit();
this.SuspendLayout();
//
// MAZAKDataLinkLabel
//
this.MAZAKDataLinkLabel.AutoSize = true;
this.MAZAKDataLinkLabel.Location = new System.Drawing.Point(1287, 985);
this.MAZAKDataLinkLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.MAZAKDataLinkLabel.Name = "MAZAKDataLinkLabel";
this.MAZAKDataLinkLabel.Size = new System.Drawing.Size(179, 25);
this.MAZAKDataLinkLabel.TabIndex = 0;
this.MAZAKDataLinkLabel.TabStop = true;
this.MAZAKDataLinkLabel.Text = "View Mazak Data";
this.MAZAKDataLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.MAZAKDataLinkLabel_LinkClicked);
//
// DebugInstructionsLabel
//
this.DebugInstructionsLabel.AutoSize = true;
this.DebugInstructionsLabel.Location = new System.Drawing.Point(1066, 524);
this.DebugInstructionsLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.DebugInstructionsLabel.Name = "DebugInstructionsLabel";
this.DebugInstructionsLabel.Size = new System.Drawing.Size(623, 50);
this.DebugInstructionsLabel.TabIndex = 1;
this.DebugInstructionsLabel.Text = "Press \'Check Machine\' to ensure a device is running, otherwise \n don\'t expect muc" +
"h activity from the rats!";
this.DebugInstructionsLabel.Click += new System.EventHandler(this.DebugInstructionsLabel_Click);
//
// StatusCheckButton
//
this.StatusCheckButton.Location = new System.Drawing.Point(1271, 658);
this.StatusCheckButton.Margin = new System.Windows.Forms.Padding(4);
this.StatusCheckButton.Name = "StatusCheckButton";
this.StatusCheckButton.Size = new System.Drawing.Size(195, 54);
this.StatusCheckButton.TabIndex = 2;
this.StatusCheckButton.Text = "Check Machine Status";
this.StatusCheckButton.UseVisualStyleBackColor = true;
this.StatusCheckButton.Click += new System.EventHandler(this.StatusCheckButton_Click);
//
// TitleLabel
//
this.TitleLabel.AutoSize = true;
this.TitleLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.TitleLabel.Location = new System.Drawing.Point(1255, 382);
this.TitleLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.TitleLabel.Name = "TitleLabel";
this.TitleLabel.Size = new System.Drawing.Size(211, 51);
this.TitleLabel.TabIndex = 3;
this.TitleLabel.Text = "XML Rats";
this.TitleLabel.Click += new System.EventHandler(this.titleLabel_Click);
//
// WakeRatsButton
//
this.WakeRatsButton.Location = new System.Drawing.Point(1271, 775);
this.WakeRatsButton.Margin = new System.Windows.Forms.Padding(4);
this.WakeRatsButton.Name = "WakeRatsButton";
this.WakeRatsButton.Size = new System.Drawing.Size(195, 54);
this.WakeRatsButton.TabIndex = 4;
this.WakeRatsButton.Text = "Wake Rats";
this.WakeRatsButton.UseVisualStyleBackColor = true;
//
// SleepRatsButton
//
this.SleepRatsButton.Location = new System.Drawing.Point(1271, 885);
this.SleepRatsButton.Margin = new System.Windows.Forms.Padding(4);
this.SleepRatsButton.Name = "SleepRatsButton";
this.SleepRatsButton.Size = new System.Drawing.Size(195, 54);
this.SleepRatsButton.TabIndex = 5;
this.SleepRatsButton.Text = "Sleep Rats";
this.SleepRatsButton.UseVisualStyleBackColor = true;
//
// NISTDataLinkLabel
//
this.NISTDataLinkLabel.AutoSize = true;
this.NISTDataLinkLabel.Location = new System.Drawing.Point(1287, 1054);
this.NISTDataLinkLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.NISTDataLinkLabel.Name = "NISTDataLinkLabel";
this.NISTDataLinkLabel.Size = new System.Drawing.Size(162, 25);
this.NISTDataLinkLabel.TabIndex = 6;
this.NISTDataLinkLabel.TabStop = true;
this.NISTDataLinkLabel.Text = "View NIST Data";
//
// BakuPicBox
//
this.BakuPicBox.Image = global::XMLRats5.Properties.Resources.bakuTransSmall;
this.BakuPicBox.Location = new System.Drawing.Point(2092, 1388);
this.BakuPicBox.Name = "BakuPicBox";
this.BakuPicBox.Size = new System.Drawing.Size(632, 424);
this.BakuPicBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.BakuPicBox.TabIndex = 9;
this.BakuPicBox.TabStop = false;
//
// HousePicBox
//
this.HousePicBox.Image = global::XMLRats5.Properties.Resources.nosleep;
this.HousePicBox.Location = new System.Drawing.Point(1057, 1388);
this.HousePicBox.Name = "HousePicBox";
this.HousePicBox.Size = new System.Drawing.Size(632, 424);
this.HousePicBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.HousePicBox.TabIndex = 8;
this.HousePicBox.TabStop = false;
//
// DekuPicBox
//
this.DekuPicBox.Image = global::XMLRats5.Properties.Resources.DekuBackgroundTransparent;
this.DekuPicBox.Location = new System.Drawing.Point(12, 1388);
this.DekuPicBox.Name = "DekuPicBox";
this.DekuPicBox.Size = new System.Drawing.Size(632, 424);
this.DekuPicBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.DekuPicBox.TabIndex = 7;
this.DekuPicBox.TabStop = false;
this.DekuPicBox.Click += new System.EventHandler(this.DekuPicBox_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(2736, 1824);
this.Controls.Add(this.BakuPicBox);
this.Controls.Add(this.HousePicBox);
this.Controls.Add(this.DekuPicBox);
this.Controls.Add(this.NISTDataLinkLabel);
this.Controls.Add(this.SleepRatsButton);
this.Controls.Add(this.WakeRatsButton);
this.Controls.Add(this.TitleLabel);
this.Controls.Add(this.StatusCheckButton);
this.Controls.Add(this.DebugInstructionsLabel);
this.Controls.Add(this.MAZAKDataLinkLabel);
this.Margin = new System.Windows.Forms.Padding(4);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.BakuPicBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.HousePicBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.DekuPicBox)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.LinkLabel MAZAKDataLinkLabel;
private System.Windows.Forms.Label DebugInstructionsLabel;
private System.Windows.Forms.Button StatusCheckButton;
private System.Windows.Forms.Label TitleLabel;
private System.Windows.Forms.Button WakeRatsButton;
private System.Windows.Forms.Button SleepRatsButton;
private System.Windows.Forms.LinkLabel NISTDataLinkLabel;
public System.Windows.Forms.PictureBox DekuPicBox;
public System.Windows.Forms.PictureBox HousePicBox;
public System.Windows.Forms.PictureBox BakuPicBox;
}
}
//-------------------------------------------------------------DRAWING.CS----------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
using System.Drawing;
using System.Windows.Forms;
namespace XMLRats5
{
public class Drawing : Form1
{
private PictureBox HouseImage;
private PictureBox DekuImage;
private PictureBox BakuImage;
public Drawing(PictureBox house, PictureBox deku, PictureBox baku)
{
HouseImage = house;
DekuImage = deku;
BakuImage = baku;
} // Code is jumping back to form1 call :S
public void ClearRats()
{
//DekuImage.Image.Dispose();
//BakuImage.Image.Dispose();
//HouseImage.Image.Dispose();
HouseImage.Hide();
DekuImage.Hide();
BakuImage.Hide();
}
public void RePaint()
{
//BakuImage.Paint();
//DekuImage.Paint();
//HouseImage.Paint();
}
public void DrawRats(bool DekuWake, bool BakuWake) // Call this function using active status of 2 machines
{
this.ClearRats();
DekuPicBox.SuspendLayout();
BakuPicBox.SuspendLayout();
HousePicBox.SuspendLayout();
System.Drawing.Point DekuCoord = new System.Drawing.Point(ImageRat.Deku.PosX, ImageRat.Deku.PosY); // Create a 'System Point' for Deku
System.Drawing.Point BakuCoord = new System.Drawing.Point(ImageRat.Bakugo.PosX, ImageRat.Bakugo.PosY); // Create a 'System Point' for Bakugo
Console.WriteLine("Randomly Generated Point Assigned (Deku):" + DekuCoord);
Console.WriteLine("Randomly Generated Point Assigned (Baku):" + BakuCoord);
if (DekuWake == false)
{
DekuImage.Hide();
if (BakuWake == false)
{
BakuPicBox.Hide();
HousePicBox.Image = XMLRats5.Properties.Resources.bothsleep;// set HouseImage to both sleep
}
else
{
BakuPicBox.Location = BakuCoord;
BakuPicBox.Show();
HousePicBox.Image = XMLRats5.Properties.Resources.dekuSleep; //Set HouseImage to DekuSleep
}
}
else //DekuWake == true
{
DekuImage.Show();
if (BakuWake == true)
{
HousePicBox.Image = XMLRats5.Properties.Resources.nosleep;//Set House image to nosleep
DekuPicBox.Location = DekuCoord;
DekuPicBox.Show();
BakuPicBox.Location = BakuCoord;
BakuPicBox.Show();
}
else
{
BakuPicBox.Hide();
HousePicBox.Image = XMLRats5.Properties.Resources.bakusleep;// Set house image to bakusleep
DekuPicBox.Location = DekuCoord;
DekuPicBox.Show();
}
}
HousePicBox.Show(); // Out here as it should always happen
}
}
}
Honestly I'm baffled as to why it keeps jumping back to the start of form1.
What have I broken?
As Drawing is derived from Form1 & you create an instance of Drawing in the Form1 constructor - this is going to cause the Form1 constructor to be invoked again which causes the creation of another instance of Drawing which causes ........... -
Note the base class constructor is called before the code in the derived class constructor - which is why you don't get to the code in the Drawing constructor.
I tried to monitor the directory with FileWatcher. When several files changed I must insert added data of txt files into database. But it does not work after the second attempt. So, Windows shows such message: this file is used by another program. I think that it relates to the ReaderWriterLockSlim class which used in this code. Please, suppose your solutions. I am working with ASP.NET MVC, not Windows Forms App.
Here the code
public class MultiWatcher : IDisposable
{
private List<string> filePaths;
private ReaderWriterLockSlim rwlock;
private System.Timers.Timer processTimer;
private string watchedPath;
private FileSystemWatcher watcher;
private int readLinesCount = 0;
public MultiWatcher(string watchedPath)
{
filePaths = new List<string>();
rwlock = new ReaderWriterLockSlim();
this.watchedPath = watchedPath;
InitFileSystemWatcher();
}
private void InitFileSystemWatcher()
{
watcher = new FileSystemWatcher();
watcher.Filter = "*.txt";
watcher.Changed += new FileSystemEventHandler(Watcher_FileChanged);
watcher.Error += Watcher_Error;
watcher.Path = watchedPath;
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
}
private void Watcher_Error(object sender, ErrorEventArgs e)
{
// Watcher crashed. Re-init.
InitFileSystemWatcher();
}
private void Watcher_FileChanged(object sender, FileSystemEventArgs e)
{
try
{
rwlock.EnterWriteLock();
filePaths.Add(e.Name);
if (processTimer == null)
{
// First file, start timer.
processTimer = new System.Timers.Timer(1000);
processTimer.Elapsed += ProcessQueue;
processTimer.Start();
}
else
{
// Subsequent file, reset timer.
processTimer.Stop();
processTimer.Start();
}
}
finally
{
rwlock.ExitWriteLock();
}
}
private void ProcessQueue(object sender, ElapsedEventArgs args)
{
try
{
//Console.WriteLine("Processing queue, " + filePaths.Count + " files created:");
rwlock.EnterReadLock();
foreach (string filePath in filePaths)
{
RecordEntry(filePath); // try to insert txt file data into database
}
filePaths.Clear();
}
finally
{
if (processTimer != null)
{
processTimer.Stop();
processTimer.Dispose();
processTimer = null;
}
rwlock.ExitReadLock();
}
}
//insert txt file data into database
private void RecordEntry(string fileName)
{
if (fileName != null)
{
using (var fs = new FileStream(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName), FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader reader = new StreamReader(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)))
{
Data_access da = new Data_access();
readLinesCount = da.GetReadLinesCount(fileName);
int totalLinesCount = File.ReadAllLines(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)).Length;
int newLinesCount = totalLinesCount - readLinesCount;
//var fileByLine = File.ReadLines(HostingEnvironment.MapPath("/Content/101_Sensors.txt")).Last();
var fileByLine = File.ReadLines(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)).Skip(readLinesCount).Take(newLinesCount);
var each = fileByLine.Select(l => l.Split('_'));
string[] parsedFileContent = new string[fileByLine.Count()];
foreach (var item in fileByLine)
{
parsedFileContent = item.Split('_');
da.AddParams(parsedFileContent, totalLinesCount, fileName);
}
da.SetReadLinesCount(totalLinesCount, fileName);
}
}
//using (StreamReader reader = new StreamReader(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)))
//{
// int totallinesCount = File.ReadAllLines(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)).Length;
// int newLinesCount = totallinesCount - readLinesCount;
// //var fileByLine = File.ReadLines(HostingEnvironment.MapPath("/Content/101_Sensors.txt")).Last();
// var fileByLine = File.ReadLines(HostingEnvironment.MapPath("~/Content/Sensors/" + fileName)).Skip(readLinesCount).Take(newLinesCount);
// var each = fileByLine.Select(l => l.Split('_'));
// string[] parsedFileContent = new string[fileByLine.Count()];
// foreach (var item in fileByLine)
// {
// parsedFileContent = item.Split('_');
// da.AddParams(parsedFileContent, totallinesCount, fileName, readLinesCount);
// }
//}
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (rwlock != null)
{
rwlock.Dispose();
rwlock = null;
}
if (watcher != null)
{
watcher.EnableRaisingEvents = false;
watcher.Dispose();
watcher = null;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
I have a form that i dynamicly compiled and i have a style class. When i copy this style class to my form source and compile it all works fine. But how can i use this style class without copy it to my form source. My main program that compile this form has this class, how can i use it? Maybe i can pass style class to this for with i compile it, like a var?
Program source:
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Microsoft.CSharp;
namespace dynamic
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new Thread(newForm).Start();
}
public void newForm()
{
using (CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary<string, string>
{
{"CompilerVersion", "v4.0"}
}))
{
var parameters = new CompilerParameters
{
GenerateExecutable = false, // Create a dll
GenerateInMemory = true, // Create it in memory
WarningLevel = 3, // Default warning level
CompilerOptions = "/optimize", // Optimize code
TreatWarningsAsErrors = false // Better be false to avoid break in warnings
};
parameters.ReferencedAssemblies.Add("mscorlib.dll");
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.ReferencedAssemblies.Add("System.Data.dll");
parameters.ReferencedAssemblies.Add("System.Drawing.dll");
parameters.ReferencedAssemblies.Add("System.Xml.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
var source = File.ReadAllText("form.txt");
CompilerResults results = provider.CompileAssemblyFromSource(parameters, source);
Type type = results.CompiledAssembly.GetType("myForm.Form1");
object compiledObject = Activator.CreateInstance(type);
type.GetMethod("ShowDialog", new Type[0]).Invoke(compiledObject, new object[] {});
MessageBox.Show("formClosed");
}
}
}
}
Style folder:
Form source:
using System;
using System.Windows.Forms;
namespace myForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var newTmr = new Timer { Interval = 1000 };
newTmr.Tick += count;
newTmr.Enabled = true;
}
private void count(Object myObject, EventArgs myEventArgs)
{
timer.Value2 = (Int32.Parse(timer.Value2) + 1).ToString();
}
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("clicked");
}
private void nsButton1_Click(object sender, EventArgs e)
{
MessageBox.Show("button");
}
}
}
namespace myForm
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.nsTheme1 = new myForm.NSTheme();
this.nsButton1 = new myForm.NSButton();
this.timer = new myForm.NSLabel();
this.nsControlButton1 = new myForm.NSControlButton();
this.nsTheme1.SuspendLayout();
this.SuspendLayout();
//
// nsTheme1
//
this.nsTheme1.AccentOffset = 0;
this.nsTheme1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(50)))));
this.nsTheme1.BorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.nsTheme1.Colors = new myForm.Bloom[0];
this.nsTheme1.Controls.Add(this.nsControlButton1);
this.nsTheme1.Controls.Add(this.timer);
this.nsTheme1.Controls.Add(this.nsButton1);
this.nsTheme1.Customization = "";
this.nsTheme1.Dock = System.Windows.Forms.DockStyle.Fill;
this.nsTheme1.Font = new System.Drawing.Font("Verdana", 8F);
this.nsTheme1.Image = null;
this.nsTheme1.Location = new System.Drawing.Point(0, 0);
this.nsTheme1.Movable = true;
this.nsTheme1.Name = "nsTheme1";
this.nsTheme1.NoRounding = false;
this.nsTheme1.Sizable = true;
this.nsTheme1.Size = new System.Drawing.Size(284, 274);
this.nsTheme1.SmartBounds = true;
this.nsTheme1.StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultLocation;
this.nsTheme1.TabIndex = 0;
this.nsTheme1.Text = "nsTheme1";
this.nsTheme1.TransparencyKey = System.Drawing.Color.Empty;
this.nsTheme1.Transparent = false;
//
// nsButton1
//
this.nsButton1.Location = new System.Drawing.Point(100, 166);
this.nsButton1.Name = "nsButton1";
this.nsButton1.Size = new System.Drawing.Size(75, 23);
this.nsButton1.TabIndex = 0;
this.nsButton1.Text = "nsButton1";
this.nsButton1.Click += new System.EventHandler(this.nsButton1_Click);
//
// timer
//
this.timer.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Bold);
this.timer.Location = new System.Drawing.Point(91, 82);
this.timer.Name = "timer";
this.timer.Size = new System.Drawing.Size(101, 23);
this.timer.TabIndex = 1;
this.timer.Text = "nsLabel1";
this.timer.Value1 = "Timer: ";
this.timer.Value2 = "0";
//
// nsControlButton1
//
this.nsControlButton1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.nsControlButton1.ControlButton = myForm.NSControlButton.Button.Close;
this.nsControlButton1.Location = new System.Drawing.Point(262, 4);
this.nsControlButton1.Margin = new System.Windows.Forms.Padding(0);
this.nsControlButton1.MaximumSize = new System.Drawing.Size(18, 20);
this.nsControlButton1.MinimumSize = new System.Drawing.Size(18, 20);
this.nsControlButton1.Name = "nsControlButton1";
this.nsControlButton1.Size = new System.Drawing.Size(18, 20);
this.nsControlButton1.TabIndex = 2;
this.nsControlButton1.Text = "nsControlButton1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 274);
this.Controls.Add(this.nsTheme1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "Form1";
this.Text = "Form1";
this.nsTheme1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private NSTheme nsTheme1;
private NSButton nsButton1;
private NSControlButton nsControlButton1;
private NSLabel timer;
}
}
Style source:
http://pastebin.com/CjmQQ9ND
Project source - https://yadi.sk/d/ChtMacrsraD4g
If you compile this source, all will work fine. That because i use style at form.txt file. I separated form from style at form.txt file. I have this style at my main program (you can see that at screenshot). How can i send this style class to my dynamicly compiled form, so form can use it.
You should be able to simply append the style to the source like so:
var source = File.ReadAllText("form.txt");
source += Environment.NewLine;
source += File.ReadAllText("style.txt");
Inside Form.txt file instead of the classes in order prescribes the macro:
namespace myForm
{
<%THEME%>
}
namespace myForm
{
<%THEMEBASE%>
}
Before compile, load style files and replace them in the code form:
//Load style files
var NSThemeSource = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"..\..\Class\Style\NSTheme.cs"));
var themeBaseSource = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"..\..\Class\Style\ThemeBase154.cs"));
var source = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Form.txt"));
//Substitute in the form styles
source = source.Replace("<%THEME%>", NSThemeSource);
source = source.Replace("<%THEMEBASE%>", themeBaseSource);
P.S.
You can switch build action for style files at Embedded Resource so you can get style class from exe.
And use this helper - http://www.vcskicks.com/embedded-resource.php
Than you need to change code to:
var NSThemeSource = ResourceHelper.GetEmbeddedResource("Class/Style/NSTheme.cs");
var themeBaseSource = ResourceHelper.GetEmbeddedResource("Class/Style/ThemeBase154.cs");
First, you need to make classes, enums, and etc. public in NSTheme.cs and ThemeBase154.cs.
(it is better to put into some namespace, rather than having them in the global (dynamic) namespace).
Then, add parameters.ReferencedAssemblies.Add("dynamic.exe"); to you exe file (you might want to put your styles in a separate dll).
After it, in your form.txt add using dynamic; and remove qualifiers from new myForm.NSTheme() (so, it becomes new NSTheme()).
Now you can use your styles without coping them to your form class.
In case you miss something, check the CompilerResults results errors for particular problems.
Hay i am new in media and quite new for C# i am trying for a video conference application, i have almost done it but my problem is a dll of windows actually i am using window 8.1 and i am trying to use avicap32.dll to open and close my webcam but its not working well it start webcam only once after booting then after until i don't restart my computer it always shows a black screen i am attaching my code too for reference. Thanks in advance.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using DirectX.Capture;
using DShowNET;
namespace Video_Conference
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
internal PictureBox picture_comming;
private TextBox IP_textBox;
private Label label1;
private TextBox device_number_textBox;
private Label label2;
private Button button1;
private Button button2;
private System.Windows.Forms.Timer timer1;
#region WebCam API
const short WM_CAP = 1024;
const int WM_CAP_DRIVER_CONNECT = WM_CAP + 10;
const int WM_CAP_DRIVER_DISCONNECT = WM_CAP + 11;
const int WM_CAP_EDIT_COPY = WM_CAP + 30;
const int WM_CAP_SET_PREVIEW = WM_CAP + 50;
const int WM_CAP_SET_PREVIEWRATE = WM_CAP + 52;
const int WM_CAP_SET_SCALE = WM_CAP + 53;
const int WS_CHILD = 1073741824;
const int WS_VISIBLE = 268435456;
const short SWP_NOMOVE = 2;
const short SWP_NOSIZE = 1;
const short SWP_NOZORDER = 4;
const short HWND_BOTTOM = 1;
int iDevice = 0;
Capture capture = null;
Filters filters = null;
int counter = 1;
int hHwnd;
[System.Runtime.InteropServices.DllImport("user32", EntryPoint="SendMessageA")]
static extern int SendMessage(int hwnd, int wMsg, int wParam, [MarshalAs(UnmanagedType.AsAny)] object lParam);
[System.Runtime.InteropServices.DllImport("user32", EntryPoint="SetWindowPos")]
static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
[System.Runtime.InteropServices.DllImport("user32")]
static extern bool DestroyWindow(int hndw);
[System.Runtime.InteropServices.DllImport("avicap32.dll")]
static extern int capCreateCaptureWindowA(string lpszWindowName, int dwStyle, int x, int y, int nWidth, short nHeight, int hWndParent, int nID);
[System.Runtime.InteropServices.DllImport("avicap32.dll")]
static extern bool capGetDriverDescriptionA(short wDriver, string lpszName, int cbName, string lpszVer, int cbVer);
private void OpenPreviewWindow()
{
int iHeight = 320;
int iWidth = 200;
//
// Open Preview window in picturebox
////
hHwnd = capCreateCaptureWindowA(iDevice.ToString(), (WS_VISIBLE | WS_CHILD), 0, 0, 640, 480, picCapture.Handle.ToInt32(), 0);
////hHwnd = 132190;
////
//// Connect to device
////
if (SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, iDevice, 0) == 1)
{
// //
// // Set the preview scale
// //
SendMessage(hHwnd, WM_CAP_SET_SCALE, 1, 0);
// //
// // Set the preview rate in milliseconds
// //
/ SendMessage(hHwnd, WM_CAP_SET_PREVIEWRATE, 66, 0);
// //
// Start previewing the image from the camera
// //
SendMessage(hHwnd, WM_CAP_SET_PREVIEW, 1, 0);
// //
// // Resize window to fit in picturebox
// //
SetWindowPos(hHwnd, HWND_BOTTOM, 0, 0, iWidth,iHeight, (SWP_NOMOVE | SWP_NOZORDER));
}
else
{
// //
// // Error connecting to device close window
// //
DestroyWindow(hHwnd);
}
}
void startOrStopCapturing(Capture capture)
{
btnStart.Visible = false;
if (capture != null) capture.Stop();
if (timer1.Enabled) timer1.Stop();
if (btnStart.Text == "START")
{
btnStart.Text = "STOP";
btnStart.BackColor = Color.Maroon;
try
{
if (!capture.Cued) capture.Filename = counter + ".wmv";
capture.Cue();
capture.Start();
timer1.Start();
}
catch (Exception ex)
{
MessageBox.Show("Error Message: \n\n" + ex.Message);
}
}
else
{
btnStart.Text = "START";
btnStart.BackColor = Color.DarkSlateBlue;
}
btnStart.Visible = true;
}
void preview(int deviceNo)
{
try
{
capture = new Capture(filters.VideoInputDevices[deviceNo], filters.AudioInputDevices[0]);
capture.PreviewWindow = picCapture;
if (btnStart.Text == "STOP")
{
counter++;
if (!capture.Cued) capture.Filename = counter + ".wmv";
capture.Cue();
}
capture.Start();
}
catch { }
}
private void ClosePreviewWindow()
{
//
// Disconnect from device
//
SendMessage(hHwnd, WM_CAP_DRIVER_DISCONNECT, iDevice, 0);
//
// close window
//
DestroyWindow(hHwnd);
}
#endregion
internal System.Windows.Forms.Button btnStop;
internal System.Windows.Forms.Button btnStart;
internal System.Windows.Forms.PictureBox picCapture;
private IContainer components;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnStop = new System.Windows.Forms.Button();
this.btnStart = new System.Windows.Forms.Button();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.IP_textBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.device_number_textBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.picture_comming = new System.Windows.Forms.PictureBox();
this.picCapture = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.picture_comming)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.picCapture)).BeginInit();
this.SuspendLayout();
//
// btnStop
//
this.btnStop.Anchor = System.Windows.Forms.AnchorStyles.None;
this.btnStop.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnStop.Location = new System.Drawing.Point(123, 56);
this.btnStop.Name = "btnStop";
this.btnStop.Size = new System.Drawing.Size(112, 32);
this.btnStop.TabIndex = 11;
this.btnStop.Text = "Stop Capturing";
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// btnStart
//
this.btnStart.Anchor = System.Windows.Forms.AnchorStyles.None;
this.btnStart.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnStart.Location = new System.Drawing.Point(123, 18);
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(112, 32);
this.btnStart.TabIndex = 9;
this.btnStart.Text = "Start Capturing";
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// IP_textBox
//
this.IP_textBox.Location = new System.Drawing.Point(69, 303);
this.IP_textBox.Name = "IP_textBox";
this.IP_textBox.Size = new System.Drawing.Size(161, 20);
this.IP_textBox.TabIndex = 13;
this.IP_textBox.Text = "127.0.0.1";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 306);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(51, 13);
this.label1.TabIndex = 14;
this.label1.Text = "Remot IP";
//
// device_number_textBox
//
this.device_number_textBox.Location = new System.Drawing.Point(336, 25);
this.device_number_textBox.Name = "device_number_textBox";
this.device_number_textBox.Size = new System.Drawing.Size(48, 20);
this.device_number_textBox.TabIndex = 15;
this.device_number_textBox.Text = "0";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(238, 28);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(91, 13);
this.label2.TabIndex = 16;
this.label2.Text = "Capture Device #";
//
// button1
//
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.button1.Location = new System.Drawing.Point(336, 300);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 17;
this.button1.Text = "Listener";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.button2.Location = new System.Drawing.Point(239, 301);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(91, 23);
this.button2.TabIndex = 18;
this.button2.Text = "Start Sending";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// timer1
//
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// picture_comming
//
this.picture_comming.Anchor = System.Windows.Forms.AnchorStyles.None;
this.picture_comming.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picture_comming.Image = global::Video_Conference.Properties.Resources.ip;
this.picture_comming.Location = new System.Drawing.Point(15, 104);
this.picture_comming.Name = "picture_comming";
this.picture_comming.Size = new System.Drawing.Size(246, 189);
this.picture_comming.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picture_comming.TabIndex = 12;
this.picture_comming.TabStop = false;
//
// picCapture
//
this.picCapture.Anchor = System.Windows.Forms.AnchorStyles.None;
this.picCapture.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picCapture.Image = global::Video_Conference.Properties.Resources.icony;
this.picCapture.Location = new System.Drawing.Point(15, 18);
this.picCapture.Name = "picCapture";
this.picCapture.Size = new System.Drawing.Size(102, 80);
this.picCapture.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picCapture.TabIndex = 6;
this.picCapture.TabStop = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(414, 338);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.label2);
this.Controls.Add(this.device_number_textBox);
this.Controls.Add(this.label1);
this.Controls.Add(this.IP_textBox);
this.Controls.Add(this.picture_comming);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnStart);
this.Controls.Add(this.picCapture);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Video Conference - Peer 1 - www.fadidotnet.org";
this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.picture_comming)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.picCapture)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
TcpClient myclient;
MemoryStream ms;
NetworkStream myns;
BinaryWriter mysw;
Thread myth;
TcpListener mytcpl;
Socket mysocket;
NetworkStream ns;
private void Start_Receiving_Video_Conference()
{
try
{
// Open The Port
string i = "2.1.168.192";
long z = (long)(uint)IPAddress.NetworkToHostOrder((int)IPAddress.Parse(i).Address);
IPAddress ip = new IPAddress(z);
mytcpl = new TcpListener(ip, 6000);
mytcpl.Start(); // Start Listening on That Port
mysocket = mytcpl.AcceptSocket(); // Accept Any Request From Client and Start a Session
ns = new NetworkStream(mysocket); // Receives The Binary Data From Port
picture_comming.Image = Image.FromStream(ns);
mytcpl.Stop(); // Close TCP Session
if (mysocket.Connected == true) // Looping While Connected to Receive Another Message
{
while (true)
{
Start_Receiving_Video_Conference(); // Back to First Method
}
}
myns.Flush();
}
catch (Exception) { button1.Enabled = true; myth.Abort(); }
}
private void Start_Sending_Video_Conference(string remote_IP, int port_number)
{
try
{
ms = new MemoryStream();// Store it in Binary Array as Stream
IDataObject data;
Image bmap;
// Copy image to clipboard
SendMessage(hHwnd, WM_CAP_EDIT_COPY, 0, 0);
// Get image from clipboard and convert it to a bitmap
data = Clipboard.GetDataObject();
if (data.GetDataPresent(typeof(System.Drawing.Bitmap)))
{
bmap = ((Image)(data.GetData(typeof(System.Drawing.Bitmap))));
bmap.Save(ms, ImageFormat.Bmp);
}
picCapture.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] arrImage = ms.GetBuffer();
myclient = new TcpClient(remote_IP, port_number);//Connecting with server
myns = myclient.GetStream();
mysw = new BinaryWriter(myns);
mysw.Write(arrImage);//send the stream to above address
ms.Flush();
mysw.Flush();
myns.Flush();
ms.Close();
mysw.Close();
myns.Close();
myclient.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Video Conference Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnStart_Click(object sender, System.EventArgs e)
{
iDevice = int.Parse (device_number_textBox.Text);
OpenPreviewWindow();
}
private void btnStop_Click(object sender, System.EventArgs e)
{
ClosePreviewWindow();
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (btnStop.Enabled)
{
ClosePreviewWindow();
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
myth = new Thread(new System.Threading.ThreadStart(Start_Receiving_Video_Conference)); // Start Thread Session
myth.Start(); // Start Receiveing Camera
}
private void timer1_Tick(object sender, EventArgs e)
{
Start_Sending_Video_Conference(IP_textBox.Text, 6000);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
mytcpl.Stop();
myth.Abort();
}
catch (Exception){}
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
}
}
I know little about C#.
I am trying to display a progressbar with the status of the background command line program.
After google examples of progressbar and run process in c#, so I'm trying to start a BackgroundWorker in the Windows Form, and run the command line program in the BackgroundWorker. I want to parse the command line's output to get the progress
percentage and display it to the progress bar.
The command line program is a console program, it will output periodically its current status of progress.
But it seems it did not work. I can't readline any lines of the process's standard output.
Is there anything I missed?
Here is the raw code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;
using System.Diagnostics;
using System.IO;
public class DemoForm : Form
{
private BackgroundWorker backgroundWorker1;
private Button loadButton;
private ProgressBar progressBar1;
public DemoForm()
{
InitializeComponent();
backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(
this.backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted +=
new System.ComponentModel.RunWorkerCompletedEventHandler(
this.backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged +=
new System.ComponentModel.ProgressChangedEventHandler(
this.backgroundWorker1_ProgressChanged);
}
private void loadButton_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
this.loadButton.Enabled = false;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string status;
Process p = new Process();
p.StartInfo.FileName = "xx.exe";
p.StartInfo.Arguments = "-q -r test.cap -p";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.OutputDataReceived += this.p_OutputDataReceived;
p.EnableRaisingEvents = true;
p.Start();
p.BeginOutputReadLine();
/*
while((status = p.StandardOutput.ReadLine()) != null)
{
Console.WriteLine(status);
string[] words = status.Split(' ');
int offset = Convert.ToInt32(words[0]);
int size = Convert.ToInt32(words[1]);
int percentComplete = 100 * offset / size;
MessageBox.Show(words[0], words[1]);
backgroundWorker1.ReportProgress(percentComplete);
}
Console.WriteLine("wait for exit!");
StreamReader myStreamReader = p.StandardOutput;
status = myStreamReader.ReadLine();
Console.WriteLine(status);
Console.WriteLine("wait for exit!");
*/
p.WaitForExit();
}
void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
string status = e.Data;
Console.WriteLine("get events");
Console.WriteLine(status);
string[] words = status.Split(' ');
int offset = Convert.ToInt32(words[0]);
int size = Convert.ToInt32(words[1]);
int percentComplete = 100 * offset / size;
MessageBox.Show(words[0], words[1]);
backgroundWorker1.ReportProgress(percentComplete);
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
progressBar1.Value = 100;
if (e.Error == null) {
MessageBox.Show ("Demo", "Loading completed");
}
}
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.loadButton = new System.Windows.Forms.Button();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
/* load button */
this.loadButton.Location = new System.Drawing.Point(12, 12);
this.loadButton.Name = "loadButton";
this.loadButton.Size = new System.Drawing.Size(100, 23);
this.loadButton.TabIndex = 0;
this.loadButton.Text = "Load file";
this.loadButton.UseVisualStyleBackColor = true;
this.loadButton.Click += new System.EventHandler(this.loadButton_Click);
/* progress bar */
this.progressBar1.Location = new System.Drawing.Point(12, 50);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(100, 26);
this.progressBar1.TabIndex = 1;
/* Form */
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(133, 104);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.loadButton);
this.Name = "DemoForm";
this.Text = "DemoForm";
this.ResumeLayout (false);
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new DemoForm());
}
}
Or is there any better way to get a command line program's progress?
You have to set the WorkerReportsProgress property of your backgroundWorker to true in order to be able to report while your backgroundWorker is running:
backgroundWorker1.WorkerReportsProgress = true;
After manually flush the output of the command line program, problem solved.
fflush(stdout);
It's not clear why it's buffered even a line ended.
Building on what Kamyar was stating, you would need to then code a delegate to capture the progress of your backgroundWorker object using a UserState object. This could be any object really, but you use it to update other aspects of the GUI, in this case a status label...
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
private class Progress
{
public string Status { get; set; }
public Progress(string status)
{
Status = status;
}
}
//...
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while(myWork)
{
if(backgroundWorker1.CancellationPending)
{
e.Cancel = true;
break;
}
int p = //...percentage calc
backgroundWorker1.ReportProgress(p, new Progress("My message...")));
}
e.Cancel = false;
}
void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
Progress p = (Progress)e.UserState;
lStatus.Text = p.Status;
progressBar.Value = e.ProgressPercentage;
}
This is just one method of implementing it though.
Thanks.