Esempio n. 1
0
 public Users()
 {
     InitializeComponent();
     this.Icon    = IconExtractor.Extract("shell32.dll", 86, true);
     connStr      = Properties.Settings.Default.ConnectionUrl;
     label1.Image = IconExtractor.Extract("shell32.dll", 209, false).ToBitmap();
 }
Esempio n. 2
0
        private void CreateUI()
        {
            var fp = new FlowLayoutPanel();

            fp.SuspendLayout();
            SuspendLayout();

            foreach (var entry in config.Entries)
            {
                var button = new Button
                {
                    Text   = entry.Description,
                    Width  = config.ButtonWidth,
                    Height = config.ButtonHeight,
                    Tag    = entry.Name
                };
                button.Click += Button_Click;

                buttons.Add(button);
            }

            fp.Controls.AddRange(buttons.ToArray());
            fp.Dock = DockStyle.Fill;

            Icon     = IconExtractor.Extract("shell32.dll", 9, true);
            Location = Properties.Settings.Default.WindowLocation;
            Size     = Properties.Settings.Default.WindowSize;
            Controls.Add(fp);

            fp.ResumeLayout(false);
            ResumeLayout(false);
        }
Esempio n. 3
0
 public NewUser(int rowid)
 {
     InitializeComponent();
     id        = rowid;
     this.Icon = IconExtractor.Extract("shell32.dll", 95, true);
     //btnSave.Image = IconExtractor.Extract("shell32.dll", 301, true).ToBitmap();
     //btnImgAdd.Image = IconExtractor.Extract("shell32.dll", 45, false).ToBitmap();
     //btnImgClear.Image = IconExtractor.Extract("shell32.dll", 31, false).ToBitmap();
 }
