how to remove spacing in the richtextbox? - c#

question
relevant to this question, I want to remove the spacing in my richtextbox since the display will always include a spacing like:
Hello
Hello
Hello
I want to modify the code that will display this texts as:
Hello
Hello
Hello
How would I do that? Anyone knows? Thanks
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Threading;
using System.Windows.Threading;
using System.Data.SQLite;
using System.Text.RegularExpressions;
namespace SerialTrial
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public class ThreadExample
{
FlowDocument mcFlowDoc = new FlowDocument();
Paragraph para = new Paragraph();
public static void ThreadJob(MainWindow mainWindow)
{
string dBConnectionString = #"Data Source = C:\Users\Documents\Visual Studio 2012\Projects\SerialTrial\SerialTrial\bin\Debug\employee.sqlite;";
SQLiteConnection sqliteCon = new SQLiteConnection(dBConnectionString);
//open connection to database
try
{
sqliteCon.Open();
SQLiteCommand createCommand = new SQLiteCommand("Select empID from EmployeeList", sqliteCon);
SQLiteDataReader reader;
reader = createCommand.ExecuteReader();
//richtextbox2.Document.Blocks.Clear();
while (reader.Read())
{
string Text = (String.Format("{0}", Object.Equals(Variables.buffering, reader.GetValue(0))));
if (Convert.ToBoolean(Text))
{
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run("Hello")))));
string text = "s";
mainWindow.WriteSerial(text);
Console.WriteLine(Text);
//richtextbox2.Document.Blocks.Add(new Paragraph(new Run(Text)));
}
}
sqliteCon.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public partial class MainWindow : Window
{
SerialPort serial = new SerialPort();
//string received_data;
//Thread readThread = new Thread(Read);
FlowDocument mcFlowDoc = new FlowDocument();
Paragraph para = new Paragraph();
public MainWindow()
{
InitializeComponent();
combobox1.Items.Insert(0, "Select Port");
combobox1.SelectedIndex = 0;
string[] ports = null;
ports = SerialPort.GetPortNames();
// Display each port name to the console.
int c = ports.Count();
for (int i = 1; i <= c; i++)
{
if (!combobox1.Items.Contains(ports[i - 1]))
{
combobox1.Items.Add(ports[i - 1]);
}
}
}
string dBConnectionString = #"Data Source = C:\Users\Documents\Visual Studio 2012\Projects\SerialTrial\SerialTrial\bin\Debug\employee.sqlite;";
static int count = 0;
private void Button_Click(object sender, RoutedEventArgs e)
{
count++;
string[] ports = null;
ports = SerialPort.GetPortNames();
// Display each port name to the console.
int c = ports.Count();
for (int i = 1; i <= c; i++)
{
if (!combobox1.Items.Contains(ports[i - 1]))
{
combobox1.Items.Add(ports[i - 1]);
}
}
}
private void combobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string myItem = combobox1.SelectedItem.ToString();
textbox1.Text = myItem;
}
private void button2_Click(object sender, RoutedEventArgs e)
{
try
{
if ((string)button2.Content == "Connect")
{
string myItem = combobox1.SelectedItem.ToString();
if (myItem == "Select Port")
{
MessageBox.Show("Select Port");
}
else
{
serial.PortName = myItem;
serial.Open();
textbox2.Text = "Serial Port Opened";
button2.Content = "Disconnect";
serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
}
}
else
{
serial.Close();
button2.Content = "Connect";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#region Receiving
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int bytes = serial.BytesToRead;
byte[] buffer = new byte[bytes];
serial.Read(buffer, 0, bytes);
foreach (var item in buffer)
{
Console.Write(item.ToString());
}
Variables.buffering = BitConverter.ToInt64(buffer, 0);
Console.WriteLine();
Console.WriteLine(Variables.buffering);
Thread thread = new Thread(new ThreadStart(() => ThreadExample.ThreadJob(this)));
thread.Start();
thread.Join();
}
/*
private delegate void UpdateUiTextDelegate(string text);
private void Receive(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// Collecting the characters received to our 'buffer' (string).
received_data = serial.ReadExisting();
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), received_data);
}
private void WriteData(string text)
{
// Assign the value of the recieved_data to the RichTextBox.
para.Inlines.Add(text);
mcFlowDoc.Blocks.Add(para);
richtextbox2.Document = mcFlowDoc;
richtextbox2.ScrollToEnd();
}
*/
#endregion
private void button3_Click(object sender, RoutedEventArgs e)
{
if (serial.IsOpen)
{
TextRange allTextRange = new TextRange(richtextbox1.Document.ContentStart, richtextbox1.Document.ContentEnd);
string allText = allTextRange.Text;
serial.WriteLine(allText);
}
}
public void WriteSerial(string text)
{
serial.Write(text);
}
}
}
I want to put it somewhere inside this if function:
if (Convert.ToBoolean(Text))
{
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run("Hello")))));
string text = "s";
mainWindow.WriteSerial(text);
Console.WriteLine(Text);
//richtextbox2.Document.Blocks.Add(new Paragraph(new Run(Text)));
}

