Exemple #1
0
 public HotKeyControl(IWindowsFormsEditorService editor_service, HotKeys.KeyMask key_mask)
 {
     InitializeComponent();
       this.editor_service = editor_service;
       this.key_changed = false;
       this.KeyMask = key_mask;
       this.key_text.Focus();
 }
 private static void UnregPrevHotkey(HotKeys.HotKeyCallBackHandler cb)
 {
     GlobalHotKey.HotKey prevHotKey;
     if (HotKeys.IsCallbackExists(cb, out prevHotKey))
     {
         // unregister previous one
         HotKeys.UnRegist(prevHotKey);
     }
 }
 public SoundSwitchConfiguration()
 {
     FirstRun = true;
     ChangeCommunications = false;
     SelectedPlaybackDeviceList = new HashSet<string>();
     SelectedRecordingDeviceList = new HashSet<string>();
     PlaybackHotKeys = new HotKeys(Keys.F11, HotKeys.ModifierKeys.Alt | HotKeys.ModifierKeys.Control);
     RecordingHotKeys = new HotKeys(Keys.F7,HotKeys.ModifierKeys.Alt | HotKeys.ModifierKeys.Control);
     //12 hours
     UpdateCheckInterval = 3600*12;
 }
		internal HotKeySettingWindow(DoubanFMWindow owner, HotKeys hotKeys)
		{
			InitializeComponent();

			HotKeys = hotKeys;
            foreach (var child in HotKeysGrid.Children)
			{
				if (child is HotKeySettingControl)
				{
					HotKeySettingControl setting = child as HotKeySettingControl;
					if (hotKeys.ContainsKey(setting.Command))
						setting.HotKey = hotKeys[setting.Command];
				}
			}
		}
        public SoundSwitchConfiguration()
        {
            FirstRun = true;
            ChangeCommunications = false;
            SelectedPlaybackDeviceList = null;
            SelectedRecordingDeviceList = null;
            NotificationSettings = NotificationTypeEnum.DefaultWindowsNotification;
            SelectedPlaybackDeviceListId = new HashSet<string>();
            SelectedRecordingDeviceListId = new HashSet<string>();
            PlaybackHotKeys = new HotKeys(Keys.F11, HotKeys.ModifierKeys.Alt | HotKeys.ModifierKeys.Control);
            RecordingHotKeys = new HotKeys(Keys.F7, HotKeys.ModifierKeys.Alt | HotKeys.ModifierKeys.Control);
            //12 hours
            UpdateCheckInterval = 3600 * 12;
            SubscribedBetaVersion = false;

        }
 public SoundSwitchConfiguration()
 {
     FirstRun = true;
     ChangeCommunications = false;
     SelectedPlaybackDeviceList = null;
     SelectedRecordingDeviceList = null;
     NotificationSettings = NotificationTypeEnum.DefaultWindowsNotification;
     SelectedPlaybackDeviceListId = new HashSet<string>();
     SelectedRecordingDeviceListId = new HashSet<string>();
     PlaybackHotKeys = new HotKeys(Keys.F11, HotKeys.ModifierKeys.Alt | HotKeys.ModifierKeys.Control);
     RecordingHotKeys = new HotKeys(Keys.F7, HotKeys.ModifierKeys.Alt | HotKeys.ModifierKeys.Control);
     //12 hours
     UpdateCheckInterval = 3600 * 12;
     UpdateState = UpdateState.Steath;
     SubscribedBetaVersion = false;
     TooltipInfo = TooltipInfoTypeEnum.Playback;
     CyclerType = DeviceCyclerTypeEnum.Available;
     KeepSystrayIcon = false;
 }
Exemple #7
0
        /// <summary>
        /// Called when loading a settings file to iterate through new dynamic properties (such as Hotkeys)
        /// which may have changed and would otherwise be hidden from the user
        /// </summary>
        private void CheckForNewSettings()
        {
            foreach (var defaultHotkey in _defaultHotKeys)
            {
                bool found = false;
                foreach (var hotkey in HotKeys)
                {
                    if (hotkey.Action == defaultHotkey.Action)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    HotKeys.Add(defaultHotkey.Clone());
                }
            }
        }
