My code simply reads the file, splits it into words and whows each word in the textbox with 0.1 seconds frequency.
I click to "button1" to get the file and split.
After I click Start_Button the program gets stuck. I can't see any problem in the code. Can anyone see it please?
My code is here;
public partial class Form1 : Form
{
string text1, WordToShow;
string[] WordsOfFile;
bool LoopCheck;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog BrowseFile1 = new OpenFileDialog();
BrowseFile1.Title = "Select a text file";
BrowseFile1.Filter = "Text File |*.txt";
BrowseFile1.FilterIndex = 1;
string ContainingFolder = AppDomain.CurrentDomain.BaseDirectory;
BrowseFile1.InitialDirectory = #ContainingFolder;
//BrowseFile1.InitialDirectory = #"C:\";
BrowseFile1.RestoreDirectory = true;
if (BrowseFile1.ShowDialog() == DialogResult.OK)
{
text1 = System.IO.File.ReadAllText(BrowseFile1.FileName);
WordsOfFile = text1.Split(' ');
textBox1.Text = text1;
}
}
private void Start_Button_Click(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Enabled = true;
timer1.Start();
LoopCheck = true;
try
{
while (LoopCheck)
{
foreach (string word in WordsOfFile)
{
WordToShow = word;
Thread.Sleep(1000);
}
}
}
catch
{
Form2 ErrorPopup = new Form2();
if (ErrorPopup.ShowDialog() == DialogResult.OK)
{
ErrorPopup.Dispose();
}
}
}
private void Stop_Button_Click(object sender, EventArgs e)
{
LoopCheck = false;
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.Text = WordToShow;
}
}
}
Instead of Thread.Sleep(1000); use async/await feature with Task.Delay in order to keep your UI responsible:
private async void Start_Button_Click(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Enabled = true;
timer1.Start();
LoopCheck = true;
try
{
while (LoopCheck)
{
foreach (string word in WordsOfFile)
{
WordToShow = word;
await Task.Delay(1000);
}
}
}
catch
{
Form2 ErrorPopup = new Form2();
if (ErrorPopup.ShowDialog() == DialogResult.OK)
{
ErrorPopup.Dispose();
}
}
}
Related
I have a code that read in a richtextbox the last row from a txt file.
What I want to introduce now is a refresh button with something like a text box.
I want to put it so user can put the number on the form that means minutes for the code and then user press the button refresh and the program will refresh every ... minutes. The program just call last file opened with open file dialog, refresh it on richtextbox every ... minutes.
Here is what I did to refresh just when you press the button refresh (maybe for implement it as I want I should put on the form another button and a text box?):
private string thePath;
public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
{
using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
thePath = ofd.FileName;
Refresh();
}
}
}
private void Refresh()
{
using (StreamReader rd = new StreamReader(thePath))
{
string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ReaderRichTxtBox.Text = lines[lines.Length - 1];
}
}
private void RefreshBtn_Click(object sender, EventArgs e)
{
Refresh();
}
How should the code be?
Thank you for help.
You should use some kind of Timer.
For example, you can declare a private System.Windows.Forms.Timer refreshtimer and instatiate it at the button click.
Assuming the textbox name is TextBox1, the code should look like this:
private System.Windows.Forms.Timer refreshtimer;
private string thePath;
public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
{
using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
thePath = ofd.FileName;
Refresh();
}
}
}
private void Refresh()
{
using (StreamReader rd = new StreamReader(thePath))
{
string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ReaderRichTxtBox.Text = lines[lines.Length - 1];
}
}
private void RefreshBtn_Click(object sender, EventArgs e)
{
refreshtimer = new System.Windows.Forms.Timer();
refreshtimer.Tick += new EventHandler(timer_Tick);
refreshtimer.Interval = Convert.ToInt32(TextBox1.Text) * 60000; //60000 is one minute
refreshtimer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
Refresh();
}
At the refresh button click I set the interval to the value of the TextBox (the interval is set in miliseconds, that is why I have multiplied by 60000).
I suggest you put the intialization of the timer in the constructor of the class.
Ask me more if you have any question and I will edit my answer.
public partial class TextReaderForm : Form
{
public TextReaderForm()
{
InitializeComponent();
}
private System.Windows.Forms.Timer refreshtimer;
private string thePath;
public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
{
using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
//using (StreamReader rd = new StreamReader(ofd.FileName))
{
//ReaderRichTxtBox.Text = await rd.ReadToEndAsync();
//string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
//ReaderRichTxtBox.Text = lines[lines.Length - 1];
thePath = ofd.FileName;
Refresh();
}
}
}
}
private void Refresh()
{
using (StreamReader rd = new StreamReader(thePath))
{
string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ReaderRichTxtBox.Text = lines[lines.Length - 1];
}
}
private void RefreshBtn_Click(object sender, EventArgs e)
{
Refresh();
}
private void RefreshTimerBtn_Click(object sender, EventArgs e)
{
refreshtimer = new System.Windows.Forms.Timer();
refreshtimer.Tick += new EventHandler(timer_Tick);
refreshtimer.Interval = Convert.ToInt32(RefreshTimerTxtBox.Text) * 60000; //60000 is one minute
timer1.Start();
}
void timer_Tick(object sender, EventArgs e)
{
Refresh();
}
}
I have a project that is not running anymore. I keep getting an error dialog that says "This application cannot be started. Do you want to view more information about this issue?". Also in the console, it says "The program '[10068] BinaryConverter.exe' has exited with code 0 (0x0)." Someone told me to uncheck the "Prefer 32-bit" option. When I do that, although the error dialog box is gone, the console still displays The program '[10068] BinaryConverter.exe' has exited with code 0 (0x0)." I cannot open the wpf app.
EDIT: By the way, the release folder is empty. When the app was working, my release folder had some things in it.
public MainWindow()
{
InitializeComponent();
}
public void readstuff (){
}
public static string getBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "";
}
}
private void BrowseButton2(object sender, RoutedEventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.InitialDirectory = "\\\\folder1\\savelocation";
fd.Filter = "Binary Files | *.bin";
fd.ShowDialog();
filePath2.Text = fd.FileName;
}
private void SavingPathButton2(object sender, RoutedEventArgs e)
{
FolderSelectDialog fs = new FolderSelectDialog();
fs.InitialDirectory = "\\\\Nx3200\\supplier\\FONEX\\LambdaGain";
fs.ShowDialog();
savingPath2.Text = fs.FileName;
}
private void StartConversion2(object sender, RoutedEventArgs e)
{
try
{
Byte [] a1 = File.ReadAllBytes(filePath2.Text);
Byte[] a2 = new Byte[2 * (a1.Length)];
int i = 0;
while(i < a1.Length) {
a2[2*i] = a1[i];
a2[(2 * i) + 1] = 0;
i++;
}
try
{
string fullPath = Path.Combine(savingPath2.Text, "new");
File.WriteAllBytes(savingPath2.Text, a2);
MessageBox.Show("Conversion Complete");
} catch (UnauthorizedAccessException ex)
{
Form3 frm3 = new Form3();
frm3.Text = "X-Formatter";
frm3.ShowDialog();
}
}
catch (FileNotFoundException ex)
{
string stackTrace = ex.ToString();
Form1 frm1 = new Form1(stackTrace);
frm1.Text = "X-Formatter";
frm1.ShowDialog();
}
}
private void BrowseButton1(object sender, RoutedEventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.InitialDirectory = "\\\\folder1\\savelocation";
fd.Filter = "Binary Files | *.bin";
fd.ShowDialog();
filePath1.Text = fd.FileName;
}
private void SavingPathButton1(object sender, RoutedEventArgs e)
{
FolderSelectDialog fs = new FolderSelectDialog();
fs.InitialDirectory = "\\\\folder1\\savelocation";
fs.ShowDialog();
savingPath1.Text = fs.FileName;
}
private void StartConversion1(object sender, RoutedEventArgs e)
{
try
{
Byte[] a1 = File.ReadAllBytes(filePath1.Text);
Byte[] a2 = new Byte[(a1.Length) / 2];
a2[0] = a1[0];
int i = 2;
int j = 1;
while (i < a1.Length)
{
a2[j] = a1[i];
i = i + 2;
j += 1;
}
try
{
File.WriteAllBytes(savingPath1.Text, a2);
MessageBox.Show("Conversion Complete");
}
catch (UnauthorizedAccessException ex)
{
Form3 frm3 = new Form3();
frm3.Text = "XGIGA formatter";
frm3.ShowDialog();
}
} catch(FileNotFoundException ex)
{
string stackTrace = ex.ToString();
Form1 frm1 = new Form1(stackTrace);
frm1.Text = "XGIGA Formatter";
frm1.ShowDialog();
}
}
private void FilePath1_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
AboutBox1 ab = new AboutBox1();
ab.Text = "XGIGA Formatter";
ab.ShowDialog();
}
}
I am currently working on a file copying facility that allows me to select a source and a destination for the folders to be copied from and to. A progress bar is displayed after the user clicks on Copy.
The only issue is that All of my functions reside in one file which is form1.cs (as follows)
namespace CopyFacility
{
public partial class Form1 : Form
{
BackgroundWorker background = new BackgroundWorker();
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
OpenFileDialog openFile = new OpenFileDialog();
public Form1()
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
string inputFile = null;
string outputFile = null;
private void CopyFile(string source, string destination, DoWorkEventArgs e)
{
FileStream fsOut = new FileStream(destination, FileMode.Create);
FileStream fsIn = new FileStream(source, FileMode.Open);
byte[] buffer = new byte[1048756];
int readBytes;
while((readBytes = fsIn.Read(buffer,0,buffer.Length)) > 0)
{
if(background.CancellationPending)
{
e.Cancel = true;
background.ReportProgress(0);
fsIn.Close();
fsOut.Close();
return;
}
else
{
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int) (fsIn.Position * 100 / fsIn.Length));
}
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int)(fsIn.Position * 100 / fsIn.Length));
}
fsIn.Close();
fsOut.Close();
}
private void Background_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
fileProgressBar.Value = e.ProgressPercentage;
}
private void Background_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled)
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been cancelled";
}
else
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been completed";
}
}
private void Background_DoWork(object sender, DoWorkEventArgs e)
{
CopyFile(inputFile, outputFile + #"\" + Path.GetFileName(inputFile),e);
}
private void btnCancel_Click(object sender, EventArgs e)
{
background.CancelAsync();
}
private void btnCopy_Click(object sender, EventArgs e)
{
if(background.IsBusy)
{
lblProgress.Visible = true;
}
else
{
fileProgressBar.Visible = true;
background.RunWorkerAsync();
}
}
private void btnSource_Click(object sender, EventArgs e)
{
if(openFile.ShowDialog() == DialogResult.OK )
{
inputFile = openFile.FileName;
btnSource.Text = inputFile;
}
}
private void btnDestination_Click(object sender, EventArgs e)
{
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
outputFile = folderBrowser.SelectedPath;
btnDestination.Text = outputFile + #"\" + Path.GetFileName(inputFile);
}
}
}
}
I was wondering how I could go about putting the function "CopyFile" into it's own class that can be called whenever the button is clicked?
When I try creating a new class method and inserting the functions related to the copying function into a new class "CopyFunction.cs" , I get a following error from the code "InitializingComponent();" as follows
public CopyPresenter(BackgroundWorker background, FolderBrowserDialog folderBrwoser, OpenFileDialog openFile)
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
The error says that the "InitializeComponent" doesn't exist in the current context.
I apologize for the use of language translation
I want to run the timer once. Next blogger.I'm saving it to the database.
Ongoing notification..One in 4 seconds
timer1 :Enabled ,Interval :4000
MyCode:
public bool InternetKontrol()
{
try
{
System.Net.Sockets.TcpClient kontrol_client = new System.Net.Sockets.TcpClient("www.google.com.tr", 80);
return true;
}
catch (Exception)
{
label1.Text = "";
return false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (InternetKontrol()==false)
{
NetGelenGiden ngg = new NetGelenGiden();
ngg.GidenZaman = "Net Gitti " + DateTime.Now.ToLongTimeString().ToString();
ngg.GelenZaman = "";
dat.NetGelenGidens.Add(ngg);
dat.SaveChanges();
notifyIcon1.Icon = SystemIcons.Information;
notifyIcon1.ShowBalloonTip(3000, "Net Durum", "Net Gitti " + DateTime.Now.ToLongTimeString().ToString(),ToolTipIcon.Info);
notifyIcon1.Visible = true;
label2.Text ="Net Gitti "+ DateTime.Now.ToLongTimeString().ToString();
}
I think you are defining Timer control in a Windows Forms (that's because you don't put the timer1 declaration).
At the beginning of your event timer1_Tick, disable or stop the timer:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Start();
}
private bool InternetKontrol() { /* your code */ }
public bool flagInternetService = true;
private void timer1_Tick(object sender, EventArgs e)
{
var newResult = InternetKontrol();
var warn = false;
if (flagInternetService != newResult){
if (newResult == false) warn = true;
flagInternetService = newResult;
}
if (warn)
{
/* your code warning */
label2.Text = DateTime.Now.ToLongTimeString();
}
}
}
I created an app for my dad. It's just a simple dictation program. The thing is when he installed it on his computer it stalled and said the general access denied error.
The first time it gave the error I used SaveFileDialog sfd = new SaveFileDialog() then added the usually 'if statement" to make sure the dialog was ok. However the app had an access file denied.
I did the same thing with Environment.GetFolder and it installed on his computer to the location and ran fine. However, when I use the saveFileDialog1 and openFileDialog1 out of the tool box it does not save or open a txt document.
It works on my laptop and not his. Could this be due to an error in the code vs his computer. Also what is the correct way to use the Environement.GetFolder with the SaveFileDialog.
I can also post the full code to the program if needed.
private void lblOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Title = "Open File";
open.Filter = "Text Files (*txt) | *.txt";
if (open.ShowDialog() == DialogResult.OK)
{
StreamReader read = new StreamReader(File.OpenRead(open.FileName));
txtTextBox.Text = read.ReadToEnd();
read.Dispose();
}
}
private void lblSaveFile_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter write = new StreamWriter(File.Create(save.FileName));
write.Write(txtTextBox.Text);
write.Dispose();
}
}
This is the Enviroment i used on my screen recorder. i when i click save it brings up a dialog box i put in the file name press save and it does nothing. It saves the file but not as i specified. So i am trying to merge the above and below codes. The above code does not grant access however the below does
string OutputPath;
OutputPath = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + #"\\IvanSoft Desktop Recorder" + saveFileDialog1;
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string fileName = saveFileDialog1.FileName;
fileName = "Tutorial";
}
the whole code to the program
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Threading;
namespace AGM_Speech
{
public partial class Form1 : Form
{
public SpeechRecognitionEngine recognizer;
public Grammar grammar;
public Thread RecThread;
public Boolean RecognizerState = true;
public Form1()
{
InitializeComponent();
}
private void lblAbout_Click(object sender, EventArgs e)
{
this.Hide();
About about = new About();
about.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
GrammarBuilder builder = new GrammarBuilder();
builder.AppendDictation();
grammar = new Grammar(builder);
recognizer = new SpeechRecognitionEngine();
recognizer.LoadGrammarAsync(grammar);
recognizer.SetInputToDefaultAudioDevice();
recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
RecognizerState = true;
RecThread = new Thread(new ThreadStart(RecThreadFunction));
RecThread.Start();
}
private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (!RecognizerState)
return;
this.Invoke((MethodInvoker)delegate
{
txtTextBox.Text += (e.Result.Text.ToLower() + " ");
txtTextBox.SelectionStart = txtTextBox.Text.Length - 0;
txtTextBox.SelectionLength = 0;
});
}
public void RecThreadFunction()
{
while (true)
{
try
{
recognizer.RecognizeAsync();
}
catch
{
}
}
}
private void lblStartSpeech_Click(object sender, EventArgs e)
{
RecognizerState = true;
}
private void lblStopSpeech_Click(object sender, EventArgs e)
{
RecognizerState = false;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
RecThread.Abort();
RecThread = null;
grammar = null;
recognizer.UnloadAllGrammars();
recognizer.Dispose();
}
private void lblOpenFile_Click(object sender, EventArgs e)
{
string open = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StreamReader reader = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
}
private void lblSaveFile_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter write = new StreamWriter(File.Create(save.FileName));
write.Write(txtTextBox.Text);
write.Dispose();
}
}
private void txtSearch_Click(object sender, EventArgs e)
{
txtSearch.Clear();
lblGo_Click(null, null);
}
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)ConsoleKey.Enter)
{
lblGo_Click(null, null);
}
}
private void lblGo_Click(object sender, EventArgs e)
{
int index = 0;
String temp = txtTextBox.Text;
txtTextBox.Text = "";
txtTextBox.Text = temp;
while (index <= txtTextBox.Text.LastIndexOf(txtSearch.Text))
{
txtTextBox.Find(txtSearch.Text, index, txtTextBox.TextLength, RichTextBoxFinds.None);
txtTextBox.SelectionColor = Color.YellowGreen;
index = txtTextBox.Text.IndexOf(txtSearch.Text, index) + 1;
}
}
}
}
It's hard to say where you're failing, because there isn't much in the way of try/catch or logging.
Can you use this instead, and paste the stack trace that shows in the Message Box?
private string fileOutputLocation { get; set; }
private void lblSaveFile_Click(object sender, EventArgs e)
{
bool fileSelected = false;
Try(() =>
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
save.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos), "IvanSoft Desktop Recorder");
if (save.ShowDialog() == DialogResult.OK)
{
fileOutputLocation = save.FileName;
fileSelected = true;
}
});
if (fileSelected)
{
bool fileSaved = SaveFile();
MessageBox.Show("File saved successfully: " + fileSaved.ToString());
}
}
private bool SaveFile()
{
TryDeleteFile();
bool fileSaved = false;
Try(()=>
{
File.WriteAllText(fileOutputLocation, txtTextBox.Text);
fileSaved = true;
});
return fileSaved;
}
private void TryDeleteFile()
{
Try(()=>
{
if (File.Exists(fileOutputLocation))
{
File.Delete(fileOutputLocation);
}
});
}
private void Try(Action action)
{
try
{
action();
}
catch (Exception e)
{
MessageBox.Show(string.Format("The following exception was thrown:\r\n{0}\r\n\r\nFile path: {1}", e.ToString(), fileOutputLocation));
}
}
With this, plus the events logged to the Windows Event Viewer (Start>Run>Eventvwr>Security), we should be able to tell you what the problem is.
Lastly, if you're just providing an executable to run, you should check the properties of the file to ensure it's not blocked in Windows.