Try the following Regex
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text, #"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);

string myText = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text;
var resultString = Regex.Replace(myText, #"( |\r?\n)\1+", "$1");

Related

Why when using filcesystemwatcher and dictionary with fileinfo it's throwing exceptions on wrong key and file not found?

Link for the repository on github :
https://github.com/chocolade1972/FileSystemWatcher
At the top i init with new instance both filelist and dic variables.
Then when starting watching i get all the files . and add them to the filelist and to the dic.
If for example the path is C:\ then filelist will contain 6 items :
filelist = Directory.GetFiles(textBox_path.Text, "*.*").ToList();
foreach (var item in filelist)
{
FileInfo info = new FileInfo(item);
dic.Add(item, info.Length);
}
Then in the event Watcher_Changes at this line :
var info = new FileInfo(e.FullPath);
There is exception the file not found and i see when using a breakpoint a long file temp type with tmp extension.
Then on other files it's throwing exceptions key was not present and then if i will start watching over again it will throw exceptions that the key is the same and already exist.
Other problem is now the button Button_doit in the event Button_doit_Click is not changing to stop and stay on start all the time.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
namespace Watcher_WPF
{
/// <summary>
/// MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Watcher watcher;
private List<string> filelist = new List<string>();
private Dictionary<string, long> dic = new Dictionary<string, long>();
public MainWindow()
{
InitializeComponent();
CenterWindowOnScreen();
var nf = new NFilters()
{
Size = true,
FileName = true,
DirectoryName = true,
};
watcher = new Watcher(nf);
watcher.Created += Watcher_Changes;
watcher.Changed += Watcher_Changes;
watcher.Deleted += Watcher_Changes;
watcher.Renamed += Watcher_Renamed;
PrintMsg(Application.ResourceAssembly.ToString());
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (watcher.IsStarted)
{
e.Cancel = MessageBox.Show("Watcher is working, are you sure to close?", "Oh!",
MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No;
}
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
//Ctrl
if (e.KeyboardDevice.IsKeyDown(Key.LeftCtrl) || e.KeyboardDevice.IsKeyDown(Key.RightCtrl))
{
if (e.KeyboardDevice.IsKeyDown(Key.S))
{
//Ctrl+S
SaveLogs(null, null);
}
else if (e.KeyboardDevice.IsKeyDown(Key.D))
{
//Ctrl+D
ClearLogs(null, null);
}
}
}
private void Button_doit_Click(object sender, RoutedEventArgs e)
{
try
{
if (!watcher.IsStarted)
{
SetPath(textBox_path.Text.Trim());
}
watcher.IsStarted = !watcher.IsStarted;
if(button_doit.Content.ToString() == "Stop")
{
add_path.IsEnabled = true;
}
else
{
add_path.IsEnabled = false;
RandomFiles.GenerateFiles();
filelist = Directory.GetFiles(textBox_path.Text, "*.*").ToList();
foreach (var item in filelist)
{
FileInfo info = new FileInfo(item);
dic.Add(item, info.Length);
}
}
button_doit.Content = watcher.IsStarted ? "Stop" : "Start";
button_doit.Foreground = watcher.IsStarted ? Brushes.Red : Brushes.Black;
textBox_path.IsEnabled = !watcher.IsStarted;
PrintMsg(watcher.IsStarted ? "watcher started...At " + DateTime.Now.ToString() : "watcher stopped...At " + DateTime.Now.ToString());
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Button_options_Click(object sender, RoutedEventArgs e)
{
options.IsOpen = true;
}
private void OptionsMenu_Opened(object sender, RoutedEventArgs e)
{
allow_edit.IsChecked = !richTextBox_main.IsReadOnly;
topmost_switcher.IsChecked = Topmost;
filter_setter.IsEnabled = !watcher.IsStarted;
include_subdir.IsEnabled = !watcher.IsStarted;
include_subdir.IsChecked = watcher.IncludeSubdirectories;
}
private void AddPath(object sender, RoutedEventArgs e)
{
// Configure open file dialog box
var dialog = new Microsoft.Win32.OpenFileDialog();
dialog.FileName = "Document"; // Default file name
dialog.DefaultExt = ".*"; // Default file extension
dialog.Filter = "All files|*.*"; // Filter files by extension
// Show open file dialog box
bool? result = dialog.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
textBox_path.Text = dialog.FileName;
}
}
private void SaveLogs(object sender, RoutedEventArgs e)
{
try
{
SaveFileDialog sfd = new SaveFileDialog()
{
Filter = "TXT|*.txt",
FileName = $"watcher_{DateTime.Now:yyyyMMddHHmmss}"
};
if (sfd.ShowDialog() == true)
{
string path = sfd.FileName;
string content = new TextRange(
richTextBox_main.Document.ContentStart,
richTextBox_main.Document.ContentEnd).Text;
File.WriteAllText(path, content);
PrintMsg($"saved log to \"{path}\"");
}
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void ClearLogs(object sender, RoutedEventArgs e)
{
richTextBox_main.Document.Blocks.Clear();
}
private void Switch_Window_Topmost(object sender, RoutedEventArgs e)
{
Topmost = !Topmost;
}
private void Allow_edit_Click(object sender, RoutedEventArgs e)
{
richTextBox_main.IsReadOnly = !richTextBox_main.IsReadOnly;
}
private void Filter_setter_Click(object sender, RoutedEventArgs e)
{
var tmp = new FilterWindow(watcher.NFilters, watcher.Filter) { Owner = this }.ShowDialog();
if (tmp is Fdr fdr)
{
watcher.Filter = fdr.Filter;
watcher.NFilters = fdr.Nfilters;
PrintMsg($"set Filter: Size={watcher.NFilters.Size}, FileName={watcher.NFilters.FileName}, " +
$"DirectoryName={watcher.NFilters.DirectoryName}, Filter=\"{watcher.Filter}\"");
}
}
private void Include_subdir_Click(object sender, RoutedEventArgs e)
{
watcher.IncludeSubdirectories = !watcher.IncludeSubdirectories;
PrintMsg($"IncludeSubdirectories={watcher.IncludeSubdirectories}");
}
private void View_source_code_Click(object sender, RoutedEventArgs e)
{
Process.Start("https://github.com/Mzying2001/Watcher_WPF");
}
private void TextBox_path_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
Button_doit_Click(null, null);
}
private void RichTextBox_main_TextChanged(object sender, TextChangedEventArgs e)
{
if (richTextBox_main.IsReadOnly)
richTextBox_main.ScrollToEnd();
}
private void SetPath(string path)
{
watcher.Path = path;
PrintMsg($"set path: \"{watcher.Path}\"");
}
private void Watcher_Changes(object sender, FileSystemEventArgs e)
{
try
{
if (e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Deleted)
{
}
else
{
var info = new FileInfo(e.FullPath);
var newSize = info.Length;
var oldsize = dic[e.FullPath];
string FileN1 = "File Name : ";
string FileN2 = info.Name;
string FileN3 = " Size Has Changed : From ";
string FileN4 = oldsize.ToString();
string FileN5 = " To ";
string FileN6 = newSize.ToString();
if (newSize != oldsize)
{
//string output = $"[*] {e.ChangeType}: \"{e.FullPath}\"";
Println(FileN1 + FileN2 + FileN3 + FileN4 + FileN5 + FileN6);
}
if (dic.ContainsKey(e.FullPath))
{
dic[e.FullPath] = info.Length;
}
else
{
dic.Add(e.FullPath, info.Length);
}
}
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Watcher_Renamed(object sender, RenamedEventArgs e)
{
try
{
Println($"[*] {e.ChangeType}: \"{e.OldFullPath}\" -> \"{e.FullPath}\"");
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Println(string text, SolidColorBrush brush) => Dispatcher.Invoke(() =>
{
richTextBox_main.Document.Blocks.Add(new Paragraph(new Run(text) { Foreground = brush }));
});
private void Println(string text)
{
Println("[+] " + text + " At : " + DateTime.Now.ToString(), Brushes.LawnGreen);
}
private void PrintMsg(string message)
{
Println($"[+] {message}", Brushes.Yellow);
}
private void PrintErr(Exception e)
{
Println($"[-] {e}", Brushes.Red);
}
private void CenterWindowOnScreen()
{
double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
double windowWidth = this.Width;
double windowHeight = this.Height;
this.Left = (screenWidth / 2) - (windowWidth / 2);
this.Top = (screenHeight / 2) - (windowHeight / 2);
}
private byte[] CheckSize(string filename)
{
using (MD5 md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
return md5.ComputeHash(stream);
}
}
}
private void textBox_path_TextChanged(object sender, TextChangedEventArgs e)
{
if (button_doit != null)
{
if (textBox_path.Text == "")
{
button_doit.IsEnabled = false;
}
else
{
button_doit.IsEnabled = true;
}
}
}
}
}

C# display a variable in a Textbox

i am sending Sensor information with a NUCLEOF411RE to my PC. I receive this data on the COM98 with a BaudRate of 115200. Now i want to program a Windows Application that will split my string and put it on my textboxes. until now i display the data with a Button_click event. It puts values on the Textboxes that actually are the real values. But if i move my Sensor and klick the button again there should be a lot more different values, but there are the same values on the textboxes. In addition i want to refresh the textboxes automatically and not with a button click.
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 System.IO.Ports;
namespace BNO080
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getAvailablePorts();
}
public string comport;
SerialPort serial = new SerialPort();
void getAvailablePorts()
{
String[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
comport = comboBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if(comboBox1.Text=="" || textBox6.Text=="")
{
MessageBox.Show("Please Select Port Settings");
}
else
{
serial.PortName = comboBox1.Text;
serial.BaudRate = Convert.ToInt32(textBox6.Text);
serial.Parity = Parity.None;
serial.StopBits = StopBits.One;
serial.DataBits = 8;
serial.Handshake = Handshake.None;
serial.Open();
MessageBox.Show("connected!");
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Unauthorised Access");
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
MessageBox.Show("connection closed!");
serial.Close();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
textBox5.Text = serial.ReadLine();
/*String[] Stringsizes = A.Split(new char[] {' '});
textBox1.Text = Stringsizes[0];
textBox2.Text = Stringsizes[1];
textBox3.Text = Stringsizes[2];
textBox4.Text = Stringsizes[3];*/
// textBox5.Text = A;
//Array.Clear(Stringsizes, 0, 3);
}
catch (Exception) { }
}
}
}
can someone help me?
Can you give more information why you use the Button_Click Event to read the text? Maybe it is a possible way for you to subscribe for the DataReceived-Event of the COM-port?
It would look something like this:
serial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
string receivedString = serial.ReadExisting();
//Do something here...
}
I'd do a couple things. First subscribe to the DataReceived event on the serial port. This event handler will get called when there is data available on the serial port. Then in the event handler you can read from the serial port and add it to your textbox. You can't add it directly (see the AppendText function) because the event handler is called with a different thread, only the UI thread can update UI components (or you'll get a cross-thread exception).
...
public Form1()
{
InitializeComponent();
getAvailablePorts();
// Subscribe to the DataReceived event. Our function Serial_DataReceived
// will be called whenever there's data available on the serial port.
serial.DataReceived += Serial_DataReceived;
}
// Appends the given text to the given textbox in a way that is cross-thread
// safe. This can be called by any thread, not just the UI thread.
private void AppendText(TextBox textBox, string text)
{
// If Invoke is required, i.e. we're not running on the UI thread, then
// we need to invoke it so that this function gets run again but on the UI
// thread.
if (textBox.InvokeRequired)
{
textBox.BeginInvoke(new Action(() => AppendText(textBox, text)));
}
// We're on the UI thread, we can append the new text.
else
{
textBox.Text += text;
}
}
// Gets called whenever we receive data on the serial port.
private void Serial_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
string serialData = serial.ReadExisting();
AppendText(textBox5, serialData);
}
Because i want to add an rotating 3D cube i decided to switch to WPF. I heard it is much easier to implement a 3D graphic there. So i copied my code to the new WPF project. But now i got already problems to visualize my values on the Textboxes. It doesnt work. It looks like the Evenhandler did not fire an event while receiving Data from the com port.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Drawing;
namespace cube
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
getAvailablePorts();
serial.DataReceived += Serial_DataReceived;
}
public bool button3clicked = false;
public bool button4clicked = false;
public bool button5clicked = false;
SerialPort serial = new SerialPort();
void getAvailablePorts()
{
List<string> Itemlist = new List<string>();
String[] ports = SerialPort.GetPortNames();
Itemlist.AddRange(ports);
comboBox1.ItemsSource = Itemlist;
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || textBox6.Text == "")
{
MessageBox.Show("Please Select Port Settings");
}
else
{
serial.PortName = comboBox1.Text;
serial.BaudRate = Convert.ToInt32(textBox6.Text);
serial.Parity = Parity.None;
serial.StopBits = StopBits.One;
serial.DataBits = 8;
serial.Handshake = Handshake.None;
serial.Open();
MessageBox.Show("connected!");
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Unauthorised Access");
}
}
private void button2_Click_1(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
MessageBox.Show("connection closed!");
serial.Close();
textBox1.Text = "test";
}
private void AppendText(string[] text)
{
try
{
textBox1.Text = text[0];
textBox2.Text = text[1];
textBox3.Text = text[2];
textBox4.Text = text[3];
}
catch (Exception) { }
}
private void Safe_Position1(TextBox tBr1, TextBox tBi1, TextBox tBj1, TextBox tBk1, string[] text)
{
if (button3clicked == true)
{
tBr1.Text = text[0];
tBi1.Text = text[1];
tBj1.Text = text[2];
tBk1.Text = text[3];
button3clicked = false;
}
}
private void Safe_Position2(TextBox tBr2, TextBox tBi2, TextBox tBj2, TextBox tBk2, string[] text)
{
if (button4clicked == true)
{
tBr2.Text = text[0];
tBi2.Text = text[1];
tBj2.Text = text[2];
tBk2.Text = text[3];
button4clicked = false;
}
}
private void Safe_Position3(TextBox tBr3, TextBox tBi3, TextBox tBj3, TextBox tBk3, string[] text)
{
if (button5clicked == true)
{
tBr3.Text = text[0];
tBi3.Text = text[1];
tBj3.Text = text[2];
tBk3.Text = text[3];
button5clicked = false;
}
}
private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string serialData = serial.ReadLine();
String[] text = serialData.Split(new char[] { ' ' });
AppendText(text);
Safe_Position1(textBox5, textBox7, textBox8, textBox9, text);
Safe_Position2(textBox10, textBox11, textBox12, textBox13, text);
Safe_Position3(textBox14, textBox15, textBox16, textBox17, text);
}
private void button3_Click(object sender, EventArgs e)
{
button3clicked = true;
}
private void button4_Click(object sender, EventArgs e)
{
button4clicked = true;
}
private void button5_Click(object sender, EventArgs e)
{
button5clicked = true;
}
}
}