Exemple #8
0
        public static bool RegHotkeyFromString(string hotkeyStr, string callbackName, Action <RegResult> onComplete = null)
        {
            var _callback = HotkeyCallbacks.GetCallback(callbackName);

            if (_callback == null)
            {
                throw new Exception($"{callbackName} not found");
            }

            var callback = _callback as HotKeys.HotKeyCallBackHandler;

            if (hotkeyStr.IsNullOrEmpty())
            {
                HotKeys.UnregExistingHotkey(callback);
                onComplete?.Invoke(RegResult.UnregSuccess);
                return(true);
            }
            else
            {
                var hotkey = HotKeys.Str2HotKey(hotkeyStr);
                if (hotkey == null)
                {
                    Logging.Error($"Cannot parse hotkey: {hotkeyStr}");
                    onComplete?.Invoke(RegResult.ParseError);
                    return(false);
                }
                else
                {
                    bool regResult = (HotKeys.RegHotkey(hotkey, callback));
                    if (regResult)
                    {
                        onComplete?.Invoke(RegResult.RegSuccess);
                    }
                    else
                    {
                        onComplete?.Invoke(RegResult.RegFailure);
                    }
                    return(regResult);
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Esta funcion toma los eventos KeyDown sobre los controles y actualiza el texto mostrando la informacion de la HotKey
        /// </summary>
        /// <param name="textBox">Control donde se actualiza el texto con la nueva HotKey</param>
        /// <param name="e">KeyEventArgs e</param>
        /// <param name="hook">Variable tipo KeyboardHook donde se crea el hook</param>
        /// <param name="func">Funcion que es llamada cuando las teclas se apretan </param>
        /// <returns>-1 Si no debe modificarse el valor del setting, 0 si se elimina la hotkey, sino int32 con la KeyData</returns>
        private int CheckHotKey(TextBox textBox, KeyEventArgs e, ref KeyboardHook hook, EventHandler <KeyPressedEventArgs> func)
        {
            e.Handled = true;

            // Fetch the actual shortcut key.
            Keys key  = e.KeyCode;
            Keys mods = e.Modifiers;
            Keys data = e.KeyData;

            // Ignore modifier keys.
            if (key == Keys.LShiftKey || key == Keys.RShiftKey || key == Keys.ShiftKey ||
                key == Keys.LControlKey || key == Keys.RControlKey || key == Keys.ControlKey ||
                key == Keys.Alt || key == Keys.LWin || key == Keys.RWin)
            {
                return(-1);
            }

            // HotKey remover keys
            if (key == Keys.Back || key == Keys.Delete || key == Keys.Escape)
            {
                hook.Dispose();
                textBox.Text = "None";
                return(0);
            }

            // Set the hook
            hook = new KeyboardHook();
            // register the event that is fired after the key press.
            hook.KeyPressed += func;
            try
            {
                hook.RegisterHotKey(HotKeys.ToModKeys(mods), key);
            }catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(-1);
            }
            // Update the text box.
            textBox.Text = GetTextForKeyAndMods(key, mods);
            return((int)data);
        }
Exemple #10
0
        public void UpdateHotkey(HotKeys hotkey)
        {
            if (hotkey == null)
            {
                return;
            }
            string json = JsonConvert.SerializeObject(hotkey);

            if (string.IsNullOrEmpty(json))
            {
                return;
            }

            using (FileStream fs = new FileStream(hotkeyFilePath, FileMode.Create))
                using (StreamWriter writer = new StreamWriter(fs))
                {
                    writer.Write(json);
                    writer.Flush();
                }
            //File.WriteAllText(hotkeyFilePath, json);
        }
Exemple #11
0
        private void Repeat(HotKeys key)
        {
            var autoRepeatKey = key switch {
                HotKeys.LeftAutoRepeat => MouseKeys.Left,
                HotKeys.RightAutoRepeat => MouseKeys.Right,
                _ => MouseKeys.None
            };

            Task.Run(async() => {
                if (autoRepeatKey == MouseKeys.None)
                {
                    return;
                }

                while (GetState(key) == KeyStates.Hold)
                {
                    InputEvents.MouseInput(InputEvent.Press, autoRepeatKey);
                    await Task.Delay(_data.AppData.AutoRepeatDelay);
                }
            });
        }
Exemple #12
0
        private void LoadHotKey()
        {
            HotKeys hotkey = null;

            if (System.IO.File.Exists(hotkeyFilePath))
            {
                string json = string.Empty;

                using (StreamReader sr = new StreamReader(hotkeyFilePath))
                {
                    json = sr.ReadToEnd();
                }
                try { hotkey = JsonConvert.DeserializeObject <HotKeys>(json); }
                catch (Exception e) { App.SendException("Load hotky Error", ""); }
            }
            if (hotkey == null)
            {
                hotkey = new HotKeys();
                UpdateHotkey(hotkey);
            }
            DataInstence.UpdateHotkeys(hotkey);
        }
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            // I later realized that hotkeys are natively supported in the menu strip buttons...
            // I will still keep and use this implementation.

            // Handle file manipulation hotkeys
            if (HotKeys.Save(keyData))
            {
                tsbtnSave_Click(this, null);
                return(true);
            }
            else if (HotKeys.Open(keyData))
            {
                tsbtnOpen_Click(this, null);
                return(true);
            }
            else if (HotKeys.New(keyData))
            {
                tsbtnNew_Click(this, null);
                return(true);
            }
            // Handle text manipulation hotkeys
            else if (HotKeys.Cut(keyData))
            {
                tsbtnCut_Click(this, null);
                return(true);
            }
            else if (HotKeys.Copy(keyData))
            {
                tsbtnCopy_Click(this, null);
                return(true);
            }
            else if (HotKeys.Paste(keyData))
            {
                tsbtnPaste_Click(this, null);
                return(true);
            }
            return(base.ProcessCmdKey(ref msg, keyData));
        }
        private void RegisterHotKeys()
        {
            m_hotKeys             = new HotKeys();
            m_hotKeys.KeyPressed += new EventHandler <KeyPressedEventArgs>(m_mainForm.ShowHide);

            bool   alt       = Minder.Static.StaticData.Settings.NewTaskHotkey.Alt;
            bool   shift     = Minder.Static.StaticData.Settings.NewTaskHotkey.Shift;
            bool   ctrl      = Minder.Static.StaticData.Settings.NewTaskHotkey.Ctrl;
            bool   win       = Minder.Static.StaticData.Settings.NewTaskHotkey.Win;
            string keyString = Minder.Static.StaticData.Settings.NewTaskHotkey.Key;
            Keys   key       = Keys.Decimal;

            Minder.Static.StaticData.Settings.NewTaskHotkey.KeysDic.TryGetValue(keyString, out key);

            // Nesu 100% tikras, kad gerai veikia - bet standartinis atvejis veikia
            // o kodas daug aiškesnis ir lengviau taisomas
            Core.Tools.GlobalHotKeys.ModifierKeys hotKey = new Core.Tools.GlobalHotKeys.ModifierKeys();
            if (alt)
            {
                hotKey = hotKey | Core.Tools.GlobalHotKeys.ModifierKeys.Alt;
            }
            if (shift)
            {
                hotKey = hotKey | Core.Tools.GlobalHotKeys.ModifierKeys.Shift;
            }
            if (ctrl)
            {
                hotKey = hotKey | Core.Tools.GlobalHotKeys.ModifierKeys.Control;
            }
            if (win)
            {
                hotKey = hotKey | Core.Tools.GlobalHotKeys.ModifierKeys.Win;
            }

            m_hotKeys.RegisterHotKey(hotKey, key);
            //			m_form.MTextBox.KeyDown += KeyPressed;
            m_mainForm.MTextBox.KeyDown += KeyPressed;
        }
Exemple #15
0
        public static void UnregisterHotKey(CaptureMode mode)
        {
            if (Handle == IntPtr.Zero)
            {
                return;
            }
            if (!HotKeys.ContainsKey(mode))
            {
                return;
            }

            var hotKey = HotKeys[mode];

            if (hotKey == null)
            {
                return;
            }

            if (WindowNative.UnregisterHotKey(Handle, (int)mode))
            {
                hotKey.IsRegistered = false;
            }
        }
        public SoundSwitchConfiguration()
        {
            // Basic Settings
            FirstRun        = true;
            KeepSystrayIcon = false;

            // Audio Settings
            ChangeCommunications = false;
            NotificationSettings = NotificationTypeEnum.BannerNotification;
            TooltipInfo          = TooltipInfoTypeEnum.Playback;
            CyclerType           = DeviceCyclerTypeEnum.Available;

            // Update Settings
            UpdateCheckInterval = 3600 * 24; // 24 hours
            UpdateMode          = UpdateMode.Notify;
            IncludeBetaVersions = false;

            // Language Settings
            Language = LanguageParser.ParseLanguage(CultureInfo.InstalledUICulture);
            SelectedPlaybackDeviceListId  = new HashSet <string>();
            SelectedRecordingDeviceListId = new HashSet <string>();
            PlaybackHotKeys  = new HotKeys(Keys.F11, HotKeys.ModifierKeys.Alt | HotKeys.ModifierKeys.Control);
            RecordingHotKeys = new HotKeys(Keys.F7, HotKeys.ModifierKeys.Alt | HotKeys.ModifierKeys.Control);
        }
Exemple #17
0
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            #region 保存热键
            HotKeys.Clear();
            foreach (var child in this.yy.Children)
            {
                if (child is HotKeySettingControl)
                {
                    HotKeySettingControl setting = child as HotKeySettingControl;
                    if (setting.HotKey != null)
                    {
                        HotKeys.Add(setting.Command, setting.HotKey);
                    }
                }
            }
            #endregion

            #region 类型关联
            List <string> fileTypes = new List <string>();
            //foreach (DataItem d in Items)
            //{
            //    if (d.IsEnabled) { fileTypes.Add(d.Name.Substring(d.Name.IndexOf('(').TrimEnd(')'))); }
            //}
            string dir = AppDomain.CurrentDomain.BaseDirectory;
            fileTypes.AddRange(Items.Where(item => item.IsEnabled).Select(ss => ss.Name.Substring(ss.Name.IndexOf('(') + 1).Trim(')')));
            TypeRegsiter.Regsiter(dir + "\\Player.exe", dir + "Resouce\\Symbian_Anna.dll", fileTypes);
            //  TypeRegsiter.Regsiter(fileTypes);  //TODO
            FileRegisterSave();
            #endregion
            this.Close();

            if (SettingReloadHandler != null)
            {
                SettingReloadHandler(HotKeys);
            }
        }
