How to capture Enter key in a ListBox control? - c#

I read articles over the internet but I think I'm missing something here. I tried following the answer to this SO question, but nothing has happened.
I wanted to trigger the usePort_Click method whenever I press the Enter/Return key. Also, I don't know how to get around the EventArgs parameter of usePort_Click whenever I do try calling it from the ports_Keydown method.
Note: ports is a ListBox control.
private void usePort_Click(object sender, EventArgs e)
{
try
{
port = new SerialPort((string)ports.SelectedItem, 9600);
portUsedLabel.Text = (string)ports.SelectedItem;
String buffer = "";
String tellArduino = "food"; // test value
port.Open();
port.WriteLine(tellArduino);
for (int x = 0; x < tellArduino.Length; x++)
{
buffer += port.ReadLine();
}
ports.Items.Add(buffer);
port.Close();
}
catch { //stuff }
}
private void ports_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//code here
}
}

A good solution would be to move the code you want to execute into a separate method (I called it someStuff, replace the name with something better) and call that method from both event handlers:
private void usePort_Click(object sender, EventArgs e)
{
someStuff();
}
private void ports_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
someStuff();
}
}
private void someStuff()
{
try
{
port = new SerialPort((string)ports.SelectedItem, 9600);
portUsedLabel.Text = (string)ports.SelectedItem;
String buffer = "";
String tellArduino = "food"; // test value
port.Open();
port.WriteLine(tellArduino);
for (int x = 0; x < tellArduino.Length; x++)
{
buffer += port.ReadLine();
}
ports.Items.Add(buffer);
port.Close();
}
catch { //stuff }
}

Related

cant get my Value in Listview Virtualmode

after clicking my value and pressing my OK_button I cant get the Value out of the listView to save it somewhere else. I cant use listView1.FindItemWithText because I don't have a text to search for.. Idk how to look for the clicked value after I pressed the OK_button
//Create dummy data to display
myData = new string[dataListSize];
for (int i = 0; i < dataListSize; i++)
{
myData[i] = String.Format("{0}", i);
}
}
private void listView1_SearchForVirtualItem(object sender, SearchForVirtualItemEventArgs e)
{
e.Index = Array.FindIndex(myData, s => s == textBox1.Text.ToString());
}
private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
e.Item = new ListViewItem(myData[e.ItemIndex]);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
String MyString = textBox1.Text.ToString();
ListViewItem lvi = listView1.FindItemWithText(MyString.TrimEnd());
//Select the item found and scroll it into view.
if (lvi != null)
{
listView1.SelectedIndices.Clear();
listView1.SelectedIndices.Add(lvi.Index);
listView1.EnsureVisible(lvi.Index);
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e){ }
private void OK_button_Click(object sender, EventArgs e)
{
try
{
// OK -> Daten übernehmen
int iCount = this.listView1.SelectedIndices.Count;
if (iCount != 1)
{
MessageBox.Show("Value is empty");
return;
}
DialogResult = DialogResult.OK;
Close();
}
catch (Exception)
{
//WriteProtokoll(ex.ToString(), 0);
Close();
}
}
I found out that I can get my value with:
string txt = listView1.FocusedItem.Text;

How to use check a Button in another Button statement? c#