How do I fix the speech synthesizer repeating itself c#?

So basically I used two speech recognition engines(speechrecog & speechrecog1) and one speech synthesizer. When the speechrecog is asked a question like how are you
it then replies I am fine (if the computer picks 2 from the two numbers 1,2). Then it initializes the second speech recognition engine. When it does its stuff. It then turns the second one off and the first one on again. But the problem is when using the second speech recognition engine it repeats( speech synthesizer) the number of times I have tried the second speech recognition engine out.
Here's my code for that form:
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;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Threading;
namespace Project_Juliet
{
public partial class Form11 : Form
{
public Form11()
{
InitializeComponent();
}
class FullScreen
{
public void EnterFullScreenMode(Form targetForm)
{
targetForm.WindowState = FormWindowState.Normal;
targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.WindowState = FormWindowState.Maximized;
}
public void LeaveFullScreenMode(Form targetForm)
{
targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
targetForm.WindowState = FormWindowState.Normal;
}
}
// System.Globalization.CultureInfo cl2 = new System.Globalization.CultureInfo("en-US");
SpeechRecognitionEngine speechrecog = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
SpeechSynthesizer ss = new SpeechSynthesizer();
PromptBuilder pb = new PromptBuilder();
Choices zlist = new Choices();
Form2 frm = new Form2();
FullScreen fs = new FullScreen();
bool SpeechRecognitionState = true;
Choices dirlist = new Choices();
SpeechRecognitionEngine speechrecog1 = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
bool sprs2 = false;
Choices us = new Choices();
string dir234;
string[] gm;
private void Form11_Load(object sender, EventArgs e)
{
listBox1.Visible = false;
string dir = "C:/Users/" + Environment.UserName + "/Documents/Juliet/response";
DirectoryInfo dinfo = new DirectoryInfo(dir);
FileInfo[] Files = dinfo.GetFiles("*.txt");
webBrowser1.ScriptErrorsSuppressed = true;
foreach (FileInfo file2 in Files)
{
string yts = ".txt";
listBox1.Items.Add(file2.Name.Replace(yts + "", ""));
}
/* String[] list = new String();
list = listBox1.Items.OfType<string>().ToList();
*/
fs.EnterFullScreenMode(this);
textBox1.Width = toolStrip1.Width - 10;
// toolStripTextBox1.Width = toolStrip1.Width - 30;
// toolStripTextBox1.Select();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Teen);
zlist.Add(new string[] { "exit"});
Grammar gr = new Grammar(new GrammarBuilder(zlist));
gr.Weight = 0.9f;
dirlist.Add(new string[]{"Mr.Danely"});
foreach (FileInfo file2 in Files)
{
string yts = ".txt";
dirlist.Add(file2.Name.Replace(yts + "", ""));
}
Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
gr1.Weight = 1f;
Grammar tgi = new DictationGrammar();
tgi.Weight = 0.3f;
try
{
if (SpeechRecognitionState == true)
{
speechrecog.RequestRecognizerUpdate();
speechrecog.LoadGrammar(gr);
speechrecog.LoadGrammar(gr1);
speechrecog.LoadGrammar(tgi);
speechrecog.SpeechRecognized += speechrecog_SpeechRecognized;
speechrecog.SetInputToDefaultAudioDevice();
speechrecog.RecognizeAsync(RecognizeMode.Multiple);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
//us.Add(new string[] { "yes","no","good","bad" });
us.Add(new string[] { "exit" });
Grammar gr12 = new Grammar(new GrammarBuilder(us));
if (sprs2 == true)
{
}
}
void speechrecog1_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if(File.Exists(#"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//"+e.Result.Text.ToString()+".txt"))
{
string hjjk = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//" + e.Result.Text.ToString() + ".txt";
StreamReader file = new StreamReader(hjjk);
string readText = file.ReadLine();
file.Close();
ss.Speak(readText);
timer2.Interval = 10;
timer2.Start();
}
}
void speechrecog_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string igput = e.Result.Text.ToString();
dir234 = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//" + igput + ".txt";
if (igput == "exit")
{
speechrecog.RecognizeAsyncStop();
this.Hide();
frm.Closed += (s, args) => this.Close();
frm.Show();
}
else
{
if (File.Exists(dir234))
{
StreamReader file = new StreamReader(dir234);
string readText = file.ReadLine();
file.Close();
if (readText.Contains("%"))
{
string[] words = readText.Split('%');
Random r = new Random();
int selection = r.Next(1, 3);
if (selection == 1)
{
ss.SpeakAsync(words[0]);
}
if (selection == 2)
{
if (readText.Contains('#'))
{
SpeechRecognitionState = false;
us.Add(new string[] { "exit" });
gm = words[1].Split('#');
string speak = words[0] + gm[0];
ss.SpeakAsync(speak);
List<string> lk = gm.ToList();
lk.RemoveAt(0);
string[] hkl = lk.ToArray<string>();
foreach(string g3 in hkl)
{
if (g3.Contains(".txt"))
{
string fj = g3.Replace(".txt" + "", "");
us.Add(fj);
}
else
{
string fj = g3;
us.Add(fj);
}
}
string dir333 = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1";
Grammar gr12 = new Grammar(new GrammarBuilder(us));
try
{
speechrecog1.RequestRecognizerUpdate();
speechrecog1.LoadGrammar(gr12);
speechrecog1.SpeechRecognized += speechrecog1_SpeechRecognized;
speechrecog1.SetInputToDefaultAudioDevice();
speechrecog1.RecognizeAsync(RecognizeMode.Single);
//speechrecog1.RecognizeAsyncStop();
//speechrecog.RecognizeAsync(RecognizeMode.Multiple);
//_completed.WaitOne(); // wait until speech recognition is completed
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
// timer2.Interval = 7000;
//timer2.Start();
// timer2.Interval = 5000;
//timer2.Start();
}
else
{
string speak = words[0] + words[1];
ss.SpeakAsync(speak);
}
}
}
else
{
ss.Speak(readText);
}
}
else
{
try
{
tabControl1.SelectedIndex = 1;
webBrowser1.Navigate("https://www.google.com/search?q=" + e.Result.Text.ToString());
}
catch (Exception ex)
{
string ggh = "Error"+ex;
}
}
}
/* SpeechRecognitionState = false;
timer1.Interval = 3000;
timer1.Start();
* */
textBox1.Text = "You: "+e.Result.Text.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
SpeechRecognitionState = true;
timer1.Stop();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void timer2_Tick(object sender, EventArgs e)
{
//loading the grammar again somehow make the recognition better
speechrecog.UnloadAllGrammars();
Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
gr1.Weight = 1f;
Grammar tgi = new DictationGrammar();
tgi.Weight = 0.3f;
Grammar gr = new Grammar(new GrammarBuilder(zlist));
gr.Weight = 0.9f;
speechrecog.LoadGrammar(gr);
speechrecog.LoadGrammar(gr1);
speechrecog.LoadGrammar(tgi);
SpeechRecognitionState = true;
speechrecog1.RecognizeAsyncStop();
speechrecog1.UnloadAllGrammars();
timer2.Stop();
}
}
}
For example:
the text file how are you.txt contains:
i am fine. thank you.% how are you#good#bad
and the computer asks if im good and I reply with good. In the good.txt file:
Oh thats cool
the first time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(1 time)
the 2nd time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(repeats it 2 times)
the 3rd time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(repeats it 3 times)
How do i fix the repetition problem.
Thanks to #Nikolay Shmyrev I found the solution. As he said my event handler was firing twice. So inside it I put a:
try
{
//My code
}
finally
{
speechrecog1.SpeechRecognized -= speechrecog1_SpeechRecognized;
}

How can i get the listening start time with speechRecognition in c#

I'm doing project in C# that read from a video file and convert it to subtitle text, but i want to get the start time for each text line so it can be shown in the video at the right time, i tried the AudioPosition but it not working well, is there a away to do this?
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Threading.Tasks;
namespace project
{
public partial class Form1 : Form
{
StringBuilder sb = new StringBuilder();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
string[] tokens;
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "WAV|*.wav";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
SpeechRecognitionEngine sre = new SpeechRecognitionEngine();
Grammar gr = new DictationGrammar();
sre.LoadGrammar(gr);
sre.SetInputToWaveFile(#openFileDialog1.FileName);
while (true)
{
try
{
var recText = sre.Recognize();
sb.Append(recText.Audio.AudioPosition + " * ");
textBox4.Text = sb.ToString();
tokens = sb.ToString().Split('#');
for (int i = 0; i < tokens.Length - 1; i++)
{
textBox2.AppendText(tokens.Length.ToString());
textBox2.AppendText(i+" - "+tokens[i]);
textBox2.AppendText(Environment.NewLine);
}
}
catch (Exception ex)
{
break;
}
}
}

C# Server-Client App(One Server-Multi Client)

I want to develop a client-server application. I started the project but I encountered the some problems. When I want to connect to server with one client, everything is done. Program is working. But when I want to connect with two or three etc. PC to server, clients of them is working but others is not working. How can I fix this problem?
Here is the 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;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Timers;
using ClientServer;
namespace ClientServer
{
public partial class Form1 : Form
{
private TcpClient Client;
private StreamReader STR;
public StreamWriter STW;
public string receive;
public string text_to_send;
//int zaman;
public Form1()
{
InitializeComponent();
- Client = new TcpClient();
Control.CheckForIllegalCrossThreadCalls = false; //cross threading problem
IPAddress[] LocalIP = Dns.GetHostAddresses(Dns.GetHostName()); // my IP Adress
foreach (IPAddress adress in LocalIP)
{
if(adress.AddressFamily== AddressFamily.InterNetwork)
{
textBox3.Text = adress.ToString();
}
}
}
private void button2_Click(object sender, EventArgs e) //Start server
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text));
listener.Start();
Client = listener.AcceptTcpClient();
STR = new StreamReader(Client.GetStream());
STW = new StreamWriter(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //receive data background
backgroundWorker2.WorkerSupportsCancellation = true; //ability cancel this thread
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //receive data
{
while(Client.Connected)
{
try
{
receive = STR.ReadLine();
if(receive=="soru1")
{
label7.Text = "Merhaba bu bir denemedir :)";
//zaman = 45;
timer1.Enabled = true;
}
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Sen:" + receive + "\n"); }));
receive = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //veri gönder
{
if(Client.Connected)
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ben:" + text_to_send + "\n"); }));
}
else
{
MessageBox.Show("Gönderim başarısız!");
}
backgroundWorker2.CancelAsync();
}
private void button3_Click(object sender, EventArgs e) //Connect Server
{
Client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text));
try
{
Client.Connect(IP_End);
if(Client.Connected)
{
textBox2.AppendText("Server'a bağlantı sağlandı" + "\n");
STW = new StreamWriter(Client.GetStream());
STR = new StreamReader(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //receive data in background
backgroundWorker2.WorkerSupportsCancellation = true; //
}
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
private void button1_Click(object sender, EventArgs e) //Send Button
{
if(textBox1.Text != "")
{
text_to_send = textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
//private void timer1_Tick(object sender, System.EventArgs e) //
//{
// zaman--; //timer her saniyede sayıyı 1 azaltacak
// label9.Text = zaman.ToString();
// if (zaman == 0)
// {
// timer1.Enabled = false;
// }
//}
}
}
Here a good links:
http://www.mikeadev.net/2012/07/multi-threaded-tcp-server-in-csharp/
https://www.codeproject.com/Articles/511814/Multi-client-per-one-server-socket-programming-in
tcpListener.Start();
Console.WriteLine("************This is Server program************");
Console.WriteLine("Hoe many clients are going to connect to this server?:");
int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine());
for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
}

Categories