protected override Result RunCommand(RhinoDoc doc, RunMode mode)
    {
      m_doc = doc;

      m_window = new Window {Title = "Object ID and Thread ID", Width = 500, Height = 75};
      m_label = new Label();
      m_window.Content = m_label;
      new System.Windows.Interop.WindowInteropHelper(m_window).Owner = Rhino.RhinoApp.MainWindowHandle();
      m_window.Show();


      // register the rhinoObjectAdded method with the AddRhinoObject event
      RhinoDoc.AddRhinoObject += RhinoObjectAdded;

      // add a sphere from the main UI thread.  All is good
      AddSphere(new Point3d(0,0,0));

      // add a sphere from a secondary thread. Not good: the rhinoObjectAdded method
      // doesn't work well when called from another thread
      var add_sphere_delegate = new Action<Point3d>(AddSphere);
      add_sphere_delegate.BeginInvoke(new Point3d(0, 10, 0), null, null);

      // handle the AddRhinoObject event with rhinoObjectAddedSafe which is
      // desgined to work no matter which thread the call is comming from.
      RhinoDoc.AddRhinoObject -= RhinoObjectAdded;
      RhinoDoc.AddRhinoObject += RhinoObjectAddedSafe;

      // try again adding a sphere from a secondary thread.  All is good!
      add_sphere_delegate.BeginInvoke(new Point3d(0, 20, 0), null, null);

      doc.Views.Redraw();

      return Result.Success;
    }
Example #2
1
 void App_Startup(object sender, StartupEventArgs e)
 {
     Window = new MainWindow();
     SubscribeToWindowEvents();
     MainWindow = Window;
     Window.Show();
 }
Example #3
1
 protected override void OnStartup(StartupEventArgs args)
 {
     base.OnStartup(args);
     Window win = new Window();
     win.Title = "Inherit the App";
     win.Show();
 }
Example #4
1
        public PlatformWpf()
            : base(null, true)
        {
            var app = new Application ();
            var slCanvas = new Canvas ();
            var win = new Window
            {
                Title = Title,
                Width = Width,
                Height = Height,
                Content = slCanvas
            };

            var cirrusCanvas = new CirrusCanvas(slCanvas, Width, Height);
            MainCanvas = cirrusCanvas;

            win.Show ();

            EntryPoint.Invoke (null, null);

            var timer = new DispatcherTimer ();
            timer.Tick += runDelegate;
            timer.Interval = TimeSpan.FromMilliseconds (1);

            timer.Start ();
            app.Run ();
        }
Example #5
1
		public static void Main()
		{
			// original (doesn't work with snoop, well, can't find a window to own the snoop ui)
			Window window = new Window();
			window.Title = "Say Hello";
			window.Show();

			Application application = new Application();
			application.Run();


			// setting the MainWindow directly (works with snoop)
//			Window window = new Window();
//			window.Title = "Say Hello";
//			window.Show();
//
//			Application application = new Application();
//			application.MainWindow = window;
//			application.Run();


			// creating the application first, then the window (works with snoop)
//			Application application = new Application();
//			Window window = new Window();
//			window.Title = "Say Hello";
//			window.Show();
//			application.Run();


			// creating the application first, then the window (works with snoop)
//			Application application = new Application();
//			Window window = new Window();
//			window.Title = "Say Hello";
//			application.Run(window);
		}	}
Example #6
0
        public void TestDateTimeWithTwoDataPoints()
        {
            Chart chart = new Chart();
            chart.Width = 500;
            chart.Height = 300;

            _isLoaded = false;
            chart.Loaded += new RoutedEventHandler(chart_Loaded);

            Random rand = new Random();

            DataSeries dataSeries = new DataSeries();

            dataSeries.DataPoints.Add(new DataPoint() { XValue = new DateTime(2009, 1, 1), YValue = rand.Next(10, 100) });
            dataSeries.DataPoints.Add(new DataPoint() { XValue = new DateTime(2009, 1, 2), YValue = rand.Next(10, 100) });

            chart.Series.Add(dataSeries);

            Window window = new Window();
            window.Content = chart;
            window.Show();
            if (_isLoaded)
            {
                Assert.AreEqual(2, chart.Series[0].DataPoints.Count);
                window.Dispatcher.InvokeShutdown();
                window.Close();
            }
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            #if DEBUG
            Microsoft.Msagl.GraphViewerGdi.DisplayGeometryGraph.SetShowFunctions();
            #endif

            appWindow = new Window {
                Title = "WpfApplicationSample",
                Content = mainGrid,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                WindowState = WindowState.Normal
            };

            SetupToolbar();
            graphViewerPanel.ClipToBounds = true;
            mainGrid.Children.Add(toolBar);
            toolBar.VerticalAlignment=VerticalAlignment.Top;
            graphViewer.ObjectUnderMouseCursorChanged += graphViewer_ObjectUnderMouseCursorChanged;

            mainGrid.Children.Add(graphViewerPanel);
            graphViewer.BindToPanel(graphViewerPanel);

            SetStatusBar();
            graphViewer.MouseDown += WpfApplicationSample_MouseDown;
            appWindow.Loaded += (a,b)=>CreateAndLayoutAndDisplayGraph(null,null);

            //CreateAndLayoutAndDisplayGraph(null,null);
            //graphViewer.MainPanel.MouseLeftButtonUp += TestApi;
            appWindow.Show();
        }
        public void ShouldCreateWindowWrapperAndSetProperties()
        {
            var a = new WindowDialogActivationBehavior();

            var windowWrapper = new WindowWrapper();
            var style = new Style();
            windowWrapper.Style = style;
            Assert.AreEqual(style, windowWrapper.Style);

            var content = new Grid();
            windowWrapper.Content = content;
            Assert.AreEqual(content, windowWrapper.Content);
            
            var owner = new Window();
            owner.Show();
            windowWrapper.Owner = owner;
            Assert.AreEqual(owner, windowWrapper.Owner);

            windowWrapper.Show();
            windowWrapper.Closed += WindowWrapperOnClosed;
            windowWrapper.Close();
            windowWrapper.Closed -= WindowWrapperOnClosed;
            Assert.IsTrue(this._wasClosed);

        }
