Writing and closing Notepad++ using speech recognition libraries - c#

I'm trying to write code that will open Notepad++, write to a file, and close it afterward. My code is included below. I'm totally new to C#. Is there any library or way to do this?
// Button Reference
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text.Equals("Enable Voice Control"))
{
button1.Text = "Stop Voice Control";
recEngine.RecognizeAsync(RecognizeMode.Multiple);
}
else
{
button1.Text = "Enable Voice Control";
recEngine.RecognizeAsyncStop();
}
}
public void Form1_Load(object sender, EventArgs e)
{
Choices commands = new Choices();
commands.Add(myCommands);
GrammarBuilder gBuilder = new GrammarBuilder();
gBuilder.Append(commands);
Grammar grammar = new Grammar(gBuilder);
recEngine.LoadGrammarAsync(grammar);
recEngine.SetInputToDefaultAudioDevice();
recEngine.SpeechRecognized += recEngine_SpeechRecognized;
}
void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
Process cmd = new Process();
cmd.StartInfo.FileName = #"notepad++.exe" ;
//cmd.StartInfo.Arguments =#"\Write.txt";
cmd.Start();
cmd.CloseMainWindow();
cmd.WaitForExit();
cmd.Refresh();
//if (cmd.StandardError != null)
//Console.WriteLine(cmd.StandardError.ReadToEnd());
var result = e.Result;
var i = 0;
foreach (var command in myCommands)
{
if (command.StartsWith("close"))
{
this.Close();
//cmd.StartInfo.FileName = #"notepad++";
cmd.Kill();
}
if (command.StartsWith("--") || command == string.Empty) continue; // Skip commentBlocks and skipEmptylines
var parts = command.Split(new char[] { '|' }); // Split the lines
i++;
if (command.Equals(result.Text))
{
Console.WriteLine("Command is {0}: {1}", i, command);
break;
}
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}

You need not open notepad and write to file. You can do it programmarically.
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
// Open the file to read from.
string readText = File.ReadAllText(path);

You can use the below code to close the notepad:
Process[] processes = Process.GetProcessesByName("notepad");
foreach (var process in processes)
{
process.Kill();
}
It will close all instances of notepad. So better be sure the notepads are only that of yours (opened by your speech recognition program)
If you actually do not want to open notepad and your requirement is just to capture text and write to file programatically, then use the below code:
// Create a file to write to.
string createText = "Hello World"; // Replace with voice captured text
File.WriteAllText(path, createText);
// Open the file to read from.
string readText = File.ReadAllText(path);

Related

in c# Read full txt file

I tried to do a form application and I have a problem about use StreamReader feature. in StreamWriter feature, I did it but StreamReader just read the last line and The txt file contains, in many rows for example: names and phone numbers but like I said the code read last line
private void button2_Click(object sender, EventArgs e)
{
//1
StreamWriter sw;
sw = File.AppendText("metinbelgesi.txt");
sw.Write(textBox1.Text + " ");
sw.Write(textBox2.Text + " ");
sw.WriteLine(textBox3.Text+"." );
sw.Flush();
sw.Close();
}
private void button3_Click(object sender, EventArgs e)
{
if (File.Exists("metinbelgesi.txt"))
{
FileStream fs = new FileStream("metinbelgesi.txt", FileMode.Open, FileAccess.Read);
StreamReader sw = new StreamReader(fs);
//sw = File.AppendText("metinbelgesi.txt");
string yazi = sw.ReadLine();
while (yazi != null)
{
richTextBox1.Text = yazi;
}
sw.Close();
fs.Close();
}
else
{
MessageBox.Show("First, You Join.");
}
}
What do I do?
You are reading it line by line and keep overwriting richTextBox1 with the next line... try:
richTextBox1.Text = "";
while (yazi != null)
{
richTextBox1.Text += yazi;
yazi = sw.ReadLine();
}
Or, if you don't need to parse each line, you can read it all in one go:
if (File.Exists("metinbelgesi.txt"))
{
richTextBox1.Text = File.ReadAllText("metinbelgesi.txt");
}
According to your code, you're only reading the first line. There should be a ReadLine() statement inside your loop as well.
Pay attention that you will always overwrite the contents of the textbox with the line of text you've just read.
So, when you've finished your loop, only the last line that you've read will occur in the textbox.
For simplicity, you can also have a look at the File class and more specifically the ReadAllLines() method.
You should probaby try to make your life easier by using some of the simpler File operations.
Try this instead:
private void button2_Click(object sender, EventArgs e)
{
File.AppendAllText("metinbelgesi.txt", $"{textBox1.Text} {textBox2.Text} {textBox3.Text}.");
}
private void button3_Click(object sender, EventArgs e)
{
if (File.Exists("metinbelgesi.txt"))
{
richTextBox1.Text = File.ReadAllText("metinbelgesi.txt");
}
else
{
MessageBox.Show("First, You Join.");
}
}