I am having a problem . I want to use if statement to check if a button is clicked. For Example:
public void button1_Click(object sender, EventArgs e)
{
while (1)
{
...
...
...
if (Button2 == clicked)
{
break;
}
}
}
But it's not working like this, because the ".click" can only be on the left side of "+=" or "-=". Any idea how i can check if Button2 is clicked?
the code is loking like this: and i want to check button2 to stop the "programm".
the check for the Button2 is nearly at the end of the code ;)
public void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int EmFilterPos;
int ExFilterPos;
string String1;
int[] EmLB = new int[126];
int[] ExLB = new int[126];
int LBEmAnzahl = 0;
int LBEmTot = 0;
int LBExAnzahl = 0;
int LBExTot = 0;
UInt32 C_Zyklen;
UInt32 Zyklen;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_On = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOn;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_Off = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOff;
Roche.DetectionControl2.Device_Filterwheels.fiweGetLBResponse LightBarrier;
string Text = String.Format("Filterrad-Dauertest\r\nGestart am {0:d} um {0:t}\r\n\r\n", DateTime.Now);
System.IO.File.WriteAllText(#"TestLogFile\Filterrad_Dauertest1.txt", Text);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
while (Zyklen <= 20)
{
for (int q=1;q<8;q++)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(q,q);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
for (int w=0;w<7;w++)
{
ExFilterPos = rnd.Next(1,8);
EmFilterPos = rnd.Next(1,8);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
C_Zyklen = Zyklen;
if ((C_Zyklen % 2) < 14)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Init bei: ");
String1 = String.Format("{0,7}",Zyklen);
file.Write(String1);
file.Write(file.NewLine);
}
ExFilterPos = 60;
EmFilterPos = 60;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_On);
while (EmFilterPos != -60)
{
LightBarrier = Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweGetLB();
if (LightBarrier.LBEm == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBEmAnzahl++;
LBEmTot += EmFilterPos;
}
if (LightBarrier.LBEx == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBExAnzahl++;
LBExTot += ExFilterPos;
}
ExFilterPos--;
EmFilterPos--;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
}
EmFilterPos = LBEmTot / LBEmAnzahl;
ExFilterPos = LBExTot / LBExAnzahl;
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Nullstelle Mittelposition Em-Filter: ");
file.Write(EmFilterPos);
file.Write(file.NewLine);
file.Write("Nullstelle Mittelposition Ex-Filter: ");
file.Write(ExFilterPos);
file.Write(file.NewLine);
file.Write(file.NewLine);
}
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_Off);
}
if (Button2 == clicked) // or something like this
break;
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Beendet am {0:d} um {0:t}\r\n", DateTime.Now);
}*/
}
Hm...
bool b1clicked = false, b2clicked = false;
public void button2_Click(object sender, EventArgs e)
{
b2clicked = true;
}
public void button1_Click(object sender, EventArgs e)
{
b1clicked = true;
if (b1clicked && b2clicked)
{
//...
}
}
Beside the weird behavior you want..and since you are not using Threads, you have the following options:
Local functions (.Net > 4.7)
private void B_Click(object sender, EventArgs e)
{
bool clickFlag = false;
void Click(object sender2, EventArgs e2)
{
clickFlag = true;
}
b2.Click += Click;
while (!clickFlag)
{
Thread.Sleep(1);
}
b2.Click -= Click;
//Continue with your stuff
}
Threads
Thread newThread;
private void Button1_Click()
{
newThread = new Thread(YourBreakableProcess);
newThread.Start();
}
private void Button2_Click()
{
newThread.Join();
}
private void YourBreakableProcess()
{
//Your breakable process
}
Async methods.
I hope you find a solution. Cheers.
Edit:
Since what you want is to interrupt the process of whatever you are doing, the only option you have is Local fuctions as shown above, if you are not tied to a specific framework version.
BackgroundWorker and check in every step if the button 2 was pressed with the flag thing mentioned in other answer.
Threads, and make a thread.Join when the button 2 is pressed.
Edit 2:
Updated answer with Threads, I will recommend that if you go with this option it is much better to use a BackgroundWorker instead as you will have the whole control of the process breaking it only in the place where it would be fine to break it.
You can achieve this using a flag variable. Declare and initialize flag value to false.On button2 click change flag value to true as follows,
private bool flag= false;
private void button2_Click(object sender, EventArgs e)
{
flag= true;
}
public void button1_Click(object sender, EventArgs e)
{
//Use flag to check whether button 2 has clicked or not
if (flag)
{
}
else
{
}
}

How to make Trackbar works while media is playing

