Application base class
Inheritance: System.Windows.Threading.DispatcherObject, IHaveResources, IQueryAmbient
Exemplo n.º 1
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 ();
        }
Exemplo n.º 2
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);
		}	}
Exemplo n.º 3
0
        public static void ChangeTheme(Application app, Accent newAccent, Theme newTheme)
        {
            if (app == null) throw new ArgumentNullException("app");

            var oldTheme = DetectTheme(app);
            ChangeTheme(app.Resources, oldTheme, newAccent, newTheme);
        }
Exemplo n.º 4
0
		static void Main()
		{
			//the WPF application object will be the main UI loop
			System.Windows.Application wpfApplication = new System.Windows.Application
			{
				//otherwise the application will close when all WPF windows are closed
				ShutdownMode = ShutdownMode.OnExplicitShutdown 
			};
			SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());

			//set the WinForms properties
			//notice how you don't need to do anything else with the Windows Forms Application (except handle exceptions)
			System.Windows.Forms.Application.EnableVisualStyles();
			System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
			
			WpfProgramAddWinForms p = new WpfProgramAddWinForms();
			p.ExitRequested += (sender, e) =>
			{
				wpfApplication.Shutdown();
			};

			Task programStart = p.StartAsync();
			HandleExceptions(programStart, wpfApplication);

			wpfApplication.Run();
		}
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            var app = new Application();
            Window wind = new PackageBuilderMainWindow();

            app.Run(wind);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Called by the ApplicationLoader when this bootstrapper is loaded
        /// </summary>
        /// <param name="application">Application within which Stylet is running</param>
        public void Setup(Application application)
        {
            if (application == null)
            {
                throw new ArgumentNullException("application");
            }

            Application = application;

            // Use the current application's dispatcher for Execute
            Execute.Dispatcher = new DispatcherWrapper(Application.Dispatcher);

            Application.Startup += (o, e) => Start(e.Args);
            // Make life nice for the app - they can handle these by overriding Bootstrapper methods, rather than adding event handlers
            Application.Exit += (o, e) =>
                        {
                            OnExit(e);
                            Dispose();
                        };

            // Fetch this logger when needed. If we fetch it now, then no-one will have been given the change to enable the LogManager, and we'll get a NullLogger
            Application.DispatcherUnhandledException += (o, e) =>
                        {
                            LogManager.GetLogger(typeof(BootstrapperBase)).Error(e.Exception, "Unhandled exception");
                            OnUnhandledException(e);
                        };
        }
Exemplo n.º 7
0
        public MainClass()
        {
            window = new MainWindow();
            window.OnClickEvent += OnPinCode_ButtonClickEvent;
            window.Closing += new CancelEventHandler(MainWindow_Closing);
            window.Show();

            Task.Run(() => {
                trialThread = new Thread(TrialTimer);
                trialThread.Start();

                server = new QuitServer();
                serverThread = new Thread(server.Run);
                serverThread.Start();

                twitter = new Twitter();
                twitter.OnRequestEvent += OnRequest_TwitterEvent;
                twitter.OnIndexTextEvent += OnIndexText_TwitterEvent;
                twitter.OnAuthCompleteEvent += OnAuthComplete_TwitterEvent;
                twitter.OnAuthErrorEvent += OnAuthError_TwitterEvent;
                twitter.Init();
            });

            app = new Application();
            app.Run(window);
        }
Exemplo n.º 8
0
 public static void UiThread(object arg)
 {
     var app = new Application();
     var window = new MainWindow();
     window.onClosed += window_onClosed;
     app.Run(window);
 }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            Standard s1 = new Standard("ГОСТ Р 21.1101-2009");
            Standard s2 = new Standard("ГОСТ", "2.101");
            HashSet<Standard> sl1 = new HashSet<Standard>();
            HashSet<Standard> sl2 = new HashSet<Standard>();

            sl1.Add(s1);
            sl1.Add(s2);

            string[] test = { "tesT", "best", "rest" };
            IEnumerable<string> tt = test.Take(test.Length - 1).ToList();

            ConfigManager.ConfigManager cm = ConfigManager.ConfigManager.Instance;
            HashSet<Document> s1d = s1.Check();
            Console.WriteLine(s1d.First());

            string str = "333-ГОСТ--444";
            Console.WriteLine(str.cleanAllWithWhiteList());
            NormaCS ncs = new NormaCS(sl1);
            ncs.checkStandards();

            ReportWindow.Main mn = new ReportWindow.Main(ncs.Documents);

            Application app = new Application();
            app.Run(mn);
        }
        static void EnsureApplicationResources()
        {
            if (!UriParser.IsKnownScheme("pack"))
            {
                UriParser.Register(new GenericUriParser(GenericUriParserOptions.GenericAuthority), "pack", -1);
            }

            var appResourcesUri = new Uri("pack://application:,,,/GitHub.Authentication;component/AppResources.xaml", UriKind.RelativeOrAbsolute);

            // If we launch two dialogs in the same process (Credential followed by 2fa), calling new App()
            // throws an exception stating the Application class  can't be created twice. Creating an App
            // instance happens to set Application.Current to that instance (it's weird). However, if you
            // don't set the ShutdownMode to OnExplicitShutdown, the second time you launch a dialog,
            // Application.Current is null even in the same process.
            if (Application.Current == null)
            {
                var app = new Application();
                Debug.Assert(Application.Current == app, "Current application not set");
                app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
                app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = appResourcesUri });
            }
            else
            {
                // Application.Current exists, but what if in the future, some other code created
                // the singleton. Let's make sure our resources are still loaded.
                var resourcesExist = Application.Current.Resources.MergedDictionaries.Any(r => r.Source == appResourcesUri);
                if (!resourcesExist)
                {
                    Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = appResourcesUri });
                }
            }
        }
Exemplo n.º 11
0
 static void Main(string[] args)
 {
     Application app = new Application();
     MainWindow win = new MainWindow();
     //TestWnd win = new TestWnd();
     app.Run(win);
 }
Exemplo n.º 12
0
        public ConvertToWriteableBitmap()
        {
            WriteableBitmap wb = null;

            // OpenCVによる画像処理 (Threshold)
            using (IplImage src = new IplImage(Const.ImageLenna, LoadMode.GrayScale))
            using (IplImage dst = new IplImage(src.Size, BitDepth.U8, 1))
            {
                src.Smooth(src, SmoothType.Gaussian, 5);
                src.Threshold(dst, 0, 255, ThresholdType.Otsu);
                // IplImage -> WriteableBitmap
                wb = dst.ToWriteableBitmap(PixelFormats.BlackWhite);
                //wb = WriteableBitmapConverter.ToWriteableBitmap(dst, PixelFormats.BlackWhite);
            }

            // WPFのWindowに表示してみる
            Image image = new Image { Source = wb };
            Window window = new Window
            {
                Title = "from IplImage to WriteableBitmap",
                Width = wb.PixelWidth,
                Height = wb.PixelHeight,
                Content = image
            };

            Application app = new Application();
            app.Run(window);
        }