Example #9
0
        public void LineThicknessDefaultValue()
        {
            Chart chart = new Chart();
            chart.Width = 500;
            chart.Height = 300;

            Common.CreateAndAddDefaultDataSeries(chart);
            ChartGrid grid = new ChartGrid();
            Axis axis = new Axis();
            axis.Grids.Add(grid);
            chart.AxesY.Add(axis);
            
            _isLoaded = false;
            chart.Loaded += new RoutedEventHandler(chart_Loaded);

            Window window = new Window();
            window.Content = chart;
            window.Show();
            if (_isLoaded)
            {
                Assert.AreEqual(0.25, grid.LineThickness);
            }

            window.Dispatcher.InvokeShutdown();
            window.Close();
        }
 private static void ShowSplash()
 {
     _splashWindow = new IgnoreStartupURI();
     _splashWindow.Show();
     _resetSplashCreated.Set();
     Dispatcher.Run();
 }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var buffer = (ITextBuffer)((FrameworkElement)sender).Tag;

            var view = TextEditorFactory.CreateTextView(buffer);

            var projectionBuffer = TextView.TextBuffer as IProjectionBuffer;
            var spansFromBuffer = from ss in projectionBuffer.CurrentSnapshot.GetSourceSpans()
                                  where ss.Snapshot.TextBuffer == buffer
                                  select ss.Span;

            view.Properties[ProjectionSpanTaggerProvider.PropertyName] = new List<Span>(spansFromBuffer);
            var host = TextEditorFactory.CreateTextViewHost(view, setFocus: true);

            var window = new Window
            {
                Content = host.HostControl,
                ShowActivated = true,
            };

            window.Closed += (s, a) =>
            {
                host.Close();
            };

            window.Show();
        }
Example #12
0
        private void OpenLocationView(object sender, MouseButtonEventArgs e){
            var locIcon = (Ellipse)sender;
            var location = (LocationDef)locIcon.DataContext;
            var maker = new SchematicMaker(location.BackingLocation, 15, 15);
            var locDisplay = new LocationDisplay(maker);
            //Display the LocationDisplay in its own window
            Window extLocationDisplay = new Window(){
                Title = location.Description,
                Content = locDisplay
            };

            //For debug only 
            //Image testImage = new Image();
            //testImage.Source = new BitmapImage(maker.IconList[0].Icon);
            //Window testImageDisplay = new Window(){
            //    Title = "Test Image",
            //    Content = testImage
            //};
            //testImageDisplay.Show();
            locDisplay.IsEnabled = true;
            extLocationDisplay.Show();


            /*This should display the LocationDisplay control alongside the MapDisplay, but
             for some reason the LocationDisplay control is never visible, and the vshost seems
             to crash when this is attempted*/

            //MainWindow parent = (MainWindow)Window.GetWindow(this);
            //parent.AddDock(locDisplay);
        }
        public void View_will_automatically_bind_to_corresponding_viewmodel()
        {
            var app = new Application();

            var container = new WindsorContainer();
            container.AddFacility(new ViewModelRegistrationFacility(Application.Current));

            container.Register(Component.For<SquareViewModel>().ImplementedBy<SquareViewModel>());

            var window = new Window();
            app.MainWindow = window;

            var contentPresenter = new ContentPresenter();
            window.Content = contentPresenter;
            var vm = new SquareViewModel();
            contentPresenter.Content = vm;

            window.Show();

            try
            {
                var child = VisualTreeHelper.GetChild(contentPresenter, 0);
                Assert.That(child, Is.InstanceOf<SquareView>());
                Assert.That(((Control) child).DataContext, Is.SameAs(vm));
            }
            finally
            {
                window.Close();
            }
        }
