Esempio n. 1
0
        public TrayIcon(Window window)
        {
            _icon = new NotifyIcon
            {
                Visible = true,
                Icon = Icon.FromHandle(Resources.ce16.GetHicon()),
                ContextMenu = new ContextMenu(new[]
                {
                    new MenuItem("&Show", (sender, args) => window.Show()),
                    new MenuItem("&Hide", (sender, args) => window.Hide()),
                    new MenuItem("Stay on &Top", (sender, args) =>
                    {
                        window.Topmost = !window.Topmost;
                        ((MenuItem) sender).Checked = window.Topmost;
                    }),
                    new MenuItem("-"),
                    new MenuItem("Settings", (sender, args) =>
                    {
                        var dlg = new SettingsWindow { Owner = window };
                        dlg.ShowDialog();
                    }),
                    new MenuItem("-"),
                    new MenuItem("&Exit", (sender, args) => window.Close())
                })
            };

            _icon.ContextMenu.MenuItems[2].Checked = ConfigManager.Config.StayOnTop;
        }
 /// <summary>
 /// hooks the window to the wpf trace
 /// </summary>
 /// <param name="windowToTest">The window to test</param>
 public static void TestDataBindingsForObject(Window windowToTest)
 {
     EnforceDataBindingTraceListener(windowToTest);
     windowToTest.ShowInTaskbar = false;
     windowToTest.Show();
     windowToTest.Hide();
 }
Esempio n. 3
0
 public static void HideForeground(Window mainWindow)
 {
     mainWindow.Show();
     mainWindow.WindowState = WindowState.Minimized;
     mainWindow.ShowInTaskbar = false;
     mainWindow.Hide();
 }
Esempio n. 4
0
 public static void FadeOutHideWindow(Window window, TimeSpan duration)
 {
     window.Opacity = 1D;
     var board = CreateFadeOutStoryboard(duration);
     board.Completed += (s, e) =>
     {
         window.Hide();
     };
     board.Begin(window);
 }
Esempio n. 5
0
        static void ActivateMainWindow(bool activate, Window mainWindow) {
            if (!activate) {
                mainWindow.Hide();
                return;
            }

            SetToNormalIfMinimized(mainWindow);

            TryActivateMainWindow(mainWindow);
        }
Esempio n. 6
0
		public MainWindow()
		{
			InitializeComponent();

			var vm = this.DataContext as MainWindowViewModel;
			vm.ConfirmationHandler = () =>
				{
					// Note the use of the TaskCompletionSource here
					var tcs = new TaskCompletionSource<bool>();

					// Dynamically build confirmation dialog (just for demo purposes; you
					// could use XAML, too).
					#region Confirmation dialog
					var dialog = new Window() { SizeToContent = SizeToContent.WidthAndHeight };
					var stackPanel = new StackPanel() { Margin = new Thickness(10.0) };
					dialog.Content = stackPanel;

					stackPanel.Children.Add(new TextBlock() { Text = "Are you sure?" });
					Button yesButton, noButton;
					stackPanel.Children.Add(yesButton = new Button() {
						Content = "Yes"
					});
					yesButton.Click += (_, __) => {
						tcs.SetResult(true);
						dialog.Hide();
					};
					stackPanel.Children.Add(noButton = new Button()
					{
						Content = "No"
					});
					noButton.Click += (_, __) =>
					{
						tcs.SetResult(false);
						dialog.Hide();
					};
					#endregion

					dialog.Show();

					return tcs.Task;
				};
		}
Esempio n. 7
0
 /// <summary>
 /// Initializes a new hidden toolwindow to be the owner for all other windows.
 /// This hides the applications icons from the task switcher.
 /// </summary>
 private static void InitializeParentWindow()
 {
     _parentWindow               = new Window();
     _parentWindow.Top           = -100;                   // Location of new window is outside of visible part of screen
     _parentWindow.Left          = -100;
     _parentWindow.Width         = 1;                      // size of window is enough small to avoid its appearance at the beginning
     _parentWindow.Height        = 1;
     _parentWindow.WindowStyle   = WindowStyle.ToolWindow; // Set window style as ToolWindow to avoid its icon in AltTab
     _parentWindow.ShowInTaskbar = false;
     _parentWindow.Show();                                 // We need to show window before set is as owner to our main window
     _parentWindow.Hide();                                 // Hide helper window just in case
 }
Esempio n. 8
0
        static BubblesManager()
        {
            _views = new List<Window>();

            OwnerWindow = new Window();
            OwnerWindow.WindowStyle = WindowStyle.ToolWindow;
            OwnerWindow.Left = 10000;
            OwnerWindow.Top = 1000;
            OwnerWindow.Width = 1;
            OwnerWindow.Show();
            OwnerWindow.Hide();
        }
Esempio n. 9
0
        void Hide(System.Windows.Window window)
        {
            var windowMain = window as WindowMain;

            if (windowMain != null)
            {
                windowMain.HideWindow();
            }
            else
            {
                window.Hide();
            }
        }
        public void Show(string account, Uri authenticationUri, Uri redirectUri)
        {
            if (window == null) {
                waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
                var uiThread = new Thread(() => {
                    window = new Window() { Title = account };
                    window.Closing += (s, e) => {
                        window.Hide();
                        waitHandle.Set();
                        e.Cancel = true;
                    };

                    browser = new WebBrowser();
                    browser.Loaded += (s, e) => {
                        browser.Navigate(authenticationUri);
                    };
                    browser.Navigating += (s, e) => {
                        if (redirectUri.IsBaseOf(e.Uri) && redirectUri.AbsolutePath == e.Uri.AbsolutePath) {
                            var parameters = new NameValueCollection();
                            foreach (var parameter in e.Uri.Query.TrimStart('?').Split('&')) {
                                var nameValue = parameter.Split('=');
                                parameters.Add(nameValue[0], nameValue[1]);
                            }
                            var handler = Authenticated;
                            handler?.Invoke(this, new AuthenticatedEventArgs(parameters));
                            e.Cancel = true;
                        }
                    };
                    browser.Navigated += (s, e) => {
                        if (authenticationUri.IsBaseOf(e.Uri))
                            SetForegroundWindow(new WindowInteropHelper(window).Handle);
                    };

                    window.Content = browser;
                    window.Show();

                    System.Windows.Threading.Dispatcher.Run();
                });
                uiThread.SetApartmentState(ApartmentState.STA);
                uiThread.Start();
            } else {
                window.Dispatcher.Invoke(() => {
                    browser.Source = authenticationUri;
                    window.Title = account;
                    window.Show();
                });
            }

            waitHandle.WaitOne();
        }
