Thursday, March 14, 2019

[Fix] SerialPort.Open raises IOException with error 87 "The parameter is incorrect"

See my answer on StackOverflow.

In short: use SerialPortStream library and SerialPortStream.OpenDirect() method.

namespace Vurdalakov
{
    using System;
    using RJCP.IO.Ports;

    class Program
    {
        static void Main(String[] args)
        {
            using (var serialPort = new SerialPortStream("COM1"))
            {
                serialPort.OpenDirect();

                while (serialPort.IsOpen)
                {
                    var ch = (Char)serialPort.ReadChar();
                    Console.Write(ch);
                }
            }
        }
    }
}

Monday, January 28, 2019

C#: Handle unhandled exceptions

namespace Vurdalakov
{
    using System;
    using System.Windows.Forms;

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
            AppDomain.CurrentDomain.UnhandledException += (s, e) => HandleUnhandledException(e.ExceptionObject as Exception);

            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Application.Run(new MainForm());
            }
            catch (Exception ex)
            {
                HandleUnhandledException(ex);
            }

            Environment.Exit(0);
        }

        private static void HandleUnhandledException(Exception ex)
        {
            // Handle unhandled exception

            Application.Exit();
        }
    }
}

C#: Hide WinForms main window

Can be used for any Windows application.

namespace Vurdalakov
{
    using System;
    using System.Drawing;
    using System.Windows.Forms;

    public partial class MainForm : Form
    {
        public MainForm()
        {
            this.InitializeComponent();
        }

        private void MainForm_Load(Object sender, EventArgs e)
        {
            this.HideMainForm();
        }

        private void HideMainForm()
        {
            this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
            this.StartPosition = FormStartPosition.Manual;

            var x = 0;
            var y = 0;

            foreach (var screen in Screen.AllScreens)
            {
                var bounds = screen.Bounds;
                x = Math.Min(x, bounds.Left);
                y = Math.Min(y, bounds.Bottom);
            }

            this.Location = new Point(x - this.Width - 100, y - this.Height - 100);
        }
    }
}

C#: Allow only one instance of application using mutex

namespace Vurdalakov
{
    using System;
    using System.Security.AccessControl;
    using System.Security.Principal;
    using System.Threading;
    using System.Windows.Forms;

    static class Program
    {
        [STAThread]
        static void Main()
        {
            // Allow everyone to access mutex
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);

            using (var mutex = new Mutex(false, "ApplicationMutex", out Boolean createdNew, securitySettings))
            {
                var isMutextOwned = false;
                try
                {
                    try
                    {
                        isMutextOwned = mutex.WaitOne(500, false);
                        if (!createdNew || !isMutextOwned)
                        {
                            Tracer.Trace("Application is already running, exiting");
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        isMutextOwned = true;
                    }

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    Application.Run(new MainForm());
                }
                catch (Exception ex)
                {
                    // Handle unhandled exception here
                }
                finally
                {
                    if (isMutextOwned)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }
    }
}

Thursday, January 24, 2019

Get MATLAB version and license number from C# project



try
{
    var matlab = new MLApp.MLApp();

    matlab.Feval("version", 1, out var result2);
    var matlabVersion = (result2 as Object[])[0] as String;
    Console.WriteLine($"MATLAB version: '{matlabVersion}'");

    matlab.Feval("license", 1, out var result1);
    var matlabLicense = (result2 as Object[])[0] as String;
    Console.WriteLine($"MATLAB license: '{matlabLicense}'");
}
catch (Exception ex)
{
    Console.WriteLine("MATLAB is not installed");
}