Example #14
0
        public void ChartAxisViaXaml()
        {
            Object result = XamlReader.Load(new XmlTextReader(new StringReader(Resource.Chart_AxisXaml)));
            Assert.IsInstanceOfType(result, typeof(Chart));

            Chart chart = result as Chart;

            _isLoaded = false;
            chart.Loaded += new RoutedEventHandler(chart_Loaded);

            Window window = new Window();
            window.Content = chart;
            window.Show();
            if (_isLoaded)
            {
                Assert.AreEqual(Convert.ToString(1), chart.AxesX[0].AxisMinimum);
                Assert.AreEqual(Convert.ToString(100), chart.AxesX[0].AxisMaximum);
                Assert.AreEqual(Convert.ToString(0), chart.AxesY[0].AxisMinimum);
                Assert.AreEqual(Convert.ToString(200), chart.AxesY[0].AxisMaximum);
            }

            window.Dispatcher.InvokeShutdown();
            window.Close();

        }
			public SelectedContentTabControl ()
			{
				Assert.IsNull (SelectedContent, "1");
				Items.Add ("Test");
				Assert.IsNull (SelectedContent, "2");
				try {
					OnSelectionChanged (new SelectionChangedEventArgs (SelectionChangedEvent, null, new object [] { Items [0] }));
					Assert.Fail ("3");
				} catch (ArgumentException) {
				}
				OnSelectionChanged (new SelectionChangedEventArgs (SelectionChangedEvent, new object [] { }, new object [] { Items [0] }));
				Assert.IsNull (SelectedContent, "4");
				Items.Clear ();
				TabItem tab_item = new TabItem ();
				tab_item.Content = "Test";
				Items.Add (tab_item);
				Assert.IsNull (SelectedContent, "5");
				OnSelectionChanged (new SelectionChangedEventArgs (SelectionChangedEvent, new object [] { }, new object [] { tab_item }));
				Assert.IsNull (SelectedContent, "6");
				SelectionChangedEventArgs e = new SelectionChangedEventArgs (SelectionChangedEvent, new object [] { }, new object [] { tab_item });
				e.Source = this;
				OnSelectionChanged (e);
				Assert.IsNull (SelectedContent, "7");
				Window w = new Window ();
				w.Content = this;
				w.Show ();
				Assert.AreEqual ((string)SelectedContent, "Test", "8");
			}
Example #16
0
        public searchCustomer(searchCustomerTypeEnum displayType)
        {
            InitializeComponent();
            dataContext = new searchCustomer_ModelView(displayType);
            this.DataContext = dataContext;

            dataContext.NewCustomerRequested += (s, a) =>
            {
                newCustomerUC = new NewCustomerUC(displayType);
                newCustomerWindow = new Window()
                {
                    Title = "Új ügyfél",
                    Content = newCustomerUC,
                    SizeToContent = SizeToContent.WidthAndHeight
                };
                newCustomerVM = newCustomerUC.DataContext as NewCustomer_ViewModel;
                newCustomerVM.CustomerInserted += (so, ar) =>
                {
                    dataContext.selectedCustomer = (CustomerBaseRepresentation)so;
                    dataContext.OnCustomerSelected(EventArgs.Empty);
                    newCustomerWindow.Close();
                };
                newCustomerWindow.Show();
            };

            DataProxy.Instance.CustomersChanged += (s, a) =>
            {
                dataContext.RefreshCustomerList();
            };
        }
Example #17
0
        /// <summary>
        /// Shows a control in a window.
        /// </summary>
        /// <param name="control">Control to show in a window.</param>
        public static void ShowControlInWindow(UIElement control)
        {
#if SILVERLIGHT
    // Create window
            ChildWindow window = new ChildWindow();

            // Set as window content
            window.Content = control;
#else
            // Create window
            Window window = new Window();

            // Create a stack panel
            StackPanel stackPanel = new StackPanel();
            stackPanel.Children.Add(control);

            // Set as window content
            window.Content = stackPanel;
#endif

            // Set title
            window.Title = "Test window";

            // Show window
            window.Show();
        }
Example #18
0
 public static void HideForeground(Window mainWindow)
 {
     mainWindow.Show();
     mainWindow.WindowState = WindowState.Minimized;
     mainWindow.ShowInTaskbar = false;
     mainWindow.Hide();
 }
        public IssueBrowserViewModel()
        {
            Projects = new ObservableCollection<ShortProject>();
            Issues = new ObservableCollection<ShortIssue>();

            DisplayIssueCommand = new DelegateCommand<string>(id =>
            {
                var page = new IssueView();
                page.ViewModel.Initialize(Proxy, Issues.FirstOrDefault(i => i.ID == id));

                var window = new Window();
                window.Title = string.Format("View Issue {0}", id);
                window.Content = page;
                window.Width = 500;
                window.Height = 500;
                window.Show();
            });

            // Refresh issue list when project changed
            PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == "CurrentProjectShortName" || args.PropertyName == "CurrentQuery")
                {
                    QueryForIssues();
                }
            };
        }
        public static void ShowAddImagesToChangelistWindow(List<string> files)
        {
            var window = new Window { Width = 300, Height = 300 };
            window.Content = new AddImagesToChangelistWindow(window, files);

            window.Show();
        }
Example #21
0
        public override object CreateBlock()
        {
            Window window = new Window();
            window.Show();

            return window;
        }