Exemplo n.º 13
0
        public void InformeGeneralObras()
        {
            oExcel = new Application();
            oBooks = oExcel.Workbooks;
            oBook = oBooks.Add(1);
            oSheets = (Sheets)oBook.Worksheets;
            oSheet = oSheets.get_Item(1);

            this.oSheet.Cells[1,1] = "Consecutivo";
            this.oSheet.Cells[1,2] = "Título";
            this.oSheet.Cells[1,3] = "Núm. de Material";
            this.oSheet.Cells[1,4] = "Año";
            this.oSheet.Cells[1,5] = "Tiraje";            

            int ind = 2;
            for (int j = 0; j < obrasImprimir.Count; j++)
            {
                oSheet.Cells[1][ind] = obrasImprimir[j].Consecutivo;
                oSheet.Cells[2][ind] = obrasImprimir[j].Titulo;
                oSheet.Cells[3][ind] = obrasImprimir[j].NumMaterial;
                oSheet.Cells[4][ind] = obrasImprimir[j].AnioPublicacion;
                oSheet.Cells[5][ind] = obrasImprimir[j].Tiraje;
                ind++;
            }            
            this.oExcel.ActiveWorkbook.Save();
            this.oExcel.Quit();
        }
        /// <summary>
        /// Called by the bootstrapper's constructor at runtime to start the framework.
        /// </summary>
        protected virtual void StartRuntime() {
            Execute.InitializeWithDispatcher();
            EventAggregator.DefaultPublicationThreadMarshaller = Execute.OnUIThread;

            EventAggregator.HandlerResultProcessing = (target, result) => {
                var coroutine = result as IEnumerable<IResult>;
                if (coroutine != null) {
                    var viewAware = target as IViewAware;
                    var view = viewAware != null ? viewAware.GetView() : null;
                    var context = new ActionExecutionContext { Target = target, View = (DependencyObject)view };

                    Coroutine.BeginExecute(coroutine.GetEnumerator(), context);
                }
            };

            AssemblySource.Instance.AddRange(SelectAssemblies());

            if (useApplication) {
                Application = Application.Current;
                PrepareApplication();
            }

            Configure();
            IoC.GetInstance = GetInstance;
            IoC.GetAllInstances = GetAllInstances;
            IoC.BuildUp = BuildUp;
        }
Exemplo n.º 15
0
        public void Run() {
            FlowRuntimeConfiguration.SynchronizationFactory = () => new SyncWithWPFDispatcher();
            var frc = new FlowRuntimeConfiguration();
            frc.AddStreamsFrom("appchatten.application.root.flow", Assembly.GetExecutingAssembly());

            var chat = new Chat(new QueueFinder<Message>());
            var mainWindow = new MainWindow();

            frc.AddAction<string>("anmelden", chat.Anmelden);
            frc.AddAction<string>("verbinden", chat.Verbinden);
            frc.AddFunc<string, Message>("absender_hinzufuegen", chat.Absender_hinzufuegen);
            frc.AddFunc<Message, Message>("versenden", chat.Versenden).MakeAsync();
            frc.AddFunc<Message, string>("formatieren", m => string.Format("{0}: {1}", m.Absender, m.Text));
            frc.AddAction<string>("anzeigen", mainWindow.MessageHinzufügen).MakeSync();
            frc.AddOperation(new Timer("timer", 500));
            frc.AddAction<Message>("empfangen", chat.Empfangen).MakeAsync();
            frc.AddAction<FlowRuntimeException>("fehler_anzeigen", ex => mainWindow.FehlerAnzeigen(ex.InnerException.Message)).MakeSync();

            using (var fr = new FlowRuntime(frc)) {
                fr.Message += Console.WriteLine;

                fr.UnhandledException += fr.CreateEventProcessor<FlowRuntimeException>(".exception");

                mainWindow.Anmelden += fr.CreateEventProcessor<string>(".anmelden");
                mainWindow.Verbinden += fr.CreateEventProcessor<string>(".verbinden");
                mainWindow.TextSenden += fr.CreateEventProcessor<string>(".senden");

                var app = new Application{MainWindow = mainWindow};
                app.Run(mainWindow);
            }
        }     
Exemplo n.º 16
0
		public static void Main()
		{
			Application app = new Application();
			Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
			app.Startup += new StartupEventHandler(app_Startup);
			app.Run();
		}
Exemplo n.º 17
0
        public void ConfigureApp(Application app, string appName)
        {
            this.ApplicationStartedTime = DateTime.UtcNow;
            this.ApplicationName = appName;

            // check where we can write
            if (CanCreateFile("."))
            {
                var codeBase = Assembly.GetExecutingAssembly().CodeBase;
                var uri = new UriBuilder(codeBase);
                var path = Uri.UnescapeDataString(uri.Path);
                ApplicationPath = Path.GetDirectoryName(path);
            }
            else
            {
                ApplicationPath = ApplicationDataPath();
            }
            //this.NLogFileName = "${specialfolder:dir=logs:file=" + this.ApplicationName + ".${shortdate}.log:folder=" + this.ApplicationPath + "}";
            this.NLogFileName = Path.Combine(this.ApplicationPath, "logs", this.ApplicationName + ".${shortdate}.log").Replace("\\", "/");

            this.ConfigureLogging();

            this.Log().Info("========================== {0} started ==========================", this.ApplicationName);

            // setup exception handling
            this.ConfigureHandlingUnhandledExceptions();

            // configure timer (log all 10min == 600000ms)
            this.gcTimer = new Timer(this.LogMemoryUsageAndInfos, this.ApplicationStartedTime, 0, GCTimerPeriod);
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            if (args.Length != 0)
                if (args[0] == "testsC++")
                {
                    if (FonctionsNatives.executerTests())
                        Debug.Write("Échec d'un ou plusieurs tests.");
                    else
                        Debug.Write("Tests réussis.");

                    return;
                }

            chrono.Start();

            // Tiré de http://stackoverflow.com/questions/15811215/convert-number-in-textbox-to-float-c-sharp
            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

            Application app = new Application();
            var timer = new DispatcherTimer (
                TimeSpan.FromMilliseconds(1),
                DispatcherPriority.ApplicationIdle,
                (s, e) => ExecuterQuandInactif(s, e),
                app.Dispatcher
            );
            window = new MainWindow();

            app.Run(window);
        }