Esempio n. 11
0
        public TrayMainWindows(Window window)
        {
            _window = window;
            try
            {
                _notifyIcon = new System.Windows.Forms.NotifyIcon();
                _notifyIcon.Text = _window.Title;
                _notifyIcon.Icon = new System.Drawing.Icon("TodoTouch_512.ico");
                _notifyIcon.Visible = true;
                _notifyIcon.DoubleClick += DoubleClick;

                _window.Closed += (sender, args) => { this.Dispose(); };
                _window.StateChanged += (sender, args) => { if (_window.WindowState == WindowState.Minimized) _window.Hide(); };
            }
            catch (Exception ex)
            {
                var msg = "Error create tray icon";
                Log.Error(msg, ex);
            }
        }
        /// <summary>
        /// This is a helper class to rapidly add a minimize-to-tray functionality in WPF Win32 apps.
        /// </summary>
        /// <param name="Window">A reference to the window to control.</param>
        /// <param name="Icon">A string referencing the .ICO path. The Icon *must* be set for this class to work properly.</param>
        /// <param name="StartMinimized">Should the window be minimized to the tray immediately?</param>
        /// <param name="RequireDoubleClick">Should the tray icon require a double-click, or will a single-click suffice?</param>
        public MinimizeToSystemTray(Window Window, Icon Icon, bool StartMinimized = false, bool RequireDoubleClick = false)
        {
            if (Icon == null)
                throw new Exception("Icon must be set for this class to function properly.");
            if (Window == null)
                throw new Exception("Window must not be null.");
            this.window = Window;
            Window.Closing += window_Closing;
            Window.StateChanged += window_StateChanged;
            ni = new NotifyIcon();
            ni.Icon = Icon;
            ni.Visible = true;
            if (RequireDoubleClick)
                ni.DoubleClick += IconClick;
            else
                ni.Click += IconClick;

            if(StartMinimized)
            {
                Window.WindowState = System.Windows.WindowState.Minimized;
                Window.Hide();
            }
        }
Esempio n. 13
0
        public TrayMainWindows(Window window)
        {
            _window = window;
            try
            {
                _notifyIcon = new System.Windows.Forms.NotifyIcon();
                _notifyIcon.Text = _window.Title;
                Stream iconStream = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/TodoTouch_512.ico")).Stream;
                _notifyIcon.Icon = new System.Drawing.Icon(iconStream);
                _notifyIcon.Visible = true;
                _notifyIcon.DoubleClick += DoubleClick;

                _notifyIcon.ContextMenu = new ContextMenu();
                _notifyIcon.ContextMenu.MenuItems.Add("E&xit", new EventHandler(ExitClick));

                _window.Closed += (sender, args) => { this.Dispose(); };
                _window.StateChanged += (sender, args) => { if (_window.WindowState == WindowState.Minimized) _window.Hide(); };
            }
            catch (Exception ex)
            {
                var msg = "Error create tray icon";
                Log.Error(msg, ex);
            }
        }
Esempio n. 14
0
		void ChooseStation ()
		{
			Locations loc = new Locations ();
			TreeStore store = new TreeStore (typeof (string), typeof (string), typeof (string));

			List <Region> regions = loc.Regions;
			foreach (Region r in regions) {
				TreeIter iter = store.AppendValues (r.Name, GetTypeName (r), String.Empty);
				AddTreeEntries (r, store, iter);
			}
			
			Window win = new Window ("Select your location");
			win.SetDefaultSize (400,400);

			VBox vbox = new VBox (false, 0);
			win.Add (vbox);
			
			ScrolledWindow sw = new ScrolledWindow ();
			vbox.PackStart (sw, true, true, 0);
			
			TreeView tv = new TreeView (store);
			tv.HeadersVisible = true;
			tv.EnableSearch = true;
			
			tv.AppendColumn ("Location", new CellRendererText (), "text", 0);
			tv.AppendColumn ("Type", new CellRendererText (), "text", 1);
                        tv.AppendColumn ("Code", new CellRendererText (), "text", 2);
			
			sw.Add (tv);
			sw.Show ();

			HBox hbox = new HBox (true, 0);
			Button closeBtn = new Button (Stock.Close);
			closeBtn.Clicked += delegate {
				TreeSelection sel = tv.Selection;
				TreeModel model;
				TreeIter iter;

				string val = null;
				if (sel.GetSelected (out model, out iter)) {
					val = (string) model.GetValue (iter, 1);
					if (val == "Location")
						val = (string) model.GetValue (iter, 2);
					else
						val = null;
				}
				
				win.Hide ();
				win.Destroy ();

				if (!String.IsNullOrEmpty (val)) {
					stationID.Text = val;
					StoreConfig ();
					UpdateData (null, null);
				}
			};
			
			hbox.PackEnd (closeBtn, false, false, 0);
			vbox.PackStart (hbox, false, false, 1);
			
			win.ShowAll ();
		}
Esempio n. 15
0
 private void HideForm(Window varControl)
 {
     if (!varControl.Dispatcher.CheckAccess())
     {
         varControl.Dispatcher.Invoke(new Action(() => HideForm(varControl)));
     }
     else
     {
         varControl.Hide();
     }
 }