Example #22
0
        private Task<LiveConnectSession> LoginAsync()
        {
            TaskCompletionSource<LiveConnectSession> taskCompletion = new TaskCompletionSource<LiveConnectSession>();

            var url = _client.GetLoginUrl(new[] { "wl.basic", "wl.signin", "onedrive.readonly", "wl.skydrive", "wl.photos" });

            WebBrowser browser = new WebBrowser();
            var window = new Window();
            window.Content = browser;

            NavigatingCancelEventHandler handler = null;
            handler = async (o, args) =>
            {
                if (args.Uri.AbsolutePath.Equals("/oauth20_desktop.srf"))
                {
                    browser.Navigating -= handler;
                    window.Close();

                    var session = await GetConnectSession(args.Uri.Query);
                    taskCompletion.SetResult(session);
                }
            };
            browser.Navigating += handler;
            browser.Navigate(url);
            window.Show();
            return taskCompletion.Task;
        }
        /// <summary>
        /// Is called on the click of the server's Listen button
        /// starts the server at the specified port number
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListenButton1_Click(object sender, RoutedEventArgs e)
        {
            string localPort1 = RemotePortTextBox1.Text;
            string endpoint1 = RemoteAddressTextBox.Text + ":" + localPort1 + "/IBasicService";

            try
            {
                server = new ProgHost();
                server.CreateReceiveChannel(endpoint1);
                listBox1.Items.Insert(0, "Started.. Waiting for a Client");
                ListenButton1.IsEnabled = false;
                StopButton.IsEnabled = true;
            }
            catch (Exception ex)
            {
                Window temp = new Window();
                StringBuilder msg = new StringBuilder(ex.Message);
                msg.Append("\nport = ");
                msg.Append(localPort1.ToString());
                temp.Content = msg.ToString();
                temp.Height = 100;
                temp.Width = 500;
                temp.Show();
            }
        }
        public static void LoadServices(this IEnumerable<ServiceBase> services)
        {
            // if run from visual studio:
            //if (!Debugger.IsAttached) return;

            var t = Task.Factory.StartNew
                (
                    () =>
                    {
                        var app = new App();
                        app.InitializeComponent();
                        app.Startup += (o, e) =>
                        {
                            var window = new Window
                            {
                                Width = 350,
                                Height = 200,
                                Title = "Windows Service Runner",
                                Content =
                                    new ServicesControllerViewModel(
                                        services.Select(s => new ServiceViewModel(s)).ToList())
                            };

                            window.Show();
                        };
                        app.Run();
                    },
                    CancellationToken.None,
                    TaskCreationOptions.PreferFairness,
                    new StaTaskScheduler(25)
                );
            t.Wait();
        }
 /// <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();
 }
Example #26
0
 static void TryShowWindow(Window window) {
     try {
         window.Show();
     } catch (InvalidOperationException e) {
         MainLog.Logger.FormattedDebugException(e);
     }
 }
Example #27
0
        public PageEdit(Article article)
        {
            _editArticle = article;
            InitializeComponent();

            ArticleTitle.Text = article.Title;
            ArticleContent.Text = article.Content;
            ArticleLink.Text = article.Link;
            ArticleDescription.Text = article.Description;
            _ow = new Window
            {
                AllowsTransparency = true,
                WindowStyle = WindowStyle.None,
                Opacity = 0.01,
                Background = Brushes.White,
                Owner = Application.Current.MainWindow,
                ShowInTaskbar = false,
                ShowActivated = false,
                Focusable = false
            };

            ArticleContentPreview.SizeChanged += ArticleContentPreview_SizeChanged;
            this.MouseMove += PageEdit_MouseMove;
            _ow.Show();

            this.Loaded += PageEdit_Loaded;
        }
Example #28
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            // General
            /* TODO: Do the following tasks for Login
             * 1- The first window to spawn is gonna be the login.
             * 2- After the users enters the correct credentials (email and pasword) close the login window, make spawn the application
             * window, and make that new window the main one.
             */

            // New Login window
            _loginWindow = new SessionView();
            SessionViewModel context = new SessionViewModel();
            _loginWindow.DataContext = context;
            _loginWindow.Show();
            //App.RunAppAfterSuccessfulLogin();

            // Old but login window
             /*
            _loginWindow = new LoginView();
            LoginViewModel context = new LoginViewModel();
            _loginWindow.DataContext = context;
            _loginWindow.Show();*/
            //App.RunAppAfterSuccessfulLogin();

            /*ApplicationView app = new ApplicationView();
            string path = "Data/employees.xml";
            ApplicationViewModel context = new ApplicationViewModel(path);
            app.DataContext = context;
            app.Show();*/
        }
