Cross-thread operation not valid: Control 'ocrTB' accessed from a thread other than the thread it was created on.
This is the error i have. And below is my coding.
#region OCR(Tab5_Component)
//When user is selecting, RegionSelect = true
private bool RegionSelect = false;
private int x0, x1, y0, y1;
private Bitmap bmpImage;
private void loadImageBT_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = #"C:\Users\Shen\Desktop";
open.Filter = "Image Files(*.jpg; *.jpeg)|*.jpg; *.jpeg";
if (open.ShowDialog() == DialogResult.OK)
{
singleFileInfo = new FileInfo(open.FileName);
string dirName = System.IO.Path.GetDirectoryName(open.FileName);
loadTB.Text = open.FileName;
pictureBox1.Image = new Bitmap(open.FileName);
bmpImage = new Bitmap(pictureBox1.Image);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
//User image selection Start Point
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
RegionSelect = true;
//Save the start point.
x0 = e.X;
y0 = e.Y;
}
//User select image progress
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
//Do nothing it we're not selecting an area.
if (!RegionSelect) return;
//Save the new point.
x1 = e.X;
y1 = e.Y;
//Make a Bitmap to display the selection rectangle.
Bitmap bm = new Bitmap(bmpImage);
//Draw the rectangle in the image.
using (Graphics g = Graphics.FromImage(bm))
{
g.DrawRectangle(Pens.Red, Math.Min(x0, x1), Math.Min(y0, y1), Math.Abs(x1 - x0), Math.Abs(y1 - y0));
}
//Temporary display the image.
pictureBox1.Image = bm;
}
//Image Selection End Point
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Do nothing it we're not selecting an area.
if (!RegionSelect) return;
RegionSelect = false;
//Display the original image.
pictureBox1.Image = bmpImage;
// Copy the selected part of the image.
int wid = Math.Abs(x0 - x1);
int hgt = Math.Abs(y0 - y1);
if ((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using (Graphics g = Graphics.FromImage(area))
{
Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
}
// Display the result.
pictureBox3.Image = area;
pictureBox3.Image.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");
}
/*private void loadFolderBT_Click(object sender, EventArgs e)
{
folderBrowserDialog.ShowDialog();
folderLocation.Text = folderBrowserDialog.SelectedPath;
}*/
private void ScanBT_Click(object sender, EventArgs e)
{
var folder = #"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";
DirectoryInfo directoryInfo;
FileInfo[] files;
directoryInfo = new DirectoryInfo(folder);
files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);
exit = false;
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, null, null);
System.IO.File.Delete(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");
}
private void ProcessImages2(FileInfo[] files)
{
var comparableImages = new List<ComparableImage>();
//Invoke(setMaximumDelegate, new object[] { workingProgressBar, files.Length });
var index = 0x0;
var operationStartTime = DateTime.Now;
foreach (var file in files)
{
if (exit)
{
return;
}
var comparableImage = new ComparableImage(file);
comparableImages.Add(comparableImage);
index++;
//Invoke(updateOperationStatusDelegate, new object[] { "Processed images", workingLabel, workingProgressBar, index, operationStartTime });
}
//Invoke(setMaximumDelegate, new object[] { workingProgressBar, comparableImages.Count });
index = 0;
similarityImagesSorted = new List<SimilarityImages>();
operationStartTime = DateTime.Now;
var fileImage = new ComparableImage(singleFileInfo);
for (var i = 0; i < comparableImages.Count; i++)
{
if (exit)
return;
var destination = comparableImages[i];
var similarity = fileImage.CalculateSimilarity(destination);
var sim = new SimilarityImages(fileImage, destination, similarity);
similarityImagesSorted.Add(sim);
index++;
//Invoke(updateOperationStatusDelegate, new object[] { "Compared images", workingLabel, workingProgressBar, index, operationStartTime });
}
similarityImagesSorted.Sort();
similarityImagesSorted.Reverse();
similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);
var buttons =
new List<Button>
{
ScanBT
};
if (similarityImages[0].Similarity > 85)
{
//MessageBox.Show("Similarity(%) : " + similarityImages[0].Similarity.ToString(), "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
//MessageBox.Show("Similarity(%) : " + similarityImages[0].Destination.ToString(), "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
//MessageBox.Show("Similarity(%) : " + similarityImages[0].Source.ToString(), "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getFile = "SELECT ImageName, Character FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination + "'";
SqlCommand cmd2 = new SqlCommand(getFile, con);
SqlDataReader rd2 = cmd2.ExecuteReader();
while (rd2.Read())
{
ocrTB.Text = rd2["Character"].ToString(); // <<<<<< error occur here
}
con.Close();
}
else
{
MessageBox.Show("No character found!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
Any solution for this?
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, null, null);
You are executing this delegate asynchronously in a different thread - are you sure that's what you want? That being the case you can use Control.Invoke() to update a UI control from another thread (the one your ProcessImages2 method is executed under) :
string text = rd2["Character"].ToString();
Action updateText = () => ocrTB.Text = text;
ocrTB.Invoke(updateText);
In general it would be easier to use a background worker to process your data and update it in the Completed event handler.
You cannot modify the UI in any thread other than the UI thread, ProcessImages2 in this example attempts to do this, you need to use Dispatcher.Invoke or just run ProcessImages2 in the same thread (i.e. don't do processImagesDelegate.BeginInvoke.
Also, posting a big chunk of code can be good, but try to give details on which line is throwing the error!
You need to marshal back to the other thread when trying to access controls on the UI from a new thread.. You can use Control.Invoke like such:
someControl.Invoke((MethodInvoker)delegate
{
someControl.DoSomething();
});
Related
So basically I used two speech recognition engines(speechrecog & speechrecog1) and one speech synthesizer. When the speechrecog is asked a question like how are you
it then replies I am fine (if the computer picks 2 from the two numbers 1,2). Then it initializes the second speech recognition engine. When it does its stuff. It then turns the second one off and the first one on again. But the problem is when using the second speech recognition engine it repeats( speech synthesizer) the number of times I have tried the second speech recognition engine out.
Here's my code for that form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Threading;
namespace Project_Juliet
{
public partial class Form11 : Form
{
public Form11()
{
InitializeComponent();
}
class FullScreen
{
public void EnterFullScreenMode(Form targetForm)
{
targetForm.WindowState = FormWindowState.Normal;
targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.WindowState = FormWindowState.Maximized;
}
public void LeaveFullScreenMode(Form targetForm)
{
targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
targetForm.WindowState = FormWindowState.Normal;
}
}
// System.Globalization.CultureInfo cl2 = new System.Globalization.CultureInfo("en-US");
SpeechRecognitionEngine speechrecog = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
SpeechSynthesizer ss = new SpeechSynthesizer();
PromptBuilder pb = new PromptBuilder();
Choices zlist = new Choices();
Form2 frm = new Form2();
FullScreen fs = new FullScreen();
bool SpeechRecognitionState = true;
Choices dirlist = new Choices();
SpeechRecognitionEngine speechrecog1 = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
bool sprs2 = false;
Choices us = new Choices();
string dir234;
string[] gm;
private void Form11_Load(object sender, EventArgs e)
{
listBox1.Visible = false;
string dir = "C:/Users/" + Environment.UserName + "/Documents/Juliet/response";
DirectoryInfo dinfo = new DirectoryInfo(dir);
FileInfo[] Files = dinfo.GetFiles("*.txt");
webBrowser1.ScriptErrorsSuppressed = true;
foreach (FileInfo file2 in Files)
{
string yts = ".txt";
listBox1.Items.Add(file2.Name.Replace(yts + "", ""));
}
/* String[] list = new String();
list = listBox1.Items.OfType<string>().ToList();
*/
fs.EnterFullScreenMode(this);
textBox1.Width = toolStrip1.Width - 10;
// toolStripTextBox1.Width = toolStrip1.Width - 30;
// toolStripTextBox1.Select();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Teen);
zlist.Add(new string[] { "exit"});
Grammar gr = new Grammar(new GrammarBuilder(zlist));
gr.Weight = 0.9f;
dirlist.Add(new string[]{"Mr.Danely"});
foreach (FileInfo file2 in Files)
{
string yts = ".txt";
dirlist.Add(file2.Name.Replace(yts + "", ""));
}
Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
gr1.Weight = 1f;
Grammar tgi = new DictationGrammar();
tgi.Weight = 0.3f;
try
{
if (SpeechRecognitionState == true)
{
speechrecog.RequestRecognizerUpdate();
speechrecog.LoadGrammar(gr);
speechrecog.LoadGrammar(gr1);
speechrecog.LoadGrammar(tgi);
speechrecog.SpeechRecognized += speechrecog_SpeechRecognized;
speechrecog.SetInputToDefaultAudioDevice();
speechrecog.RecognizeAsync(RecognizeMode.Multiple);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
//us.Add(new string[] { "yes","no","good","bad" });
us.Add(new string[] { "exit" });
Grammar gr12 = new Grammar(new GrammarBuilder(us));
if (sprs2 == true)
{
}
}
void speechrecog1_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if(File.Exists(#"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//"+e.Result.Text.ToString()+".txt"))
{
string hjjk = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//" + e.Result.Text.ToString() + ".txt";
StreamReader file = new StreamReader(hjjk);
string readText = file.ReadLine();
file.Close();
ss.Speak(readText);
timer2.Interval = 10;
timer2.Start();
}
}
void speechrecog_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string igput = e.Result.Text.ToString();
dir234 = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//" + igput + ".txt";
if (igput == "exit")
{
speechrecog.RecognizeAsyncStop();
this.Hide();
frm.Closed += (s, args) => this.Close();
frm.Show();
}
else
{
if (File.Exists(dir234))
{
StreamReader file = new StreamReader(dir234);
string readText = file.ReadLine();
file.Close();
if (readText.Contains("%"))
{
string[] words = readText.Split('%');
Random r = new Random();
int selection = r.Next(1, 3);
if (selection == 1)
{
ss.SpeakAsync(words[0]);
}
if (selection == 2)
{
if (readText.Contains('#'))
{
SpeechRecognitionState = false;
us.Add(new string[] { "exit" });
gm = words[1].Split('#');
string speak = words[0] + gm[0];
ss.SpeakAsync(speak);
List<string> lk = gm.ToList();
lk.RemoveAt(0);
string[] hkl = lk.ToArray<string>();
foreach(string g3 in hkl)
{
if (g3.Contains(".txt"))
{
string fj = g3.Replace(".txt" + "", "");
us.Add(fj);
}
else
{
string fj = g3;
us.Add(fj);
}
}
string dir333 = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1";
Grammar gr12 = new Grammar(new GrammarBuilder(us));
try
{
speechrecog1.RequestRecognizerUpdate();
speechrecog1.LoadGrammar(gr12);
speechrecog1.SpeechRecognized += speechrecog1_SpeechRecognized;
speechrecog1.SetInputToDefaultAudioDevice();
speechrecog1.RecognizeAsync(RecognizeMode.Single);
//speechrecog1.RecognizeAsyncStop();
//speechrecog.RecognizeAsync(RecognizeMode.Multiple);
//_completed.WaitOne(); // wait until speech recognition is completed
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
// timer2.Interval = 7000;
//timer2.Start();
// timer2.Interval = 5000;
//timer2.Start();
}
else
{
string speak = words[0] + words[1];
ss.SpeakAsync(speak);
}
}
}
else
{
ss.Speak(readText);
}
}
else
{
try
{
tabControl1.SelectedIndex = 1;
webBrowser1.Navigate("https://www.google.com/search?q=" + e.Result.Text.ToString());
}
catch (Exception ex)
{
string ggh = "Error"+ex;
}
}
}
/* SpeechRecognitionState = false;
timer1.Interval = 3000;
timer1.Start();
* */
textBox1.Text = "You: "+e.Result.Text.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
SpeechRecognitionState = true;
timer1.Stop();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void timer2_Tick(object sender, EventArgs e)
{
//loading the grammar again somehow make the recognition better
speechrecog.UnloadAllGrammars();
Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
gr1.Weight = 1f;
Grammar tgi = new DictationGrammar();
tgi.Weight = 0.3f;
Grammar gr = new Grammar(new GrammarBuilder(zlist));
gr.Weight = 0.9f;
speechrecog.LoadGrammar(gr);
speechrecog.LoadGrammar(gr1);
speechrecog.LoadGrammar(tgi);
SpeechRecognitionState = true;
speechrecog1.RecognizeAsyncStop();
speechrecog1.UnloadAllGrammars();
timer2.Stop();
}
}
}
For example:
the text file how are you.txt contains:
i am fine. thank you.% how are you#good#bad
and the computer asks if im good and I reply with good. In the good.txt file:
Oh thats cool
the first time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(1 time)
the 2nd time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(repeats it 2 times)
the 3rd time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(repeats it 3 times)
How do i fix the repetition problem.
Thanks to #Nikolay Shmyrev I found the solution. As he said my event handler was firing twice. So inside it I put a:
try
{
//My code
}
finally
{
speechrecog1.SpeechRecognized -= speechrecog1_SpeechRecognized;
}
I'm exploring Microsoft Cognitive Face API and I'm very new to it. I'm able to achieve Face Attributes with an image which is easy but, my question is how can I get Face Attributes of a person in a real time video feed from Kinect in WPF c#. It would be great if somebody can help me out. Thanks in Advance!
I have tried capturing the frame from the Kinect color feed at every 2 seconds to some file location and use that file path and converted it to a Stream and then pass it on to the Face-API Functions and that worked. Following is the code I tried.
namespace CognitiveFaceAPISample
{
public partial class MainWindow : Window
{
private readonly IFaceServiceClient faceServiceClient = new FaceServiceClient("c2446f84b1eb486ca11e2f5d6e670878");
KinectSensor ks;
ColorFrameReader cfr;
byte[] colorData;
ColorImageFormat format;
WriteableBitmap wbmp;
BitmapSource bmpSource;
int imageSerial;
DispatcherTimer timer,timer2;
string streamF = "Frames//frame.jpg";
public MainWindow()
{
InitializeComponent();
ks = KinectSensor.GetDefault();
ks.Open();
var fd = ks.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Bgra);
uint frameSize = fd.BytesPerPixel * fd.LengthInPixels;
colorData = new byte[frameSize];
format = ColorImageFormat.Bgra;
imageSerial = 0;
cfr = ks.ColorFrameSource.OpenReader();
cfr.FrameArrived += cfr_FrameArrived;
}
void cfr_FrameArrived(object sender, ColorFrameArrivedEventArgs e)
{
if (e.FrameReference == null) return;
using (ColorFrame cf = e.FrameReference.AcquireFrame())
{
if (cf == null) return;
cf.CopyConvertedFrameDataToArray(colorData, format);
var fd = cf.FrameDescription;
// Creating BitmapSource
var bytesPerPixel = (PixelFormats.Bgr32.BitsPerPixel) / 8;
var stride = bytesPerPixel * cf.FrameDescription.Width;
bmpSource = BitmapSource.Create(fd.Width, fd.Height, 96.0, 96.0, PixelFormats.Bgr32, null, colorData, stride);
// WritableBitmap to show on UI
wbmp = new WriteableBitmap(bmpSource);
FacePhoto.Source = wbmp;
}
}
private void SaveImage(BitmapSource image)
{
try
{
FileStream stream = new System.IO.FileStream(#"Frames\frame.jpg", System.IO.FileMode.OpenOrCreate);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.FlipHorizontal = true;
encoder.FlipVertical = false;
encoder.QualityLevel = 30;
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(stream);
stream.Close();
}
catch (Exception)
{
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
timer.Tick += Timer_Tick;
timer.Start();
timer2 = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer2.Tick += Timer2_Tick;
timer2.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
SaveImage(bmpSource);
}
private async void Timer2_Tick(object sender, EventArgs e)
{
Title = "Detecting...";
FaceRectangle[] faceRects = await UploadAndDetectFaces(streamF);
Face[] faceAttributes = await UploadAndDetectFaceAttributes(streamF);
Title = String.Format("Detection Finished. {0} face(s) detected", faceRects.Length);
if (faceRects.Length > 0)
{
DrawingVisual visual = new DrawingVisual();
DrawingContext drawingContext = visual.RenderOpen();
drawingContext.DrawImage(bmpSource,
new Rect(0, 0, bmpSource.Width, bmpSource.Height));
double dpi = bmpSource.DpiX;
double resizeFactor = 96 / dpi;
foreach (var faceRect in faceRects)
{
drawingContext.DrawRectangle(
Brushes.Transparent,
new Pen(Brushes.Red, 2),
new Rect(
faceRect.Left * resizeFactor,
faceRect.Top * resizeFactor,
faceRect.Width * resizeFactor,
faceRect.Height * resizeFactor
)
);
}
drawingContext.Close();
RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
(int)(bmpSource.PixelWidth * resizeFactor),
(int)(bmpSource.PixelHeight * resizeFactor),
96,
96,
PixelFormats.Pbgra32);
faceWithRectBitmap.Render(visual);
FacePhoto.Source = faceWithRectBitmap;
}
if (faceAttributes.Length > 0)
{
foreach (var faceAttr in faceAttributes)
{
Label lb = new Label();
//Canvas.SetLeft(lb, lb.Width);
lb.Content = faceAttr.FaceAttributes.Gender;// + " " + faceAttr.Gender + " " + faceAttr.FacialHair + " " + faceAttr.Glasses + " " + faceAttr.HeadPose + " " + faceAttr.Smile;
lb.FontSize = 50;
lb.Width = 200;
lb.Height = 100;
stack.Children.Add(lb);
}
}
}
private async Task<FaceRectangle[]> UploadAndDetectFaces(string imageFilePath)
{
try
{
using (Stream imageFileStream = File.OpenRead(imageFilePath))
{
var faces = await faceServiceClient.DetectAsync(imageFilePath);
var faceRects = faces.Select(face => face.FaceRectangle);
var faceAttrib = faces.Select(face => face.FaceAttributes);
return faceRects.ToArray();
}
}
catch (Exception)
{
return new FaceRectangle[0];
}
}
private async Task<Face[]> UploadAndDetectFaceAttributes(string imageFilePath)
{
try
{
using (Stream imageFileStream = File.Open(imageFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var faces = await faceServiceClient.DetectAsync(imageFileStream, true, true, new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Glasses, FaceAttributeType.HeadPose, FaceAttributeType.FacialHair });
return faces.ToArray();
}
}
catch (Exception)
{
return new Face[0];
}
}
}
Above code worked well. But, I want to convert each frame of Kinect Color Feed directly to Stream and I have no idea how to do it though I searched but nothing worked for me. If Somebody can help me then it'll be great. Thanks!
Instead of persisting the frame to a file in SaveImage, you can persist it to a MemoryStream, rewind it (by calling Position = 0), and send that stream to DetectAsync().
Also note that in UploadAndDetectFaces, you should send imageFileStream, not imageFilePath, to DetectAsync(). You probably don't want to call both UploadAndDetectFaces and UploadAndDetectFaceAttributes anyway, since you're just doubling your work (and quota/rate-limit hit.)
I am currently working on a small DB project in which I have tried implementing a browser for image so that they can be saved for each player accordingly.
I am particularly struggling with wring the path of the image to a string, and the storing that string into the arraylist which will then be used to load the file by using the path stored in that arraylist. As you see in the code I have tried to assign the OpenFd.FileName to a string called pathToImage but it doesn't work, the string remains empty after a quick debug check using MessageBox.Show(pathToImage)
Can anyone help me?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assignment1_Template2
{
public partial class Form1 : Form
{
// =======================The data Structure ===========================
// ========Uses [SERIALIZABLE] to allow simple loading/saving ==========
[Serializable]
private struct myStruct
{ // The "constructor". Fills data structure with default values
public myStruct(int playerId)
{
uniquePlayerId = new int[playerId];
playerIgName = "";
contactStreet = "";
contactTown = "";
contactPostcode = "";
contactEmail = "";
contactTelephone = "";
imagePath = "";
for (int i = 0; i < playerId; ++i) uniquePlayerId[i] = 0;
}
// The data types of the struct
public int[] uniquePlayerId;
public string playerIgName;
public string contactStreet;
public string contactTown;
public string contactPostcode;
public string contactEmail;
public string contactTelephone;
public string imagePath;
}
// ================== End of data Structure definition ===================
// =======================================================================
// ================ Global Variables used in the Program =================
private ArrayList dataList; // This is the main data collection
private int currentEntryShown = 0; // current myStruct on display
private int numberOfEntries = 0; // total number of myStructs
private string filename = "C:\\test.dat"; // path of the file being read in
public string pathToImage = "";
public string pathToImagePlaceholder = "";
// =======================================================================
// ================== STARTING POINT FOR THE PROGRAM =====================
public Form1()
{
// Brings up the window.
InitializeComponent();
// Create the ArrayList
dataList = new ArrayList();
// Call methods implemented below
LoadData();
ShowData();
UpdatePrevNextBtnStatus();
}
// =========================================================================
// =================== END OF STARTING POINT FOR PROGRAM ===================
// ========= All further events are now triggered by user actions ==========
// =========================================================================
// =========================================================================
// ========================= BUTTON ACTION HANDLERS ========================
// =========================================================================
private void showPreviousBtn_Click(object sender, EventArgs e)
{
--currentEntryShown;
ShowData();
UpdatePrevNextBtnStatus();
}
private void showNextBtn_Click(object sender, EventArgs e)
{
++currentEntryShown;
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void addNewPlayerBtn_Click(object sender, EventArgs e)
{
++numberOfEntries; // "Add" clicked: we need to create one more entry
currentEntryShown = numberOfEntries - 1; // scroll to an empty record at the end
// Create a new data structure, its constructor will fill it with default values
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct); // add the frshly created struct to the ArrayList
ShowData(); // display
addNewPlayerBtn.Enabled = true; // can't do this again before saving
UpdatePrevNextBtnStatus();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
SaveData(); // Call the Save() method implemented below
addNewPlayerBtn.Enabled = true; // After saving we can add another new record
UpdatePrevNextBtnStatus(); // Set 'Next' and 'Previous' button appearance
}
// =========================================================================
// =========================================================================
// ================ HANDLE DATA CHANGES BY USER ============================
// =========================================================================
// If the text box string is changed by the user, update
private void playerIdBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
dataList[currentEntryShown] = aNewStruct;
}
private void playerIgNameBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.playerIgName = playerIgNameBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactStreetBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactStreet = contactStreetBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTownBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTown = contactTownBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactPostcode = contactPostcodeBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactEmailBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactEmail = contactEmailBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTelephone = contactTelephoneBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
// =========================================================================
// ================= HELPER METHODS FOR DISPLAYING DATA ====================
// =========================================================================
private void ShowData()
{
playerIdBox.Text = ((myStruct)dataList[currentEntryShown]).uniquePlayerId[0].ToString();
playerIgNameBox.Text = ((myStruct)dataList[currentEntryShown]).playerIgName;
contactStreetBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactStreet;
contactTownBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTown;
contactPostcodeBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactPostcode;
contactEmailBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactEmail;
contactTelephoneBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTelephone;
pathToImagePlaceholder = "" + ((myStruct)dataList[currentEntryShown]).imagePath;
MessageBox.Show(pathToImagePlaceholder);
try
{
playerPictureBox.Image = Image.FromFile(pathToImagePlaceholder);
}
catch
{
return;
}
}
private void UpdatePrevNextBtnStatus()
{
if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
else showPreviousBtn.Enabled = false;
if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
else showNextBtn.Enabled = false;
label1.Text = "Player ID";
label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
}
// =========================================================================
// =========================================================================
// =============== HELPER METHODS FOR LOADING AND SAVING ===================
// =========================================================================
private void SaveData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, dataList);
MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Could not serialise to " + filename,
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
MessageBox.Show("Could not open " + filename +
" for saving.\nNo access rights to the folder, perhaps?",
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void LoadData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
try
{
BinaryFormatter bf = new BinaryFormatter();
dataList = (ArrayList)bf.Deserialize(fs);
currentEntryShown = 0;
numberOfEntries = dataList.Count;
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename +
"\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
"FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
fs.Close(); // close file
Environment.Exit(1); // crash out
}
fs.Close();
}
catch
{
if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
"FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
// No data exist yet. Create a first entry
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct);
numberOfEntries = 1;
currentEntryShown = 0;
}
}
}
// =========================================================================
// =========================================================================
// ====================== HELPER METHODS FOR SORTING =======================
// =========================================================================
// This function will sort by player name by using the PlayerNameComparer below
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
dataList.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
// Overriding (= overwriting) the default IComparer
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((myStruct)x).playerIgName.CompareTo(((myStruct)y).playerIgName);
}
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveData();
UpdatePrevNextBtnStatus();
}
private void deletePlayerBtn_Click(object sender, EventArgs e)
{
dataList.RemoveAt(currentEntryShown);
SaveData();
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
Form searchForm = new Form1();
searchForm.Show();
}
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
pathToImage = OpenFd.FileName;
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = pathToImage;
dataList[currentEntryShown] = aNewStruct;
// save the FileName to a string.
}
MessageBox.Show(pathToImage);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
Set pathToImage after the ShowDIalog has completed, not before:
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
pathToImage = OpenFd.FileName; ...
I could be wrong because reading all that wall of code requires too much time, but your last method should be
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
// REMOVED HERE .... pathToImage = OpenFd.FileName
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = OpenFd.FileName; // Changed this line...
dataList[currentEntryShown] = aNewStruct;
}
// no much sense this here if the user cancel the dialogbox
// MessageBox.Show(pathToImage);
}
I have this class,
public class ImageBox : Grid
{
Image imgclose; public String path;
List<ImageBox> ImageBoxes;
public ImageBox(string label,List<ImageBox> ImBox)
{
this.ImageBoxes = ImBox;
imgclose = new Image();
imgclose.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("pack://application:,,,/Close.ico"));
imgclose.Width = 20; imgclose.Height = 20; imgclose.Cursor = Cursors.Hand; imgclose.HorizontalAlignment = System.Windows.HorizontalAlignment.Right; imgclose.VerticalAlignment = System.Windows.VerticalAlignment.Top;
imgclose.Visibility = System.Windows.Visibility.Hidden;
imgclose.MouseLeftButtonDown += new MouseButtonEventHandler(imgclose_MouseLeftButtonDown);
this.MouseEnter += new MouseEventHandler(Blank_MouseEnter);
this.MouseLeave += new MouseEventHandler(Blank_MouseLeave);
this.Height = 100; this.Width = 100;
try
{
System.Windows.Forms.OpenFileDialog open = new System.Windows.Forms.OpenFileDialog();
path = open.FileName.Replace(Directory.GetCurrentDirectory(), "");
this.Background = new System.Windows.Media.ImageBrush(new System.Windows.Media.Imaging.BitmapImage(new Uri(label)));
path = label;
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
Grid.SetColumn(imgclose, 0); Grid.SetRow(imgclose, 1);
this.Children.Add(imgclose);
ContextMenu contextMenu1 = new ContextMenu();
MenuItem conitem1 = new MenuItem() { Header = "Send to back" }; conitem1.Click += new System.Windows.RoutedEventHandler(conitem1_Click);
MenuItem conitem2 = new MenuItem() { Header = "Bring to Front" }; conitem2.Click += new System.Windows.RoutedEventHandler(conitem2_Click);
contextMenu1.Items.Add(conitem1); contextMenu1.Items.Add(conitem2);
this.ContextMenu = contextMenu1;
}
void conitem1_Click(object sender, EventArgs e)
{
Canvas.SetZIndex(this, (Canvas.GetZIndex(this) - 1));
}
void conitem2_Click(object sender, EventArgs e)
{
Canvas.SetZIndex(this, (Canvas.GetZIndex(this) + 1));
}
void Blank_MouseEnter(object sender, MouseEventArgs e)
{
imgclose.Visibility = System.Windows.Visibility.Visible;
}
void Blank_MouseLeave(object sender, MouseEventArgs e)
{
imgclose.Visibility = System.Windows.Visibility.Hidden;
}
void imgclose_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (System.Windows.MessageBox.Show("Are you sure?", "Confirm", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Question) == System.Windows.MessageBoxResult.OK)
{
ImageBoxes.Remove(this);
(this.Parent as System.Windows.Controls.Canvas).Children.Remove(this);
}
else
{
}
}
}
This class displays an image (chosen from a dialog box).
How can I modify it to make it play a video file ?
More precisely,
How should I modify the line
this.Background = new System.Windows.Media.ImageBrush(new System.Windows.Media.Imaging.BitmapImage(new Uri(label)));
path = label;
so that it plays a video file.
The Background property has to have some sort of Brush in it. A quick Google search came up with this: VideoBrush. I hope this is what you were looking for.
Let's say I have 3 image views in my xaml . I am downloading images from a server & now I want to set those images in my image views . How can I do that ? Please Help !
My Code :
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//parse data
var container = DeserializeFromJson<DataJsonAttributeContainer>(e.Result);
//load into list
for (int i = 0; i < container.MyBookList.Count; i++)
{
newData[i] = new data();
newData[i].id = container.MyBookList[i].ID;
newData[i].title = container.MyBookList[i].TITLE;
newData[i].type = container.MyBookList[i].TYPE;
newData[i].price = container.MyBookList[i].PRICE;
newData[i].downloadLink = container.MyBookList[i].DOWNLOADLINK;
string file_name = newData[i].downloadLink.ToString();
string image_uri = "http://www.banglanews24.com/images/imgAll/" + file_name;
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri(image_uri), wc);
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
try
{ //I can set just one image here....what should I do ?
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
image1.Source = image;
}
catch (Exception ex)
{
//Exception handle appropriately for your app
}
}
else
{
//Either cancelled or error handle appropriately for your app
}
}
This should do it:
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//parse data
var container = DeserializeFromJson<DataJsonAttributeContainer>(e.Result);
//load into list
for (int i = 0; i < container.MyBookList.Count; i++)
{
newData[i] = new data();
newData[i].id = container.MyBookList[i].ID;
newData[i].title = container.MyBookList[i].TITLE;
newData[i].type = container.MyBookList[i].TYPE;
newData[i].price = container.MyBookList[i].PRICE;
newData[i].downloadLink = container.MyBookList[i].DOWNLOADLINK;
string file_name = newData[i].downloadLink.ToString();
string image_uri = "http://www.banglanews24.com/images/imgAll/" + file_name;
Uri uri = new Uri(image_uri, UriKind.Relative);
ImageSource imgSource = new BitmapImage(uri);
if (i==0) image1.source = imgSource;
else if (i==1) image2.source = imgSource;
else if (i==2) image3.source = imgSource;
etc
}
You will find that your images will automatically be downloaded when you give it a Image URI.