Esempio n. 16
0
        /// <summary>
        /// A window with its own UI Thread.
        /// </summary>
        public ThreadedWindow(string xamlPath, object dataContext, string name = "", int height = 0, int width = 0)
        {            
            try
            {
                

                if (String.IsNullOrEmpty(xamlPath))
                    throw new ArgumentException("xamlPath");

                if (dataContext == null)
                    throw new ArgumentException("dataContext");

                if (!File.Exists(xamlPath))
                    throw new ArgumentException("xamlPath: file doesn't exist");

                _thread = new Thread(threadDataContext =>
                {
                    _window = new Window
                    {
                        Height = height > MinimumHeight ? height : 750,
                        Width = height > MininumWidth ? width : 1200,
                        MinHeight = MinimumHeight,
                        MinWidth = MininumWidth,
                        Title = name,
                        Content = UILoader.LoadAndTransformXamlFile<UserControl>(xamlPath),
                        DataContext = threadDataContext
                    };

                    IsWindowCreated = true;

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Application.Current.MainWindow.Closing += (sender, args) =>
                        {
                            Logger.Log("ThreadedWindow: Closing {0} window ", name);
                            _allowedToClose = true;
                            _dispatcher.InvokeShutdown();
                        };
                    });                    

                    // Hide window instead of closing to avoid WPF thread ownership issues.
                    _window.Closing += (sender, args) =>
                    {
                        if (!_allowedToClose)
                        {
                            Logger.Log("ThreadedWindow: Hiding {0} window ", name);                            
                            _window.Hide();
                            OnHidden();
                            args.Cancel = true;
                        }
                        _isWindowOpen = false;
                    };

                    _window.ContentRendered += (sender, args) =>
                    {
                        IsWindowLoaded = true;
                    };

                    _window.Closed += (s, e) =>
                    {
                        Logger.Log("ThreadedWindow: Shutting down {0} thread ", name);
                        _window.Dispatcher.InvokeShutdown();
                    };

                    _window.WindowStartupLocation = WindowStartupLocation.CenterScreen;

                    Dispatcher.Run();
                });

                // Single thread apartment prevents access to owned objects by other threads
                _thread.SetApartmentState(ApartmentState.STA);

                if (!String.IsNullOrEmpty(name))
                    _thread.Name = name + " ThreadedWindow";

                _thread.Start(dataContext);

                _internalTimer.Tick += InternalTimerTick;
                _internalTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
                _internalTimer.Start();
            }
            catch (Exception ex)
            {
                Logger.Log("Unable to create ThreadedWindow: {0}", ex);
            }
 
        }
Esempio n. 17
0
 /// <summary>
 /// Initializes a new hidden toolwindow to be the owner for all other windows.
 /// This hides the applications icons from the task switcher.
 /// </summary>
 private static void InitializeParentWindow()
 {
     _parentWindow = new Window();
     _parentWindow.Top = -100; // Location of new window is outside of visible part of screen
     _parentWindow.Left = -100;
     _parentWindow.Width = 1; // size of window is enough small to avoid its appearance at the beginning
     _parentWindow.Height = 1;
     _parentWindow.WindowStyle = WindowStyle.ToolWindow; // Set window style as ToolWindow to avoid its icon in AltTab
     _parentWindow.ShowInTaskbar = false;
     _parentWindow.Show(); // We need to show window before set is as owner to our main window
     _parentWindow.Hide(); // Hide helper window just in case
 }
Esempio n. 18
0
 public void Close()
 {
     _WindowCore.Hide();
     _WindowCore.Content = null;
 }
Esempio n. 19
0
        private void BuildSearchToolWindow()
        {
            if (toolPickerUC == null)
            {
                toolPickerUC = new searchTool();
                toolPicker_VM = toolPickerUC.DataContext as searchTool_ModelView;
            }

            toolPickerWindow = new Window()
            {
                Content = toolPickerUC,
                Title = "Gép választó",
                SizeToContent = SizeToContent.WidthAndHeight
            };

            toolPicker_VM.ToolSelected += (s, a) =>
            {
                ToolRepresentation tool = s as ToolRepresentation;
                tool.ValidationRules = new ToolValidationRules();
                viewModel.selectedTool = tool;
                toolPickerWindow.Hide();
            };
        }
        //When the notification bar loses keyboard focus, the retrieval is paused, text is sent to the database, and the timer is restarted
        private void Notifications_Bar_LostFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            StopTimer();

            #region Ugly Workaround
            //Ugliest workaround for a bug in the history of man?
            //A blank window is the only way I could find for the 'notification' text from the UI to be updated and pass into the following functions
            Window window = new Window();
                window.Visibility = Visibility.Hidden;
                window.Height = 0;
                window.Width = 0;
                window.Top = 5000;
                window.Show();
                window.Hide();
                window.Close();
            #endregion

            //Send the notification
            Notif.Text = notification;
            Notif.SendNotification();

            StartTimer();

            //Should it retrieve the notification right after sending? I decided not to
            //Notif.RetrieveNotification();
            //notification = Notif.Text;
        }