Exemplo n.º 19
0
        public static void Main() {
            var boardUi = new BoardUI();
            var interactors = new Interactors();
            var sync = new Synchronizer<IEnumerable<Task>>();

            // Start
            var columns_and_tasks = interactors.Start();
            boardUi.Setup_Board(columns_and_tasks);

            // Refresh
            sync.Result += tasks => boardUi.Set_Tasks(tasks);
            interactors.Refresh(tasks => sync.Process(tasks));

            // Create Task
            boardUi.Create_Task += text => {
                var task = interactors.Create_Task(text);
                boardUi.Add_Task(task);
            };

            // Show Task
            boardUi.Show_Task += (column, position) => {
                var text = interactors.Show_Task(column, position);
                boardUi.Display_Text(text);
            };

            // Move Task
            boardUi.Move_Task += (column, position, direction) => {
                var tasks_and_selectedTask = interactors.Move_Task(column, position, direction);
                boardUi.Set_Tasks(tasks_and_selectedTask.Item1, tasks_and_selectedTask.Item2);
            };

            var app = new Application { MainWindow = boardUi };
            app.Run(boardUi);
        }
Exemplo n.º 20
0
        public void Convert(string projectfile, string outputpath)
        {
            var app = new Application();
            var project = ProjectSettings.Load(projectfile);

            var jsf = Path.Combine(outputpath, "converter.settings.js");
            project.Save(jsf);

            var model = new ConverterModel();
            model.PageTitle = project.PageTitle;
            model.IsOptimized = false;
            model.InlineAllScript = true;
            model.OutputDirectory = outputpath;
            // model.IncludeResources = new string[] { "base.css", "application.css", "*.png", "octicons.*" };
            model.TraceOutputFile = "converter.output.html";

            // trace flags
            if (null != Flags)
            {
                Log.ShowVerbose = Flags.Verbose;
                Log.ShowConverterModel = Flags.ShowFiles;
                Log.ShowResources = Flags.ShowResources;

                if (Flags.ShowClasses)
                {
                    Log.ShowClassDependencies = Flags.ShowClasses;
                }
            }

            // setting the project property triggers the conversion process
            model.Project = project;

            WarningCount = model.Converter.WarningCount;
            ErrorCount = model.Converter.ErrorCount;
        }
Exemplo n.º 21
0
        public ConvertToBitmapSource()
        {
            BitmapSource bs = null;

            // OpenCVによる画像処理 (Threshold)
            using (IplImage src = new IplImage(Const.ImageLenna, LoadMode.GrayScale))
            using (IplImage dst = new IplImage(src.Size, BitDepth.U8, 1))
            {
                src.Smooth(src, SmoothType.Gaussian, 5);
                src.Threshold(dst, 0, 255, ThresholdType.Otsu);
                // IplImage -> BitmapSource
                bs = dst.ToBitmapSource();
                //bs = BitmapSourceConverter.ToBitmapSource(dst);
            }

            // WPFのWindowに表示してみる
            Image image = new Image { Source = bs };
            Window window = new Window
            {
                Title = "from IplImage to BitmapSource",
                Width = bs.PixelWidth,
                Height = bs.PixelHeight,
                Content = image
            };

            Application app = new Application();
            app.Run(window);
        }
