Example #1
0
File: HotKey.cs Project: Jitlee/LPS
        Window Window; //热键所在窗体

        #endregion Fields

        #region Constructors

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="win">注册窗体</param>
        /// <param name="control">控制键</param>
        /// <param name="key">主键</param>
        public HotKey(Window win, HotKey.KeyFlags control, Keys key)
        {
            Handle = new WindowInteropHelper(win).Handle;
            Window = win;
            ControlKey = (uint)control;
            Key = (uint)key;
            KeyId = (int)ControlKey + (int)Key * 10;

            if (HotKey.KeyPair.ContainsKey(KeyId))
            {
                throw new Exception("热键已经被注册!");
            }

            //注册热键
            if (false == HotKey.RegisterHotKey(Handle, KeyId, ControlKey, Key))
            {
                throw new Exception("热键注册失败!");
            }

            //消息挂钩只能连接一次!!
            if (HotKey.KeyPair.Count == 0)
            {
                if (false == InstallHotKeyHook(this))
                {
                    throw new Exception("消息挂钩连接失败!");
                }
            }
            if (HotKey.KeyPair.Count > 0)
                HotKey.KeyPair.Clear();
            HotKey.KeyPair.Clear();
            //添加这个热键索引
            HotKey.KeyPair.Add(KeyId, this);
        }
 public MainWindow()
 {
     InitializeComponent();
     core = (AppCoreModel)DataContext;
     CompositionTarget.Rendering += CheckForNonActive;
     var hotKey = new HotKey(Key.Space, KeyModifier.Alt, OnHotKeyHandler);
 }
        public OptionsWindow()
        {
            InitializeComponent();

            // Show what's already selected
            _hotkey = (HotKey) Application.Current.Properties["hotkey"];

            try
            {
                _hotkey.LoadSettings();
            }
            catch (HotkeyAlreadyInUseException)
            {
            }

            _hotkeyViewModel = new HotkeyViewModel
            {
                KeyCode = KeyInterop.KeyFromVirtualKey((int) _hotkey.KeyCode),
                Alt = _hotkey.Alt,
                Ctrl = _hotkey.Ctrl,
                Windows = _hotkey.WindowsKey,
                Shift = _hotkey.Shift
            };

            HotkeyPreview.Text = _hotkeyViewModel.ToString();
            AltTabCheckBox.IsChecked = Settings.Default.AltTabHook;
        }
 private async Task<string> Start()
 {
     DatabaseManager.SetDBLocation(AppDomain.CurrentDomain.BaseDirectory + "FilesData.sqlite");
     //SharedHelper.KillProcess("CurtInstaller");
     SharedHelper.DeleteDirectory(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\tmp");           
     TextBar1.Focus();
     //Startup.RemoveStartup();
     Key key;
     Enum.TryParse(ConfigurationManager.AppSettings["Key"], out key);
     KeyModifier keyMod;
     Enum.TryParse(ConfigurationManager.AppSettings["KeyMod"], out keyMod);
     HotKey _hotKey = new HotKey(key, keyMod, OnHotKeyHandler);
     Startup.SetStartup();        
     filesIcons = new Dictionary<int, BitmapSource>();
     TaskBarWindow taskBar = new TaskBarWindow();
     WindowWatcher.AddWindow(taskBar);
     var commandList = DatabaseManager.SelectFromCommandsTable("");
     if (commandList.Count == 0)
     {
         commandList.Add(new Command { Name = "-Outlook", Path = "https://Outlook.com" });
         commandList.Add(new Command { Name = "-Asana", Path = "https://Asana.com" });
         commandList.Add(new Command { Name = "-Gmail", Path = "https://Gmail.com" });
         commandList.Add(new Command { Name = "-Visual Studio", Path = @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe" });
         DatabaseManager.WriteCommandsTable(commandList);
     }
     return "";
 }
Example #5
0
        /// <summary>
        /// Initialize key combination registration and attach it to reffered window
        /// </summary>
        /// <param name="attachedWindow">Window to attach key combination (for example MainWindow)</param>
        public void Init(Window attachedWindow)
        {
            DataContext = attachedWindow.DataContext;

            _hotKey = new HotKey(ModifierKey, Key, attachedWindow);
            _hotKey.HotKeyPressed += HotKeyOnHotKeyPressed;
        }
Example #6
0
 public void RegistHotKey()
 {
     // キーインプットのON/OFF
     hotKey_K = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.K);
     hotKey_K.HotKeyPush += new EventHandler(hotKey_HotKeyPush);
     // Z キー押すだけ
     hotKey_Z = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.Z);
     hotKey_Z.HotKeyPush += new EventHandler(hotKey_HotKeyPush);
     // オートショットON/OFF
     hotKey_A = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.A);
     hotKey_A.HotKeyPush += new EventHandler(hotKey_HotKeyPush);
     // 初期化
     hotKey_I = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.I);
     hotKey_I.HotKeyPush += new EventHandler(hotKey_HotKeyPush);
     // テキストボックスのログ消去
     hotKey_D = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.D);
     hotKey_D.HotKeyPush += new EventHandler(hotKey_HotKeyPush);
     // ユーザ切り替え用
     hotKey_User[0] = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.D0);
     hotKey_User[1] = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.D1);
     hotKey_User[2] = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.D2);
     hotKey_User[3] = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.D3);
     hotKey_User[4] = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.D4);
     hotKey_User[5] = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.D5);
     hotKey_User[6] = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.D6);
     hotKey_User[7] = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.D7);
     hotKey_User[8] = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.D8);
     hotKey_User[9] = new HotKey(MOD_KEY.CONTROL | MOD_KEY.ALT | MOD_KEY.NOREPEAT, Keys.D9);
     for (int i = 0; i < Settings.MAX_USER_COUNT; i++ )
     {
         hotKey_User[i].HotKeyPush += new EventHandler(hotKey_HotKeyPush);
     }
 }
Example #7
0
 private void OnHotKeyHandler(HotKey hotKey)
 {
     Show();
     WindowState = WindowState.Normal;
     Activate();
     InputLanguageManager.SetInputLanguage(_ExpressionBox, CultureInfo.CreateSpecificCulture("en"));
     _ExpressionBox.SelectAll();
 }
Example #8
0
 public static string HotKeyName(HotKey hotkey)
 {
     if (hotkey.Modifier != -1 && hotkey.Modifier != 0) {
         return string.Format ("<{0}>+{1}", NameFromKeyval ((uint)hotkey.Modifier),
                               NameFromKeyval ((uint)hotkey.Key));
     } else {
         return string.Format ("{0}", NameFromKeyval ((uint)hotkey.Key));
     }
 }
Example #9
0
 public void TestDefined()
 {
     HotKey hk = new HotKey ();
     Assert.IsFalse (hk.Defined);
     hk.Key = 2;
     Assert.IsTrue (hk.Defined);
     hk.Key = -1;
     hk.Modifier = 1;
     Assert.IsFalse (hk.Defined);
 }
Example #10
0
 public DashboardButton()
 {
     Name = "";
     Position = new Point (0, 0);
     Width = Constants.BUTTON_WIDTH;
     Height = Constants.BUTTON_HEIGHT;
     BackgroundColor = Color.Red;
     TextColor = Config.Style.PaletteBackgroundLight;
     HotKey = new HotKey ();
     ActionLinks = new List<ActionLink> ();
 }
Example #11
0
 public void TestEquality()
 {
     HotKey k1 = new HotKey {Key = 1, Modifier = 2};
     HotKey k2 = new HotKey {Key = 1, Modifier = 3};
     Assert.AreNotEqual (k1, k2);
     Assert.IsTrue (k1 != k2);
     Assert.IsFalse (k1 == k2);
     k2.Modifier = 2;
     Assert.AreEqual (k1, k2);
     Assert.IsFalse (k1 != k2);
     Assert.IsTrue (k1 == k2);
 }
Example #12
0
        public void TestSerialization()
        {
            HotKey hk = new HotKey ();
            hk.Key = 2;
            hk.Modifier = 3;

            Utils.CheckSerialization (hk);

            HotKey hk2 = Utils.SerializeDeserialize (hk);
            Assert.AreEqual (hk.Key, hk2.Key);
            Assert.AreEqual (hk.Modifier, hk2.Modifier);
        }
Example #13
0
        private void InitializeHotKeys()
        {
            var kc = new SWF.KeysConverter();
            var mkc = new ModifierKeysConverter();

            _sshHotkey = new HotKey((ModifierKeys)mkc.ConvertFromString(_config.Hotkeys.Select.Modifiers), (SWF.Keys)kc.ConvertFromString(_config.Hotkeys.Select.Key));
            _sshHotkey.HotKeyPressed += k => ((MainWindow)this.MainWindow).ShowFullscreenWindow();

            Exit += (s, e) =>
            {
                _sshHotkey.Dispose();
            };
        }
