I'm trying to build a program that would take a picture of a user 3 times and save those pictures in the desktop my problem is it only saves the picture instead of taking the picture 3 times.
private void Form1_Load(object sender, EventArgs e)
{
bool useCam = true;
if (!useCam)
measureImage(null);
else
{
try
{
camera = new Capture();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
Application.Idle += viewImage;
captureProcess = true;
}
}
here is the capturing code...
private void btnCapture_Click(object sender, EventArgs e)
{
for (int ctr = 0; ctr < 3; ctr++)
{
if (captureProcess == true)
{
string data="";
Application.Idle -= viewImage;
SaveFileDialog dlg = new SaveFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
img.ToBitmap().Save(#"C:\\Users\\Julie\\Desktop\\" + ctr + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
data = dlg.FileName + ".bmp";
MessageBox.Show(data);
measureImage(data);
Form1_Load(sender, e);
}
else
{
Application.Exit();
}
}
}
captureProcess = false;
}
Presuming captureProcess is a variable at the window scope, you're setting it to false within the first for loop, so the 2nd and 3rd never execute due to the if(captureProcess == true) check.
Related
We need to show a Modal or a Toast notification on an ASP.net page whenever there is a new text file or there is some change in an existing text file. Here is what we've come up with:
private string htmsDir = "C:\\HTMS";
private string htmsDirPath = string.Empty;
FileSystemWatcher watcher;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
watcher = new FileSystemWatcher(htmsDir);
watcher.Filter = "*.txt";
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.EnableRaisingEvents = true;
}
}
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
try
{
String[] lines = System.IO.File.ReadAllLines(e.FullPath);
if (lines.Length < 1)
return;
String line = lines[lines.Length - 1];
int counter = 1;
while (line == null || line.Length < 1)
{
counter++;
if (counter > lines.Length)
break;
line = lines[lines.Length - counter];
}
if (line == null || line.Length < 1)
return;
if (ParseHTMSData(line))
{
UpdateForm();
}
}
catch (Exception) { }
}
private bool ParseHTMSData(string line) {
return true;
}
private void UpdateForm()
{
try
{
Response.Write("this");
}
catch (Exception ex)
{
Common.logger.CreateDBLog(ex.ToString());
}
}
But the problem is functions like Response.Write(); are not working at all! And there is no proper Exception available to start with.
What are we doing wrong? is there any simpler way?
I am having a problem . I want to use if statement to check if a button is clicked. For Example:
public void button1_Click(object sender, EventArgs e)
{
while (1)
{
...
...
...
if (Button2 == clicked)
{
break;
}
}
}
But it's not working like this, because the ".click" can only be on the left side of "+=" or "-=". Any idea how i can check if Button2 is clicked?
the code is loking like this: and i want to check button2 to stop the "programm".
the check for the Button2 is nearly at the end of the code ;)
public void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int EmFilterPos;
int ExFilterPos;
string String1;
int[] EmLB = new int[126];
int[] ExLB = new int[126];
int LBEmAnzahl = 0;
int LBEmTot = 0;
int LBExAnzahl = 0;
int LBExTot = 0;
UInt32 C_Zyklen;
UInt32 Zyklen;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_On = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOn;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_Off = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOff;
Roche.DetectionControl2.Device_Filterwheels.fiweGetLBResponse LightBarrier;
string Text = String.Format("Filterrad-Dauertest\r\nGestart am {0:d} um {0:t}\r\n\r\n", DateTime.Now);
System.IO.File.WriteAllText(#"TestLogFile\Filterrad_Dauertest1.txt", Text);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
while (Zyklen <= 20)
{
for (int q=1;q<8;q++)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(q,q);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
for (int w=0;w<7;w++)
{
ExFilterPos = rnd.Next(1,8);
EmFilterPos = rnd.Next(1,8);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
C_Zyklen = Zyklen;
if ((C_Zyklen % 2) < 14)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Init bei: ");
String1 = String.Format("{0,7}",Zyklen);
file.Write(String1);
file.Write(file.NewLine);
}
ExFilterPos = 60;
EmFilterPos = 60;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_On);
while (EmFilterPos != -60)
{
LightBarrier = Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweGetLB();
if (LightBarrier.LBEm == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBEmAnzahl++;
LBEmTot += EmFilterPos;
}
if (LightBarrier.LBEx == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBExAnzahl++;
LBExTot += ExFilterPos;
}
ExFilterPos--;
EmFilterPos--;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
}
EmFilterPos = LBEmTot / LBEmAnzahl;
ExFilterPos = LBExTot / LBExAnzahl;
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Nullstelle Mittelposition Em-Filter: ");
file.Write(EmFilterPos);
file.Write(file.NewLine);
file.Write("Nullstelle Mittelposition Ex-Filter: ");
file.Write(ExFilterPos);
file.Write(file.NewLine);
file.Write(file.NewLine);
}
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_Off);
}
if (Button2 == clicked) // or something like this
break;
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Beendet am {0:d} um {0:t}\r\n", DateTime.Now);
}*/
}
Hm...
bool b1clicked = false, b2clicked = false;
public void button2_Click(object sender, EventArgs e)
{
b2clicked = true;
}
public void button1_Click(object sender, EventArgs e)
{
b1clicked = true;
if (b1clicked && b2clicked)
{
//...
}
}
Beside the weird behavior you want..and since you are not using Threads, you have the following options:
Local functions (.Net > 4.7)
private void B_Click(object sender, EventArgs e)
{
bool clickFlag = false;
void Click(object sender2, EventArgs e2)
{
clickFlag = true;
}
b2.Click += Click;
while (!clickFlag)
{
Thread.Sleep(1);
}
b2.Click -= Click;
//Continue with your stuff
}
Threads
Thread newThread;
private void Button1_Click()
{
newThread = new Thread(YourBreakableProcess);
newThread.Start();
}
private void Button2_Click()
{
newThread.Join();
}
private void YourBreakableProcess()
{
//Your breakable process
}
Async methods.
I hope you find a solution. Cheers.
Edit:
Since what you want is to interrupt the process of whatever you are doing, the only option you have is Local fuctions as shown above, if you are not tied to a specific framework version.
BackgroundWorker and check in every step if the button 2 was pressed with the flag thing mentioned in other answer.
Threads, and make a thread.Join when the button 2 is pressed.
Edit 2:
Updated answer with Threads, I will recommend that if you go with this option it is much better to use a BackgroundWorker instead as you will have the whole control of the process breaking it only in the place where it would be fine to break it.
You can achieve this using a flag variable. Declare and initialize flag value to false.On button2 click change flag value to true as follows,
private bool flag= false;
private void button2_Click(object sender, EventArgs e)
{
flag= true;
}
public void button1_Click(object sender, EventArgs e)
{
//Use flag to check whether button 2 has clicked or not
if (flag)
{
}
else
{
}
}
How could I show a progress bar when moving a file?
Currently I've got this:
private void btnMoveFile_Click(object sender, EventArgs e)
{
try
{
if (pathFrom != null && pathTo != null)
{
if (txtRename.Text != null)
{
pathTo = pathTo + "\\" + txtRename.Text;
}
else
{
pathTo = pathTo + "\\" + Path.GetFileName(pathFrom);
}
File.Move(pathFrom, pathTo);
}
else
{
MessageBox.Show("Kies eerst een bestand.");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
// Wait 100 milliseconds.
Thread.Sleep(100);
// Report progress.
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
But because File.Move(pathFrom, pathTo); is not a loupe I've got no Idea how to do this.
Consider using the SHFileOperation API from shell32.
A working solution is described in this answer: How to bring up the built-in File Copy dialog?
It works for copy as well as for move and delete.
I'm making a media player where I add media files to a list-box. What I would like to do is to make the media-element automatically start playing the next song/video in the list-box after the current one has ended. Also I would like to make a doubleclickevent where if listitem clicked the song/video should play. This is what I currently have:
Xaml:
<MediaElement Name="objMediaPlayer" LoadedBehavior="Manual" UnloadedBehavior="Stop" MediaOpened="objMediaPlayer_MediaOpened" MediaEnded="objMediaPlayer_MediaEnded" Margin="20,19,20,40" ButtonBase.Click="mediaItemList_MouseDoubleClick" />
<ListBox Canvas.Left="882" Canvas.Top="12" Height="467" Name="mediaItemList" Width="260" Background="Gray" MouseDoubleClick="mediaItemList_MouseDoubleClick" />
cs-sheet:
private void BrowseButtonClick(object sender, RoutedEventArgs e)
{
System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
dlg.Multiselect = true;
dlg.InitialDirectory = "c:\\";
dlg.Filter = "All Files (*.*)|*.*";
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
foreach (string file in dlg.FileNames)
{
FileInfo fileName = new FileInfo(file);
mediaItemList.Items.Add(fileName);
}
string selectedFileName = dlg.FileName;
fileNameLabel.Content = selectedFileName;
objMediaPlayer.Source = new Uri(selectedFileName);
objMediaPlayer.Play();
lblCoverUp.Visibility = Visibility.Hidden;
}
}
private int currentSongIndex = -1;
private void objMediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
{
if (currentSongIndex == -1)
{
currentSongIndex = mediaItemList.SelectedIndex;
}
currentSongIndex++;
if (currentSongIndex < mediaItemList.Items.Count)
{
objMediaPlayer.Play();
}
else
{
// last song in listbox has been played
}
}
private void mediaItemList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
For the Doubleclick function
private void mediaItemList_MouseDoubleClick(object sender, RoutedEventArgs e)
{
System.Windows.Controls.Button prevButton = objMediaPlayer.Tag as System.Windows.Controls.Button;
System.Windows.Controls.Button button = (sender as System.Windows.Controls.Button);
FileInfo fileInfo = button.DataContext as FileInfo;
// If a file is playing, stop it
if (prevButton != null)
{
objMediaPlayer.Tag = null;
objMediaPlayer.Stop();
prevButton.Background = Brushes.LightYellow;
// if the one thats playing is the one that was clicked -> don't play it
if (prevButton == button)
return;
}
// Play the one that was clicked
objMediaPlayer.Tag = button;
objMediaPlayer.Source = new Uri(fileInfo.FullName);
objMediaPlayer.Play();
}
For Media_ended I have already tried: objMediaPlayer.Play(mediaItemList.Items[currentSongIndex]);
When activating the Doubleclick event I get the following error:Object reference not set to an instance of an object. (FileInfo fileInfo = button.DataContext as FileInfo).
I hope someone can help me. If you need more information, just ask
EDIT:
I have fixed mostly of the media ended problem by using the following code:
private void objMediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
{
objMediaPlayer.Stop();
if (mediaItemList.SelectedIndex <= mediaItemList.Items.Count)
{
mediaItemList.SelectedIndex = mediaItemList.SelectedIndex += 1;
fileNameLabel.Content = mediaItemList.SelectedItem;
objMediaPlayer.Play();
}
else
{
objMediaPlayer.Stop();
fileNameLabel.Content = " ";
}
}
The only problem now is that the player doesn't stop after finishing the last song(listitem). How do you fix this.
Surely you need to open each file before you play them?:
private void objMediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
{
if (currentSongIndex == -1)
{
currentSongIndex = mediaItemList.SelectedIndex;
}
currentSongIndex++;
if (currentSongIndex < mediaItemList.Items.Count)
{
objMediaPlayer.Open(new Uri(mediaItemList.ElementAt(currentSongIndex),
UriKind.Absolute));
}
else
{
// last song in listbox has been played
}
}
private void MediaPlayer_MediaOpened(object sender, EventArgs e)
{
objMediaPlayer.Play();
}
I am having two functions - one is runs some commands on my serial port within a loop, the other one is an event handler that should stop the execution of the loop in the first method. Here is some sample code.
public void btm_Processing_Click(object sender, EventArgs e)
{
for (int i = 1; i <= x ; i++)
{
// My processing commands are here .
}
}
And here is my stop button event handler.
private void btm_Stop_Click(object sender, EventArgs e)
{
var dialogResult = MessageBox.Show("Do you want to stop processing?",
"Error",
MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
// Here is where I want to break that loop.
}
else
{
// Do other things.
}
}
I am not sure how I can do this.
The best way to do this would be to use a BackgroundWorker thread to execute your loop, then you can cancel it later from the main thread later.
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
The easier way would be the make a global variable that you set
private volatile bool isWorking = false;
public void btm_Processing_Click(object sender, EventArgs e)
{
isWorking = true;
for (int i = 1; i <= x ; i++)
{
//My Processing Commands are Here
if(!isWorking)
break;
}
}
private void btm_Stop_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do You Want To Stop Processing ? ", "Error", MessageBoxButtons.YesNo);
isWorking = dialogResult != DialogResult.Yes;
}
Set a break variable;
private volatile bool shouldStop = false;
private void btm_Processing_Click(object sender, EventArgs e)
{
for (int i = 1; i <= x ; i++)
{
//My Processing Commands are Here
if (shouldStop)
{
shouldStop=false;
break;
}
}
}
private void btm_Stop_Click(object sender, EventArgs e)
{
var dialogResult = MessageBox.Show("Do you want to stop processing?",
"Error",
MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
shouldStop = true;
}
else
{
// Do other things.
}
}