Example #29
0
        public BasicsWindow()
        {
            Window basics = new Window
            {
                Title = "Code Basics",
                Height = 400,
                Width = 400,
                FontSize = 20,
            };

            StackPanel sp = new StackPanel();
            basics.Content = sp;

            TextBlock title = new TextBlock
            {
                Text = "Code Basics",
                FontSize = 24,
                TextAlignment = TextAlignment.Center,
            };
            sp.Children.Add(title);

            txtName = new TextBox();
            sp.Children.Add(txtName);
            txtName.Margin = new Thickness(10);

            Button btnSend = new Button
            {
                Content = "Send",
            };
            sp.Children.Add(btnSend);
            btnSend.Margin = new Thickness(10);
            btnSend.Click += BtnSend_Click;

            basics.Show();
        }
 public static void QuickPlot(double[] x, double[] y, 
     Tuple<double, double> xRange = null, Tuple<double, double> yRange = null)
 {
     PlotHelper.Dispatcher.Invoke(() =>
     {
         var window = new Window()
         {
             Width = 640,
             Height = 480
         };
         var plotControl = new PlotControl();
         plotControl.AddLine(
             x.Zip(y, (a, b) => new OxyPlot.DataPoint(a, b))
             .ToArray());
         if (xRange != null)
         {
             var xAxis = plotControl.Plot.Axes.First();
             xAxis.Minimum = xRange.Item1;
             xAxis.Maximum = xRange.Item2;
         }
         window.Content = plotControl;
         window.Title = "Plot Window";
         window.Show();
         window.Focus();
         window.BringIntoView();
         window.InvalidateVisual();
     });
 }
Example #31
0
        /// <summary>
        /// ウィンドウを表示します。
        /// </summary>
        /// <param name="windowName">表示するウィンドウの名前を指定します。</param>
        /// <returns>表示するウィンドウを返します。</returns>
        private System.Windows.Window ShowWindowCore(string windowName)
        {
            if (windowName == null)
            {
                return(null);
            }

            System.Windows.Window     vw = null;
            KeyValuePair <Type, Type> pair;

            if (_windowMap.TryGetValue(windowName, out pair))
            {
                var vwType = pair.Key;
                var vmType = pair.Value;

                vw = views.FirstOrDefault(view => view.GetType() == vwType);
                if (vw == null)
                {
                    vw = CrateWindowInstance(vwType, vmType);

                    if (vw != null)
                    {
                        views.Add(vw);
                        vw.Show();
                    }
                }
                else
                {
                    if (vw.WindowState == WindowState.Minimized)
                    {
                        vw.WindowState = WindowState.Normal;
                    }
                    vw.Activate();
                }
            }

            return(vw);
        }
        /// <summary>
        ///     This function is the callback used to execute the command when the menu item is clicked.
        ///     See the constructor to see how the menu item is associated with this function using
        ///     OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            if (_definitionWindow != null)
            {
                _definitionWindow.Focus();
                _definitionWindow.Show();
                return;
            }
            Window         window         = new Window();
            DefinitionPage definitionPage = new DefinitionPage();

            definitionPage.Closing += (_s, _e) =>
            {
                window.Close();
                _definitionWindow = null;
            };
            window.Closed += (_s, _e) => { _definitionWindow = null; };
            window.Title   = "编码规范工具设置";
            window.Content = definitionPage;
            window.Show();

            _definitionWindow = window;
        }
Example #33
0
        private void ToggleButtonMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed)
            {
                return;
            }
            Point pt = e.GetPosition(this);

            pt = this.PointToScreen(pt);

            if ((Popup == null) || (Popup.Visibility != Visibility.Visible))
            {
                CreatePopupWindow();
                Popup.Left = pt.X;
                Popup.Top  = pt.Y;
                Popup.Show();
                Popup.DragMove();


                DataObject data = selectedToolBoxItem.GetData(SelectedType);
                DragDrop.DoDragDrop(this, data, DragDropEffects.Copy);
            }
        }
        private void ConformWindow(string file, List <string> project)
        {
            if (_conformWindow != null)
            {
                _conformWindow.Focus();
                _conformWindow.Show();
                return;
            }

            string folder = "";

            if (!string.IsNullOrEmpty(file))
            {
                folder = new FileInfo(file).Directory?.FullName;
            }
            Window window = new Window()
            {
                Width  = 500,
                Height = 500
            };
            ConformPage conformPage = new ConformPage();

            window.Content       = conformPage;
            window.Title         = "编码规范工具";
            conformPage.Closing += (_s, _e) =>
            {
                window.Close();
                _conformWindow = null;
            };
            window.Closed += (_s, _e) => { _conformWindow = null; };
            conformPage.SolutionFolder = folder;
            conformPage.Project        = project;
            window.Show();
            conformPage.InspectFolderEncoding();
            _conformWindow = window;
        }
Example #35
0
        private static void OnSizeLocationChanged(System.Windows.FrameworkElement placementTarget, System.Windows.Window webHost)
        {
            //Here we set the location and size of the borderless Window hosting the WebBrowser control.
            //	This is based on the location and size of the child grid of the NTWindow. When the grid changes,
            //	the hosted WebBrowser changes to match.
            if (webHost.Visibility == Visibility.Visible)
            {
                webHost.Show();
            }

            webHost.Owner = Window.GetWindow(placementTarget);
            Point locationFromScreen  = placementTarget.PointToScreen(new System.Windows.Point(0, 0));
            PresentationSource source = PresentationSource.FromVisual(webHost);

            if (source != null && source.CompositionTarget != null)
            {
                Point targetPoints = source.CompositionTarget.TransformFromDevice.Transform(locationFromScreen);
                webHost.Left = targetPoints.X;
                webHost.Top  = targetPoints.Y;
            }

            webHost.Width  = placementTarget.ActualWidth;
            webHost.Height = placementTarget.ActualHeight;
        }
