Webcam motion Detection using AForge C# - webcam

I am using code for motion detection webcam using Aforge. When running the program, it can run perfectly, but when edit libel1 "motion Detection" and libel2 "no motion Detection" it cannot running. Why?
The code I'm using for motion detection:
public Form1()
{
InitializeComponent();
}
FilterInfoCollection fic;
VideoCaptureDevice Device;
MotionDetector motionDetector;
float f;
private void Form1_Load(object sender, EventArgs e)
{
motionDetector = new MotionDetector(new TwoFramesDifferenceDetector(), new MotionAreaHighlighting());
fic = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo item in fic)
{
comboBoxDevice.Items.Add(item.Name);
}
comboBoxDevice.SelectedIndex = 0;
}
private void BtnStart_Click(object sender, EventArgs e)
{
Device = new VideoCaptureDevice(fic[comboBoxDevice.SelectedIndex].MonikerString);
videoSourcePlayer1.VideoSource = Device;
videoSourcePlayer1.Start();
}
private void BtnStop_Click(object sender, EventArgs e)
{
videoSourcePlayer1.Stop();
}
private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
{
if (motionDetector == null) return;
f = motionDetector.ProcessFrame(image);
if (f >0)
{
label1.ForeColor = Color.Red;
label1.Text = "Motion Detected";
}
else
{
label1.ForeColor = Color.Green;
label1.Text = "No Motion Detected";
}
}
private void timer_Tick(object sender, EventArgs e)
{
label3.Text = "Value: " + f.ToString();
}
}
}

I think you want to change a label in your UI when you detect a motion. If you want to change a label in UI, you can't run the change function in the same thread. So, you can change it by defining another thread. Just make sure you prevent race conditions.
// Changing UI Labels (Make thread)
Label1.Invoke((MethodInvoker)delegate {
// What do you want to change?
Label1.Text = "Detecting Motions";
});

Related

GTK# Nodeview Nodestore always gets null reference

I've created a GTK# Nodeview + NodeStore following the code in the GTK# Mono tutorial page! My changes were adding a button to Add new entries to the NodeView and trying to make it interactable. My problem is the NodeView
Selection Changed event is crashing the application.
using System;
using Gtk;
public partial class MainWindow : Window
{
Button button;
NodeView nodeview;
NodeStore nodestore;
[TreeNode(ListOnly = true)]
public class MyTreeNode : TreeNode
{
public MyTreeNode(string artist)
{
Artist = artist;
}
[TreeNodeValue(Column = 0)]
public string Artist;
}
public MainWindow() : base(WindowType.Toplevel)
{
Build();
var vbox = new VBox();
nodeview = new NodeView();
// Create a column with title Artist and bind its renderer to model column 0
nodeview.AppendColumn("Artist", new CellRendererText(), "text", 0);
nodestore = new NodeStore(typeof(MyTreeNode));
nodestore.AddNode(new MyTreeNode("temp"));
nodeview.NodeStore = nodestore;
nodeview.Selection.Changed += Selection_Changed;
button = new Button("Add New!!");
button.Clicked += Button_Clicked;
vbox.PackStart(nodeview, true, true, 0);
vbox.PackStart(button, false, true, 0);
Add(vbox);
ShowAll();
}
void Button_Clicked(object sender, EventArgs e)
{
nodestore.AddNode(new MyTreeNode("temp"));
}
void Selection_Changed(object sender, EventArgs e)
{
NodeSelection selection = (NodeSelection)sender;
if (selection != null)
{
MyTreeNode node = (MyTreeNode)selection.SelectedNode;
var a = node.Artist;
}
}
protected void OnDeleteEvent(object sender, DeleteEventArgs a)
{
Application.Quit();
a.RetVal = true;
}
}
When I select a node in the NodeView the application crashs without any notice. Then with some debugging I realized that when entering NodeSelection_Changed the NodeStore variable in the Nodeview is always null. Even though it is adding nodes to it.. (they are being rendered to the nodeview).
This seems to be a bug in GTK# which has been fixed but not in the version that ships with Mono 5.8 and older.
A workaround is to set the 'store' field in the NodeView class using reflection.
typeof (NodeView).GetField ("store", BindingFlags.Instance | BindingFlags.NonPublic).SetValue (nodeview, nodestore);
If you add the line above just after the line that sets the nodestore on the NodeView then this fixes the NodeView.NodeStore being null.
nodeview.NodeStore = nodestore;
typeof (NodeView).GetField ("store", BindingFlags.Instance | BindingFlags.NonPublic).SetValue (nodeview, nodestore);
Also note that the code you have in the Selection_Changed event is failing because the sender is a Gtk.TreeSelection not a Gtk.NodeSelection. I changed the Selection_Changed method to be the following which works:
void Selection_Changed(object sender, EventArgs e)
{
NodeSelection selection = nodeview.NodeSelection;
if (selection != null)
{
MyTreeNode node = (MyTreeNode)selection.SelectedNode;
var a = node.Artist;
}
}

Duplicated output from process.OutputDataReceived