Exemple #18
0
 public SettingPage(HotKeys hotKeys)
 {
     #region FileType Init
     FileRegisterLoad();
     #endregion
     InitializeComponent();
     #region 读取热键
     HotKeys = hotKeys;
     if (hotKeys != null)
     {
         foreach (var child in this.yy.Children)
         {
             if (child is HotKeySettingControl)
             {
                 HotKeySettingControl setting = child as HotKeySettingControl;
                 if (hotKeys.ContainsKey(setting.Command))
                 {
                     setting.HotKey = hotKeys[setting.Command];
                 }
             }
         }
     }
     #endregion
 }
        /// <summary>
        /// Find correct callback and corresponding label
        /// </summary>
        /// <param name="tb"></param>
        /// <param name="cb"></param>
        /// <param name="lb"></param>
        private void PrepareForHotkey(TextBox tb, out HotKeys.HotKeyCallBackHandler cb, out Label lb)
        {
            /*
             * XXX: The labelName, TextBoxName and callbackName
             *      must follow this rule to make use of reflection
             *
             *      <BaseName><Control-Type-Name>
             */
            if (tb == null)
                throw new ArgumentNullException(nameof(tb));

            var pos = tb.Name.LastIndexOf("TextBox", StringComparison.OrdinalIgnoreCase);
            var rawName = tb.Name.Substring(0, pos);
            var labelName = rawName + "Label";
            var callbackName = rawName + "Callback";

            var callback = GetDelegateViaMethodName(this.GetType(), callbackName);
            if (callback == null)
            {
                throw new Exception($"{callbackName} not found");
            }
            cb = callback as HotKeys.HotKeyCallBackHandler;

            object label = GetFieldViaName(this.GetType(), labelName, this);
            if (label == null)
            {
                throw new Exception($"{labelName} not found");
            }
            lb = label as Label;
        }
Exemple #20
0
 public override void EnterState()
 {
     hotkeyMenu = boardManager.ui.optionsMenu.hotkeymenu;
     hotkeys    = inputHandler.hotkeys;
 }
Exemple #21
0
 public HideForm()
 {
     InitializeComponent();
     SetStyle(ControlStyles.Opaque, true);
     HotKeys.Register(Handle);
 }
 private void ShowHotkeyAlreadyInUse()
 {
     MessageBox.Show("Your selected HotKey is already in use! Try another one or make sure your selected HotKey is not used.", "HavocClicks");
     HotkeyTeachingMode = HotKeys.None;
 }
