i'M in a small project that needs to Screenshot a game.
I made it Screenshot the game,and I need to make it Start and Stop the Screenshooter.
But I 've a problem now...
Code:
public string path = "";
public Form1()
{
InitializeComponent();
}
private static string _path = "C:\\temp\\not posted";
private static int _timespan = 3000;
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
var path =#"FPSS";
if (path != string.Empty)
_path = path;
_timespan = 3000;
DirectoryInfo dir = new DirectoryInfo(_path);
PrintScreen ps = new PrintScreen();
if (!dir.Exists) dir.Create();
var countScreens = 0;
while (true)
{
var task=StartPrinting(ps);
task.Wait();
Thread.Sleep(_timespan);
if (countScreens == 20)
{
System.GC.Collect();
countScreens = 0;
}
countScreens++;
}
}
private static async Task StartPrinting(PrintScreen ps)
{
var name = DateTime.Now.ToString("yyyyMMddhhmmss");
ps.CaptureScreenToFile($"{_path}\\{name}.png", ImageFormat.Png);
Console.WriteLine($"Printed {name}");
}
private void button2_Click(object sender, EventArgs e)
{
button1.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
But in this way (with button1 start the infinite loop) I can't turn this off because the loop is running...
Any ideas? :)
Thanks!
Related
I've written desktop application, that receives location via serial communication from NRF/GPS module, split that data in order to distinguish latitude, longitude and then i load these coordinates to map(i use GMap). But when i receive data, first 1 or 2 seconds it comes in a little confused form(like this 06840.370056;49.84006068). And i thought adding some Thread.Sleep will solve this problem, but instead application crashes after 5-10 seconds. How can i solve this problem, because i want my app run smoothly? Here is part of my code:
public partial class Form1 : Form
{
public string dataIn;
private List<PointLatLng> _points;
public Form1()
{
_points = new List<PointLatLng>();
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GMapProviders.GoogleMap.ApiKey = AppConfig.Key;
string[] ports = SerialPort.GetPortNames();
cBoxCom.Items.AddRange(ports);
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
gMap.MapProvider = GMapProviders.GoogleMap;
gMap.ShowCenter = false;
gMap.DragButton = MouseButtons.Left;
gMap.SetPositionByKeywords("Chennai, India");
}
private void btnConnect_Click(object sender, EventArgs e)
{
serialPort1.PortName = cBoxCom.Text;
serialPort1.BaudRate = Convert.ToInt32(cBoxBaudrate.Text);
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
serialPort1.Open();
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
}
}
private void btnClearDataIn_Click(object sender, EventArgs e)
{
if (richBoxReciever.Text != "")
{
richBoxReciever.Text = " ";
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
dataIn = serialPort1.ReadExisting();
this.Invoke(new EventHandler(ShowData));
}
private void ShowData(object sender, EventArgs e)
{
Thread.Sleep(3000);
richBoxReciever.Text += dataIn;
Thread.Sleep(5000);
string[] locationData = dataIn.Split(new char[] { ';' });
List<string> tokens = new List<string>();
foreach (string s in locationData)
{
if (s.Length != 0)
{
tokens.Add(s);
}
}
txtLat.Text = tokens[0];
txtLon.Text = tokens[1];
}
I am loading a local HTML page using the WebBrowser control.
namespace ConfigEditorWinForms
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class ConfigEditorForm : Form
{
String _currentConfigFilePath = null;
public ConfigEditorForm()
{
Load += new EventHandler(ConfigEditorForm_Load);
InitializeComponent();
}
private void ConfigEditorForm_Load(object sender, EventArgs e)
{
webBrowser1.AllowWebBrowserDrop = true;
webBrowser1.IsWebBrowserContextMenuEnabled = false;
webBrowser1.WebBrowserShortcutsEnabled = false;
webBrowser1.ObjectForScripting = this;
//webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(OnDocumentCompleted);
string curDir = Directory.GetCurrentDirectory();
webBrowser1.Url = new Uri(String.Format("file:///{0}/ConfigEditor/ConfigEditor.html", curDir));
}
private void OnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
MessageBox.Show("Document completed");
}
public string GetFileContents(String path)
{
return System.IO.File.ReadAllText(path);
}
public void SaveFileContents(String path, String contents)
{
System.IO.File.WriteAllText(path, contents);
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog.InitialDirectory = #"XXX";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
HtmlDocument doc = webBrowser1.Document;
HtmlElement fileToOpenInput = doc.GetElementById("fileToOpenInput");
fileToOpenInput.InvokeMember("onchange", new object[1] { openFileDialog.FileName });
_currentConfigFilePath = openFileDialog.FileName;
}
}
}
}
On my computer :
The document completed event is fired twice
Opening a file from the menu works fine too
On another computer :
The document completed event is only fired (ONCE) when the executable is run as administrator
Document.Body is null and Document.GetElementById returns null too, despite the document completed event being fired several seconds before.
What's going on please ?
Thank you. :)
I am trying to develop a WindowsForm Application which will use webcamera to detect QRCode and decode the message. For this I am using AForge.NET and ZXing.NET.
So far, I have been able to figure out how to decode the QRCode from an URI, but I want to detect the QRCode from webcamera, and decode it.
Below is the sample to my code.
public String Decode(Uri uri)
{
Bitmap image;
try
{
image = (Bitmap)Bitmap.FromFile(uri.LocalPath);
}
catch (Exception ex)
{
throw new FileNotFoundException("Resource not found: " + uri);
}
using (image)
{
String text = "";
LuminanceSource source = new BitmapLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = new MultiFormatReader().decode(bitmap);
if (result != null)
{
text = result.Text;
return text;
}
text = "Provided QR couldn't be read.";
return text;
}
}
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource;
private Bitmap capturedImage;
private String message = "";
public FormQRCodeScanner()
{
InitializeComponent();
}
private void FormQRCodeScanner_Load(object sender, EventArgs e)
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo device in videoDevices)
{
comboBoxCameraSource.Items.Add(device.Name);
}
comboBoxCameraSource.SelectedIndex = 0;
videoSource = new VideoCaptureDevice();
buttonStartStop.Text = "Start";
buttonCapture.Enabled = false;
buttonDecode.Enabled = false;
}
private void FormQRCodeScanner_FormClosing(object sender, FormClosingEventArgs e)
{
if (videoSource.IsRunning)
{
videoSource.Stop();
}
}
void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap image = (Bitmap) eventArgs.Frame.Clone();
pictureBoxSource.Image = image;
}
private void buttonStartStop_Click(object sender, EventArgs e)
{
if (videoSource.IsRunning)
{
videoSource.Stop();
pictureBoxSource.Image = null;
pictureBoxCaptured.Image = null;
pictureBoxSource.Invalidate();
pictureBoxCaptured.Invalidate();
buttonStartStop.Text = "Start";
buttonCapture.Enabled = false;
buttonDecode.Enabled = false;
}
else
{
videoSource = new VideoCaptureDevice(videoDevices[comboBoxCameraSource.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
videoSource.Start();
buttonStartStop.Text = "Stop";
buttonCapture.Enabled = true;
buttonDecode.Enabled = true;
}
}
private void buttonCapture_Click(object sender, EventArgs e)
{
if (videoSource.IsRunning)
{
pictureBoxCaptured.Image = (Bitmap)pictureBoxSource.Image.Clone();
capturedImage = (Bitmap)pictureBoxCaptured.Image;
}
}
private void buttonDecode_Click(object sender, EventArgs e)
{
if (capturedImage != null)
{
ExtractQRCodeMessageFromImage(capturedImage);
richTextBoxMessage.Text = message;
richTextBoxMessage.ReadOnly = true;
}
}
private string ExtractQRCodeMessageFromImage(Bitmap bitmap)
{
try
{
BarcodeReader reader = new BarcodeReader
(null, newbitmap => new BitmapLuminanceSource(bitmap), luminance => new GlobalHistogramBinarizer(luminance));
reader.AutoRotate = true;
reader.TryInverted = true;
reader.Options = new DecodingOptions { TryHarder = true };
var result = reader.Decode(bitmap);
if (result != null)
{
message = result.Text;
return message;
}
else
{
message = "QRCode couldn't be decoded.";
return message;
}
}
catch (Exception ex)
{
message = "QRCode couldn't be detected.";
return message;
}
}
**For this you should install these packages
Install-Package AForge
Install-Package AForge.Video
Install-Package AForge.Video.DirectShow
Install-Package ZXing.Net
you can watch this video for more help
https://www.youtube.com/watch?v=wcoy0Gwxr50**
using System.IO;
using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using ZXing;
using ZXing.Aztec;
private void Form1_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
}
private void button1_Click(object sender, EventArgs e)
{
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
}
private void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
}
private void timer1_Tick(object sender, EventArgs e)
{
BarcodeReader Reader = new BarcodeReader();
Result result = Reader.Decode((Bitmap)pictureBox1.Image);
try
{
string decoded = result.ToString().Trim();
if (decoded != "")
{
timer1.Stop();
MessageBox.Show(decoded);
Form2 form = new Form2();
form.Show();
this.Hide();
}
}
catch(Exception ex){
}
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning == true)
{
FinalFrame.Stop();
}
}
My goal is to use my webcam to capture my face and detect my mood by facial expression. The output should be probabilites like 70 % happy, 10 % sad, ...
My approach: very happy and very sad ( and other states ) faces should be saved in a HaarCascade.
My problems are twofold:
How do I create a HaarCascade to use with HaarObjectDetector for the
HaarObjectDetector object to output percentages instead of
outputting a "true" when a threshold is being surpassed?
How do I create a HaarCascade for HaarCascade? Is it easier to use String path = #"C:\Users\haarcascade-frontalface_alt2.xml"; HaarCascade cascade1 = HaarCascade.FromXml(path); with opencv-xml or generate it using HaarCascade m = new HaarCascade(20,20,HaarCascadeStages);? What would HaarCascadeStages be?
Have others already solved this issue and offer sourcecode for c#?
My current code:
public partial class Form1 : Form
{
private bool DeviceExist = false;
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource = null;
Bitmap picture;
HaarObjectDetector detector;
FaceHaarCascade cascade;
public Form1()
{
InitializeComponent();
}
// get the devices name
private void getCamList()
{
try
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
comboBox1.Items.Clear();
if (videoDevices.Count == 0)
throw new ApplicationException();
DeviceExist = true;
foreach (FilterInfo device in videoDevices)
{
comboBox1.Items.Add(device.Name);
}
comboBox1.SelectedIndex = 0; //make dafault to first cam
}
catch (ApplicationException)
{
DeviceExist = false;
comboBox1.Items.Add("No capture device on your system");
}
}
//toggle start and stop button
private void start_Click(object sender, EventArgs e)
{
}
//eventhandler if new frame is ready
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
picture = (Bitmap)eventArgs.Frame.Clone();
//Rectangle[] objects = detector.ProcessFrame(picture);
//if (objects.Length > 0)
//{
// RectanglesMarker marker = new RectanglesMarker(objects, Color.Fuchsia);
// pictureBox1.Image = marker.Apply(picture);
//}
pictureBox1.Image = picture;
}
//close the device safely
private void CloseVideoSource()
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
//get total received frame at 1 second tick
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text = "Device running... " + videoSource.FramesReceived.ToString() + " FPS";
}
//prevent sudden close while device is running
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
CloseVideoSource();
}
private void Form1_Load(object sender, EventArgs e)
{
getCamList();
cascade = new FaceHaarCascade();
detector = new HaarObjectDetector(cascade, 30);
detector.SearchMode = ObjectDetectorSearchMode.Average;
detector.ScalingFactor = 1.5f;
detector.ScalingMode = ObjectDetectorScalingMode.GreaterToSmaller;
detector.UseParallelProcessing = false;
detector.Suppression = 2;
}
private void rfsh_Click_1(object sender, EventArgs e)
{
}
private void start_Click_1(object sender, EventArgs e)
{
if (start.Text == "Start")
{
if (DeviceExist)
{
videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
CloseVideoSource();
videoSource.DesiredFrameSize = new Size(640, 480);
//videoSource.DesiredFrameRate = 10;
videoSource.Start();
label2.Text = "Device running...";
start.Text = "Stop";
timer1.Enabled = true;
}
else
{
label2.Text = "Error: No Device selected.";
}
}
else
{
if (videoSource.IsRunning)
{
timer1.Enabled = false;
CloseVideoSource();
label2.Text = "Device stopped.";
start.Text = "Start";
}
}
}
}
I have a problem with my audio application. I'm using nAudio library.
So when I play a sound without using "SamplesPerPixel" method on my waveViewer control, everything works perfectly, but when I want assign a value to this method. The Sound, when I play it starts from unexpected time and finish about 4sec. later.
Here is my code:
namespace AudioMixer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int bytesPerSample;
int samples;
int samplespixel;
private NAudio.Wave.WaveStream pcm = null;
private NAudio.Wave.BlockAlignReductionStream stream = null;
private NAudio.Wave.DirectSoundOut output = null;
private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Audio File (*.wav;*.mp3)|*.wav;*.mp3;";
if (dialog.ShowDialog() != DialogResult.OK) return;
DisposeWave();
if (dialog.FileName.EndsWith(".mp3"))
{
pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(dialog.FileName));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
else if (dialog.FileName.EndsWith(".wav"))
{
pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(dialog.FileName));
stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
}
output = new NAudio.Wave.DirectSoundOut();
output.Init(stream);
output.Stop();
waveViewer1.WaveStream = stream;
bytesPerSample = (pcm.WaveFormat.BitsPerSample / 8) * pcm.WaveFormat.Channels;
samples = (int)(pcm.Length / bytesPerSample);
samplespixel = samples / this.Width;
waveViewer1.SamplesPerPixel = samplespixel;
opened_file_name.Text = dialog.FileName;
play_button.Visible = true;
play_button.Enabled = true;
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
waveViewer1.SamplesPerPixel = samplespixel;
}
private void Form1_Load(object sender, EventArgs e)
{
opened_file_name.Text = "Audio file not opened, choose one from Your computer";
play_button.Visible = false;
}
private void play_button_Click(object sender, EventArgs e)
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Pause();
}
else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused)
{
output.Play();
}
else if (output.PlaybackState == NAudio.Wave.PlaybackState.Stopped)
{
output.Play();
}
}
}
private void DisposeWave()
{
if (output != null)
{
if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing)
{
output.Stop();
output.Dispose();
output = null;
}
}
if (stream != null)
{
stream.Dispose();
stream = null;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DisposeWave();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
i think this may help you
waveViewer1.SamplesPerPixel = 400;
waveViewer1.StartPosition = 400;