public EditorViewport(Window window) { Window = window; IsZoomingEnabled = true; ResetScreenSpace(); Settings.Current.LimitFramerate = 60; }
public override bool HandleDialog(Window window) { if (CanHandleDialog(window)) { dialogHandler._window = window; Message = dialogHandler.Message; var confirmDialogHandler = dialogHandler as ConfirmDialogHandler; // hasHandledDialog must be set before the Click and not // after because this code executes on a different Thread // and could lead to property HasHandledDialog returning false // while hasHandledDialog set had to be set. HasHandledDialog = true; if (confirmDialogHandler != null && clickCancelButton) { confirmDialogHandler.CancelButton.Click(); } else { dialogHandler.OKButton.Click(); } } return HasHandledDialog; }
public KinectHelpState(string name, StateManager manager, string mainWindow, string whereWindow, bool avatar) : base(name, manager) { mInput = manager.Coordinator.GetPlugin<KinectMovementPlugin>(); mMainWindow = manager.Coordinator[mainWindow]; mWhereWindow = whereWindow; mWhereButton = new ImageHoverTrigger(mMainWindow.OverlayManager, new DialCursorRenderer(), new OverlayImage(new Bitmap(mWhereAmIImage), .65f, .25f, mainWindow)); mWhereButton.Triggered += new Action(mWhereButton_Triggered); mCloseWhereButton = new ImageHoverTrigger(Manager.Coordinator[whereWindow].OverlayManager, new DialCursorRenderer(), mWhereButton.Image); mCloseWhereButton.Triggered += new Action(mCloseWhereButton_Triggered); mClickTrigger = new CursorTrigger(new CircleRenderer(100), mMainWindow); SkeletonFeature helpSkeleton = new SkeletonFeature(.065f, 0f, avatar ? .23f : .13f, 125f, mainWindow); AddFeature(helpSkeleton); AddFeature(new OverlayImage(new Bitmap(avatar ? mHelpAvatarImages : mHelpFlycamImages), .05f, avatar ? .2f : .1f, mainWindow)); AddFeature(mClickTrigger); //AddFeature(mWhereButton); mWhereButton.Active = false; mCloseWhereButton.Active = false; }
public TreeViewDemo() { Application.Init (); PopulateStore (); Window win = new Window ("TreeView demo"); win.DeleteEvent += new DeleteEventHandler (DeleteCB); win.SetDefaultSize (640,480); ScrolledWindow sw = new ScrolledWindow (); win.Add (sw); TreeView tv = new TreeView (store); tv.EnableSearch = true; tv.HeadersVisible = true; tv.HeadersClickable = true; tv.AppendColumn ("Name", new CellRendererText (), "text", 0); tv.AppendColumn ("Type", new CellRendererText (), "text", 1); sw.Add (tv); dialog.Destroy (); dialog = null; win.ShowAll (); Application.Run (); }
private void GameUpdate(Window window) { if (window.IsTouching) { alien.position = window.TouchPosition; if ((sprite001.position-window.TouchPosition).Length < 100) { window.Vibrate(1000); } } else { window.CancelVibration(); } alien.DrawTexture(alienTexture); particleSystem001.Update(window); sprite001.position.X += 10f * window.deltaTime; sprite001.DrawSolidColor(1, 0, 0, 0.5f); lineDrawer.Point2 = window.TouchPosition; lineDrawer.DrawSolidColor(1f, 1f, 0f, 1f); window.Update(); }
/// <summary> /// Drops a standard shadow to a WPF Window, even if the window isborderless. Only works with DWM (Windows Vista or newer). /// This method is much more efficient than setting AllowsTransparency to true and using the DropShadow effect, /// as AllowsTransparency involves a huge permormance issue (hardware acceleration is turned off for all the window). /// </summary> /// <param name="window">Window to which the shadow will be applied</param> public static void DropShadowToWindow(Window window) { if (!DropShadow(window)) { window.SourceInitialized += new EventHandler(window_SourceInitialized); } }
/// <summary> /// The actual method that makes API calls to drop the shadow to the window /// </summary> /// <param name="window">Window to which the shadow will be applied</param> /// <returns>True if the method succeeded, false if not</returns> private static bool DropShadow(Window window) { try { WindowInteropHelper helper = new WindowInteropHelper(window); int val = 2; int ret1 = DwmSetWindowAttribute(helper.Handle, 2, ref val, 4); if (ret1 == 0) { Margins m = new Margins { Bottom = 0, Left = 0, Right = 0, Top = 0 }; int ret2 = DwmExtendFrameIntoClientArea(helper.Handle, ref m); return ret2 == 0; } else { return false; } } catch (Exception ex) { // Probably dwmapi.dll not found (incompatible OS) return false; } }
public IsometricCamera(Device device, Window window, Vector3D lookDirection) : base(device, window) { base.Position = -lookDirection; ResetZoom(); leftDirection = Vector3D.Normalize(Vector3D.Cross(lookDirection, -UpDirection)); }
public IsometricCamera(Device device, Window window) : base(device, window) { base.Position = -Vector3D.UnitY; ResetZoom(); leftDirection = Vector3D.Normalize(Vector3D.Cross(Vector3D.UnitY, -UpDirection)); }
static void OnReady() { var grid = new jQuery("#grid").kendoGrid(new GridConfiguration { dataSourceObject = new DataSourceConfiguration { pageSize = 10, data = People.createRandomData(50) }, pageableBoolean = true, height = 260, columns = new JsArray<GridColumnConfiguration> { new GridColumnConfiguration { field = "FirstName", title = "First Name" }, new GridColumnConfiguration { field = "LastName", title = "Last Name" }, new GridColumnConfiguration { field = "Title" }, new GridColumnConfiguration { command = new {text="Details", click= new JsAction<Event>(showDetails)}.As<GridColumnsCommandOptions>(), title = " ", widthString = "110px"} } }).data("kendoGrid"); wnd = new jQuery("#details").kendoWindow(new WindowConfiguration { title = "Customer Details", modal = true, visible = false, resizable = false, width = "300" }).data("kendoWindow").As<Window>(); detailsTemplate = Kendo.template(new jQuery("#template").html()); }
//static long nextTick = DateTime.Now.Ticks; public BusinessGraphicsForm(BusinessGraphicsSourceDesign sourceDesign, Window window) { InitializeComponent(); if (window is ActiveWindow) { wnd = (ActiveWindow)window; BackColor = wnd.BorderColorFrienly; } sourceDesign.Wnd = wnd; sourceDesign.IsPlayerMode = true; _sourceCopy = SourceDesignClone(sourceDesign); this.sourceDesign = sourceDesign; this.sourceDesign.InitializeChart(true); Controls.Clear(); this.sourceDesign.AddChartToContainer(this, wnd); FormClosing += BusinessGraphicsForm_FormClosing; if (sourceDesign.ODBCRefreshInterval > 0) { int time = sourceDesign.ODBCRefreshInterval*1000; if (((BusinessGraphicsResourceInfo) sourceDesign.ResourceDescriptor.ResourceInfo).ProviderType == ProviderTypeEnum.ODBC) refreshTimer = new Timer(RefreshChart, "Timer", time, time); } //начал делать тут проверку, а она оказывается не нужна// //nextTick += time; }
private void VisibilityEvents_WindowShowing(Window window) { if (window.Kind == "Tool" && window.Caption == Resource.ToolWindowTitle) { //_control.OnToolDeactivated(); } }
public HelloWorld() { win = new Window(); win.Title = "Hello World"; win.Name = "EWL_WINDOW"; win.Class = "EWLWindow"; win.SizeRequest(200, 100); win.DeleteEvent += winDelete; win.Show(); lbl = new Entry(); //lbl.SetFont("/usr/share/fonts/ttf/western/Adeventure.ttf", 12); //lbl.SetColor(255, 0 , 0 , 255); //lbl.Style = "soft_shadow"; //lbl.SizeRequest(win.Width, win.Height); //lbl.Disable(); lbl.ChangedEvent += new EwlEventHandler(txtChanged); lbl.Text = "Enlightenment"; Console.WriteLine(lbl.Text); Console.WriteLine(lbl.Text); lbl.TabOrderPush(); win.Append(lbl); lbl.Show(); }
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); }
/// <summary> /// Improves the branch and jump. /// </summary> /// <param name="window">The window.</param> /// <returns></returns> private bool ImproveBranchAndJump(Window window) { if (window.Size < 3) return false; if (!(window.Previous.Instruction is Instructions.Jmp)) return false; if (!(window.PreviousPrevious.Instruction is Instructions.Branch)) return false; if (window.Previous.BasicBlock != window.PreviousPrevious.BasicBlock) return false; if (window.Current.BasicBlock == window.Previous.BasicBlock) return false; if (window.PreviousPrevious.BranchTargets[0] != window.Current.BasicBlock.Label) return false; Debug.Assert(window.PreviousPrevious.BranchTargets.Length == 1); // Negate branch condition window.PreviousPrevious.ConditionCode = GetOppositeConditionCode(window.PreviousPrevious.ConditionCode); // Change branch target window.PreviousPrevious.BranchTargets[0] = window.Previous.BranchTargets[0]; // Delete jump window.DeletePrevious(); return true; }
public void Launch() { _process = Process.Start(_executableLocation); WaitForAppProcessToStart(); WaitForAppWindowToLoad(); Window = new Window(_process); }
public override Window.WindowItemBase FindWindow(Window.SearchCriteria criteria) { Window.WindowItemBase found = null; if (criteria.IsEmpty) return found; if (!string.IsNullOrEmpty(criteria.ClassName) && !criteria.HasExcludes && !criteria.HasID && string.IsNullOrEmpty(criteria.Text)) found = new WindowItem(WindowsAPI.FindWindow(criteria.ClassName, criteria.Title)); else { foreach (var window in AllWindows) { if (window.Equals(criteria)) { found = window; break; } } } if (found != null && found.IsSpecified) LastFound = found; return found; }
public void play_puzzle() { int i; UICollection<UIObject> UICoPane; UICondition uIpane = UICondition.Create("@ControlType=Pane", new Object[0]); UIObject uIopane = this.Children.Find(uIpane); //UICondition uIpane = UICondition.Create("@ControlType=ControlType.Pane", new Object[0]); UICoPane = uIopane.Children.FindMultiple(uIpane); int Dim = UICoPane.Count; //foreach (UIObject i in UICoPane) //{ // Window objpuzzle = new Window(i); // objpuzzle.Click(); //} for(int aa = 0; aa < 40; aa++) { Random rand = new Random(Environment.TickCount); i = rand.Next(Dim); //Console.Write(i.ToString()+" : "); //Console.WriteLine(UICoPane.Count.ToString()+" : "+aa.ToString()); Window objpuzzle = new Window(UICoPane[i]); objpuzzle.Click(); Thread.Sleep(200); } }
public static IDisposable Attach(Window window) { return window.AddHandler( Window.KeyDownEvent, WindowPreviewKeyDown, Interactivity.RoutingStrategies.Tunnel); }
public UI(Window window, Game game) { this.window = window; this.game = game; new Command(window.CloseAfterFrame).Add(new KeyTrigger(Key.Escape, State.Pressed)); new Command(() => window.SetFullscreen(new Size(1920, 1080))).Add(new KeyTrigger(Key.F)); }
public PluginManagerDialog(Window parent, PluginManager manager) : base(Catalog.GetString("Plugins"), parent, DialogFlags. Modal, Catalog.GetString("Close"), ResponseType. None) { SetupTree (); foreach (PluginInfo info in manager.Plugins) { if (info.Plugin == null) { continue; } store.AppendValues (info); } ScrolledWindow win = new ScrolledWindow (); win.HscrollbarPolicy = PolicyType.Automatic; win.VscrollbarPolicy = PolicyType.Automatic; win.Child = tree; VBox.PackStart (win, true, true, 4); SetSizeRequest (400, 400); VBox.ShowAll (); }
private static void FileStorageTest() { const string fileName = "foo.yml"; try { using (var fs = new FileStorage(fileName, FileStorage.Mode.Write | FileStorage.Mode.FormatYaml)) { fs.Write("int", 123); fs.Write("double", Math.PI); using (var tempMat = new Mat("data/lenna.png")) { fs.Write("mat", tempMat); } } using (var fs = new FileStorage(fileName, FileStorage.Mode.Read)) { Console.WriteLine("int: {0}", fs["int"].ReadInt()); Console.WriteLine("double: {0}", (double) fs["double"]); using (var window = new Window("mat")) { window.ShowImage(fs["mat"].ReadMat()); Cv2.WaitKey(); } } } finally { File.Delete(fileName); } }
public void Run() { var capture = new VideoCapture(); capture.Set(CaptureProperty.FrameWidth, 640); capture.Set(CaptureProperty.FrameHeight, 480); capture.Open(-1); if (!capture.IsOpened()) throw new Exception("capture initialization failed"); var fs = FrameSource.CreateCameraSource(-1); var sr = SuperResolution.CreateBTVL1(); sr.SetInput(fs); using (var normalWindow = new Window("normal")) using (var srWindow = new Window("super resolution")) { var normalFrame = new Mat(); var srFrame = new Mat(); while (true) { capture.Read(normalFrame); sr.NextFrame(srFrame); if (normalFrame.Empty() || srFrame.Empty()) break; normalWindow.ShowImage(normalFrame); srWindow.ShowImage(srFrame); Cv2.WaitKey(100); } } }
public override void Initialize () { window = new Window(this); window.IsToolTip = false; window.FontFamily = this.FontFamily; window.BorderThickness = new Thickness (0); window.BorderBrush = Brushes.Transparent; window.Background = Brushes.Transparent;//new SolidColorBrush(new System.Windows.Media.Color ( .2f, .2f, .2f ) * .9f); // new SolidColorBrush(/*new System.Windows.Media.Color ( .8f, .8f, .8f )*/ Colors.CornflowerBlue ); window.Left = (int)this.GetAbsoluteLeft() + this.ActualWidth + 2; window.Top = (int)this.GetAbsoluteTop() + this.ActualHeight / 2f - this.ItemsPanel.ActualHeight / 2f; window.Width = this.ItemsPanel.ActualWidth; window.Height = this.ItemsPanel.ActualHeight; window.LostFocus += delegate { this.IsChecked = false; }; this.ItemsPanel.BorderBrush = null; this.ItemsPanel.BorderThickness = new Thickness(); this.ItemsPanel.Background = new SolidColorBrush(new System.Windows.Media.Color ( .5f, .5f, .5f ) * .95f ); this.ItemsPanel.Parent = window; window.Content = this.ItemsPanel; foreach (var item in items) { this.ItemsPanel.Children.Add(item); } base.Initialize(); }
public static void Main() { BusG.Init (); Application.Init (); tv = new TextView (); ScrolledWindow sw = new ScrolledWindow (); sw.Add (tv); Button btn = new Button ("Click me"); btn.Clicked += OnClick; Button btnq = new Button ("Click me (thread)"); btnq.Clicked += OnClickQuit; VBox vb = new VBox (false, 2); vb.PackStart (sw, true, true, 0); vb.PackStart (btn, false, true, 0); vb.PackStart (btnq, false, true, 0); Window win = new Window ("D-Bus#"); win.SetDefaultSize (640, 480); win.Add (vb); win.Destroyed += delegate {Application.Quit ();}; win.ShowAll (); bus = Bus.Session.GetObject<IBus> ("org.freedesktop.DBus", new ObjectPath ("/org/freedesktop/DBus")); Application.Run (); }
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); }
public MainWindow() { this.InitializeComponent(); this.addingWordWindow = new AddingWindow(); factory = TranslationObjectsFactory.GetFactoryInstance(); this.LoadItemsToList(); }
public static int Main9 (string[] args) { Gtk.Application.Init (); Window win = new Window ("Custom Widget Test"); win.DeleteEvent += new DeleteEventHandler (OnQuit); VPaned paned = new VPaned (); CustomWidget cw = new CustomWidget (); cw.Label = "This one contains a button"; Button button = new Button ("Ordinary button"); cw.Add (button); paned.Pack1 (cw, true, false); cw = new CustomWidget (); cw.Label = "And this one a TextView"; cw.StockId = Stock.JustifyLeft; ScrolledWindow sw = new ScrolledWindow (null, null); sw.ShadowType = ShadowType.In; sw.HscrollbarPolicy = PolicyType.Automatic; sw.VscrollbarPolicy = PolicyType.Automatic; TextView textView = new TextView (); sw.Add (textView); cw.Add (sw); paned.Pack2 (cw, true, false); win.Add (paned); win.ShowAll (); Gtk.Application.Run (); return 0; }
public Window Get(FlowWindow window) { Window result = null; this.list.RemoveAll((info) => { var w = Flow.FlowSystem.GetWindow(info.id); return w == null || w.IsSocial() == false; }); if (window.IsSocial() == false) return result; foreach (var item in this.list) { if (item.id == window.id) { result = item; break; } } if (result == null) { result = new Window(window); this.list.Add(result); } return result; }
public void Named_Canvas_Is_Freed() { Func<Window> run = () => { var window = new Window { Content = new Canvas { Name = "foo" } }; // Do a layout and make sure that Canvas gets added to visual tree. window.LayoutManager.ExecuteLayoutPass(); Assert.IsType<Canvas>(window.Find<Canvas>("foo")); Assert.IsType<Canvas>(window.Presenter.Child); // Clear the content and ensure the Canvas is removed. window.Content = null; window.LayoutManager.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount)); }
private void MinimizeCurentWindow(object parameter) { Window window = (Window)parameter; window.WindowState = WindowState.Minimized; }
private void Preview_window_Closed(object sender, EventArgs e) { preview_window = null; (this.DataContext as EqualizerLayerHandler).NewLayerRender -= Control_EqualizerLayer_NewLayerRender; preview_window_open = false; }
public void Load(IResource resource) => Window.GetTag <OnceAction>().Next += () => LoadModelNow(resource);
void MainView_Loaded(object sender, RoutedEventArgs e) { parentWindow = Window.GetWindow(this); mw = parentWindow as MainWindow; }
public SomeGenericScreen(Window window, ScreenRepository screenRepository) : base(window, screenRepository) { this.window = window; }
void ShowResizerOverlayWindow(LayoutGridResizerControl splitter) { _resizerGhost = new Border() { Background = splitter.BackgroundWhileDragging, Opacity = splitter.OpacityWhileDragging }; int indexOfResizer = InternalChildren.IndexOf(splitter); var prevChild = InternalChildren[indexOfResizer - 1] as FrameworkElement; var nextChild = GetNextVisibleChild(indexOfResizer); var prevChildActualSize = prevChild.TransformActualSizeToAncestor(); var nextChildActualSize = nextChild.TransformActualSizeToAncestor(); var prevChildModel = (ILayoutPositionableElement)(prevChild as ILayoutControl).Model; var nextChildModel = (ILayoutPositionableElement)(nextChild as ILayoutControl).Model; Point ptTopLeftScreen = prevChild.PointToScreenDPIWithoutFlowDirection(new Point()); Size actualSize; if (Orientation == System.Windows.Controls.Orientation.Horizontal) { actualSize = new Size( prevChildActualSize.Width - prevChildModel.DockMinWidth + splitter.ActualWidth + nextChildActualSize.Width - nextChildModel.DockMinWidth, nextChildActualSize.Height); _resizerGhost.Width = splitter.ActualWidth; _resizerGhost.Height = actualSize.Height; ptTopLeftScreen.Offset(prevChildModel.DockMinWidth, 0.0); } else { actualSize = new Size( prevChildActualSize.Width, prevChildActualSize.Height - prevChildModel.DockMinHeight + splitter.ActualHeight + nextChildActualSize.Height - nextChildModel.DockMinHeight); _resizerGhost.Height = splitter.ActualHeight; _resizerGhost.Width = actualSize.Width; ptTopLeftScreen.Offset(0.0, prevChildModel.DockMinHeight); } _initialStartPoint = splitter.PointToScreenDPIWithoutFlowDirection(new Point()) - ptTopLeftScreen; if (Orientation == System.Windows.Controls.Orientation.Horizontal) { Canvas.SetLeft(_resizerGhost, _initialStartPoint.X); } else { Canvas.SetTop(_resizerGhost, _initialStartPoint.Y); } Canvas panelHostResizer = new Canvas() { HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch }; panelHostResizer.Children.Add(_resizerGhost); _resizerWindowHost = new Window() { SizeToContent = System.Windows.SizeToContent.Manual, ResizeMode = ResizeMode.NoResize, WindowStyle = System.Windows.WindowStyle.None, ShowInTaskbar = false, AllowsTransparency = true, Background = null, Width = actualSize.Width, Height = actualSize.Height, Left = ptTopLeftScreen.X, Top = ptTopLeftScreen.Y, ShowActivated = false, //Owner = Window.GetWindow(this), Content = panelHostResizer }; _resizerWindowHost.Loaded += (s, e) => { _resizerWindowHost.SetParentToMainWindowOf(this); }; _resizerWindowHost.Show(); }
protected override void OnStartup(StartupEventArgs args) //перегружаем OnStartup { base.OnStartup(args); //base позволяет запускать любую логику базового класса Window win = new Window(); //создаем окно win.Title = "Examine Routed Events"; // Grid grid = new Grid(); //создаем grid (Задание области с таблицей переменного размера) win.Content = grid; //контентом окна задаем grid RowDefinition rowdef = new RowDefinition(); //инициализируем класс RowDefinition(Определяет специфические для строки свойства, применимые к элементам Grid.) rowdef.Height = GridLength.Auto; // высота строки выставляется автоматически grid.RowDefinitions.Add(rowdef); //добавляем строку rowdef = new RowDefinition(); rowdef.Height = GridLength.Auto; grid.RowDefinitions.Add(rowdef); rowdef = new RowDefinition(); rowdef.Height = new GridLength(100, GridUnitType.Star); //высота строки 100 star( grid.RowDefinitions.Add(rowdef); //добавляем строку Button btn = new Button(); //создаем кнопку btn.HorizontalAlignment = HorizontalAlignment.Center; //ставим кнопку по центру btn.Margin = new Thickness(24); // выставляем margin btn.Padding = new Thickness(24); // выставляем padding grid.Children.Add(btn); // добавляем в наш grid TextBlock text = new TextBlock(); //создаем textblock text.FontSize = 24; // размер шрифта text.Text = win.Title; // задаем значение текстового поля нашего textblock btn.Content = text; //добавляем наш текст в кнопку TextBlock textHeadings = new TextBlock(); //задаем заголовок для вывода над scroll viewer :) textHeadings.FontFamily = fontfam; // шрифтом Lucida Console textHeadings.Inlines.Add(new Underline(new Run(String.Format(strFormat, "Routed Event", "sender", "Source", "OriginalSource")))); // задаем то как будет выводиться в консоле описание для scrolviewer grid.Children.Add(textHeadings); //добавляем строку с вышезаданаыми параметрами Grid.SetRow(textHeadings, 1); //выводим ее первой ScrollViewer scroll = new ScrollViewer(); //создаем ScrollViewer grid.Children.Add(scroll); //добавляем ScrollViewer в наш grid Grid.SetRow(scroll, 2); //выводим его вторым stackOutput = new StackPanel(); //создаем StackPanel для отображения событий scroll.Content = stackOutput; //задаем контент для нашегоScrollViewer (StackPanel ) UIElement[] els = { win, grid, btn, text }; //добвляем обработчика событий/ создаем массив класса UIElement ( из окна , grid, кнопки и текста)(принимаем весь ввод) foreach (UIElement el in els) { // для каждого элемента el.PreviewKeyDown += AllPurposeEventHandler; //клавиатура el.PreviewKeyUp += AllPurposeEventHandler; el.PreviewTextInput += AllPurposeEventHandler; el.KeyDown += AllPurposeEventHandler; el.KeyUp += AllPurposeEventHandler; el.TextInput += AllPurposeEventHandler;//мыш el.MouseDown += AllPurposeEventHandler; el.MouseUp += AllPurposeEventHandler; el.PreviewMouseDown += AllPurposeEventHandler; el.PreviewMouseUp += AllPurposeEventHandler;//стилус el.StylusDown += AllPurposeEventHandler; el.StylusUp += AllPurposeEventHandler; el.PreviewStylusDown += AllPurposeEventHandler; el.PreviewStylusUp += AllPurposeEventHandler; //клики el.AddHandler(Button.ClickEvent, new RoutedEventHandler(AllPurposeEventHandler)); // убираем лишний клик мыши при нажатии кнопки } win.Show(); // показываем окно }
public static Task <string[]> ShowManagedAsync(this OpenFileDialog dialog, Window parent, ManagedFileDialogOptions options = null) => ShowManagedAsync <Window>(dialog, parent, options);
async Task <string[]> Show(SystemDialog d, Window parent, ManagedFileDialogOptions options = null) { var model = new ManagedFileChooserViewModel((FileSystemDialog)d, options ?? new ManagedFileDialogOptions()); var dialog = new T { Content = new ManagedFileChooser(), Title = d.Title, DataContext = model }; dialog.Closed += delegate { model.Cancel(); }; string[] result = null; model.CompleteRequested += items => { result = items; dialog.Close(); }; model.OverwritePrompt += async(filename) => { Window overwritePromptDialog = new Window() { Title = "Confirm Save As", SizeToContent = SizeToContent.WidthAndHeight, WindowStartupLocation = WindowStartupLocation.CenterOwner, Padding = new Thickness(10), MinWidth = 270 }; string name = Path.GetFileName(filename); var panel = new DockPanel() { HorizontalAlignment = Layout.HorizontalAlignment.Stretch }; var label = new Label() { Content = $"{name} already exists.\nDo you want to replace it?" }; panel.Children.Add(label); DockPanel.SetDock(label, Dock.Top); var buttonPanel = new StackPanel() { HorizontalAlignment = Layout.HorizontalAlignment.Right, Orientation = Layout.Orientation.Horizontal, Spacing = 10 }; var button = new Button() { Content = "Yes", HorizontalAlignment = Layout.HorizontalAlignment.Right }; button.Click += (sender, args) => { result = new string[1] { filename }; overwritePromptDialog.Close(); dialog.Close(); }; buttonPanel.Children.Add(button); button = new Button() { Content = "No", HorizontalAlignment = Layout.HorizontalAlignment.Right }; button.Click += (sender, args) => { overwritePromptDialog.Close(); }; buttonPanel.Children.Add(button); panel.Children.Add(buttonPanel); DockPanel.SetDock(buttonPanel, Dock.Bottom); overwritePromptDialog.Content = panel; await overwritePromptDialog.ShowDialog(dialog); }; model.CancelRequested += dialog.Close; await dialog.ShowDialog <object>(parent); return(result); }
public static Task <string[]> ShowManagedAsync <TWindow>(this OpenFileDialog dialog, Window parent, ManagedFileDialogOptions options = null) where TWindow : Window, new() { return(new ManagedSystemDialogImpl <TWindow>().ShowFileDialogAsync(dialog, parent, options)); }
public async Task <string[]> ShowFileDialogAsync(FileDialog dialog, Window parent) { return(await Show(dialog, parent)); }
public async Task <string[]> ShowFileDialogAsync(FileDialog dialog, Window parent, ManagedFileDialogOptions options) { return(await Show(dialog, parent, options)); }
void ApplyRegion(Rect wndRect) { if (!this.CanTransform()) { return; } wndRect = new Rect( this.TransformFromDeviceDPI(wndRect.TopLeft), this.TransformFromDeviceDPI(wndRect.Size)); _lastApplyRect = wndRect; if (PresentationSource.FromVisual(this) == null) { return; } if (_dockingManager != null) { List <Rect> otherRects = new List <Rect>(); foreach (Window fl in Window.GetWindow(_dockingManager).OwnedWindows) { //not with myself! if (fl == this) { continue; } if (!fl.IsVisible) { continue; } //Issue 11545, thx to SrdjanPolic Rect flRect = new Rect( PointFromScreen(new Point(fl.Left, fl.Top)), PointFromScreen(new Point(fl.Left + fl.RestoreBounds.Width, fl.Top + fl.RestoreBounds.Height))); if (flRect.IntersectsWith(wndRect) && fl.AllowsTransparency == false) { otherRects.Add(Rect.Intersect(flRect, wndRect)); } //Rect flRect = new Rect( // PointFromScreen(new Point(fl.Left, fl.Top)), // PointFromScreen(new Point(fl.Left + fl.Width, fl.Top + fl.Height))); //if (flRect.IntersectsWith(wndRect)) // otherRects.Add(Rect.Intersect(flRect, wndRect)); } IntPtr hDestRegn = InteropHelper.CreateRectRgn( (int)wndRect.Left, (int)wndRect.Top, (int)wndRect.Right, (int)wndRect.Bottom); foreach (Rect otherRect in otherRects) { IntPtr otherWin32Rect = InteropHelper.CreateRectRgn( (int)otherRect.Left, (int)otherRect.Top, (int)otherRect.Right, (int)otherRect.Bottom); InteropHelper.CombineRgn(hDestRegn, hDestRegn, otherWin32Rect, (int)InteropHelper.CombineRgnStyles.RGN_DIFF); } InteropHelper.SetWindowRgn(new WindowInteropHelper(this).Handle, hDestRegn, true); } }
public async Task <string> ShowFolderDialogAsync(OpenFolderDialog dialog, Window parent) { return((await Show(dialog, parent))?.FirstOrDefault()); }
private void CommandBinding_PlayEpisode(object sender, ExecutedRoutedEventArgs e) { Window parentWindow = Window.GetWindow(this); object obj = e.Parameter; if (obj == null) { return; } try { if (obj.GetType() == typeof(AnimeEpisodeDisplayVM)) { AnimeEpisodeDisplayVM ep = obj as AnimeEpisodeDisplayVM; if (ep.FilesForEpisode.Count == 1) { bool force = true; if (ep.FilesForEpisode[0].VideoLocal_ResumePosition > 0) { AskResumeVideo ask = new AskResumeVideo(ep.FilesForEpisode[0].VideoLocal_ResumePosition); ask.Owner = Window.GetWindow(this); if (ask.ShowDialog() == true) { force = false; } } MainWindow.videoHandler.PlayVideo(ep.FilesForEpisode[0], force); } else if (ep.FilesForEpisode.Count > 1) { if (AppSettings.AutoFileSingleEpisode) { VideoDetailedVM vid = MainWindow.videoHandler.GetAutoFileForEpisode(ep); if (vid != null) { bool force = true; if (vid.VideoLocal_ResumePosition > 0) { AskResumeVideo ask = new AskResumeVideo(vid.VideoLocal_ResumePosition); ask.Owner = Window.GetWindow(this); if (ask.ShowDialog() == true) { force = false; } } MainWindow.videoHandler.PlayVideo(vid, force); } } else { PlayVideosForEpisodeForm frm = new PlayVideosForEpisodeForm(); frm.Owner = parentWindow; frm.Init(ep); bool?result = frm.ShowDialog(); } } } } catch (Exception ex) { Utils.ShowErrorMessage(ex); } }
protected override void OnMouseMove(MouseEventArgs e) { if (_moveEvent && e.GetPosition(null) != _mousePosition) { this.RenderTransform = new TranslateTransform(Mouse.GetPosition(Window.GetWindow(this)).X, Mouse.GetPosition(Window.GetWindow(this)).Y); } base.OnMouseMove(e); }
private void CommandBinding_ToggleWatchedStatus(object sender, ExecutedRoutedEventArgs e) { object obj = e.Parameter; if (obj == null) { return; } this.Cursor = Cursors.Wait; try { Window parentWindow = Window.GetWindow(this); AnimeSeriesVM ser = null; bool newStatus = false; if (obj.GetType() == typeof(VideoDetailedVM)) { VideoDetailedVM vid = obj as VideoDetailedVM; newStatus = !vid.Watched; JMMServerVM.Instance.clientBinaryHTTP.ToggleWatchedStatusOnVideo(vid.VideoLocalID, newStatus, JMMServerVM.Instance.CurrentUser.JMMUserID.Value); MainListHelperVM.Instance.UpdateHeirarchy(vid); ser = MainListHelperVM.Instance.GetSeriesForVideo(vid.VideoLocalID); } if (obj.GetType() == typeof(AnimeEpisodeDisplayVM)) { AnimeEpisodeDisplayVM ep = obj as AnimeEpisodeDisplayVM; newStatus = !ep.Watched; JMMServerBinary.Contract_ToggleWatchedStatusOnEpisode_Response response = JMMServerVM.Instance.clientBinaryHTTP.ToggleWatchedStatusOnEpisode(ep.AnimeEpisodeID, newStatus, JMMServerVM.Instance.CurrentUser.JMMUserID.Value); if (!string.IsNullOrEmpty(response.ErrorMessage)) { MessageBox.Show(response.ErrorMessage, Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error); return; } MainListHelperVM.Instance.UpdateHeirarchy(response.AnimeEpisode); ser = MainListHelperVM.Instance.GetSeriesForEpisode(ep); } RefreshData(); if (newStatus == true && ser != null) { Utils.PromptToRateSeries(ser, parentWindow); } } catch (Exception ex) { Utils.ShowErrorMessage(ex); } finally { this.Cursor = Cursors.Arrow; } }
void ShowResizerOverlayWindow(Resizer splitter) { _resizerGhost = new Border() { Background = Brushes.Black, Opacity = 0.7 }; if (CorrectedAnchor == AnchorStyle.Left || CorrectedAnchor == AnchorStyle.Right) { _resizerGhost.Width = splitter.Width; _resizerGhost.Height = MaxHeight; } else { _resizerGhost.Height = splitter.Height; _resizerGhost.Width = MaxWidth; } Canvas panelHostResizer = new Canvas() { HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch }; panelHostResizer.Children.Add(_resizerGhost); _resizerWindowHost = new Window() { ResizeMode = ResizeMode.NoResize, WindowStyle = System.Windows.WindowStyle.None, ShowInTaskbar = false, AllowsTransparency = true, Background = null, Width = MaxWidth, Height = MaxHeight, Left = Left, Top = Top, ShowActivated = false, Owner = this, Content = panelHostResizer }; if (CorrectedAnchor == AnchorStyle.Right) { _resizerWindowHost.Left = Left - MaxWidth + Width; } else if (CorrectedAnchor == AnchorStyle.Bottom) { _resizerWindowHost.Top = Top - MaxHeight + Height; } if (CorrectedAnchor == AnchorStyle.Left) { Canvas.SetLeft(_resizerGhost, Width - splitter.Width); } else if (CorrectedAnchor == AnchorStyle.Right) { Canvas.SetLeft(_resizerGhost, MaxWidth - Width); } else if (CorrectedAnchor == AnchorStyle.Top) { Canvas.SetTop(_resizerGhost, Height - splitter.Height); } else if (CorrectedAnchor == AnchorStyle.Bottom) { Canvas.SetTop(_resizerGhost, MaxHeight - Height); } _initialStartPoint = new Vector(Canvas.GetLeft(_resizerGhost), Canvas.GetTop(_resizerGhost)); _resizerWindowHost.Show(); }
public static IntPtr GetHandle(this Window window) { var source = new WindowInteropHelper(window); return source.EnsureHandle(); }
void btnPlayNextEp_Click(object sender, RoutedEventArgs e) { if (UnwatchedEpisodes.Count == 0) { return; } try { AnimeEpisodeVM ep = UnwatchedEpisodes[0]; if (ep.IsWatched == 1) { if (UnwatchedEpisodes.Count == 1) { ep = UnwatchedEpisodes[1]; } else { return; } } if (ep.FilesForEpisode.Count == 1) { bool force = true; if (ep.FilesForEpisode[0].VideoLocal_ResumePosition > 0) { AskResumeVideo ask = new AskResumeVideo(ep.FilesForEpisode[0].VideoLocal_ResumePosition); ask.Owner = Window.GetWindow(this); if (ask.ShowDialog() == true) { force = false; } } MainWindow.videoHandler.PlayVideo(ep.FilesForEpisode[0], force); } else if (ep.FilesForEpisode.Count > 1) { if (AppSettings.AutoFileSingleEpisode) { VideoDetailedVM vid = MainWindow.videoHandler.GetAutoFileForEpisode(ep); if (vid != null) { bool force = true; if (vid.VideoLocal_ResumePosition > 0) { AskResumeVideo ask = new AskResumeVideo(vid.VideoLocal_ResumePosition); ask.Owner = Window.GetWindow(this); if (ask.ShowDialog() == true) { force = false; } } MainWindow.videoHandler.PlayVideo(vid, force); } } else { MainWindow mainwdw = (MainWindow)Window.GetWindow(this); PlayVideosForEpisodeForm frm = new PlayVideosForEpisodeForm(); frm.Owner = mainwdw; frm.Init(ep); bool?result = frm.ShowDialog(); } } } catch (Exception ex) { Utils.ShowErrorMessage(ex); } }
public SanPhamContentVM() { DanhMucSanPhamCommand = new RelayCommand <UserControl>((p) => { return(true); }, (p) => { var w = Window.GetWindow(p) as Window; if (w != null) { w.Hide(); DanhMucSanPham DanhMucForm = new DanhMucSanPham(); DanhMucForm.ShowDialog(); w.Show(); } }); LoaiSanPhamCommand = new RelayCommand <UserControl>((p) => { return(true); }, (p) => { var w = Window.GetWindow(p) as Window; if (w != null) { w.Hide(); LoaiSanPham LoaiSPForm = new LoaiSanPham(); LoaiSPForm.ShowDialog(); w.Show(); } }); NhaCungCapCommand = new RelayCommand <UserControl>((p) => { return(true); }, (p) => { var w = Window.GetWindow(p) as Window; if (w != null) { w.Hide(); NhaCungCap nccForm = new NhaCungCap(); nccForm.ShowDialog(); w.Show(); } }); ThemSanPhamCommand = new RelayCommand <UserControl>((p) => { return(true); }, (p) => { var w = Window.GetWindow(p) as Window; if (w != null) { w.Hide(); ThemSanPham themSPForm = new ThemSanPham(); ThemSanPhamVM.idUpdate = ""; ThemSanPhamVM.isUpdate = false; var sanPhamVM = themSPForm.DataContext as ThemSanPhamVM; sanPhamVM.Init(); themSPForm.ShowDialog(); w.Show(); } }); }
private void ouvrirAcceuil(object sender, RoutedEventArgs e) { Window pageAcceuil = Window.GetWindow(this); pageAcceuil.Content = new MenuSelectionB(); }
public GlowWindow(Window owner, GlowDirection direction) { InitializeComponent(); this.IsGlowing = true; this.AllowsTransparency = true; this.Closing += (sender, e) => e.Cancel = !closing; this.Owner = owner; glow.Visibility = Visibility.Collapsed; var b = new Binding("GlowBrush"); b.Source = owner; glow.SetBinding(Glow.GlowBrushProperty, b); b = new Binding("NonActiveGlowBrush"); b.Source = owner; glow.SetBinding(Glow.NonActiveGlowBrushProperty, b); b = new Binding("BorderThickness"); b.Source = owner; glow.SetBinding(Glow.BorderThicknessProperty, b); glow.Direction = direction; switch (direction) { case GlowDirection.Left: glow.Orientation = Orientation.Vertical; glow.HorizontalAlignment = HorizontalAlignment.Right; getLeft = (rect) => rect.left - glowSize + 1; getTop = (rect) => rect.top - 2; getWidth = (rect) => glowSize; getHeight = (rect) => rect.Height + 4; getHitTestValue = p => new Rect(0, 0, ActualWidth, edgeSize).Contains(p) ? HitTestValues.HTTOPLEFT : new Rect(0, ActualHeight - edgeSize, ActualWidth, edgeSize).Contains(p) ? HitTestValues.HTBOTTOMLEFT : HitTestValues.HTLEFT; getCursor = p => { return((owner.ResizeMode == ResizeMode.NoResize || owner.ResizeMode == ResizeMode.CanMinimize) ? owner.Cursor : new Rect(0, 0, ActualWidth, edgeSize).Contains(p) ? Cursors.SizeNWSE : new Rect(0, ActualHeight - edgeSize, ActualWidth, edgeSize).Contains(p) ? Cursors.SizeNESW : Cursors.SizeWE); }; break; case GlowDirection.Right: glow.Orientation = Orientation.Vertical; glow.HorizontalAlignment = HorizontalAlignment.Left; getLeft = (rect) => rect.right - 1; getTop = (rect) => rect.top - 2; getWidth = (rect) => glowSize; getHeight = (rect) => rect.Height + 4; getHitTestValue = p => new Rect(0, 0, ActualWidth, edgeSize).Contains(p) ? HitTestValues.HTTOPRIGHT : new Rect(0, ActualHeight - edgeSize, ActualWidth, edgeSize).Contains(p) ? HitTestValues.HTBOTTOMRIGHT : HitTestValues.HTRIGHT; getCursor = p => { return((owner.ResizeMode == ResizeMode.NoResize || owner.ResizeMode == ResizeMode.CanMinimize) ? owner.Cursor : new Rect(0, 0, ActualWidth, edgeSize).Contains(p) ? Cursors.SizeNESW : new Rect(0, ActualHeight - edgeSize, ActualWidth, edgeSize).Contains(p) ? Cursors.SizeNWSE : Cursors.SizeWE); }; break; case GlowDirection.Top: glow.Orientation = Orientation.Horizontal; glow.VerticalAlignment = VerticalAlignment.Bottom; getLeft = (rect) => rect.left - 2; getTop = (rect) => rect.top - glowSize + 1; getWidth = (rect) => rect.Width + 4; getHeight = (rect) => glowSize; getHitTestValue = p => new Rect(0, 0, edgeSize - glowSize, ActualHeight).Contains(p) ? HitTestValues.HTTOPLEFT : new Rect(Width - edgeSize + glowSize, 0, edgeSize - glowSize, ActualHeight).Contains(p) ? HitTestValues.HTTOPRIGHT : HitTestValues.HTTOP; getCursor = p => { return((owner.ResizeMode == ResizeMode.NoResize || owner.ResizeMode == ResizeMode.CanMinimize) ? owner.Cursor : new Rect(0, 0, edgeSize - glowSize, ActualHeight).Contains(p) ? Cursors.SizeNWSE : new Rect(Width - edgeSize + glowSize, 0, edgeSize - glowSize, ActualHeight). Contains(p) ? Cursors.SizeNESW : Cursors.SizeNS); }; break; case GlowDirection.Bottom: glow.Orientation = Orientation.Horizontal; glow.VerticalAlignment = VerticalAlignment.Top; getLeft = (rect) => rect.left - 2; getTop = (rect) => rect.bottom - 1; getWidth = (rect) => rect.Width + 4; getHeight = (rect) => glowSize; getHitTestValue = p => new Rect(0, 0, edgeSize - glowSize, ActualHeight).Contains(p) ? HitTestValues.HTBOTTOMLEFT : new Rect(Width - edgeSize + glowSize, 0, edgeSize - glowSize, ActualHeight).Contains(p) ? HitTestValues.HTBOTTOMRIGHT : HitTestValues.HTBOTTOM; getCursor = p => { return((owner.ResizeMode == ResizeMode.NoResize || owner.ResizeMode == ResizeMode.CanMinimize) ? owner.Cursor : new Rect(0, 0, edgeSize - glowSize, ActualHeight).Contains(p) ? Cursors.SizeNESW : new Rect(Width - edgeSize + glowSize, 0, edgeSize - glowSize, ActualHeight). Contains(p) ? Cursors.SizeNWSE : Cursors.SizeNS); }; break; } owner.ContentRendered += (sender, e) => glow.Visibility = Visibility.Visible; owner.Activated += (sender, e) => { Update(); glow.IsGlow = true; }; owner.Deactivated += (sender, e) => glow.IsGlow = false; owner.StateChanged += (sender, e) => Update(); owner.IsVisibleChanged += (sender, e) => Update(); owner.Closed += (sender, e) => { closing = true; Close(); }; }
public static uint GetDpi(Window window, DpiType dpiType) { var hwnd = new WindowInteropHelper(window).Handle; return(GetDpi(hwnd, dpiType)); }
public static string AskForSelection([NotNull] string title, [CanBeNull] string header, [NotNull] string message, [NotNull] IEnumerable <string> options, [CanBeNull] Window owner, [CanBeNull] string defaultValue = null, [CanBeNull] bool?allowMultiSelect = null, [CanBeNull] bool?forceShinyDialog = null) { Assert.ArgumentNotNull(title, nameof(title)); Assert.ArgumentNotNull(message, nameof(message)); Assert.ArgumentNotNull(options, nameof(options)); var optionsArray = options.ToArray(); if (forceShinyDialog == true || (optionsArray.Length < 5 && allowMultiSelect != true)) { TaskDialogOptions config = new TaskDialogOptions { Owner = owner, Title = title, MainInstruction = header ?? title, Content = message, CommandButtons = optionsArray, MainIcon = VistaTaskDialogIcon.Information, AllowDialogCancellation = true }; TaskDialogResult res = null; if (owner == null) { res = TaskDialog.Show(config); } else { owner.Dispatcher.Invoke(() => { res = TaskDialog.Show(config); }); } if (res == null) { return(null); } var resultIndex = res.CommandButtonResult; if (resultIndex == null) { return(null); } return(optionsArray[(int)resultIndex]); } SelectDialog dialog = new SelectDialog { DataContext = optionsArray, Title = message, AllowMultiSelect = allowMultiSelect ?? false }; if (defaultValue != null) { dialog.DefaultValue = defaultValue; } object result = null; if (owner == null) { result = ShowDialog(dialog, null); } else { owner.Dispatcher.Invoke(() => { result = ShowDialog(dialog, owner); }); } return(result as string); }
public StateBar() { InitializeComponent(); if (Design.IsInDesignMode) { return; } this.RunOneceOnLoaded(() => { var window = Window.GetWindow(this); window.Activated += (object sender, EventArgs e) => { Vm.OnPropertyChanged(nameof(Vm.IsAutoAdminLogon)); Vm.OnPropertyChanged(nameof(Vm.AutoAdminLogonToolTip)); Vm.OnPropertyChanged(nameof(Vm.IsRemoteDesktopEnabled)); Vm.OnPropertyChanged(nameof(Vm.RemoteDesktopToolTip)); }; // 时间事件是在WPF UI线程的,所以这里不用考虑访问UI线程创建的Vm对象的问题 window.On <MinutePartChangedEvent>("时间的分钟部分变更过更新计时器显示", LogEnum.None, action: message => { Vm.UpdateDateTime(); }); window.On <Per1SecondEvent>("挖矿计时秒表", LogEnum.None, action: message => { DateTime now = DateTime.Now; Vm.UpdateBootTimeSpan(now - NTMinerRoot.Instance.CreatedOn); if (NTMinerRoot.IsAutoStart && VirtualRoot.SecondCount <= Vm.MinerProfile.AutoStartDelaySeconds && !NTMinerRoot.IsAutoStartCanceled) { return; } var mineContext = NTMinerRoot.Instance.CurrentMineContext; if (mineContext != null) { Vm.UpdateMineTimeSpan(now - mineContext.CreatedOn); if (!Vm.MinerProfile.IsMining) { Vm.MinerProfile.IsMining = true; } } else { if (Vm.MinerProfile.IsMining) { Vm.MinerProfile.IsMining = false; } } }); window.On <AppVersionChangedEvent>("发现了服务端新版本", LogEnum.DevConsole, action: message => { UIThread.Execute(() => { if (NTMinerRoot.CurrentVersion.ToString() != NTMinerRoot.ServerVersion) { Vm.CheckUpdateForeground = new SolidColorBrush(Colors.Red); } else { Vm.CheckUpdateForeground = new SolidColorBrush(Colors.Black); } }); }); window.On <KernelSelfRestartedEvent>("内核自我重启时刷新计数器", LogEnum.DevConsole, action: message => { UIThread.Execute(() => { Vm.OnPropertyChanged(nameof(Vm.KernelSelfRestartCountText)); }); }); window.On <MineStartedEvent>("挖矿开始后将内核自我重启计数清零", LogEnum.DevConsole, action: message => { UIThread.Execute(() => { Vm.OnPropertyChanged(nameof(Vm.KernelSelfRestartCountText)); }); }); }); var gpuSet = NTMinerRoot.Instance.GpuSet; // 建议每张显卡至少对应4G虚拟内存,否则标红 if (NTMinerRoot.OSVirtualMemoryMb < gpuSet.Count * 4) { BtnShowVirtualMemory.Foreground = new SolidColorBrush(Colors.Red); } }
public static WindowPosition ToWindowPosition(this Window window) { return(WindowPosition.FromWindow(window)); }
public void Activate() { Window window = NUIApplication.GetDefaultWindow(); root = new View() { Size2D = new Size2D(1920, 1080), }; CreateBoardAndButtons(); scrollBar1_1 = new ScrollBar(); scrollBar1_1.Position2D = new Position2D(50, 300); scrollBar1_1.Size2D = new Size2D(300, 4); scrollBar1_1.Style.Track.BackgroundColor = Color.Green; scrollBar1_1.MaxValue = (int)scrollBar1_1.SizeWidth / 10; scrollBar1_1.MinValue = 0; scrollBar1_1.Style.Thumb.Size = new Size(30, 4); scrollBar1_1.CurrentValue = 0; //set after thumbsize scrollBar1_1.Style.Thumb.BackgroundColor = Color.Black; root.Add(scrollBar1_1); scrollBar1_2 = new ScrollBar(); scrollBar1_2.Position2D = new Position2D(50, 400); scrollBar1_2.Size2D = new Size2D(300, 4); scrollBar1_2.Style.Track.BackgroundColor = Color.Green; scrollBar1_2.MaxValue = (int)scrollBar1_2.SizeWidth / 10; scrollBar1_2.MinValue = 0; scrollBar1_2.Style.Thumb.Size = new Size(30, 4); scrollBar1_2.CurrentValue = 0;//set after thumbsize scrollBar1_2.Style.Thumb.BackgroundColor = Color.Yellow; scrollBar1_2.Style.Track.ResourceUrl = CommonResource.GetTVResourcePath() + "component/c_progressbar/c_progressbar_white_buffering.png"; root.Add(scrollBar1_2); ScrollBarStyle attr = new ScrollBarStyle { Track = new ImageViewStyle { BackgroundColor = new Selector <Color> { All = new Color(0.43f, 0.43f, 0.43f, 0.1f), } }, Thumb = new ImageViewStyle { BackgroundColor = new Selector <Color> { All = new Color(1.0f, 0.0f, 0.0f, 0.2f), } }, }; scrollBar2_1 = new ScrollBar(attr); scrollBar2_1.Position2D = new Position2D(500, 300); scrollBar2_1.Size2D = new Size2D(300, 4); scrollBar2_1.MaxValue = (int)scrollBar2_1.SizeWidth / 10; scrollBar2_1.MinValue = 0; scrollBar2_1.Style.Thumb.Size = new Size(30, 4); scrollBar2_1.CurrentValue = 0; //set after thumbsize root.Add(scrollBar2_1); board.UpFocusableView = button1; window.Add(root); FocusManager.Instance.SetCurrentFocusView(button1); }
public static void ApplyToWindow(this WindowPosition windowPosition, Window window) { WindowPosition.ToWindow(window, windowPosition); }
public static TaskDialogResult LongRunningTask(Action longRunningTask, string title, Window owner, string content = null, string technicalInformation = null, bool allowHidingWindow = false, bool dirtyCancelationMode = false, bool allowSkip = false) { bool canceled = false; using (new ProfileSection("Long running task")) { ProfileSection.Argument("longRunningTask", longRunningTask); ProfileSection.Argument("title", title); ProfileSection.Argument("owner", owner); ProfileSection.Argument("content", content); ProfileSection.Argument("technicalInformation", technicalInformation); ProfileSection.Argument("allowHidingWindow", allowHidingWindow); ProfileSection.Argument("dirtyCancelationMode", dirtyCancelationMode); ProfileSection.Argument("allowSkip", allowSkip); bool isDone = false; var thread = new Thread(() => { using (new ProfileSection("{0} (background thread)".FormatWith(title))) { try { if (!dirtyCancelationMode) { longRunningTask(); } else { // this may be required when some of underlying code ignores ThreadAbortException // so we just letting it to complete and just stop waiting var innerDone = false; var async = new Action(() => { longRunningTask(); innerDone = true; }); async.BeginInvoke(null, null); // waiting until it is done or ThreadAbortException is thrown while (!innerDone) { Thread.Sleep(100); } } } catch (ThreadAbortException ex) { Log.Warn(ex, $"Long running task \"{title}\" failed with exception"); } catch (Exception ex) { HandleError("Long running task \"{0}\" failed with exception".FormatWith(title), true, ex); } isDone = true; } }); const string Inerrupt = "&Cancel"; const string Skip = "&Skip"; var options = allowSkip ? new[] { Inerrupt, Skip } : new[] { Inerrupt }; // const string hide = "&Hide"; TaskDialogOptions config = new TaskDialogOptions { Owner = owner, Title = title, MainInstruction = content ?? title, ExpandedInfo = technicalInformation ?? string.Empty, CustomButtons = options, /* ButtonId=500; dialog.ClickCustomButton(0) }, */ // allowHidingWindow ? new[] { hide /* ButtonId=501 */, inerrupt /* ButtonId=500; dialog.ClickCustomButton(0) */ } : AllowDialogCancellation = true, ShowMarqueeProgressBar = true, EnableCallbackTimer = true, Callback = (dialog, args, obj) => { switch (args.Notification) { // initialization case VistaTaskDialogNotification.Created: dialog.SetProgressBarMarquee(true, 0); // 0 is ignored break; // dialog is hidden case VistaTaskDialogNotification.ButtonClicked: case VistaTaskDialogNotification.Destroyed: // do not shutdown thread if button Hide was clicked if (thread.IsAlive) { switch (args.ButtonId) { case 500: thread.Abort(); canceled = true; break; case 501: thread.Abort(); break; } } break; case VistaTaskDialogNotification.Timer: dialog.SetContent($"Time elapsed: {TimeSpan.FromMilliseconds(args.TimerTickCount).ToString(@"h\:mm\:ss")}"); if (isDone) { dialog.ClickCustomButton(0); } break; } return(false); } }; try { thread.Start(); var result = TaskDialog.Show(config); return(canceled ? null : result); } catch (ThreadAbortException) { } catch (Exception ex) { HandleError("The long running task caused an exception", true, ex); } return(null); } }