Exemplo n.º 22
0
        private static void EnsureApplication()
        {
            lock(m_appInitializingSync)
            {
                if(Application.Current != null)
                {
                    return;
                }

                var waitForApplication = new TaskCompletionSource<bool>();
                Thread thread = new Thread(new ThreadStart(() =>
                    {
                        var app = new Application();
                        app.Startup += (s, e) => { waitForApplication.SetResult(true); };
                        app.Run();
                    }));

                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();

                //Task task = new Task(new Action(() =>
                //{
                //    var app = new Application();
                //    app.Startup += (s, e) => { waitForApplication.SetResult(true); };
                //    app.Run();
                //}));

                //task.Start();

                waitForApplication.Task.Wait();
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Create a new instance of the <see cref="UserAccountControlService"/>.
        /// </summary>
        /// <param name="application">
        /// An instance of the current <see cref="Application"/> object.
        /// The service will use this to perform shutdown and re-launch operations.
        /// </param>
        public UserAccountControlService(Application application)
        {
            if (application == null)
                throw new ArgumentNullException("application");

            Application = application;
        }
		public void SetUp()
		{
			application = new Application();

			uncaughtException = null;
			container = new WindsorContainer();

			container.AddFacility<SynchronizeFacility>()
				.Register(Component.For<SynchronizationContext>(),
						  Component.For<AsynchronousContext>(),
						  Component.For<DummyWindow>().Named("Dummy").Activator<DummyFormActivator>(),
						  Component.For<IDummyWindow>().ImplementedBy<DummyWindow>(),
						  Component.For<ClassUsingWindowInWindowsContext>(),
						  Component.For<ClassUsingWindowInAmbientContext>(),
						  Component.For(typeof(IClassUsingDepedenecyContext<>)).ImplementedBy(typeof(ClassUsingDispatcherContext<>)),
						  Component.For<IWorker>().ImplementedBy<SimpleWorker>(),
						  Component.For<IWorkerWithOuts>().ImplementedBy<AsynchronousWorker>(),
						  Component.For<ManualWorker>()
						  );

			var componentNode = new MutableConfiguration("component");
			componentNode.Attributes[Constants.SynchronizedAttrib] = "true";
			var synchronizeNode = new MutableConfiguration("synchronize");
			synchronizeNode.Attributes["contextType"] = typeof(DispatcherSynchronizationContext).AssemblyQualifiedName;
			var doWorkMethod = new MutableConfiguration("method");
			doWorkMethod.Attributes["name"] = "DoWork";
			doWorkMethod.Attributes["contextType"] = typeof(DispatcherSynchronizationContext).AssemblyQualifiedName;
			synchronizeNode.Children.Add(doWorkMethod);
			componentNode.Children.Add(synchronizeNode);

			container.Kernel.ConfigurationStore.AddComponentConfiguration("class.needing.context", componentNode);
			container.Register(Component.For<ClassUsingWindow>().Named("class.needing.context"));
		}
Exemplo n.º 25
0
        public static void Main(string[] args) {
            var mainWindow = new MainWindow();
            var interactors = new Interactors();

            mainWindow.Resize += size => {
                var text = interactors.Resize(size);
                mainWindow.Seite_anzeigen(text);
            };

            mainWindow.Vorwärts += () => {
                var text = interactors.Vorwärts_blättern();
                mainWindow.Seite_anzeigen(text);
            };

            mainWindow.Rückwärts += () => {
                var text = interactors.Rückwärts_blättern();
                mainWindow.Seite_anzeigen(text);
            };

            var seite = interactors.Start();
            mainWindow.Seite_anzeigen(seite);

            var app = new Application { MainWindow = mainWindow };
            app.Run(mainWindow);
        }
Exemplo n.º 26
0
        protected override void Run()
        {
            RxApp.LoggerFactory = _ => new FileLogger("Squirrel") { Level = ReactiveUIMicro.LogLevel.Info };
            ReactiveUIMicro.RxApp.ConfigureFileLogging(); // HACK: we can do better than this later

            theApp = new Application();

            // NB: These are mirrored instead of just exposing Command because
            // Command is impossible to mock, since there is no way to set any
            // of its properties
            DisplayMode = Command.Display;
            Action = Command.Action;

            this.Log().Info("WiX events: DisplayMode: {0}, Action: {1}", Command.Display, Command.Action);

            setupWiXEventHooks();

            var bootstrapper = new WixUiBootstrapper(this);

            theApp.MainWindow = new RootWindow
            {
                viewHost = { Router = bootstrapper.Router }
            };

            MainWindowHwnd = IntPtr.Zero;
            if (Command.Display == Display.Full)
            {
                MainWindowHwnd = new WindowInteropHelper(theApp.MainWindow).Handle;
                uiDispatcher = theApp.MainWindow.Dispatcher;
                theApp.Run(theApp.MainWindow);
            }

            Engine.Quit(0);
        }
Exemplo n.º 27
0
        private static void MakeStandaloneAndRun(string commandFilePath, ref DynamoViewModel viewModel)
        {
            DynamoPathManager.Instance.InitializeCore(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            DynamoPathManager.PreloadAsmLibraries(DynamoPathManager.Instance);
            
            var model = DynamoModel.Start(
                new DynamoModel.StartConfiguration()
                {
                    Preferences = PreferenceSettings.Load()
                });

            viewModel = DynamoViewModel.Start(
                new DynamoViewModel.StartConfiguration()
                {
                    CommandFilePath = commandFilePath,
                    DynamoModel = model
                });

            var view = new DynamoView(viewModel);

            var app = new Application();
            app.Run(view);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RemoteControlHandler"/> class.
 /// </summary>
 /// <param name="app">The app.</param>
 public RemoteControlHandler(Application app)
 {
     app.MainWindow.KeyDown += this.Window_KeyDown;
     app.MainWindow.CommandBindings.Add(new CommandBinding(MediaCommands.Play, this.MediaCommands_Play));
     app.MainWindow.CommandBindings.Add(new CommandBinding(MediaCommands.Stop, this.MediaCommands_Stop));
     app.MainWindow.CommandBindings.Add(new CommandBinding(MediaCommands.Record, this.MediaCommands_Record));
 }
Exemplo n.º 29
0
		static JumpLists()
		{
			_app = new Application();
			var jmp = new JumpList();
			jmp.ShowRecentCategory = true;
			JumpList.SetJumpList(_app, jmp);
		}
Exemplo n.º 30
0
 static void Main()
 {
     HostView hostView = new HostView();
     WorkflowApplicationManager manager = new WorkflowApplicationManager(hostView);
     Application application = new Application();
     application.Run(hostView);
 }
Exemplo n.º 31
0
        /// <summary>
        /// 设置程序显示语言
        /// </summary>
        /// <param name="languageTag">程序中已包含的语言字典名称,例如zh-CN</param>
        //设置语言
        public static void SetLanguage(string languageTag)
        {
            List <ResourceDictionary> dictionaryList = new List <ResourceDictionary>();

            foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
            {
                dictionaryList.Add(dictionary);
            }

            string requestedCulture = string.Format(@"Language\{0}.xaml", languageTag);

            Uri reUri = new Uri(requestedCulture, UriKind.Relative);
            ResourceDictionary rdDictionary = (ResourceDictionary)Application.LoadComponent(reUri);

            Application.Current.Resources.MergedDictionaries.Remove(rdDictionary);
            Application.Current.Resources.MergedDictionaries.Add(rdDictionary);
        }
Exemplo n.º 32
0
        /// <summary>
        /// The set notify icon.
        /// </summary>
        private static void SetNotifyIcon()
        {
            notifyIcon              = new NotifyIcon();
            notifyIcon.DoubleClick += (s, args) => ShowMainWindow();
            var iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/Resources/geometry.ico"));

            notifyIcon.Icon    = new Icon(iconStream?.Stream ?? throw new NullReferenceException());
            notifyIcon.Visible = true;

#if !DEBUG
            notifyIcon.BalloonTipIcon  = ToolTipIcon.Info;
            notifyIcon.BalloonTipTitle = "Bilgi";
            notifyIcon.BalloonTipText  = "ODM Mail senkronlayıcı çalışıyor";
            notifyIcon.ShowBalloonTip(3000);
#endif
            CreateContextMenu();
        }
Exemplo n.º 33
0
        private static TaskbarIcon CreateIcon()
        {
            var contextMenu = new ContextMenu();

            var mnuConfigure = new MenuItem()
            {
                Header = TranslationService.Default.Configure
            };

            mnuConfigure.Click += TriggerConfigure;
            contextMenu.Items.Add(mnuConfigure);

            var mnuRestart = new MenuItem()
            {
                Header = TranslationService.Default.Restart
            };

            mnuRestart.Click += TriggerRestart;
            contextMenu.Items.Add(mnuRestart);

            var mnuRefresh = new MenuItem()
            {
                Header = TranslationService.Default.RefreshConnection
            };

            mnuRefresh.Click += TriggerRefresh;
            contextMenu.Items.Add(mnuRefresh);

            var mnuExit = new MenuItem()
            {
                Header = TranslationService.Default.Exit
            };

            mnuExit.Click += TriggerExit;
            contextMenu.Items.Add(mnuExit);

            return(new TaskbarIcon
            {
                ToolTipText = "AppleWirelessKeyboard",
                Icon = new Icon(Application
                                .GetResourceStream(
                                    new Uri("pack://application:,,,/Gnome-Preferences-Desktop-Keyboard-Shortcuts.ico"))?.Stream),
                Visibility = Visibility.Collapsed,
                ContextMenu = contextMenu
            });
        }
Exemplo n.º 34
0
        /// <summary>
        /// The create context menu.
        /// </summary>
        private static void CreateContextMenu()
        {
            var mailSynchronizer = container.GetService <MailSynchronizer>();

            notifyIcon.ContextMenuStrip = new ContextMenuStrip();
            var showButton = notifyIcon.ContextMenuStrip.Items.Add("Göster");

            showButton.Click += (s, e) => ShowMainWindow();
            showButton.Image  = Image.FromStream(Application.GetResourceStream(new Uri("pack://application:,,,/Resources/eye.png"))?.Stream);

            notifyIcon.ContextMenuStrip.Items.Add(new ToolStripSeparator());

            var start = notifyIcon.ContextMenuStrip.Items.Add("Başlat");

            start.Click += (s, e) => { mailSynchronizer.Start(); };
            start.Image  = Image.FromStream(Application.GetResourceStream(new Uri("pack://application:,,,/Resources/play-circle.png"))?.Stream);

            var stop = notifyIcon.ContextMenuStrip.Items.Add("Durdur");

            stop.Click += (s, e) => mailSynchronizer.Stop();
            stop.Image  = Image.FromStream(Application.GetResourceStream(new Uri("pack://application:,,,/Resources/stop-circle.png"))?.Stream);

            notifyIcon.ContextMenuStrip.Items.Add(new ToolStripSeparator());

            var exitButton = notifyIcon.ContextMenuStrip.Items.Add("Çıkış");

            exitButton.Click += (s, e) => ExitApplication();
            exitButton.Image  = Image.FromStream(Application.GetResourceStream(new Uri("pack://application:,,,/Resources/exit-to-app.png"))?.Stream);

            mailSynchronizer.WhenChanged(synchronizer => synchronizer.IsStarted,
                                         (synchronizer, b) => b)
            .Subscribe(b =>
            {
                if (b)
                {
                    start.Enabled = false;
                    stop.Enabled  = true;
                }
                else
                {
                    start.Enabled = true;
                    stop.Enabled  = false;
                }
            });
        }
Exemplo n.º 35
0
        /// <summary>
        ///     Włącz/Wyłącz bota
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToggleBot(object sender, RoutedEventArgs e)
        {
            // Czy {_botThread} jest uruchomiony?
            if (_factory != null)
            {
                // Usuń event otrzymania wiadomości
                MainWindow.Skype.MessageStatus -= Skype_MessageRecieved;

                // Oczyszczanie pamięci
                _factory = null;
                _bot     = null;
                _botSessions.Clear();
                _botIds.Clear();
                _lastMsg.Clear();
                _sessions     = 0;
                _messagesSent = 0;

                // Zaktualizuj przycisk
                var resourceUri = new Uri("Resources/Toggle Off-96.png", UriKind.Relative);
                var streamInfo  = Application.GetResourceStream(resourceUri);
                var temp        = BitmapFrame.Create(streamInfo.Stream);
                var brush       = new ImageBrush();
                brush.ImageSource = temp;

                (sender as Button).Background = brush;

                // Zaktualizuj statystyki
                statisticsSessions.Text = _sessions.ToString();
                statisticsSent.Text     = _messagesSent.ToString();
            }
            else
            {
                // Uruchom bot-a
                EnableBot();

                // Zaktualizuj przycisk
                var resourceUri = new Uri("Resources/Toggle On-96.png", UriKind.Relative);
                var streamInfo  = Application.GetResourceStream(resourceUri);
                var temp        = BitmapFrame.Create(streamInfo.Stream);
                var brush       = new ImageBrush();
                brush.ImageSource = temp;

                (sender as Button).Background = brush;
            }
        }
        /// <summary>
        /// shows enable/disabled state based on n/w availability
        /// </summary>
        public static void ToggleNotifyIconStatus()
        {
            try
            {
                var sPack     = PackUriHelper.UriSchemePack;
                var uriString =
                    String.Format("{0}://application:,,,/DeviceTracker;component/Assets/Images/appIcon.ico", sPack);

                StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(uriString, UriKind.RelativeOrAbsolute));
                if (streamResourceInfo != null)
                {
                    _notifyIcon.Icon = new Icon(streamResourceInfo.Stream, IconSize);
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 37
0
        private Icon LoadIcon(string uriPath, string messageOnFail)
        {
            Icon result;
            var  iconUri        = new Uri(uriPath, UriKind.RelativeOrAbsolute);
            var  resourceStream = Application.GetResourceStream(iconUri);

            if (resourceStream == null)
            {
                throw new ApplicationException(messageOnFail);
            }

            using (Stream iconStream = resourceStream.Stream)
            {
                result = new Icon(iconStream);
            }

            return(result);
        }
Exemplo n.º 38
0
        private static System.Drawing.Icon FromImageSource(ImageSource icon)
        {
            if (icon == null)
            {
                return(null);
            }

            Uri iconUri = new Uri(icon.ToString());

            if (iconUri.LocalPath.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase))
            {
                var bm  = new Bitmap(Application.GetResourceStream(iconUri).Stream);
                var hnd = bm.GetHicon();
                return(System.Drawing.Icon.FromHandle(hnd));
            }

            return(new Icon(Application.GetResourceStream(iconUri).Stream));
        }
Exemplo n.º 39
0
        public BadgesWindow()
        {
            InitializeComponent();
            DataContextChanged += OnDataContextChanged;
            Loaded             += OnWindowLoaded;

            var icoUri     = new Uri("pack://application:,,,/CardIdleRemastered;component/CardIdle.ico");
            var iconStream = Application.GetResourceStream(icoUri).Stream;

            _ni = new NotifyIcon
            {
                Icon    = new Icon(iconStream),
                Text    = "Card Idle",
                Visible = false
            };

            _ni.DoubleClick += ExpandWindow;
        }
        static void Main(string[] args) {

            //Initialize CoreHost (we can do it in Window Initialize but this way
            //we don't even pop the form if Initialize fails

            ArcGIS.Core.Hosting.Host.Initialize();//this will throw!

            Application app = new Application();
            w = new Window();
            w.Height = 500;
            w.Width = 700;
            Grid g = new Grid();
            g.Children.Add(new GDBGrid());
            w.Content = g;
            w.Title = "ArcGIS Pro CoreHost GDB Sample: File GDB Reader";
            app.Run(w);
            
        }
Exemplo n.º 41
0
        private static async void HandleExceptions(Task task, System.Windows.Application wpfApplication)
        {
            try
            {
                await Task.Yield();                 //ensure this runs as a continuation

                await task;
            }
            catch (Exception ex)
            {
                //deal with exception, either with message box
                //or delegating to general exception handling logic you may have wired up
                //e.g. to Application.DispatcherUnhandledException and AppDomain.UnhandledException
                System.Windows.MessageBox.Show(ex.ToString());

                wpfApplication.Shutdown();
            }
        }
Exemplo n.º 42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ShellView"/> class.
        /// </summary>
        public ShellView()
        {
            this.InitializeComponent();

            IUserSettingService userSettingService = IoC.Get <IUserSettingService>();
            bool minimiseToTray = userSettingService.GetUserSetting <bool>(UserSettingConstants.MainWindowMinimize);

            if (minimiseToTray)
            {
                this.notifyIcon             = new System.Windows.Forms.NotifyIcon();
                this.notifyIcon.ContextMenu = new ContextMenu(new[] { new MenuItem("Restore", NotifyIconClick) });

                StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri("pack://application:,,,/handbrakepineapple.ico"));
                if (streamResourceInfo != null)
                {
                    Stream iconStream = streamResourceInfo.Stream;
                    this.notifyIcon.Icon = new System.Drawing.Icon(iconStream);
                }
                this.notifyIcon.DoubleClick += this.NotifyIconClick;
                this.StateChanged           += this.ShellViewStateChanged;
            }

            // Start Encode (Ctrl+S)
            // Stop Encode (Ctrl+K)
            // Open Log Window (Ctrl+L)
            // Open Queue Window (Ctrl+Q)
            // Add to Queue (Ctrl+A)
            // Scan a File (Ctrl+F)
            // Scan a Folder (Ctrl+R)

            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.S, ModifierKeys.Control)), new KeyGesture(Key.S, ModifierKeys.Control)));
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.K, ModifierKeys.Control)), new KeyGesture(Key.K, ModifierKeys.Control)));
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.L, ModifierKeys.Control)), new KeyGesture(Key.L, ModifierKeys.Control)));
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.Q, ModifierKeys.Control)), new KeyGesture(Key.Q, ModifierKeys.Control)));
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.A, ModifierKeys.Control)), new KeyGesture(Key.A, ModifierKeys.Control)));
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.F, ModifierKeys.Control)), new KeyGesture(Key.F, ModifierKeys.Control)));
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.R, ModifierKeys.Control)), new KeyGesture(Key.R, ModifierKeys.Control)));

            // Enable Windows 7 Taskbar progress indication.
            if (this.TaskbarItemInfo == null)
            {
                this.TaskbarItemInfo = Win7.WindowsTaskbar;
            }
        }