Esempio n. 21
0
        public MailTray(GmailDataHelper gdh)
        {
            this.gdh = gdh;
            LoadImage();
            ni = new NotifyIcon();

            try
            {
                ni.Icon = EmptyIco;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to retreive the Icon " + ex.Message);
                ni.Icon = new Icon(SystemIcons.Application, 40, 40);
            }

            #region Left Click
            niMenuLeftClick = new System.Windows.Forms.ContextMenuStrip();
            niMenuLeftClick.Items.Add(gdh.Datas.Login, peopleIM);
            niMenuLeftClick.Items.Add("-");
            niMenuLeftClick.Items.Add(new ToolStripMenuItem("Update", mailUpdateIM, (s, ee) =>
            {
                gdh.UpdateData();
            }));
            niMenuLeftClick.Items.Add(new ToolStripMenuItem("Again", mailAgainIM, (s, ee) =>
            {
                foreach (var mail in gdh.Datas.Mails)
                {
                    gdh.NotifyMail(mail);
                }

            }));
            niMenuLeftClick.Items.Add(new ToolStripMenuItem("Open", mailViewIM, (s, ee) =>
            {
                System.Diagnostics.Process.Start(gdh.Datas.Link);
            }));
            niMenuLeftClick.Items.Add("-");
            niMenuLeftClick.Items.Add(new ToolStripMenuItem("Quit", closeIM, (s, ee) =>
            {
                if (System.Windows.Forms.Application.MessageLoop)
                {
                    // WinForms app
                    System.Windows.Forms.Application.Exit();
                }
                else
                {
                    // Console app
                    System.Environment.Exit(1);
                }
            }));
            #endregion

            #region Right Click
            niMenuRightClick = new System.Windows.Forms.ContextMenuStrip();
            ni.ContextMenuStrip = niMenuRightClick;

            ni.ContextMenuStrip.Items.Add(new ToolStripMenuItem("About", infoIM, (s, ee) => {
                if (Wabout == null)
                {
                    Wabout = new AboutWindow();
                    Wabout.Closing += (ss, e) =>
                    {
                        e.Cancel = true;
                        Wabout.Hide();
                    };
                    Wabout.Show();
                }
                else
                {
                    UIUtil.BringToFrontWindow(Wabout);
                }
            }));

            ni.ContextMenuStrip.Items.Add(new ToolStripMenuItem("Config", gearIM, (s, ee) =>
            {
                if (Wsettings == null)
                {
                    Wsettings = new SettingsWindow();
                    Wsettings.DataContext = new SettingsVM(gdh.Datas.Login, gdh.Settings);
                    Wsettings.Closing += (ss, e) =>
                    {
                        e.Cancel = true;
                        Wsettings.Hide();
                    };
                    Wsettings.Show();
                }
                else
                {
                    UIUtil.BringToFrontWindow(Wsettings);
                }
            }));
            #endregion

            gdh.Datas.PropertyChanged += gdh_PropertyChanged;
            gdh.Datas.Mails.CollectionChanged += Mails_CollectionChanged;

            ni.MouseClick += new MouseEventHandler(ni_MouseClick);
            ni.Visible = true;
            ni.Text = gdh.ToString();
        }
Esempio n. 22
0
        public Context()
        {
            _components = new System.ComponentModel.Container();

            // Load Settings, but first create if not exist
            if (!File.Exists(@"config.ini"))
            {
                var height = SystemInformation.VirtualScreen.Height;
                File.WriteAllText(@"config.ini",
                                  "[Settings]" + Environment.NewLine +
                                  "displayindex=2" + Environment.NewLine +
                                  "xaxis=20" + Environment.NewLine +
                                  "yaxis=" + (height - new display().Height - 60) + Environment.NewLine +
                                  "displaytime=2" + Environment.NewLine +
                                  "notify=True" + Environment.NewLine +
                                  "logkeys=True" + Environment.NewLine +
                                  "stdkeys=True" + Environment.NewLine);
            }
            if (File.Exists(@"config.ini"))
            {
                var myini = new IniFile(@"config.ini");
                location = new System.Drawing.Point(
                    Convert.ToInt16(myini.Read("xaxis", "Settings")),
                    Convert.ToInt16(myini.Read("yaxis", "Settings"))
                    );
                displaytime = Convert.ToInt16(myini.Read("displaytime", "Settings"));
                notify      = Convert.ToBoolean(myini.Read("notify", "Settings"));
                stdkeys     = Convert.ToBoolean(myini.Read("stdkeys", "Settings"));
                logkeys     = Convert.ToBoolean(myini.Read("logkeys", "Settings"));
            }
            keyui          = new display();
            keyui.Location = location;

            _contextmenustrip = new ContextMenuStrip();
            _contextmenustrip.Items.Add(NewToolStripItem("Stop recording", (o, s) => {
                var firstItem = _contextmenustrip.Items[0];
                if (record)
                {
                    // Stop Recording
                    record         = false;
                    firstItem.Text = "Start recording";
                    DisplayStatusMessage("Kling : Service stopped");
                }
                else
                {
                    // Start Recording
                    record         = true;
                    firstItem.Text = "Stop recording";
                    DisplayStatusMessage("Kling : Service started");
                }
            }));
            _contextmenustrip.Items.Add(new ToolStripSeparator());
            _contextmenustrip.Items.Add(NewToolStripItem("Settings", ShowSettings));
            _contextmenustrip.Items.Add(NewToolStripItem("Restart", (o, s) => { System.Windows.Forms.Application.Restart(); }));
            _contextmenustrip.Items.Add(NewToolStripItem("About", (o, s) => {
                // About screen dialog
                if (!isaboutshowing)
                {
                    isaboutshowing        = true;
                    Components.AboutUI ui = new Components.AboutUI();
                    ui.Closing           += (obj, ex) => { isaboutshowing = false; };
                    ui.ShowDialog();
                }
            }));
            _contextmenustrip.Items.Add(new ToolStripSeparator());
            _contextmenustrip.Items.Add(NewToolStripItem("Exit", (o, s) =>
            {
                // Exit Button
                if (eventHookFactory != null)
                {
                    eventHookFactory.Dispose();
                }
                System.Windows.Forms.Application.Exit();
            }));

            _notifyIcon = new NotifyIcon(_components)
            {
                ContextMenuStrip = _contextmenustrip,
                Icon             = Kling.Properties.Resources.icon,
                Text             = "Kling",
                Visible          = true,
            };

            _notifyIcon.DoubleClick += ShowSettings;

            _hiddenWindow = new System.Windows.Window();
            _hiddenWindow.Hide();
            DisplayStatusMessage(_notifyIcon.Text + ": Start pressing keys");

            keyboardWatcher = eventHookFactory.GetKeyboardWatcher();
            keyboardWatcher.OnKeyboardInput += (s, e) =>
            {
                if (!record)
                {
                    return;
                }

                if (_macroEvents != null)
                {
                    _macroEvents.Add(e);
                }

                if (e.KeyMouseEventType == MacroEventType.KeyPress)
                {
                    var keyEvent = (KeyPressEventArgs)e.EventArgs;
                    if (e.KeyMouseEventType.ToString().Contains("KeyUp"))
                    {
                        // This will also show a form
                        DisplayKeys(getKeys(keyEvent.KeyChar.ToString()));
                    }
                }
                else
                {
                    var keyEvent = (System.Windows.Forms.KeyEventArgs)e.EventArgs;
                    if (e.KeyMouseEventType.ToString().Contains("KeyUp"))
                    {
                        // This will show a form
                        var keys = keyEvent.KeyCode;

                        // Suppress next event
                        if (suppresskey)
                        {
                            suppresskey = false;
                            return;
                        }

                        if (isControlPressed(keyEvent, keys))
                        {
                            specialkeys = true;
                            if (isShiftPressed(keyEvent, keys))
                            {
                                showKey("Ctrl + Shift + ", keys);
                            }
                            else if (isAltPressed(keyEvent, keys))
                            {
                                showKey("Ctrl + Alt + ", keys);
                            }
                            else
                            {
                                DisplayKeys("Ctrl + " + getKeys(keys.ToString()));
                            }
                        }
                        else if (isAltPressed(keyEvent, keys))
                        {
                            specialkeys = true;
                            if (isShiftPressed(keyEvent, keys))
                            {
                                showKey("Alt + Shift + ", keys);
                            }
                            else if (isControlPressed(keyEvent, keys))
                            {
                                showKey("Alt + Ctrl + ", keys);
                            }
                            else
                            {
                                DisplayKeys("Alt + " + getKeys(keys.ToString()));
                            }
                        }
                        else if (isShiftPressed(keyEvent, keys))
                        {
                            specialkeys = true;
                            if (isControlPressed(keyEvent, keys))
                            {
                                showKey("Shift + Ctrl + ", keys);
                            }
                            else if (isAltPressed(keyEvent, keys))
                            {
                                showKey("Shift + Alt + ", keys);
                            }
                            else
                            {
                                DisplayKeys("Shift + " + getKeys(keys.ToString()));
                            }
                        }
                        else
                        {
                            if (!specialkeys)
                            {
                                DisplayKeys(getKeys(keys.ToString()));
                            }
                            else
                            {
                                specialkeys = false;
                            }
                        }
                    }
                }
            };

            _macroEvents = new List <MacroEvent>();
            keyboardWatcher.Start(Hook.GlobalEvents());

            timer          = new Timer();
            timer.Interval = displaytime * 1000;
            timer.Tick    += async(o, e) => {
                timer.Stop();
                while (keyui.Opacity > 0.0)
                {
                    await Task.Delay(20);

                    keyui.Opacity -= 0.05;
                }
                keyui.Opacity = 0;
                keyui.Hide();
                keyui.Opacity = 0.7;
            };
        }