Example #14
0
 private void KeyPressed(HotKey k)
 {
     if (_window.WindowState == WindowState.Minimized)
     {
         _window.Show();
         _window.Activate();
         _window.WindowState = WindowState.Normal;
     }
     else
     {
         _window.WindowState = WindowState.Minimized;
         _window.Hide();
     }
 }
        protected override bool OnKeyPressEvent(Gdk.EventKey evnt)
        {
            if (evnt.Key == Gdk.Key.Escape || evnt.Key == Gdk.Key.Return) {
                return base.OnKeyPressEvent (evnt);
            }

            if (IsSupportedModifier (evnt.Key)) {
                return true;
            }

            hotKey = App.Current.Keyboard.ParseEvent (evnt);
            Respond (ResponseType.Ok);
            return true;
        }
Example #16
0
 public HotKeyMainWindows(Window window, ModifierKeys modifierKeys, Keys key)
 {
     try
     {
         _window = window;
         _hotkey = new HotKey(modifierKeys, key, _window);
         _hotkey.HotKeyPressed += KeyPressed;
         _window.Closed += (sender, args) => { Dispose(); };
     }
     catch (Exception ex)
     {
         var msg = "Error Global HotKey Registered";
         Log.Error(msg, ex);
         System.Windows.MessageBox.Show(ex.Message, msg, MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Example #17
0
        public GameEditor(GameScene scene)
        {
            actions = new ActionStack();
            gameScene = scene;

            hotkeys1 = new List<HotKey>();
            KeyboardManager.Manager.AddKeyboardUser(this);
            var ctrlz = new HotKey(new[] { Keys.LeftControl, Keys.Z }, revertAction);
            hotkeys1.Add(ctrlz);
            var biggerarrows = new HotKey(new[] { Keys.OemPlus }, biggerArrows);
            hotkeys1.Add(biggerarrows);
            var smallerarrows = new HotKey(new[] { Keys.OemMinus }, smallerArrows);
            hotkeys1.Add(smallerarrows);
            var deleteobjects = new HotKey(new[] { Keys.Delete }, DeleteSelectedObjects);
            hotkeys1.Add(deleteobjects);
            activeObject = new ObjectContainer();
        }
Example #18
0
        public void AddWidget(KeyAction action, string desc, HotKey key, int position)
        {
            uint row_top, row_bottom, col_left, col_right;
            HBox box;
            Label descLabel, keyLabel;
            Button edit;
            Gtk.Image editImage;

            box = new HBox ();
            box.Spacing = 5;
            descLabel = new Label ();
            descLabel.Markup = String.Format ("<b>{0}</b>", desc);
            keyLabel = new Label ();
            keyLabel.Markup = GLib.Markup.EscapeText (key.ToString());
            edit = new Button ();
            editImage = new Gtk.Image (LongoMatch.Gui.Helpers.Misc.LoadIcon ("longomatch-pencil", 24));
            edit.Add (editImage);
            box.PackStart (descLabel, true, true, 0);
            box.PackStart (keyLabel, false, true, 0);
            box.PackStart (edit, false, true, 0);
            box.ShowAll ();

            sgroup.AddWidget (keyLabel);
            descLabel.Justify = Justification.Left;
            descLabel.SetAlignment (0f, 0.5f);
            edit.Clicked += (sender, e) => {
                HotKey hotkey = Config.GUIToolkit.SelectHotkey (key);
                if (hotkey != null) {
                    if (Config.Hotkeys.ActionsHotkeys.ContainsValue (hotkey)) {
                        Config.GUIToolkit.ErrorMessage (Catalog.GetString ("Hotkey already in use: ") +
                                                        GLib.Markup.EscapeText (hotkey.ToString()), this);
                    } else {
                        Config.Hotkeys.ActionsHotkeys[action] = hotkey;
                        Config.Save ();
                        keyLabel.Markup = GLib.Markup.EscapeText (hotkey.ToString());
                    }
                }
            };

            row_top = (uint)(position / table.NColumns);
            row_bottom = (uint)row_top + 1;
            col_left = (uint)position % table.NColumns;
            col_right = (uint)col_left + 1;
            table.Attach (box, col_left, col_right, row_top, row_bottom);
        }
Example #19
0
		private void Form1_Load(object sender, EventArgs e)
		{
			//ウィンドウの名前変更
			Text = "CBExtension (" + pre + ")";

			textbox = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8, textBox9 };

			Pres();
			Pre1();

			HotKey c1 = new HotKey(MOD_KEY.CONTROL, Keys.D1);
			HotKey c2 = new HotKey(MOD_KEY.CONTROL, Keys.D2);
			HotKey c3 = new HotKey(MOD_KEY.CONTROL, Keys.D3);
			HotKey c4 = new HotKey(MOD_KEY.CONTROL, Keys.D4);
			HotKey c5 = new HotKey(MOD_KEY.CONTROL, Keys.D5);
			HotKey c6 = new HotKey(MOD_KEY.CONTROL, Keys.D6);
			HotKey c7 = new HotKey(MOD_KEY.CONTROL, Keys.D7);
			HotKey c8 = new HotKey(MOD_KEY.CONTROL, Keys.D8);
			HotKey c9 = new HotKey(MOD_KEY.CONTROL, Keys.D9);

			HotKey a1 = new HotKey(MOD_KEY.ALT, Keys.D1);
			HotKey a2 = new HotKey(MOD_KEY.ALT, Keys.D2);
			HotKey a3 = new HotKey(MOD_KEY.ALT, Keys.D3);
			HotKey a4 = new HotKey(MOD_KEY.ALT, Keys.D4);
			HotKey a5 = new HotKey(MOD_KEY.ALT, Keys.D5);

			ctrl = new HotKey[] { c1, c2, c3, c4, c5, c6, c7, c8, c9 };
			alt = new HotKey[] { a1, a2, a3, a4, a5 };

			ctrl[0].HotKeyPush += new EventHandler(c1_push);
			ctrl[1].HotKeyPush += new EventHandler(c2_push);
			ctrl[2].HotKeyPush += new EventHandler(c3_push);
			ctrl[3].HotKeyPush += new EventHandler(c4_push);
			ctrl[4].HotKeyPush += new EventHandler(c5_push);
			ctrl[5].HotKeyPush += new EventHandler(c6_push);
			ctrl[6].HotKeyPush += new EventHandler(c7_push);
			ctrl[7].HotKeyPush += new EventHandler(c8_push);
			ctrl[8].HotKeyPush += new EventHandler(c9_push);

			alt[0].HotKeyPush += new EventHandler(a1_push);
			alt[1].HotKeyPush += new EventHandler(a2_push);
			alt[2].HotKeyPush += new EventHandler(a3_push);
			alt[3].HotKeyPush += new EventHandler(a4_push);
			alt[4].HotKeyPush += new EventHandler(a5_push);
		}
Example #20
0
        /// =================================
        #region Private Methods
        /// =================================
        private void SetUpHotKey()
        {
            _hotkey = new HotKey();
            _hotkey.LoadSettings();

            Application.Current.Properties["hotkey"] = _hotkey;

            _hotkey.HotkeyPressed += hotkey_HotkeyPressed;
            try
            {
                _hotkey.Enabled = true;
            }
            catch (HotkeyAlreadyInUseException)
            {
                var boxText = "The current hotkey for activating Switcheroo is in use by another program." +
                                     Environment.NewLine +
                                     Environment.NewLine +
                                     "You can change the hotkey by right-clicking the Switcheroo icon in the system tray and choosing 'Options'.";
                MessageBox.Show(boxText, "Hotkey already in use", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Example #21
0
        protected override bool OnKeyPressEvent(Gdk.EventKey evnt)
        {
            if (evnt.Key == Gdk.Key.Escape || evnt.Key == Gdk.Key.Return) {
                return base.OnKeyPressEvent (evnt);
            }

            if (IsSupportedModifier (evnt.Key)) {
                return true;
            }

            hotKey = Keyboard.ParseEvent (evnt);
            if (hotKey.Modifier != -1 && !IsSupportedModifier ((Gdk.Key)hotKey.Modifier)) {
                string msg = Keyboard.NameFromKeyval ((uint)hotKey.Modifier) +
                             Catalog.GetString ("is not a valid key modifier: Alt, Shift or Ctrl");
                Config.GUIToolkit.WarningMessage (msg, this);
                hotKey = null;
                return true;
            }
            Respond (ResponseType.Ok);
            return true;
        }
Example #22
0
        public OptionsWindow()
        {
            InitializeComponent();

            Regex filter = new Regex("^([A-Z]|F([1-9]|1[0-2])|Space)$");
            var keyList = Enum.GetValues(typeof(Keys))
                              .Cast<Keys>()
                              .Where(x => filter.Match(x.ToString()).Success);
            Keys.DataContext = keyList;

            // Highlight what's already selected
            hotkey = Core.HotKey;
            Keys.SelectedItem = hotkey.KeyCode;
            Alt.IsChecked = hotkey.Alt;
            Ctrl.IsChecked = hotkey.Ctrl;
            WindowsKey.IsChecked = hotkey.WindowsKey;
            Shift.IsChecked = hotkey.Shift;

            // Populate text box
            ExceptionList.Text = String.Join(Environment.NewLine, Core.ExceptionList.ToArray());
        }
Example #23
0
        /// <summary>
        /// ホットキーを追加します。
        /// </summary>
        public void Add(HotKey hotKey)
        {
            var atom = Kernel32.GlobalAddAtom(hotKey.ToString());
            if (atom == (short)IntPtr.Zero)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            var model = new
            {
                ID = HotKey.GetIDFromAtom(atom),
                Modifiers = (uint)hotKey.ModiferKeys,
                Key = (uint)KeyInterop.VirtualKeyFromKey(hotKey.Key),
            };

            if (User32.RegisterHotKey(this.Handle, model.ID, model.Modifiers, model.Key) == false)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            this.HotKies.Add(atom, hotKey);
        }
Example #24
0
        public MainPageViewModel()
        {
            LoadOffsets();

            _hotKey = new HotKey(ModifierKeys.Control, Keys.Z, Application.Current.MainWindow);
            _hotKey.HotKeyPressed +=
               key => AddPoint(Game.GetCoords(SelectedOffset, "elementclient"));

            PathCollection = new PathCollection();

            LoadFromFileCommand = new RelayCommand(LoadFromFile);
            SaveToFileCommand = new RelayCommand(SaveToFile);

            AddPathCommand = new RelayCommand(AddPath);
            AddPointCommand = new RelayCommand(AddPoint);
            AddSegmentCommand = new RelayCommand(AddSegment);

            DeletePathsCommand = new RelayCommand(DeletePaths);
            DeletePointsCommand = new RelayCommand(DeletePoints);
            DeleteSegmentsCommand = new RelayCommand(DeleteSegments);

            OpenMapCommand = new RelayCommand(OpenMapExecute);
        }
        public SelectTaskWindow()
        {
            InitializeComponent();

            var folderViewModel = new FolderViewModel();
            DataContext = folderViewModel;

            // Setup sys tray icon
            System.Windows.Forms.NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon();
            ContextMenuStrip contextMenu = new ContextMenuStrip();
            ToolStripItem item = new ToolStripMenuItem();
            item.Text = "Quit";
            item.Click += (s, e) =>
                {
                    System.Windows.Application.Current.Shutdown();
                };
            contextMenu.Items.Add(item);
            notifyIcon.Icon = new System.Drawing.Icon(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("FolderLounge.propertysheets.ico"));
            notifyIcon.ContextMenuStrip = contextMenu;
            notifyIcon.Visible = true;
            notifyIcon.DoubleClick += (s, e) =>
            {
                ShowThisWindow();
            };

            // Setup global hotkey for showing main Window
            Loaded += (s, e) =>
            {
                _hotkey = new HotKey(ModifierKeys.Windows | ModifierKeys.Shift, Keys.E, this);
                _hotkey.HotKeyPressed += (k) => ShowThisWindow();
                Hide();

                // Setup grouping in list view
                var dv = CollectionViewSource.GetDefaultView((DataContext as FolderViewModel).FolderDisplayItems);
                dv.GroupDescriptions.Add(new PropertyGroupDescription("Pinned", new BooleanToPinnedTextConverter()));
            };
        }
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            string defaultURL = Common.Default.LastURL;
            wbSample.Navigate(defaultURL);
            //JsScript = "alert('ganesh');";
            Css = Common.Default.CSSSetting;
            JsScript = Common.Default.JSSetting;
            txtUrl.Text = defaultURL;

            WindowTitle = Common.Default.WindowTitle;
            CloseApplicationCommand = new RelayCommand<object>(OnCloseApplication, x => true);
            OpenApplicationCommand = new RelayCommand<object>(OnOpenApplication, x => true);
            HideApplicationCommand = new RelayCommand<object>(OnHideApplication, obj => true);
            ToggleToolbarCommand = new RelayCommand<object>(OnToggleToolbarCommand, x => true);
            RefreshBrowserCommand = new RelayCommand<object>(OnRefreshBrowserCommand, x => true);

            MoveLeftCommand = new RelayCommand<object>(OnMoveLeftCommand, x => true);
            MoveRightCommand = new RelayCommand<object>(OnMoveRightCommand, x => true);
            MoveTopCommand = new RelayCommand<object>(OnMoveTopCommand, x => true);
            MoveDownCommand = new RelayCommand<object>(OnMoveDownCommand, x => true);

            SizeLeftCommand = new RelayCommand<object>(OnSizeLeftCommand, x => true);
            SizeRightCommand = new RelayCommand<object>(OnSizeRightCommand, x => true);
            SizeTopCommand = new RelayCommand<object>(OnSizeTopCommand, x => true);
            SizeDownCommand = new RelayCommand<object>(OnSizeDownCommand, x => true);

            SaveSettingsCommand = new RelayCommand<object>(SaveSettings, x => true);
            AlwaysOnTop = false;
            IsBrowserToolbarVisible = Visibility.Collapsed;

            var _hotKey = new HotKey(Key.Escape, KeyModifier.Shift, OnHotKeyHandler);
            var _hotKey1 = new HotKey(Key.Tab, KeyModifier.Shift, OnHotKeyHandler1);
            this.Closed += MainWindow_Closed;
        }
 /// <summary>
 /// Converts MahApps.Metro.Controls.HotKey to GlobalHotKey.HotKey for the GlobalHotKey api
 /// </summary>
 /// <param name="hotkey"></param>
 /// <returns></returns>
 public static GlobalHotKey.HotKey ToGlobalHotKey(this HotKey hotkey)
 {
     return(new GlobalHotKey.HotKey(hotkey.Key, hotkey.ModifierKeys));
 }
 internal KeyPressedEventArgs(HotKey key)
 {
     _key = key;
 }
Example #29
0
 private void OnShowDesktop(HotKey hotKey)
 {
     ToggleOverlay();
 }
Example #30
0
        private void SettingsForm_Load(object sender, EventArgs e)
        {
            _modifiers = new Dictionary <string, HotKeyModifiers>();
            _keys      = new Dictionary <string, Keys>();
            _akeys     = new Dictionary <string, Keys>();
            OptionsListBox.CheckOnClick = false;

            //
            // Blaze HotKey
            //
            _hotkey = SettingsManager.Instance.GetMainHotKey();
            // modifiers
            _modifiers.Add("None", new HotKeyModifiers(false, false, false, false));
            _modifiers.Add("Alt", new HotKeyModifiers(true, false, false, false));
            _modifiers.Add("Ctrl", new HotKeyModifiers(false, true, false, false));
            _modifiers.Add("Shift", new HotKeyModifiers(false, false, true, false));
            _modifiers.Add("Win", new HotKeyModifiers(false, false, false, true));

            _modifiers.Add("Alt+Ctrl", new HotKeyModifiers(true, true, false, false));
            _modifiers.Add("Alt+Shift", new HotKeyModifiers(true, false, true, false));
            _modifiers.Add("Alt+Win", new HotKeyModifiers(true, false, false, true));

            _modifiers.Add("Ctrl+Shift", new HotKeyModifiers(false, true, true, false));
            _modifiers.Add("Ctrl+Win", new HotKeyModifiers(false, true, false, true));

            _modifiers.Add("Shift+Win", new HotKeyModifiers(false, false, true, true));

            // keys
            _keys.Add("Space", Keys.Space);
            _keys.Add("Return", Keys.Return);
            _keys.Add("A", Keys.A);
            _keys.Add("B", Keys.B);
            _keys.Add("C", Keys.C);
            _keys.Add("D", Keys.D);
            _keys.Add("E", Keys.E);
            _keys.Add("F", Keys.F);
            _keys.Add("G", Keys.G);
            _keys.Add("H", Keys.H);
            _keys.Add("I", Keys.I);
            _keys.Add("J", Keys.J);
            _keys.Add("K", Keys.K);
            _keys.Add("L", Keys.L);
            _keys.Add("M", Keys.M);
            _keys.Add("N", Keys.N);
            _keys.Add("O", Keys.O);
            _keys.Add("P", Keys.P);
            _keys.Add("Q", Keys.Q);
            _keys.Add("R", Keys.R);
            _keys.Add("S", Keys.S);
            _keys.Add("T", Keys.T);
            _keys.Add("U", Keys.U);
            _keys.Add("V", Keys.V);
            _keys.Add("W", Keys.W);
            _keys.Add("X", Keys.X);
            _keys.Add("Y", Keys.Y);
            _keys.Add("Z", Keys.Z);
            _keys.Add("0", Keys.D0);
            _keys.Add("1", Keys.D1);
            _keys.Add("2", Keys.D2);
            _keys.Add("4", Keys.D4);
            _keys.Add("5", Keys.D5);
            _keys.Add("6", Keys.D6);
            _keys.Add("8", Keys.D8);
            _keys.Add("9", Keys.D9);
            _keys.Add("Pause", Keys.Pause);
            _keys.Add("Scroll Lock", Keys.Scroll);
            _keys.Add("Caps Lock", Keys.CapsLock);
            _keys.Add("Num Lock", Keys.NumLock);

            string[] modifiers = new string[_modifiers.Keys.Count];
            string[] keys      = new string[_keys.Keys.Count];
            _modifiers.Keys.CopyTo(modifiers, 0);
            _keys.Keys.CopyTo(keys, 0);

            Keys[] keys_codes = new Keys[_keys.Values.Count];
            _keys.Values.CopyTo(keys_codes, 0);

            ModifierComboBox.Items.AddRange(modifiers);
            ModifierComboBox.SelectedIndex = 0;
            MainKeyComboBox.Items.AddRange(keys);
            MainKeyComboBox.SelectedIndex = 0;
            // select user key
            ModifierComboBox.SelectedIndex = Array.FindIndex <string>(modifiers, delegate(string s)
            {
                return(s == _hotkey.ModifiersName);
            });
            MainKeyComboBox.SelectedIndex = Array.FindIndex <Keys>(keys_codes, delegate(Keys s)
            {
                return(s == (Keys)_hotkey.Key);
            });
            //

            //
            // Assistant HotKey
            //
            _ahotkey = SettingsManager.Instance.GetAssistantHotKey();

            // keys
            _akeys.Add("None", Keys.None);
            _akeys.Add("Caps Lock", Keys.CapsLock);
            _akeys.Add("Pause", Keys.Pause);
            _akeys.Add("Scroll Lock", Keys.Scroll);
            _akeys.Add("Num Lock", Keys.NumLock);
            _akeys.Add("Left Alt", Keys.LMenu);
            _akeys.Add("Left Ctrl", Keys.LControlKey);
            _akeys.Add("Right Ctrl", Keys.RControlKey);
            _akeys.Add("Left Shift", Keys.LShiftKey);
            _akeys.Add("Right Shift", Keys.RShiftKey);
            _akeys.Add("Left Win", Keys.LWin);
            _akeys.Add("Right Win", Keys.RWin);

            string[] akeys_names = new string[_akeys.Keys.Count];
            _akeys.Keys.CopyTo(akeys_names, 0);

            Keys[] akeys_codes = new Keys[_akeys.Values.Count];
            _akeys.Values.CopyTo(akeys_codes, 0);

            AssistantKeyComboBox.Items.AddRange(akeys_names);
            AssistantKeyComboBox.SelectedIndex = 0;
            // select user key
            AssistantKeyComboBox.SelectedIndex = Array.FindIndex <Keys>(akeys_codes, delegate(Keys s)
            {
                return(s == (Keys)_ahotkey.Key);
            });
            //

            //
            // Interface
            //
            _interface_info = new InterfaceInfo(SettingsManager.Instance.GetInterfaceInfo());
            suggestionsNumericUpDown.Value = _interface_info.NumberOfSuggestions;
            //

            //
            // System Options
            //
            _system_options_info          = new SystemOptionsInfo(SettingsManager.Instance.GetSystemOptionsInfo());
            updateTimeNumericUpDown.Value = _system_options_info.UpdateTime;
            stopIndexingCheckBox.Checked  = _system_options_info.StopAutoUpdateOnBattery;
            autoUpdatesCheckBox.Checked   = _system_options_info.AutoUpdates;
            //

            //
            // Automation Options
            //
            _automation_options_info = new AutomationOptionsInfo(SettingsManager.Instance.GetAutomationOptionsInfo());
            if (_automation_options_info.IsMonitoringEnabled)
            {
                yesAutomationRadioButton.Checked = true;
            }
            else
            {
                noAutomationRadioButton.Checked = true;
            }
            stopMonitoringCheckBox.Checked = _automation_options_info.StopAutoUpdateOnBattery;
            //

            //
            // Plugins
            //
            OptionsListBox.Items.Add("Include directories");
            OptionsListBox.Items.Add("Search subdirectories");
            _plugins_map_options = new Dictionary <string, int>();
            _options_map_plugins = new Dictionary <int, string>();
            _indexerPlugins      = new List <IndexerPlugin>();
            _interpreterPlugins  = new List <InterpreterPlugin>();
            _plugins             = _parent.Plugins;
            _pluginInfo          = new PluginInfo(SettingsManager.Instance.GetLoadablePlugins());
            for (int i = 0; i < _plugins.Count; i++)
            {
                PluginsListBox.Items.Add(_plugins[i].Name, _pluginInfo.Enabled[_plugins[i].Name]);
                if (_plugins[i].Type == PluginType.Indexer)
                {
                    IndexerPlugin p = (IndexerPlugin)_plugins[i];
                    _indexerPlugins.Add(p);
                    OptionsListBox.Items.Add(p.QuickDescription);
                    _plugins_map_options.Add(p.Name, OptionsListBox.Items.Count - 1);
                    _options_map_plugins.Add(OptionsListBox.Items.Count - 1, p.Name);
                }
                else
                {
                    InterpreterPlugin p = (InterpreterPlugin)_plugins[i];
                    _interpreterPlugins.Add(p);
                }
            }
            if (PluginsListBox.Items.Count > 0)
            {
                PluginsListBox.SelectedIndex = 0;
            }
            //

            //
            // Index
            //
            DirInfo info = SettingsManager.Instance.GetDirectories();

            _directories         = new List <string>(info.Directories.ToArray());
            _extensions          = new Dictionary <string, List <string> >(info.Extensions);
            _includeDirectories  = new Dictionary <string, bool>(info.IncludeDirectories);
            _indexSubdirectories = new Dictionary <string, bool>(info.IndexSubdirectories);
            _dirPlugins          = new Dictionary <string, List <string> >(info.Plugins);
            DirectoriesListBox.Items.AddRange(_directories.ToArray());
            if (_directories.Count > 0)
            {
                DirectoriesListBox.SelectedIndex = 0;
            }
            //

            AutomatorLabel.Text            = AssemblyTitle + (CommonInfo.IsPortable ? " Portable " : " ") + AssemblyVersion + " beta";
            AutomatorDescriptionLabel.Text = "Blaze is an application that is being developed in the scope of a college project." + Environment.NewLine +
                                             "The main goal is to develop an application launcher that is able to automate the" + Environment.NewLine +
                                             "recurrent tasks that arise from everyday usage.";
            stopMonitoringCheckBox.Text = "Stop monitoring when my laptop is " + Environment.NewLine + "running on battery";
            Process proc = Process.GetCurrentProcess();

            MemoryEditableLabel.Text    = (proc.PrivateMemorySize64 / 1024).ToString() + " kilobytes";
            StartTimeEditableLabel.Text = proc.StartTime.ToString();
            TimeSpan indexing_time = SettingsManager.Instance.GetIndexingTime();

            IndexingTimeEditableLabel.Text = string.Format("{0:00}h {1:00}m {2:00}s {3:000}ms", indexing_time.TotalHours, indexing_time.Minutes, indexing_time.Seconds, indexing_time.Milliseconds);
            IndexedItemsEditableLabel.Text = SettingsManager.Instance.GetNumberOfIndexedItems().ToString() + " items";
            LastIndexEditableLabel.Text    = SettingsManager.Instance.GetLastIndexBuild().ToString();
            proc.Dispose();
        }
        private void ApplyButton_Click(object sender, RoutedEventArgs e)
        {
            DateTime startTime = DateTime.Now;

            string TT1 = T1; // T1 Temp
            string TT2 = T2; // T2 Temp

            // 内容查找与替换
            if (ReplaceText.IsChecked.Value)
            {
                TT1 = F.Replace(TT1, rtFindText.Text, rtReplacement.Text, !rtIgnoreCase.IsChecked.Value);
            }
            // 删除括号内容
            else if (Bracket.IsChecked.Value)
            {
                TT1 = F.Bracket(TT1, ref TT2, brLeft.Text, brRight.Text, brKeepBracket.IsChecked.Value, brNestBracket.IsChecked.Value);
                if (!brShowBracketContent.IsChecked.Value)
                {
                    TT2 = F.EM;
                }
            }
            // 删除空白
            else if (DeleteBlank.IsChecked.Value)
            {
                int mode = 0;
                if (dbRemoveAll.IsChecked.Value)
                {
                    mode = 1;
                }
                else if (dbRemoveFront.IsChecked.Value)
                {
                    mode = 2;
                }
                else if (dbRemoveEnd.IsChecked.Value)
                {
                    mode = 3;
                }
                else if (dbRemoveFrontAndEnd.IsChecked.Value)
                {
                    mode = 4;
                }
                TT1 = F.Blank(TT1, mode);
            }
            // 换行符相关
            else if (NewlineSymbol.IsChecked.Value)
            {
                int mode = 0;
                if (nsRemoveAll.IsChecked.Value)
                {
                    mode = 1;
                }
                else if (nsRemoveUseless.IsChecked.Value)
                {
                    mode = 2;
                }
                else if (nsAddNewlines.IsChecked.Value)
                {
                    mode = 3;
                }
                TT1 = F.Return(TT1, mode);
            }
            // 文本顺序调换
            else if (TextOrder.IsChecked.Value)
            {
                int mode = 0;
                if (toByLine.IsChecked.Value)
                {
                    mode = 1;
                }
                else if (toByWord.IsChecked.Value)
                {
                    mode = 2;
                }
                else if (toByWordInLine.IsChecked.Value)
                {
                    mode = 3;
                }
                TT1 = F.Reorder(TT1, mode);
            }
            // 批量重复文本
            else if (RepeatText.IsChecked.Value)
            {
                TT1 = F.Repeat(TT1, rptTime.Text, rptAutoNewLine.IsChecked.Value);
            }
            // 逐行插入相同内容
            else if (AddByLine.IsChecked.Value)
            {
                TT1 = F.AddTextByLine(TT1, ablInsertContent.Text, ablPosition.Text, ablIgnoreEmpty.IsChecked.Value, ablIgnoreBlank.IsChecked.Value);
            }
            // 逐行插入不同内容
            else if (SpecialInsert.IsChecked.Value)
            {
                TT1 = F.AddTextsByLine(TT1, TT2, siPosition.Text, siIngoreEmpty.IsChecked.Value);
            }
            // 隔行删除
            else if (DeleteByLine.IsChecked.Value)
            {
                TT1 = F.DeleteByLine(TT1, ref TT2, dblReserve.Text, dblRemove.Text);
            }
            // 隔行插入
            else if (InsertByLine.IsChecked.Value)
            {
                TT1 = F.InsertByLine(TT1, TT2, iblReserve.Text, iblInsert.Text);
            }
            // 逐行添加序号
            else if (AddIndexByLine.IsChecked.Value)
            {
                IndexFormat mode = IndexFormat.Normal;
                if (aiblNormal.IsChecked.Value)
                {
                    mode = IndexFormat.Normal;
                }
                else if (aiblChinese.IsChecked.Value)
                {
                    mode = IndexFormat.Chinese;
                }
                else if (aiblRoman.IsChecked.Value)
                {
                    mode = IndexFormat.Roman;
                }
                else if (aiblCircle.IsChecked.Value)
                {
                    mode = IndexFormat.Circle;
                }
                else if (aiblBracket.IsChecked.Value)
                {
                    mode = IndexFormat.Bracket;
                }

                int start  = 1;
                int digits = 0;
                if (int.TryParse(aiblStartValue.Text, out start) && int.TryParse(aiblDigits.Text, out digits))
                {
                    TT1 = F.InsertIndexAt(TT1, aiblLeft.Text, aiblRight.Text, start, digits, aiblPosition.Text, mode, aiblIgnoreEmpty.IsChecked.Value, aiblAlignNumber.IsChecked.Value);
                }
            }
            // 文本格式转换
            else if (FormatText.IsChecked.Value)
            {
                TextFormatMode mode = TextFormatMode.Tranditional;
                if (ftST.IsChecked.Value)
                {
                    mode = TextFormatMode.Tranditional;
                }
                else if (ftTS.IsChecked.Value)
                {
                    mode = TextFormatMode.Simplified;
                }
                else if (ftLU.IsChecked.Value)
                {
                    mode = TextFormatMode.Upper;
                }
                else if (ftUL.IsChecked.Value)
                {
                    mode = TextFormatMode.Lower;
                }
                else if (ftFU.IsChecked.Value)
                {
                    mode = TextFormatMode.InitialUpper;
                }
                else if (ftCP.IsChecked.Value)
                {
                    mode = TextFormatMode.Pinyin;
                }
                TT1 = F.TextFormat(TT1, mode);
            }
            // 正则表达式
            else if (RegularExpression.IsChecked.Value)
            {
                RegexOptions option = F.GetRexOptions(reIgnoreCase.IsChecked.Value, reMultiline.IsChecked.Value, reSingleline.IsChecked.Value,
                                                      reIgnorePatternWhitespace.IsChecked.Value, reExplicitCapture.IsChecked.Value);
                RegexMode mode = RegexMode.Match;
                if (reReplaceOnly.IsChecked.Value)
                {
                    mode = RegexMode.Replace;
                }
                else if (reReplaceAndShow.IsChecked.Value)
                {
                    mode = RegexMode.ReplaceAndMatch;
                }
                else if (reShowOnly.IsChecked.Value)
                {
                    mode = RegexMode.Match;
                }

                TT1 = F.UseRegex(TT1, ref TT2, reFind.Text, reReplace.Text, mode, option);
            }
            // 自定义转换列表
            else if (TransformList.IsChecked.Value)
            {
                PairListManager manager;
                if (TransformListFiles.Text == PairListPanel.CurrentListName.Text)
                {
                    manager = PairListPanel.Manager;
                }
                else
                {
                    manager = new PairListManager(pairFolder + @"\" + TransformListFiles.Text + ".txt");
                }
                TT1 = F.TransformList(TT1, manager, tlR.IsChecked.Value);
            }
            // 文件批量重命名
            else if (RenameFiles.IsChecked.Value)
            {
                ApplyRename();
                return;
            }
            // 剪贴板辅助工具
            else if (ClipboardHelper.IsChecked.Value)
            {
                if (isUsingPasteHelper)
                {
                    return;
                }
                PasteLines = F.SplitByString(TT1, F.NL, !chIgnoreBlank.IsChecked.Value);
                if (PasteLines.Count == 0)
                {
                    MessageBox.Show("当前无可复制文本,剪贴板辅助工具开启失败。");
                    return;
                }
                MessageBox.Show("剪贴板辅助工具已启用,\n共采集到文本信息 " + PasteLines.Count.ToString() + " 行。");
                isUsingPasteHelper = true;
                PasteLineIndex     = 0;
                Clipboard.SetText(PasteLines[0]);

                // 改变相关控件的IsEnabled,防止用户在使用期间更改相关参数,导致程序出错
                chStopButton.Visibility = Visibility.Visible;
                chIgnoreBlank.IsEnabled = false;
                chCycle.IsEnabled       = false;
                chAutoPaste.IsEnabled   = false;
                chAutoKeyDown.IsEnabled = false;
                chDelay.IsEnabled       = false;

                if (chAutoPaste.IsChecked.Value)
                {
                    hotkey           = new HotKey(this, HotKey.KeyFlags.MOD_CONTROL, Form.Keys.V);
                    hotkey.OnHotKey += HotKeyEvent;
                }
                else
                {
                    kh = new KeyboardHook();
                    kh.SetHook();
                    kh.OnKeyDownEvent += HookOnKeyDownEvent;
                }
            }

            // 最终执行效果
            T1 = TT1;
            if (EditorPanel.IsShowingBox2 || EditorPanel.AlwaysShowingBox2) // 当Box2不显示时,使其缓存的文本内容不改变
            {
                T2 = TT2;
            }

            DateTime stopTime = DateTime.Now;

            if (showRunTime)
            {
                TimeSpan span = stopTime - startTime;
                MessageBox.Show("执行耗时" + span.TotalMilliseconds.ToString() + "毫秒");
            }
        }
Example #32
0
        private void HotKeyPressed(HotKey hotKey)
        {
            bool lockTaken = false;

            try
            {
                m_SpinLock.Enter(ref lockTaken);

                if (hotKey.Modifiers == 0 && m_CurrentItem != null)
                {
                    SpinWait.SpinUntil(() => !HotKeyManager.IsKeyPressed(hotKey.Key));

                    if (m_KeyHook_KEYS.Contains(hotKey))
                    {
                        long buyPrice = m_CurrentItem.BuyPrice + 1;

                        if (CopperValue >= 0)
                        {
                            buyPrice = (long)((Math.Floor(m_CurrentItem.BuyPrice / 100.0) * 100) + CopperValue);

                            if (buyPrice <= m_CurrentItem.BuyPrice + 1)
                            {
                                buyPrice += 100;
                            }
                        }

                        long buyPriceC = (buyPrice % 100);
                        long buyPriceS = (long)(Math.Floor(buyPrice / 100.0) % 100);
                        long buyPriceG = (long)(Math.Floor(buyPrice / 10000.0));

                        switch (m_CurrentState)
                        {
                        case HandlerState.SEARCH:
                            SendKeys.Send(m_CurrentItem.Name);
                            m_CurrentState = HandlerState.ENTERG;
                            break;

                        case HandlerState.ENTERG:
                            SendKeys.Send(buyPriceG.ToString());
                            m_CurrentState = HandlerState.ENTERS;
                            break;

                        case HandlerState.ENTERS:
                            SendKeys.Send(buyPriceS.ToString());
                            m_CurrentState = HandlerState.ENTERC;
                            break;

                        case HandlerState.ENTERC:
                            SendKeys.Send(buyPriceC.ToString());
                            m_CurrentState = HandlerState.NEXT;
                            break;

                        case HandlerState.NEXT:
                            m_CurrentItem  = null;
                            m_CurrentState = HandlerState.SEARCH;
                            break;
                        }
                    }
                    else if (m_KeyHook_KEYS_SKIP.Contains(hotKey))
                    {
                        m_CurrentItem  = null;
                        m_CurrentState = HandlerState.SEARCH;
                    }
                }
            }
            finally
            {
                if (lockTaken)
                {
                    m_SpinLock.Exit();
                }
            }
        }
Example #33
0
        private void RegisterHotkey()
        {
            HotKey.RegisterHotKey(Handle, 0xAAAA, HotKey.KeyModifiers.None, Keys.F8);

            HotKey.RegisterHotKey(Handle, 0xAAAB, HotKey.KeyModifiers.None, Keys.F9);
        }
 /// <summary>
 /// Registers a hot key in the system.
 /// </summary>
 /// <param name="hotkey">A HotKey Struct</param>
 public void RegisterHotKey(HotKey hotkey)
 {
     keys.Add(hotkey);
 }
 public static void Set(HotKey hotkey)
 {
     Set(hotkey.HotKeyType.ToString(),
         string.Format("{0}#{1}", (int)hotkey.Modifiers, (int)hotkey.Key));
 }
Example #36
0
 public HotKeyEventArgs(HotKey hotKey, ButtonState state)
 {
     this.hotKey = hotKey;
     this.state  = state;
 }
Example #37
0
        public static void Initialize()
        {
            new ReqPartyLocTimer().Start();

            HotKey.Add(HKCategory.Misc, LocString.ToggleMap, new HotKeyCallback(ToggleMap));
        }
Example #38
0
        private HotKeyListener hkListener       = new HotKeyListener();     // ascolta se viene premuto una combinazione di tasti e ne esegue l'handler

        public FormClient()
        {
            InitializeComponent();

            HotKey hk_exit = new HotKey(Keys.LControlKey, Keys.F12);

            // Evento eseguito quando viene premuto l'hotkey: smetti di catturare e inviare gli eventi (flag active da true a false)
            hk_exit.HotKeyHappened += (object sender, EventArgs e) =>
            {
                //simulare keyup qua
                hk_exit.SimulateKeysUp();

                keyboardHook.Stop();
                mouseHook.Stop();
                //Thread.Sleep(timer1.Interval);
                timer1.Stop();

                if (events.Count > 0)
                {
                    EventsBuffer.AddEvents(events);
                    cs.SendEventsList(EventsBuffer.ConsumeEvents());
                    events = new List <MacroEvent>();
                }

                active = false;
                EventsBuffer.Close();
            };
            hkListener.Add(hk_exit);

            //foreach(server s in serverfarm)
            // s.hotkey.hotkeyhappened += clientsocket.connecttoserver(s.ip,s.port);

            mouseHook.MouseMove  += new MouseEventHandler(mouseHook_MouseMove);
            mouseHook.MouseDown  += new MouseEventHandler(mouseHook_MouseDown);
            mouseHook.MouseUp    += new MouseEventHandler(mouseHook_MouseUp);
            mouseHook.MouseWheel += new MouseEventHandler(mouseHook_MouseWheel);

            keyboardHook.KeyDown += new KeyEventHandler(keyboardHook_KeyDown);
            keyboardHook.KeyUp   += new KeyEventHandler(keyboardHook_KeyUp);
            // Handlers di HotKeyListener vengono eseguiti dopo che gli eventi vengono aggiunti alla lista da inviare
            keyboardHook.KeyDown += hkListener.KeyDownListen;
            keyboardHook.KeyUp   += hkListener.KeyUpListen;


            // Evento: ClientSocket si collega al server (connected da false a true)
            cs.Connected += (object sender, EventArgs e) =>
            {
                connected = true;
                btnAttiva.Invoke(new MethodInvoker(() => { this.btnAttiva.Enabled = true; }));
                btnConnetti.Invoke(new MethodInvoker(() => { this.btnConnetti.Text = "Disconnetti"; }));
            };

            // Evento: ClientSocker non è più collegato al server (connected da true a false)
            cs.Disconnected += (object sender, EventArgs e) =>
            {
                connected = false;
                btnAttiva.Invoke(new MethodInvoker(() => { this.btnAttiva.Enabled = false; }));
                btnConnetti.Invoke(new MethodInvoker(() => { this.btnConnetti.Text = "Connetti"; }));

                // se il server si disconnette mentre il client è attivo
                if (active)
                {
                    keyboardHook.Stop();
                    mouseHook.Stop();
                    timer1.Stop();
                    active = false;
                }
                //EventsBuffer.Close();
            };


            loadServerFarm();

            foreach (Server s in Server_farm.server_list.Values)
            {
                listView1.Items.Add(s.Name);
            }

            if (listView1.Items.Count > 0)
            {
                showServerDetails(Server_farm.server_list[listView1.Items[0].Text]);
                listView1.Items[0].Selected = true;
            }

            listView1.Columns[0].Width = listView1.Width - 4;
        }
Example #39
0
 public static void Initialize()
 {
     HotKey.Add(HKCategory.Misc, LocString.NextWaypoint, new HotKeyCallback(NextWaypoint));
     HotKey.Add(HKCategory.Misc, LocString.PrevWaypoint, new HotKeyCallback(PrevWaypoint));
     HotKey.Add(HKCategory.Misc, LocString.HideWaypoint, new HotKeyCallback(ClearWaypoint));
 }
Example #40
0
 private void Form1_FormClosed(object sender, FormClosedEventArgs e)
 {
     HotKey.UnregisterHotKey(Handle, 0xAAAA);
     HotKey.UnregisterHotKey(Handle, 0xAAAB);
     isRunning = false;
 }
Example #41
0
 private void FmMain_FormClosed(object sender, FormClosedEventArgs e)
 {
     HotKey.UnregisterHotKey(Handle, 200);
 }
 public void RegisterCallback(HotKey hk, Action callback)
 {
     _callbacks[hk] = callback;
 }
Example #43
0
        /// <summary>
        /// 执行初始化操作
        /// </summary>
        private void Init()
        {
            trayMenuHsiAlgorithmGeometry.Tag = HsiAlgorithm.Geometry;
            trayMenuHsiAlgorithmAxis.Tag     = HsiAlgorithm.Axis;
            trayMenuHsiAlgorithmSegment.Tag  = HsiAlgorithm.Segment;
            trayMenuHsiAlgorithmBajon.Tag    = HsiAlgorithm.Bajon;
            trayMenuHsiAlgorithmStandard.Tag = HsiAlgorithm.Standard;

            previewForm = new PreviewForm();
            previewForm.LocationChanged += previewForm_LocationChanged;

            currentDisplayMode = DisplayMode.Fixed;
            SwitchHsiAlgorithm(Settings.Main.HsiAlgorithm);

            colorBuffer = new StringBuilder(8, 64);


            if (Settings.Preview.Visible)
            {
                TogglePreview();
            }

            if (trayMenuFixed.Checked)
            {
                FixedPosition();
            }

            SwitchFormatMode(Settings.Main.Format);

            var now = DateTime.Now;

            lastPressTime = Util.Enum <HotKeyType>()
                            .ToDictionary(item => item, item => now);

            HotKey.Bind(Handle);

            trayMenuCopyPolicyHexValueOnly.Checked = Settings.Base.HexValueOnly;
            trayMenuCopyPolicyRgbValueOnly.Checked = Settings.Base.RgbValueOnly;
            trayMenuCopyPolicyUpperCase.Checked    = Settings.Base.CopyUpperCase;

            new Thread(() =>
            {
                UpdateTooltip();

                // 读取开机启动的注册表
                this.InvokeMethod(() =>
                {
                    trayMenuAutoStart.Checked = Settings.Base.Autostart;
                    trayMenuAutoPin.Checked   = Settings.Base.AutoPin;

                    trayMenuPixelScale.Checked = Settings.Preview.PixelScale;

                    trayMenuShootOnCurrentScreen.Checked = Settings.Shoot.CurrentScreen;
                });
            })
            {
                IsBackground = true
            }.Start();

            caretTimer = new Timer {
                Interval = caretInterval
            };
            caretTimer.Tick += carettimer_Tick;
            caretTimer.Start();

            colorTimer = new Timer {
                Interval = colorInterval
            };
            colorTimer.Tick += colortimer_Tick;
            colorTimer.Start();

            // 检查是否是首次运行
            if (Settings.Base.IsFirstRun)
            {
                Settings.Base.IsFirstRun = false;

                // 首次运行时,打开帮助窗口
                trayMenuShowAbout_Click(null, null);
                if (!IsDisposed)
                {
                    // 然后打开快捷键设置窗口
                    trayMenuHotkey_Click(null, null);
                }
            }

            // 是否监听剪贴板
            trayMenuEnableClipboard.Checked = Settings.Clipboard.Enabled;
            if (trayMenuEnableClipboard.Checked)
            {
                NativeMethods.AddClipboardFormatListener(Handle);
            }

            // 加载语言并选中使用的项
            new Thread(() =>
            {
                // 当前显示的语言
                var locale = (Settings.I18n.Lang ?? System.Globalization.CultureInfo.InstalledUICulture.Name).ToLower();
                // 加载自定义语言
                var langs = i18n.I18nManager.GetLocalLangs();
                if (langs.Any())
                {
                    // 都放到其它语言菜单项下
                    var others = new ToolStripMenuItem();
                    resources.ApplyResources(others, "trayMenuLanguageOther");
                    others.Name = "trayMenuLanguageOther";

                    // 存放语言 tooltip 的临时量
                    var temp = new StringBuilder();

                    var subs = langs.Select(language =>
                    {
                        var item  = new ToolStripMenuItem();
                        item.Name = $"customize-lang--{language.Locale}";
                        item.Text = language.Name;

                        // 选中项
                        var l        = language.Locale.ToLower();
                        item.Checked = locale == l || locale.StartsWith(l) || l.StartsWith(locale);

                        // 提示信息中显示语言的版本以及作者
                        temp.Append($"{language.Version}\n");
                        if (language.Authors != null && language.Authors.Any())
                        {
                            temp.Append("------------\n");
                            foreach (var author in language.Authors)
                            {
                                temp.AppendFormat("{0}/{1}\n", author.Name, author.Mail);
                                if (string.IsNullOrEmpty(author.HomePage))
                                {
                                    temp.Append(author.HomePage);
                                }
                            }
                        }
                        item.ToolTipText = temp.ToString();
                        temp.Clear();
                        return(item);
                    });

                    // 添加菜单项
                    others.DropDownItems.AddRange(subs.ToArray());
                    this.InvokeMethod(() =>
                    {
                        trayMenuLanguage.DropDownItems.Add(others);
                    });
                }
                if (locale.StartsWith("zh"))
                {
                    trayMenuLanguageZH.Checked = true;
                }
                else if (!langs.Any() || locale.StartsWith("en"))
                {
                    // 没有其它语言或设置为英语时
                    trayMenuLanguageEN.Checked = true;
                }
            })
            {
                IsBackground = true
            }.Start();

            // 启动时检查更新
            trayMenuCheckUpdateOnStartup.Checked = Settings.Update.CheckOnStartup;

            // 自动检查更新
            if (trayMenuCheckUpdateOnStartup.Checked &&
                (DateTime.Now.Date - Settings.Update.LastUpdate).TotalDays >= Settings.Update.Span)
            {
                update.UpdateForm.ShowWindow(true);
            }
        }
Example #44
0
        public HotKeyManager RegisterGlobal(string id, string description, HotKeyScope scope, HotKey defaultHotKey, Action callback, bool enabled = true)
        {
            Register(id, description, scope, defaultHotKey, callback, enabled);

            return(this);
        }
Example #45
0
        //private void IncludeSubDirCheckBox_CheckedChanged(object sender, EventArgs e)
        //{
        //    if (DirectoriesListBox.SelectedItem != null)
        //    {
        //        string item = DirectoriesListBox.SelectedItem.ToString();
        //        if (item != string.Empty)
        //        {
        //            _indexSubdirectories[item] = OptionsListBox.GetItemChecked(1);
        //        }
        //    }
        //}

        private void okButton_Click(object sender, EventArgs e)
        {
            Keys[] keys_codes = new Keys[_keys.Values.Count];
            _keys.Values.CopyTo(keys_codes, 0);
            Keys[] akeys_codes = new Keys[_akeys.Values.Count];
            _akeys.Values.CopyTo(akeys_codes, 0);

            HotKey newMainHotkey = new HotKey(_modifiers[ModifierComboBox.SelectedItem.ToString()],
                                              keys_codes[MainKeyComboBox.SelectedIndex]);
            HotKey newAssistantHotkey = new HotKey(false, false, false, false, akeys_codes[AssistantKeyComboBox.SelectedIndex]);

            if (newMainHotkey != _hotkey ||
                newAssistantHotkey != _ahotkey)
            {
                _parent.UnregisterHotKey();
                if (!_parent.RegisterHotKey(newMainHotkey) || newMainHotkey == newAssistantHotkey)
                {
                    MessageBox.Show("The hotkey you have chosen is already in use. Please pick another one",
                                    "Hotkey in use", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    _parent.RegisterHotKey();
                    return;
                }
                _parent.RegisterAssistantHotKey(newAssistantHotkey);
                SettingsManager.Instance.SaveMainHotKey(newMainHotkey);
                SettingsManager.Instance.SaveAssistantHotKey(newAssistantHotkey);
            }
            _interface_info.NumberOfSuggestions              = (int)suggestionsNumericUpDown.Value;
            _system_options_info.UpdateTime                  = (int)updateTimeNumericUpDown.Value;
            _system_options_info.StopAutoUpdateOnBattery     = stopIndexingCheckBox.Checked;
            _system_options_info.AutoUpdates                 = autoUpdatesCheckBox.Checked;
            _automation_options_info.IsMonitoringEnabled     = yesAutomationRadioButton.Checked;
            _automation_options_info.StopAutoUpdateOnBattery = stopMonitoringCheckBox.Checked;
            List <List <string> > ext    = new List <List <string> >();
            List <bool>           subdir = new List <bool>();
            List <bool>           incdir = new List <bool>();

            foreach (string dir in _directories)
            {
                ext.Add(_extensions[dir]);
                subdir.Add(_indexSubdirectories[dir]);
                incdir.Add(_includeDirectories[dir]);
            }
            SettingsManager.Instance.SaveDirectories(new DirInfo(_directories, _extensions, _includeDirectories, _indexSubdirectories, _dirPlugins));
            SettingsManager.Instance.SaveLoadablePlugins(_pluginInfo);
            SettingsManager.Instance.SaveInterfaceInfo(_interface_info);
            SettingsManager.Instance.SaveSystemOptionsInfo(_system_options_info);
            SettingsManager.Instance.SaveAutomationOptionsInfo(_automation_options_info);
            if (_automation_options_info.IsMonitoringEnabled)
            {
                UserContext.Instance.ObserverObject.StartMonitoring();
            }
            else
            {
                UserContext.Instance.ObserverObject.StopMonitoring();
            }
            _parent.Interpreter.SetUpdateTimerInterval(_system_options_info.UpdateTime);
            _parent.LoadPlugins();
            _parent.UpdateUponInput();
            //_parent.RebuildIndex();
            Close();
        }
Example #46
0
        public HotKeyManager RegisterLocal(string id, string description, HotKey defaultHotKey, Action callback = null, bool enabled = true)
        {
            Register(id, description, null, defaultHotKey, callback, enabled);

            return(this);
        }
Example #47
0
 public HotKeyData Match(HotKey hotKey) => _hotKeyDataMap.SafeGet(hotKey);
Example #48
0
 private void OnShowProgramsMenu(HotKey hotKey)
 {
     ToggleProgramsMenu();
 }
Example #49
0
        //The rigth way to build a Server. Call this before pass argument to constructor.
        public bool validArgumentsForServer(String name, String password, HotKey hk, String ip, String port)
        {
            bool _name = false, _password = false, _hk = false, _ip = false, _port = false;

            //VISUALIZZARE A VIDEO L'INFORMAZIONE ERRATA

            // 1. NAME
            if (name.Length > 0)
            {
                _name             = true;
                txtName.ForeColor = DefaultForeColor;
            }
            else
            {
                txtName.ForeColor = System.Drawing.Color.Red;
            }

            // 2. PASSWORD
            if (password.Length > 4)
            {
                _password             = true;
                txtPassword.ForeColor = DefaultForeColor;
            }
            else
            {
                txtPassword.ForeColor = System.Drawing.Color.Red;
            }

            // 3. HOT KEY
            if (hk == null)
            {
                //TODO : ne assegnamo uno di default
                hk  = getDefaultHotKey();
                _hk = true;
                Console.WriteLine("HOT KEY DEFAULT DA ASSEGNARE");
            }
            else
            {
                _hk = true;
                foreach (Server s in Server_farm.server_list.Values)
                {
                    if (!s.Name.Equals(name))
                    {
                        if (s.HotKey.HasSameKeysSequence(hk))
                        {
                            _hk = false;
                            txtHotKey.ForeColor = System.Drawing.Color.Red;
                            break;
                        }
                    }
                }
            }

            // 4. IP
            try
            {
                IPAddress.Parse(ip);
                _ip = true;
                txtIpAddress.ForeColor = DefaultForeColor;
            }
            catch (FormatException)
            {
                txtIpAddress.ForeColor = System.Drawing.Color.Red;
                Console.WriteLine("Indirizzo IP non valido");
            }

            // 5. PORTA
            try
            {
                int int_port = int.Parse(port);
                if (int_port > 1000 && int_port < 20000)
                {
                    _port = true;
                    txtPortNumber.ForeColor = DefaultForeColor;
                }
                else
                {
                    txtPortNumber.ForeColor = System.Drawing.Color.Red;
                }
            }
            catch (FormatException)
            {
                txtPortNumber.ForeColor = System.Drawing.Color.Red;
                Console.WriteLine("Valore porta non valido");
            }

            //TUTTI CAMPI VALIDI?
            if (_name && _password && _hk && _ip && _port)
            {
                return(true);
            }

            showMessageInvalidData();
            return(false);
        }
Example #50
0
        void UpdateMapping(KeyAction action, string name)
        {
            HotKey key = Keyboard.ParseName(name);

            ActionsHotkeys [action] = key;
        }
 private bool IsHotKeyValid(HotKey hotKey, string hotKeyDescription)
 {
     return(hotKey.IsNullOrNone() || _knownShortcuts[hotKey] == hotKeyDescription);
 }
Example #52
0
 private int CompareKey(HotKey x, HotKey y)
 {
     return(x.Action - y.Action);
 }
 private void OnHotKey(HotKey hotKey)
 {
     var vm = DataContext as MainViewModel;
     if (vm != null)
     {
         vm.TextKeyWizardFromHotKey();
     }
 }
 private void RegisterHotKey(HotKey hk)
 {
     RegisterHotKey(hk.Modifier, hk.Key);
 }
Example #55
0
        /// <summary>
        /// 执行初始化操作
        /// </summary>
        private void Init()
        {
            // 接收消息
            Msg.Listen();

            previewForm = new PreviewForm();
            previewForm.LocationChanged += previewForm_LocationChanged;

            currentDisplayMode = DisplayMode.Fixed;

            colorBuffer = new StringBuilder(8, 64);


            if (Settings.Preview.Visible)
            {
                TogglePreview();
            }

            if (Settings.Main.Display == DisplayMode.Fixed)
            {
                FixedPosition();
            }

            SwitchFormatMode(Settings.Main.Format);

            var now = DateTime.Now;

            lastPressTime = Util.Enum <HotKeyType>()
                            .ToDictionary(item => item, item => now);

            HotKey.Bind(Handle);

            new Thread(() =>
            {
                UpdateTooltip();
            })
            {
                IsBackground = true
            }.Start();

            caretTimer = new Timer {
                Interval = caretInterval
            };
            caretTimer.Tick += carettimer_Tick;
            caretTimer.Start();

            colorTimer = new Timer {
                Interval = colorInterval
            };
            colorTimer.Tick += colortimer_Tick;
            colorTimer.Start();

            // 是否监听剪贴板
            if (Settings.Clipboard.Enabled)
            {
                NativeMethods.AddClipboardFormatListener(Handle);
            }

            // 加载语言并选中使用的项
            //new Thread(() =>
            //{
            //    // 当前显示的语言
            //    var locale = (Settings.I18n.Lang ?? System.Globalization.CultureInfo.InstalledUICulture.Name).ToLower();
            //    // 加载自定义语言
            //    var langs = i18n.I18nManager.GetLocalLangs();
            //    if (langs.Any())
            //    {
            //        // 都放到其它语言菜单项下
            //        var others = new ToolStripMenuItem();
            //        resources.ApplyResources(others, "trayMenuLanguageOther");
            //        others.Name = "trayMenuLanguageOther";

            //        // 存放语言 tooltip 的临时量
            //        var temp = new StringBuilder();

            //        var subs = langs.Select(language =>
            //        {
            //            var item = new ToolStripMenuItem();
            //            item.Name = $"customize-lang--{language.Locale}";
            //            item.Text = language.Name;

            //            // 选中项
            //            var l = language.Locale.ToLower();
            //            item.Checked = locale == l || locale.StartsWith(l) || l.StartsWith(locale);

            //            // 提示信息中显示语言的版本以及作者
            //            temp.Append($"{language.Version}\n");
            //            if (language.Authors != null && language.Authors.Any())
            //            {
            //                temp.Append("------------\n");
            //                foreach (var author in language.Authors)
            //                {
            //                    temp.AppendFormat("{0}/{1}\n", author.Name, author.Mail);
            //                    if (string.IsNullOrEmpty(author.HomePage))
            //                    {
            //                        temp.Append(author.HomePage);
            //                    }
            //                }
            //            }
            //            item.ToolTipText = temp.ToString();
            //            temp.Clear();
            //            return item;
            //        });

            //        // 添加菜单项
            //        others.DropDownItems.AddRange(subs.ToArray());
            //        this.InvokeMethod(() =>
            //        {
            //            trayMenuLanguage.DropDownItems.Add(others);
            //        });
            //    }
            //    if (locale.StartsWith("zh"))
            //    {
            //        trayMenuLanguageZH.Checked = true;
            //    }
            //    else if (!langs.Any() || locale.StartsWith("en"))
            //    {
            //        // 没有其它语言或设置为英语时
            //        trayMenuLanguageEN.Checked = true;
            //    }
            //})
            //{
            //    IsBackground = true
            //}.Start();

            DoFirstRunWorks();

            // 自动检查更新
            if (Settings.Update.CheckOnStartup &&
                (DateTime.Now.Date - Settings.Update.LastUpdate).TotalDays >= Settings.Update.Interval)
            {
                update.UpdateForm.ShowWindow(true);
            }

            //RegisterDeskband();

            var worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += AppArgsHandler;
            worker.RunWorkerAsync();

            // 启动 websocket
            if (Settings.Websocket.Enabled)
            {
                new HttpServer("127.0.0.1", Settings.Websocket.Port).Start();
            }
        }
Example #56
0
        /// <summary>
        /// Registers a global key and a modifier. Invokes Method after keypress. If the key already exists it wont do anything
        /// </summary>
        /// <param name="hotkey">object to be sent to the Method. Can be null</param>
        public bool RegisterKey(HotKey hotkey)
        {
            int id = ((int)hotkey.Modifier * 1000) + hotkey.KeyCode;
            if(Hotkeys.ContainsKey(id))
                throw new Exception("Hotkey with the key \"" + hotkey.KeyName + "\" and Modifier \"" + hotkey.ModifierName + "\" already exists.");

            Hotkeys.Add(id, hotkey);
            return RegisterHotKey(handle, id, (int)hotkey.Modifier, hotkey.KeyCode);
        }
Example #57
0
 public bool ChangeMod(HotKey hotkey, ModifierKeys newMod)
 {
     if(Collection.Contains(hotkey)) {
         UnregisterKey(hotkey);
         return RegisterKey(new HotKey(hotkey.Key, newMod, hotkey.Method, hotkey.Parameter));
     }
     return false;
 }
Example #58
0
 public static void AddHotkey(string script)
 {
     HotKey.Add(HKCategory.Scripts, HKSubCat.None, Language.Format(LocString.PlayScript, script), HotkeyCallback,
                script);
 }
Example #59
0
 /// <summary>
 /// Unregisters global key binding from register 
 /// </summary>
 /// <param name="hotkey">Hotkey to unregister</param>
 public bool UnregisterKey(HotKey hotkey)
 {
     var id = ((int)hotkey.Modifier * 1000) + hotkey.KeyCode;
     return UnregisterHotKey(handle, id);
 }
Example #60
0
 public static void RemoveHotkey(string script)
 {
     HotKey.Remove(Language.Format(LocString.PlayScript, script));
 }