I am at a loss after looking at relevant posts and documentation, many others seem to have had similar problems, but none of the existing solutions results in any keypresses actually being recognized by the browser.
All my code is below, just an empty form trying to type in a username/password on a website that currently doesn't have an API but it is coming. So this is just a bandaid fix until their API is fleshed out. Mostly just need to login and send keypresses to the website, but nothing seems to be working.
I have also tried: https://ourcodeworld.com/articles/read/520/simulating-keypress-in-the-right-way-using-inputsimulator-with-csharp-in-winforms
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 CefSharp;
using CefSharp.WinForms;
namespace Hydros_tmp_api
{
public partial class Form1 : Form
{
public ChromiumWebBrowser chromeBrowser;
string CurrentAddress = "";
public void InitializeChromium()
{
CefSettings settings = new CefSettings();
// Initialize cef with the provided settings
Cef.Initialize(settings);
// Create a browser component
chromeBrowser = new ChromiumWebBrowser("https://www.coralvuehydros.com/app/#/status");
// Add it to the form and fill it to the form window.
Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill;
(chromeBrowser).LoadingStateChanged += Browser_FrameLoadEnd;
chromeBrowser.AddressChanged += Browser_AddressChanged;
}
public Form1()
{
InitializeComponent();
InitializeChromium();
}
private void Form1_Load(object sender, EventArgs e)
{
}
async void Browser_FrameLoadEnd(object sender, LoadingStateChangedEventArgs e)
{ // Jumps in here when the page is fully loaded:
if (e.IsLoading == false)
{
if (CurrentAddress.Contains("login"))
{
timer_login.Enabled = true;
}
}
}
private void Browser_AddressChanged(object sender, AddressChangedEventArgs e)
{
CurrentAddress = e.Address;
}
private void timer_login_Tick(object sender, EventArgs e)
{
timer_login.Enabled = false;
chromeBrowser.GetBrowserHost().SetFocus(true);
Random rnd = new Random();
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.Tab, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyDown
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.Tab, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyUp
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.T, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyDown
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
chromeBrowser.GetBrowser().GetHost().SendKeyEvent(new KeyEvent
{
WindowsKeyCode = (int)Keys.T, // Enter
FocusOnEditableField = true,
IsSystemKey = false,
Type = KeyEventType.KeyUp
});
System.Threading.Thread.Sleep(rnd.Next(20, 120));
}
}
}
Edit: It appears to be a specific oddity with their website that is not accepting simulated input because it works fine on other sites? So idk where to go from here.
Related
I am trying to use SpeechRecognitionEngine in a C# application under Windows 11
I have tried the default microphone array that works with Cortana. I have tried an USB microphone and a bluetooth one. They all show they are working in Settings->Sound
I cannot get any of the events to fire including SpeechDetected and AudioStateChanged
Here is my code based on the Microsoft example:
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.Speech.Recognition;
using System.Diagnostics;
namespace Speech_Test
{
public partial class Form1 : Form
{
SpeechRecognitionEngine recognizer = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
recognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-GB"));
Choices services = new Choices(new string[] { "restaurants", "hotels", "gas stations" });
Choices cities = new Choices(new string[] { "Seattle", "Boston", "Dallas" });
GrammarBuilder findServices = new GrammarBuilder("Find");
findServices.Append(services);
findServices.Append("near");
findServices.Append(cities);
Grammar servicesGrammar = new Grammar(findServices);
recognizer.LoadGrammarAsync(servicesGrammar);
recognizer.SpeechDetected +=
new EventHandler<SpeechDetectedEventArgs>(recognizer_SpeechDetected);
recognizer.AudioStateChanged +=
new EventHandler<AudioStateChangedEventArgs>(recognizer_AudioStateChanged);
// Add a handler for the speech recognized event.
recognizer.SpeechRecognized +=
new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
recognizer.SpeechRecognitionRejected +=
new EventHandler<SpeechRecognitionRejectedEventArgs>(recognizer_SpeechRejected);
// Configure the input to the speech recognizer.
recognizer.SetInputToDefaultAudioDevice();
recognizer.RecognizeAsync(RecognizeMode.Multiple);
//recognizer.EmulateRecognize("Find restaurants near Dallas");
}
catch (Exception ex)
{
Debug.WriteLine(ex.InnerException.Message);
}
}
// Handle the AudioStateChanged event.
private void recognizer_AudioStateChanged(object sender, AudioStateChangedEventArgs e)
{
Debug.WriteLine("The new audio state is: " + e.AudioState);
}
private void recognizer_SpeechDetected(object sender, SpeechDetectedEventArgs e)
{
Console.WriteLine(" Speech detected at AudioPosition = {0}", e.AudioPosition);
}
private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
Debug.WriteLine("Recognized text: " + e.Result.Text);
}
private void recognizer_SpeechRejected(object sender, SpeechRecognitionRejectedEventArgs e)
{
Debug.WriteLine("Rejected text: " + e.Result.Text);
}
}
}
Any suggestions on how to find out why audio is not getting through?
Thanks
I am hoping someone can help me in getting an issue of mine to work, I feel as if it is an easy one, however not having any luck in fixing what I am trying to do. I want to be able to pause a video which I am playing using vlc.dotnet below is a brief summary of the structure of 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.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using Vlc.DotNet.Forms;
using System.Threading;
using Vlc.DotNet.Core;
using System.Diagnostics;
namespace TS1_C
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button8.Click += new EventHandler(this.button8_Click);
}
void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
string chosen = listBox1.SelectedItem.ToString();
string final = selectedpath2 + "\\" + chosen; //Path
playfile(final);
}
void playfile(string final)
{
var control = new VlcControl();
var currentAssembly = Assembly.GetEntryAssembly();
var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
// Default installation path of VideoLAN.LibVLC.Windows
var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
control.BeginInit();
control.VlcLibDirectory = libDirectory;
control.Dock = DockStyle.Fill;
control.EndInit();
panel1.Controls.Add(control);
control.Play();
}
private void button8_Click(object sender, EventArgs e)
{
}
}
}
As you can see I have one method which takes a double click from an item in a list box and plays it using the method playfile. However I want to be able to pause the video using my button known as button8. I have tried many things even this
control.Paused += new System.EventHandler<VlcMediaPlayerPausedEventArgs>(button8_Click);
Which I put into the playfile method, however nothing seems to work. I am wondering if my whole method in which I play a file using playfile(); is completely wrong. I am hoping someone can help me in trying to achieve what I need
Thank you
Your control should be initialized only once:
private VlcControl control;
public Form1()
{
InitializeComponent();
control = new VlcControl();
var currentAssembly = Assembly.GetEntryAssembly();
var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
// Default installation path of VideoLAN.LibVLC.Windows
var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
control.BeginInit();
control.VlcLibDirectory = libDirectory;
control.Dock = DockStyle.Fill;
control.EndInit();
panel1.Controls.Add(control);
}
then, your play method could be simplified:
void playfile(string url)
{
control.Play(url);
}
And for your pause method:
private void button8_Click(object sender, EventArgs e)
{
control.Pause();
}
I write code to create and connect to VPN using Dotras in C#. It works very good, but when I write code to get connection status, It doesn't work.
I read Dotras document, and write code like example, but It still doesn't work.
It doesn't show status in multiple line textbox. :(
Please show me, what I wrong. Thank you.
Here is 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.Tasks;
using System.Windows.Forms;
using DotRas;
using System.Net;
namespace VPN1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_create_vpn_Click(object sender, EventArgs e)
{
try
{
string vpnuser = txt_vpn_user.Text;
string ip_address = txt_IP.Text;
this.rasPhoneBook1.Open();
RasEntry entry = RasEntry.CreateVpnEntry(vpnuser, ip_address, RasVpnStrategy.Default, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn, false));
this.rasPhoneBook1.Entries.Add(entry);
MessageBox.Show("Success");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private RasHandle handle = null;
private void btn_dial_Click(object sender, EventArgs e)
{
this.rasDialer1.EntryName = txt_vpn_user.Text;
string username = txt_user.Text;
string password = txt_pass.Text;
this.rasDialer1.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
try
{
this.rasDialer1.Credentials = new NetworkCredential(username, password);
this.handle = this.rasDialer1.DialAsync();
this.btn_disconnect.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void rasDialer1_StateChanged(object sender, StateChangedEventArgs e)
{
this.txt_status.AppendText(e.State.ToString() + "\r\n");
}
private void rasDialer1_DialCompleted(object sender, DialCompletedEventArgs e)
{
if(e.Cancelled)
{
this.txt_status.AppendText("Cancelled");
}
else if(e.TimedOut)
{
this.txt_status.AppendText("Timeout");
}
else if(e.Connected)
{
this.txt_status.AppendText("Connection successful");
}
else if (e.Error != null)
{
this.txt_status.AppendText(e.Error.ToString());
}
if(!e.Connected)
{
this.btn_disconnect.Enabled = false;
}
}
private void btn_disconnect_Click(object sender, EventArgs e)
{
if(this.rasDialer1.IsBusy)
{
this.rasDialer1.DialAsyncCancel();
}
else
{
RasConnection connection = RasConnection.GetActiveConnectionByHandle(this.handle);
if(connection!=null)
{
connection.HangUp();
}
}
}
}
}
If the events are not firing, the issue might be that the Events are not set in the events section in the properties window of the rasDialer1 control you added to the form (Form1). Using Visual Studio, Enter the design view, click on the rasDialer1 control which reveals the properties of the RasDialer you added, then navigate to events section (marked with a lightening icon) and then set the StateChanged and DialCompleted events.
OR
You can do all this from code simply by
rasDialer.StateChanged += rasDialer1_StateChanged;
rasDialer.DialCompleted += rasDialer1_DialCompleted;
somewhere in the Form1() constructor, where rasDialer1_StateChanged and rasDialer1_DialCompleted are the event handlers in your code.
I'm also anticipating a potential error within your code where accessing UI controls in those event handlers will get you a Cross-thread operation not valid error since they are called from an async operation this.rasDialer1.DialAsync();
The right way of accessing controls from methods called from another thread is below ...
textbox1.Invoke(new Action(() => textbox1.text = "my string"));
Try using dial instead of dialAsync
try:
{
File.WriteAllText("your rasphone.pbk path","")//Add
string vpnuser = txt_vpn_user.Text;
string ip_address = txt_IP.Text;
this.rasPhoneBook1.Open();
RasEntry entry = RasEntry.CreateVpnEntry(vpnuser, ip_address, RasVpnStrategy.Default, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn, false));
this.rasPhoneBook1.Entries.Add(entry);
MessageBox.Show("Success");
}
This program is used to display the data and store the data into a txt file using the input from the pic18f4550.
when the GUI received the input data is '1 ', the GUI should display the data and store the data into a txt file. data can be saved, but the data are keep repeating itself without stopping if the input is still in a state of '1 '.
how should i do, if i want to store the data just once even the input still '1'?
Here is 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.Windows.Forms;
using System.IO;
namespace Monitoring_System
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
// Create the USB reference device object (passing VID and PID)
theUsbDemoDevice = new usbDemoDevice(0x04D8, 0x003F);
// Add a listener for usb events
theUsbDemoDevice.usbEvent += new usbDemoDevice.usbEventsHandler(usbEvent_receiver);
// Perform an initial search for the target device
theUsbDemoDevice.findTargetDevice();
}
// Create an instance of the USB reference device
private usbDemoDevice theUsbDemoDevice;
// Listener for USB events
private void usbEvent_receiver(object o, EventArgs e)
{
// Check the status of the USB device and update the form accordingly
if (theUsbDemoDevice.isDeviceAttached)
{
// Device is currently attached
// Update the status label
usb_status.Text = "Status : USB Device Connected";
}
else
{
// Device is currently unattached
// Update the status label
usb_status.Text = "Status : USB Device Unplugged";
cr1v.Visible = false;
cr1i.Visible = false;
cr2v.Visible = false;
cr2i.Visible = false;
cr3v.Visible = false;
cr3i.Visible = false;
tr1v.Visible = false;
tr1i.Visible = false;
tr2v.Visible = false;
tr2i.Visible = false;
tr3v.Visible = false;
tr3i.Visible = false;
}
}
private void button_exit_Click(object sender, EventArgs e)
{
this.Hide();
Form4 f2 = new Form4();
f2.ShowDialog();
}
private void timer1_Tick_1(object sender, EventArgs e)
{
if(theUsbDemoDevice.isDeviceAttached)
{
// Read the push button state
bool sw1 = theUsbDemoDevice.sw1();
if (sw1 == true)
{
cr1i.Visible = false;
cr1v.Visible = true;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"D:\Desktop\log data.txt", true))
{
file.WriteLine("Class Room 1 in use");
file.Close();
}
}
else if (sw1 == false)
{
cr1i.Visible = true;
cr1v.Visible = false;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"D:\Desktop\log data.txt", true))
{
file.WriteLine("Class Room 1 vacant");
file.Close();
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form5 f2 = new Form5();
f2.ShowDialog();
}
}
}
It looks like you are using a timer. Every tick your timer is writing to a file. You need to re-work your logic to either not include a timer. Or, disable it after a write, and re-enable it on another event.
So I am trying to change a voice in C# for the System.Speech.Synthesis library. It will work for me when I attempt the code in console mode. However when I am working on a windows application it does not change the voice while giving no errors. Here is the code of the windows application that works asside from the voice change.
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.Windows.Forms;
using System.Speech.Synthesis;
using System.Speech.Recognition;
namespace JarvisRev1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.button1.Click += new EventHandler(button1_Click);
this.button2.Click += new EventHandler(button2_Click);
this.button3.Click += new EventHandler(button3_Click);
foreach (InstalledVoice voice in sSynth.GetInstalledVoices())
{
cbVoice.Items.Add(voice.VoiceInfo.Name);
}
}
SpeechSynthesizer sSynth = new SpeechSynthesizer();
PromptBuilder pBuilder = new PromptBuilder();
SpeechRecognitionEngine sRecognize = new SpeechRecognitionEngine();
private void button1_Click(object sender, EventArgs e)
{
pBuilder.ClearContent();
pBuilder.AppendText(textBox1.Text);
sSynth.SelectVoice("IVONA 2 Brian");
sSynth.SpeakAsync(pBuilder);
}
private void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
button3.Enabled = true;
Choices sList = new Choices();
sList.Add(new string[] { "hello", "test", "it works", "how", "are", "you", "today", "i", "am", "fine", "exit", "close", "quit", "so", "hello how are you" });
Grammar gr = new Grammar(new GrammarBuilder(sList));
try
{
sRecognize.RequestRecognizerUpdate();
sRecognize.LoadGrammar(gr);
sRecognize.SpeechRecognized += sRecognize_SpeechRecognized;
sRecognize.SetInputToDefaultAudioDevice();
sRecognize.RecognizeAsync(RecognizeMode.Multiple);
sRecognize.Recognize();
}
catch
{
return;
}
}
private void button3_Click(object sender, EventArgs e)
{
sRecognize.RecognizeAsyncStop();
button2.Enabled = true;
button3.Enabled = false;
}
private void sRecognize_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (e.Result.Text == "exit")
{
Application.Exit();
}
else
{
textBox1.Text = textBox1.Text + " " + e.Result.Text.ToString();
}
}
}
}
This is the code in console mode that is working for me.
using System;
using System.Speech.Synthesis; // Add reference to System.Speech
class Program
{
static void Main(string[] args)
{
var synth = new SpeechSynthesizer();
synth.SelectVoice("IVONA 2 Brian");
synth.SpeakAsync("For you Sir, Always.");
foreach (var voice in synth.GetInstalledVoices())
{
Console.WriteLine(voice.VoiceInfo.Name);
}
Console.ReadLine();
}
}
Have same issue when Microsoft Irina Desktop voice is available in system. Workaround to set voice explicitly in prompt, e.g.:
using System.Speech.Synthesis;
var synth=new SpeechSynthesizer();
var builder=new PromptBuilder();
builder.StartVoice("Microsoft David Desktop");
builder.AppendText("Hello, World!");
builder.EndVoice();
synth.SpeakAsync(new Prompt(builder));
As you already utilize PromptBuilder, try to add StartVoice and EndVoice calls around text.