Exemple #23
0
        private static void Main(string[] args)
        {
            #region Single Instance and IPC
            bool hasAnotherInstance = !mutex.WaitOne(TimeSpan.Zero, true);

            // store args for further use
            Args = args;
            Parser.Default.ParseArguments <CommandLineOption>(args)
            .WithParsed(opt => Options = opt)
            .WithNotParsed(e => e.Output());

            if (hasAnotherInstance)
            {
                if (!string.IsNullOrWhiteSpace(Options.OpenUrl))
                {
                    IPCService.RequestOpenUrl(Options.OpenUrl);
                }
                else
                {
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.")
                                    + Environment.NewLine
                                    + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                                    I18N.GetString("Shadowsocks is already running."));
                }
                return;
            }
            #endregion

            #region Enviroment Setup
            Directory.SetCurrentDirectory(WorkingDirectory);
            // todo: initialize the NLog configuartion
            Model.NLogConfig.TouchAndApplyNLogConfig();

            // .NET Framework 4.7.2 on Win7 compatibility
            ServicePointManager.SecurityProtocol |=
                SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            #endregion

            #region Compactibility Check
            // Check OS since we are using dual-mode socket
            if (!Utils.IsWinVistaOrHigher())
            {
                MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Check .NET Framework version
            if (!Utils.IsSupportedRuntimeVersion())
            {
                if (DialogResult.OK == MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to {0} or later.", "4.7.2"),
                                                       "Shadowsocks Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error))
                {
                    Process.Start("https://dotnet.microsoft.com/download/dotnet-framework/net472");
                }
                return;
            }
            #endregion

            #region Event Handlers Setup
            Utils.ReleaseMemory(true);

            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            // handle UI exceptions
            Application.ThreadException += Application_ThreadException;
            // handle non-UI exceptions
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ApplicationExit   += Application_ApplicationExit;
            SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            AutoStartup.RegisterForRestart(true);
            #endregion

#if DEBUG
            // truncate privoxy log file while debugging
            string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
            if (File.Exists(privoxyLogFilename))
            {
                using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
            }
#endif
            MainController = new ShadowsocksController();
            MenuController = new MenuViewController(MainController);

            HotKeys.Init(MainController);
            MainController.Start();

            // Update online config
            Task.Run(async() =>
            {
                await Task.Delay(10 * 1000);
                await MainController.UpdateAllOnlineConfig();
            });

            #region IPC Handler and Arguement Process
            IPCService ipcService = new IPCService();
            Task.Run(() => ipcService.RunServer());
            ipcService.OpenUrlRequested += (_1, e) => MainController.AskAddServerBySSURL(e.Url);

            if (!string.IsNullOrWhiteSpace(Options.OpenUrl))
            {
                MainController.AskAddServerBySSURL(Options.OpenUrl);
            }
            #endregion

            Application.Run();
        }
 public KeyPressedEventArgs(HotKeys hotKeys)
 {
     HotKeys = hotKeys;
 }
Exemple #25
0
        static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(Application.StartupPath);
            // todo: initialize the NLog configuartion
            Model.NLogConfig.TouchAndApplyNLogConfig();

            // .NET Framework 4.7.2 on Win7 compatibility
            System.Net.ServicePointManager.SecurityProtocol |=
                System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

            // store args for further use
            Args = args;
            // Check OS since we are using dual-mode socket
            if (!Utils.IsWinVistaOrHigher())
            {
                MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Check .NET Framework version
            if (!Utils.IsSupportedRuntimeVersion())
            {
                if (DialogResult.OK == MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to {0} or later.", "4.7.2"),
                                                       "Shadowsocks Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error))
                {
                    //Process.Start("https://www.microsoft.com/download/details.aspx?id=53344");    // 4.6.2
                    Process.Start("https://dotnet.microsoft.com/download/dotnet-framework/net472");
                }
                return;
            }

            Utils.ReleaseMemory(true);
            using (Mutex mutex = new Mutex(false, $"Global\\Shadowsocks_{Application.StartupPath.GetHashCode()}"))
            {
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                // handle UI exceptions
                Application.ThreadException += Application_ThreadException;
                // handle non-UI exceptions
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.ApplicationExit   += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                AutoStartup.RegisterForRestart(true);

                if (!mutex.WaitOne(0, false))
                {
                    Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
                    if (oldProcesses.Length > 0)
                    {
                        Process oldProcess = oldProcesses[0];
                    }
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.")
                                    + Environment.NewLine
                                    + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                                    I18N.GetString("Shadowsocks is already running."));
                    return;
                }
                Directory.SetCurrentDirectory(Application.StartupPath);

#if DEBUG
                // truncate privoxy log file while debugging
                string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
                if (File.Exists(privoxyLogFilename))
                {
                    using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
                }
#endif
                MainController = new ShadowsocksController();
                MenuController = new MenuViewController(MainController);

                HotKeys.Init(MainController);
                MainController.Start();
                Application.Run();
            }
        }
Exemple #26
0
    public void setHotKeys(GameObject hotkey)
    {
        Debug.Log("Selected slot name " + selectedSlot.name);
        if (selectedSlot.item != null)
        {
            HotKeys chosen_hotkey_component = hotkey.GetComponentInChildren <HotKeys> ();

            List <GameObject> hotkey_list = new List <GameObject> ();
            hotkey_list.Add(this.hotKey1);
            hotkey_list.Add(this.hotKey2);
            hotkey_list.Add(this.hotKey3);

            string message       = "";
            int    hotkey_number = 1;
            foreach (GameObject hotkey_obj in hotkey_list)
            {
                HotKeys hotkey_component = hotkey_obj.GetComponentInChildren <HotKeys> ();
                if (hotkey_component.item != null)
                {
                    message += "Hotkey " + hotkey_number + " contains " + hotkey_component.item.m_ItemName.ToString();
                }
                else if (chosen_hotkey_component.gameObject == hotkey_obj &&
                         hotkey_component.item != null)
                {
                    message += "Chosen hotkey already occupied and contains " + hotkey_component.item.m_ItemName.ToString();
                }
                else
                {
                    message += "Hotkey " + hotkey_number + " empty.";
                }
                message += "\n";
                hotkey_number++;
            }
            Debug.Log(message);



            ItemSlot currentSlot = selectedSlot.GetComponent <ItemSlot> ();
            //for every hotkey...
            foreach (GameObject hotkey_obj in hotkey_list)
            {
                HotKeys hotkey_component = hotkey_obj.GetComponentInChildren <HotKeys> ();
                //if the item we're trying to assign to a hotkey is already in the hotkey...
                ItemClass item_in_hotkey = hotkey_component.item;
                if (item_in_hotkey != null &&
                    item_in_hotkey.m_ItemName.ToString() == currentSlot.item.m_ItemName.ToString())
                {
                    //then empty that hotkey...
                    this.RemoveHotKeyContents(hotkey_obj);
                }
            }

            //And assign the item in question
            Debug.Log("Current slot item name: " + currentSlot.item.m_ItemName.ToString());
            if (hotkey.GetComponentInChildren <HotKeys> ().item != null)
            {
                Debug.Log("Hotkey item name: " + hotkey.GetComponentInChildren <HotKeys> ().item.m_ItemName.ToString());
            }
            hotkey.GetComponentInChildren <HotKeys> ().item = currentSlot.item;
            GameObject imageUI = hotkey.GetComponentInChildren <HotKeys> ().gameObject;
            imageUI.GetComponent <Image> ().sprite       = currentSlot.getItemSprite();
            hotkey.GetComponentInChildren <Text> ().text = currentSlot.getText().text;
        }
        else
        {
            Debug.Log("This slot is empty");
            m_audioSource.PlayOneShot(GetComponent <MenuSounds> ().getErrorSound());
        }
    }
Exemple #27
0
        private bool toggle_modifier(HotKeys.KeyModifier which, bool state)
        {
            if (state)
              {
            key_mask.Modifier |= which;
              }
              else
              {
            key_mask.Modifier = key_mask.Modifier & ((HotKeys.KeyModifier)0xFFFF ^ which);
              }

              return (key_mask.Modifier & which) != 0;
        }
        // This is run when Jogging Keyboard Focus is Focused
        private void Jogging_KeyDown(object sender, KeyEventArgs e)
        {
            if (!machine.Connected)
            {
                return;
            }

            // Get Keycode
            string currentHotPressed = HotKeys.KeyProcess(sender, e); // Get Keycode

            if (currentHotPressed == null)
            {
                return;                            // If currentHotPressed is null, Return (to avoid continuing with  blank)
            }
            if (!CheckBoxEnableJog.IsChecked.Value)
            {
                return;
            }

            e.Handled = e.Key != Key.Tab;

            if (e.IsRepeat)
            {
                return;
            }

            if (machine.BufferState > 0 || machine.Status != "Idle")
            {
                return;
            }

            string direction = null;

            if (currentHotPressed == HotKeys.hotkeyCode["JogXPos"])
            {
                direction = "X";
            }
            else if (currentHotPressed == HotKeys.hotkeyCode["JogXNeg"])
            {
                direction = "X-";
            }
            else if (currentHotPressed == HotKeys.hotkeyCode["JogYPos"])
            {
                direction = "Y";
            }
            else if (currentHotPressed == HotKeys.hotkeyCode["JogYNeg"])
            {
                direction = "Y-";
            }
            else if (currentHotPressed == HotKeys.hotkeyCode["JogZPos"])
            {
                direction = "Z";
            }
            else if (currentHotPressed == HotKeys.hotkeyCode["JogZNeg"])
            {
                direction = "Z-";
            }
            else if (currentHotPressed == HotKeys.hotkeyCode["RTOrigin"]) // Return to Origin ie back to all axis Zero position
            {
                ButtonManualReturnToZero.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            }
            else if (currentHotPressed == HotKeys.hotkeyCode["FSStop"]) // Jog Cancel
            {
                machine.JogCancel();
            }

            if (direction != null)
            {
                manualJogSendCommand(direction);
            }
        }
Exemple #29
0
 public HotKeyViewModel(KeyManager manager, AppSettings settings)
 {
     KeyManager        = manager;
     _settings         = settings;
     _lastValidHotkeys = HotKeys.Clone();
 }
Exemple #30
0
        static void Main(string[] args)
        {
            //string TheProxyModeInLaunching;
            if (Utils.IsVirusExist())
            {
                return;
            }
#if !_CONSOLE
                foreach (string arg in args)
            {
                if (arg == "--setautorun")
                {
                    if (!AutoStartup.Switch())
                    {
                        Environment.ExitCode = 1;
                    }
                    return;
                }
            }

            using (Mutex mutex = new Mutex(false, "Global\\ShadowsocksR_" + Application.StartupPath.GetHashCode()))
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.EnableVisualStyles();
                Application.ApplicationExit += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.SetCompatibleTextRenderingDefault(false);
                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + "\n" +
                        I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                        I18N.GetString("ShadowsocksR is already running."));
                    return;
                }