Esempio n. 23
0
        private void BuildSearchContactWindow()
        {
            contactPicker = new searchCustomer(searchCustomerTypeEnum.Contact);
            contactPicker_VM = contactPicker.DataContext as searchCustomer_ModelView;
            contactPickerWindow = new Window()
            {
                Title = "Kapcsolattartó választó",
                Content = contactPicker,
                SizeToContent = SizeToContent.WidthAndHeight
            };

            contactPicker_VM.CustomerSelected += (s, a) =>
            {
                DataProxy.Instance.AddContact(viewModel.selectedCustomer, (PersonRepresentation)s);
                ((FirmRepresentation)viewModel.selectedCustomer).contacts.Add((CustomerBaseRepresentation)s);
                contactPickerWindow.Hide();
            };
        }
Esempio n. 24
0
		public void ExtentSimpleCanContentScrollHorizontal ()
		{
			Window w = new Window ();
			ScrollViewer v = new ScrollViewer ();
			v.CanContentScroll = true;
			w.Content = v;
			StackPanel p = new StackPanel ();
			p.Orientation = Orientation.Horizontal;
			v.Content = p;
			global::System.Windows.Controls.Button b = new global::System.Windows.Controls.Button ();
			p.Children.Add (b);
			w.Show ();
			Assert.AreEqual (p.ExtentWidth, 1, "1");
			Assert.AreEqual (p.ExtentHeight, Utility.GetEmptyButtonSize (), "2");
			p.Orientation = Orientation.Vertical;
			Assert.AreEqual (p.ExtentWidth, 0, "3");
			Assert.AreEqual (p.ExtentHeight, 0, "4");
			w.Hide ();
			w.Show ();
			Assert.AreEqual (p.ExtentWidth, 0, "5");
			Assert.AreEqual (p.ExtentHeight, 0, "6");
		}
Esempio n. 25
0
        internal static void ShowView(Window view, bool show, bool updateActive=true)
        {
            if (!view.CheckAccess())
            {
                var action = new Action(() => ShowView(view, show, updateActive));
                view.Dispatcher.Invoke(action);
                return;
            }

            if (updateActive)
                ConfigurationHelper.Configuration.Repositories.FirstOrDefault(r => r.View == view).isActive = show;

            if (show)
            {
                if (view.Visibility == Visibility.Hidden) Position(view);
                view.Show();
            }
            else 
                view.Hide();
        }
Esempio n. 26
0
        private void BuildCityChooserWindow()
        {
            cityPickerWindow = new SearchCity();
            cityPicker_VM = cityPickerWindow.DataContext as SearchCity_ViewModel;

            cityPicker_VM.citySelected += (s, a) =>
            {
                viewModel.selectedCustomer.city = (CityRepresentation)s;
                cityPickerWindow.Hide();
            };
        }
