Controlling a Camera with WIA - c#

First of all, this is my first post in stackoverflow. I use this side very often and I found nearly everything I needed.
And now to my Question. I searched for this Question but I didn't really found anything. I wanted to write an application where I can click on a button and make a picture of a person and link that photo with the user in the database. Is it possible to control a camera with WIA? Do I need a special camera for that?
I would appreciate, if somebody could post a good Tutorial for the general use of WIA.

WIA Camera test example in C#. Took me a whole night!
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 WIA;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.button1.Text = "Select Camera";
this.label1.Text = "[ no camera selected ]";
}
private void Form1_Load(object sender, EventArgs e) { }
private String _label = null;
private void button1_Click_1(object sender, EventArgs e)
{
try
{
// create a new WIA common dialog box for the user to select a device from
WIA.CommonDialog dlg = new WIA.CommonDialog();
// show user the WIA device dialog
Device d = dlg.ShowSelectDevice(WiaDeviceType.CameraDeviceType, true, false);
// check if a device was selected
if (d != null)
{
// Print camera properties
richTextBox1.AppendText("\n\n Print properties:\n");
foreach (Property p in d.Properties)
{
richTextBox1.AppendText(p.Name + ": " + p.get_Value() + " ("+ p.PropertyID + ":" + p.IsReadOnly + ") \n");
// Update UI
if (p.PropertyID == 3) _label = (String) p.get_Value();
if (p.PropertyID == 4) _label = _label + " - " + p.get_Value();
this.label1.Text = _label;
}
// Print commands
richTextBox1.AppendText("\n\n Print commands:\n");
foreach (DeviceCommand dvc in d.Commands)
{
richTextBox1.AppendText(dvc.Name + ": " + dvc.Description + " ("+ dvc.CommandID +") \n");
}
// Print events
richTextBox1.AppendText("\n\n Print events:\n");
foreach (DeviceEvent dve in d.Events)
{
richTextBox1.AppendText(dve.Name + ": " + dve.Description + " (" + dve.Type + ") \n");
}
// Print item properties
richTextBox1.AppendText("\n\n Print item properties:\n");
foreach (Property item in d.Items[1].Properties)
{
richTextBox1.AppendText(item.IsReadOnly + ": " + item.Name + " (" + item.PropertyID + ") \n");
}
foreach (WIA.Property p in d.Properties)
{
Object tempNewProperty;
// change Exposure Compensation: value 0 to 2 (ID 2053, isReadonly False)
if (p.PropertyID == 2053)
{
tempNewProperty = (int) -2000; // can not be set to minus values, why???
((IProperty)p).set_Value(ref tempNewProperty);
richTextBox1.AppendText(">>>>" + p.get_Value());
}
}
// Now let's take a picture !
d.ExecuteCommand(CommandID.wiaCommandTakePicture);
richTextBox1.AppendText(".");
}
else
{
d = null;
richTextBox1.AppendText("Result: no device selected or device could not be read. ");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "WIA Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
namespace WindowsFormsApplication1
{
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.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(137, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click_1);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(9, 44);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 1;
this.label1.Text = "label1";
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(12, 60);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(946, 445);
this.richTextBox1.TabIndex = 2;
this.richTextBox1.Text = "";
//
// button2
//
this.button2.Location = new System.Drawing.Point(156, 11);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(173, 23);
this.button2.TabIndex = 3;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click_1);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(970, 517);
this.Controls.Add(this.button2);
this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.Button button2;
}
}

It looks like Microsoft has provided a tutorial here.
I think you'd be specifically interested in the section Capturing a Still Image from Streaming Video.

I've been there and I've done that. You need a camera that has WIA drivers. Several ones do it. It's not easy but can be done for sure.

As for a WIA C# wrapper, I came across ScanWIA on Codeplex. It doesn't have a whole lot of documentation. However, reading the source code might help. Also, the project has a demo project that you may tailor to get pictures from a camera.

Related

Why has my code become recursive within form1?

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.

Need help linking navigation pages to navigation bar (Windows Forms/DevExpress)

I'm working through the following tutorial:
https://documentation.devexpress.com/WindowsForms/116628/Build-an-Application/Choose-Application-UI/Office-Inspired-UI/How-to-Build-an-Office-inspired-UI-manually
I've achieved the desired output at step 8 (linking the office navigation bar and navigation bar controls), but I'm having trouble achieving the desired output at step 10 (changing the navigation page to display the different labels depending on the selected navigation bar group).
Here's my Form1.Designer.cs:
namespace dev_express_again
{
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.navigationFrame1 = new DevExpress.XtraBars.Navigation.NavigationFrame();
this.navigationPage1 = new DevExpress.XtraBars.Navigation.NavigationPage();
this.labelControl1 = new DevExpress.XtraEditors.LabelControl();
this.navigationPage2 = new DevExpress.XtraBars.Navigation.NavigationPage();
this.labelControl2 = new DevExpress.XtraEditors.LabelControl();
this.navBarControl1 = new DevExpress.XtraNavBar.NavBarControl();
this.navBarGroup1 = new DevExpress.XtraNavBar.NavBarGroup();
this.navBarGroup2 = new DevExpress.XtraNavBar.NavBarGroup();
this.officeNavigationBar1 = new DevExpress.XtraBars.Navigation.OfficeNavigationBar();
((System.ComponentModel.ISupportInitialize)(this.navigationFrame1)).BeginInit();
this.navigationFrame1.SuspendLayout();
this.navigationPage1.SuspendLayout();
this.navigationPage2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.navBarControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.officeNavigationBar1)).BeginInit();
this.SuspendLayout();
//
// navigationFrame1
//
this.navigationFrame1.Controls.Add(this.navigationPage1);
this.navigationFrame1.Controls.Add(this.navigationPage2);
this.navigationFrame1.Location = new System.Drawing.Point(146, 0);
this.navigationFrame1.Name = "navigationFrame1";
this.navigationFrame1.Pages.AddRange(new DevExpress.XtraBars.Navigation.NavigationPageBase[] {
this.navigationPage1,
this.navigationPage2});
this.navigationFrame1.SelectedPage = this.navigationPage1;
this.navigationFrame1.Size = new System.Drawing.Size(462, 311);
this.navigationFrame1.TabIndex = 0;
this.navigationFrame1.Text = "navigationFrame1";
//
// navigationPage1
//
this.navigationPage1.Caption = "navigationPage1";
this.navigationPage1.Controls.Add(this.labelControl1);
this.navigationPage1.Name = "navigationPage1";
this.navigationPage1.Size = new System.Drawing.Size(462, 311);
this.navigationPage1.Tag = "Employees";
//
// labelControl1
//
this.labelControl1.Location = new System.Drawing.Point(190, 145);
this.labelControl1.Name = "labelControl1";
this.labelControl1.Size = new System.Drawing.Size(33, 13);
this.labelControl1.TabIndex = 0;
this.labelControl1.Text = "Page 1";
//
// navigationPage2
//
this.navigationPage2.Caption = "navigationPage2";
this.navigationPage2.Controls.Add(this.labelControl2);
this.navigationPage2.Name = "navigationPage2";
this.navigationPage2.Size = new System.Drawing.Size(462, 311);
this.navigationPage2.Tag = "Customers";
//
// labelControl2
//
this.labelControl2.Location = new System.Drawing.Point(194, 135);
this.labelControl2.Name = "labelControl2";
this.labelControl2.Size = new System.Drawing.Size(33, 13);
this.labelControl2.TabIndex = 0;
this.labelControl2.Text = "Page 2";
//
// navBarControl1
//
this.navBarControl1.ActiveGroup = this.navBarGroup1;
this.navBarControl1.Groups.AddRange(new DevExpress.XtraNavBar.NavBarGroup[] {
this.navBarGroup1,
this.navBarGroup2});
this.navBarControl1.Location = new System.Drawing.Point(0, 0);
this.navBarControl1.Name = "navBarControl1";
this.navBarControl1.OptionsNavPane.ExpandedWidth = 140;
this.navBarControl1.PaintStyleKind = DevExpress.XtraNavBar.NavBarViewKind.NavigationPane;
this.navBarControl1.Size = new System.Drawing.Size(140, 311);
this.navBarControl1.TabIndex = 1;
this.navBarControl1.Text = "navBarControl1";
//
// navBarGroup1
//
this.navBarGroup1.Caption = "Employees";
this.navBarGroup1.Expanded = true;
this.navBarGroup1.Name = "navBarGroup1";
//
// navBarGroup2
//
this.navBarGroup2.Caption = "Customers";
this.navBarGroup2.Name = "navBarGroup2";
//
// officeNavigationBar1
//
this.officeNavigationBar1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.officeNavigationBar1.Location = new System.Drawing.Point(0, 317);
this.officeNavigationBar1.Name = "officeNavigationBar1";
this.officeNavigationBar1.NavigationClient = this.navBarControl1;
this.officeNavigationBar1.Size = new System.Drawing.Size(608, 45);
this.officeNavigationBar1.TabIndex = 2;
this.officeNavigationBar1.Text = "officeNavigationBar1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(608, 362);
this.Controls.Add(this.officeNavigationBar1);
this.Controls.Add(this.navBarControl1);
this.Controls.Add(this.navigationFrame1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.navigationFrame1)).EndInit();
this.navigationFrame1.ResumeLayout(false);
this.navigationPage1.ResumeLayout(false);
this.navigationPage1.PerformLayout();
this.navigationPage2.ResumeLayout(false);
this.navigationPage2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.navBarControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.officeNavigationBar1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private DevExpress.XtraBars.Navigation.NavigationFrame navigationFrame1;
private DevExpress.XtraBars.Navigation.NavigationPage navigationPage1;
private DevExpress.XtraBars.Navigation.NavigationPage navigationPage2;
private DevExpress.XtraNavBar.NavBarControl navBarControl1;
private DevExpress.XtraNavBar.NavBarGroup navBarGroup1;
private DevExpress.XtraNavBar.NavBarGroup navBarGroup2;
private DevExpress.XtraBars.Navigation.OfficeNavigationBar officeNavigationBar1;
private DevExpress.XtraEditors.LabelControl labelControl1;
private DevExpress.XtraEditors.LabelControl labelControl2;
}
}
And my 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.Windows.Forms;
namespace dev_express_again
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
navigationPage1.Tag = navBarGroup1.Caption = navigationPage1.Caption = "Employees";
navigationPage2.Tag = navBarGroup2.Caption = navigationPage2.Caption = "Customers";
officeNavigationBar1.NavigationClient = navBarControl1;
}
private void navBarControl1_ActiveGroupChanged(object sender, DevExpress.XtraNavBar.NavBarGroupEventArgs e)
{
navigationFrame1.SelectedPage = (DevExpress.XtraBars.Navigation.NavigationPage)navigationFrame1.Pages.FindFirst(x => (string)x.Tag == e.Group.Caption);
}
}
}
Both are exactly the same as the tutorial, as far as I can see. When I run the code, I get a window that looks exactly like the one in the tutorial. When I change the selection in the office navigation bar, it reflects in the navigation bar control, but does not change the navigation page.
Any ideas as to what I'm missing?
Figured out the solution. The tutorial neglected to mention that you also must add the line navBarControl1.ActiveGroupChanged += new DevExpress.XtraNavBar.NavBarGroupEventHandler(navBarControl1_ActiveGroupChanged); to Form1.cs in order to enable the user's changing of the active group to actually call the navBarControl1_ActiveGroupChanged function.