#endif
                Directory.SetCurrentDirectory(Application.StartupPath);

#if !_CONSOLE
                int try_times = 0;
                while (Configuration.Load() == null)
                {
                    if (try_times >= 5)
                        return;
                    using (InputPassword dlg = new InputPassword())
                    {
                        if (dlg.ShowDialog() == DialogResult.OK)
                            Configuration.SetPassword(dlg.password);
                        else
                            return;
                    }
                    try_times += 1;
                }
                if (try_times > 0)
                    Logging.save_to_file = false;
#endif
                //#if !DEBUG
                Logging.OpenLogFile();
                //#endif
                _controller = new ShadowsocksController();
                HostMap.Instance().LoadHostFile();

#if _DOTNET_4_0
                // Enable Modern TLS when .NET 4.5+ installed.
                if (EnvCheck.CheckDotNet45())
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
#endif
#if !_CONSOLE
                _viewController = new MenuViewController(_controller);
#endif
                HotKeys.Init();
                _controller.Start();

#if !_CONSOLE
                //Util.Utils.ReleaseMemory(true);

                foreach (string arg in args)
                {
                    if (arg == "-Direct")
                    {
                        _viewController.DirectItem_Click();
                        break;
                    }
                    else if(arg == "-Pac")
                    {
                        _viewController.PACModeItem_Click();
                        break;
                    }
                    else if(arg == "-Global")
                    {
                        _viewController.GlobalModeItem_Click();
                        break;
                    }
                }

                Application.Run();
            }
#else
            Console.ReadLine();
            _controller.Stop();
#endif
        }
 private void tbAutoClickerTriggerKeyboard_MouseDoubleClick(object sender, MouseButtonEventArgs e)
 {
     HotkeyTeachingMode = HotKeys.AutoClickerKeyboardTrigger;
 }
Exemple #32
0
 public bool ModifyMenuItem(MirandaPlugin owner, MenuItemDeclarationAttribute menuItem, string text, MenuItemProperties flags, Icon icon, HotKeys hotKey)
 {
     return ModifyMenuItem(owner, menuItem, text, flags, icon, hotKey, true);
 }