I'm having an issue with duplicated content from redirected output.
In my forms I have two buttons: Run and Clear.
public partial class BatchRun : Form
{
Process process = new Process();
public BatchRun()
{
InitializeComponent();
}
private void RunBTN_Click(object sender, EventArgs e)
{
//initiate the process
this.process.StartInfo.FileName = sMasterBATname;
this.process.StartInfo.UseShellExecute = false;
this.process.StartInfo.CreateNoWindow = true;
this.process.StartInfo.RedirectStandardOutput = true;
this.process.OutputDataReceived += new DataReceivedEventHandler(StandardOutputHandler);
this.process.StartInfo.RedirectStandardInput = true;
this.process.Start();
this.process.BeginOutputReadLine();
}
public void StandardOutputHandler(object sender, DataReceivedEventArgs outLine)
{
BeginInvoke(new MethodInvoker(() =>
{
Label TestLBL = new Label();
TestLBL.Text = text.TrimStart();
TestLBL.AutoSize = true;
TestLBL.Location = new Point(10, CMDpanel.AutoScrollPosition.Y + CMDpanel.Controls.Count * 20);
CMDpanel.Controls.Add(TestLBL);
CMDpanel.AutoScrollPosition = new Point(10, CMDpanel.Controls.Count * 20);
}));
}
private void ClearBTN_Click(object sender, EventArgs e)
{
CMDpanel.Controls.Clear();
this.process.CancelOutputRead();
this.process.Close();
this.process.Refresh();
}
}
This works great if I want to run process only once i.e. close the forms once process has completed.
However, I need to allow user to rerun the same process or run a new one hence I have added a clear button the clear various controls etc.
The problem I'm having is that after clicking clear button, I want to click run button again without closing which should then run the sMAsterBAT file(CMD).
StandardOutputHandler seems to be including content of the previous run as well as the new one resulting in duplicated labels in my CMDpanel.
Is this stored in some kind of buffer? If so, How do i clear it to allow me a rerun?
Could someone explain why this is happening and how to resolve it please.
Spoke to someone at work who fixed it for me. So easy lol
private void ClearBTN_Click(object sender, EventArgs e)
{
CMDpanel.Controls.Clear();
this.process.CancelOutputRead();
this.process.Close();
this.process.Refresh();
this.process = new Process(); // this line resolved my issue!!
}
}

background worker dont work

I want to read a text file from the Internet and I want while reading the file a picturebox, that is a gif animation, show and after the reading is finished picturebox hide.
I use background worker. I have a lable that shows the state, but when I click BtnCheck Button bg doesn't work and the lable doesn't change.
My code:
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
private void BtnCheck_Click(object sender, EventArgs e)
{
PbLoading.Visible = true;
if (backgroundWorker1.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
LbleState.Text = "Reading txt File...";
webClient1 = new WebClient();
if (CheckForInternetConnection())
{
try
{
Stream stream = webClient1.OpenRead(TxtWebAdrss);
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
reader.Close();
LbleState.Text = "Reading Finished .";
}
catch
{
LbleState.Text = "Error reading";
}
}
else LbleState.Text = "Internet not connected!";
}
You may just need to do a bit more research into this class. You should perform UI changes on the UI thread.
There are three event handlers that you can use and these are,
backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
The following link should help,
http://msdn.microsoft.com/en-us/library/System.ComponentModel.BackgroundWorker(v=vs.110).aspx

Improve software responsiveness when slider is manipulated in windows phone

I have a slider in my windows phone 7.1 project. When manipulated, this slider fires an event which starts a background worker to performs several trigonometric operations.
If I move the cursor on the slider, I have a certain delay in the response although I have implement background worker cancelAsync method in manipulationstarted event, I would like more responsiveness, how can I achieve this?
Code:
private void sliderCosinus_ManipulationStarted(object sender,ManipulationStartedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync(); // Cancel the asynchronous operation.
}
}
private void sldCosinus_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
try
{
Value = Convert.ToInt32(sldCosinus.Value) * 10;
}
catch
{
// errore message here
}
finally
{
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
else
{
Dispatcher.BeginInvoke(() => app.IsEffectApplied=TrigonometricTrans()
// TrigonomtriecTrans calculate sin and cosinus for every pixel in image
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// progress bar here
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
//this.tbProgress.Text = "Canceled!";
}
else if (!(e.Error == null))
{
//this.tbProgress.Text = ("Error: " + e.Error.Message);
}
else
{
DoubleBufferToScreen();
}
}

DOTMsn is not firing the SingedIn event

I have just started building a app using “XihSolutions.DotMSN.dll” version: 2.0.0.40909,
My problem is that it is not firing the “Nameserver_SignedIn” event. Not sure if I am doing something wrong.
your help will be really helpful.
void Nameserver_SignedIn(object sender, EventArgs e)
{
throw new Exception("User Signed In");
}
private string message = string.Empty;
void NameserverProcessor_ConnectionEstablished(object sender, EventArgs e)
{
message = "Connected";
SetMessage();
}
void SetMessage()
{
if (tbMessage.InvokeRequired)
tbMessage. Invoke(new ThreadStart(SetMessage));
else
tbMessage.Text += Environment.NewLine+ message;
}
private void btnSingIn_Click(object sender, EventArgs e)
{
if (messenger.Connected)
{
// SetStatus("Disconnecting from server");
messenger.Disconnect();
}
// set the credentials, this is ofcourse something every DotMSN program will need to
// implement.
messenger.Credentials.Account = tbUserName.Text;
messenger.Credentials.Password = tbPwd.Text;
// inform the user what is happening and try to connecto to the messenger network.
//SetStatus("Connecting to server");
messenger.Connect();
}
You might use MSNPSharp instead - DotMSN is old and may not support the current MSN protocol. There link is here:
http://code.google.com/p/msnp-sharp/