Esempio n. 27
0
        private void ExportToPNG_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Title = "Select visualisation file";
            openDialog.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
            openDialog.FilterIndex = 0;
            Nullable<bool> result = openDialog.ShowDialog();

            if (result == true)
            {
                string tempFileName = openDialog.FileName;
                //string tempFileName = @"C:\Users\Iman\Documents\Visual Studio 2012\Projects\CONVErT\CONVErT\Test\Working\HorBarchart.xml";
                try
                {
                    XAMLRenderer rend = new XAMLRenderer();
                    UIElement rendResult = rend.createStillVisualisation(tempFileName);

                    if (rendResult != null)
                    {
                        //get PNG file name
                        SaveFileDialog saveDialog = new SaveFileDialog();

                        saveDialog.Title = "Export to PNG";
                        saveDialog.Filter = "PNG files (*.png)|*.png|All files (*.*)|*.*";
                        saveDialog.FileName = "";
                        saveDialog.ShowDialog();

                        if (!saveDialog.FileName.Equals(""))
                        {
                            //resulted visualisation model file
                            string savePngFile = saveDialog.FileName;
                            //where the reaulted reverse will be saved

                            if (!savePngFile.ToLower().EndsWith(".png"))
                                savePngFile += ".png";

                            //save to file
                            using (Stream imageStream = File.Create(savePngFile))
                            {
                                Window wind = new Window();
                                wind.WindowStyle = WindowStyle.None;
                                wind.ShowInTaskbar = false;
                                wind.ShowActivated = false;

                                // Create Minimized so the window does not show. wind.WindowState = System.Windows.WindowState.Minimized;
                                wind.SizeToContent = SizeToContent.WidthAndHeight;

                                wind.Content = (UIElement)rendResult;
                                wind.Show(); // The window needs to be created for the XAML elements to be rendered.

                                BitmapSource bitmapSrc = visualToBitmap(wind, 100, 100);//dpiX, dpiY);
                                BitmapEncoder encoder = new PngBitmapEncoder();

                                encoder.Frames.Clear();
                                encoder.Frames.Add(BitmapFrame.Create(bitmapSrc));
                                encoder.Save(imageStream);

                                imageStream.Flush();

                                wind.Hide();
                            }
                        }
                        else
                            reportMessage("Failed to save PNG file!", ReportIcon.Error);
                    }
                    else
                        reportMessage("Export to PNG -> Rendered XAML returned empty!", ReportIcon.Error);
                }
                catch (Exception ex)
                {
                    reportMessage("Exception in Visualiser.ExportToPNG -> " + ex.Message, ReportIcon.Error);
                }
            }
        }
Esempio n. 28
0
        private void BuildSearchCustomerWindow()
        {
            if (customerPicker == null)
            {
                customerPicker = new searchCustomer(searchCustomerTypeEnum.Customer);
                customerPicker_VM = customerPicker.DataContext as searchCustomer_ModelView;
            }
            customerPickerWindow = new Window()
            {
                Title = "Ügyfél választó",
                Content = customerPicker,
                SizeToContent = SizeToContent.WidthAndHeight
            };

            customerPicker_VM.CustomerSelected += (s, a) =>
            {
                viewModel.selectedCustomer = (CustomerBaseRepresentation)s;
                customerPickerWindow.Hide();
            };
        }
Esempio n. 29
0
        /// <summary>
        /// Metodo que crea el notifyIcon, se pasa el form sobre el que se va aplicar.
        /// </summary>
        /// <param name="form">Formulario que se aplica al NotifyIcon</param>
        /// <returns>torna un objecto de tipo NotifyIcon</returns>
        /// <history>
        /// [michan]  25/04/2016  Created
        /// </history>
        public static NotifyIcon Notify(System.Windows.Application app = null, System.Windows.Window form = null, string title = null)
        {
            /// Objeto del tipo NotifyIcon
            System.Windows.Forms.NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon();
            //_frm = form;
            ///icono que muestra la nube de notificación. será tipo info, pero existen warning, error, etc..
            notifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info;
            string strTitle = "";

            ///la ruta del icono que se va a mostrar cuando la app esté minimizada.
            if (form != null)
            {
                if (form.Icon != null)
                {
                    Uri iconUri = new Uri(form.Icon.ToString(), UriKind.RelativeOrAbsolute);
                    System.IO.Stream iconStream = System.Windows.Application.GetResourceStream(new Uri(form.Icon.ToString())).Stream;
                    notifyIcon.Icon = new System.Drawing.Icon(iconStream);
                }
                strTitle = form.Title.ToString();
            }
            // AppContext.BaseDirectory
            else if (app != null)
            {
                notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
            }


            if (title != null)
            {
                strTitle = title;
            }

            //notifyIcon.Icon = new System.Drawing.Icon(iconStream);//@"M:\PalaceResorts\Client4.6\IntelligenceMarketing\IM.Base\Images\IM.ico");
            /// Mensaje que se muestra al minimizar al formulario
            notifyIcon.BalloonTipTitle = "Information";

            notifyIcon.Text           = (!String.IsNullOrEmpty(strTitle) && !String.IsNullOrWhiteSpace(strTitle)) ? strTitle : "The application";
            notifyIcon.BalloonTipText = "Running " + strTitle;
            notifyIcon.Visible        = true;

            /// Evento clic para mostrar la ventana cuando se encuentre minimizada.
            notifyIcon.Click += new EventHandler(
                (s, e) =>
            {
                if (notifyIcon != null)
                {
                    /// cuando se pulse el boton mostrará informacion, cambiaremos los textos para que muestre que la app esta trabajando...
                    notifyIcon.BalloonTipIcon  = ToolTipIcon.Warning;
                    notifyIcon.BalloonTipText  = strTitle + " is working...";
                    notifyIcon.BalloonTipTitle = "Wait...";
                    notifyIcon.ShowBalloonTip(400);
                    notifyIcon.BalloonTipIcon  = ToolTipIcon.Info;
                    notifyIcon.BalloonTipText  = strTitle + " Running...";
                    notifyIcon.BalloonTipTitle = "Information";
                }
            }
                );

            notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(
                (s, e) =>
            {
                if (notifyIcon != null)
                {
                    if (form != null)
                    {
                        form.Show();
                        form.WindowState = WindowState.Normal;
                        form.Activate();
                    }
                    else if (app != null)
                    {
                        app.MainWindow.Show();
                        app.MainWindow.WindowState = WindowState.Normal;
                        app.MainWindow.Activate();
                    }

                    notifyIcon.Visible = true;
                    notifyIcon.ContextMenu.MenuItems[0].Visible = false;
                    notifyIcon.ContextMenu.MenuItems[1].Visible = true;
                }
            }
                );



            // agrgegamos el menu en el notyficon
            notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(
                /// Menu contextual que sera visible en el icono
                new System.Windows.Forms.MenuItem[]
            {
                new System.Windows.Forms.MenuItem(
                    "Show",// opcion de abrir para cuando la ventana este minimizada
                    (s, e) =>
                {
                    if (form != null)
                    {
                        //Se agrega al menu la opcion para mostrar el formulario
                        form.Show();
                        form.WindowState = WindowState.Normal;
                        form.Activate();
                    }
                    else if (app != null)
                    {
                        app.MainWindow.Show();
                        app.MainWindow.WindowState = WindowState.Normal;
                        app.MainWindow.Activate();
                    }



                    notifyIcon.Visible = true;
                    notifyIcon.ContextMenu.MenuItems[0].Visible = false;
                    notifyIcon.ContextMenu.MenuItems[1].Visible = true;
                }
                    ),
                new System.Windows.Forms.MenuItem(
                    "Hide",// opcion para mostrar la ventana cuando se encuentre maximizada
                    (s, e) =>
                {
                    if (form != null)
                    {
                        // Se agrega en el menu la opcion para ocultar el form
                        form.Hide();
                        form.WindowState = WindowState.Minimized;
                    }
                    else if (app != null)
                    {
                        app.MainWindow.Hide();
                        app.MainWindow.WindowState = WindowState.Minimized;
                    }

                    notifyIcon.Visible = true;
                    notifyIcon.ShowBalloonTip(400);
                    notifyIcon.ContextMenu.MenuItems[0].Visible = true;
                    notifyIcon.ContextMenu.MenuItems[1].Visible = false;
                }
                    ),
                new System.Windows.Forms.MenuItem("-"),
                new System.Windows.Forms.MenuItem("Close",
                                                  (s, e) => {
                    if (form != null)
                    {
                        form.Close();
                    }
                    else if (app != null)
                    {
                        app.Shutdown();
                    }
                }
                                                  )
            }
                );

            notifyIcon.ContextMenu.MenuItems[0].Visible = false;
            notifyIcon.ContextMenu.MenuItems[1].Visible = true;

            return(notifyIcon);
        }
