This program is used to display the data and store the data into a txt file using the input from the pic18f4550.
when the GUI received the input data is '1 ', the GUI should display the data and store the data into a txt file. data can be saved, but the data are keep repeating itself without stopping if the input is still in a state of '1 '.
how should i do, if i want to store the data just once even the input still '1'?
Here is 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 Monitoring_System
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
// Create the USB reference device object (passing VID and PID)
theUsbDemoDevice = new usbDemoDevice(0x04D8, 0x003F);
// Add a listener for usb events
theUsbDemoDevice.usbEvent += new usbDemoDevice.usbEventsHandler(usbEvent_receiver);
// Perform an initial search for the target device
theUsbDemoDevice.findTargetDevice();
}
// Create an instance of the USB reference device
private usbDemoDevice theUsbDemoDevice;
// Listener for USB events
private void usbEvent_receiver(object o, EventArgs e)
{
// Check the status of the USB device and update the form accordingly
if (theUsbDemoDevice.isDeviceAttached)
{
// Device is currently attached
// Update the status label
usb_status.Text = "Status : USB Device Connected";
}
else
{
// Device is currently unattached
// Update the status label
usb_status.Text = "Status : USB Device Unplugged";
cr1v.Visible = false;
cr1i.Visible = false;
cr2v.Visible = false;
cr2i.Visible = false;
cr3v.Visible = false;
cr3i.Visible = false;
tr1v.Visible = false;
tr1i.Visible = false;
tr2v.Visible = false;
tr2i.Visible = false;
tr3v.Visible = false;
tr3i.Visible = false;
}
}
private void button_exit_Click(object sender, EventArgs e)
{
this.Hide();
Form4 f2 = new Form4();
f2.ShowDialog();
}
private void timer1_Tick_1(object sender, EventArgs e)
{
if(theUsbDemoDevice.isDeviceAttached)
{
// Read the push button state
bool sw1 = theUsbDemoDevice.sw1();
if (sw1 == true)
{
cr1i.Visible = false;
cr1v.Visible = true;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"D:\Desktop\log data.txt", true))
{
file.WriteLine("Class Room 1 in use");
file.Close();
}
}
else if (sw1 == false)
{
cr1i.Visible = true;
cr1v.Visible = false;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"D:\Desktop\log data.txt", true))
{
file.WriteLine("Class Room 1 vacant");
file.Close();
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form5 f2 = new Form5();
f2.ShowDialog();
}
}
}
It looks like you are using a timer. Every tick your timer is writing to a file. You need to re-work your logic to either not include a timer. Or, disable it after a write, and re-enable it on another event.
Related
I am at a loss after looking at relevant posts and documentation, many others seem to have had similar problems, but none of the existing solutions results in any keypresses actually being recognized by the browser.
All my code is below, just an empty form trying to type in a username/password on a website that currently doesn't have an API but it is coming. So this is just a bandaid fix until their API is fleshed out. Mostly just need to login and send keypresses to the website, but nothing seems to be working.
I have also tried: https://ourcodeworld.com/articles/read/520/simulating-keypress-in-the-right-way-using-inputsimulator-with-csharp-in-winforms
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 CefSharp;
using CefSharp.WinForms;
namespace Hydros_tmp_api
{
public partial class Form1 : Form
{
public ChromiumWebBrowser chromeBrowser;
string CurrentAddress = "";
public void InitializeChromium()
{
CefSettings settings = new CefSettings();
// Initialize cef with the provided settings
Cef.Initialize(settings);
// Create a browser component
chromeBrowser = new ChromiumWebBrowser("https://www.coralvuehydros.com/app/#/status");
// Add it to the form and fill it to the form window.
Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill;
(chromeBrowser).LoadingStateChanged += Browser_FrameLoadEnd;
chromeBrowser.AddressChanged += Browser_AddressChanged;
}
public Form1()
{
InitializeComponent();
InitializeChromium();
}
private void Form1_Load(object sender, EventArgs e)
{
}
async void Browser_FrameLoadEnd(object sender, LoadingStateChangedEventArgs e)
{ // Jumps in here when the page is fully loaded:
if (e.IsLoading == false)
{
if (CurrentAddress.Contains("login"))
{
timer_login.Enabled = true;
}
}
}
private void Browser_AddressChanged(object sender, AddressChangedEventArgs e)
{
CurrentAddress = e.Address;
}
private void timer_login_Tick(object sender, EventArgs e)
{
timer_login.Enabled = false;
chromeBrowser.GetBrowserHost().SetFocus(true);
Random rnd = new Random();
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.Tab, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyDown
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.Tab, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyUp
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.T, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyDown
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.T, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyUp
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
}
}
}
Edit: It appears to be a specific oddity with their website that is not accepting simulated input because it works fine on other sites? So idk where to go from here.
I made a small gadget with an Arduino that sends 2 values via serial to my c# program (potentiometer value for volume and switch button to change output device). The volume part is already complete but I'm not being able to change between the two output devices (monitor audio and Headphones).
My code at the moment:
using AudioSwitcher.AudioApi.CoreAudio;
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;
namespace Volume
{
public partial class Form1 : Form
{
//msg recieved by serial
String msg;
string[] tokens;
//active device
CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice;
String PHONES = "Headphones (Razer Kraken USB)";
String COLUNA = "ASUS VP228-4 (NVIDIA High Definition Audio)";
public Form1()
{
//open port for serial msg and start timmer
InitializeComponent();
serialPort1.Open();
timer1.Enabled = true;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
//handling of the msg
msg = serialPort1.ReadLine();
tokens = msg.Split('%');
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = tokens[0];
label2.Text = tokens[1];
label6.Text = defaultPlaybackDevice.FullName;
//change volume
defaultPlaybackDevice.Volume = Int32.Parse(tokens[0]);
//change output device
if (tokens[1] == "ON")
{
if (defaultPlaybackDevice.FullName == PHONES)
{
//do nothing
}
else
{
//change to monitor output
}
}
else
{
if (defaultPlaybackDevice.FullName == COLUNA)
{
//do nothing
}
else
{
//change to headphones
}
}
}
}
}
I am using an API called AudioSwitcher.AudioApi.CoreAudio which should allow me to do what I want but I am not being able to find how.
First you need to get all the PlaybackDevices
IEnumerable<CoreAudioDevice> devices = new CoreAudioController().GetPlaybackDevices();
and then you can make a function to change your Default playbackdevice with the fullname like this
private void ChangeOutput(string op)
{
foreach (CoreAudioDevice d in devices)
{
if (d.FullName == op)
d.SetAsDefault();
}
}
I need some help with Background worker. I am trying to read data from a serial port (works fine with a button) the problem is that I need to continuously read from the serial port, until someone presses a button (Close button) on the form to stop reading. I tried doing this by adding a loop, but it just ran infinitely and froze up the form. I have the following code, whenever I press the button to read, a file is created, but when I press the close port button,it says
The I/O operation has been aborted because of either a thread exit or
an application request
Any ideas on how to fix this?
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.Ports;
using System.IO;
namespace SerialCommunication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
GetAvaliablePortNames();
}
bool indicator;
StreamWriter sw = new StreamWriter(#"C:\Users\slahiri\Desktop\Data\jumbo.txt");
void GetAvaliablePortNames()
{
string[] Ports = SerialPort.GetPortNames();
cmbPort.Items.AddRange(Ports);
}
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
if (cmbPort.Text == "" || cmbBaud.Text == "")
{
MessageBox.Show("Please select the Port and Baud Rates");
}
else
{
serialPort1.PortName = cmbPort.Text;
serialPort1.BaudRate = Convert.ToInt32(cmbBaud.Text);
serialPort1.Open();
progressBar1.Value = 100;
groupBox2.Enabled = true;
btnRead.Enabled = true;
btnOpen.Enabled = false;
btnClose.Enabled = true;
}
}
catch (UnauthorizedAccessException)
{
txtRead.Text = "Unauthorized Acess";
}
}
private void btnClose_Click(object sender, EventArgs e)
{
serialPort1.Close();
progressBar1.Value = 0;
btnClose.Enabled = false;
btnRead.Enabled = false;
btnOpen.Enabled = true;
indicator = true;
}
private void btnRead_Click(object sender, EventArgs e)
{
if (btnRead.Text == "Read")
{
btnRead.Text = "Stop and Close Port";
progressBar1.Maximum = 1000;
progressBar1.Value = 0;
backgroundWorker1.RunWorkerAsync(progressBar1.Maximum);
indicator = false;
}
else
{
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.CancelAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
int max = (int)e.Argument;
int n = 0;
indicator = false;
do
{
//write to serial writer
sw.WriteLine(serialPort1.ReadLine());
if (backgroundWorker1.CancellationPending)
{
sw.Flush();
sw.Close();
e.Cancel = true;
break;
}
// backgroundWorker1.ReportProgress(n++);
}
while (indicator ==false);
}
catch (TimeoutException)
{
//Close Serial Writer & Messagebox
//txtRead.Text = "Time Out!";
MessageBox.Show("TimeOut Exception");
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnRead.Text = "Read";
//close serial writer
}
}
}
Since you have a do-while construct you evaluate the condition at the END!
So when you hit the Close button and close the SerialPort the backgroundworker is still active and running in the background trying to read from the SerialPort. It enters the do compartment and tries to read from a closed port, which is like running agains a closed door :) this leads to the exception.
You could solve it by
1) putting the while-evaluation on top and get rid of the do statement (making it a simple while-loop). This way the serialPort.ReadLine will not be executed anymore, because you set indicator = true; when hitting the close button.
May be in this case you should put the setting of indicator as the first line before closing the port:
private void btnClose_Click(object sender, EventArgs e)
{
try
{
indicator = true;
serialPort1.Close();
Or
2) put an extra if clause that makes sure to read only if the port is open!
if (serialPort1.IsOpen)
{
sw.WriteLine(serialPort1.ReadLine());
}
I write code to create and connect to VPN using Dotras in C#. It works very good, but when I write code to get connection status, It doesn't work.
I read Dotras document, and write code like example, but It still doesn't work.
It doesn't show status in multiple line textbox. :(
Please show me, what I wrong. Thank you.
Here is 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.Threading.Tasks;
using System.Windows.Forms;
using DotRas;
using System.Net;
namespace VPN1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_create_vpn_Click(object sender, EventArgs e)
{
try
{
string vpnuser = txt_vpn_user.Text;
string ip_address = txt_IP.Text;
this.rasPhoneBook1.Open();
RasEntry entry = RasEntry.CreateVpnEntry(vpnuser, ip_address, RasVpnStrategy.Default, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn, false));
this.rasPhoneBook1.Entries.Add(entry);
MessageBox.Show("Success");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private RasHandle handle = null;
private void btn_dial_Click(object sender, EventArgs e)
{
this.rasDialer1.EntryName = txt_vpn_user.Text;
string username = txt_user.Text;
string password = txt_pass.Text;
this.rasDialer1.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
try
{
this.rasDialer1.Credentials = new NetworkCredential(username, password);
this.handle = this.rasDialer1.DialAsync();
this.btn_disconnect.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void rasDialer1_StateChanged(object sender, StateChangedEventArgs e)
{
this.txt_status.AppendText(e.State.ToString() + "\r\n");
}
private void rasDialer1_DialCompleted(object sender, DialCompletedEventArgs e)
{
if(e.Cancelled)
{
this.txt_status.AppendText("Cancelled");
}
else if(e.TimedOut)
{
this.txt_status.AppendText("Timeout");
}
else if(e.Connected)
{
this.txt_status.AppendText("Connection successful");
}
else if (e.Error != null)
{
this.txt_status.AppendText(e.Error.ToString());
}
if(!e.Connected)
{
this.btn_disconnect.Enabled = false;
}
}
private void btn_disconnect_Click(object sender, EventArgs e)
{
if(this.rasDialer1.IsBusy)
{
this.rasDialer1.DialAsyncCancel();
}
else
{
RasConnection connection = RasConnection.GetActiveConnectionByHandle(this.handle);
if(connection!=null)
{
connection.HangUp();
}
}
}
}
}
If the events are not firing, the issue might be that the Events are not set in the events section in the properties window of the rasDialer1 control you added to the form (Form1). Using Visual Studio, Enter the design view, click on the rasDialer1 control which reveals the properties of the RasDialer you added, then navigate to events section (marked with a lightening icon) and then set the StateChanged and DialCompleted events.
OR
You can do all this from code simply by
rasDialer.StateChanged += rasDialer1_StateChanged;
rasDialer.DialCompleted += rasDialer1_DialCompleted;
somewhere in the Form1() constructor, where rasDialer1_StateChanged and rasDialer1_DialCompleted are the event handlers in your code.
I'm also anticipating a potential error within your code where accessing UI controls in those event handlers will get you a Cross-thread operation not valid error since they are called from an async operation this.rasDialer1.DialAsync();
The right way of accessing controls from methods called from another thread is below ...
textbox1.Invoke(new Action(() => textbox1.text = "my string"));
Try using dial instead of dialAsync
try:
{
File.WriteAllText("your rasphone.pbk path","")//Add
string vpnuser = txt_vpn_user.Text;
string ip_address = txt_IP.Text;
this.rasPhoneBook1.Open();
RasEntry entry = RasEntry.CreateVpnEntry(vpnuser, ip_address, RasVpnStrategy.Default, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn, false));
this.rasPhoneBook1.Entries.Add(entry);
MessageBox.Show("Success");
}
i am working to make a c# program that can start streaming webcam, close and capture the still image when closing.
the programs work as excepted on my development machine but when i open it on other it dosent work and gives me unhandled exception: Afroge.Video.DirectShow error.
I have added references AFroge.Video.dll and AFroge.Video.DirectShow.dll
here is the exe file and code of my project.
sendspace .com/file/4okqsi
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;
//Create using directives for easier access of AForge library's methods
using AForge.Video;
using AForge.Video.DirectShow;
namespace aforgeWebcamTutorial
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Create webcam object
VideoCaptureDevice videoSource;
private void Form1_Load(object sender, EventArgs e)
{
}
void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
//Cast the frame as Bitmap object and don't forget to use ".Clone()" otherwise
//you'll probably get access violation exceptions
pictureBoxVideo.BackgroundImage = (Bitmap)eventArgs.Frame.Clone();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
//Stop and free the webcam object if application is closing
if (videoSource != null && videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
private void button1_Click(object sender, EventArgs e)
{
try {
if (videoSource.IsRunning)
{
videoSource.Stop();
pictureBoxVideo.BackgroundImage.Save("abc.png");
pictureBoxVideo.BackgroundImage = null;
}
}
catch (Exception er) { }
}
private void button2_Click(object sender, EventArgs e)
{
try {
//List all available video sources. (That can be webcams as well as tv cards, etc)
FilterInfoCollection videosources = new FilterInfoCollection(FilterCategory.VideoInputDevice);
//Check if atleast one video source is available
if (videosources != null)
{
//For example use first video device. You may check if this is your webcam.
videoSource = new VideoCaptureDevice(videosources[0].MonikerString);
try
{
//Check if the video device provides a list of supported resolutions
if (videoSource.VideoCapabilities.Length > 0)
{
string highestSolution = "0;0";
//Search for the highest resolution
for (int i = 0; i < videoSource.VideoCapabilities.Length; i++)
{
if (videoSource.VideoCapabilities[i].FrameSize.Width > Convert.ToInt32(highestSolution.Split(';')[0]))
highestSolution = videoSource.VideoCapabilities[i].FrameSize.Width.ToString() + ";" + i.ToString();
}
//Set the highest resolution as active
videoSource.VideoResolution = videoSource.VideoCapabilities[Convert.ToInt32(highestSolution.Split(';')[1])];
}
}
catch { }
//Create NewFrame event handler
//(This one triggers every time a new frame/image is captured
videoSource.NewFrame += new AForge.Video.NewFrameEventHandler(videoSource_NewFrame);
//Start recording
videoSource.Start();
}
}
catch (Exception er) { }
}
}
}
Try this link!
It worked for me!
If some parts cannot be installed. Delete all of the assemblies of AForge.Net and follow following tutorial.
https://premsivakumar.wordpress.com/2010/06/28/aforge-net-visual-studio-2010-setup-tutorial/