Click here to Skip to main content
15,884,966 members
Home / Discussions / C#
   

C#

 
AnswerRe: Password Regex Help Pin
Bohdan Stupak19-Apr-23 3:28
professionalBohdan Stupak19-Apr-23 3:28 
Questioncreate our own unit testing framework in C# Pin
Sakhalean26-Mar-23 18:32
Sakhalean26-Mar-23 18:32 
AnswerRe: create our own unit testing framework in C# Pin
OriginalGriff26-Mar-23 21:00
mveOriginalGriff26-Mar-23 21:00 
AnswerRe: create our own unit testing framework in C# Pin
jschell27-Mar-23 7:00
jschell27-Mar-23 7:00 
AnswerRe: create our own unit testing framework in C# Pin
Gerry Schmitz27-Mar-23 11:39
mveGerry Schmitz27-Mar-23 11:39 
GeneralRe: create our own unit testing framework in C# Pin
mtoha13-Apr-23 16:39
professionalmtoha13-Apr-23 16:39 
QuestionManagement of window coordinates and sizes for multiple screens of different resolutions Pin
temuco25-Mar-23 13:14
professionaltemuco25-Mar-23 13:14 
AnswerRe: Management of window coordinates and sizes for multiple screens of different resolutions Pin
OriginalGriff25-Mar-23 20:18
mveOriginalGriff25-Mar-23 20:18 
Hi René!
You are going to have to give more detail as to what exactly you need help with - I have three monitors here, all different resolutions (1920x1080, 1080x1920, and 1280x1024 @ 100%), plus my Surface Go 2 (1920x1280 @ 150%) which I can write / test apps on (plus gawd knows what once the software is released) and generally it's not a problem.

Why does you app need to "know where it is"? What is it doing that it needs this? What will it do with the info? What's the problem in finding out?

My apps generally "remember" where they were, and restore their position on that particular system:
C#
#region Event Handlers
#region Form
/// <summary>
/// Restore size and location (if the user doesn't
/// override it)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FrmMain_Load(object sender, EventArgs e)
    {
    if ((ModifierKeys & Keys.Shift) == 0)
        {
        this.LoadLocation();
        }
    }
/// <summary>
/// Save the size and location (if the user doesn't
/// override it)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
    if ((ModifierKeys & Keys.Shift) == 0)
        {
        this.SaveLocation();
        }
    }
Is part of my standard "new form" code, along with the support methods:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Data;
using System.Drawing;
using System.Diagnostics;