Example #36
0
        private void ОткрытьЧатВОкне(object sender)
        {
            var item = ((Selector)sender).SelectedValue;

            if (item == null)
            {
                return;
            }

            if (chats.ContainsKey(item))
            {
                chats[item].Activate();
            }
            else
            {
                var window = new System.Windows.Window()
                {
                    Title   = string.Format("Чат: {0}", ((RosApplication.Клиент.Main.абочаОбластьПользователя)((Selector)sender).SelectedItem).Пользователь.НазваниеОбъекта),
                    Content = new RosControl.Forms.ЧатПользователей()
                    {
                        id_node = item
                    },
                    Width  = 580,
                    Height = 640,
                    WindowStartupLocation = WindowStartupLocation.CenterScreen,
                    ShowActivated         = true
                };
                window.Closed += (object _sender, EventArgs _e) =>
                {
                    chats.Remove(((RosControl.Forms.ЧатПользователей)((System.Windows.Window)_sender).Content).id_node);
                };
                window.Activated += (object _sender, EventArgs _e) =>
                {
                    var main = RosControl.Helper.FindParentControl <Main>(this);
                    if (main == null)
                    {
                        return;
                    }

                    var id_node = Convert.ToDecimal(((RosControl.Forms.ЧатПользователей)((System.Windows.Window)_sender).Content).id_node);
                    var user    = main.СписокПользователей.FirstOrDefault(p => p.id_node == id_node);
                    if (user == null || user.Сообщения == 0)
                    {
                        return;
                    }
                    user.Сообщения = 0;
                    main.ОбновитьКоличествоНовыхСообщений();

                    System.Threading.Tasks.Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            using (RosService.Client client = new RosService.Client())
                            {
                                client.Сервисы.СообщенияПользователя_Очистить(client.СведенияПользователя.id_node, id_node, client.Пользователь, client.Домен);
                            }
                        }
                        catch (Exception)
                        {
                            //this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate { MessageBox.Show(ex.Message); });
                        }
                    });
                };
                window.Show();
                chats.Add(item, window);
            }
        }
Example #37
0
        public MainWindow(MainWindowViewModel viewModel)
        {
            InitializeComponent();
            ViewModel  = viewModel;
            growlToken = GrowlStackPanel.Name;
            Growl.Register(growlToken, GrowlStackPanel);
            this.WhenActivated(disposableRegistration =>
            {
                this.OneWayBind(ViewModel,
                                vm => vm.AccountAuthorityLevel,
                                v => v.LoginSideMenu.Visibility,
                                value => value == AuthorityLevel.Visitor ? Visibility.Visible : Visibility.Collapsed)
                .DisposeWith(disposableRegistration);
                this.OneWayBind(ViewModel,
                                vm => vm.AccountAuthorityLevel,
                                v => v.RegisterSideMenu.Visibility,
                                value => value == AuthorityLevel.Visitor ? Visibility.Visible : Visibility.Collapsed)
                .DisposeWith(disposableRegistration);
                this.OneWayBind(ViewModel,
                                vm => vm.AccountAuthorityLevel,
                                v => v.BorrowLogSideMenu.Visibility,
                                value => value >= AuthorityLevel.Member ? Visibility.Visible : Visibility.Collapsed)
                .DisposeWith(disposableRegistration);
                this.OneWayBind(ViewModel,
                                vm => vm.AccountAuthorityLevel,
                                v => v.AccountInfoSideMenu.Visibility,
                                value => value >= AuthorityLevel.Member ? Visibility.Visible : Visibility.Collapsed)
                .DisposeWith(disposableRegistration);
                this.OneWayBind(ViewModel,
                                vm => vm.AccountAuthorityLevel,
                                v => v.BooksSideMenu.Visibility,
                                value => value >= AuthorityLevel.Member ? Visibility.Visible : Visibility.Collapsed)
                .DisposeWith(disposableRegistration);

                Observable.FromEventPattern(MainSideMenu, nameof(MainSideMenu.SelectionChanged))
                .Select(ep => (ep.EventArgs as FunctionEventArgs <object>)?.Info as SideMenuItem)
                .Where(smi => smi != null)
                .Subscribe(smi => Navigate(smi.Name))
                .DisposeWith(disposableRegistration);

                Observable.FromEventPattern(AboutMenuItem, nameof(AboutMenuItem.Click))
                .Subscribe(ep => aboutWindow.Show())
                .DisposeWith(disposableRegistration);

                foreach (SideMenuItem smi in MainSideMenu.Items.OfType <SideMenuItem>().SelectMany(smi => smi.Items).OfType <SideMenuItem>())
                {
                    sideMenuItems.Add(smi.Name, smi);
                }

                // 注册右上角漂浮通知
                ViewModel.GUINotify.RegisterHandler(async interactioni =>
                {
                    await Task.Run(() =>
                    {
                        GUINotifyingDataPackage info = interactioni.Input;
                        interactioni.SetOutput(Unit.Default);
                        GrowlInfo growlInfo = new GrowlInfo
                        {
                            Message   = info.Message,
                            WaitTime  = (int)info.Duration.TotalSeconds,
                            Token     = growlToken,
                            StaysOpen = false,
                            IsCustom  = true
                        };
                        switch (info.Type)
                        {
                        case NotifyingType.Success:
                            growlInfo.WaitTime = growlInfo.WaitTime == 0 ? 4 : growlInfo.WaitTime;
                            Growl.Success(growlInfo);
                            break;

                        default:
                        case NotifyingType.Info:
                            growlInfo.WaitTime = growlInfo.WaitTime == 0 ? 4 : growlInfo.WaitTime;
                            Growl.Info(growlInfo);
                            break;

                        case NotifyingType.Warning:
                            growlInfo.WaitTime = growlInfo.WaitTime == 0 ? 6 : growlInfo.WaitTime;
                            Growl.Warning(growlInfo);
                            break;

                        case NotifyingType.Error:
                            growlInfo.WaitTime = growlInfo.WaitTime == 0 ? 8 : growlInfo.WaitTime;
                            Growl.Error(growlInfo);
                            break;

                        case NotifyingType.Fatal:
                            growlInfo.WaitTime = growlInfo.WaitTime == 0 ? 10 : growlInfo.WaitTime;
                            Growl.Fatal(growlInfo);
                            break;
                        }
                    });
                });
            });
        }