How to save the data in the text file in column format alone?

I've a gui and I get temperature data from a Uc. I can see the data in the rich text box and save to a text file. But I cannot understand how to sort the saved data in the column format. Right now it is a long row of data. Please advice.
Would it be advisable to replace the rich text box to a normal text box?
I've a button to save data to the text file (button3_Click);
using System;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
namespace Serial_receive
{
public partial class Form1 : Form
{
// All members variables should be placed here
// make it more readable, hopefully!
string t;
SerialPort sp;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
// User can already search for ports when the constructor of the FORM1 is calling
// And let the user search ports again with a click
// Searching for ports function
SearchPorts();
}
//search button
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
SearchPorts();
}
void SearchPorts()
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
}
private void button2_Click(object sender, EventArgs e)
{
// Catch exception if it will be thrown so the user will see it in a message box
OpenCloseSerial();
}
void OpenCloseSerial()
{
try
{
if (sp == null || sp.IsOpen == false)
{
t = comboBox1.Text.ToString();
sErial(t);
button2.Text = "Close Serial port"; // button text
}
else
{
sp.Close();
button2.Text = "Connect and wait for inputs"; // button text
}
}
catch (Exception err) // catching error message
{
MessageBox.Show(err.Message); // displaying error message
}
}
void sErial(string Port_name)
{
try
{
sp = new SerialPort(Port_name, 115200, Parity.None, 8, StopBits.One); // serial port parameters
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
sp.Open();
}
catch (Exception err)
{
throw (new SystemException(err.Message));
}
}
//
private void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{
// This below line is not need , sp is global (belongs to the class!!)
//SerialPort sp = (SerialPort)sender;
if (e.EventType == SerialData.Chars)
{
if (sp.IsOpen)
{
string w = sp.ReadExisting();
if (w != String.Empty)
{
Invoke(new Action(() => richTextBox1.AppendText(w)));
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (sp == null || sp.IsOpen == false)
{
OpenCloseSerial();
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "Serial Channel to FRDM-KW40Z";
}
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\Users\varman\Documents\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string temperature = "Temperature";
string sorted = richTextBox1.Text.Replace(temperature, Environment.NewLine + temperature);
sorted = sorted.Substring(sorted.IndexOf(temperature));
File.WriteAllText(saveFileDialog1.FileName, sorted);
Text += "\r\n";
richTextBox1.Text = saveFileDialog1.FileName;
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
richTextBox1.ScrollBars = ScrollBars.Both;
}
}
}
I assume you want to sort it only in the output file because you didn't share the code that change richTextBox1.Text.
So you can add a new line for each temperature before writing to the file:
private void button3_Click(object sender, EventArgs e)
{
...
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string temperature = "Temperature";
string sorted = richTextBox1.Text.Replace(temperature, Environment.NewLine + temperature);
File.WriteAllText(saveFileDialog1.FileName, sorted);
Text += "\r\n";
richTextBox1.Text = saveFileDialog1.FileName;
}
}
Add this line of code before File.WriteAllText if you want to write the text that starts with "Temperature" (this way you remove the "?????" at the beginning):
sorted = sorted.Substring(sorted.IndexOf(temperature));
EDIT:
Following your last edit - you added the code that updates the RichTextBox. So you can do the sorting by column only in DataReceivedHandler. See below:
private void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{
if (e.EventType != SerialData.Chars || !sp.IsOpen)
{
return;
}
string w = sp.ReadExisting();
if (w != String.Empty)
{
string temperature = "Temperature";
string sorted = w.Replace(temperature, Environment.NewLine + temperature);
Invoke(new Action(() => richTextBox1.AppendText(sorted)));
}
}
Basically what you need to understand is that File.WriteAllText(fileName, input) is where you write input into the file, so you can manipulate input as you wish before that line. If you wish to alter the text before it's dispalyed in the RichTextBox then you need to see where you execute something like richTextBox1.AppendText(input) or richTextBox1.Text = input and do all the changes you want on input before that line.