Exemplo n.º 43
0
        static void Main(string[] args)
        {
            var application = new Application();

            Forms.Init();
            var formsApplicationPage = new FormsApplicationPage();

            formsApplicationPage.LoadApplication(new XamarinNeller.App());

            Task.Run(() =>
            {
                Task.Delay(1000).Wait();

                application.Dispatcher.InvokeAsync(() =>
                {
                    var window = new Window()
                    {
                        Height = 600,
                        Width  = 600
                    };

                    var viewPage = new ViewPage()
                    {
                        HeightRequest = 500,
                        WidthRequest  = 500
                    };

                    var pageRenderer = new PageRenderer();

                    var mainPage = new MainPage();
                    pageRenderer.SetElement(viewPage);

                    //var formsContentLoader = new FormsContentLoader();
                    //var content = formsContentLoader.LoadContentAsync(window,null, mainPage,new CancellationToken()).Result;

                    var frameworkElement = pageRenderer.GetNativeElement();
                    window.Content       = frameworkElement;
                    window.Show();
                });
            });

            application.Run();
        }
Exemplo n.º 44
0
        static void RunUnderApplication(Activity activity)
        {
            Application application = new System.Windows.Application()
            {
                ShutdownMode = ShutdownMode.OnExplicitShutdown
            };

            application.Startup += delegate
            {
                WorkflowApplication wfApp = new WorkflowApplication(activity);
                wfApp.SynchronizationContext = SynchronizationContext.Current;
                wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
                {
                    application.Shutdown();
                };
                wfApp.Run();
            };
            application.Run();
        }