Esempio n. 30
0
        /// <summary>
        /// Shows a window that contains the TouchControl
        /// </summary>
        /// <param name="entryPoint"></param>
        /// <param name="touchEvent"></param>
        internal static void Show(TouchBranchCommand entryPoint, TouchEventArgs touchEvent)
        {
            var position = touchEvent.GetTouchPoint(null).Position.FixCoordinates(touchEvent.Source as DependencyObject);

            Window touchWindow;
            if (!windowCache.TryGetValue(entryPoint, out touchWindow))
            {
                touchWindow = new Window()
                {
                    ShowInTaskbar = false,
                    ShowActivated = true,
                    AllowsTransparency = true,
                    Background = new SolidColorBrush(Colors.Transparent),
                    WindowStyle = WindowStyle.None,
                    WindowStartupLocation = WindowStartupLocation.Manual,
                    Width = TouchControlShapeFactory.DIAMETER + 2, // 2 accounts for 1px margins of the canvas
                    Height = TouchControlShapeFactory.DIAMETER + 2,
                };
                touchWindow.Content = new TouchControl(entryPoint, touchWindow)
                {
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                };
                touchWindow.LostFocus += (s, e) => { touchWindow.Hide(); };
                touchWindow.Deactivated += (s, e) => { touchWindow.Hide(); };
                touchWindow.Closed += (s, e) =>
                {
                    touchWindow.Content = null;
                    touchWindow = null;
                    windowCache.Remove(entryPoint);
                };

                windowCache.Add(entryPoint, touchWindow);
            }
            // Move the window such that "position" point is in the middle, and show the window
            touchWindow.Left = position.X - TouchControlShapeFactory.DIAMETER / 2;
            touchWindow.Top = position.Y - TouchControlShapeFactory.DIAMETER / 2;
            touchWindow.Show();
            touchWindow.Focus();
        }