Folder Browser Dialog with Environment

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.

.Reading and writing to a file from the same textbox

I have a windows form that reads strings from a file and shows them all in a textbox when I press a button.
private void buttonTxt_Click(object sender, EventArgs e)
{
string[] Test = File.ReadAllLines("C:\\testfile.txt");
for (int i = 0; i < testfile.Length; i++)
{
TextBox.Text += testfile[i];
}
}
I'd like to make two radio buttons. So that first button lets my program work the way I described (by default) AND second radio button makes it work vice versa -- so that I could write in a textbox myself and when I press a button it writes a new line to the same file. Is there a way to do it?
Simply add an if statement in this event handler and implement both sending and receiving the data. Done. Sample in principle:
private const string FilePath = #"C:\testfile.txt";
private void buttonTxt_Click(object sender, EventArgs e)
{
if (radioReadMode.Checked) // check which radio button is selected
{ // read mode
string[] Test = File.ReadAllLines(FilePath);
for (int i = 0; i < testfile.Length; i++)
TextBox.Text += testfile[i];
}
else
{ // write mode
File.WriteAllText(FilePath, TextBox.Text);
}
}
I believe this is what you might be looking for. If radio button 1 is checked then if the file exists it will read that file and put it into a textbox in the form. If you switch to radio button 2. You can type in the text box and then when you press the button it will append it to the file.
public partial class Form1 : Form
{
System.IO.StreamReader sr;
System.IO.StreamWriter sw;
public Form1()
{
InitializeComponent();
radioButton1.Checked = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sr = new System.IO.StreamReader("C:\\testfile.txt");
while (!sr.EndOfStream)
{
textBox1.Text += sr.ReadLine() + "\r\n";
}
}
finally
{
sr.Close();
sr.Dispose();
}
}
}
if (radioButton2.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sw = new System.IO.StreamWriter("C:\\testfile.txt", true);
string result = textBox1.Text;
string[] lststr = result.Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in lststr)
{
sw.WriteLine(s);
}
}
finally
{
sw.Flush();
sw.Close();
sw.Dispose();
}
}
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = true;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = false;
}
}
Yes, there's a way. Just add another button to your form and inside read the text from the text box this way:
var textBoxContent = TextBox.Text;
and save it to your file this way
File.WriteAllText("C:\\testfile.txt", textBoxContent);
Note: I recommend getting the path to your file into a variable

Parse first word of the command in recognized speech

I am trying to take speech input and convert them to string and show it on the richtext box control. I have read about speech synthesis and voice recognition in several articles where I learned to get commands via speech however I want to write on richtext box control after my command Write is recognized. Is it possible?
Here is the code if it helps understand what I am trying to achieve and what I have done so far
object declarations
PromptBuilder pb = new PromptBuilder();
SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
Choices clist = new Choices();
The code for Enabling Voice Input
private void btnEnableVoice_Click(object sender, EventArgs e)
{
btnEnableVoice.Enabled = false;
btnDisableVoice.Enabled = true;
/////////////Adding commands in a list of type Choices///////////////////////
clist.Add(new string[] { "Is it working", "Write" });
Grammar gr = new Grammar(new GrammarBuilder(clist));
try
{
recognizer.RequestRecognizerUpdate(); ///////starting engine
recognizer.LoadGrammar(gr);
recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
recognizer.SetInputToDefaultAudioDevice();
recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
switch (e.Result.Text.ToString())
{
case "Is it working":
ss.SpeakAsync("Yes its working");
break;
case "Write":
richTextBox1.Text += ""; //Speech to text input here
break;
}
}
First you need to construct a grammar in a proper way to allow dictation, see for the reference http://msdn.microsoft.com/en-us/library/ms576565(v=vs.110).aspx:
Choices clist = new Choices();
clist.Add(new string[] { "Is it working", "Write" });
GrammarBuilder bl = new GrammarBuilder(clist);
bl.appendDictation();
Grammar gr = new Grammar(bl);
To parse you need something like
void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
string result = e.Result.Text.ToString();
if (result.startsWith("Write")) {
richTextBox1.Text += result.substring(7); // Skip first 6 chars
} else if (result.startsWith("Is it working")) {
ss.SpeakAsync("Yes its working");
}
}

Categories