C
C#5mo ago
Yavuz

Form app doesnt loading

Hi there,I tried to make a simple COM port interface with forms,altought there is no error it doesnt loading.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 System.IO.Ports; namespace COMv1 { public partial class Form1 : Form { private SerialPort port; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string[] ports = SerialPort.GetPortNames(); for (int i=0;i< ports.Length;i++) { listBox1.Items.Add(ports[i]); } label1.Text = "Select port"; this.Show(); while (listBox1.SelectedIndex == -1) { } port = new SerialPort(listBox1.GetItemText(listBox1.SelectedItem), 9600); port.Open(); if (port.IsOpen) { label1.ForeColor = Color.Green; } else { label1.ForeColor = Color.Red; } this.Show(); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { string veri = textBox1.Text; textBox1.Clear(); port.Write(veri); } private void textBox1_TextChanged(object sender, EventArgs e) { } } }
No description
9 Replies
Buddy
Buddy5mo ago
Don't use synchronous methods in the load event
Yavuz
YavuzOP5mo ago
Like while rgiht?
Buddy
Buddy5mo ago
You also have an infinite loop from what I can see Why are you calling this.Show() multiple times?
Yavuz
YavuzOP5mo ago
Because it will stuck in while and dont display things before it
Buddy
Buddy5mo ago
Remove the while loop, see if that solves anything. Actually, remove everything regarding COM connection in the load
Yavuz
YavuzOP5mo ago
yes,It fixed it thank you then,how can I wait util I select smetihnig from listbox?
Buddy
Buddy5mo ago
It shouldn't be there either way, prefer a button like "Connect" or something of that sort. if the code is blocking you could use threads and work your way from there. If you need to work with the GUI, you can use yourControl.Invoke(..) if the UI code isn't called from the UI Thread. https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.invoke?view=windowsdesktop-8.0
Yavuz
YavuzOP5mo ago
Thanks a lot,I will try it:catlove:
Buddy
Buddy5mo ago
However. Avoid relying on the UI to do everything, such as this line listBox1.GetItemText(listBox1.SelectedItem). Otherwise it may bring you pain in the future.
Want results from more Discord servers?
Add your server