Received SMS does not show in C# application

I have a C# application that receives SMSes and displays them.
When I send an SMS without this program and using a GSM modem, the SMS gets saved in the GSM modem. When I start the application and click on "read SMS" it shows me only SMSes that were previously received, and which I have already seen in the GSM modem. A new SMS that I sent recently, is not visible.
The program just shows SMSes that are read from the modem. What should I do to show a received SMS immediately in the program?
Code:
public Receive()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <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.btnReadMessage = new System.Windows.Forms.Button();
this.rbMessagePhone = new System.Windows.Forms.RadioButton();
this.rbMessageSIM = new System.Windows.Forms.RadioButton();
this.txtOutput = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.dataGrid1 = new System.Windows.Forms.DataGrid();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// btnReadMessage
//
this.btnReadMessage.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnReadMessage.Location = new System.Drawing.Point(192, 80);
this.btnReadMessage.Name = "btnReadMessage";
this.btnReadMessage.Size = new System.Drawing.Size(112, 24);
this.btnReadMessage.TabIndex = 17;
this.btnReadMessage.Text = "Read All Messages";
this.btnReadMessage.Click += new System.EventHandler(this.btnReadMessage_Click);
//
// rbMessagePhone
//
this.rbMessagePhone.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.rbMessagePhone.Location = new System.Drawing.Point(16, 56);
this.rbMessagePhone.Name = "rbMessagePhone";
this.rbMessagePhone.Size = new System.Drawing.Size(64, 24);
this.rbMessagePhone.TabIndex = 25;
this.rbMessagePhone.Text = "Phone";
//
// rbMessageSIM
//
this.rbMessageSIM.Checked = true;
this.rbMessageSIM.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.rbMessageSIM.Location = new System.Drawing.Point(16, 24);
this.rbMessageSIM.Name = "rbMessageSIM";
this.rbMessageSIM.Size = new System.Drawing.Size(64, 24);
this.rbMessageSIM.TabIndex = 24;
this.rbMessageSIM.TabStop = true;
this.rbMessageSIM.Text = "SIM";
//
// txtOutput
//
this.txtOutput.Location = new System.Drawing.Point(8, 304);
this.txtOutput.Multiline = true;
this.txtOutput.Name = "txtOutput";
this.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtOutput.Size = new System.Drawing.Size(448, 144);
this.txtOutput.TabIndex = 57;
this.txtOutput.Text = "";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.rbMessageSIM);
this.groupBox1.Controls.Add(this.rbMessagePhone);
this.groupBox1.Location = new System.Drawing.Point(8, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(176, 96);
this.groupBox1.TabIndex = 58;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Message Storage";
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(8, 120);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(448, 176);
this.dataGrid1.TabIndex = 59;
//
// Receive
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(464, 454);
this.Controls.Add(this.dataGrid1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.txtOutput);
this.Controls.Add(this.btnReadMessage);
this.Name = "Receive";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Read Messages";
this.Load += new System.EventHandler(this.Receive_Load);
this.groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void btnReadMessage_Click(object sender, System.EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
string storage = GetMessageStorage();
try
{
// Read all SMS messages from the storage
DecodedShortMessage[] messages = CommSetting.comm.ReadMessages(PhoneMessageStatus.All,storage );
foreach(DecodedShortMessage message in messages)
{
Output(string.Format("Message status = {0}, Location = {1}/{2}",
StatusToString(message.Status), message.Storage, message.Index));
ShowMessage(message.Data);
Output("");
}
Output(string.Format("{0,9} messages read.", messages.Length.ToString()));
Output("");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Cursor.Current = Cursors.Default;
}
private void BindGrid(SmsPdu pdu)
{
DataRow dr=dt.NewRow();
SmsDeliverPdu data = (SmsDeliverPdu)pdu;
dr[0]=data.OriginatingAddress.ToString();
dr[1]=data.SCTimestamp.ToString();
dr[2]=data.UserDataText;
dt.Rows.Add(dr);
dataGrid1.DataSource=dt;
}
private void ShowMessage(SmsPdu pdu)
{
if (pdu is SmsSubmitPdu)
{
// Stored (sent/unsent) message
SmsSubmitPdu data = (SmsSubmitPdu)pdu;
Output("SENT/UNSENT MESSAGE");
Output("Recipient: " + data.DestinationAddress);
Output("Message text: " + data.UserDataText);
Output("-------------------------------------------------------------------");
return;
}
if (pdu is SmsDeliverPdu)
{
// Received message
SmsDeliverPdu data = (SmsDeliverPdu)pdu;
Output("RECEIVED MESSAGE");
Output("Sender: " + data.OriginatingAddress);
Output("Sent: " + data.SCTimestamp.ToString());
Output("Message text: " + data.UserDataText);
Output("-------------------------------------------------------------------");
BindGrid(pdu);
return;
}
if (pdu is SmsStatusReportPdu)
{
// Status report
SmsStatusReportPdu data = (SmsStatusReportPdu)pdu;
Output("STATUS REPORT");
Output("Recipient: " + data.RecipientAddress);
Output("Status: " + data.Status.ToString());
Output("Timestamp: " + data.DischargeTime.ToString());
Output("Message ref: " + data.MessageReference.ToString());
Output("-------------------------------------------------------------------");
return;
}
Output("Unknown message type: " + pdu.GetType().ToString());
}
private string StatusToString(PhoneMessageStatus status)
{
// Map a message status to a string
string ret;
switch(status)
{
case PhoneMessageStatus.All:
ret = "All";
break;
case PhoneMessageStatus.ReceivedRead:
ret = "Read";
break;
case PhoneMessageStatus.ReceivedUnread:
ret = "Unread";
break;
case PhoneMessageStatus.StoredSent:
ret = "Sent";
break;
case PhoneMessageStatus.StoredUnsent:
ret = "Unsent";
break;
default:
ret = "Unknown (" + status.ToString() + ")";
break;
}
return ret;
}
private string GetMessageStorage()
{
string storage = string.Empty;
if (rbMessageSIM.Checked)
storage = PhoneStorageType.Sim;
if (rbMessagePhone.Checked)
storage = PhoneStorageType.Phone;
if (storage.Length == 0)
throw new ApplicationException("Unknown message storage.");
else
return storage;
}
private void Output(string text)
{
if (this.txtOutput.InvokeRequired)
{
SetTextCallback stc = new SetTextCallback(Output);
this.Invoke(stc, new object[] { text });
}
else
{
txtOutput.AppendText(text);
txtOutput.AppendText("\r\n");
}
}
private void Receive_Load(object sender, System.EventArgs e)
{
dt.Columns.Add("Sender",typeof(string));
dt.Columns.Add("Time",typeof(string));
dt.Columns.Add("Message",typeof(string));
}
private void Output(string text, params object[] args)
{
string msg = string.Format(text, args);
Output(msg);
}
If you are using GSMCOMM class, I think you're missing the
comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived);
though you have to set the modem to notify you of an incoming message. Look at the samples included in the GSMComm Demo.

How to write a Text file from this Output

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);
}
}
}