Esempio n. 31
0
        /// <summary>
        /// Creates a touch control
        /// </summary>
        /// <param name="entryCommand"></param>
        /// <param name="parentWindow"></param>
        public TouchControl(TouchBranchCommand entryCommand, Window parentWindow)
        {
            InitializeComponent();
            initializeBrushes();

            var segmentAmount = entryCommand.Commands.Count();
            int index = 0;
            foreach (var command in entryCommand.Commands)
            {
                // Slice shape:
                var segment = TouchControlShapeFactory.GetSegment(segmentAmount, index);
                var path = new Path()
                {
                    Data = segment,
                };
                touchCanvas.Children.Add(path);

                // Invisible border that holds and centers the text label:
                var border = new Border()
                {
                    Width = TEXT_AVAILABLE_WIDTH,
                    Height = TEXT_AVAILABLE_HEIGHT,
                    IsHitTestVisible = false,
                };
                var textCenter = TouchControlShapeFactory.GetTextPosition(segmentAmount, index);
                Canvas.SetLeft(border, textCenter.X - TEXT_AVAILABLE_WIDTH / 2);
                Canvas.SetRight(border, textCenter.X + TEXT_AVAILABLE_WIDTH / 2);
                Canvas.SetTop(border, textCenter.Y - TEXT_AVAILABLE_HEIGHT / 2);
                Canvas.SetBottom(border, textCenter.Y + TEXT_AVAILABLE_HEIGHT / 2);

                // The text label, centered inside the invisible border
                var text = new TextBlock()
                {
                    Text = command.DisplayName,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                };
                border.Child = text;
                touchCanvas.Children.Add(border);

                // Give action to the slice. Looking forward to using extended `is` expression in pattern matching (https://github.com/dotnet/roslyn/issues/206)
                var vsCommand = command as TouchVSCommand;
                var branchCommand = command as TouchBranchCommand;
                if (vsCommand != null)
                {
                    path.TouchUp += (s, e) =>
                    {
                        e.Handled = true;
                        VisualStudioModule.ExecuteCommand(vsCommand.VsCommandName, vsCommand.VsCommandParams);
                        parentWindow.Hide();
                    };
                }
                else if (branchCommand != null)
                {
                    path.TouchUp += (s, e) =>
                    {
                        e.Handled = true;
                        parentWindow.Hide();
                        Show(branchCommand, e);
                    };
                }

                index++;
            }
        }
 /// <summary>
 /// </summary>
 /// <param name="window"></param>
 /// <param name="stayOnTop"></param>
 /// <param name="force"></param>
 private static void ToggleTopMost(Window window, bool stayOnTop, bool force)
 {
     if (window.Topmost && stayOnTop && !force)
     {
         return;
     }
     window.Topmost = false;
     if (!stayOnTop)
     {
         if (window.IsVisible)
         {
             window.Hide();
         }
         return;
     }
     window.Topmost = true;
     if (!window.IsVisible)
     {
         window.Show();
     }
 }
Esempio n. 33
0
 /// <summary>
 /// In this method, Window.Hide() is necessary.
 /// </summary>
 private void Reproduce1()
 {
     var hiddenWindow = new Window();
     hiddenWindow.Show();
     hiddenWindow.Hide();
 }
Esempio n. 34
0
		private static void ShowOrHide(Window window)
		{
			if (window == null)
				throw new ArgumentNullException("window");

			if (window.Visibility == Visibility.Visible)
				window.Hide();
			else
				window.Show();
		}
Esempio n. 35
0
        public App()
        {
            #if DEBUG
            Debugger.Launch();
            #endif
            Command command = new Command(Command.Type.NormalStartup);
            var p = new OptionSet()
            {
                $"Usage: {Assembly.GetExecutingAssembly().GetName().Name} [command]",
                "",
                "Commands:",
                {
                    "install-task", "Install the scheduled task", v =>
                    {
                        if (v != null)
                        {
                            command = new Command(Command.Type.InstallTask);
                        }
                    }
                },
                {
                    "remove-task", "Remove the scheduled task", v =>
                    {
                        if (v != null)
                        {
                            command = new Command(Command.Type.RemoveTask);
                        }
                    }
                },
                {
                    "show-ui", "Show UI", v =>
                    {
                        if (v != null)
                        {
                            command = new Command(Command.Type.ShowStartup);
                        }
                    }
                },
                {
                    "h|help", "show this message and exit", v =>
                    {
                        if (v != null)
                        {
                            command = new Command(Command.Type.ShowHelp);
                        }
                    }
                }
            };

            List<string> extra;
            try
            {
                extra = p.Parse(Environment.GetCommandLineArgs());
            }
            catch
            {
            }

            if (command.Id == Command.Type.ShowHelp)
            {
                p.WriteOptionDescriptions(Console.Out);
                Application.Current.Shutdown();
                return;
            }

            if (command.Id == Command.Type.InstallTask || command.Id == Command.Type.RemoveTask)
            {
                // are we administrator
                if (!MainViewModel.IsAdministrator)
                {
                    Console.Out.WriteLine("This command must be run as administrator");
                    Application.Current.Shutdown();
                    return;

                }
            }
            if (command.Id == Command.Type.InstallTask || command.Id == Command.Type.RemoveTask || command.Id == Command.Type.ShowStartup)
            {
                // wait until the mutex is free
                do
                {
                    Thread.Sleep(100);
                    mutex = new Mutex(false, Settings.GuiMutex);
                    if (mutex.WaitOne(0, false))
                    {
                        break;
                    }
                } while (_contentLoaded);
            }
            else
            {
                mutex = new Mutex(false, Settings.GuiMutex);
                if (!mutex.WaitOne(0, false))
                {
                    PostMessage((IntPtr) HWND_BROADCAST, WM_SHOWME, IntPtr.Zero, IntPtr.Zero);
                    Application.Current.Shutdown();
                    return;
                }
            }

            Application.Current.Exit += (sender, args) =>
            {
                RunHelper.Exit();
                mutex.ReleaseMutex();

            };

            try
            {
                RunHelper.Start();
            }
            catch (Exception e)
            {
                MessageBox.Show($"Could not extract runner!\n\n{e.Message}", "MoveToDesktop", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown();
                return;
            }

            mainWindow = new MainWindow();

            mainWindow.SourceInitialized += (sender, args) =>
            {
                HwndSource source = PresentationSource.FromVisual(mainWindow) as HwndSource;
                source?.AddHook(WndProc);
            };

            mainWindow.StateChanged += (sender, args) =>
            {
                if (mainWindow.WindowState == WindowState.Minimized)
                {
                    notifyIcon.Visible = !Settings.HideTray;
                    mainWindow.Hide();
                }
            };

            mainWindow.Closed += (sender, args) =>
            {
                notifyIcon.Visible = false;
                Application.Current.Shutdown();
            };

            notifyIcon = new System.Windows.Forms.NotifyIcon();
            notifyIcon.Icon = MoveToDesktop.Properties.Resources.icon;
            notifyIcon.Text = "MoveToDesktop is running";
            notifyIcon.Click += (sender, args) =>
            {
                ShowWindow();
            };

            notifyIcon.Visible = !Settings.HideTray;

            RunCommand(command);
        }