Example #38
0
        public void FormShouldAllowOwningToWpf()
        {
            bool passed = false;
            var  ev     = new ManualResetEvent(false);

            Invoke(() =>
            {
                var nativeWindow           = new sw.Window();
                nativeWindow.SizeToContent = sw.SizeToContent.WidthAndHeight;
                nativeWindow.Closed       += (sender, e) => ev.Set();

                var showDialog = new Button {
                    Text = "Show Owned Dialog"
                };
                showDialog.Click += (sender, e) =>
                {
                    var parentWindow = showDialog.ParentWindow;
                    if (parentWindow == null)
                    {
                        passed = false;
                        nativeWindow.Close();
                        return;
                    }

                    var form = new Form();

                    var closeButton = new Button {
                        Text = "Close"
                    };
                    closeButton.Click += (sender2, e2) => form.Close();

                    form.Content = new StackLayout
                    {
                        Padding = 10,
                        Spacing = 10,
                        Items   =
                        {
                            "This should show as a child to the parent, and should not be able to go behind it",
                            closeButton
                        }
                    };

                    form.Owner = parentWindow;
                    form.Show();
                };

                var passButton = new Button {
                    Text = "Pass"
                };
                passButton.Click += (sender, e) =>
                {
                    passed = true;
                    nativeWindow.Close();
                    ev.Set();
                };
                var failButton = new Button {
                    Text = "Fail"
                };
                failButton.Click += (sender, e) =>
                {
                    passed = false;
                    nativeWindow.Close();
                    ev.Set();
                };

                var panel = new StackLayout
                {
                    Items =
                    {
                        new Panel {
                            Padding = 20, Content = showDialog
                        },
                        TableLayout.Horizontal(failButton, passButton)
                    }
                };

                var wpfPanel = panel.ToNative(true);

                nativeWindow.HorizontalContentAlignment = sw.HorizontalAlignment.Stretch;
                nativeWindow.VerticalContentAlignment   = sw.VerticalAlignment.Stretch;
                nativeWindow.Content = wpfPanel;

                nativeWindow.Show();
            });
            ev.WaitOne();
            Assert.IsTrue(passed);
        }