Exemple #33
0
        public bool ModifyMenuItem(MirandaPlugin owner, MenuItemDeclarationAttribute menuItem, string text, MenuItemProperties flags, Icon icon, HotKeys hotKey, bool updateItemDescriptor)
        {
            if (owner == null)
                throw new ArgumentNullException("owner");

            if (menuItem == null)
                throw new ArgumentNullException("menuItem");

            if (menuItem.MirandaHandle == IntPtr.Zero)
                throw new ArgumentException("Invalid menu item handle.");

            UnmanagedStructHandle<CLISTMENUITEM> nativeHandle = UnmanagedStructHandle<CLISTMENUITEM>.Empty;

            try
            {
                SynchronizationHelper.BeginMenuItemUpdate(menuItem);

                CLISTMENUITEM nativeItem = new CLISTMENUITEM(owner, menuItem);
                MenuItemModifyFlags modifyFlags = MenuItemModifyFlags.None;

                if (text != null)
                {
                    modifyFlags |= MenuItemModifyFlags.CMIM_NAME;
                    nativeItem.Text = text;

                    if (updateItemDescriptor) menuItem.Text = text;
                }
                if (flags != MenuItemProperties.KeepCurrent)
                {
                    modifyFlags |= MenuItemModifyFlags.CMIM_FLAGS;
                    nativeItem.Flags = (uint)flags;

                    if (updateItemDescriptor) menuItem.Flags = flags;
                }
                if (icon != null)
                {
                    modifyFlags |= MenuItemModifyFlags.CMIM_ICON;
                    nativeItem.Icon = icon.Handle;
                }
                if (hotKey != 0)
                {
                    modifyFlags |= MenuItemModifyFlags.CMIM_HOTKEY;
                    nativeItem.HotKey = (uint)hotKey;
                    if (updateItemDescriptor) menuItem.HotKey = hotKey;
                }

                nativeItem.Flags |= (uint)modifyFlags;

                nativeHandle = new UnmanagedStructHandle<CLISTMENUITEM>(ref nativeItem);
                bool result = MirandaContext.Current.CallService(MirandaServices.MS_CLIST_MODIFYMENUITEM, (UIntPtr)(uint)menuItem.MirandaHandle, nativeHandle.IntPtr) == 0
                    ? true : false;

                Debug.Assert(result);
                return result;
            }
            catch (Exception e)
            {
                throw new MirandaException(TextResources.ExceptionMsg_ErrorWhileCallingMirandaService + e.Message, e);
            }
            finally
            {
                nativeHandle.Free();
                SynchronizationHelper.EndUpdate(menuItem);
            }
        }
Exemple #34
0
        private IntPtr LowLevelKeyboardProc(int nCode,
                                            IntPtr wParam,
                                            IntPtr lParam)
        {
            if (nCode < 0)
            {
                return(CallNextHookEx(_windowsHookHandle,
                                      nCode,
                                      wParam,
                                      lParam));
            }

            var wparamTyped = wParam.ToInt32();

            // TODO: Invoke KeyboardPressed

            if (Enum.IsDefined(typeof(KeyboardState),
                               wparamTyped))
            {
                KeyboardState kbState = (KeyboardState)wparamTyped;
                LowLevelKeyboardInputEvent kbEvent = (LowLevelKeyboardInputEvent)Marshal.PtrToStructure(lParam,
                                                                                                        typeof(LowLevelKeyboardInputEvent));

                if (kbState == KeyboardState.KeyDown || kbState == KeyboardState.SysKeyDown)
                {
                    var hkReg = HotKeys.SafeGet(
                        new HotKey(
                            kbEvent.Key,
                            GetCtrlPressed(), GetAltPressed(), GetShiftPressed(), GetMetaPressed())
                        );

                    if (hkReg != null)
                    {
                        bool scopeMatches = true;

                        if (hkReg.Scope != HotKeyScope.Global)
                        {
                            var foregroundWdwHandle = GetForegroundWindow();

                            // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                            if (foregroundWdwHandle == null || foregroundWdwHandle == IntPtr.Zero)
                            {
                                scopeMatches = false;
                            }

                            else if (hkReg.Scope == HotKeyScope.SMBrowser && foregroundWdwHandle != _elWdwHandle)
                            {
                                scopeMatches = false;
                            }

                            else if (hkReg.Scope == HotKeyScope.SM)
                            {
                                GetWindowThreadProcessId(foregroundWdwHandle, out var foregroundProcId);

                                if (foregroundProcId != _smProcessId)
                                {
                                    scopeMatches = false;
                                }
                            }
                        }

                        if (scopeMatches)
                        {
                            TriggeredCallbacks.Enqueue(hkReg.Callback);
                            TriggeredEvent.Set();

                            return((IntPtr)1);
                        }
                    }
                }
            }

            return(CallNextHookEx(_windowsHookHandle,
                                  nCode,
                                  wParam,
                                  lParam));
        }
Exemple #35
0
        static void Main()
        {
            // Check OS since we are using dual-mode socket
            if (!Utils.IsWinVistaOrHigher())
            {
                MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Check .NET Framework version
            if (!Utils.IsSupportedRuntimeVersion())
            {
                MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to 4.6.2 or later."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                Process.Start(
                    "http://dotnetsocial.cloudapp.net/GetDotnet?tfm=.NETFramework,Version=v4.6.2");
                return;
            }

            Utils.ReleaseMemory(true);
            using (Mutex mutex = new Mutex(false, $"Global\\Shadowsocks_{Application.StartupPath.GetHashCode()}"))
            {
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                // handle UI exceptions
                Application.ThreadException += Application_ThreadException;
                // handle non-UI exceptions
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.ApplicationExit   += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
                    if (oldProcesses.Length > 0)
                    {
                        Process oldProcess = oldProcesses[0];
                    }
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.")
                                    + Environment.NewLine
                                    + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                                    I18N.GetString("Shadowsocks is already running."));
                    return;
                }
                Directory.SetCurrentDirectory(Application.StartupPath);
#if DEBUG
                Logging.OpenLogFile();

                // truncate privoxy log file while debugging
                string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
                if (File.Exists(privoxyLogFilename))
                {
                    using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
                }
