// <copyright file="SettingsForm.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace FSI.BT.Tools.Global.UserInterface
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.IO;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using Microsoft.Win32;
    using FSI.BT.Tools.SystemTrayMenu.Properties;
    using FSI.BT.Tools.Global.UserInterface.FolderBrowseDialog;
    using FSI.BT.Tools.SystemTrayMenu.Utilities;
    using Windows.ApplicationModel;
    using static FSI.BT.Tools.Global.UserInterface.HotkeyTextboxControl.HotkeyControl;
    using FSI.BT.Tools.SystemTrayMenu.UserInterface;
    using FSI.BT.Tools.Global.Utilities;

    public partial class SettingsForm : Form
    {
        private const string MenuName = @"Software\Classes\directory\shell\FSI.BT.Tools.SystemTrayMenu_SetAsRootFolder";
        private const string Command = @"Software\Classes\directory\shell\FSI.BT.Tools.SystemTrayMenu_SetAsRootFolder\command";

        private static readonly Icon SystemTrayMenu = Resources.SystemTrayMenu;
        private static SettingsForm settingsForm;
        private readonly ColorConverter colorConverter = new();
        private bool inHotkey;

        public SettingsForm()
        {
            InitializeComponent();
            Icon = SystemTrayMenu;

            // Initialize and replace here here, because designer always removes it
            InitializeTextBoxHotkeyAndReplacetextBoxHotkeyPlaceholder();
            void InitializeTextBoxHotkeyAndReplacetextBoxHotkeyPlaceholder()
            {
                textBoxHotkey = new Tools.Global.UserInterface.HotkeyTextboxControl.HotkeyControl
                {
                    Hotkey = Keys.None,
                    HotkeyModifiers = Keys.None,
                    Name = "textBoxHotkey",
                    Size = new Size(200, 20),
                    Text = "None",
                    TabStop = false,
                };
                textBoxHotkey.Enter += new EventHandler(TextBoxHotkeyEnter);
                textBoxHotkey.Leave += new EventHandler(TextBoxHotkey_Leave);
                tableLayoutPanelHotkey.Controls.Remove(textBoxHotkeyPlaceholder);
                tableLayoutPanelHotkey.Controls.Add(textBoxHotkey, 0, 0);
            }

            // designer always resets it to 1
            tabControl.SelectedIndex = 0;

            CombineControls(textBoxColorIcons, pictureBoxIcons);
            CombineControls(textBoxColorBackground, pictureBoxBackground);
            CombineControls(textBoxColorBackgroundBorder, pictureBoxBackgroundBorder);
            CombineControls(textBoxColorSearchField, pictureBoxSearchField);
            CombineControls(textBoxColorOpenFolder, pictureBoxOpenFolder);
            CombineControls(textBoxColorOpenFolderBorder, pictureBoxOpenFolderBorder);
            CombineControls(textBoxColorSelectedItem, pictureBoxSelectedItem);
            CombineControls(textBoxColorSelectedItemBorder, pictureBoxSelectedItemBorder);
            CombineControls(textBoxColorScrollbarBackground, pictureBoxScrollbarBackground);
            CombineControls(textBoxColorSlider, pictureBoxSlider);
            CombineControls(textBoxColorSliderDragging, pictureBoxSliderDragging);
            CombineControls(textBoxColorSliderHover, pictureBoxSliderHover);
            CombineControls(textBoxColorSliderArrowsAndTrackHover, pictureBoxSliderArrowsAndTrackHover);
            CombineControls(textBoxColorArrow, pictureBoxArrow);
            CombineControls(textBoxColorArrowClick, pictureBoxArrowClick);
            CombineControls(textBoxColorArrowClickBackground, pictureBoxArrowClickBackground);
            CombineControls(textBoxColorArrowHover, pictureBoxArrowHover);
            CombineControls(textBoxColorArrowHoverBackground, pictureBoxArrowHoverBackground);

            CombineControls(textBoxColorIconsDarkMode, pictureBoxIconsDarkMode);
            CombineControls(textBoxColorBackgroundDarkMode, pictureBoxBackgroundDarkMode);
            CombineControls(textBoxColorBackgroundBorderDarkMode, pictureBoxBackgroundBorderDarkMode);
            CombineControls(textBoxColorSearchFieldDarkMode, pictureBoxSearchFieldDarkMode);
            CombineControls(textBoxColorOpenFolderDarkMode, pictureBoxOpenFolderDarkMode);
            CombineControls(textBoxColorOpenFolderBorderDarkMode, pictureBoxOpenFolderBorderDarkMode);
            CombineControls(textBoxColorSelecetedItemDarkMode, pictureColorBoxSelectedItemDarkMode);
            CombineControls(textBoxColorSelectedItemBorderDarkMode, pictureBoxSelectedItemBorderDarkMode);
            CombineControls(textBoxColorScrollbarBackgroundDarkMode, pictureBoxScrollbarBackgroundDarkMode);
            CombineControls(textBoxColorSliderDarkMode, pictureBoxSliderDarkMode);
            CombineControls(textBoxColorSliderDraggingDarkMode, pictureBoxSliderDraggingDarkMode);
            CombineControls(textBoxColorSliderHoverDarkMode, pictureBoxSliderHoverDarkMode);
            CombineControls(textBoxColorSliderArrowsAndTrackHoverDarkMode, pictureBoxSliderArrowsAndTrackHoverDarkMode);
            CombineControls(textBoxColorArrowDarkMode, pictureBoxArrowDarkMode);
            CombineControls(textBoxColorArrowClickDarkMode, pictureBoxArrowClickDarkMode);
            CombineControls(textBoxColorArrowClickBackgroundDarkMode, pictureBoxArrowClickBackgroundDarkMode);
            CombineControls(textBoxColorArrowHoverDarkMode, pictureBoxArrowHoverDarkMode);
            CombineControls(textBoxColorArrowHoverBackgroundDarkMode, pictureBoxArrowHoverBackgroundDarkMode);
            void CombineControls(Control textBoxColor, Control pictureBox)
            {
                textBoxColor.Tag = pictureBox;
                pictureBox.Tag = textBoxColor;
            }

            Translate();
            void Translate()
            {
                Text = Global.Utilities.Translator.GetText("Settings");
                tabPageGeneral.Text = Global.Utilities.Translator.GetText("General");
                groupBoxFolder.Text = Global.Utilities.Translator.GetText("Directory");
                buttonChangeFolder.Text =Global.Utilities.Translator.GetText("Changing directory");
                buttonOpenFolder.Text = Global.Utilities.Translator.GetText("Open directory");
                checkBoxSetFolderByWindowsContextMenu.Text =Global.Utilities.Translator.GetText("Set by context menu ");
                groupBoxConfigAndLogfile.Text = Global.Utilities.Translator.GetText("Configuration and log files");
                buttonChangeRelativeFolder.Text = Global.Utilities.Translator.GetText("Relative directory");
                checkBoxSaveConfigInApplicationDirectory.Text = Global.Utilities.Translator.GetText("Save configuration file in application directory");
                checkBoxSaveLogFileInApplicationDirectory.Text = Global.Utilities.Translator.GetText("Saving log file in application directory");
                buttonOpenAssemblyLocation.Text = Global.Utilities.Translator.GetText("Open application directory");
                groupBoxAutostart.Text = Global.Utilities.Translator.GetText("App start");
                if (IsStartupTask())
                {
                    groupBoxAutostart.Text += $" ({Global.Utilities.Translator.GetText("Task Manager")})";
                }

                checkBoxAutostart.Text = Global.Utilities.Translator.GetText("Start with Windows");
                checkBoxCheckForUpdates.Text = Global.Utilities.Translator.GetText("Check for updates");
                buttonAddStartup.Text = Global.Utilities.Translator.GetText("Start with Windows");
                groupBoxHotkey.Text = Global.Utilities.Translator.GetText("Hotkey");
                buttonHotkeyDefault.Text = Global.Utilities.Translator.GetText("Default");
                groupBoxLanguage.Text = Global.Utilities.Translator.GetText("Language");
                buttonGeneralDefault.Text = Global.Utilities.Translator.GetText("Default");

                tabPageSizeAndLocation.Text = Global.Utilities.Translator.GetText("Size and location");
                groupBoxSize.Text = Global.Utilities.Translator.GetText("Sizes in percent");
                labelSizeInPercent.Text = Global.Utilities.Translator.GetText("Application size");
                labelIconSizeInPercent.Text = Global.Utilities.Translator.GetText("Icon size");
                labelRowHeightInPercentage.Text = Global.Utilities.Translator.GetText("Row height");
                labelMaxMenuWidth.Text = Global.Utilities.Translator.GetText("Maximum menu width");
                labelMaxMenuHeight.Text = Global.Utilities.Translator.GetText("Maximum menu height");
                groupBoxMenuAppearAt.Text = Global.Utilities.Translator.GetText("Main menu appears");
                radioButtonAppearAtTheBottomLeft.Text = Global.Utilities.Translator.GetText("Bottom left");
                radioButtonAppearAtTheBottomRight.Text = Global.Utilities.Translator.GetText("Bottom right");
                radioButtonUseCustomLocation.Text = Global.Utilities.Translator.GetText("Custom (drag it to the appropriate position)");
                radioButtonAppearAtMouseLocation.Text = Global.Utilities.Translator.GetText("At mouse location");
                groupBoxSubMenuAppearAt.Text = Global.Utilities.Translator.GetText("Sub menu appears");
                radioButtonNextToPreviousMenu.Text = Global.Utilities.Translator.GetText("Next to the previous one");
                radioButtonOverlapping.Text = Global.Utilities.Translator.GetText("Overlapping");
                labelOverlappingByPixelsOffset.Text = Global.Utilities.Translator.GetText("Offset by pixels");
                buttonSizeAndLocationDefault.Text = Global.Utilities.Translator.GetText("Default");

                tabPageAdvanced.Text = Global.Utilities.Translator.GetText("Advanced");
                groupBoxOptionalFeatures.Text = Global.Utilities.Translator.GetText("Optional Features");
                checkBoxResolveLinksToFolders.Text = Global.Utilities.Translator.GetText("Resolve links to folders and show content");
                checkBoxShowInTaskbar.Text = Global.Utilities.Translator.GetText("Show in Taskbar");
                checkBoxSendHotkeyInsteadKillOtherInstances.Text = Global.Utilities.Translator.GetText("Send hotkey to other instance");
                checkBoxSupportGamepad.Text = Global.Utilities.Translator.GetText("Support Gamepad");
                groupBoxClick.Text = Global.Utilities.Translator.GetText("Click");
                checkBoxOpenItemWithOneClick.Text = Global.Utilities.Translator.GetText("Single click to open an element");
                checkBoxOpenDirectoryWithOneClick.Text = Global.Utilities.Translator.GetText("Single click to open a directory");
                groupBoxDrag.Text = Global.Utilities.Translator.GetText("Drag");
                checkBoxDragDropItems.Text = Global.Utilities.Translator.GetText("Copy row element via drag and drop");
                checkBoxSwipeScrolling.Text = Global.Utilities.Translator.GetText("Scroll via swipe");
                groupBoxInternetShortcutIcons.Text = Global.Utilities.Translator.GetText("Directory of Internet Shortcut Icons");
                buttonChangeIcoFolder.Text = Global.Utilities.Translator.GetText("Changing directory");
                groupBoxSorting.Text = Global.Utilities.Translator.GetText("Sorting");
                radioButtonSortByTypeAndName.Text = Global.Utilities.Translator.GetText("Sorted by type (folder or file) and name");
                radioButtonSortByTypeAndDate.Text = Global.Utilities.Translator.GetText("Sorted by type (folder or file) and date");
                radioButtonSortByFileExtensionAndName.Text = Global.Utilities.Translator.GetText("Sorted by file extension and name");
                radioButtonSortByName.Text = Global.Utilities.Translator.GetText("Sorted by name");
                radioButtonSortByDate.Text = Global.Utilities.Translator.GetText("Sorted by date");
                groupBoxHiddenFilesAndFolders.Text = Global.Utilities.Translator.GetText("Hidden files and directories");
                radioButtonSystemSettingsShowHiddenFiles.Text = Global.Utilities.Translator.GetText("Use operating system settings");
                radioButtonNeverShowHiddenFiles.Text = Global.Utilities.Translator.GetText("Never show");
                radioButtonAlwaysShowHiddenFiles.Text = Global.Utilities.Translator.GetText("Always show");
                buttonAdvancedDefault.Text = Global.Utilities.Translator.GetText("Default");

                tabPageFolders.Text = Global.Utilities.Translator.GetText("Directories");
                groupBoxFoldersInRootFolder.Text = Global.Utilities.Translator.GetText("Add content of directory to root directory");
                checkBoxShowOnlyAsSearchResult.Text = Global.Utilities.Translator.GetText("Show only as search result");
                buttonAddFolderToRootFolder.Text = Global.Utilities.Translator.GetText("Add directory");
                buttonRemoveFolder.Text = Global.Utilities.Translator.GetText("Remove directory");
                ColumnFolder.HeaderText = Global.Utilities.Translator.GetText("Directory paths");
                ColumnRecursiveLevel.HeaderText = Global.Utilities.Translator.GetText("Recursive");
                ColumnOnlyFiles.HeaderText = Global.Utilities.Translator.GetText("Only Files");
                buttonAddSampleStartMenuFolder.Text = Global.Utilities.Translator.GetText("Add sample directory 'Start Menu'");
                buttonDefaultFolders.Text = Global.Utilities.Translator.GetText("Default");
                checkBoxGenerateShortcutsToDrives.Text = Global.Utilities.Translator.GetText("Generate drive shortcuts on startup");

                tabPageExpert.Text = Global.Utilities.Translator.GetText("Expert");
                groupBoxStaysOpen.Text = Global.Utilities.Translator.GetText("Menu stays open");
                checkBoxStayOpenWhenItemClicked.Text = Global.Utilities.Translator.GetText("If an element was clicked");
                checkBoxStayOpenWhenFocusLost.Text = Global.Utilities.Translator.GetText("If the focus is lost and the mouse is still on the menu");
                labelTimeUntilCloses.Text = Global.Utilities.Translator.GetText("Milliseconds until the menu closes if the mouse then leaves the menu");
                groupBoxOpenSubmenus.Text = Global.Utilities.Translator.GetText("Time until a menu opens");
                labelTimeUntilOpen.Text = Global.Utilities.Translator.GetText("Milliseconds until a menu opens when the mouse is on it");
                checkBoxStayOpenWhenFocusLostAfterEnterPressed.Text = Global.Utilities.Translator.GetText("If the focus is lost and the Enter key was pressed");
                labelTimeUntilClosesAfterEnterPressed.Text = Global.Utilities.Translator.GetText("Milliseconds until the menu closes if the menu is not reactivated");
                groupBoxCache.Text = Global.Utilities.Translator.GetText("Cache");
                labelClearCacheIfMoreThanThisNumberOfItems.Text = Global.Utilities.Translator.GetText("Clear cache if more than this number of items");
                groupBoxSearchPattern.Text = Global.Utilities.Translator.GetText("Filter menu by file type e.g.: *.exe|*.dll");
                buttonExpertDefault.Text = Global.Utilities.Translator.GetText("Default");

                tabPageCustomize.Text = Global.Utilities.Translator.GetText("Customize");
                groupBoxAppearance.Text = Global.Utilities.Translator.GetText("Appearance");
                checkBoxUseIconFromRootFolder.Text = Global.Utilities.Translator.GetText("Use icon from directory");
                checkBoxRoundCorners.Text = Global.Utilities.Translator.GetText("Round corners");
                checkBoxDarkModeAlwaysOn.Text = Global.Utilities.Translator.GetText("Color scheme dark always active");
                checkBoxUseFading.Text = Global.Utilities.Translator.GetText("Fading");
                checkBoxShowLinkOverlay.Text = Global.Utilities.Translator.GetText("Show link overlay");
                checkBoxShowDirectoryTitleAtTop.Text = Global.Utilities.Translator.GetText("Show directory title at top");
                checkBoxShowCountOfElementsBelow.Text = Global.Utilities.Translator.GetText("Show count of elements");
                checkBoxShowSearchBar.Text = Global.Utilities.Translator.GetText("Show search bar");
                checkBoxShowFunctionKeyOpenFolder.Text = Global.Utilities.Translator.GetText("Show function key 'Open Folder'");
                checkBoxShowFunctionKeyPinMenu.Text = Global.Utilities.Translator.GetText("Show function key 'Pin menu'");
                checkBoxShowFunctionKeySettings.Text = Global.Utilities.Translator.GetText("Show function key 'Settings'");
                checkBoxShowFunctionKeyRestart.Text = Global.Utilities.Translator.GetText("Show function key 'Restart'");
                buttonAppearanceDefault.Text = Global.Utilities.Translator.GetText("Default");
                groupBoxColorsLightMode.Text = Global.Utilities.Translator.GetText("Color scheme bright");
                groupBoxColorsDarkMode.Text = Global.Utilities.Translator.GetText("Color scheme dark");
                labelMenuLightMode.Text = Global.Utilities.Translator.GetText("App menu");
                labelMenuDarkMode.Text = Global.Utilities.Translator.GetText("App menu");
                labelScrollbarLightMode.Text = Global.Utilities.Translator.GetText("Scrollbar");
                labelScrollbarDarkMode.Text = Global.Utilities.Translator.GetText("Scrollbar");
                labelIcons.Text = Global.Utilities.Translator.GetText("Icons");
                labelIconsDarkMode.Text = Global.Utilities.Translator.GetText("Icons");
                labelBackground.Text = Global.Utilities.Translator.GetText("Background");
                labelBackgroundDarkMode.Text = Global.Utilities.Translator.GetText("Background");
                labelBackgroundBorder.Text = Global.Utilities.Translator.GetText("Border of menu");
                labelBackgroundBorderDarkMode.Text = Global.Utilities.Translator.GetText("Border of menu");
                labelSearchField.Text = Global.Utilities.Translator.GetText("Search field");
                labelSearchFieldDarkMode.Text = Global.Utilities.Translator.GetText("Search field");
                labelOpenFolder.Text = Global.Utilities.Translator.GetText("Opened directory");
                labelOpenFolderDarkMode.Text = Global.Utilities.Translator.GetText("Opened directory");
                labelOpenFolderBorder.Text = Global.Utilities.Translator.GetText("Border of opened directory");
                labelOpenFolderBorderDarkMode.Text = Global.Utilities.Translator.GetText("Border of opened directory");
                labelSelectedItem.Text = Global.Utilities.Translator.GetText("Selected element");
                labelSelectedItemDarkMode.Text = Global.Utilities.Translator.GetText("Selected element");
                labelSelectedItemBorder.Text = Global.Utilities.Translator.GetText("Border of selected element");
                labelSelectedItemBorderDarkMode.Text = Global.Utilities.Translator.GetText("Border of selected element");
                labelScrollbarBackground.Text = Global.Utilities.Translator.GetText("Background");
                labelColorDarkModeScrollbarBackground.Text = Global.Utilities.Translator.GetText("Background");
                labelSlider.Text = Global.Utilities.Translator.GetText("Slider");
                labelColorDarkModeSlider.Text = Global.Utilities.Translator.GetText("Slider");
                labelSliderDragging.Text = Global.Utilities.Translator.GetText("Slider while dragging");
                labelColorDarkModeSliderDragging.Text = Global.Utilities.Translator.GetText("Slider while dragging");
                labelSliderHover.Text = Global.Utilities.Translator.GetText("Slider while mouse hovers over it 1");
                labelColorDarkModeSliderHover.Text = Global.Utilities.Translator.GetText("Slider while mouse hovers over it 1");
                labelSliderArrowsAndTrackHover.Text = Global.Utilities.Translator.GetText("Slider while mouse hovers over it 2");
                labelColorDarkModeSliderArrowsAndTrackHover.Text = Global.Utilities.Translator.GetText("Slider while mouse hovers over it 2");
                labelArrow.Text = Global.Utilities.Translator.GetText("Arrow");
                labelColorDarkModeArrow.Text = Global.Utilities.Translator.GetText("Arrow");
                labelArrowClick.Text = Global.Utilities.Translator.GetText("Arrow when clicking");
                labelColorDarkModeArrowClick.Text = Global.Utilities.Translator.GetText("Arrow when clicking");
                labelArrowClickBackground.Text = Global.Utilities.Translator.GetText("Background of arrow when clicking");
                labelColorDarkModeArrowClickBackground.Text = Global.Utilities.Translator.GetText("Background of arrow when clicking");
                labelArrowHover.Text = Global.Utilities.Translator.GetText("Arrow while mouse hovers over it");
                labelColorDarkModeArrowHover.Text = Global.Utilities.Translator.GetText("Arrow while mouse hovers over it");
                labelArrowHoverBackground.Text = Global.Utilities.Translator.GetText("Background of arrow while mouse hovers over it");
                labelColorDarkModeArrowHoverBackground.Text = Global.Utilities.Translator.GetText("Background of arrow while mouse hovers over it");

                buttonColorsDefault.Text = Global.Utilities.Translator.GetText("Default");
                buttonColorsDefaultDarkMode.Text = Global.Utilities.Translator.GetText("Default");
                buttonOk.Text = Global.Utilities.Translator.GetText("OK");
                buttonCancel.Text = Global.Utilities.Translator.GetText("Abort");
            }

            textBoxFolder.Text = Tools.SystemTrayMenu.Config.Path;
            checkBoxSetFolderByWindowsContextMenu.Checked = Global.Vars.SystemTrayMenuSettings.SetFolderByWindowsContextMenu;
            //checkBoxSaveConfigInApplicationDirectory.Checked = CustomSettingsProvider.IsActivatedConfigPathAssembly();
            checkBoxSaveLogFileInApplicationDirectory.Checked = Global.Vars.SystemTrayMenuSettings.SaveLogFileInApplicationDirectory;

            if (IsStartupTask())
            {
                checkBoxAutostart.Visible = false;
                labelStartupStatus.Text = string.Empty;
            }
            else
            {
                buttonAddStartup.Visible = false;
                labelStartupStatus.Visible = false;
                checkBoxAutostart.Checked = Global.Vars.SystemTrayMenuSettings.IsAutostartActivated;
            }

            checkBoxCheckForUpdates.Checked = Global.Vars.SystemTrayMenuSettings.CheckForUpdates;
            textBoxHotkey.SetHotkey(Global.Vars.SystemTrayMenuSettings.HotKey);

            InitializeLanguage();
            void InitializeLanguage()
            {
                List<Language> dataSource = new()
                {                   
                    new Language() { Name = "Deutsch", Value = "de" },                 
                    new Language() { Name = "English", Value = "en" },                    
                };
                comboBoxLanguage.DataSource = dataSource;
                comboBoxLanguage.DisplayMember = "Name";
                comboBoxLanguage.ValueMember = "Value";
                comboBoxLanguage.SelectedValue =
                    Global.Vars.SystemTrayMenuSettings.CurrentCultureInfoName;
                comboBoxLanguage.SelectedValue ??= "en";
            }

            numericUpDownSizeInPercent.Minimum = 100;
            numericUpDownSizeInPercent.Maximum = 200;
            numericUpDownSizeInPercent.Increment = 5;
            numericUpDownSizeInPercent.MouseWheel += NumericUpDown_MouseWheel;
            void NumericUpDown_MouseWheel(object sender, MouseEventArgs e)
            {
                NumericUpDown numericUpDown = (NumericUpDown)sender;
                decimal newValue = numericUpDown.Value;
                if (e.Delta > 0)
                {
                    newValue += numericUpDown.Increment;
                    if (newValue > numericUpDown.Maximum)
                    {
                        newValue = (int)numericUpDown.Maximum;
                    }
                }
                else
                {
                    newValue -= numericUpDown.Increment;
                    if (newValue < numericUpDown.Minimum)
                    {
                        newValue = (int)numericUpDown.Minimum;
                    }
                }

                numericUpDown.Value = newValue;
                ((HandledMouseEventArgs)e).Handled = true;
            }

            numericUpDownSizeInPercent.Value = Global.Vars.SystemTrayMenuSettings.SizeInPercent;

            numericUpDownIconSizeInPercent.Minimum = 50;
            numericUpDownIconSizeInPercent.Maximum = 200;
            numericUpDownIconSizeInPercent.Increment = 5;
            numericUpDownIconSizeInPercent.MouseWheel += NumericUpDown_MouseWheel;
            numericUpDownIconSizeInPercent.Value = Global.Vars.SystemTrayMenuSettings.IconSizeInPercent;

            numericUpDownRowHeighteInPercentage.Minimum = 50;
            numericUpDownRowHeighteInPercentage.Maximum = 200;
            numericUpDownRowHeighteInPercentage.Increment = 5;
            numericUpDownRowHeighteInPercentage.MouseWheel += NumericUpDown_MouseWheel;
            if (Global.DllImports.NativeMethods.IsTouchEnabled())
            {
                numericUpDownRowHeighteInPercentage.Value = Global.Vars.SystemTrayMenuSettings.RowHeighteInPercentageTouch;
            }
            else
            {
                numericUpDownRowHeighteInPercentage.Value = Global.Vars.SystemTrayMenuSettings.RowHeighteInPercentage;
            }

            numericUpDownMenuWidth.Minimum = 25;
            numericUpDownMenuWidth.Maximum = 400;
            numericUpDownMenuWidth.Increment = 5;
            numericUpDownMenuWidth.Value = Global.Vars.SystemTrayMenuSettings.WidthMaxInPercent;

            numericUpDownMenuHeight.Minimum = 25;
            numericUpDownMenuHeight.Maximum = 400;
            numericUpDownMenuHeight.Increment = 5;
            numericUpDownMenuHeight.Value = Global.Vars.SystemTrayMenuSettings.HeightMaxInPercent;

            if (Global.Vars.SystemTrayMenuSettings.UseCustomLocation)
            {
                radioButtonUseCustomLocation.Checked = true;
            }
            else if (Global.Vars.SystemTrayMenuSettings.AppearAtMouseLocation)
            {
                radioButtonAppearAtMouseLocation.Checked = true;
            }
            else if (Global.Vars.SystemTrayMenuSettings.AppearAtTheBottomLeft)
            {
                radioButtonAppearAtTheBottomLeft.Checked = true;
            }
            else
            {
                radioButtonAppearAtTheBottomRight.Checked = true;
            }

            numericUpDownOverlappingOffsetPixels.Value = Global.Vars.SystemTrayMenuSettings.OverlappingOffsetPixels;
            if (Global.Vars.SystemTrayMenuSettings.AppearNextToPreviousMenu)
            {
                radioButtonNextToPreviousMenu.Checked = true;
                numericUpDownOverlappingOffsetPixels.Enabled = false;
            }
            else
            {
                radioButtonOverlapping.Checked = true;
                numericUpDownOverlappingOffsetPixels.Enabled = true;
            }

            checkBoxResolveLinksToFolders.Checked = Global.Vars.SystemTrayMenuSettings.ResolveLinksToFolders;
            checkBoxShowInTaskbar.Checked = Global.Vars.SystemTrayMenuSettings.ShowInTaskbar;
            checkBoxSendHotkeyInsteadKillOtherInstances.Checked = Global.Vars.SystemTrayMenuSettings.SendHotkeyInsteadKillOtherInstances;
            checkBoxSupportGamepad.Checked = Global.Vars.SystemTrayMenuSettings.SupportGamepad;
            checkBoxOpenItemWithOneClick.Checked = Global.Vars.SystemTrayMenuSettings.OpenItemWithOneClick;
            checkBoxOpenDirectoryWithOneClick.Checked = Global.Vars.SystemTrayMenuSettings.OpenDirectoryWithOneClick;

            if (Global.DllImports.NativeMethods.IsTouchEnabled())
            {
                checkBoxDragDropItems.Checked = Global.Vars.SystemTrayMenuSettings.DragDropItemsEnabledTouch;
                checkBoxSwipeScrolling.Checked = Global.Vars.SystemTrayMenuSettings.SwipeScrollingEnabledTouch;
            }
            else
            {
                checkBoxDragDropItems.Checked = Global.Vars.SystemTrayMenuSettings.DragDropItemsEnabled;
                checkBoxSwipeScrolling.Checked = Global.Vars.SystemTrayMenuSettings.SwipeScrollingEnabled;
            }

            textBoxIcoFolder.Text = Global.Vars.SystemTrayMenuSettings.PathIcoDirectory;
            radioButtonSortByTypeAndName.Checked = Global.Vars.SystemTrayMenuSettings.SortByTypeAndNameWindowsExplorerSort;
            radioButtonSortByTypeAndDate.Checked = Global.Vars.SystemTrayMenuSettings.SortByTypeAndDate;
            radioButtonSortByFileExtensionAndName.Checked = Global.Vars.SystemTrayMenuSettings.SortByFileExtensionAndName;
            radioButtonSortByName.Checked = Global.Vars.SystemTrayMenuSettings.SortByName;
            radioButtonSortByDate.Checked = Global.Vars.SystemTrayMenuSettings.SortByDate;
            radioButtonSystemSettingsShowHiddenFiles.Checked = Global.Vars.SystemTrayMenuSettings.SystemSettingsShowHiddenFiles;
            radioButtonNeverShowHiddenFiles.Checked = Global.Vars.SystemTrayMenuSettings.NeverShowHiddenFiles;
            radioButtonAlwaysShowHiddenFiles.Checked = Global.Vars.SystemTrayMenuSettings.AlwaysShowHiddenFiles;

            checkBoxShowOnlyAsSearchResult.Checked = Global.Vars.SystemTrayMenuSettings.ShowOnlyAsSearchResult;
            try
            {
                foreach (string pathAndRecursivString in Global.Vars.SystemTrayMenuSettings.PathsAddToMainMenu.Split(@"|"))
                {
                    if (string.IsNullOrEmpty(pathAndRecursivString))
                    {
                        continue;
                    }

                    string pathAddToMainMenu = pathAndRecursivString.Split("recursiv:")[0].Trim();
                    bool recursive = pathAndRecursivString.Split("recursiv:")[1].StartsWith("True");
                    bool onlyFiles = pathAndRecursivString.Split("onlyFiles:")[1].StartsWith("True");
                    dataGridViewFolders.Rows.Add(pathAddToMainMenu, recursive, onlyFiles);
                }
            }
            catch (Exception ex)
            {
                Log.Warn("PathsAddToMainMenu", ex);
            }

            checkBoxGenerateShortcutsToDrives.Checked = Global.Vars.SystemTrayMenuSettings.GenerateShortcutsToDrives;

            checkBoxStayOpenWhenItemClicked.Checked = Global.Vars.SystemTrayMenuSettings.StaysOpenWhenItemClicked;
            checkBoxStayOpenWhenFocusLost.Checked = Global.Vars.SystemTrayMenuSettings.StaysOpenWhenFocusLost;

            numericUpDownTimeUntilClose.Minimum = 200;
            numericUpDownTimeUntilClose.Maximum = 5000;
            numericUpDownTimeUntilClose.Increment = 10;
            numericUpDownTimeUntilClose.Value = Global.Vars.SystemTrayMenuSettings.TimeUntilCloses;

            numericUpDownTimeUntilOpens.Minimum = 20;
            numericUpDownTimeUntilOpens.Maximum = 1000;
            numericUpDownTimeUntilOpens.Increment = 10;
            numericUpDownTimeUntilOpens.Value = Global.Vars.SystemTrayMenuSettings.TimeUntilOpens;

            checkBoxStayOpenWhenFocusLostAfterEnterPressed.Checked = Global.Vars.SystemTrayMenuSettings.StaysOpenWhenFocusLostAfterEnterPressed;

            numericUpDownTimeUntilClosesAfterEnterPressed.Minimum = 20;
            numericUpDownTimeUntilClosesAfterEnterPressed.Maximum = 1000;
            numericUpDownTimeUntilClosesAfterEnterPressed.Increment = 10;
            numericUpDownTimeUntilClosesAfterEnterPressed.Value = Global.Vars.SystemTrayMenuSettings.TimeUntilClosesAfterEnterPressed;

            numericUpDownClearCacheIfMoreThanThisNumberOfItems.Value = Global.Vars.SystemTrayMenuSettings.ClearCacheIfMoreThanThisNumberOfItems;

            textBoxSearchPattern.Text = Global.Vars.SystemTrayMenuSettings.SearchPattern;

            checkBoxUseIconFromRootFolder.Checked = Global.Vars.SystemTrayMenuSettings.UseIconFromRootFolder;
            checkBoxRoundCorners.Checked = Global.Vars.SystemTrayMenuSettings.RoundCorners;
            checkBoxDarkModeAlwaysOn.Checked = Global.Vars.SystemTrayMenuSettings.IsDarkModeAlwaysOn;
            checkBoxUseFading.Checked = Global.Vars.SystemTrayMenuSettings.UseFading;
            checkBoxShowLinkOverlay.Checked = Global.Vars.SystemTrayMenuSettings.ShowLinkOverlay;
            checkBoxShowDirectoryTitleAtTop.Checked = Global.Vars.SystemTrayMenuSettings.ShowDirectoryTitleAtTop;
            checkBoxShowSearchBar.Checked = Global.Vars.SystemTrayMenuSettings.ShowSearchBar;
            checkBoxShowCountOfElementsBelow.Checked = Global.Vars.SystemTrayMenuSettings.ShowCountOfElementsBelow;
            checkBoxShowFunctionKeyOpenFolder.Checked = Global.Vars.SystemTrayMenuSettings.ShowFunctionKeyOpenFolder;
            checkBoxShowFunctionKeyPinMenu.Checked = Global.Vars.SystemTrayMenuSettings.ShowFunctionKeyPinMenu;
            checkBoxShowFunctionKeySettings.Checked = Global.Vars.SystemTrayMenuSettings.ShowFunctionKeySettings;
            checkBoxShowFunctionKeyRestart.Checked = Global.Vars.SystemTrayMenuSettings.ShowFunctionKeyRestart;

            textBoxColorSelectedItem.Text = Global.Vars.SystemTrayMenuSettings.ColorSelectedItem;
            textBoxColorSelecetedItemDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorDarkModeSelecetedItem;
            textBoxColorSelectedItemBorder.Text = Global.Vars.SystemTrayMenuSettings.ColorSelectedItemBorder;
            textBoxColorSelectedItemBorderDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorDarkModeSelectedItemBorder;
            textBoxColorOpenFolder.Text = Global.Vars.SystemTrayMenuSettings.ColorOpenFolder;
            textBoxColorOpenFolderDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorDarkModeOpenFolder;
            textBoxColorOpenFolderBorder.Text = Global.Vars.SystemTrayMenuSettings.ColorOpenFolderBorder;
            textBoxColorOpenFolderBorderDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorDarkModeOpenFolderBorder;
            textBoxColorIcons.Text = Global.Vars.SystemTrayMenuSettings.ColorIcons;
            textBoxColorIconsDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorDarkModeIcons;
            textBoxColorBackground.Text = Global.Vars.SystemTrayMenuSettings.ColorBackground;
            textBoxColorBackgroundDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorDarkModeBackground;
            textBoxColorBackgroundBorder.Text = Global.Vars.SystemTrayMenuSettings.ColorBackgroundBorder;
            textBoxColorBackgroundBorderDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorDarkModeBackgroundBorder;
            textBoxColorSearchField.Text = Global.Vars.SystemTrayMenuSettings.ColorSearchField;
            textBoxColorSearchFieldDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorDarkModeSearchField;

            textBoxColorScrollbarBackground.Text = Global.Vars.SystemTrayMenuSettings.ColorScrollbarBackground;
            textBoxColorSlider.Text = Global.Vars.SystemTrayMenuSettings.ColorSlider;
            textBoxColorSliderDragging.Text = Global.Vars.SystemTrayMenuSettings.ColorSliderDragging;
            textBoxColorSliderHover.Text = Global.Vars.SystemTrayMenuSettings.ColorSliderHover;
            textBoxColorSliderArrowsAndTrackHover.Text = Global.Vars.SystemTrayMenuSettings.ColorSliderArrowsAndTrackHover;
            textBoxColorArrow.Text = Global.Vars.SystemTrayMenuSettings.ColorArrow;
            textBoxColorArrowClick.Text = Global.Vars.SystemTrayMenuSettings.ColorArrowClick;
            textBoxColorArrowClickBackground.Text = Global.Vars.SystemTrayMenuSettings.ColorArrowClickBackground;
            textBoxColorArrowHover.Text = Global.Vars.SystemTrayMenuSettings.ColorArrowHover;
            textBoxColorArrowHoverBackground.Text = Global.Vars.SystemTrayMenuSettings.ColorArrowHoverBackground;
            textBoxColorScrollbarBackgroundDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorScrollbarBackgroundDarkMode;
            textBoxColorSliderDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorSliderDarkMode;
            textBoxColorSliderDraggingDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorSliderDraggingDarkMode;
            textBoxColorSliderHoverDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorSliderHoverDarkMode;
            textBoxColorSliderArrowsAndTrackHoverDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorSliderArrowsAndTrackHoverDarkMode;
            textBoxColorArrowDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorArrowDarkMode;
            textBoxColorArrowClickDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorArrowClickDarkMode;
            textBoxColorArrowClickBackgroundDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorArrowClickBackgroundDarkMode;
            textBoxColorArrowHoverDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorArrowHoverDarkMode;
            textBoxColorArrowHoverBackgroundDarkMode.Text = Global.Vars.SystemTrayMenuSettings.ColorArrowHoverBackgroundDarkMode;
        }

        /// <summary>
        /// Gets NewHotKey.
        /// </summary>
        public string NewHotKey { get; } = string.Empty;

        /// <summary>
        /// Registers all hotkeys as configured, displaying a dialog in case of hotkey conflicts with other tools.
        /// </summary>
        /// <returns>Whether the hotkeys could be registered to the users content. This also applies if conflicts arise and the user decides to ignore these (i.e. not to register the conflicting hotkey).</returns>
        public static bool RegisterHotkeys()
        {
            return RegisterHotkeys(false);
        }

        public static void ShowSingleInstance()
        {
            if (IsOpen())
            {
                settingsForm.HandleInvoke(settingsForm.Activate);
            }
            else
            {
                settingsForm = new();
                settingsForm.ShowDialog();
            }
        }

        public static bool IsOpen()
        {
            return settingsForm != null;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.Escape:
                    if (!inHotkey)
                    {
                        DialogResult = DialogResult.Cancel;
                    }
                    else
                    {
                        return base.ProcessCmdKey(ref msg, keyData);
                    }

                    break;
                default:
                    return base.ProcessCmdKey(ref msg, keyData);
            }

            return true;
        }

        /// <summary>
        /// Helper method to cleanly register a hotkey.
        /// </summary>
        /// <param name="failedKeys">failedKeys.</param>
        /// <param name="hotkeyString">hotkeyString.</param>
        /// <param name="handler">handler.</param>
        /// <returns>bool success.</returns>
        private static bool RegisterHotkey(StringBuilder failedKeys, string hotkeyString, HotKeyHandler handler)
        {
            Keys modifierKeyCode = HotkeyModifiersFromString(hotkeyString);
            Keys virtualKeyCode = HotkeyFromString(hotkeyString);
            if (!Keys.None.Equals(virtualKeyCode))
            {
                if (RegisterHotKey(modifierKeyCode, virtualKeyCode, handler) < 0)
                {
                    if (failedKeys.Length > 0)
                    {
                        failedKeys.Append(", ");
                    }

                    failedKeys.Append(hotkeyString);
                    return false;
                }
            }

            return true;
        }

        private static bool RegisterWrapper(StringBuilder failedKeys, HotKeyHandler handler)
        {
            bool success = RegisterHotkey(
                failedKeys,
                Global.Vars.SystemTrayMenuSettings.HotKey,
                handler);
            return success;
        }

        /// <summary>
        /// Registers all hotkeys as configured, displaying a dialog in case of hotkey conflicts with other tools.
        /// </summary>
        /// <param name="ignoreFailedRegistration">if true, a failed hotkey registration will not be reported to the user - the hotkey will simply not be registered.</param>
        /// <returns>Whether the hotkeys could be registered to the users content. This also applies if conflicts arise and the user decides to ignore these (i.e. not to register the conflicting hotkey).</returns>
        private static bool RegisterHotkeys(bool ignoreFailedRegistration)
        {
            bool success = true;
            StringBuilder failedKeys = new();
            if (!RegisterWrapper(failedKeys, Handler))
            {
                success = false;
            }

            if (!success)
            {
                if (!ignoreFailedRegistration)
                {
                    success = HandleFailedHotkeyRegistration(failedKeys.ToString());
                }
            }

            return success || ignoreFailedRegistration;
        }

        private static void Handler()
        {
        }

        /// <summary>
        /// Displays a dialog for the user to choose how to handle hotkey registration failures:
        /// retry (allowing to shut down the conflicting application before),
        /// ignore (not registering the conflicting hotkey and resetting the respective config to "None", i.e. not trying to register it again on next startup)
        /// abort (do nothing about it).
        /// </summary>
        /// <param name="failedKeys">comma separated list of the hotkeys that could not be registered, for display in dialog text.</param>
        /// <returns>bool success.</returns>
        private static bool HandleFailedHotkeyRegistration(string failedKeys)
        {
            bool success = false;
            string warningTitle = Global.Utilities.Translator.GetText("Warning");
            string message = Global.Utilities.Translator.GetText("Could not register the hot key.") + failedKeys;
            DialogResult dr = MessageBox.Show(message, warningTitle, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Exclamation);
            if (dr == DialogResult.Retry)
            {
                UnregisterHotkeys();
                success = RegisterHotkeys(false);
            }
            else if (dr == DialogResult.Ignore)
            {
                UnregisterHotkeys();
                success = RegisterHotkeys(true);
            }

            return success;
        }

        private static void AdjustControlMultilineIfNecessary(Control control)
        {
            if (control.Width > control.Parent.Width)
            {
                control.MaximumSize = new Size(control.Parent.Width, 0);
                control.MinimumSize = new Size(0, control.Height * 2);
            }
        }

        private static void AddSetFolderByWindowsContextMenu()
        {
            RegistryKey registryKeyContextMenu = null;
            RegistryKey registryKeyContextMenuCommand = null;

            try
            {
                registryKeyContextMenu = Registry.CurrentUser.CreateSubKey(MenuName);
                string binLocation = Environment.ProcessPath;
                if (registryKeyContextMenu != null)
                {
                    registryKeyContextMenu.SetValue(string.Empty, Global.Utilities.Translator.GetText("Set as directory"));
                    registryKeyContextMenu.SetValue("Icon", binLocation);
                }

                registryKeyContextMenuCommand = Registry.CurrentUser.CreateSubKey(Command);

                if (registryKeyContextMenuCommand != null)
                {
                    registryKeyContextMenuCommand.SetValue(string.Empty, binLocation + " \"%1\"");
                }

                Global.Vars.SystemTrayMenuSettings.SetFolderByWindowsContextMenu = true;
            }
            catch (Exception ex)
            {
                Log.Warn("SaveSetFolderByWindowsContextMenu failed", ex);
            }
            finally
            {
                if (registryKeyContextMenu != null)
                {
                    registryKeyContextMenu.Close();
                }

                if (registryKeyContextMenuCommand != null)
                {
                    registryKeyContextMenuCommand.Close();
                }
            }
        }

        private static void RemoveSetFolderByWindowsContextMenu()
        {
            try
            {
                RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(Command);
                if (registryKey != null)
                {
                    registryKey.Close();
                    Registry.CurrentUser.DeleteSubKey(Command);
                }

                registryKey = Registry.CurrentUser.OpenSubKey(MenuName);
                if (registryKey != null)
                {
                    registryKey.Close();
                    Registry.CurrentUser.DeleteSubKey(MenuName);
                }

                Global.Vars.SystemTrayMenuSettings.SetFolderByWindowsContextMenu = false;
            }
            catch (Exception ex)
            {
                Log.Warn("DeleteSetFolderByWindowsContextMenu failed", ex);
            }
        }

        private static bool IsStartupTask()
        {
            bool useStartupTask = false;
#if RELEASEPACKAGE
            useStartupTask = true;
#endif
            return useStartupTask;
        }

        private void SettingsForm_Load(object sender, EventArgs e)
        {
            AdjustControlMultilineIfNecessary(checkBoxStayOpenWhenFocusLost);
            dataGridViewFolders.ClearSelection();
            tabPageGeneral.AutoScrollMinSize = tableLayoutPanelGeneral.Size;
            tabPageSizeAndLocation.AutoScrollMinSize = tableLayoutPanelSizeAndLocation.Size;
            tabPageAdvanced.AutoScrollMinSize = tableLayoutPanelAdvanced.Size;
            tabPageFolders.AutoScrollMinSize = tableLayoutPanelFoldersInRootFolder.Size;
            tabPageExpert.AutoScrollMinSize = tableLayoutPanelExpert.Size;
            tabPageCustomize.AutoScrollMinSize = tableLayoutPanelCustomize.Size;
            tableLayoutPanelMain.Dock = DockStyle.Fill;
            tabControl.Dock = DockStyle.Fill;
            tabPageGeneral.Dock = DockStyle.Fill;
            tableLayoutPanelGeneral.Dock = DockStyle.Fill;
            tabPageSizeAndLocation.Dock = DockStyle.Fill;
            tableLayoutPanelSizeAndLocation.Dock = DockStyle.Fill;
            tabPageAdvanced.Dock = DockStyle.Fill;
            tableLayoutPanelAdvanced.Dock = DockStyle.Fill;
            tabPageFolders.Dock = DockStyle.Fill;
            tableLayoutPanelFoldersInRootFolder.Dock = DockStyle.Fill;
            tabPageExpert.Dock = DockStyle.Fill;
            tableLayoutPanelExpert.Dock = DockStyle.Fill;
            tabPageCustomize.Dock = DockStyle.Fill;
            tableLayoutPanelCustomize.Dock = DockStyle.Fill;
        }

        private void SettingsForm_Shown(object sender, EventArgs e)
        {
            Size size = Size;
            SuspendLayout();
            AutoSize = false;
            AutoSizeMode = AutoSizeMode.GrowOnly;
            Size = size;
            textBoxFolder.Anchor = AnchorStyles.Left | AnchorStyles.Right;
            textBoxHotkey.Anchor = AnchorStyles.Left | AnchorStyles.Right;
            textBoxIcoFolder.Anchor = AnchorStyles.Left | AnchorStyles.Right;
            dataGridViewFolders.Dock = DockStyle.Fill;
            textBoxSearchPattern.Anchor = AnchorStyles.Left | AnchorStyles.Right;
            Opacity = 1;
            ResumeLayout();
        }

        private void ButtonOk_Click(object sender, EventArgs e)
        {
            if (checkBoxSetFolderByWindowsContextMenu.Checked)
            {
                AddSetFolderByWindowsContextMenu();
            }
            else
            {
                RemoveSetFolderByWindowsContextMenu();
            }

            Global.Vars.SystemTrayMenuSettings.SaveLogFileInApplicationDirectory = checkBoxSaveLogFileInApplicationDirectory.Checked;
            if (Global.Vars.SystemTrayMenuSettings.SaveLogFileInApplicationDirectory)
            {
                try
                {
                    string fileNameToCheckWriteAccess = "CheckWriteAccess";
                    File.WriteAllText(fileNameToCheckWriteAccess, fileNameToCheckWriteAccess);
                    File.Delete(fileNameToCheckWriteAccess);
                    Global.Vars.SystemTrayMenuSettings.SaveLogFileInApplicationDirectory = true;
                }
                catch (Exception ex)
                {
                    Global.Vars.SystemTrayMenuSettings.SaveLogFileInApplicationDirectory = false;
                    Log.Warn($"Failed to save log file in application folder {Log.GetLogFilePath()}", ex);
                }
            }

            if (!IsStartupTask())
            {
                if (checkBoxAutostart.Checked)
                {
                    RegistryKey key = Registry.CurrentUser.OpenSubKey(
                            @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                    key.SetValue(
                        Assembly.GetExecutingAssembly().GetName().Name,
                        Environment.ProcessPath);

                    Global.Vars.SystemTrayMenuSettings.IsAutostartActivated = true;
                }
                else
                {
                    RegistryKey key = Registry.CurrentUser.OpenSubKey(
                        @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                    key.DeleteValue("FSI.BT.Tools.SystemTrayMenu", false);

                    Global.Vars.SystemTrayMenuSettings.IsAutostartActivated = false;
                }
            }

            Global.Vars.SystemTrayMenuSettings.CheckForUpdates = checkBoxCheckForUpdates.Checked;

            Global.Vars.SystemTrayMenuSettings.HotKey = new KeysConverter().ConvertToInvariantString(textBoxHotkey.Hotkey | textBoxHotkey.HotkeyModifiers);
            Global.Vars.SystemTrayMenuSettings.CurrentCultureInfoName = comboBoxLanguage.SelectedValue.ToString();

            Global.Vars.SystemTrayMenuSettings.SizeInPercent = (int)numericUpDownSizeInPercent.Value;
            Global.Vars.SystemTrayMenuSettings.IconSizeInPercent = (int)numericUpDownIconSizeInPercent.Value;
            if (Global.DllImports.NativeMethods.IsTouchEnabled())
            {
                Global.Vars.SystemTrayMenuSettings.RowHeighteInPercentageTouch = (int)numericUpDownRowHeighteInPercentage.Value;
            }
            else
            {
                Global.Vars.SystemTrayMenuSettings.RowHeighteInPercentage = (int)numericUpDownRowHeighteInPercentage.Value;
            }

            Global.Vars.SystemTrayMenuSettings.WidthMaxInPercent = (int)numericUpDownMenuWidth.Value;
            Global.Vars.SystemTrayMenuSettings.HeightMaxInPercent = (int)numericUpDownMenuHeight.Value;

            if (radioButtonUseCustomLocation.Checked)
            {
                Global.Vars.SystemTrayMenuSettings.UseCustomLocation = true;
                Global.Vars.SystemTrayMenuSettings.AppearAtMouseLocation = false;
                Global.Vars.SystemTrayMenuSettings.AppearAtTheBottomLeft = false;
            }
            else if (radioButtonAppearAtMouseLocation.Checked)
            {
                Global.Vars.SystemTrayMenuSettings.UseCustomLocation = false;
                Global.Vars.SystemTrayMenuSettings.AppearAtMouseLocation = true;
                Global.Vars.SystemTrayMenuSettings.AppearAtTheBottomLeft = false;
            }
            else if (radioButtonAppearAtTheBottomLeft.Checked)
            {
                Global.Vars.SystemTrayMenuSettings.UseCustomLocation = false;
                Global.Vars.SystemTrayMenuSettings.AppearAtMouseLocation = false;
                Global.Vars.SystemTrayMenuSettings.AppearAtTheBottomLeft = true;
            }
            else
            {
                Global.Vars.SystemTrayMenuSettings.UseCustomLocation = false;
                Global.Vars.SystemTrayMenuSettings.AppearAtMouseLocation = false;
                Global.Vars.SystemTrayMenuSettings.AppearAtTheBottomLeft = false;
            }

            Global.Vars.SystemTrayMenuSettings.OverlappingOffsetPixels = (int)numericUpDownOverlappingOffsetPixels.Value;
            if (radioButtonNextToPreviousMenu.Checked)
            {
                Global.Vars.SystemTrayMenuSettings.AppearNextToPreviousMenu = true;
            }
            else
            {
                Global.Vars.SystemTrayMenuSettings.AppearNextToPreviousMenu = false;
            }

            Global.Vars.SystemTrayMenuSettings.ResolveLinksToFolders = checkBoxResolveLinksToFolders.Checked;
            Global.Vars.SystemTrayMenuSettings.ShowInTaskbar = checkBoxShowInTaskbar.Checked;
            Global.Vars.SystemTrayMenuSettings.SendHotkeyInsteadKillOtherInstances = checkBoxSendHotkeyInsteadKillOtherInstances.Checked;
            Global.Vars.SystemTrayMenuSettings.SupportGamepad = checkBoxSupportGamepad.Checked;
            Global.Vars.SystemTrayMenuSettings.OpenItemWithOneClick = checkBoxOpenItemWithOneClick.Checked;
            Global.Vars.SystemTrayMenuSettings.OpenDirectoryWithOneClick = checkBoxOpenDirectoryWithOneClick.Checked;

            if (Global.DllImports.NativeMethods.IsTouchEnabled())
            {
                Global.Vars.SystemTrayMenuSettings.DragDropItemsEnabledTouch = checkBoxDragDropItems.Checked;
                Global.Vars.SystemTrayMenuSettings.SwipeScrollingEnabledTouch = checkBoxSwipeScrolling.Checked;
            }
            else
            {
                Global.Vars.SystemTrayMenuSettings.DragDropItemsEnabled = checkBoxDragDropItems.Checked;
                Global.Vars.SystemTrayMenuSettings.SwipeScrollingEnabled = checkBoxSwipeScrolling.Checked;
            }

            Global.Vars.SystemTrayMenuSettings.PathIcoDirectory = textBoxIcoFolder.Text;
            Global.Vars.SystemTrayMenuSettings.SortByTypeAndNameWindowsExplorerSort = radioButtonSortByTypeAndName.Checked;
            Global.Vars.SystemTrayMenuSettings.SortByTypeAndDate = radioButtonSortByTypeAndDate.Checked;
            Global.Vars.SystemTrayMenuSettings.SortByFileExtensionAndName = radioButtonSortByFileExtensionAndName.Checked;
            Global.Vars.SystemTrayMenuSettings.SortByName = radioButtonSortByName.Checked;
            Global.Vars.SystemTrayMenuSettings.SortByDate = radioButtonSortByDate.Checked;
            Global.Vars.SystemTrayMenuSettings.SystemSettingsShowHiddenFiles = radioButtonSystemSettingsShowHiddenFiles.Checked;
            Global.Vars.SystemTrayMenuSettings.AlwaysShowHiddenFiles = radioButtonAlwaysShowHiddenFiles.Checked;
            Global.Vars.SystemTrayMenuSettings.NeverShowHiddenFiles = radioButtonNeverShowHiddenFiles.Checked;

            Global.Vars.SystemTrayMenuSettings.ShowOnlyAsSearchResult = checkBoxShowOnlyAsSearchResult.Checked;
            Global.Vars.SystemTrayMenuSettings.PathsAddToMainMenu = string.Empty;
            foreach (DataGridViewRow row in dataGridViewFolders.Rows)
            {
                string pathAddToMainMenu = row.Cells[0].Value.ToString();
                bool recursiv = (bool)row.Cells[1].Value;
                bool onlyFiles = (bool)row.Cells[2].Value;
                Global.Vars.SystemTrayMenuSettings.PathsAddToMainMenu += $"{pathAddToMainMenu} recursiv:{recursiv} onlyFiles:{onlyFiles}|";
            }

            Global.Vars.SystemTrayMenuSettings.GenerateShortcutsToDrives = checkBoxGenerateShortcutsToDrives.Checked;

            Global.Vars.SystemTrayMenuSettings.StaysOpenWhenItemClicked = checkBoxStayOpenWhenItemClicked.Checked;
            Global.Vars.SystemTrayMenuSettings.StaysOpenWhenFocusLost = checkBoxStayOpenWhenFocusLost.Checked;
            Global.Vars.SystemTrayMenuSettings.TimeUntilCloses = (int)numericUpDownTimeUntilClose.Value;
            Global.Vars.SystemTrayMenuSettings.TimeUntilOpens = (int)numericUpDownTimeUntilOpens.Value;
            Global.Vars.SystemTrayMenuSettings.StaysOpenWhenFocusLostAfterEnterPressed = checkBoxStayOpenWhenFocusLostAfterEnterPressed.Checked;
            Global.Vars.SystemTrayMenuSettings.TimeUntilClosesAfterEnterPressed = (int)numericUpDownTimeUntilClosesAfterEnterPressed.Value;
            Global.Vars.SystemTrayMenuSettings.ClearCacheIfMoreThanThisNumberOfItems = (int)numericUpDownClearCacheIfMoreThanThisNumberOfItems.Value;
            Global.Vars.SystemTrayMenuSettings.SearchPattern = textBoxSearchPattern.Text;

            Global.Vars.SystemTrayMenuSettings.UseIconFromRootFolder = checkBoxUseIconFromRootFolder.Checked;
            Global.Vars.SystemTrayMenuSettings.RoundCorners = checkBoxRoundCorners.Checked;
            Global.Vars.SystemTrayMenuSettings.IsDarkModeAlwaysOn = checkBoxDarkModeAlwaysOn.Checked;
            Global.Vars.SystemTrayMenuSettings.UseFading = checkBoxUseFading.Checked;
            Global.Vars.SystemTrayMenuSettings.ShowLinkOverlay = checkBoxShowLinkOverlay.Checked;
            Global.Vars.SystemTrayMenuSettings.ShowDirectoryTitleAtTop = checkBoxShowDirectoryTitleAtTop.Checked;
            Global.Vars.SystemTrayMenuSettings.ShowSearchBar = checkBoxShowSearchBar.Checked;
            Global.Vars.SystemTrayMenuSettings.ShowCountOfElementsBelow = checkBoxShowCountOfElementsBelow.Checked;
            Global.Vars.SystemTrayMenuSettings.ShowFunctionKeyOpenFolder = checkBoxShowFunctionKeyOpenFolder.Checked;
            Global.Vars.SystemTrayMenuSettings.ShowFunctionKeyPinMenu = checkBoxShowFunctionKeyPinMenu.Checked;
            Global.Vars.SystemTrayMenuSettings.ShowFunctionKeySettings = checkBoxShowFunctionKeySettings.Checked;
            Global.Vars.SystemTrayMenuSettings.ShowFunctionKeyRestart = checkBoxShowFunctionKeyRestart.Checked;

            //if (checkBoxSaveConfigInApplicationDirectory.Checked)
            //{
            //    CustomSettingsProvider.ActivateConfigPathAssembly();
            //    TrySettingsDefaultSave();
            //}
            //else
            //{
            //    TrySettingsDefaultSave();
            //    CustomSettingsProvider.DeactivateConfigPathAssembly();
            //}

            static void TrySettingsDefaultSave()
            {
                //try
                //{
                //    //Global.Vars.SystemTrayMenuSettings.Save();
                //}
                //catch (Exception ex)
                //{
                //    Log.Warn($"Failed to save configuration file in application folder {CustomSettingsProvider.ConfigPathAssembly}", ex);
                //}
            }

            DialogResult = DialogResult.OK;
            AppRestart.ByConfigChange();
            Close();
        }

        private void ButtonAddStartup_Click(object sender, EventArgs e)
        {
            _ = AddStartUpAsync();
            async Task AddStartUpAsync()
            {
                // Pass the task ID you specified in the appxmanifest file
                StartupTask startupTask = await StartupTask.GetAsync("MyStartupId");
                Log.Info($"Autostart {startupTask.State}.");

                switch (startupTask.State)
                {
                    case StartupTaskState.Enabled:
                    case StartupTaskState.EnabledByPolicy:
                        UpdateLabelStartupStatus(startupTask.State);
                        break;
                    case StartupTaskState.Disabled:
                        // Task is disabled but can be enabled.
                        StartupTaskState newState = await startupTask.RequestEnableAsync();
                        UpdateLabelStartupStatus(newState);
                        break;
                    case StartupTaskState.DisabledByUser:
                        UpdateLabelStartupStatus(startupTask.State);
                        break;
                    case StartupTaskState.DisabledByPolicy:
                        UpdateLabelStartupStatus(startupTask.State);
                        break;
                    default:
                        break;
                }
            }
        }

        private void UpdateLabelStartupStatus(StartupTaskState newState)
        {
            switch (newState)
            {
                case StartupTaskState.Disabled:
                case StartupTaskState.DisabledByUser:
                case StartupTaskState.DisabledByPolicy:
                    labelStartupStatus.Text = Global.Utilities.Translator.GetText("Deactivated");
                    break;
                case StartupTaskState.Enabled:
                case StartupTaskState.EnabledByPolicy:
                    labelStartupStatus.Text = Global.Utilities.Translator.GetText("Activated");
                    break;
                default:
                    break;
            }
        }

        private void ButtonChange_Click(object sender, EventArgs e)
        {
            Tools.SystemTrayMenu.Config.SetFolderByUser(false);
            textBoxFolder.Text = Tools.SystemTrayMenu.Config.Path;
        }

        private void ButtonOpenFolder_Click(object sender, EventArgs e)
        {
            Log.ProcessStart("explorer.exe", Tools.SystemTrayMenu.Config.Path, true);
        }

        private void ButtonChangeRelativeFolder_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Tools.SystemTrayMenu.Config.Path))
            {
                Global.Vars.SystemTrayMenuSettings.PathDirectory = Path.GetRelativePath(
                    Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName,
                    Tools.SystemTrayMenu.Config.Path);
                textBoxFolder.Text = Tools.SystemTrayMenu.Config.Path;
            }
        }

        private void ButtonOpenAssemblyLocation_Click(object sender, EventArgs e)
        {
            Log.ProcessStart(Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName);
        }

        private void TextBoxHotkeyEnter(object sender, EventArgs e)
        {
            UnregisterHotkeys();
            inHotkey = true;
        }

        private void TextBoxHotkey_Leave(object sender, EventArgs e)
        {
            Global.Vars.SystemTrayMenuSettings.HotKey =
                new KeysConverter().ConvertToInvariantString(
                textBoxHotkey.Hotkey | textBoxHotkey.HotkeyModifiers);
            RegisterHotkeys();
            inHotkey = false;
        }

        private void ButtonHotkeyDefault_Click(object sender, EventArgs e)
        {
            textBoxHotkey.SetHotkey("Ctrl+LWin");
        }

        private void ButtonGeneralDefault_Click(object sender, EventArgs e)
        {
            checkBoxSetFolderByWindowsContextMenu.Checked = false;
            checkBoxSaveConfigInApplicationDirectory.Checked = false;
            checkBoxSaveLogFileInApplicationDirectory.Checked = false;
            checkBoxAutostart.Checked = false;
            checkBoxCheckForUpdates.Checked = false;
        }

        private void ButtonChangeIcoFolder_Click(object sender, EventArgs e)
        {
            Tools.SystemTrayMenu.Config.SetFolderIcoByUser();
            textBoxIcoFolder.Text = Global.Vars.SystemTrayMenuSettings.PathIcoDirectory;
        }

        private void ButtonAddSampleStartMenuFolder_Click(object sender, EventArgs e)
        {
            dataGridViewFolders.Rows.Clear();
            string folderPathCommonStartMenu = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu);
            dataGridViewFolders.Rows.Add(folderPathCommonStartMenu, true, true);
            dataGridViewFolders.ClearSelection();
        }

        private void ButtonClearFolders_Click(object sender, EventArgs e)
        {
            checkBoxShowOnlyAsSearchResult.Checked = false;
            dataGridViewFolders.Rows.Clear();
            checkBoxGenerateShortcutsToDrives.Checked = false;
        }

        private void ButtonAddFolderToRootFolder_Click(object sender, EventArgs e)
        {
            using FolderDialog dialog = new();
            dialog.InitialFolder = Tools.SystemTrayMenu.Config.Path;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                dataGridViewFolders.Rows.Add(dialog.Folder, false, true);
            }

            dataGridViewFolders.ClearSelection();
        }

        private void ButtonRemoveFolder_Click(object sender, EventArgs e)
        {
            int selectedRowCount = dataGridViewFolders.Rows.GetRowCount(DataGridViewElementStates.Selected);
            if (selectedRowCount > 0)
            {
                for (int i = 0; i < selectedRowCount; i++)
                {
                    dataGridViewFolders.Rows.RemoveAt(dataGridViewFolders.SelectedRows[0].Index);
                }
            }

            dataGridViewFolders.ClearSelection();
        }

        private void DataGridViewFolders_SelectionChanged(object sender, EventArgs e)
        {
            buttonRemoveFolder.Enabled = dataGridViewFolders.SelectedRows.Count > 0;
        }

        private void DataGridViewFolders_MouseClick(object sender, MouseEventArgs e)
        {
            if (dataGridViewFolders.HitTest(e.X, e.Y).RowIndex < 0)
            {
                dataGridViewFolders.ClearSelection();
            }
        }

        private void DataGridViewFolders_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                dataGridViewFolders.CancelEdit();
            }
        }

        private void DataGridViewFolders_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            EnableButtonAddStartMenu();
        }

        private void DataGridViewFolders_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            EnableButtonAddStartMenu();
        }

        private void DataGridViewFolders_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            EnableButtonAddStartMenu();
        }

        private void EnableButtonAddStartMenu()
        {
            bool doesStartMenuFolderExist = false;
            foreach (DataGridViewRow row in dataGridViewFolders.Rows)
            {
                string folderPathCommonStartMenu = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu);
                string pathAddToMainMenu = row.Cells[0].Value.ToString();
                bool recursiv = (bool)row.Cells[1].EditedFormattedValue;
                bool onlyFiles = (bool)row.Cells[2].EditedFormattedValue;
                if (folderPathCommonStartMenu == pathAddToMainMenu &&
                    recursiv == true &&
                    onlyFiles == true)
                {
                    doesStartMenuFolderExist = true;
                }
            }

            buttonAddSampleStartMenuFolder.Enabled = !doesStartMenuFolderExist;
        }

        private void ButtonSizeAndLocationDefault_Click(object sender, EventArgs e)
        {
            numericUpDownSizeInPercent.Value = 100;
            numericUpDownIconSizeInPercent.Value = 100;
            numericUpDownRowHeighteInPercentage.Value = 100;
            numericUpDownMenuWidth.Value = 100;
            numericUpDownMenuHeight.Value = 100;

            radioButtonAppearAtTheBottomRight.Checked = false;
            radioButtonAppearAtTheBottomLeft.Checked = true;
            radioButtonUseCustomLocation.Checked = false;
            radioButtonAppearAtMouseLocation.Checked = false;

            radioButtonNextToPreviousMenu.Checked = true;
            numericUpDownOverlappingOffsetPixels.Value = 150;
        }

        private void ButtonAdvancedDefault_Click(object sender, EventArgs e)
        {
            checkBoxResolveLinksToFolders.Checked = true;
            checkBoxShowInTaskbar.Checked = true;
            checkBoxSendHotkeyInsteadKillOtherInstances.Checked = false;
            checkBoxSupportGamepad.Checked = false;
            checkBoxOpenItemWithOneClick.Checked = true;
            checkBoxOpenDirectoryWithOneClick.Checked = false;
            if (Global.DllImports.NativeMethods.IsTouchEnabled())
            {
                checkBoxDragDropItems.Checked = false;
                checkBoxSwipeScrolling.Checked = true;
            }
            else
            {
                checkBoxDragDropItems.Checked = true;
                checkBoxSwipeScrolling.Checked = false;
            }

            textBoxIcoFolder.Text = Path.Combine(
                    Path.Combine(
                        Environment.GetFolderPath(
                            Environment.SpecialFolder.ApplicationData), $"FSI.BT.Tools.SystemTrayMenu"), "ico");
            if (!Directory.Exists(Global.Vars.SystemTrayMenuSettings.PathIcoDirectory))
            {
                Directory.CreateDirectory(Global.Vars.SystemTrayMenuSettings.PathIcoDirectory);
            }

            radioButtonSortByName.Checked = true;
            radioButtonSortByDate.Checked = false;
            radioButtonSystemSettingsShowHiddenFiles.Checked = true;
            radioButtonNeverShowHiddenFiles.Checked = false;
            radioButtonAlwaysShowHiddenFiles.Checked = false;
        }

        private void CheckBoxStayOpenWhenFocusLost_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDownTimeUntilClose.Enabled = checkBoxStayOpenWhenFocusLost.Checked;
        }

        private void CheckBoxStayOpenWhenFocusLostAfterEnterPressed_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDownTimeUntilClosesAfterEnterPressed.Enabled = checkBoxStayOpenWhenFocusLostAfterEnterPressed.Checked;
        }

        private void ButtonExpertDefault_Click(object sender, EventArgs e)
        {
            checkBoxStayOpenWhenItemClicked.Checked = true;
            checkBoxStayOpenWhenFocusLost.Checked = true;
            numericUpDownTimeUntilClose.Value = 400;
            numericUpDownTimeUntilOpens.Value = 100;
            checkBoxStayOpenWhenFocusLostAfterEnterPressed.Checked = true;
            numericUpDownTimeUntilClosesAfterEnterPressed.Value = 200;
            numericUpDownClearCacheIfMoreThanThisNumberOfItems.Value = 200;
            textBoxSearchPattern.Text = string.Empty;
        }

        private void TextBoxColorsChanged(object sender, EventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            PictureBox pictureBox = (PictureBox)textBox.Tag;
            pictureBox.BackColor = GetConvertFromStringOrDefault(textBox.Text.Trim());

            SaveColorsTemporarily();
        }

        private Color GetConvertFromStringOrDefault(string text)
        {
            try
            {
                return (Color)colorConverter.ConvertFromString(text);
            }
            catch
            {
                return Color.White;
            }
        }

        private void SaveColorsTemporarily()
        {
            if (Visible)
            {
                Global.Vars.SystemTrayMenuSettings.ColorSelectedItem = textBoxColorSelectedItem.Text;
                Global.Vars.SystemTrayMenuSettings.ColorDarkModeSelecetedItem = textBoxColorSelecetedItemDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorSelectedItemBorder = textBoxColorSelectedItemBorder.Text;
                Global.Vars.SystemTrayMenuSettings.ColorDarkModeSelectedItemBorder = textBoxColorSelectedItemBorderDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorOpenFolder = textBoxColorOpenFolder.Text;
                Global.Vars.SystemTrayMenuSettings.ColorDarkModeOpenFolder = textBoxColorOpenFolderDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorOpenFolderBorder = textBoxColorOpenFolderBorder.Text;
                Global.Vars.SystemTrayMenuSettings.ColorDarkModeOpenFolderBorder = textBoxColorOpenFolderBorderDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorIcons = textBoxColorIcons.Text;
                Global.Vars.SystemTrayMenuSettings.ColorDarkModeIcons = textBoxColorIconsDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorBackground = textBoxColorBackground.Text;
                Global.Vars.SystemTrayMenuSettings.ColorDarkModeBackground = textBoxColorBackgroundDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorBackgroundBorder = textBoxColorBackgroundBorder.Text;
                Global.Vars.SystemTrayMenuSettings.ColorDarkModeBackgroundBorder = textBoxColorBackgroundBorderDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorSearchField = textBoxColorSearchField.Text;
                Global.Vars.SystemTrayMenuSettings.ColorDarkModeSearchField = textBoxColorSearchFieldDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorScrollbarBackground = textBoxColorScrollbarBackground.Text;
                Global.Vars.SystemTrayMenuSettings.ColorSlider = textBoxColorSlider.Text;
                Global.Vars.SystemTrayMenuSettings.ColorSliderDragging = textBoxColorSliderDragging.Text;
                Global.Vars.SystemTrayMenuSettings.ColorSliderHover = textBoxColorSliderHover.Text;
                Global.Vars.SystemTrayMenuSettings.ColorSliderArrowsAndTrackHover = textBoxColorSliderArrowsAndTrackHover.Text;
                Global.Vars.SystemTrayMenuSettings.ColorArrow = textBoxColorArrow.Text;
                Global.Vars.SystemTrayMenuSettings.ColorArrowClick = textBoxColorArrowClick.Text;
                Global.Vars.SystemTrayMenuSettings.ColorArrowClickBackground = textBoxColorArrowClickBackground.Text;
                Global.Vars.SystemTrayMenuSettings.ColorArrowHover = textBoxColorArrowHover.Text;
                Global.Vars.SystemTrayMenuSettings.ColorArrowHoverBackground = textBoxColorArrowHoverBackground.Text;
                Global.Vars.SystemTrayMenuSettings.ColorScrollbarBackgroundDarkMode = textBoxColorScrollbarBackgroundDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorSliderDarkMode = textBoxColorSliderDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorSliderDraggingDarkMode = textBoxColorSliderDraggingDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorSliderHoverDarkMode = textBoxColorSliderHoverDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorSliderArrowsAndTrackHoverDarkMode = textBoxColorSliderArrowsAndTrackHoverDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorArrowDarkMode = textBoxColorArrowDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorArrowClickDarkMode = textBoxColorArrowClickDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorArrowClickBackgroundDarkMode = textBoxColorArrowClickBackgroundDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorArrowHoverDarkMode = textBoxColorArrowHoverDarkMode.Text;
                Global.Vars.SystemTrayMenuSettings.ColorArrowHoverBackgroundDarkMode = textBoxColorArrowHoverBackgroundDarkMode.Text;

                Tools.SystemTrayMenu.Config.InitializeColors(false);
            }
        }

        private void CheckBoxDarkModeAlwaysOnCheckedChanged(object sender, EventArgs e)
        {
            Global.Vars.SystemTrayMenuSettings.IsDarkModeAlwaysOn = checkBoxDarkModeAlwaysOn.Checked;
            Tools.SystemTrayMenu.Config.ResetReadDarkModeDone();
            SaveColorsTemporarily();
        }

        private void PictureBoxClick(object sender, EventArgs e)
        {
            PictureBox pictureBox = (PictureBox)sender;
            TextBox textBox = (TextBox)pictureBox.Tag;
            colorDialog.Color = pictureBox.BackColor;
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                textBox.Text = ColorTranslator.ToHtml(colorDialog.Color);
                pictureBox.BackColor = colorDialog.Color;
            }
        }

        private void ButtonAppearanceDefault_Click(object sender, EventArgs e)
        {
            checkBoxUseIconFromRootFolder.Checked = false;
            checkBoxRoundCorners.Checked = false;
            checkBoxUseFading.Checked = false;
            checkBoxDarkModeAlwaysOn.Checked = true;
            checkBoxShowLinkOverlay.Checked = false;
            checkBoxShowDirectoryTitleAtTop.Checked = false;
            checkBoxShowSearchBar.Checked = true;
            checkBoxShowCountOfElementsBelow.Checked = false;
            checkBoxShowFunctionKeyOpenFolder.Checked = false;
            checkBoxShowFunctionKeyPinMenu.Checked = false;
            checkBoxShowFunctionKeySettings.Checked = false;
            checkBoxShowFunctionKeyRestart.Checked = false;
        }

        private void ButtonDefaultColors_Click(object sender, EventArgs e)
        {
            textBoxColorIcons.Text = "#95a0a6";
            textBoxColorOpenFolder.Text = "#C2F5DE";
            textBoxColorOpenFolderBorder.Text = "#99FFA5";
            textBoxColorBackground.Text = "#ffffff";
            textBoxColorBackgroundBorder.Text = "#000000";
            textBoxColorSearchField.Text = "#ffffff";
            textBoxColorSelectedItem.Text = "#CCE8FF";
            textBoxColorSelectedItemBorder.Text = "#99D1FF";
            textBoxColorArrow.Text = "#606060";
            textBoxColorArrowHoverBackground.Text = "#dadada";
            textBoxColorArrowHover.Text = "#000000";
            textBoxColorArrowClick.Text = "#ffffff";
            textBoxColorArrowClickBackground.Text = "#606060";
            textBoxColorSliderArrowsAndTrackHover.Text = "#c0c0c0";
            textBoxColorSlider.Text = "#cdcdcd";
            textBoxColorSliderHover.Text = "#a6a6a6";
            textBoxColorSliderDragging.Text = "#606060";
            textBoxColorScrollbarBackground.Text = "#f0f0f0";
        }

        private void ButtonDefaultColorsDark_Click(object sender, EventArgs e)
        {
            textBoxColorIconsDarkMode.Text = "#95a0a6";
            textBoxColorOpenFolderDarkMode.Text = "#14412A";
            textBoxColorOpenFolderBorderDarkMode.Text = "#144B55";
            textBoxColorBackgroundDarkMode.Text = "#202020";
            textBoxColorBackgroundBorderDarkMode.Text = "#000000";
            textBoxColorSearchFieldDarkMode.Text = "#191919";
            textBoxColorSelecetedItemDarkMode.Text = "#333333";
            textBoxColorSelectedItemBorderDarkMode.Text = "#141D4B";
            textBoxColorArrowDarkMode.Text = "#676767";
            textBoxColorArrowHoverBackgroundDarkMode.Text = "#373737";
            textBoxColorArrowHoverDarkMode.Text = "#676767";
            textBoxColorArrowClickDarkMode.Text = "#171717";
            textBoxColorArrowClickBackgroundDarkMode.Text = "#a6a6a6";
            textBoxColorSliderArrowsAndTrackHoverDarkMode.Text = "#4d4d4d";
            textBoxColorSliderDarkMode.Text = "#4d4d4d";
            textBoxColorSliderHoverDarkMode.Text = "#7a7a7a";
            textBoxColorSliderDraggingDarkMode.Text = "#a6a6a6";
            textBoxColorScrollbarBackgroundDarkMode.Text = "#171717";
        }

        private void StopPlayingDingSoundEnterKeyPressed_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.Handled = e.SuppressKeyPress = true;
            }
        }

        private void StopPlayingDingSoundEnterKeyPressed_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.Handled = e.SuppressKeyPress = true;
            }
        }

        private void ButtonCancel_Click(object sender, EventArgs e)
        {
            //Global.Vars.SystemTrayMenuSettings.Reload();
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void SettingsForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            settingsForm?.Dispose();
            settingsForm = null;
        }

        private void RadioButtonNextToPreviousMenu_CheckedChanged(object sender, EventArgs e)
        {
            radioButtonOverlapping.CheckedChanged -= RadioButtonOverlapping_CheckedChanged;
            radioButtonOverlapping.Checked = false;
            radioButtonOverlapping.CheckedChanged += RadioButtonOverlapping_CheckedChanged;
            numericUpDownOverlappingOffsetPixels.Enabled = false;
        }

        private void RadioButtonOverlapping_CheckedChanged(object sender, EventArgs e)
        {
            radioButtonNextToPreviousMenu.CheckedChanged -= RadioButtonNextToPreviousMenu_CheckedChanged;
            radioButtonNextToPreviousMenu.Checked = false;
            radioButtonNextToPreviousMenu.CheckedChanged += RadioButtonNextToPreviousMenu_CheckedChanged;
            numericUpDownOverlappingOffsetPixels.Enabled = true;
        }
    }
}