Example #39
0
        /// <summary>
        /// Create the NotifyIcon UI, the ContextMenu for the NotifyIcon and an Exit menu item.
        /// </summary>
        private void InitializeContext(IChoWinFormApp windowApp)
        {
            this._components            = new System.ComponentModel.Container();
            this.NotifyIcon             = new System.Windows.Forms.NotifyIcon(this._components);
            this._notifyIconContextMenu = GetContextMenu(windowApp);
            if (windowApp != null)
            {
                this._mainFormWindow = windowApp.MainFormWindow;
            }

            this.NotifyIcon.DoubleClick += new System.EventHandler(this.notifyIcon_DoubleClick);

            this.NotifyIcon.Icon = windowApp != null ? windowApp.TrayIcon : null;
            if (this.NotifyIcon.Icon == null)
            {
                Assembly entryAssembly = ChoAssembly.GetEntryAssembly();
                if (entryAssembly != null)
                {
                    this.NotifyIcon.Icon = Icon.ExtractAssociatedIcon(entryAssembly.Location);
                }
            }

            this.NotifyIcon.Text = windowApp != null ? (windowApp.TooltipText.IsNullOrWhiteSpace() ? ChoGlobalApplicationSettings.Me.ApplicationName : windowApp.TooltipText) : ChoGlobalApplicationSettings.Me.ApplicationName;

            string defaultBaloonTipText = "{0} is running...".FormatString(ChoGlobalApplicationSettings.Me.ApplicationName);

            this.NotifyIcon.BalloonTipText = windowApp != null ? (windowApp.BalloonTipText.IsNullOrWhiteSpace() ? defaultBaloonTipText : windowApp.BalloonTipText) : defaultBaloonTipText;

            this.NotifyIcon.ContextMenu = _notifyIconContextMenu;
            this.NotifyIcon.Visible     = true;

            if (this._mainFormWindow != null)
            {
                _mainWPFWindow.Show();
                ChoWindowsManager.HideConsoleWindow();
                ChoWindowsManager.MainWindowHandle = this._mainFormWindow.Handle;
                _mainFormWindow.Closed            += new EventHandler(mainForm_Closed);
                _mainFormWindow.Closing           += new System.ComponentModel.CancelEventHandler(mainForm_Closing);
                _mainFormWindow.Resize            += new EventHandler(mainForm_Resize);
            }
            else if (this._mainWPFWindow != null)
            {
                ChoWindowsManager.HideConsoleWindow();
                _mainWPFWindow.Visibility = Visibility.Hidden;
                _mainWPFWindow.Show();
                WindowInteropHelper windowInteropHelper = new WindowInteropHelper(_mainWPFWindow);
                ChoWindowsManager.MainWindowHandle = windowInteropHelper.Handle;

                //_mainWPFWindow.Show();
                //_mainWPFWindow.SourceInitialized += new EventHandler(mainWPFWindow_SourceInitialized);
                //ChoWindowsManager.MainWindowHandle = this._mainWPFWindow;
                //_mainFormWindow.Closed += new EventHandler(mainForm_Closed);
                //_mainFormWindow.Closing += new System.ComponentModel.CancelEventHandler(mainForm_Closing);
                //_mainFormWindow.Resize += new EventHandler(mainForm_Resize);
            }

            if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn)
            {
                if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.HideMainWindowAtStartup)
                {
                    this._showContextMenuItem.Checked = false;
                    ToggleShowContextMenuItem();
                }
            }
            else
            {
                ShowMainWindow();
            }

            ChoGlobalApplicationSettings.Me.ObjectChanged += new EventHandler(Me_ConfigChanged);

            Me_ConfigChanged(null, null);
            if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn)
            {
                if (ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.HideMainWindowAtStartup)
                {
                    HideMainWindow();
                }
                else
                {
                    HideMainWindow();
                    ShowMainWindow();
                }
            }
        }
Example #40
0
 public void Show(System.Windows.Window view)
 {
     view.Show();
 }
Example #41
0
        // Call on MainWindow.Loaded event to check on start-up.
        public static async Task CheckForUpdates(bool Silent)
        {
            if (ServiceURI == null || RemoteFileURI == null)
            {
                throw new Exception("AutoUpdater - RemoteFileURI and ServiceURI must be set.");
            }
            try
            {
                System.Net.WebClient       webClient  = new System.Net.WebClient();
                System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
                var result = await httpClient.GetAsync(ServiceURI);

                var strServerVersion = await result.Content.ReadAsStringAsync();

                var serverVersion = Version.Parse(strServerVersion);
                var thisVersion   = Application.ResourceAssembly.ManifestModule.Assembly.GetName().Version;
                if (serverVersion > thisVersion)
                {
                    var strFilePath  = System.IO.Path.GetTempPath() + FileName;
                    var dialogResult = System.Windows.MessageBox.Show("A new version of " + AppName + " is available!  Would you like to download it now?  It's a no-fuss, instant process.", "New Version Available", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (dialogResult == MessageBoxResult.Yes)
                    {
                        if (System.IO.File.Exists(strFilePath))
                        {
                            System.IO.File.Delete(strFilePath);
                        }
                        var windowProgress = new System.Windows.Window();
                        windowProgress.DragMove();
                        windowProgress.Height                = 150;
                        windowProgress.Width                 = 400;
                        windowProgress.WindowStyle           = WindowStyle.None;
                        windowProgress.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                        var progressControl = new DownloadProgressControl();
                        windowProgress.Content             = progressControl;
                        webClient.DownloadProgressChanged += (sender, args) => {
                            progressControl.progressBar.Value = args.ProgressPercentage;
                        };
                        windowProgress.Show();
                        await webClient.DownloadFileTaskAsync(new Uri(RemoteFileURI), strFilePath);

                        windowProgress.Close();
                        var psi = new ProcessStartInfo(strFilePath, "-wpfautoupdate \"" + Application.ResourceAssembly.ManifestModule.Assembly.Location + "\"");

                        // Check if target directory is writable with current privileges.  If not, start update process as admin.
                        try
                        {
                            var installPath = Path.GetDirectoryName(Application.ResourceAssembly.ManifestModule.Assembly.Location);
                            var fi          = new FileInfo(Path.Combine(installPath, "Test.txt"));
                            fi.Create();
                            fi.Delete();
                        }
                        catch
                        {
                            psi.Verb = "runas";
                        }
                        Process.Start(psi);
                        Application.Current.Shutdown();
                        return;
                    }
                }
                else
                {
                    if (!Silent)
                    {
                        MessageBox.Show(AppName + " is up-to-date.", "No Updates", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch
            {
                if (!Silent)
                {
                    MessageBox.Show("Unable to contact the server.  Check your network connection or try again later.", "Server Unreachable", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
                return;
            }
        }
Example #42
0
 public void Open()
 {
     _WindowCore.Show();
 }
Example #43
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);
        }