Trying to code up a little serial port communications/control panel in C# with Visual Studio 2022. I'm making it up as a WindowsForm app using .Net Framework 4.8. When launching the code all the other aspects work fine (as far as I can test them without being able to choose and connect to a paired serial port). In the window it creates I'm able to navigate without a problem but the combo box that should have the serial ports listed in it instead remains blank. Debugging and monitoring the value of "ports" also has it responding with either "error CS0103: The name 'ports' does not exist in the current context" or just "null". Another similar program uses the same logic to obtain the ports created with the virtual port emulator software I am using and this works without a worry.
Early Relevant Code Blocks
public partial class Form1 : Form
{
string dataOUT;
string sendWith;
string dataIN;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
cBoxCOMPORT.Items.AddRange(ports);
btnOpen.Enabled = true;
btnClose.Enabled = false;
chBxDTR.Checked = false;
serialPort1.DtrEnable = false;
chBxRTS.Checked = false;
serialPort1.RtsEnable = false;
btnSendOut.Enabled = true;
sendWith = "Both";
toolStripComboBox1.Text = "Add to Old Data";
toolStripComboBox2.Text = "Both";
toolStripComboBox3.Text = "BOTTOM";
}
~additional non-relevant functions
}
I'm sure the ports are available as the previous code solution can still find them so I don't think it's a problem with drivers or my virtual comm ports and I've check them on HKEY_LOCAL_MACHINE and they are present. The old solution was made around a week ago so it might be using .NET Framework 4.7.2 instead of 4.8. Regardless I have just copied and adjusted snippets of relevant code across and remade the design layout. There are no compilation errors or warnings either and I am for sure including the "using System.IO.Ports;" line.
I was following a guide provided on YouTube (https://www.youtube.com/watch?v=I6uhMIFTF24) and it worked. I did however have to remake it on a fresh solution and for whatever reason now the same lines of code don't obtain any of the ports made available.
Any help or ideas would be appreciated. No clue where to look or what to fiddle with to get it to find them in this solution.
I think I've found the issue. The Form1 was not triggering the Form1_Load event when launching the program and creating the window Form1 is the main window in the [Design] tab and under its properties the 'Load' box option had no event tied to it. Changed that to be 'Form1_Load' and this now gets that block of code working so it's finding/displaying the COM Ports as well as all the other related set up. Not sure why this wasn't happening by default or if I missed a step creating it. Will add anything else that develops if a similar issue pops up but hopefully that's the end of that.
Related
The issue:
We have an application written in C# that uses UIAutomation to get the current text (either selected or the word behind the carret) in other applications (Word, OpenOffice, Notepad, etc.).
All is working great on Windows 10, even up to 21H2, last update check done today.
But we had several clients informing us that the application is closing abruptly on Windows 11.
After some debugging I've seen some System.AccessViolationException thrown when trying to use the TextPatternRange.GetText() method:
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
What we've tried so far:
Setting uiaccess=true in manifest and signing the app : as mentionned here https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/350ceab8-436b-4ef1-8512-3fee4b470c0a/problem-with-manifest-and-uiaccess-set-to-true?forum=windowsgeneraldevelopmentissues => no changes (app is in C:\Program Files\
In addition to the above, I did try to set the level to "requireAdministrator" in the manifest, no changes either
As I've seen that it may come from a bug in Windows 11 (https://forum.emclient.com/t/emclient-9-0-1317-0-up-to-9-0-1361-0-password-correction-crashes-the-app/79904), I tried to install the 22H2 Preview release, still no changes.
Reproductible example
In order to be able to isolate the issue (and check it was not something else in our app that was causing the exception) I quickly made the following test (based on : How to get selected text of currently focused window? validated answer)
private void btnRefresh_Click(object sender, RoutedEventArgs e)
{
var p = Process.GetProcessesByName("notepad").FirstOrDefault();
var root = AutomationElement.FromHandle(p.MainWindowHandle);
var documentControl = new
PropertyCondition(AutomationElement.ControlTypeProperty,
ControlType.Document);
var textPatternAvailable = new PropertyCondition(AutomationElement.IsTextPatternAvailableProperty, true);
var findControl = new AndCondition(documentControl, textPatternAvailable);
var targetDocument = root.FindFirst(TreeScope.Descendants, findControl);
var textPattern = targetDocument.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
string text = "";
foreach (var selection in textPattern.GetSelection())
{
text += selection.GetText(255);
Console.WriteLine($"Selection: \"{selection.GetText(255)}\"");
}
lblFocusedProcess.Content = p.ProcessName;
lblSelectedText.Content = text;
}
When pressing a button, this method is called and the results displayed in labels.
The method uses UIAutomation to get the notepad process and extract the selected text.
This works well in Windows 10 with latest update, crashes immediately on Windows 11 with the AccessViolationException.
On Windows 10 it works even without the uiaccess=true setting in the manifest.
Questions/Next steps
Do anyone know/has a clue about what can cause this?
Is Windows 11 way more regarding towards UIAutomation?
On my side I'll probably open an issue by Microsoft.
And one track we might follow is getting an EV and sign the app itself and the installer as it'll also enhance the installation process, removing the big red warnings. But as this is an app distributed for free we had not done it as it was working without it.
I'll also continue testing with the reproductible code and update this question should anything new appear.
I posted the same question on MSDN forums and got this answer:
https://learn.microsoft.com/en-us/answers/questions/915789/uiautomation-throws-accessviolationexception-on-wi.html
Using IUIautomation instead of System.Windows.Automation works on Windows 11.
So I'm marking this as solved but if anyone has another idea or knows what happens you're welcome to comment!
I've made a Bootloader implementation in a SAMD21J18A mcu, based on a
Atmel example. I can connect to the bootloader via USB CDC and it is recognized in windows as a COM port with the name: AT91 USB to Serial Converter, not showing any problems.
The COM-port works fine, I've made a working Windows Form C# program to download code to the bootloader. In the working program I've just manually set the PortName.
Now, I want to make the program more user friendly and want to make a ComboBoxto enable the user to pick the COM-port to use. Therefore I'm calling the GetPortNames function:
string[] Ports = null;
Ports = SerialPort.GetPortNames();
This works fine, as long as I don't plugin my bootloader.
If I attach eg. a FTDI device, it detects the device and adds it to the list, but if I attach the Bootloader("AT91 USB to Serial Converter"), then I get a System.StackOverflowException on the SerialPort.GetPortNames() function.
Does anyone know what is wrong with GetPortNames or the USB CDC driver?
Thanks for your help mjwills :-)
The complete program were too large to show here, so I decided to make a short program showing the problem. However, the new short program didn't have this problem. So, found out the problem didn't directly originate from the line refered to by visual studio.
Anyway, here's the function which created the problem:
// Update comport pull-down list:
private void UpdateComPortList()
{
string[] Ports = null;
Ports = SerialPort.GetPortNames();
int index = -1;
string ComPortName = null;
comboBoxComPort.Items.Clear();
do
{
index += 1;
comboBoxComPort.Items.Add(Ports[index]);
//if(Properties.Settings.Default.comPort == Ports[index]) comboBoxComPort.SelectedIndex = index;
}
while (!((Ports[index] == ComPortName) || (index == Ports.GetUpperBound(0))));
comboBoxComPort.Items.Add("update list...");
}
If I remove the line which I've now commented, the program works.
I think the problem is that, I try to select an item while at the same time adding items...
Can someone please tell me whey I am getting a black screen with no video, only sound?
private void screen1btnPlay_Click(object sender, EventArgs e)
{
ScreenOne playScreen1 = new ScreenOne();
playScreen1.PlayScreenOne();
}
... and the other form is like this:
public partial class ScreenOne : Form
{
public ScreenOne()
{
InitializeComponent();
}
public void PlayScreenOne()
{
axVLCPlugin21.playlist.add("file:///" + #"Filepath", null);
axVLCPlugin21.playlist.play();
}
}
Sound works fine, but no video. All the properties of the VLC are left to default, is there something I need to change when using this plugin across multiple forms? Anyone know what's wrong?
Update:: I rebuilt the program in WPF and I am having the same problem. When I have a button on the second form (same form as player) it works fine, as soon as I call it from the main form, sound only. ugh!
I dont know but i can give some solution suggestions,
Make sure the VLC program is installed as 32-bit. I dont know, I've solved a problem that way.
I think high probabilty your problem is based on about "C:\Program Files (x86)\VideoLAN\VLC\plugins" Check your plugins. maybe your audio_filter, audio_mixer, audio_output plugins are missing.
you can remove Vlc, then download and install last VLC 32 bit.
I think that will solve your problem. Dont forget AxAXVLC works with vlc plugins.
I figured out my problem on my own!
When I was creating this instance,
ScreenOne playScreen1 = new ScreenOne();
I was actually creating a redundant instance of what I was trying to do, I'm not sure if that's the right way to put it but I basically already had an instance of the second form and was making another separate instance of the form that was named differently.
I already had in my code to open the second form
Screen2 Screen2 = new Screen2();
private void openScreen2Button_Click(object sender, EventArgs e)
{
Screen2.Show();
}
Then later was doing this which is WRONG, I was adding playscreen1 when I should still have been using Screen2.
Screen2 playScreen1 = new Screen2();
playScreen1.PlayScreenOne();
So when I wanted to use the method to play the media player on the second form from the first one, I just needed to use the same instance of Screen2 that I had created to open the form to begin with instead of created a new instance for what method I wanted to use.
IDK if my explanation makes sense, or maybe its basics to most people (I'm a noob), but if anyone comes across this problem, message me and I'll try to help.
o7
Hopefully some of the experienced WPF developers have come across this issue before.
BACKGROUND: This information is probably not necessary to helping fixing the problem, but in case it is relevant.
My solution consists of three projects. A front-end GUI, a business logic service, and a printer service. The three projects have IPC via named pipes. The business logic hands the printing logic a label type and a pallet id.
The Problem: The printing logic then creates the label and prints it (by adding it to the print queue of a printer) As the title suggests this all works fine when I am debugging in visual studio. However when I deploy / install the services on my developer pc it is not working.
Update: It is not throwing an exception but I am only logging "About to send doc to printer" and not the line "Sent doc to printer" So it is hanging on the dw1.Write(fixedDoc); line
More Information: I am using .Net 4.0 in the printing project / visual studio 2013
public void printLabel(string labelType, string _palletID = null)
{
try
{
ILabelTemplate Label = createLabel(labelType, _palletID);
PrintDialog pd = new PrintDialog();
FixedDocument fixedDoc = new FixedDocument();
PageContent pageContent = new PageContent();
FixedPage fixedPage = getFixedPage();
fixedDoc.DocumentPaginator.PageSize = new System.Windows.Size(fixedPage.Width, fixedPage.Height);
IXamlTemplate vm = CreateViewModel(Label);
ILabelPrintDocument template = CreateTemplate(Label);
template.dockPanel.DataContext = vm;
template.dockPanel.Height = fixedPage.Height;
template.dockPanel.Width = fixedPage.Width;
template.dockPanel.UpdateLayout();
fixedPage.Children.Add(template.dockPanel);
((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
XpsDocumentWriter dw1 = PrintQueue.CreateXpsDocumentWriter(new System.Printing.PrintQueue(new System.Printing.PrintServer(), Label.PrinterName));
Library.WriteErrorLog("About to send doc to printer");
dw1.Write(fixedDoc);
Library.WriteErrorLog("Sent doc to printer");
}
catch (Exception ex)
{
Library.WriteErrorLog(ex);
}
SOLVED ... kind of
After several hours of trying different things and reading about this, I found that it was due to my application running as me when I'm debugging but as a LOCAL SYSTEM when I have it deployed. And a local system service does not have access to network resources such as printers. Despite learning this, I then started down the path of how to make a C# service print. Well after seeing many posts (too late in the game to be very helpful)
Like this and also this one I have learned that I was going down the wrong path.
The moral of the story is, if you're reading this post you're probably not at the level of "writing your own printing DLL using the Win32 API (in C/C++ for instance), then use it from your service with P/Invoke"
The solution that did work for me was instead of running this project as a service which was started via my GUI. I have instead turned it into a process which is still started and stopped via my GUI.
The code in question is
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\yourAppNameGoesHere.exe"))
{
Process.Start(AppDomain.CurrentDomain.BaseDirectory + "\\yourAppNameGoesHere.exe");
}
then when the GUI is closed I run the code
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\yourAppNameGoesHere.exe"))
{
Process[] myapps = Process.GetProcesses("yourAppNameGoesHere.exe");
foreach (Process _p in myapps)
{
_p.Kill();
}
}
C# VS 2005.
I have developed an application that run perfectly on my development machine when I install it. However, it doesn't run on any of the clients machines.
I have tested with VMWare with a fresh install of windows, and still the application doesn't run.
I have added logging to try and determine where the application is failing. My previous versions worked, and after a week of development I gave to the client and then experienced this problem.
I have entered logging at the start and end of the constructor and form_load event. The constructor runs ok. However, at the end of the constructor it doesn't run in the form_load event as I have a log statement that should print out.
When the application runs it displays for a few seconds in task manager then fails to load.
I think this could be a very difficult problem to solve. So if anyone has experienced this before or could point me in the right direction to solve this problem.
The code in the form load event.
private void CATDialer_Load(object sender, EventArgs e)
{
my_logger.Info("Start of form load event"); // Doesn't display this.
.
.
}
===== Edit static main ====
[STAThread]
static void Main()
{
Application.SetCompatibleTextRenderingDefault(false);
// Get the language and set this cultureUI in the statusdisplay that will
// change the language for the whole program.
string language = CATWinSIP.Properties.Settings.Default.Language;
if (language == "th-TH")
{
StatusDisplay.StatusDisplay status_display = new StatusDisplay.StatusDisplay(true);
}
else if(language == "en-GB")
{
StatusDisplay.StatusDisplay status_display = new StatusDisplay.StatusDisplay(false);
}
try
{
Application.Run(new CATDialer());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
=== Constructor ===
public CATDialer()
{
//Set the language for all the controls on the form.
//Has to be done before all components are initialized.
//If not Thai language then must be using English.
if (Settings.Default.Language == "th-TH")
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("th-TH");
}
else
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");
}
InitializeComponent();
this.statusDisplay1.BalanceStatus = CATWinSIP_MsgStrings.BalanceStatus;
this.statusDisplay1.RedialHistory = CATWinSIP_MsgStrings.RedialHistory;
this.statusDisplay1.LoginStatus = CATWinSIP_MsgStrings.LoginSuccessful;
// Enable logging
XmlConfigurator.Configure();
logger.Info("CATDialer Constructor(): XmlConfigurator.Configure() Loaded [ OK ]");
// MessageBox.Show("Balance Status: " + this.statusDisplay1.BalanceStatus);
//Short cut menu.
this.SetupShortCutMenu();
this.fill_properties();
logger.Debug("CATDialer Constructor(): Fill properties loaded [ OK ]");
}
--
Hello,
Thanks for all the advice.
I have problem with one of my class libraries I created that used a crypto stream.
I found the answer when I added this to my program.cs
The message box displayed the information for the failed assembly.
Thanks,
try
{
Application.Run(new CATDialer());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Have you checked on a different development machine? Are your systems running same version of the .net framework? Is the .net framework installed correctly on the remote system? Have you tested your application in a different environment?
edit: have you tried spamming your log? Wrap the entire thing in a try catch and see what you can capture. Sometimes I found using the messagebox useful for this kind of logging (MessageBox.Show())
You probably need to post a bit more detail about the type of exception that is being thrown to get the most help.
If all the obvious checks such as having the correct framework version pass, the next thing to fail can often be a missing assembly.
If this is the case you may want to troubleshoot assembly loading in your app.
The MS Assembly Binding Log Viewer (fuslogvw) is a valuable piece of kit for this task.
In this sort of scenario I frequently find .NET assembly binding log viewer (Fusion) very useful in finding out what is going on. With fusion you can see which assemblies are being loaded and where they are being loaded from. More importantly for you, it is possible to enable it so that fusion also displays the assemblies that fail to load and where .NET tried to load them from.
Check out the MSDN article on fusion if you think this might help.