#else
                Logging.OpenLogFile();
#endif
                MainController = new ShadowsocksController();
                MenuController = new MenuViewController(MainController);
                HotKeys.Init(MainController);
                MainController.Start();
                Application.Run();
            }
        }
Exemple #36
0
 public void UpdateHotkeys(HotKeys hotkeys)
 {
     this.hotKey = hotkeys;
     FileManager.FileInstence.UpdateHotkey(hotkeys);
 }
 private void textboxHotkeyRepeater_MouseDoubleClick(object sender, MouseButtonEventArgs e)
 {
     HotkeyTeachingMode = HotKeys.Repeater;
 }
        private static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(Application.StartupPath);
            // todo: initialize the NLog configuartion
            Model.NLogConfig.TouchAndApplyNLogConfig();

            // .NET Framework 4.7.2 on Win7 compatibility
            ServicePointManager.SecurityProtocol |=
                SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            // store args for further use
            Args = args;
            // Check OS since we are using dual-mode socket
            if (!Utils.IsWinVistaOrHigher())
            {
                MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Check .NET Framework version
            if (!Utils.IsSupportedRuntimeVersion())
            {
                if (DialogResult.OK == MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to {0} or later.", "4.7.2"),
                                                       "Shadowsocks Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error))
                {
                    Process.Start("https://dotnet.microsoft.com/download/dotnet-framework/net472");
                }
                return;
            }
            string pipename = $"Shadowsocks\\{Application.StartupPath.GetHashCode()}";

            string addedUrl = null;

            using (NamedPipeClientStream pipe = new NamedPipeClientStream(pipename))
            {
                bool pipeExist = false;
                try
                {
                    pipe.Connect(10);
                    pipeExist = true;
                }
                catch (TimeoutException)
                {
                    pipeExist = false;
                }

                // TODO: switch to better argv parser when it's getting complicate
                List <string> alist = Args.ToList();
                // check --open-url param
                int urlidx = alist.IndexOf("--open-url") + 1;
                if (urlidx > 0)
                {
                    if (Args.Length <= urlidx)
                    {
                        return;
                    }

                    // --open-url exist, and no other instance, add it later
                    if (!pipeExist)
                    {
                        addedUrl = Args[urlidx];
                    }
                    // has other instance, send url via pipe then exit
                    else
                    {
                        byte[] b        = Encoding.UTF8.GetBytes(Args[urlidx]);
                        byte[] opAddUrl = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(1));
                        byte[] blen     = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(b.Length));
                        pipe.Write(opAddUrl, 0, 4); // opcode addurl
                        pipe.Write(blen, 0, 4);
                        pipe.Write(b, 0, b.Length);
                        pipe.Close();
                        return;
                    }
                }
                // has another instance, and no need to communicate with it return
                else if (pipeExist)
                {
                    Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
                    if (oldProcesses.Length > 0)
                    {
                        Process oldProcess = oldProcesses[0];
                    }
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.")
                                    + Environment.NewLine
                                    + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                                    I18N.GetString("Shadowsocks is already running."));
                    return;
                }
            }

            Utils.ReleaseMemory(true);

            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            // handle UI exceptions
            Application.ThreadException += Application_ThreadException;
            // handle non-UI exceptions
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ApplicationExit   += Application_ApplicationExit;
            SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            AutoStartup.RegisterForRestart(true);

            Directory.SetCurrentDirectory(Application.StartupPath);

#if DEBUG
            // truncate privoxy log file while debugging
            string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
            if (File.Exists(privoxyLogFilename))
            {
                using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
            }
#endif
            MainController = new ShadowsocksController();
            MenuController = new MenuViewController(MainController);

            HotKeys.Init(MainController);
            MainController.Start();

            NamedPipeServer namedPipeServer = new NamedPipeServer();
            Task.Run(() => namedPipeServer.Run(pipename));
            namedPipeServer.AddUrlRequested += (_1, e) => MainController.AskAddServerBySSURL(e.Url);
            if (!addedUrl.IsNullOrEmpty())
            {
                MainController.AskAddServerBySSURL(addedUrl);
            }
            Application.Run();
        }
Exemple #39
0
 public bool UnregisterHotKey(HotKey hotkey)
 {
     return(HotKeys.TryRemove(hotkey,
                              out _));
 }
Exemple #40
0
 public bool ModifyMenuItem(MirandaPlugin owner, MenuItemDeclarationAttribute menuItem, HotKeys hotKey)
 {
     return ModifyMenuItem(owner, menuItem, null, MenuItemProperties.None, null, hotKey, true);
 }
Exemple #41
0
        static void Main(string[] args)
        {
            BimtRemoting.RegeistChanel();
            bool ok = true;

            //Utils.IsVip(ref ok, args);
            //if (!ok)
            //{
            //    return;
            //}
            LoadBimtProxySetting();
            // Check OS since we are using dual-mode socket
            //为了xp拼了
            if (!Utils.IsWinVistaOrHigher())
            {
                MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
                //BimtProxyService<ProxyEntity> proxy = new BimtProxyService<ProxyEntity>(ProxyEntity.URL);
                //proxy.Entity.StartUp();
                //BIMTClassLibrary.frmGoogleSearch frm = new BIMTClassLibrary.frmGoogleSearch();
                //frm.Show();
                //Application.Run();
            }
            else
            {
                Utils.ReleaseMemory(true);
                using (Mutex mutex = new Mutex(false, $"Global\\Shadowsocks_{Application.StartupPath.GetHashCode()}"))
                {
                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                    // handle UI exceptions
                    Application.ThreadException += Application_ThreadException;
                    // handle non-UI exceptions
                    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                    Application.ApplicationExit   += Application_ApplicationExit;
                    SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    if (!mutex.WaitOne(0, false))
                    {
                        Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
                        if (oldProcesses.Length > 0)
                        {
                            Process oldProcess = oldProcesses[0];
                        }
                        MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.")
                                        + Environment.NewLine
                                        + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                                        I18N.GetString("Shadowsocks is already running."));
                        return;
                    }
                    Directory.SetCurrentDirectory(Application.StartupPath);
#if DEBUG
                    Logging.OpenLogFile();

                    // truncate privoxy log file while debugging
                    string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
                    if (File.Exists(privoxyLogFilename))
                    {
                        using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
                    }
#else
                    Logging.OpenLogFile();
#endif
                    _controller     = new ShadowsocksController();
                    _viewController = new MenuViewController(_controller);
                    HotKeys.Init();
                    _controller.Start();
                    string   path = string.Format("{0}\\SmartReader.View.exe", Application.StartupPath);
                    string[] arg  = new string[2];
                    //arg[0] = User.GetInstance().IsVip().ToString();
                    //arg[1] = User.GetInstance().Id;
                    StartProcess(path, args);
                    Application.Run();
                }
            }
        }