namespace OneOffJobs
    {
    /// <summary>
    /// Provides the storage related code
    /// </summary>
    public static class Storage
        {
        #region Constants
        /// <summary>
        /// Restore command, used as a parameter to ShowWindow
        /// </summary>
        private const int SW_RESTORE = 9;
        #endregion

        #region DLL Imports
        // Sets the window to be foreground
        [DllImport("User32")]
        private static extern int SetForegroundWindow(IntPtr hwnd);
        // Activate or minimize a window
        [DllImportAttribute("User32.DLL")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        #endregion

        #region Fields
        #region Internal
        #endregion

        #region Property bases
        #endregion
        #endregion

        #region Properties
        /// <summary>
        /// Get the Application Guid
        /// </summary>
        public static Guid AppGuid
            {
            get
                {
                Assembly asm = Assembly.GetEntryAssembly();
                object[] attr = (asm.GetCustomAttributes(typeof(GuidAttribute), true));
                return new Guid((attr[0] as GuidAttribute).Value);
                }
            }
        /// <summary>
        /// Get the current assembly Guid.
        /// <remarks>
        /// Note that the Assembly Guid is not necessarily the same as the
        /// Application Guid - if this code is in a DLL, the Assembly Guid
        /// will be the Guid for the DLL, not the active EXE file.
        /// </remarks>
        /// </summary>
        public static Guid AssemblyGuid
            {
            get
                {
                Assembly asm = Assembly.GetExecutingAssembly();
                object[] attr = (asm.GetCustomAttributes(typeof(GuidAttribute), true));
                return new Guid((attr[0] as GuidAttribute).Value);
                }
            }
        /// <summary>
        /// Get the current user data folder
        /// </summary>
        public static string UserDataFolder
            {
            get
                {
                Guid appGuid = AppGuid;
                string folderBase = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                string dir = string.Format(@"{0}\{1}\", folderBase, appGuid.ToString("B").ToUpper());
                return CheckDir(dir);
                }
            }
        /// <summary>
        /// Get the current user roaming data folder
        /// </summary>
        public static string UserRoamingDataFolder
            {
            get
                {
                Guid appGuid = AppGuid;
                string folderBase = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string dir = string.Format(@"{0}\{1}\", folderBase, appGuid.ToString("B").ToUpper());
                return CheckDir(dir);
                }
            }
        /// <summary>
        /// Get all users data folder
        /// </summary>
        public static string AllUsersDataFolder
            {
            get
                {
                Guid appGuid = AppGuid;
                string folderBase = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                string dir = string.Format(@"{0}\{1}\", folderBase, appGuid.ToString("B").ToUpper());
                return CheckDir(dir);
                }
            }
        /// <summary>
        /// Location to store control locations in.
        /// </summary>
        public static string LocationsStorageFile { get; private set; }
        #endregion

        #region Regular Expressions
        #endregion

        #region Enums
        #endregion

        #region Constructors
        /// <summary>
        /// Fill out the static properties
        /// </summary>
        static Storage()
            {
            LocationsStorageFile = UserDataFolder + "control.storage.locations";
            }
        #endregion

        #region Events
        #region Event Constructors
        #endregion

        #region Event Handlers
        #endregion
        #endregion

        #region Public Methods
        /// <summary>
        /// Save the control location
        /// (Because a Form is derived from Control, it works
        /// for them as well)
        /// </summary>
        /// <param name="control">Form to save location of</param>
        /// <param name="instance">Instance identifier (for use with multiple instances)</param>
        public static void SaveLocation(this Control control, string instance = null)
            {
            string controlName = control.GetType().Name;
            if (!File.Exists(LocationsStorageFile))
                {
                CreateBlankLocationFile();
                }
            if (!(control is Form f) || (f.Visible && f.WindowState == FormWindowState.Normal))
                {
                // For Forms, we don't want to save if hidden, or if maximized / minimized
                // If we did, it causes the form to be misplaced, or far too small to see.
                DataTable dt = ReadXML(LocationsStorageFile);
                if (dt.Columns.Count >= 6)
                    {
                    bool ignoreInstance = string.IsNullOrWhiteSpace(instance);
                    DataRow current = dt.NewRow();    // Assume new row or instance.
                    current["ControlName"] = controlName;
                    current["Instance"] = instance ?? "";
                    foreach (DataRow row in dt.Rows)
                        {
                        if (row["ControlName"] as string == controlName && (ignoreInstance || row["Instance"] as string == instance))
                            {
                            // Found it!
                            //current = row;
                            dt.Rows.Remove(row);
                            break;
                            }
                        }
                    current["LocationX"] = control.Location.X;
                    current["LocationY"] = control.Location.Y;
                    current["SizeW"] = control.Size.Width;
                    current["SizeH"] = control.Size.Height;
                    dt.Rows.Add(current);
                    WriteXML(dt, LocationsStorageFile);
                    }
                }
            }
        /// <summary>
        /// Load the Control location
        /// (Because a Form is derived from Control, it works
        /// for them as well)
        /// </summary>
        /// <param name="control">Form to load location of</param>
        /// <param name="instance">Instance identifier (for use with multiple instances)</param>
        public static void LoadLocation(this Control control, string instance = null)
            {
            string controlName = control.GetType().Name;
            if (!File.Exists(LocationsStorageFile))
                {
                CreateBlankLocationFile();
                }
            DataTable dt = ReadXML(LocationsStorageFile);
            if (dt.Columns.Count >= 6)
                {
                bool ignoreInstance = string.IsNullOrWhiteSpace(instance);
                DataRow current = dt.NewRow();    // Assume new row or instance.
                current["ControlName"] = controlName;
                current["Instance"] = instance ?? "";
                current["LocationX"] = control.Location.X;
                current["LocationY"] = control.Location.Y;
                current["SizeW"] = control.Size.Width;
                current["SizeH"] = control.Size.Height;
                foreach (DataRow row in dt.Rows)
                    {
                    if (row["ControlName"] as string == controlName && (ignoreInstance || row["Instance"] as string == instance))
                        {
                        // Found it!
                        current = row;
                        if (int.TryParse(current["LocationX"].ToString(), out int x) &&
                            int.TryParse(current["LocationY"].ToString(), out int y) &&
                            int.TryParse(current["SizeW"].ToString(), out int w) &&
                            int.TryParse(current["SizeH"].ToString(), out int h))
                            {
                            control.Location = new Point(x, y);
                            control.Size = new Size(w, h);
                            }
                        break;
                        }
                    }
                }
            }
        /// <summary>
        /// Ensures that just a single instance of an application is running.
        /// </summary>
        /// <remarks>
        /// Checks if this is the only executing example of this process.
        /// If it is, all well and good.
        /// Otherwise, switches the focus to the other instance, and 
        /// terminates this process.
        /// </remarks>
        /// <example>
        /// In program.cs:
        /// 
        /// [STAThread]
        /// static void Main()
        ///     {
        ///     Process.GetCurrentProcess().SingleInstance();
        ///     Application.EnableVisualStyles();
        ///     Application.SetCompatibleTextRenderingDefault(false);
        ///     Application.Run(new frmMain());
        ///     }
        /// </example>
        /// <param name="thisProcess"></param>
        public static void SingleInstance(this Process thisProcess)
            {
            foreach (Process proc in Process.GetProcessesByName(thisProcess.ProcessName))
                {
                if (proc.Id != thisProcess.Id)
                    {
                    ShowWindow(proc.MainWindowHandle, SW_RESTORE);
                    SetForegroundWindow(proc.MainWindowHandle);
                    thisProcess.Kill();
                    }
                }
            }
        #endregion

        #region Overrides
        #endregion

        #region Private Methods
        /// <summary>
        /// Check the specified folder, and create if it doesn't exist.
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        private static string CheckDir(string dir)
            {
            if (!Directory.Exists(dir))
                {
                Directory.CreateDirectory(dir);
                }
            return dir;
            }
        /// <summary>
        /// Read the data from the XML file
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private static DataTable ReadXML(string file)
            {
            using (DataSet ds = new DataSet())
                {
                ds.ReadXml(file);
                DataTable dt;
                if (ds.Tables.Count > 0)
                    {
                    // Can't leave it attached to the DataSet, even if the set is Disposed!
                    dt = ds.Tables[0];
                    ds.Tables.Remove(dt);
                    }
                else
                    {
                    dt = new DataTable("Empty");
                    }
                return dt;
                }
            }
        /// <summary>
        /// Write the data to the XML file
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file"></param>
        private static void WriteXML(DataTable dt, string file)
            {
            using (DataSet ds = new DataSet())
                {
                ds.Tables.Add(dt);
                ds.WriteXml(file);
                ds.Tables.Remove(dt);
                }
            }
        /// <summary>
        /// Create a blank file template
        /// </summary>
        private static void CreateBlankLocationFile()
            {
            DataTable dtNew = new DataTable("Locations");
            dtNew.Columns.Add("ControlName", typeof(string));
            dtNew.Columns.Add("Instance", typeof(string));
            dtNew.Columns.Add("LocationX", typeof(int));
            dtNew.Columns.Add("LocationY", typeof(int));
            dtNew.Columns.Add("SizeW", typeof(int));
            dtNew.Columns.Add("SizeH", typeof(int));
            DataRow dr = dtNew.NewRow();
            dr["ControlName"] = "%%SAMPLE%%";
            dr["Instance"] = "%%INSTANCE%%";
            dr["LocationX"] = 0;
            dr["LocationY"] = 0;
            dr["SizeW"] = 200;
            dr["SizeH"] = 200;
            dtNew.Rows.Add(dr);
            WriteXML(dtNew, LocationsStorageFile);
            }
        #endregion
        }
    }

"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!

GeneralRe: Management of window coordinates and sizes for multiple screens of different resolutions Pin
temuco26-Mar-23 1:22
professionaltemuco26-Mar-23 1:22 
GeneralRe: Management of window coordinates and sizes for multiple screens of different resolutions Pin
Dave Kreskowiak26-Mar-23 5:38
mveDave Kreskowiak26-Mar-23 5:38 
GeneralRe: Management of window coordinates and sizes for multiple screens of different resolutions Pin
temuco26-Mar-23 22:28
professionaltemuco26-Mar-23 22:28 
GeneralRe: Management of window coordinates and sizes for multiple screens of different resolutions Pin
Dave Kreskowiak27-Mar-23 1:30
mveDave Kreskowiak27-Mar-23 1:30 
GeneralRe: Management of window coordinates and sizes for multiple screens of different resolutions Pin
temuco27-Mar-23 21:18
professionaltemuco27-Mar-23 21:18 
GeneralRe: Management of window coordinates and sizes for multiple screens of different resolutions Pin
Gerry Schmitz26-Mar-23 7:57
mveGerry Schmitz26-Mar-23 7:57 
QuestionEntity Framework Code First - two Foreign Keys from same table Pin
Alex Dunlop21-Mar-23 8:43
Alex Dunlop21-Mar-23 8:43 
AnswerRe: Entity Framework Code First - two Foreign Keys from same table Pin
Gerry Schmitz21-Mar-23 9:30
mveGerry Schmitz21-Mar-23 9:30 
AnswerRe: Entity Framework Code First - two Foreign Keys from same table Pin
jschell23-Mar-23 6:04
jschell23-Mar-23 6:04 
AnswerRe: Entity Framework Code First - two Foreign Keys from same table Pin
Richard Deeming27-Mar-23 0:35
mveRichard Deeming27-Mar-23 0:35 
QuestionHow to highlight all rows in listbox between two index values? Pin
Member 1405587917-Mar-23 1:25
Member 1405587917-Mar-23 1:25 
AnswerRe: How to highlight all rows in listbox between two index values? Pin
Pete O'Hanlon17-Mar-23 1:33
mvePete O'Hanlon17-Mar-23 1:33 
AnswerRe: How to highlight all rows in listbox between two index values? Pin
RedDk17-Mar-23 6:26
RedDk17-Mar-23 6:26 
QuestionMessage Closed Pin
15-Mar-23 20:32
Sivanujan Sivaraja15-Mar-23 20:32 
AnswerRe: Serial port listening application Pin
OriginalGriff15-Mar-23 21:02
mveOriginalGriff15-Mar-23 21:02 
GeneralRe: Serial port listening application Pin
Richard MacCutchan15-Mar-23 22:34
mveRichard MacCutchan15-Mar-23 22:34 
GeneralRe: Serial port listening application Pin
OriginalGriff15-Mar-23 22:41
mveOriginalGriff15-Mar-23 22:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.