I am working on a simple mediaplayer application. It works great but I want to add some extra features. I have added a trackbar control.How can i set trackbar length the same as the music's length ?
Like if the song is halfways the trackbars halfways.This is what I have so far
string[] files, indexed_files;
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if (ofd.ShowDialog() == DialogResult.OK) {
files = ofd.SafeFileNames;
indexed_files = ofd.FileNames;
for (int i = 0; i < files.Length; i++)
{
listBox1.Items.Add(files[i]);
}
}
button4.Enabled = true;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = indexed_files[listBox1.SelectedIndex];
progressBar1.Maximum =(int) axWindowsMediaPlayer1.currentMedia.duration;
axWindowsMediaPlayer1.PlayStateChange += axWindowsMediaPlayer1_PlayStateChange;
}
void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
trackBar1.Value = (int)axWindowsMediaPlayer1.Ctlcontrols.currentPosition;
}
int index = 0;
private void button4_Click(object sender, EventArgs e)
{
if (listBox1.Items.Count != 0) {
axWindowsMediaPlayer1.URL = indexed_files[index];
trackBar1.Maximum = (int)axWindowsMediaPlayer1.currentMedia.duration;
index++;
index = (index % listBox1.Items.Count);
}
}
This will bring you the desired outcome.In my example i just placed the url in the form load for demonstration purposes.The openstatechanged event its to set the trackbar maximum since you need to wait for the player to load the file,after that the code its pretty self-explanatory:
public partial class Form1 : Form
{
Timer t;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = "YourUrlHere";
t = new Timer();
t.Interval = 1000;
t.Tick += new EventHandler(t_Tick);
}
void t_Tick(object sender, EventArgs e)
{
trackBar1.Value = (int)this.axWindowsMediaPlayer1.Ctlcontrols.currentPosition;
}
private void axWindowsMediaPlayer1_OpenStateChange(object sender, AxWMPLib._WMPOCXEvents_OpenStateChangeEvent e)
{
if (axWindowsMediaPlayer1.openState == WMPLib.WMPOpenState.wmposMediaOpen)
{
trackBar1.Maximum = (int)axWindowsMediaPlayer1.currentMedia.duration;
t.Start();
}
}
}
Yes its a timer:),and probably it is best to set it bellow 1000 for reasons of delay.
So you should now add a timer and insert the following code in timer Tick event handler:
trackbar.Value = this.axWindowsMediaPlayer1.ctlControls.CurrentPosition;

Where to declare queues in separate event handlers