Esempio n. 4
0
        public Msg(string strmsg, Int32 iconum)
        {
            //221 -OK
            //237 -Error

            InitializeComponent();
            this.Icon = IconExtractor.Extract("shell32.dll", 144, true);

            lblMsgText.Text  = msgtext = strmsg;
            lblMsgText.Image = IconExtractor.Extract("shell32.dll", iconum, true).ToBitmap();
            btnOK.Image      = IconExtractor.Extract("shell32.dll", 176, false).ToBitmap();
        }
        /// <summary>
        /// Extract an Icon form a given path
        /// </summary>
        /// <param name="path"></param>
        /// <param name="dataFlow"></param>
        /// <param name="largeIcon"></param>
        /// <returns></returns>
        public static System.Drawing.Icon ExtractIconFromPath(string path, DataFlow dataFlow, bool largeIcon)
        {
            System.Drawing.Icon ico;
            var key = $"{path}-${largeIcon}";

            if (IconCache.Contains(key))
            {
                return((System.Drawing.Icon)IconCache.Get(key));
            }
            try
            {
                if (path.EndsWith(".ico"))
                {
                    ico = System.Drawing.Icon.ExtractAssociatedIcon(path);
                }
                else
                {
                    var iconInfo  = path.Split(',');
                    var dllPath   = iconInfo[0];
                    var iconIndex = int.Parse(iconInfo[1]);
                    ico = IconExtractor.Extract(dllPath, iconIndex, largeIcon);
                }
            }
            catch (Exception e)
            {
                Log.Error(e, "Can't extract icon from {path}", path);
                switch (dataFlow)
                {
                case DataFlow.Capture:
                    return(DefaultMicrophone);

                case DataFlow.Render:
                    return(DefaultSpeakers);

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            IconCache.Add(key, ico, CacheItemPolicy);
            return(ico);
        }
        private ProfileToolStripMenuItem BuildMenuItem(Profile profile)
        {
            Image image = null;

            try
            {
                var appTrigger = profile.Triggers.FirstOrDefault(trigger => trigger.ApplicationPath != null);
                if (appTrigger != null)
                {
                    image = IconExtractor.Extract(appTrigger.ApplicationPath, 0, false).ToBitmap();
                }
            }
            catch (Exception)
            {
                // ignored
            }

            foreach (var wrapper in profile.Devices)
            {
                if (image != null)
                {
                    break;
                }

                try
                {
                    var device = AudioDeviceLister.PlaybackDevices.FirstOrDefault(info => info.Equals(wrapper.DeviceInfo));
                    image = device?.SmallIcon.ToBitmap();
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            image ??= Resources.profile_menu_icon;

            return(new ProfileToolStripMenuItem(profile, image, profileClicked => ProfileManager.SwitchAudio(profileClicked)));
        }
Esempio n. 7
0
        public void RefreshProfiles()
        {
            ListViewItem ProfileToListViewItem(Profile profile)
            {
                var listViewItem = new ListViewItem(profile.Name)
                {
                    Tag = profile
                };
                Icon           appIcon       = null;
                DeviceFullInfo recording     = null;
                DeviceFullInfo playback      = null;
                DeviceFullInfo communication = null;

                var applicationTrigger = profile.Triggers.FirstOrDefault(trig => trig.Type == TriggerFactory.Enum.Process);
                var hotkeyTrigger      = profile.Triggers.FirstOrDefault(trig => trig.Type == TriggerFactory.Enum.HotKey);

                if (applicationTrigger != null)
                {
                    try
                    {
                        appIcon = IconExtractor.Extract(applicationTrigger.ApplicationPath, 0, false);
                    }
                    catch
                    {
                        appIcon = Resources.program;
                    }
                }

                if (profile.Playback != null)
                {
                    playback = _audioDeviceLister.PlaybackDevices.FirstOrDefault(info =>
                                                                                 info.Equals(profile.Playback));
                }

                if (profile.Recording != null)
                {
                    recording = _audioDeviceLister.RecordingDevices.FirstOrDefault(info =>
                                                                                   info.Equals(profile.Recording));
                }

                if (profile.Communication != null)
                {
                    communication = _audioDeviceLister.PlaybackDevices.FirstOrDefault(info =>
                                                                                      info.Equals(profile.Communication));
                }

                listViewItem.SubItems.AddRange(new[]
                {
                    new ListViewItem.ListViewSubItem(listViewItem, applicationTrigger?.ApplicationPath.Split('\\').Last() ?? "")
                    {
                        Tag = appIcon
                    },
                    new ListViewItem.ListViewSubItem(listViewItem, hotkeyTrigger?.HotKey.ToString() ?? ""),
                    new ListViewItem.ListViewSubItem(listViewItem, playback?.NameClean ?? profile.Playback?.ToString() ?? "")
                    {
                        Tag = playback?.SmallIcon
                    },
                    new ListViewItem.ListViewSubItem(listViewItem,
                                                     recording?.NameClean ?? profile.Recording?.ToString() ?? "")
                    {
                        Tag = recording?.SmallIcon
                    },
                    new ListViewItem.ListViewSubItem(listViewItem,
                                                     communication?.NameClean ?? profile.Communication?.ToString() ?? "")
                    {
                        Tag = communication?.SmallIcon
                    },
                });

                return(listViewItem);
            }

            profilesListView.Items.Clear();

            foreach (var profile in AppModel.Instance.ProfileManager.Profiles)
            {
                var listViewItem = ProfileToListViewItem(profile);
                profilesListView.Items.Add(listViewItem);
            }

            if (AppModel.Instance.ProfileManager.Profiles.Count > 0)
            {
                foreach (ColumnHeader column in profilesListView.Columns)
                {
                    column.Width = -2;
                }
            }
        }
Esempio n. 8
0
 private void numericUpDown_ValueChanged(object sender, EventArgs e)
 {
     icon = Convert.ToInt32(numericUpDown.Value);
     Shell32IconsForm.ActiveForm.Icon = IconExtractor.Extract("shell32.dll", icon, true);
 }
        static int Main(string[] args)
        {
            #region Initialize Variables

            bool        escapemessage = true;
            bool        tooltip       = false;
            bool        wait          = false;
            int         timeout       = 10000;
            int         iconindex     = 277;
            string[]    searchpath    = Environment.GetEnvironmentVariable("PATH").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            string      iconfile      = "shell32.dll";
            string      iconext       = ".dll";
            Icon        systrayicon   = IconExtractor.Extract(iconfile, iconindex, true);
            ToolTipIcon tooltipicon   = ToolTipIcon.Info;
            string      message       = String.Empty;
            string      title         = String.Empty;

            #endregion Initialize Variables


            #region Parse Command Line

            if (args.Length == 0)
            {
                return(ShowHelp( ));
            }
            foreach (string arg in args)
            {
                if (arg == "/?")
                {
                    return(ShowHelp( ));
                }
                if (arg.ToUpper( ) == "/W")
                {
                    if (wait)
                    {
                        return(ShowHelp("Duplicate command line switch /W"));
                    }
                    wait = true;
                }
                else if (arg.ToUpper( ) == "/L")
                {
                    if (!escapemessage)
                    {
                        return(ShowHelp("Duplicate command line switch /NE"));
                    }
                    escapemessage = false;
                }
                else if (arg[0] == '/')
                {
                    if (arg.Length > 3 && arg[2] == ':')
                    {
                        switch (arg[1].ToString( ).ToUpper( ))
                        {
                        case "I":
                            if (tooltipicon != ToolTipIcon.Info)
                            {
                                return(ShowHelp("Duplicate command line switch /I"));
                            }
                            switch (arg.Substring(3).ToUpper( ))
                            {
                            case "ERROR":
                                tooltipicon = ToolTipIcon.Error;
                                break;

                            case "INFO":
                                tooltipicon = ToolTipIcon.Info;
                                break;

                            case "NONE":
                                tooltipicon = ToolTipIcon.None;
                                break;

                            case "WARNING":
                                tooltipicon = ToolTipIcon.Warning;
                                break;

                            default:
                                return(ShowHelp("Invalid tooltip icon type \"{0}\"", arg.Substring(3)));
                            }
                            break;

                        case "P":
                            if (iconfile.ToUpper( ) != "SHELL32.DLL")
                            {
                                return(ShowHelp("Duplicate command line switch /P"));
                            }
                            iconext = Path.GetExtension(arg.Substring(3)).ToLower( );
                            if (File.Exists(arg.Substring(3)))
                            {
                                iconfile = Path.GetFullPath(arg.Substring(3));
                            }
                            else if (iconext == ".dll" || iconext == ".exe")
                            {
                                foreach (string folder in searchpath)
                                {
                                    if (File.Exists(Path.Combine(folder, arg.Substring(3))))
                                    {
                                        iconfile = Path.Combine(folder, arg.Substring(3));
                                        break;
                                    }
                                }
                                if (!File.Exists(iconfile))
                                {
                                    return(ShowHelp("Invalid path to icon file or library \"{0}\"", arg.Substring(3)));
                                }
                            }
                            break;

                        case "S":
                            if (iconindex != 277)
                            {
                                return(ShowHelp("Duplicate command line switch /S"));
                            }
                            try
                            {
                                iconindex = Convert.ToInt32(arg.Substring(3));
                                if (iconindex < 0)
                                {
                                    return(ShowHelp("Invalid system tray icon index \"{0}\"", arg.Substring(3)));
                                }
                            }
                            catch (Exception)
                            {
                                return(ShowHelp("Invalid system tray icon argument \"{0}\"", arg));
                            }
                            break;

                        case "T":
                            if (String.IsNullOrWhiteSpace(title))
                            {
                                title = arg.Substring(3).Trim("\" \t".ToCharArray( ));
                            }
                            else
                            {
                                return(ShowHelp("Duplicate command line switch /T"));
                            }
                            break;

                        case "V":
                            if (timeout != 10000)
                            {
                                return(ShowHelp("Duplicate command line switch /V"));
                            }
                            try
                            {
                                timeout = 1000 * Convert.ToInt32(arg.Substring(3));
                                if (timeout < 1000)
                                {
                                    return(ShowHelp("Invalid time (\"{0}\"), must be greater than zero", arg.Substring(3)));
                                }
                            }
                            catch (Exception)
                            {
                                return(ShowHelp("Invalid time \"{0}\"", arg.Substring(3)));
                            }
                            break;

                        default:
                            return(ShowHelp("Invalid command line switch \"{0}\"", arg));
                        }
                    }
                    else
                    {
                        return(ShowHelp("Invalid command line switch \"{0}\"", arg));
                    }
                }
                else
                {
                    if (String.IsNullOrWhiteSpace(message))
                    {
                        message = arg;
                        tooltip = true;
                    }
                    else
                    {
                        return(ShowHelp("Duplicate message on command line"));
                    }
                }
            }

            if (String.IsNullOrWhiteSpace(message))
            {
                tooltip = false;
            }

            if (tooltip && escapemessage)
            {
                message = Regex.Replace(message, @"(?<!\\)\\n", "\n");
                message = Regex.Replace(message, @"(?<!\\)\\t", "\t");
                message = Regex.Replace(message, @"\\", @"\");
            }

            if (iconext == ".dll")
            {
                systrayicon = IconExtractor.Extract(iconfile, iconindex, true);
            }
            else
            {
                systrayicon = new Icon(iconfile);
            }

            #endregion Parse Command Line


            notifyicon         = new NotifyIcon( );
            notifyicon.Icon    = systrayicon;
            notifyicon.Visible = true;

            if (tooltip)
            {
                if (wait)
                {
                    // Wait for the icon/message to be clicked
                    notifyicon.BalloonTipClicked += (object sender, EventArgs e) => { rc = 2; };
                    notifyicon.BalloonTipClosed  += (object sender, EventArgs e) => { rc = 2; };
                }
                notifyicon.ShowBalloonTip(timeout, title, message, tooltipicon);
            }

            if (wait)
            {
                rc = 3;
                while (timeout > 0 && rc == 3)
                {
                    Thread.Sleep(1);
                    Application.DoEvents( );
                    timeout--;
                }
                notifyicon.Visible = false;
                notifyicon.Dispose( );
            }

            return(rc);
        }
Esempio n. 10
0
        private void ShowData()
        {
            client = new MyClient();
            ds     = new DataSet();

            ds.Tables.Add(client.GetTable("Select a.Id,a.SurName,a.Name,a.UserName,a.Address,a.PhoneNumber,b.Name As OfficeName,a.Email,a.PasswordHash,a.RoleStr,a.Img,a.CreatedDate,IIf(a.ClosedDate Is Null, 'Aktiv','Deaktiv') As ClosedDate,b.Id As OfficeId"
                                          + " From Users As a INNER JOIN Office As b  ON a.OfficeId = b.Id"));
            ds.Tables.Add(client.GetTable("Select Id,Name From Office"));

            dgvUsers.DataSource = null;
            dgvUsers.Columns.Clear();

            dgvUsers.DataSource   = ds.Tables[0].DefaultView;
            cmbShow.SelectedIndex = 0;
            cmbShow_SelectedIndexChanged(null, null);

            dgvUsers.Columns[0].HeaderText  = "Kodu";
            dgvUsers.Columns[1].HeaderText  = "Soyadı";
            dgvUsers.Columns[2].HeaderText  = "Adı";
            dgvUsers.Columns[3].HeaderText  = "Giriş adı";
            dgvUsers.Columns[4].HeaderText  = "Ünvanı";
            dgvUsers.Columns[5].HeaderText  = "Telefonu";
            dgvUsers.Columns[6].HeaderText  = "Ofis";
            dgvUsers.Columns[7].HeaderText  = "E-poçt";
            dgvUsers.Columns[8].HeaderText  = "Şifrə";
            dgvUsers.Columns[9].HeaderText  = "Yetkisi";
            dgvUsers.Columns[10].HeaderText = "Foto";
            dgvUsers.Columns[11].HeaderText = "Daxil olma tarixi";
            dgvUsers.Columns[12].HeaderText = "Status";


            DataGridViewButtonColumn col = new DataGridViewButtonColumn();

            col.HeaderText                  = "Ümumi";
            col.Name                        = "column14";
            col.Width                       = 40;
            col.Text                        = "...";
            col.DefaultCellStyle.Font       = new System.Drawing.Font("Palatino Linotype", 7.5F, FontStyle.Bold);
            col.FlatStyle                   = FlatStyle.System;
            col.UseColumnTextForButtonValue = true;
            dgvUsers.Columns.Insert(14, col);
            dgvUsers.Columns[14].Width = 40;
            dgvUsers.Columns[12].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvUsers.Columns[12].Width = 60;

            for (int i = 0; i < dgvUsers.Columns.Count; i++)
            {
                if (dgvUsers.Columns[i] is DataGridViewImageColumn)
                {
                    ((DataGridViewImageColumn)dgvUsers.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Zoom;
                    break;
                }
            }

            dgvUsers.Columns[10].Width   = 60;
            dgvUsers.Columns[8].Width    = 50;
            dgvUsers.Columns[0].Width    = 40;
            dgvUsers.Columns[13].Visible = false;

            label2.Image = IconExtractor.Extract("shell32.dll", 209, true).ToBitmap();
        }
        static int Main(string[] args)
        {
            #region Initialize Variables

            const int defaultheight = 90;
            const int defaultwidth  = 200;

            char          delimiter           = ';';
            List <string> namedargs           = new List <string>( );
            List <string> unnamedargs         = new List <string>( );
            string        file                = String.Empty;
            string        list                = String.Empty;
            string        cancelcaption       = "&Cancel";
            string        okcaption           = "&OK";
            string        localizationstring  = String.Empty;
            string        prompt              = String.Empty;
            string        selectedText        = String.Empty;
            string        title               = String.Format("DropDownBox,  Version {0}", progver);
            bool          delimiterset        = false;
            bool          heightset           = false;
            bool          iconset             = false;
            bool          indexset            = false;
            bool          localizedcaptionset = false;
            bool          monospaced          = false;
            bool          skipfirstitem       = false;
            bool          sortlist            = false;
            bool          tablengthset        = false;
            bool          topmost             = true;
            bool          widthset            = false;
            int           height              = defaultheight;
            int           icon                = 23;
            int           selectedindex       = 0;
            int           tablength           = 4;
            int           width               = defaultwidth;

            bool isredirected = Console.IsInputRedirected;             // Requires .NET Framework 4.5
            bool listset      = isredirected;
            int  redirectnum  = (isredirected ? 1 : 0);
            int  arguments    = args.Length + redirectnum;

            #endregion Initialize Variables


            #region Command Line Parsing

            if (arguments == 0)
            {
                return(ShowHelp( ));
            }

            if (arguments > 13)
            {
                return(ShowHelp("Too many command line arguments"));
            }

            // Split up named and unnamed arguments
            foreach (string arg in args)
            {
                if (arg == "/?")
                {
                    return(ShowHelp( ));
                }
                if (arg[0] == '/')
                {
                    namedargs.Add(arg);
                }
                else
                {
                    unnamedargs.Add(arg);
                }
            }

            // Read Standard Input if the list is redirected
            if (isredirected)
            {
                try
                {
                    string delim = delimiter.ToString( );
                    list = String.Join(delim, Console.In.ReadToEnd( ).Split("\n\r".ToCharArray( ), StringSplitOptions.RemoveEmptyEntries));
                    // Trim list items, remove empty ones
                    string pattern = "\\s*" + delim + "+\\s*";
                    list = Regex.Replace(list, pattern, delim);
                }
                catch (Exception e)
                {
                    return(ShowHelp(e.Message));
                }
            }

            // First, validate the named arguments
            #region Named Arguments

            foreach (string arg in namedargs)
            {
                if (arg.Length < 3 && arg.ToUpper( ) != "/K" && arg.ToUpper( ) != "/L" && arg.ToUpper( ) != "/S")
                {
                    return(ShowHelp("Invalid command line switch {0} or missing value", arg));
                }
                if (arg.ToUpper( ) == "/K")
                {
                    if (skipfirstitem)
                    {
                        return(ShowHelp("Duplicate command line switch /K"));
                    }
                    skipfirstitem = true;
                }
                else if (arg.ToUpper( ) == "/L")
                {
                    if (localizedcaptionset)
                    {
                        return(ShowHelp("Duplicate command line switch /L"));
                    }
                    localizedcaptionset = true;
                }
                else if (arg.ToUpper( ) == "/S")
                {
                    if (sortlist)
                    {
                        return(ShowHelp("Duplicate command line switch /S"));
                    }
                    sortlist = true;
                }
                else
                {
                    switch (arg.Substring(0, 3).ToUpper( ))
                    {
                    case "/C:":
                        if (iconset)
                        {
                            return(ShowHelp("Duplicate command line switch /D"));
                        }
                        try
                        {
                            icon = Convert.ToInt32(arg.Substring(3));
                        }
                        catch (Exception)
                        {
                            return(ShowHelp("Invalid icon index: {0}", arg.Substring(3)));
                        }
                        iconset = true;
                        break;

                    case "/D:":
                        if (delimiterset)
                        {
                            return(ShowHelp("Duplicate command line switch /D"));
                        }
                        string test = arg.Substring(3);
                        if (test.Length == 1)
                        {
                            delimiter = test[0];
                        }
                        else if (test.Length == 3 && ((test[0] == '"' && test[2] == '"') || (test[0] == '\'' && test[2] == '\'')))
                        {
                            delimiter = test[1];
                        }
                        else
                        {
                            return(ShowHelp(String.Format("Invalid delimiter specified \"{0}\"", arg)));
                        }
                        break;

                    case "/F:":
                        if (listset)
                        {
                            return(ShowHelp("Duplicate command line switch /F"));
                        }
                        file = arg.Substring(3);
                        if (String.IsNullOrEmpty(file) || !File.Exists(file))
                        {
                            return(ShowHelp("List file not found: \"{0}\"", file));
                        }
                        else
                        {
                            try
                            {
                                string delim = delimiter.ToString( );
                                list = String.Join(delim, File.ReadLines(file));
                                string pattern = delim + "{2,}";
                                // Remove empty list items
                                Regex.Replace(list, pattern, delim);
                            }
                            catch (Exception e)
                            {
                                return(ShowHelp(e.Message));
                            }
                        }
                        listset = true;
                        break;

                    case "/H:":
                        if (heightset)
                        {
                            return(ShowHelp("Duplicate command line switch /H"));
                        }
                        try
                        {
                            height = Convert.ToInt32(arg.Substring(3));
                            if (height < defaultheight || height > Screen.PrimaryScreen.Bounds.Height)
                            {
                                return(ShowHelp(String.Format("Height {0} outside allowed range of {1}..{2}", arg.Substring(3), defaultheight, Screen.PrimaryScreen.Bounds.Height)));
                            }
                        }
                        catch (Exception e)
                        {
                            return(ShowHelp(String.Format("Invalid height \"{0}\": {1}", arg.Substring(3), e.Message)));
                        }
                        heightset = true;
                        break;

                    case "/I:":
                        if (indexset)
                        {
                            return(ShowHelp("Duplicate command line switch /I"));
                        }
                        try
                        {
                            selectedindex = Convert.ToInt32(arg.Substring(3));
                        }
                        catch (Exception e)
                        {
                            return(ShowHelp(String.Format("Invalid index value \"{0}\": {1}", arg, e.Message)));
                        }
                        break;

                    case "/L:":
                        if (localizedcaptionset)
                        {
                            return(ShowHelp("Duplicate command line switch /L"));
                        }
                        localizedcaptionset = true;
                        localizationstring  = arg.Substring(3);
                        string localizationpattern = "(;|^)(OK|Cancel)=[^\\\"';]+(;|$)";
                        foreach (string substring in localizationstring.Split(";".ToCharArray( ), StringSplitOptions.RemoveEmptyEntries))
                        {
                            if (!Regex.IsMatch(substring, localizationpattern, RegexOptions.IgnoreCase))
                            {
                                return(ShowHelp("Invalid value for /L switch: \"{1}\"", localizationstring));
                            }
                        }
                        break;

                    case "/MF":
                        if (monospaced)
                        {
                            return(ShowHelp("Duplicate command line switch /MF"));
                        }
                        monospaced = true;
                        break;

                    case "/NM":
                        if (!topmost)
                        {
                            return(ShowHelp("Duplicate command line switch /NM"));
                        }
                        topmost = false;
                        break;

                    case "/R0":
                    case "/RO":
                        if (returnindex0 || returnindex1)
                        {
                            return(ShowHelp("Duplicate command line switch /R0, /R1, /RI and/or /RO"));
                        }
                        returnindex0 = true;
                        break;

                    case "/R1":
                    case "/RI":
                        if (returnindex0 || returnindex1)
                        {
                            return(ShowHelp("Duplicate command line switch /R0, /R1, /RI and/or /RO"));
                        }
                        returnindex1 = true;
                        break;

                    case "/T:":
                        if (tablengthset)
                        {
                            return(ShowHelp("Duplicate command line switch /T"));
                        }
                        try
                        {
                            tablength = Convert.ToInt32(arg.Substring(3));
                            if (tablength < 4 || tablength > 16)
                            {
                                return(ShowHelp(String.Format("Tab length {0} outside allowed range of {1}..{2}", arg.Substring(3), 4, 16)));
                            }
                        }
                        catch (Exception e)
                        {
                            return(ShowHelp(String.Format("Invalid tab length \"{0}\": {1}", arg.Substring(3), e.Message)));
                        }
                        tablengthset = true;
                        break;

                    case "/W:":
                        if (widthset)
                        {
                            return(ShowHelp("Duplicate command line switch /W"));
                        }
                        try
                        {
                            width = Convert.ToInt32(arg.Substring(3));
                            if (width < defaultwidth || width > Screen.PrimaryScreen.Bounds.Width)
                            {
                                return(ShowHelp(String.Format("Width {0} outside allowed range of {1}..{2}", arg.Substring(3), defaultwidth, Screen.PrimaryScreen.Bounds.Width)));
                            }
                        }
                        catch (Exception e)
                        {
                            return(ShowHelp(String.Format("Invalid width \"{0}\": {1}", arg.Substring(3), e.Message)));
                        }
                        widthset = true;
                        break;

                    default:
                        return(ShowHelp(String.Format("Invalid command line switch \"{0}\"", arg)));
                    }
                }
            }

            #endregion Named Arguments


            // Next, validate unnamed arguments
            #region Unnamed Arguments

            if (listset)               // This check is the reason why named arguments had to be validated before unnamed ones: /F switch changes the meaning of unnamed arguments
            {
                switch (unnamedargs.Count)
                {
                case 0:
                    break;

                case 1:
                    prompt = unnamedargs[0];
                    break;

                case 2:
                    prompt = unnamedargs[0];
                    title  = unnamedargs[1];
                    break;

                case 3:
                    return(ShowHelp("Invalid command line argument: {0}", unnamedargs[2]));

                default:
                    unnamedargs.RemoveRange(0, 2);
                    return(ShowHelp("Invalid command line arguments: {0}", String.Join(", ", unnamedargs)));
                }
            }
            else
            {
                switch (unnamedargs.Count)
                {
                case 0:
                    break;

                case 1:
                    list    = unnamedargs[0];
                    listset = true;
                    break;

                case 2:
                    list    = unnamedargs[0];
                    prompt  = unnamedargs[1];
                    listset = true;
                    break;

                case 3:
                    list    = unnamedargs[0];
                    prompt  = unnamedargs[1];
                    title   = unnamedargs[2];
                    listset = true;
                    break;

                case 4:
                    return(ShowHelp("Invalid command line argument: {0}", unnamedargs[3]));

                default:
                    unnamedargs.RemoveRange(0, 3);
                    return(ShowHelp("Invalid command line arguments: {0}", String.Join(", ", unnamedargs)));
                }
            }

            #endregion Unnamed Arguments


            // List is mandatory
            if (!listset)
            {
                return(ShowHelp("No list specified"));
            }

            // Validate selected index
            int listrange = list.Split(delimiter).Length - 1;
            if (selectedindex < 0 || selectedindex > listrange)
            {
                return(ShowHelp(String.Format("Selected index ({0}) outside list range (0..{0})", selectedindex, listrange)));
            }

            #endregion Command Line Parsing


            #region Set Localized Captions

            if (localizedcaptionset)
            {
                cancelcaption = Load("user32.dll", 801, cancelcaption);
                okcaption     = Load("user32.dll", 800, okcaption);

                if (!String.IsNullOrWhiteSpace(localizationstring))
                {
                    string[] locstrings = localizationstring.Split(";".ToCharArray( ));
                    foreach (string locstring in locstrings)
                    {
                        string key = locstring.Substring(0, locstring.IndexOf('='));
                        string val = locstring.Substring(Math.Min(locstring.IndexOf('=') + 1, locstring.Length - 1));
                        if (!String.IsNullOrWhiteSpace(val))
                        {
                            switch (key.ToUpper( ))
                            {
                            case "OK":
                                okcaption = val;
                                break;

                            case "CANCEL":
                                cancelcaption = val;
                                break;

                            default:
                                return(ShowHelp("Invalid localization key \"{0}\"", key));
                            }
                        }
                    }
                }
            }

            #endregion Set Localized Captions


            #region Build Form

            // Inspired by code by Gorkem Gencay on StackOverflow.com:
            // http://stackoverflow.com/questions/97097/what-is-the-c-sharp-version-of-vb-nets-inputdialog#17546909

            Form dropdownForm = new Form( );
            Size size         = new Size(width, height);
            dropdownForm.FormBorderStyle = FormBorderStyle.FixedDialog;
            dropdownForm.MaximizeBox     = false;
            dropdownForm.MinimizeBox     = false;
            dropdownForm.StartPosition   = FormStartPosition.CenterParent;
            dropdownForm.ClientSize      = size;
            dropdownForm.Text            = title;
            dropdownForm.Icon            = IconExtractor.Extract("shell32.dll", icon, true);

            if (!String.IsNullOrWhiteSpace(prompt))
            {
                Label labelPrompt = new Label( );
                labelPrompt.Size     = new Size(size.Width - 20, 20);
                labelPrompt.Location = new Point(10, 10);
                // Replace tabs with spaces
                if (prompt.IndexOf("\\t", StringComparison.Ordinal) > -1)
                {
                    string tab = new String(' ', tablength);
                    // First split the prompt on newlines
                    string[] prompt2 = prompt.Split(new string[] { "\\n" }, StringSplitOptions.None);
                    for (int i = 0; i < prompt2.Length; i++)
                    {
                        if (prompt2[i].IndexOf("\\t", StringComparison.Ordinal) > -1)
                        {
                            // Slit each "sub-line" of the prompt on tabs
                            string[] prompt3 = prompt2[i].Split(new string[] { "\\t" }, StringSplitOptions.None);
                            // Each substring before a tab gets n spaces attached, and then is cut off at the highest possible length which is a multiple of n
                            for (int j = 0; j < prompt3.Length - 1; j++)
                            {
                                prompt3[j] += tab;
                                int length = prompt3[j].Length;
                                length    /= tablength;
                                length    *= tablength;
                                prompt3[j] = prompt3[j].Substring(0, length);
                            }
                            prompt2[i] = String.Join("", prompt3);
                        }
                    }
                    prompt = String.Join("\n", prompt2);
                }
                labelPrompt.Text = prompt.Replace("\\n", "\n").Replace("\\r", "\r");
                if (!heightset)
                {
                    // Add 20 to window height to allow space for prompt
                    size = new Size(size.Width, size.Height + 20);
                    dropdownForm.ClientSize = size;
                }
                labelPrompt.Size = new Size(size.Width - 20, size.Height - 90);
                if (monospaced)
                {
                    labelPrompt.Font = new Font(FontFamily.GenericMonospace, labelPrompt.Font.Size);
                }
                dropdownForm.Controls.Add(labelPrompt);
            }

            ComboBox combobox;
            combobox                    = new ComboBox( );
            combobox.Size               = new Size(size.Width - 20, 25);
            combobox.Location           = new Point(10, size.Height - 70);
            combobox.AutoCompleteMode   = AutoCompleteMode.Append;
            combobox.AutoCompleteSource = AutoCompleteSource.ListItems;
            combobox.DropDownStyle      = ComboBoxStyle.DropDownList;
            dropdownForm.Controls.Add(combobox);

            Button okButton = new Button( );
            okButton.DialogResult = DialogResult.OK;
            okButton.Name         = "okButton";
            okButton.Size         = new Size(80, 25);
            okButton.Text         = okcaption;
            okButton.Location     = new Point(size.Width / 2 - 10 - 80, size.Height - 35);
            dropdownForm.Controls.Add(okButton);

            Button cancelButton = new Button( );
            cancelButton.DialogResult = DialogResult.Cancel;
            cancelButton.Name         = "cancelButton";
            cancelButton.Size         = new Size(80, 25);
            cancelButton.Text         = cancelcaption;
            cancelButton.Location     = new Point(size.Width / 2 + 10, size.Height - 35);
            dropdownForm.Controls.Add(cancelButton);

            dropdownForm.AcceptButton = okButton;              // OK on Enter
            dropdownForm.CancelButton = cancelButton;          // Cancel on Esc
            dropdownForm.Activate( );

            #endregion Build Form


            #region Populate List

            // Populate the dropdown list
            List <string> listitems = list.Split(delimiter).ToList <string>( );
            if (skipfirstitem)
            {
                listitems.RemoveAt(0);
            }
            if (sortlist)
            {
                listitems.Sort( );
            }
            foreach (string item in listitems)
            {
                combobox.Items.Add(item);
            }
            // Preselect an item
            combobox.SelectedIndex = selectedindex;

            #endregion Populate List


            dropdownForm.TopMost = topmost;
            DialogResult result = dropdownForm.ShowDialog( );
            if (result == DialogResult.OK)
            {
                selectedText = combobox.SelectedItem.ToString( );
                Console.WriteLine(selectedText);
                if (returnindex0)
                {
                    // With /RO: return code equals selected index for "OK", or -1 for (command line) errors or "Cancel".
                    return(combobox.SelectedIndex);
                }
                else if (returnindex1)
                {
                    // With /RI: return code equals selected index + 1 for "OK", or 0 for (command line) errors or "Cancel".
                    return(combobox.SelectedIndex + 1);
                }
                else
                {
                    // Default: return code 0 for "OK", 1 for (command line) errors, 2 for "Cancel".
                    return(0);
                }
            }
            else
            {
                // Cancelled
                if (returnindex0)
                {
                    // With /RO: return code equals selected index for "OK", or -1 for (command line) errors or "Cancel".
                    return(-1);
                }
                else if (returnindex1)
                {
                    // With /RI: return code equals selected index + 1 for "OK", or 0 for (command line) errors or "Cancel".
                    return(0);
                }
                else
                {
                    // Default: return code 0 for "OK", 1 for (command line) errors, 2 for "Cancel".
                    return(2);
                }
            }
        }
Esempio n. 12
0
        public void RefreshProfiles()
        {
            ListViewItem ProfileToListViewItem(ProfileSetting profile)
            {
                var listViewItem = new ListViewItem(profile.ProfileName)
                {
                    Tag = profile
                };
                Icon           appIcon   = null;
                DeviceFullInfo recording = null;
                DeviceFullInfo playback  = null;

                if (!string.IsNullOrEmpty(profile.ApplicationPath))
                {
                    try
                    {
                        appIcon = IconExtractor.Extract(profile.ApplicationPath, 0, false);
                    }
                    catch
                    {
                        appIcon = Resources.program;
                    }
                }

                if (profile.Playback != null)
                {
                    playback = _audioDeviceLister.PlaybackDevices.FirstOrDefault(info => info.Id == profile.Playback.Id);
                }

                if (profile.Recording != null)
                {
                    recording = _audioDeviceLister.RecordingDevices.FirstOrDefault(info => info.Id == profile.Recording.Id);
                }

                listViewItem.SubItems.AddRange(new[]
                {
                    new ListViewItem.ListViewSubItem(listViewItem, profile.ApplicationPath?.Split('\\').Last() ?? "")
                    {
                        Tag = appIcon
                    },
                    new ListViewItem.ListViewSubItem(listViewItem, profile.HotKey?.ToString() ?? ""),
                    new ListViewItem.ListViewSubItem(listViewItem, playback?.Name ?? profile.Playback?.ToString() ?? "")
                    {
                        Tag = playback?.SmallIcon
                    },
                    new ListViewItem.ListViewSubItem(listViewItem, recording?.Name ?? profile.Recording?.ToString() ?? "")
                    {
                        Tag = recording?.SmallIcon
                    },
                });
                return(listViewItem);
            }

            profilesListView.Items.Clear();

            foreach (var profile in AppModel.Instance.ProfileManager.Profiles)
            {
                var listViewItem = ProfileToListViewItem(profile);
                profilesListView.Items.Add(listViewItem);
            }

            if (AppModel.Instance.ProfileManager.Profiles.Count > 0)
            {
                foreach (ColumnHeader column in profilesListView.Columns)
                {
                    column.Width = -2;
                }
            }
        }
Esempio n. 13
0
 private void LoadImages()
 {
     configImageList.Images.Add(IconExtractor.Extract(4));
     configImageList.Images.Add(IconExtractor.Extract(70));
 }
Esempio n. 14
0
		static int Main( string[] args )
		{
			#region Initialize Variables

			char delimiter = ';';
			List<string> namedargs = new List<string>( );
			List<string> unnamedargs = new List<string>( );
			string file = String.Empty;
			string list = String.Empty;
			string cancelcaption = "&Cancel";
			string okcaption = "&OK";
			string localizationstring = String.Empty;
			string prompt = String.Empty;
			string selectedtext = String.Empty;
			string title = String.Format( "RadioButtonBox,  Version {0}", progver );
			bool deduplist = false;
			bool delimiterset = false;
			bool heightset = false;
			bool iconset = false;
			bool indexset = false;
			bool localizedcaptionset = false;
			bool monospaced = false;
			bool skipfirstitem = false;
			bool sortlist = false;
			bool tablengthset = false;
			bool topmost = true;
			bool widthset = false;
			double rbsafetyfactor = 1.05;
			int columns = 0;
			int defaultindex = 0;
			int icon = 23;
			int promptheight = 20;
			int rc = 0;
			int rows = 0;
			int tablength = 4;
			int windowheight = defaultwindowheight;
			int windowwidth = defaultwindowwidth;
			Label labelPrompt = new Label( );

			bool isredirected = Console.IsInputRedirected; // Requires .NET Framework 4.5
			bool listset = isredirected;
			int redirectnum = ( isredirected ? 1 : 0 );
			int arguments = args.Length + redirectnum;

			int[] borders = BorderDimensions( );
			borderX = borders[0];
			borderY = borders[1];
			maximumwindowheight = screenheight - borderY;
			maximumwindowwidth = screenwidth - borderX;

			#endregion Initialize Variables


			#region Command Line Parsing

			if ( arguments == 0 )
			{
				return ShowHelp( );
			}

			if ( arguments > 16 )
			{
				return ShowHelp( "Too many command line arguments" );
			}

			// Split up named and unnamed arguments
			foreach ( string arg in args )
			{
				if ( arg[0] == '/' )
				{
					namedargs.Add( arg );
				}
				else
				{
					unnamedargs.Add( arg );
				}
			}

			// Read Standard Input if the list is redirected
			if ( isredirected )
			{
				try
				{
					string delim = delimiter.ToString( );
					list = String.Join( delim, Console.In.ReadToEnd( ).Split( "\n\r".ToCharArray( ), StringSplitOptions.RemoveEmptyEntries ) );
					// Trim list items, remove empty ones
					string pattern = "\\s*" + delim + "+\\s*";
					list = Regex.Replace( list, pattern, delim );
				}
				catch ( Exception e )
				{
					return ShowHelp( e.Message );
				}
			}

			// First, validate the named arguments
			#region Named Arguments

			foreach ( string arg in namedargs )
			{
				if ( arg.Length > 1 && !arg.Contains( ":" ) && !arg.Contains( "=" ) )
				{
					#region Boolean Named Arguments

					string key = arg.ToUpper( );
					switch ( key )
					{
						case "/?":
						case "/HELP":
							return ShowHelp( );
						case "/??":
						case "/???":
						case "/A":
						case "/ALIAS":
						case "/ALIASES":
							return ShowAliases( );
						case "/DE":
						case "/DEDUP":
							if ( deduplist )
							{
								return ShowHelp( "Duplicate command line switch /DE" );
							}
							deduplist = true;
							break;
						case "/K":
						case "/SKIP":
						case "/SKIPFIRST":
						case "/SKIPFIRSTITEM":
							if ( skipfirstitem )
							{
								return ShowHelp( "Duplicate command line switch /K" );
							}
							skipfirstitem = true;
							break;
						case "/L":
						case "/LOCALIZED":
						case "/LOCALIZEDCAPTIONS":
							if ( localizedcaptionset )
							{
								return ShowHelp( "Duplicate command line switch /L" );
							}
							localizedcaptionset = true;
							break;
						case "/MF":
						case "/MONO":
						case "/MONOSPACED":
						case "/MONOSPACEDFONT":
							if ( monospaced )
							{
								return ShowHelp( "Duplicate command line switch /MF" );
							}
							monospaced = true;
							break;
						case "/NM":
						case "/NONMODAL":
						case "/NON-MODAL":
							if ( !topmost )
							{
								return ShowHelp( "Duplicate command line switch /NM" );
							}
							topmost = false;
							break;
						case "/RC0":
						case "/RETURN0BASEDINDEX":
							if ( returnindex0 || returnindex1 )
							{
								return ShowHelp( "Duplicate command line switch /RC0 and/or /RC1" );
							}
							returnindex0 = true;
							break;
						case "/RC1":
						case "/RETURN1BASEDINDEX":
							if ( returnindex0 || returnindex1 )
							{
								return ShowHelp( "Duplicate command line switch /RC0 and/or /RC1" );
							}
							returnindex1 = true;
							break;
						case "/S":
						case "/SORT":
						case "/SORTLIST":
							if ( sortlist )
							{
								return ShowHelp( "Duplicate command line switch /S" );
							}
							sortlist = true;
							break;
						default:
							return ShowHelp( "Invalid command line switch {0} or missing value", arg );
					}
					
					#endregion Boolean Named Arguments
				}
				else if ( arg.Length > 3 && ( arg.Contains( ":" ) || arg.Contains( "=" ) ) )
				{
					#region Key/Value Named Arguments

					string key = arg.ToUpper( ).Substring( 0, arg.IndexOfAny( ":=".ToCharArray( ) ) );
					string val = arg.Substring( arg.IndexOfAny( ":=".ToCharArray( ) ) + 1 );
					switch ( key )
					{
						case "/C":
						case "/COL":
						case "/COLS":
						case "/COLUMNS":
							if ( columns != 0 )
							{
								return ShowHelp( "Duplicate command line switch /C" );
							}
							try
							{
								columns = Convert.ToInt32( val );
								if ( columns < 0 )
								{
									return ShowHelp( "Columns must be a positive integer" );
								}
							}
							catch ( Exception )
							{
								return ShowHelp( "Invalid columns value \"{0}\"", arg );
							}
							break;
						case "/D":
						case "/DELIMITER":
							if ( delimiterset )
							{
								return ShowHelp( "Duplicate command line switch /D" );
							}
							if ( val.Length == 1 )
							{
								delimiter = val[0];
							}
							else if ( val.Length == 3 && ( ( val[0] == '"' && val[2] == '"' ) || ( val[0] == '\'' && val[2] == '\'' ) ) )
							{
								delimiter = val[1];
							}
							else
							{
								return ShowHelp( String.Format( "Invalid delimiter specified \"{0}\"", arg ) );
							}
							break;
						case "/F":
						case "/FILE":
							if ( listset )
							{
								return ShowHelp( "Duplicate command line switch /F" );
							}
							file = val;
							if ( String.IsNullOrEmpty( file ) || !File.Exists( file ) )
							{
								return ShowHelp( "List file not found: \"{0}\"", file );
							}
							else
							{
								try
								{
									string delim = delimiter.ToString( );
									list = String.Join( delim, File.ReadLines( file ) );
									string pattern = delim + "{2,}";
									// Remove empty list items
									Regex.Replace( list, pattern, delim );
								}
								catch ( Exception e )
								{
									return ShowHelp( e.Message );
								}
							}
							listset = true;
							break;
						case "/H":
						case "/HEIGHT":
							if ( heightset )
							{
								return ShowHelp( "Duplicate command line switch /H" );
							}
							try
							{
								windowheight = Convert.ToInt32( val );
								if ( windowheight < minimumwindowheight || windowheight > maximumwindowheight )
								{
									return ShowHelp( String.Format( "Height {0} outside allowed range of {1}..{2}", val, minimumwindowheight, maximumwindowheight ) );
								}
							}
							catch ( Exception e )
							{
								return ShowHelp( String.Format( "Invalid height \"{0}\": {1}", val, e.Message ) );
							}
							heightset = true;
							break;
						case "/I":
						case "/ICON":
							if ( iconset )
							{
								return ShowHelp( "Duplicate command line switch /I" );
							}
							try
							{
								icon = Convert.ToInt32( val );
							}
							catch ( Exception )
							{
								return ShowHelp( "Invalid icon index: {0}", val );
							}
							iconset = true;
							break;
						case "/L":
						case "/LOCALIZED":
						case "/LOCALIZEDCAPTIONS":
							if ( localizedcaptionset )
							{
								return ShowHelp( "Duplicate command line switch /L" );
							}
							localizedcaptionset = true;
							localizationstring = val;
							string localizationpattern = "(;|^)(OK|Cancel)=[^\\\"';]+(;|$)";
							foreach ( string substring in localizationstring.Split( ";".ToCharArray( ), StringSplitOptions.RemoveEmptyEntries ) )
							{
								if ( !Regex.IsMatch( substring, localizationpattern, RegexOptions.IgnoreCase ) )
								{
									return ShowHelp( "Invalid value for /L switch: \"{1}\"", localizationstring );
								}
							}
							break;
						case "/P":
						case "/DEFAULT":
						case "/DEFAULTINDEX":
						case "/PRE":
						case "/PRESELECTED":
						case "/PRESELECTEDINTEX":
							if ( indexset )
							{
								return ShowHelp( "Duplicate command line switch /P" );
							}
							try
							{
								defaultindex = Convert.ToInt32( val );
							}
							catch ( Exception e )
							{
								return ShowHelp( String.Format( "Invalid index value \"{0}\": {1}", arg, e.Message ) );
							}
							break;
						case "/R":
						case "/ROWS":
							if ( rows != 0 )
							{
								return ShowHelp( "Duplicate command line switch /R" );
							}
							try
							{
								rows = Convert.ToInt32( val );
								if ( rows < 0 )
								{
									return ShowHelp( "Rows must be a positive integer" );
								}
							}
							catch ( Exception )
							{
								return ShowHelp( "Invalid rows value \"{0}\"", arg );
							}
							break;
						case "/T:":
						case "/TAB":
						case "/TABLENGTH":
							if ( tablengthset )
							{
								return ShowHelp( "Duplicate command line switch /T" );
							}
							try
							{
								tablength = Convert.ToInt32( val );
								if ( tablength < 4 || tablength > 16 )
								{
									return ShowHelp( String.Format( "Tab length {0} outside allowed range of {1}..{2}", val, 4, 16 ) );
								}
							}
							catch ( Exception e )
							{
								return ShowHelp( String.Format( "Invalid tab length \"{0}\": {1}", val, e.Message ) );
							}
							tablengthset = true;
							break;
						case "/W":
						case "/WIDTH":
							if ( widthset )
							{
								return ShowHelp( "Duplicate command line switch /W" );
							}
							try
							{
								windowwidth = Convert.ToInt32( val );
								if ( windowwidth < minimumwindowwidth || windowwidth > maximumwindowwidth )
								{
									return ShowHelp( String.Format( "Width {0} outside allowed range of {1}..{2}", val, minimumwindowwidth, maximumwindowwidth ) );
								}
							}
							catch ( Exception e )
							{
								return ShowHelp( String.Format( "Invalid width \"{0}\": {1}", val, e.Message ) );
							}
							widthset = true;
							break;
						default:
							return ShowHelp( String.Format( "Invalid command line switch \"{0}\"", arg ) );
					}

					#endregion Key/Value Named Arguments

				}
			}

			#endregion Named Arguments


			// Next, validate unnamed arguments
			#region Unnamed Arguments

			if ( listset ) // This check is the reason why named arguments had to be validated before unnamed ones: /F switch changes the meaning of unnamed arguments
			{
				switch ( unnamedargs.Count )
				{
					case 0:
						break;
					case 1:
						prompt = unnamedargs[0];
						break;
					case 2:
						prompt = unnamedargs[0];
						title = unnamedargs[1];
						break;
					case 3:
						return ShowHelp( "Invalid command line argument: {0}", unnamedargs[2] );
					default:
						unnamedargs.RemoveRange( 0, 2 );
						return ShowHelp( "Invalid command line arguments: {0}", String.Join( ", ", unnamedargs ) );
				}
			}
			else
			{
				switch ( unnamedargs.Count )
				{
					case 0:
						break;
					case 1:
						list = unnamedargs[0];
						listset = true;
						break;
					case 2:
						list = unnamedargs[0];
						prompt = unnamedargs[1];
						listset = true;
						break;
					case 3:
						list = unnamedargs[0];
						prompt = unnamedargs[1];
						title = unnamedargs[2];
						listset = true;
						break;
					case 4:
						return ShowHelp( "Invalid command line argument: {0}", unnamedargs[3] );
					default:
						unnamedargs.RemoveRange( 0, 3 );
						return ShowHelp( "Invalid command line arguments: {0}", String.Join( ", ", unnamedargs ) );
				}
			}

			#endregion Unnamed Arguments


			#region Validate Specified Values and Combinations

			if ( !listset )
			{
				return ShowHelp( "Mandatory list not specified" );
			}

			if ( rows * columns != 0 )
			{
				return ShowHelp( "You may specify the number of either columns or rows, but not both" );
			}

			int listrange = list.Split( new char[] { delimiter }, StringSplitOptions.RemoveEmptyEntries ).Length - 1;
			if ( defaultindex < 0 || defaultindex > listrange )
			{
				return ShowHelp( String.Format( "Preselected index ({0}) outside list range (0..{1})", defaultindex, listrange ) );
			}

			#endregion Validate Specified Values and Combinations

			#endregion Command Line Parsing


			#region Set Localized Captions

			if ( localizedcaptionset )
			{
				cancelcaption = Load( "user32.dll", 801, cancelcaption );
				okcaption = Load( "user32.dll", 800, okcaption );

				if ( !String.IsNullOrWhiteSpace( localizationstring ) )
				{
					string[] locstrings = localizationstring.Split( ";".ToCharArray( ) );
					foreach ( string locstring in locstrings )
					{
						string key = locstring.Substring( 0, locstring.IndexOf( '=' ) );
						string val = locstring.Substring( Math.Min( locstring.IndexOf( '=' ) + 1, locstring.Length - 1 ) );
						if ( !String.IsNullOrWhiteSpace( val ) )
						{
							switch ( key.ToUpper( ) )
							{
								case "OK":
									okcaption = val;
									break;
								case "CANCEL":
									cancelcaption = val;
									break;
								default:
									return ShowHelp( "Invalid localization key \"{0}\"", key );
							}
						}
					}
				}
			}

			#endregion Set Localized Captions


			#region Parse List

			List<string> listitems = new List<string>( list.Split( delimiter.ToString( ).ToCharArray( ), StringSplitOptions.RemoveEmptyEntries ) );
			if ( skipfirstitem )
			{
				listitems.RemoveAt( 0 );
			}
			for ( int i = 0; i < listitems.Count; i++ )
			{
				listitems[i] = listitems[i].Trim( );
			}
			if ( deduplist )
			{
				List<string> deduped = new List<string>( );
				foreach ( string key in listitems )
				{
					if ( !deduped.Contains( key ) )
					{
						deduped.Add( key );
					}
				}
				listitems = deduped;
			}
			if ( sortlist )
			{
				listitems.Sort( StringComparer.OrdinalIgnoreCase );
			}

			#endregion Parse List


			#region Main Form

			Form radiobuttonform = new Form( );
			radiobuttonform.FormBorderStyle = FormBorderStyle.FixedDialog;
			radiobuttonform.MaximizeBox = false;
			radiobuttonform.MinimizeBox = false;
			radiobuttonform.StartPosition = FormStartPosition.CenterParent;
			radiobuttonform.Text = title;
			radiobuttonform.Icon = IconExtractor.Extract( "shell32.dll", icon, true );

			#endregion Main Form


			#region Initial Sizes

			int horizontalmargin = 10;
			int verticalmargin = 10;
			int promptwidth = 0;
			int rbtextheight = 0; // radiobutton text height
			int rbtextwidth = 0; // radiobutton text width
			int rbwidth = 15; // radiobutton width without text
			int buttonheight = 25;
			int buttonwidth = 80;

			#endregion Initial Sizes


			#region Prompt

			if ( String.IsNullOrWhiteSpace( prompt ) )
			{
				promptheight = -1 * verticalmargin;
			}
			else
			{
				if ( monospaced )
				{
					labelPrompt.Font = new Font( FontFamily.GenericMonospace, labelPrompt.Font.Size );
				}

				// Calculate required height for single prompt line
				promptheight = TextRenderer.MeasureText( "Test", labelPrompt.Font ).Height;

				// Replace tabs with spaces
				if ( prompt.IndexOf( "\\t", StringComparison.Ordinal ) > -1 )
				{
					string tab = new String( ' ', tablength );
					// First split the prompt on newlines
					string[] prompt2 = prompt.Split( new string[] { "\\n" }, StringSplitOptions.None );
					for ( int i = 0; i < prompt2.Length; i++ )
					{
						if ( prompt2[i].IndexOf( "\\t", StringComparison.Ordinal ) > -1 )
						{
							// Split each "sub-line" of the prompt on tabs
							string[] prompt3 = prompt2[i].Split( new string[] { "\\t" }, StringSplitOptions.None );
							// Each substring before a tab gets n spaces attached, and then is shortened to the greatest possible multiple of n
							for ( int j = 0; j < prompt3.Length - 1; j++ )
							{
								prompt3[j] += tab;
								int length = prompt3[j].Length;
								length /= tablength;
								length *= tablength;
								prompt3[j] = prompt3[j].Substring( 0, length );
							}
							prompt2[i] = String.Join( "", prompt3 );
						}
					}
					prompt = String.Join( "\n", prompt2 );
				}
				prompt = prompt.Replace( "\\n", "\n" ).Replace( "\\r", "\r" );
				labelPrompt.Text = prompt;
				string[] lines = prompt.Split( "\n".ToCharArray( ) );
				int promptlines = lines.Length;

				foreach ( string line in lines )
				{
					promptwidth = Math.Max( promptwidth, TextRenderer.MeasureText( line, labelPrompt.Font ).Width );
				}

				// Calculate required height for multiple line prompt
				promptheight = promptlines * promptheight;
			}

			#endregion Prompt


			#region Radio Buttons

			List<RadioButton> radiobuttons = new List<RadioButton>( );
			for ( int i = 0; i < listitems.Count; i++ )
			{
				RadioButton radiobutton = new RadioButton( );
				radiobutton.Text = listitems[i];
				radiobutton.Checked = ( defaultindex == i );
				rbtextwidth = Math.Max( rbtextwidth, Convert.ToInt32( TextRenderer.MeasureText( listitems[i], radiobutton.Font ).Width * rbsafetyfactor ) );
				rbtextheight = Math.Max( rbtextheight, Convert.ToInt32( TextRenderer.MeasureText( listitems[i], radiobutton.Font ).Height * rbsafetyfactor ) );
				radiobuttons.Add( radiobutton );
			}

			GroupBox rbgroup = new GroupBox( );

			#endregion Radio Buttons


			#region Buttons

			Button okButton = new Button( );
			okButton.DialogResult = DialogResult.OK;
			okButton.Name = "okButton";
			okButton.Text = okcaption;

			Button cancelButton = new Button( );
			cancelButton.DialogResult = DialogResult.Cancel;
			cancelButton.Name = "cancelButton";
			cancelButton.Text = cancelcaption;

			#endregion Buttons


			#region Calculate Window Layout

			if ( rows > 0 )
			{
				rows = Math.Min( rows, listitems.Count );
				columns = (int) Math.Floor( (decimal) ( listitems.Count + rows - 1 ) / rows );
			}
			else if ( columns > 0 )
			{
				columns = Math.Min( columns, listitems.Count );
				rows = (int) Math.Floor( (decimal) ( listitems.Count + columns - 1 ) / columns );
			}
			else
			{
				columns = 1;
				rows = listitems.Count;
			}

			int rbgroupwidth = 0;
			int rbgroupheight = 0;
			int rowheight = 0;
			int colwidth = 0;

			if ( widthset )
			{
				rbgroupwidth = windowwidth - 2 * horizontalmargin;
				colwidth = (int) Math.Floor( (decimal) ( rbgroupwidth - horizontalmargin - columns * ( rbwidth + horizontalmargin ) ) / columns );
			}
			else
			{
				colwidth = rbtextwidth + rbwidth;
				rbgroupwidth = Math.Max( minimumwindowwidth - 2 * horizontalmargin, columns * ( colwidth + horizontalmargin ) + 2 * horizontalmargin );
				windowwidth = Math.Max( minimumwindowwidth, rbgroupwidth + 2 * horizontalmargin );
			}

			if ( heightset )
			{
				rbgroupheight = windowheight - promptheight - buttonheight - 4 * verticalmargin;
				rowheight = (int) Math.Floor( (decimal) ( rbgroupheight - 2 * verticalmargin ) / rows );
			}
			else
			{
				rowheight = rbtextheight + verticalmargin;
				windowheight = Math.Max( minimumwindowheight, 6 * verticalmargin + promptheight + buttonheight + rows * rowheight );
				rbgroupheight = rows * rowheight + 2 * verticalmargin;
			}

			#endregion Calculate Window Layout


			#region Check Available Group Box Space

			if ( rbgroupheight / rows < rowheight || rbgroupwidth / columns < colwidth )
			{
				return ShowHelp( "Window size too small to display all radio buttons;\n\tincrease window size, reduce or remove prompt,\n\tand/or change number of rows and columns" );
			}

			#endregion Check Available Group Box Space


			#region Build Form

			Size windowsize = new Size( windowwidth, windowheight );
			radiobuttonform.ClientSize = windowsize;

			if ( !String.IsNullOrWhiteSpace( prompt ) )
			{
				labelPrompt.Size = new Size( windowwidth - 2 * horizontalmargin, promptheight );
				labelPrompt.Location = new Point( horizontalmargin, verticalmargin );
				radiobuttonform.Controls.Add( labelPrompt );
			}

			rbgroup.Size = new Size( rbgroupwidth, rbgroupheight );
			rbgroup.Location = new Point( horizontalmargin, promptheight + 2 * verticalmargin );

			foreach ( RadioButton radiobutton in radiobuttons )
			{
				rbgroup.Controls.Add( radiobutton );
			}
			radiobuttonform.Controls.Add( rbgroup );

			for ( int row = 0; row < rows; row++ )
			{
				for ( int column = 0; column < columns; column++ )
				{
					int index = row * columns + column;
					if ( index < radiobuttons.Count )
					{
						int x = Convert.ToInt32( horizontalmargin + column * ( colwidth + horizontalmargin ) );
						int y = Convert.ToInt32( verticalmargin + row * rowheight );
						radiobuttons[index].Size = new Size( colwidth + horizontalmargin, rowheight );
						radiobuttons[index].Location = new Point( x, y );
					}
				}
			}

			okButton.Size = new Size( buttonwidth, buttonheight );
			okButton.Location = new Point( windowwidth / 2 - horizontalmargin - buttonwidth, windowheight - buttonheight - verticalmargin );
			radiobuttonform.Controls.Add( okButton );

			cancelButton.Size = new Size( buttonwidth, buttonheight );
			cancelButton.Location = new Point( windowwidth / 2 + horizontalmargin, windowheight - buttonheight - verticalmargin );
			radiobuttonform.Controls.Add( cancelButton );

			radiobuttonform.AcceptButton = okButton;  // OK on Enter
			radiobuttonform.CancelButton = cancelButton; // Cancel on Esc

			#endregion Build Form


			#region Show Dialog

			radiobuttonform.TopMost = topmost;
			DialogResult result = radiobuttonform.ShowDialog( );
			if ( result == DialogResult.OK )
			{
				foreach ( RadioButton rb in rbgroup.Controls )
				{
					if ( rb.Checked )
					{
						selectedtext = rb.Text;
						defaultindex = listitems.IndexOf( selectedtext );
						break;
					}
				}

				// Display selected text
				Console.WriteLine( selectedtext );

				if ( returnindex0 )
				{
					// With /RO: return code equals selected index for "OK", or -1 for (command line) errors or "Cancel".
					rc = defaultindex;
				}
				else if ( returnindex1 )
				{
					// With /RI: return code equals selected index + 1 for "OK", or 0 for (command line) errors or "Cancel".
					rc = defaultindex + 1;
				}
				else
				{
					// Default: return code 0 for "OK", 1 for (command line) errors, 2 for "Cancel".
					rc = 0;
				}
			}
			else
			{
				// Cancelled
				if ( returnindex0 )
				{
					// With /RO: return code equals selected index for "OK", or -1 for (command line) errors or "Cancel".
					rc = -1;
				}
				else if ( returnindex1 )
				{
					// With /RI: return code equals selected index + 1 for "OK", or 0 for (command line) errors or "Cancel".
					rc = 0;
				}
				else
				{
					// Default: return code 0 for "OK", 1 for (command line) errors, 2 for "Cancel".
					rc = 2;
				}
			}

			#endregion Show Dialog


			return rc;
		}
Esempio n. 15
0
 public Role(int id)
 {
     InitializeComponent();
     ShowData(id);
     this.Icon = IconExtractor.Extract("shell32.dll", 43, true);
 }
 private void Save(FileSystemInfo fileSystemInfo)
 {
     iconByExtension[fileSystemInfo.Extension] = IconExtractor.Extract(fileSystemInfo.FullName);
 }
Esempio n. 17
0
        private void btnImgClear_Click(object sender, EventArgs e)
        {
            Image myImage = IconExtractor.Extract("shell32.dll", 281, true).ToBitmap();

            imgBox.Image = myImage;
        }