Exemplo n.º 45
0
        public BasicWindow()
        {
            InitializeComponent();

            #region System Tray Initialization

            var iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/Huddle.Engine;component/Resources/HuddleLamp.ico")).Stream;
            var icon       = new Icon(iconStream);
            _notifyIcon = new NotifyIcon {
                Icon = icon
            };

            _notifyIcon.MouseClick       += NotifyIconMouseClick;
            _notifyIcon.MouseDoubleClick += OnActivateSystemTrayIcon;

            #endregion

            Loaded += BasicWindowLoaded;
        }
Exemplo n.º 46
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ShellView"/> class.
        /// </summary>
        public ShellView()
        {
            this.InitializeComponent();



            IUserSettingService userSettingService = IoC.Get <IUserSettingService>();
            bool minimiseToTray = userSettingService.GetUserSetting <bool>(UserSettingConstants.MainWindowMinimize);

            if (minimiseToTray)
            {
                INotifyIconService notifyIconService = IoC.Get <INotifyIconService>();
                this.notifyIcon             = new NotifyIcon();
                this.notifyIcon.ContextMenu = new ContextMenu(new[] { new MenuItem("Restore", NotifyIconClick), new MenuItem("Mini Status Display", ShowMiniStatusDisplay) });
                notifyIconService.RegisterNotifyIcon(this.notifyIcon);

                StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri("pack://application:,,,/handbrakepineapple.ico"));
                if (streamResourceInfo != null)
                {
                    Stream iconStream = streamResourceInfo.Stream;
                    this.notifyIcon.Icon = new Icon(iconStream);
                }
                this.notifyIcon.DoubleClick += this.NotifyIconClick;
                this.StateChanged           += this.ShellViewStateChanged;
            }

            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.S, ModifierKeys.Control)), new KeyGesture(Key.S, ModifierKeys.Control)));                                           // Start Encode
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.K, ModifierKeys.Control)), new KeyGesture(Key.K, ModifierKeys.Control)));                                           // Stop Encode
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.L, ModifierKeys.Control)), new KeyGesture(Key.L, ModifierKeys.Control)));                                           // Open Log Window
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.Q, ModifierKeys.Control)), new KeyGesture(Key.Q, ModifierKeys.Control)));                                           // Open Queue Window
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.A, ModifierKeys.Control)), new KeyGesture(Key.A, ModifierKeys.Control)));                                           // Add to Queue
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.O, ModifierKeys.Control)), new KeyGesture(Key.O, ModifierKeys.Control)));                                           // File Scan
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.O, ModifierKeys.Alt)), new KeyGesture(Key.O, ModifierKeys.Alt)));                                                   // Scan Window
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.O, ModifierKeys.Control | ModifierKeys.Shift)), new KeyGesture(Key.O, ModifierKeys.Control | ModifierKeys.Shift))); // Scan a Folder
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.G, ModifierKeys.Control | ModifierKeys.Shift)), new KeyGesture(Key.G, ModifierKeys.Control | ModifierKeys.Shift))); // Garbage Colleciton
            this.InputBindings.Add(new InputBinding(new ProcessShortcutCommand(new KeyGesture(Key.F1, ModifierKeys.None)), new KeyGesture(Key.F1, ModifierKeys.None)));                                               // Help

            // Enable Windows 7 Taskbar progress indication.
            if (this.TaskbarItemInfo == null)
            {
                this.TaskbarItemInfo = Win7.WindowsTaskbar;
            }
        }