Exemple #42
0
        public bool SetHotkeyCombination(HotKeys hotkeys, AudioDeviceType deviceType)
        {
            using (AppLogger.Log.InfoCall())
            {
                HotKeys confHotKeys = null;
                switch (deviceType)
                {
                    case AudioDeviceType.Playback:
                        confHotKeys = AppConfigs.Configuration.PlaybackHotKeys;
                        break;
                    case AudioDeviceType.Recording:
                        confHotKeys = AppConfigs.Configuration.RecordingHotKeys;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException(nameof(deviceType), deviceType, null);
                }
                AppLogger.Log.Info("Unregister previous hotkeys", confHotKeys);
                WindowsAPIAdapter.UnRegisterHotKey(confHotKeys);

                if (!WindowsAPIAdapter.RegisterHotKey(hotkeys))
                {
                    AppLogger.Log.Warn("Can't register new hotkeys", hotkeys);
                    ErrorTriggered?.Invoke(this, new ExceptionEvent(new Exception("Impossible to register HotKey: " + hotkeys)));
                    return false;
                }

                AppLogger.Log.Info("New Hotkeys registered", hotkeys);
                switch (deviceType)
                {
                    case AudioDeviceType.Playback:
                        AppConfigs.Configuration.PlaybackHotKeys = hotkeys;
                        break;
                    case AudioDeviceType.Recording:
                        AppConfigs.Configuration.RecordingHotKeys = hotkeys;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException(nameof(deviceType), deviceType, null);
                }
                AppConfigs.Configuration.Save();
                return true;
            }
        }
 /// <summary>
 ///     Unregister a registered HotKey
 /// </summary>
 /// <param name="hotKeys"></param>
 /// <returns></returns>
 public static bool UnRegisterHotKey(HotKeys hotKeys)
 {
     lock (_instance)
     {
         return (bool) _instance.Invoke(new Func<bool>(() =>
         {
             int id;
             if (!_instance._registeredHotkeys.TryGetValue(hotKeys, out id))
             {
                 return false;
             }
             _instance._registeredHotkeys.Remove(hotKeys);
             return NativeMethods.UnregisterHotKey(_instance.Handle, id);
         }));
     }
 }
 /// <summary>
 /// 注册热键
 /// </summary>
 /// <param name="winHandle">窗口句柄</param>
 /// <param name="id">待注册热键的识别ID</param>
 /// <param name="hotKeys">热键中的组合键:Ctrl, Alt, Shift或它们的组合</param>
 /// <param name="key">热键中的配合按键</param>
 /// <returns>假如注册成功,返回true,否则返回false</returns>
 public static bool Register(IntPtr winHandle, int id, HotKeys hotKeys, Keys key)
 {
     return(RegisterHotKey(winHandle, id, (uint)hotKeys, (int)key));
 }
        /// <summary>
        ///     Registers a HotKey in the system.
        /// </summary>
        /// <param name="hotKeys">Represent the hotkey to register</param>
        public static bool RegisterHotKey(HotKeys hotKeys)
        {
            lock (_instance)
            {
                return (bool) _instance.Invoke(new Func<bool>(() =>
                {
                    if (_instance._registeredHotkeys.ContainsKey(hotKeys))
                        return false;

                    var id = _instance._hotKeyId++;
                    _instance._registeredHotkeys.Add(hotKeys, id);
                    // register the hot key.
                    return NativeMethods.RegisterHotKey(_instance.Handle, id, (uint) hotKeys.Modifier,
                        (uint) hotKeys.Keys);
                }));
            }
        }
        private void RegisterHotKeys()
        {
            m_hotKeys = new HotKeys();
            m_hotKeys.KeyPressed += new EventHandler<KeyPressedEventArgs>(m_mainForm.ShowHide);

            bool alt = Minder.Static.StaticData.Settings.NewTaskHotkey.Alt;
            bool shift = Minder.Static.StaticData.Settings.NewTaskHotkey.Shift;
            bool ctrl = Minder.Static.StaticData.Settings.NewTaskHotkey.Ctrl;
            bool win = Minder.Static.StaticData.Settings.NewTaskHotkey.Win;
            string keyString = Minder.Static.StaticData.Settings.NewTaskHotkey.Key;
            Keys key = Keys.Decimal;
            Minder.Static.StaticData.Settings.NewTaskHotkey.KeysDic.TryGetValue(keyString, out key);

            // Nesu 100% tikras, kad gerai veikia - bet standartinis atvejis veikia
            // o kodas daug aiškesnis ir lengviau taisomas
            Core.Tools.GlobalHotKeys.ModifierKeys hotKey = new Core.Tools.GlobalHotKeys.ModifierKeys();
            if (alt)
                hotKey = hotKey | Core.Tools.GlobalHotKeys.ModifierKeys.Alt;
            if (shift)
                hotKey = hotKey | Core.Tools.GlobalHotKeys.ModifierKeys.Shift;
            if (ctrl)
                hotKey = hotKey | Core.Tools.GlobalHotKeys.ModifierKeys.Control;
            if (win)
                hotKey = hotKey | Core.Tools.GlobalHotKeys.ModifierKeys.Win;

            m_hotKeys.RegisterHotKey(hotKey, key);
            //			m_form.MTextBox.KeyDown += KeyPressed;
            m_mainForm.MTextBox.KeyDown += KeyPressed;
        }