Ways of displaying exe icons in a ListView

Using a ListView, I need to display (large) icons for an array of executables.
Is there a standard way of doing this / a "Pattern" (whether Design or otherwise)?
A wrinkle: these .exes should be runnable from this ListView ONLY. If a person were to navigate to the .exe via Explorer, they should not be able to run them from there. IOW, the user must log in to the system before seeing the array of program icons (and what they see will depend on their role)*, and that is the ONLY gateway to run those apps.
So, these app icons must be added programmatically.
Ideas?
Update:
Trying to use the code below to create a "Quick and Dirty" app.
Here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ListViewWithAppIcons {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
DirectoryInfo dir = new DirectoryInfo(#"C:\SpotRun");
foreach (FileInfo file in dir.GetFiles()) {
try {
this.imageList1.Images.Add(Image.FromFile(file.FullName));
} catch {
Console.WriteLine("This is not a Duck-billed Platypus");
}
}
this.listView1.View = View.LargeIcon;
this.imageList1.ImageSize = new Size(32, 32);
this.listView1.LargeImageList = this.imageList1;
//or
//this.listView1.View = View.SmallIcon;
//this.listView1.SmallImageList = this.imageList1;
for (int j = 0; j < this.imageList1.Images.Count; j++) {
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
this.listView1.Items.Add(item);
}
}
}
}
..and here's the "code generated by a tool" (not me, the other tool):
namespace ListViewWithAppIcons {
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.components = new System.ComponentModel.Container();
this.listView1 = new System.Windows.Forms.ListView();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
// listView1
//
this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listView1.Location = new System.Drawing.Point(0, 0);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(555, 408);
this.listView1.TabIndex = 0;
this.listView1.UseCompatibleStateImageBehavior = false;
//
// imageList1
//
this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(555, 408);
this.Controls.Add(this.listView1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.ImageList imageList1;
}
}
Hi Clay, I need to reference a superfluous Princess Bride!
An example off MSDN so you know your coding it up sweet:
private void Form_Load(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(#"c:\pic");
foreach (FileInfo file in dir.GetFiles())
{
try
{
this.imageList1.Images.Add(Image.FromFile(file.FullName));
}
catch
{
Console.WriteLine("This is not an image file");
}
}
this.listView1.View = View.LargeIcon;
this.imageList1.ImageSize = new Size(32, 32);
this.listView1.LargeImageList = this.imageList1;
//or
//this.listView1.View = View.SmallIcon;
//this.listView1.SmallImageList = this.imageList1;
for (int j = 0; j < this.imageList1.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
this.listView1.Items.Add(item);
}
}
To prevent people from opening the exe's (except from your program) is pretty hard, it would be easy if you wrote all those applications and could require a secret argument (as in like a command line arg) be passed in to start the other applications. But using Process Monitor/Explorer users could find out the secret key.
Alternatively you could hide the exe's in some folder but the trick here is that the name of the exe will be shown in Task Manager and once users see this they could search for the exe. I mean you could get around this using my technique here, but how deep is the rabits hole: How to hide C# application from taskmanager processtab? - see my answer, its got the most votes.
Maybe a better solution than all this mucking around hiding stuf from users would be - Kiosk mode: http://support.microsoft.com/kb/555463

Categories

Resources