Exemplo n.º 47
0
        private void CreateSystemTray()
        {
            NotifyIcon ni         = new NotifyIcon();
            Stream     iconStream = Application.GetResourceStream(new Uri(@"pack://application:,,,/TaskJeeves;component/Images/TaskJeevesIcon.ico")).Stream;

            ni.Icon         = new System.Drawing.Icon(iconStream);
            ni.Visible      = true;
            ni.DoubleClick +=
                delegate(object sender, EventArgs args)
            {
                Show();
                WindowState = WindowState.Normal;
            };

            ni.ContextMenu = new ContextMenu(new MenuItem[] { new MenuItem("Quit Task Jeeves", delegate(object sender, EventArgs args)
                {
                    Application.Current.Shutdown(110);
                }) });
        }
Exemplo n.º 48
0
        private void MoveInTray()
        {
            var streamResourceInfo = Application.GetResourceStream(new Uri(Icon.ToString()));

            if (streamResourceInfo != null)
            {
                var iconStream = streamResourceInfo.Stream;
                var icon       = new Icon(iconStream);

                m_notifyIcon = new NotifyIcon
                {
                    Icon = icon,
                };
            }

            SetNotifyMoveInTray();
            m_notifyIcon.Click  += m_notifyIcon_Click;
            m_notifyIcon.Visible = true;
        }
Exemplo n.º 49
0
        public static Icon ToIcon(this ImageSource imageSource)
        {
            if (imageSource == null)
            {
                return(null);
            }

            Uri uri = new Uri(imageSource.ToString(), UriKind.RelativeOrAbsolute);
            StreamResourceInfo streamInfo = Application.GetResourceStream(uri);

            if (streamInfo == null)
            {
                string msg = "The supplied image source '{0}' could not be resolved.";
                msg = String.Format(msg, imageSource);
                throw new ArgumentException(msg);
            }


            return(new Icon(streamInfo.Stream));
        }
Exemplo n.º 50
0
        public VisualBrush LoadIcon(string path, string resourceKey)
        {
            Object obj = Application.Current.TryFindResource(resourceKey);

            if (obj == null)
            {
                Object comp = Application.LoadComponent(
                    new Uri(path + resourceKey + ".xaml", UriKind.Relative));

                Application.Current.Resources.MergedDictionaries.Add(comp as ResourceDictionary);

                var brush = (VisualBrush)Application.Current.FindResource(resourceKey);

                return(brush);
            }
            else
            {
                return((VisualBrush)obj);
            }
        }
Exemplo n.º 51
0
        public MainWindow()
        {
            InitializeComponent();

            helper = new WindowInteropHelper(this);

            ViewModel = new MainWindowViewModel();
            ViewModel.ShowNotification = (title, message, icon) => notifyIcon.ShowBalloonTip(3000, title, message, icon);

            Closing += OnClosing;

            Activated += (sender, args) =>
            {
                helper.EnsureHandle();
                Win32Api.BringToFront(helper.Handle);
            };

            notifyIcon = new NotifyIcon();

            StreamResourceInfo resourceStream = Application.GetResourceStream(new Uri("pack://application:,,,/App.ico"));

            if (resourceStream != null)
            {
                using (Stream iconStream = resourceStream.Stream)
                {
                    notifyIcon.Icon = new System.Drawing.Icon(iconStream);
                }
            }
            notifyIcon.Visible     = true;
            notifyIcon.MouseClick += OnNotifyIconClick;
            notifyIcon.Text        = ViewModel.Update.ProductAndVersion;

            //notifyIcon.Click += OnNotifyIconClick;

            contextMenu = new ContextMenu();
            var exitMenuItem = new MenuItem("E&xit", (sender, args) => Application.Current.Shutdown());

            contextMenu.MenuItems.Add(exitMenuItem);

            notifyIcon.ContextMenu = contextMenu;
        }
Exemplo n.º 52
0
        public MainWindow()
        {
            App.CurrentMainWindow = this;

            this.InitializeComponent();
            this.DataContext = _viewModel = new MainWindowViewModel();

            // status timeout timer
            _statusTimeoutTimer = new Timer {
                AutoReset = false
            };
            _statusTimeoutTimer.Elapsed += this.StatusTimeoutTimer_Elapsed;

            this.ResetStatusText();


            // tray notifier
            _trayNotifierContextMenu = (ContextMenu)this.FindResource("TrayNotifierContextMenu");

            _trayNotifier.MouseDown   += this.TrayNotifier_MouseDown;
            _trayNotifier.DoubleClick += this.TrayNotifier_DoubleClick;
            var iconInfo = Application.GetResourceStream(new Uri("/Resources/Icons/app.ico", UriKind.Relative));

            if (iconInfo != null)
            {
                using (var iconStream = iconInfo.Stream)
                    this._trayNotifier.Icon = new System.Drawing.Icon(iconStream);
            }

            _trayNotifier.Visible = true;


            MouseHook.MouseAction += this.MouseHook_MouseAction;

            // minimize if start minimized
            if (((App)Application.Current).StartMinimized)
            {
                this.WindowState = System.Windows.WindowState.Minimized;
                this.Hide();
            }
        }
Exemplo n.º 53
0
        private void SetupNotifyIcon()
        {
            _notifyIcon = new NotifyIcon();

            var sri = Application.GetResourceStream(new Uri("/Icon/Icon32.ico", UriKind.Relative));

            if (sri != null)
            {
                _notifyIcon.Icon = new Icon(sri.Stream);
            }
            _notifyIcon.Visible     = true;
            _notifyIcon.MouseClick += (_, e) => {
                switch (e.Button)
                {
                case MouseButtons.Left:
                    Deminimize();
                    break;

                case MouseButtons.Right:
                    ShowNotifyIconContextMenu();
                    break;
                }
            };
            _notifyIcon.BalloonTipClicked += (_, __) => {
                Deminimize();
            };
            StateChanged += (_, __) => {
                if (WindowState == WindowState.Minimized && !ShowInTaskbar)
                {
                    _notifyIcon.ShowBalloonTip(5000, "EZBlocker3", "EZBlocker3 is hidden. Click this icon to restore.", ToolTipIcon.None);
                }
            };
            // ensure context menu gets closed.
            Closed += (_, __) => {
                CloseNotifyIconContextMenu();
                if (_notifyIconContextMenu != null)
                {
                    _notifyIconContextMenu.Visibility = Visibility.Hidden;
                }
            };
        }
