C# Using Speech to recite strings from a listbox - c#

T I'm having lots of trouble trying to get my code's speech synthesis class to recite words from a ListBoxItem.toString().
the foreach loop in the btnStart_Clicked() method is where i believe the problem starts:
test = testLstSet.lstWordlist.Items.ToString();
speech.SpeakAsync(test);
the speech synth tells me:
"system.windows.forms.listbox + object.collections"
could someone please help? sorry about all the code but i wanted to give you as much info as possible.
what am i doing wrong?
public partial class MyClass : Form
{
private bool testStarted = false;
private SpeechSynthesizer speech;
private string evalWord = null;
string test;
bool testBit = false;
TestList testLstSet;
public SpellingBee(TestList tstLst)
{
InitializeComponent();
testLstSet = tstLst;
speech = new SpeechSynthesizer();
speech.SpeakAsync("Hello! Welcome to The test. Shall we begin?");
}
private void btnStart_Click(object sender, EventArgs e)
{
if (testStarted)
return;
else
{
testStarted = true;
foreach(var item in wrdLstSet.lstWordlist.Items)
{
test = testLstSet.lstWordlist.Items.ToString();
speech.SpeakAsync(test);
while(!testBit)
{
}
}
}
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string evalWord = this.txtAnswer.Text;
bool answer = string.Equals(evalWord, test, StringComparison.OrdinalIgnoreCase);
if (answer)
{
speech.SpeakAsync("That's right! Good Job!");
testbit = true;
}
else
{
speech.SpeakAsync("That is incorrect.");
testbit = true;
}
}
}
}

I don't really understand what you want to achieve but I think you need part of your code to
foreach(var item in testLstSet.lstWordlist.Items)
{
speech.SpeakAsync(item.ToString());
}
When you call testLstSet.lstWordlist.Items.ToString(); - you are getting type of Items, that is object.collections. If you want to get element of this collection you should use indexer like this: testLstSet.lstWordlist.Items[0].ToString();

Related

Wait users click on popup with Rg.Plugins.Popup

I show a pop up and I have to wait user's choice to put something in an entry control, the problem is that the if statment where I decide what goes as text in entry is executing at the same time as the popup shows.
I tried by making the method await but not working, here's what I have.
Donesn't matter by now the if() statement,I was just trying
This is my popup class (I want to wait until one of the buttons is clicked):
public partial class PopupElegirRFC : PopupPage
{
string sEmisor = "";
string sReceptor = "";
public PopupElegirRFC (string emisor, string receptor)
{
InitializeComponent ();
lblREmisor.Text = "Emisor: " + emisor;
lblRReceptor.Text = "Receptor: " + receptor;
sEmisor = emisor;
sReceptor = receptor;
}
private void BtnEmisor_Clicked(object sender, EventArgs e)
{
PopupNavigation.Instance.PopAllAsync();
VGlobales.sRFSeleccionado = sEmisor;
}
private void BtnReceptor_Clicked(object sender, EventArgs e)
{
PopupNavigation.Instance.PopAllAsync();
VGlobales.sRFSeleccionado = sReceptor;
}
}
This is the code where I want to wait for users choice:
case 2:
await PopupNavigation.Instance.PushAsync(new Popups.PopupElegirRFC(list[0], list[1]));
if (VGlobales.sRFSeleccionado == list[1])
{
RFCavalidar.Text = list[1];
VGlobales.sRFSeleccionado = "";
}
else
{
RFCavalidar.Text = list[0];
VGlobales.sRFSeleccionado = "";
}
break;
The code executes, but it goes directly to the if(), not waiting the user's choice
I would like to the popup to wait until some of both buttons in it is clicked. so I can make the if() validation
It's an old question but my answer can help someone.
Add TaskCompletionSource and wait for return.
Popup class:
public partial class PopupElegirRFC : PopupPage
{
private TaskCompletionSource<string> taskCompletionSource;
public Task<string> PopupClosedTask { get { return taskCompletionSource.Task; } }
string sEmisor = "";
string sReceptor = "";
public PopupElegirRFC (string emisor, string receptor)
{
InitializeComponent();
lblREmisor.Text = "Emisor: " + emisor;
lblRReceptor.Text = "Receptor: " + receptor;
sEmisor = emisor;
sReceptor = receptor;
}
protected override void OnAppearing ()
{
base.OnAppearing();
taskCompletionSource = new TaskCompletionSource<string>();
}
private void BtnEmisor_Clicked (object sender, EventArgs e)
{
taskCompletionSource.SetResult(sEmisor);
PopupNavigation.Instance.PopAllAsync();
}
private void BtnReceptor_Clicked (object sender, EventArgs e)
{
taskCompletionSource.SetResult(sReceptor);
PopupNavigation.Instance.PopAllAsync();
}
}
Code where you want to wait:
var popupElegirRFC = new Popups.PopupElegirRFC(list[0], list[1]);
await PopupNavigation.Instance.PushAsync(popupElegirRFC);
string result = await popupElegirRFC.PopupClosedTask;
if (result == list[1])
{
RFCavalidar.Text = list[1];
}
else
{
RFCavalidar.Text = list[0];
}
This idea came from the link below:
https://github.com/rotorgames/Rg.Plugins.Popup/issues/116
as jason suggested , you can use MessagingCenter to evaluate whether which button is clicked or not.
In your Button click in popup page
private void BtnEmisor_Clicked(object sender, EventArgs e)
{
MessagingCenter.Send((App)Application.Current,"BtnEmisor_Clicked");
PopupNavigation.Instance.PopAllAsync();
VGlobales.sRFSeleccionado = sEmisor;
}
In your non- Popup page
MessagingCenter.Subscribe((App)Application.Current, "BtnEmisor_Clicked", (sender) =>
{
// Do task on that button click
});