Hi I am trying to use the queue function in my program for a mini game that receives X,Y,Z acceleration from an accelerometer.
However I don't know where I should or how I should declare the queue to make it accessible in two separate event handler.
As you can see I tried multiple attempts and declaring it in both the private event handlers was my last attempt.
Any help is appreciated. Thanks!
Here's my current code:
public Form1()
{
InitializeComponent();
ConnectedComPortUpdate();
serialPort1.DataReceived += DataReceivedHandler;
comboBox1.DropDown += comboBox1_DropDown;
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
ConnectedComPortUpdate();
}
private void Clock_Tick(object sender, EventArgs e)
{
int xAccel;
int yAccel;
int zAccel;
Queue<int> myXQueue = new Queue<int>();
Queue<int> myYQueue = new Queue<int>();
Queue<int> myZQueue = new Queue<int>();
while( myXQueue.Count!=0 && myYQueue.Count!=0 && myZQueue.Count!=0 );
{
xAccel = myXQueue.Dequeue();
yAccel = myYQueue.Dequeue();
zAccel = myZQueue.Dequeue();
this.BeginInvoke(new EventHandler(delegate
{
XAccel.Text = xAccel.ToString("000");
YAccel.Text = yAccel.ToString("000");
ZAccel.Text = zAccel.ToString("000");
}));
}
}
private void ConnectedComPortUpdate()
{
//Clears COM List
comboBox1.Items.Clear();
//Accesses System Port Information and Adds it to the ComboBox
comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames().ToArray());
//Selects the last and "first" device
try
{
comboBox1.SelectedIndex = 0;
}
catch (ArgumentOutOfRangeException)
{
MessageBox.Show("Please plug in your tiny stick");
comboBox1.Text = (" ");
}
}
private void button1_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen)
{
try
{
serialPort1.PortName = comboBox1.Text;
serialPort1.Open();
comboBox1.Enabled = false;
butPortState.Text = "Disconnect";
MessageBox.Show(String.Format("You selected port '{0}'", serialPort1.PortName));
}
catch
{
MessageBox.Show("Please select a serial port from the drop down list");
}
}
else
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
comboBox1.Enabled = true;
butPortState.Text = "Connect";
}
}
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int currentDataByte = 0;
int byteToRead;
int xAccel = 0;
int yAccel = 0;
int zAccel = 0;
Queue<int> myXQueue = new Queue<int>();
Queue<int> myYQueue = new Queue<int>();
Queue<int> myZQueue = new Queue<int>();
while (serialPort1.IsOpen && serialPort1.BytesToRead != 0)
{
try
{
byteToRead = serialPort1.ReadByte();
}
catch
{
byteToRead = 0;
}
if (byteToRead == 255)
{
currentDataByte = 0;
}
else
{
currentDataByte++;
switch (currentDataByte)
{
case 1:
myXQueue.Enqueue(byteToRead);
xAccel = byteToRead;
break;
case 2:
myYQueue.Enqueue(byteToRead);
yAccel = byteToRead;
break;
case 3:
myZQueue.Enqueue(byteToRead);
zAccel = byteToRead;
break;
}
}
}
}
}
}
You would need the queues to be declared at the class/instance level:
// These can now be used in all event handlers...
Queue<int> myXQueue = new Queue<int>();
Queue<int> myYQueue = new Queue<int>();
Queue<int> myZQueue = new Queue<int>();
public Form1()
{
InitializeComponent();
ConnectedComPortUpdate();
serialPort1.DataReceived += DataReceivedHandler;
comboBox1.DropDown += comboBox1_DropDown;
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
ConnectedComPortUpdate();
}
private void Clock_Tick(object sender, EventArgs e)
{
int xAccel;
int yAccel;
int zAccel;
I don't think the answer to this question (or even the question itself) is C# specific necessarily. Consider the question "Where should I declare variable X" The answer is almost always "In the narrowest scope possible that's accessible every place that needs to use variable X"
In your case, the answer may be "At the class level"
Alternatively, if you were to program in a more functional style the answer may be "Reconsider the structure of the program so that X can be passed as a parameter to the functions that need it". Most C# event handler have a place where you can stick a "user state" object so that it can be passed along from event source to event handler.
The answer would be the same in C, C++, java, etc.
(Perhaps this should be a comment, but I'm afraid it's a bit long)

Detect Keypress using a timer

Code:
private void sprites_updater_Tick(object sender, EventArgs e)
{
s++;
int x = player.Location.X;
int y = player.Location.Y;
if (s == 1)
if (ModifierKeys.HasFlag(Keys.A))
{
player.Location = new Point(x - 5, y);
}
s = 0;
sprites_updater.Start();
}
So while using timer code, I wrote the same thing above (ModifierKeys.HasFlag(Keys.A)) but it didn´t work. Why?!
BTW, is there any way to show a 3d camera perspective inside a WinForms Panel WITHOUT USING XNA, WPF or any other stuff (only .NET)?!
The best way to get keyboard strokes and processing them later is to catch the Keyboards events in the form using both KeyDown, KeyUp and flags:
bool isAPressed;
...
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch(e.KeyCode)
{
case Key.A:
isAPressed = true;
break;
case Key.XXXX:
...
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
switch(e.KeyCode)
{
case Key.A:
isAPressed = false;
break;
case Key.XXXX:
...
}
}
Then you can use this information in your timer :
private void sprites_updater_Tick(object sender, EventArgs e)
{
s++;
int x = player.Location.X;
int y = player.Location.Y;
if (s == 1)
if (isAPressed)
{
player.Location = new Point(x - 5, y);
}
s = 0;
sprites_updater.Start();
}
This is particularily interresting to handle player moves this way (arrows).

Categories