Exemplo n.º 54
0
        public static NotifyIcon CreateNotifyIcon(Application app, MenuItem[] menuItems, ISettings settings)
        {
            var icon = new NotifyIcon
            {
                Icon             = Properties.Resources.messenger,
                ContextMenuStrip = new ContextMenuStrip(),
                ContextMenu      = new ContextMenu(menuItems)
            };

            icon.DoubleClick += delegate
            {
                app.MainWindow.Show();
                app.MainWindow.WindowState = System.Windows.WindowState.Normal;
            };

            if (settings.CloseToTray)
            {
                app.ShutdownMode        = ShutdownMode.OnExplicitShutdown;
                app.MainWindow.Closing += (sender, args) =>
                {
                    args.Cancel = true;
                    app.MainWindow.Hide();
                };
            }
            if (settings.MinimizeToTray)
            {
                app.MainWindow.Deactivated += (sender, args) =>
                {
                    var window = sender as MainWindow;

                    if (window?.WindowState != WindowState.Minimized)
                    {
                        return;
                    }

                    window.Hide();
                };
            }

            return(icon);
        }
Exemplo n.º 55
0
            public WpfHostEnvironment()
            {
                //the WPF application object will be the main UI loop
                m_wpfApplication = new System.Windows.Application
                {
                    //otherwise the application will close when all WPF windows are closed
                    ShutdownMode = ShutdownMode.OnExplicitShutdown
                };
                SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());

                //set the WinForms properties
                //notice how you don't need to do anything else with the Windows Forms Application (except handle exceptions)
                System.Windows.Forms.Application.EnableVisualStyles();
                System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);

                //wire up exception handling
                System.Windows.Forms.Application.ThreadException += Application_ThreadException;
                m_wpfApplication.DispatcherUnhandledException    += m_wpfApplication_DispatcherUnhandledException;
                AppDomain.CurrentDomain.UnhandledException       += CurrentDomain_UnhandledException;
                TaskScheduler.UnobservedTaskException            += TaskScheduler_UnobservedTaskException;
            }
Exemplo n.º 56
0
        public override void InitializeApplication()
        {
            application = new System.Windows.Application();

            WidgetRegistry.RegisterBackend(typeof(Window), typeof(WindowBackend));
            WidgetRegistry.RegisterBackend(typeof(Menu), typeof(MenuBackend));
            WidgetRegistry.RegisterBackend(typeof(MenuItem), typeof(MenuItemBackend));
            WidgetRegistry.RegisterBackend(typeof(Box), typeof(BoxBackend));
            WidgetRegistry.RegisterBackend(typeof(Label), typeof(LabelBackend));
            WidgetRegistry.RegisterBackend(typeof(TextEntry), typeof(TextEntryBackend));
            WidgetRegistry.RegisterBackend(typeof(Button), typeof(ButtonBackend));
            WidgetRegistry.RegisterBackend(typeof(ToggleButton), typeof(ToggleButtonBackend));
            WidgetRegistry.RegisterBackend(typeof(CheckBox), typeof(CheckBoxBackend));
            WidgetRegistry.RegisterBackend(typeof(TreeView), typeof(TreeViewBackend));
            WidgetRegistry.RegisterBackend(typeof(TreeStore), typeof(TreeStoreBackend));
            WidgetRegistry.RegisterBackend(typeof(ImageView), typeof(ImageViewBackend));
            WidgetRegistry.RegisterBackend(typeof(Separator), typeof(SeparatorBackend));
            WidgetRegistry.RegisterBackend(typeof(Image), typeof(ImageHandler));
            WidgetRegistry.RegisterBackend(typeof(Font), typeof(FontBackendHandler));
            WidgetRegistry.RegisterBackend(typeof(Clipboard), typeof(ClipboardBackend));
            WidgetRegistry.RegisterBackend(typeof(ComboBox), typeof(ComboBoxBackend));
        }
Exemplo n.º 57
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                FreeConsole();
                var app         = new MainWindow();
                var application = new System.Windows.Application();
                application.Run(app);
                return;
            }

            else
            {
                if (args[0].Equals("dldata"))
                {
                    Getstockdata();
                }

                //Getstockind();
                //complete message
            }
        }
Exemplo n.º 58
0
        public MainWindow()
        {
            InitializeComponent();

            notifyIcon = new NotifyIcon();

            StreamResourceInfo resourceStream = Application.GetResourceStream(new Uri("pack://application:,,,/App.ico"));

            if (resourceStream != null)
            {
                using (Stream iconStream = resourceStream.Stream)
                {
                    notifyIcon.Icon = new Icon(iconStream);
                }

                notifyIcon.Visible      = true;
                notifyIcon.DoubleClick += OnNotifyIconDoubleClick;
            }

            MaxHeight = Screen.PrimaryScreen.Bounds.Height * 0.75;
            MinHeight = 300;
        }
Exemplo n.º 59
0
        public AwesomiumHost(string filename, string baseDirectory)
        {
            if (Application.Current == null)
            {
                app = new Application();
                app.DispatcherUnhandledException += (sender, args) =>
                {
                    // If the preview dies, it is not the end of the world,
                    // but most exceptions shouldn't actually cause the preview to stop
                    args.Handled = true;
                };
            }
            FileName           = filename;
            this.baseDirectory = baseDirectory;

            loadedWaitHandle = new ManualResetEvent(false);

            // We need a hosting user control because awesomium has issues rendering if we create it before
            // dispatcher is running
            control         = new UserControl();
            control.Loaded += ControlLoaded;
        }
Exemplo n.º 60
0
        private static void WpfMainMethod()
        {
            // Create a new WPF application.
            Application = new Application {
                ShutdownMode = ShutdownMode.OnExplicitShutdown
            };

            // Filter WPF message loop to forward keyboard messages to the Windows Forms
            // message loop. If this is uncommented, the XNA Keyboard will not receive all
            // inputs if the WPF window is active.
            ComponentDispatcher.ThreadFilterMessage += OnThreadFilterMessage;

            // The debugger will not break when an exception occurs inside the WPF thread
            // (unless catching first chance exceptions is enabled). If we break in the
            // UnhandledExceptionFilter event then the user sees the call stack of the event.
            // The call stack is unwound after this event.
            Dispatcher.UnhandledExceptionFilter += (s, e) => Debugger.Break();

            // Forward exceptions in the WPF thread to the WinForms thread.
            Application.DispatcherUnhandledException += (s, e) =>
            {
                // Set flag to avoid blocking of the forms thread.
                _applicationStarted = true;

                // Forward the exception to the main thread.
                if (Form != null)
                {
                    Form.BeginInvoke(new Action(delegate
                    {
                        throw new GraphicsException("Exception occurred in WPF environment.", e.Exception);
                    }));
                }
            };

            Application.Startup += (s, e) => _applicationStarted = true;

            Application.Run(); // This call blocks until Shutdown() is called.
        }