Can't control Threads from different Methods WPF C#

I'm writing a small Keylogger for some statistics about my typing.
The Keylogger works fine, but now i want to implement it to a wpf to have a better control.
public MainWindow()
{
InitializeComponent();
Thread ThreadLog = new Thread(Log);
Thread ThreadRefreshForm = new Thread(refreshForm);
Thread ThreadAutoSave = new Thread(AutoSave);
ThreadLog.Start();
ThreadRefreshForm.Start();
ThreadAutoSave.Start();
}
private void btn_ThreadLogStop_Click(object sender, RoutedEventArgs e)
{
if (ThreadLog.IsAlive == true)
{
ThreadLog.Abort();
}
This gives me an Error # ThreadLog.IsAlive. How can i solve the Problem?
Thanks for your help!!!!
You should declare your ThreadLog somewhere else and initialize it in the constructor, such that the method can access the ThreadLog:
private Thread ThreadLog;
public MainWindow()
{
InitializeComponent();
ThreadLog = new Thread(Log);
...
}
private void btn_ThreadLogStop_Click(object sender, RoutedEventArgs e)
{
if (ThreadLog.IsAlive == true)
{
ThreadLog.Abort();
}
Generally speaking the correct way how to end threads is like this
private volatile bool m_Stop;
public void ThreadLoop()
{
while(!m_Stop) {
// do some work
}
}
// starting
new Thread(ThreadLoop).Start();
// "force" end
m_Stop = true;
Or if you prefer tasks over threads (which I do):
public void ThreadLoop(CancellationToken token)
{
while(!token.IsCancellationRequested)
{
// do some work
}
}
var cancelation = new CancellationTokenSource();
// starting
new Task(() => ThreadLoop(cancelation.Token), cancelation.Token).Start();
// "force" end
cancelation.Cancel();

Console C# check for internet availability and wait until it is not available

I have been searching for the code which will help me if the internet connection breaks in between.
I am having a console app which takes data from database and sends mail in bulk. Now while sending mails if internet connection fails than I want to wait until internet is available.
I got good ans here
public static void ConnectToPUServer()
{
var client = new WebClient();
while (i < 500 && networkIsAvailable)
{
string html = client.DownloadString(URI);
//some data processing
Console.WriteLine(i);
i++;
URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
}
Console.WriteLine("Complete.");
writer.Close();
}
static void NetworkChange_NetworkAvailabilityChanged(object sender,NetworkAvailabilityEventArgs e)
{
networkIsAvailable = e.IsAvailable;
if (!networkIsAvailable)
{
Console.WriteLine("Internet connection not available! We resume as soon as network is available...");
}
else
{
ConnectToPUServer();
}
}
This is not exactly what I want. But I want to apply something similar to this. Can anybody help me how to implement this? I mean what is ConnectToPUServer and when NetworkChange_NetworkAvailabilityChanged will be executed and what namespace to be used?
you can use the below mentioned code for it you have to use
using System.Net.NetworkInformation;
public partial class MainWindow : Window
{
public bool IsAvailable { get; set; }
public MainWindow()
{
InitializeComponent();
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
IsAvailable = e.IsAvailable;
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
if (IsAvailable)
{
WebBrowser1.Navigate(TextBox1.Text);
}
else
{
MessageBox.Show("Your Popup Message");
}
}
}

Winforms Progress Bar update

I'm a new programmer to C# and I would like some help. I searched a lot but I didn't find a simple example. Please see the code below:
public partial class Welcome : Form
{
public Welcome()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
Compare comp = new Compare();
comp.Comparator();
}
}
In the Compare Class I have a simple method that contains a simple loop:
public class Compare
{
public void Comparator()
{
for (int i;i<val;i++)
{ /* ............. */ }
}
}
I want to update the ProgressBar in parallel with an increment of the value of i.
You said you searched a lot... where? These are most trivial things with very well described examples in MSDN
in BackgroundWorker_doWork method:
Parallel.For(0, val, i =>
{
...
backgroundWorker.ReportProgress(0);
});
in BackgroundWorker_reportProgress method:
wf.progressBar.Value=wf.progressBar.Value + 1;
in Main form constructor
public Welcome()
{
InitializeComponent();
Compare.wf=this;
}
in
public class Compare
{
static Welcome wf;
public void Comparator()
{
backgroundWorker.RunWorkerAsync();
}
}
A simple way of doing that is:
public class Compare
{
public void Comparator()
{
progressBar.Value = 0;
progressBar.Maximum = val;
progressBar.Step = 1;
for (int i;i<val;i++)
{
/* ............. */
progressBar.PerformStep();
}
}
}

C# Sql Server "loading window"

This is my first post here, but I've using this site regularly to help me with my own app's, and I should say that this site has been a great help to me, so thanks to everyone.
Now my question:
I'm developing my first software app that exchanges data between a sql server and the app itself. It's beeing developed in C#. Saving or retreiving data from the sql server database is no problem.
What I want is a way to inform the user of the delay between the local machine (where the app is installed) and the server. I can make some animations or simply display some text messages. What I need help with is how to create the code that activates/fires/runs when that server communication time is running.
If you can't understand the idea, picture a video game. When it's loading (in some games) you can see the loading screen before the game starts. I need some code that displays that "loading window" when the the app is downloading or uploading data from/to the server.
I would appreciate any code example or web site recommendation.
PS: Sorry for the extensive text, but I want to make sure everyone understand so I don't have to repeat it again :P
How do I implement a progress bar in C#?
How to create a smooth progress bar in Visual C#
ProgressBar Class
I have developed a simple PleaseWait class 2 years ago, but I didn't update this class, It works very well, have look hope this will give you an idea to implement your logic.
public partial class frmWait : Form
{
public frmWait()
{
InitializeComponent();
}
bool _isMoving = false;
int _moveStart_x = 0;
int _moveStart_y = 0;
private void tmrProgress_Tick(object sender, EventArgs e)
{
if (barProgress.Value == barProgress.Maximum)
barProgress.Value = barProgress.Minimum;
else
barProgress.Value += 1;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
PleaseWait.Abort();
}
protected override CreateParams CreateParams
{
get
{
System.Windows.Forms.CreateParams p = base.CreateParams;
p.ClassStyle += 0x20000;
p.ExStyle += 0x8000000;
return p;
}
}
protected override void WndProc(ref Message m)
{
const int WM_NCHITTEST = 132;
base.WndProc(ref m);
switch (m.Msg)
{
case WM_NCHITTEST:
if (m.Result.ToInt32() == 1)
m.Result = new IntPtr(2);
break;
}
}
private void panelEx1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_isMoving = true;
_moveStart_x = e.X;
_moveStart_y = e.Y;
}
}
private void panelEx1_MouseUp(object sender, MouseEventArgs e)
{
_isMoving = false;
}
private void pnlContainer_MouseMove(object sender, MouseEventArgs e)
{
if (_isMoving)
this.Location = new Point(Location.X + e.X - _moveStart_x, Location.Y + e.Y - _moveStart_y);
}
}
public class PleaseWait
{
#region Static Operations
private static Boolean _isAborted = false;
private static Boolean _isVisible = false;
private static frmWait _waitForm;
private static String _waitingState = "";
private static Boolean _autoClose = false;
private static Boolean _cancelable = false;
private static System.Threading.Thread _waiterThred;
public delegate void CancelButtonPressed();
public static event CancelButtonPressed OnCancel;
public static Boolean AutoClose
{
get { return PleaseWait._autoClose; }
set { PleaseWait._autoClose = value; }
}
public static string WaitingState
{
get { return PleaseWait._waitingState; }
set { PleaseWait._waitingState = value; }
}
public static bool IsVisible
{
get { return _isVisible; }
internal set { _isVisible = value; }
}
public static void ShowPleaseWait()
{
ShowPleaseWait("", _autoClose, false);
}
public static void ShowPleaseWait(string waitingState)
{
ShowPleaseWait(waitingState, _autoClose, false);
}
public static void ShowPleaseWait(bool autoClose)
{
ShowPleaseWait("", autoClose, false);
}
public static void ShowPleaseWait(string waitingState, bool autoClose, bool cancelable)
{
if (_waiterThred != null)
{
if (_isVisible)
{
// the please wait it woking, just continue and apply the changes
_waitingState = waitingState;
_autoClose = autoClose;
_cancelable = cancelable;
return;
}
else
{
_waiterThred.Abort();
_waiterThred = null;
}
}
_waitingState = waitingState;
_autoClose = autoClose;
_cancelable = cancelable;
_isAborted = false;
_isVisible = false;
if (_autoClose)
Application.Idle += new EventHandler(Application_Idle);
_waiterThred = new System.Threading.Thread(DisplayWaitingForm);
_waiterThred.IsBackground = true;
_waiterThred.Name = "Please Wait....";
_waiterThred.Start();
Application.DoEvents();
}
public static void Abort()
{
_isAborted = true;
}
private static void Application_Idle(object sender, EventArgs e)
{
if (_autoClose)
_isAborted = true;
}
private static void DisplayWaitingForm()
{
if (_waitForm != null)
{
if (!_waitForm.IsDisposed)
_waitForm.Dispose();
_waitForm = null;
_isVisible = false;
}
try
{
if (_isAborted)
return;
_waitForm = new frmWait();
if (_cancelable)
{
_waitForm.btnCancel.Enabled = true;
_waitForm.btnCancel.Click += new EventHandler(btnCancel_Click);
}
try
{
_isVisible = true;
_waitForm.Show();
_waitForm.Focus();
while (!_isAborted)
{
System.Threading.Thread.Sleep(15);
_waitForm.lblMessage.Text = _waitingState;
Application.DoEvents();
_waitForm.lblMessage.Text = _waitingState;
}
_isVisible = false;
}
finally
{
FreeWaitingForm();
}
}
finally
{
_isVisible = false;
}
}
static void btnCancel_Click(object sender, EventArgs e)
{
if (_waitForm.InvokeRequired)
{
_waitForm.BeginInvoke(new EventHandler(btnCancel_Click), new object[] { e });
}
else
{
if (OnCancel != null)
OnCancel.Invoke();
}
}
private static void FreeWaitingForm()
{
_waitingState = "";
_isVisible = false;
if (_waitForm == null)
{
return;
}
_waitForm.Hide();
if (!_waitForm.IsDisposed)
_waitForm.Dispose();
_waitForm = null;
}
#endregion
}
use like following code :
PleaseWait.ShowPleaseWait("Please wait", true, false);
// If second param is true then it will close the form automatically.
// If third param is true the it will expose a cancel button, so you can cancel your Asynchronous operations.
I didn't insert design code, you can understand by looking at code.
hope this help.
First let me thank you for your replies.
Toby your answer got me thinking about thread monitoring my sql connections but it was a bit tricky and confusing since the app is still in develop and will use a lot more connections.
S.Amani answer it wasn't quite what I want, but thanks to that I found a easier way. I created a form (could be anything else), placed a label saying: Saving To Data Base, took out the top bar, defined location and defined it's parent to be disabled when shown and enabled when closed. The following code is what I put inside my DataBaseInteractionClass
private Wait myCustomWaitDialog = new Wait(); // My Waiting form
private void SaveToDatabase(myObjectToSave obj) // Method called to save data do DB
{
// Create the connections and queries
(...)
// This is what I did
// Show Waiting Form
myCustomWaitDialog.Show();
// Instanciate the command that will carry the query and to DB
SqlCommand command = new SqlCommand(Queries.GetData(code), conn);
// This is important
//Create event that will fire when the command completes
command.StatementCompleted += new StatementCompletedEventHandler(command_StatementCompleted);
// Execute the transaction
SqlDataReader reader = command.ExecuteReader();
// Rest of the code (validations, close connections, try/catch, etc
(...)
}
void command_StatementCompleted(object sender, StatementCompletedEventArgs e)
{
// This is the method that closes my Waiting Dialog
myCustomWaitDialog.CloseDialog();
myCustomWaitDialog.Dispose();
}
It's not quite what I want yet, but is the best solution that I found so far. For now it will do :)
Anyway, thanks for the replies and I hope this helps someone else.

Categories