Inheritance: MonoBehaviour
Esempio n. 1
2
 /// <summary>
 /// Create PDF document from given HTML.<br/>
 /// </summary>
 /// <param name="html">HTML source to create PDF from</param>
 /// <param name="pageSize">the page size to use for each page in the generated pdf </param>
 /// <param name="margin">the margin to use between the HTML and the edges of each page</param>
 /// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
 /// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
 /// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
 /// <returns>the generated image of the html</returns>
 public static PdfDocument GeneratePdf(string html, PageSize pageSize, int margin = 20, CssData cssData = null, EventHandler<HtmlStylesheetLoadEventArgs> stylesheetLoad = null, EventHandler<HtmlImageLoadEventArgs> imageLoad = null)
 {
     var config = new PdfGenerateConfig();
     config.PageSize = pageSize;
     config.SetMargins(margin);
     return GeneratePdf(html, config, cssData, stylesheetLoad, imageLoad);
 }
 public CusCtlTellPanelChar(Liplis.MainSystem.Liplis lips, ObjSetting os, string url, string title, string discription, int newsEmotion, int newsPoint, Bitmap charBody, EventHandler enter, IContainer components)
 {
     this.lips = lips;
     this.os = os;
     initCms(components);
     initDataPanelNonThum(url, title, discription, newsEmotion, newsPoint, charBody, enter);
 }
Esempio n. 3
1
        /// <summary>
        /// Create a new game screen. Should be done every time there is a new game.
        /// </summary>
        /// <param name="theScreenEvent"></param>
        /// <param name="contentManager"></param>
        public GameScreen(EventHandler theScreenEvent,ContentManager contentManager)
            : base(theScreenEvent)
        {
            bScoreWasAdded = false;

            this.contentManager = contentManager;
            dlDoubleJumpTimer = new DanLabel(1150, 20, 100, 50);

            //Init our intrepid hero
            csHero = new ControlledSprite();

            bg = new LayeredBackground();

            djeJumpEffect = new DoubleJumpEffect();

            altimeter = new Altimeter(); // Make a camera for the screen with an altimeter
            cCamera = new Camera(50, 100, 600, 520, altimeter);

            blocks = new List<Sprite>();
            Sprite sp = new Sprite();
            blocks.Add(sp);
            sp = new Sprite();
            blocks.Add(sp);
            sp = new Sprite();
            blocks.Add(sp);
            sp = new Sprite();
            blocks.Add(sp);
            sp = new Sprite();
            blocks.Add(sp);

            // REVIST Set up the Arcing Block Manager with the difficulty
            arcingBlockManager = new ArcingBlockManager(cCamera, blocks, contentManager, 500, 300, 150, "Sprites/block2");
        }
Esempio n. 4
0
        protected override void InitControl()
        {
            base.InitControl();
            BackColor = Color.White;
            Anchor = System.Windows.Forms.AnchorStyles.None;

            lblFolder = new FluidLabel();
            lblFolder.Bounds = new Rectangle(10, 10, 240, 35);
            lblFolder.Font = new Font(FontFamily.GenericSerif, 9, FontStyle.Regular);
            Controls.Add(lblFolder);

            lblFile = new FluidLabel();
            lblFile.Bounds = new Rectangle(10, 40, 240, 20);
            lblFile.Font = new Font(FontFamily.GenericSerif, 9, FontStyle.Bold);
            Controls.Add(lblFile);

            lblSent = new FluidLabel();
            lblSent.Bounds = new Rectangle(10, 65, 180, 20);
            lblSent.Font = new Font(FontFamily.GenericSerif, 9, FontStyle.Regular);
            Controls.Add(lblSent);

            lblRecieved = new FluidLabel();
            lblRecieved.Bounds = new Rectangle(10, 80, 180, 20);
            lblRecieved.Font = new Font(FontFamily.GenericSerif, 9, FontStyle.Regular);
            Controls.Add(lblRecieved);

            UpdateStatus += new EventHandler(OnStatusUpdate);

            OnStatusUpdate(this, null);
        }
        public HtmlToClrEventProxy(object sender, string eventName, EventHandler eventHandler) {
            this.eventHandler = eventHandler;
            this.eventName = eventName;

            Type htmlToClrEventProxyType = typeof(HtmlToClrEventProxy);
            typeIReflectImplementation = htmlToClrEventProxyType as IReflect;
        }
Esempio n. 6
0
        public void GetServices(EventHandler<AsyncWorkerCallbackEventArgs<IList<MediaService>>> callback)
        {
            try
              {
            AsyncWorkerHandle<IList<MediaService>> handle = AsyncWorkerHelper.DoWork<IList<MediaService>>(
              delegate(object sender, DoWorkEventArgs e)
              {
            List<MediaService> services = new List<MediaService>();

            foreach (var item in ServiceProvider.GetServices<IDeviceConnectorService>())
            {
              services.Add(new MediaService()
              {
                Id = item.Value.Uri.ToString(),
                Name = item.Value.Name,
                ContractName = item.Value.Name,
                HostName = item.Value.HostName,
                Uri = item.Value.Uri,
              });
            }

            e.Result = services;
              },
              null, callback);
              }
              catch (Exception ex)
              {
            ExceptionHandler.Handle(ex);
              }
        }
Esempio n. 7
0
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                _nombreDocumento = this.toolStripTextBox1.Text;
                //leemos el documento
                _procesador = new XBRLProcesadorProveedor(new Uri(_nombreDocumento));
                //le decimos al componente que tenemos las clases generadas
                _procesador.OptimizarEnsamblado(System.Reflection.Assembly.GetExecutingAssembly());
                //procesamos el documento
                _procesador.Procesar();
                //obtenemos las instancias
                IXBRLContenedorInstanciasObjetos contenedor = _procesador.ContenedorInstanciasConceptos;

                this.conceptosMenu.DropDownItems.Clear();
                //obtenemos los conceptos existentes en las instancias
                foreach (string nombreConcepto in contenedor.Conceptos)
                {
                    //por cada concepto creamos un submenu
                    EventHandler manejadorEvento = new EventHandler(pulsameToolStripMenuItem_Click);
                    this.conceptosMenu.DropDownItems.Add(nombreConcepto, null, manejadorEvento);
                }
            }
            catch { }
        }
Esempio n. 8
0
        internal static void ToggleFindToolBar(Decorator findToolBarHost, EventHandler handlerFindClicked, bool enable)
        {
            if (enable)
            {
                // Create FindToolBar and attach it to the host.
                FindToolBar findToolBar = new FindToolBar();
                findToolBarHost.Child = findToolBar;
                findToolBarHost.Visibility = Visibility.Visible;
                KeyboardNavigation.SetTabNavigation(findToolBarHost, KeyboardNavigationMode.Continue);
                FocusManager.SetIsFocusScope(findToolBarHost, true);

                // Initialize FindToolBar
                findToolBar.SetResourceReference(Control.StyleProperty, FindToolBarStyleKey);
                findToolBar.FindClicked += handlerFindClicked;
                findToolBar.DocumentLoaded = true;
                findToolBar.GoToTextBox();
            }
            else
            {
                // Reset FindToolBar state to its initial state.
                FindToolBar findToolBar = findToolBarHost.Child as FindToolBar;
                findToolBar.FindClicked -= handlerFindClicked;
                findToolBar.DocumentLoaded = false;

                // Remov FindToolBar form its host.
                findToolBarHost.Child = null;
                findToolBarHost.Visibility = Visibility.Collapsed;
                KeyboardNavigation.SetTabNavigation(findToolBarHost, KeyboardNavigationMode.None);
                findToolBarHost.ClearValue(FocusManager.IsFocusScopeProperty);
            }
        }
Esempio n. 9
0
        public UICommand(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
            ClickForwarderDelegate = new EventHandler(ClickForwarder);
        }
Esempio n. 10
0
        internal AnimationLayer(AnimationStorage ownerStorage)
        {
            Debug.Assert(ownerStorage != null);

            _ownerStorage = ownerStorage;
            _removeRequestedHandler = new EventHandler(OnRemoveRequested);
        }
 private void RegisterCommand(ToolbarCommand id, EventHandler callback)
 {
     var menuCommandID = new CommandID(PackageConstants.GuidTortoiseGitToolbarCmdSet, (int)id);
     var menuItem = new OleMenuCommand(callback, menuCommandID);
     menuItem.Visible = false;
     _commandService.AddCommand(menuItem);
 }
Esempio n. 12
0
 public AnnoToolsForm()
 {
     InitializeComponent();
     LocalizeUI();
     MouseMode();
     Disposed += new EventHandler(FloatingToolsForm_Disposed);
 }
Esempio n. 13
0
	public MainForm ()
	{
		_checkedListBox = new CheckedListBox ();
		_checkedListBox.Dock = DockStyle.Top;
		_checkedListBox.Font = new Font (_checkedListBox.Font.FontFamily, _checkedListBox.Font.Height + 8);
		_checkedListBox.Height = 120;
		Controls.Add (_checkedListBox);
		// 
		// _threeDCheckBox
		// 
		_threeDCheckBox = new CheckBox ();
		_threeDCheckBox.Checked = _checkedListBox.ThreeDCheckBoxes;
		_threeDCheckBox.FlatStyle = FlatStyle.Flat;
		_threeDCheckBox.Location = new Point (8, 125);
		_threeDCheckBox.Text = "3D checkboxes";
		_threeDCheckBox.CheckedChanged += new EventHandler (ThreeDCheckBox_CheckedChanged);
		Controls.Add (_threeDCheckBox);
		// 
		// MainForm
		// 
		ClientSize = new Size (300, 150);
		Location = new Point (250, 100);
		StartPosition = FormStartPosition.Manual;
		Text = "bug #82100";
		Load += new EventHandler (MainForm_Load);
	}
Esempio n. 14
0
		public Label () :base ()
		{
			// Defaults in the Spec
			autosize = false;
			TabStop = false;
			string_format = new StringFormat();
			string_format.FormatFlags = StringFormatFlags.LineLimit;
			TextAlign = ContentAlignment.TopLeft;
			image = null;
			UseMnemonic = true;
			image_list = null;
			image_align = ContentAlignment.MiddleCenter;
			SetUseMnemonic (UseMnemonic);
			flat_style = FlatStyle.Standard;

			SetStyle (ControlStyles.Selectable, false);
			SetStyle (ControlStyles.ResizeRedraw | 
				ControlStyles.UserPaint | 
				ControlStyles.AllPaintingInWmPaint |
				ControlStyles.SupportsTransparentBackColor
				| ControlStyles.OptimizedDoubleBuffer
				, true);
			
			HandleCreated += new EventHandler (OnHandleCreatedLB);
		}
Esempio n. 15
0
 public void AttachEssentailHandlers(
     EventHandler<ImageRequestEventArgs> reqImageHandler,
     EventHandler<TextRequestEventArgs> reqStyleSheetHandler)
 {
     this.requestImage = reqImageHandler;
     this.requestStyleSheet = reqStyleSheetHandler;
 }
Esempio n. 16
0
        public IntWithRandom()
        {
            InitializeComponent();

            if (Core.Language == Language.English)
            {
                drawnas_1.Text = "Range";
                drawnas_2.Text = "Gauss";
            }

            EnableUndo = true;

            this.SuspendLayout();
            Anchor = AnchorStyles.Left | AnchorStyles.Right;
            this.ResumeLayout(false);

            Reading = false;
            Writing = false;

            Reading = true;
            Read();
            Reading = false;

            HandleDestroyed += new EventHandler(IntWithRandom_HandleDestroyed);
        }
Esempio n. 17
0
 /// <summary>
 ///		Initialize new instance.
 /// </summary>
 /// <param name="errorHandler">
 ///		Initial event handler of <see cref="TransportError"/>. This handler may be null.
 /// </param>
 protected EventLoop( EventHandler<RpcTransportErrorEventArgs> errorHandler )
 {
     if ( errorHandler != null )
     {
         this.TransportError += errorHandler;
     }
 }
        /// <summary>
        ///  The provider's constructor sets up the MenuAction objects and the MenuGroup which holds them.
        /// </summary>
        public DataGridMenuProvider()
        {
            // Set up the MenuGroup which holds the MenuAction items.
            MenuGroup dataOperationsGroup = new MenuGroup("DataGroup", "DataGrid");

            isDatasourceSetMenuAction = new MenuAction("You need to set ItemsSource to enable some column operations.");

            generateStockColumnsMenuAction = new MenuAction("Generate Columns");
            generateStockColumnsMenuAction.Execute += new EventHandler<MenuActionEventArgs>(GenerateStockColumnsMenuAction_Execute);

            addColumnsMenuAction = new MenuAction("Add/Edit Columns...");
            addColumnsMenuAction.Execute += new EventHandler<MenuActionEventArgs>(AddColumnsMenuAction_Execute);

            removeColumnsMenuAction = new MenuAction("Remove Columns");
            removeColumnsMenuAction.Execute += new EventHandler<MenuActionEventArgs>(RemoveColumnsMenuAction_Execute);

            dataOperationsGroup.HasDropDown = true;
            dataOperationsGroup.Items.Add(isDatasourceSetMenuAction);
            dataOperationsGroup.Items.Add(generateStockColumnsMenuAction);
            dataOperationsGroup.Items.Add(addColumnsMenuAction);
            dataOperationsGroup.Items.Add(removeColumnsMenuAction);

            this.Items.Add(dataOperationsGroup);        // Can have groups - show up as sub menus
            
            // The UpdateItemStatus event is raised immediately before 
            // the menu show, which provides the opportunity to set states.
            UpdateItemStatus += new EventHandler<MenuActionEventArgs>(DataGridMenuProvider_UpdateItemStatus);
        }
Esempio n. 19
0
        public void CanExecuteChangedTest()
        {
            var command = new RelayCommand(() =>
            {
            },
                                           () => true);

            var canExecuteChangedCalled = 0;

            var canExecuteChangedEventHandler = new EventHandler((s, e) => canExecuteChangedCalled++);

            command.CanExecuteChanged += canExecuteChangedEventHandler;

            command.RaiseCanExecuteChanged(true);

#if SILVERLIGHT
            Assert.AreEqual(1, canExecuteChangedCalled);
#else
            // In WPF, cannot trigger the CanExecuteChanged event like this
            Assert.AreEqual(0, canExecuteChangedCalled);
#endif

            command.CanExecuteChanged -= canExecuteChangedEventHandler;
            command.RaiseCanExecuteChanged(true);

#if SILVERLIGHT
            Assert.AreEqual(1, canExecuteChangedCalled);
#else
            // In WPF, cannot trigger the CanExecuteChanged event like this
            Assert.AreEqual(0, canExecuteChangedCalled);
#endif
        }
Esempio n. 20
0
        public void Intercept(IInvocation invocation)
        {
            switch (invocation.Method.Name)
              {
            case "Close":
              _closedSubscribers(invocation.InvocationTarget, EventArgs.Empty);
              _closedSubscribers = delegate { };
              break;
            case "add_Closed":
              {
            var propertyChangedEventHandler = (EventHandler) invocation.Arguments[0];
            _closedSubscribers += propertyChangedEventHandler;
              }
              break;
            case "remove_Closed":
              {
            var propertyChangedEventHandler = (EventHandler) invocation.Arguments[0];
            _closedSubscribers -= propertyChangedEventHandler;
              }
              break;
              }

              if (invocation.TargetType != null)
            invocation.Proceed();
        }
Esempio n. 21
0
	public MainForm ()
	{
		// 
		// _richTextBox
		// 
		_richTextBox = new RichTextBox ();
		_richTextBox.Dock = DockStyle.Top;
		_richTextBox.Height = 160;
		Controls.Add (_richTextBox);
		// 
		// _wordWrapCheckBox
		// 
		_wordWrapCheckBox = new CheckBox ();
		_wordWrapCheckBox.Checked = _richTextBox.WordWrap;
		_wordWrapCheckBox.Location = new Point (8, 170);
		_wordWrapCheckBox.Text = "WordWrap";
		_wordWrapCheckBox.CheckedChanged += new EventHandler (WordWrapCheckBox_CheckedChanged);
		Controls.Add (_wordWrapCheckBox);
		// 
		// MainForm
		// 
		ClientSize = new Size (300, 200);
		Location = new Point (250, 100);
		StartPosition = FormStartPosition.Manual;
		Text = "bug #81488";
		Load += new EventHandler (MainForm_Load);
	}
        /// <summary>
        /// Starts an animation to a particular value on the specified dependency property.
        /// You can pass in an event handler to call when the animation has completed.
        /// </summary>
        public static void StartAnimation(UIElement animatableElement, DependencyProperty dependencyProperty, double toValue, double animationDurationSeconds, EventHandler completedEvent)
        {
            double fromValue = (double)animatableElement.GetValue(dependencyProperty);

            DoubleAnimation animation = new DoubleAnimation();
            animation.From = fromValue;
            animation.To = toValue;
            animation.Duration = TimeSpan.FromSeconds(animationDurationSeconds);

            animation.Completed += delegate(object sender, EventArgs e)
            {
                //
                // When the animation has completed bake final value of the animation
                // into the property.
                //
                animatableElement.SetValue(dependencyProperty, animatableElement.GetValue(dependencyProperty));
                CancelAnimation(animatableElement, dependencyProperty);

                if (completedEvent != null)
                {
                    completedEvent(sender, e);
                }
            };

            animation.Freeze();

            animatableElement.BeginAnimation(dependencyProperty, animation);
        }
Esempio n. 23
0
        public CodeEditBox()
        {
            this.LoadDefaultProperties();
            InitializeComponent();

            textChanged = new EventHandler<TextChangedEventArgs>(OnTextChanged);
            rowsChanged = new EventHandler(OnRowsChanged);

            autoCompiler.GotFocus += (s, e) => { Focus(); };
            autoCompiler.MouseDown += AutoCompiler_MouseDown;
            autoCompiler.Visible = false;

            SetStyle(ControlStyles.Selectable, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);

            PropertyJoin.ChangedPropertyEvent(this, new string[] {
                "SyntaxHighlighter",
                "CommentChar",
                "PrefixChar"
            }, UpdateSyntax);

            AddRow(new Row(this));
            ClearHistory();
            Zoom = 1;
        }
Esempio n. 24
0
 public MainPage()
 {
     this.Unloaded += new RoutedEventHandler(MainPage_Unloaded);
     BindingValidationError += new EventHandler<ValidationErrorEventArgs>(MainPage_BindingValidationError);
     // Required to initialize variables
     InitializeComponent();
 }
Esempio n. 25
0
        internal InteractiveEvaluator(
            IContentType contentType,
            HostServices hostServices,
            IViewClassifierAggregatorService classifierAggregator,
            IInteractiveWindowCommandsFactory commandsFactory,
            ImmutableArray<IInteractiveWindowCommand> commands,
            string responseFilePath,
            string initialWorkingDirectory,
            string interactiveHostPath,
            Type replType)
        {
            Debug.Assert(responseFilePath == null || PathUtilities.IsAbsolute(responseFilePath));

            _contentType = contentType;
            _responseFilePath = responseFilePath;
            _workspace = new InteractiveWorkspace(this, hostServices);
            _contentTypeChangedHandler = new EventHandler<ContentTypeChangedEventArgs>(LanguageBufferContentTypeChanged);
            _classifierAggregator = classifierAggregator;
            _initialWorkingDirectory = initialWorkingDirectory;
            _commandsFactory = commandsFactory;
            _commands = commands;

            var hostPath = interactiveHostPath;
            _interactiveHost = new InteractiveHost(replType, hostPath, initialWorkingDirectory);
            _interactiveHost.ProcessStarting += ProcessStarting;
        }
        public MainWindow()
        {
            InitializeComponent();

            Reporter = this;

            TestingElement.BubblingTestEvent.GetEventTracer().EventRaising += EventTracer_EventRaising;
            TestingElement.BubblingTestEvent.GetEventTracer().EventRaised += EventTracer_EventRaised;
            TestingElement.TunnelingTestEvent.GetEventTracer().EventRaising += EventTracer_EventRaising;
            TestingElement.TunnelingTestEvent.GetEventTracer().EventRaised += EventTracer_EventRaised;
            TestingElement.ChildrenTestEvent.GetEventTracer().EventRaising += EventTracer_EventRaising;
            TestingElement.ChildrenTestEvent.GetEventTracer().EventRaised += EventTracer_EventRaised;
            TestingElement.DescendentsTestEvent.GetEventTracer().EventRaising += EventTracer_EventRaising;
            TestingElement.DescendentsTestEvent.GetEventTracer().EventRaised += EventTracer_EventRaised;
            TestingElement.ParentTestEvent.GetEventTracer().EventRaising += EventTracer_EventRaising;
            TestingElement.ParentTestEvent.GetEventTracer().EventRaised += EventTracer_EventRaised;
            TestingElement.SiblingsTestEvent.GetEventTracer().EventRaising += EventTracer_EventRaising;
            TestingElement.SiblingsTestEvent.GetEventTracer().EventRaised += EventTracer_EventRaised;
            TestingElement.SpreadTestEvent.GetEventTracer().EventRaising += EventTracer_EventRaising;
            TestingElement.SpreadTestEvent.GetEventTracer().EventRaised += EventTracer_EventRaised;

            InitElementOwnerTable();
            InitElements();

            //Location and Size
            Left = Properties.Settings.Default.X;
            Top = Properties.Settings.Default.Y;

            LocationChanged += new EventHandler(MainWindow_LocationChanged);
        }
Esempio n. 27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WindowsFormsMemberToken"/> class.
        /// </summary>
        /// <param name="objectToObserve">The object to observe.</param>
        /// <param name="propertyName">The property path.</param>
        /// <param name="remainingPath">The remaining path.</param>
        /// <param name="callback">The callback.</param>
        /// <param name="pathNavigator">The path navigator.</param>
        public WindowsFormsMemberToken(object objectToObserve, string propertyName, string remainingPath, Action<object, string> callback, IPathNavigator pathNavigator)
            : base(objectToObserve, propertyName, remainingPath, callback, pathNavigator)
        {
            _actualHandler = CurrentTarget_PropertyChanged;

            AcquireTarget(objectToObserve);
        }
Esempio n. 28
0
        public SnapToPixelsImage()
        {
            _sourceDownloaded = new EventHandler(OnSourceDownloaded);
            _sourceFailed = new EventHandler<ExceptionEventArgs>(OnSourceFailed);

            LayoutUpdated += new EventHandler(OnLayoutUpdated);
        }
Esempio n. 29
0
        private Texture2D texturaSelecionado; //  botão em estado selecionado

        #endregion Fields

        #region Constructors

        public clsButton(Game game, Texture2D TexturaNaoSelecionado, Texture2D TexturaSelecionado, Vector2 Posicao, EventHandler evento)
        {
            texturaNaoSelecionado = TexturaNaoSelecionado;
            texturaSelecionado = TexturaSelecionado;
            posicao = Posicao;
            eventoClick = evento;
        }
Esempio n. 30
0
        void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            Logging.Setup();
            Logging.AddToAuthorun();
            ShowInTaskbar = false;
            RegisterHotkey();
            
            _Model = new Model();
            this.DataContext = _Model;
            foreach (string s in Environment.GetCommandLineArgs())
            {
                if (File.Exists(s) && System.IO.Path.GetExtension(s) != ".exe")
                {
                    _Model.Open(s);
                }
            }
            if (!_Model._Loaded) _Model.Load();
            KeyDown += new KeyEventHandler(Window1_KeyDown);
            Closed += new EventHandler(Window1_Closed);
            
            Closing += new System.ComponentModel.CancelEventHandler(Window1_Closing);
            App.Current.Deactivated += new EventHandler(Current_Deactivated);
            _RitchTextBox.Focus();
            _RitchTextBox.TextChanged += new TextChangedEventHandler(RitchTextBox_TextChanged);

            new DispatcherTimer().StartRepeatMethod(60 * 10, Update);
            this.Show(); 
           
            
        }
Esempio n. 31
0
        private void NewLabirint()
        {
            labParts = new PictureBox[X, Y];

            for (int i = 0; i < X; i++)
            {
                for (int j = 0; j < Y; j++)
                {
                    labParts[i, j] = new PictureBox();

                    int xPos = (i * size) + 220;
                    int yPos = (j * size) + 150;
                    labParts[i, j].SetBounds(xPos, yPos, size, size);

                    if ((i == 0 && j == 0) || (i == 19 && j == 19) || (i == 19 && j == 40) || (i == 0 && j == 21) || (i == 21 && j == 0) || (i == 40 && j == 19) || (i == 21 && j == 21) || (i == X - 1 && j == Y - 1))
                    {
                        labParts[i, j].BackColor = Color.LightGreen;
                    }
                    else if (i == 20 || j == 20)
                    {
                        labParts[i, j].BackColor = Color.ForestGreen;
                    }
                    else
                    {
                        labParts[i, j].BackColor = Color.White;

                        EventHandler clickEvent = new EventHandler(PictureBox_Click);
                        labParts[i, j].Click += clickEvent;
                    }
                    /*2*/
                    if ((i == 21 && (j == 4 || j == 5 || j == 7 || j == 8 || j == 9 || j == 15)) ||
                        (i == 22 && (j == 2 || j == 5 || j == 7 || j == 9 || j == 10 || j == 12 || j == 13 || j == 14 || j == 15 || j == 17 || j == 18 || j == 19)) ||
                        (i == 23 && (j == 1 || j == 2 || j == 3 || j == 14 || j == 17 || j == 19)) ||
                        (i == 24 && (j == 1 || j == 6 || j == 7 || j == 9 || j == 11 || j == 13 || j == 14 || j == 16 || j == 17 || j == 19)) ||
                        (i == 25 && (j == 1 || j == 3 || j == 4 || j == 7 || j == 9 || j == 11 || j == 13 || j == 17 || j == 19)) ||
                        (i == 26 && (j == 1 || j == 3 || j == 4 || j == 5 || j == 9 || j == 11 || j == 13 || j == 15 || j == 16 || j == 17 || j == 19)) ||
                        (i == 27 && (j == 0 || j == 7 || j == 8 || j == 9 || j == 11 || j == 13 || j == 15 || j == 17 || j == 19)) ||
                        (i == 28 && (j == 0 || j == 1 || j == 2 || j == 3 || j == 4 || j == 6 || j == 7 || j == 11 || j == 13 || j == 15 || j == 17 || j == 19)) ||
                        (i == 29 && (j == 0 || j == 1 || j == 2 || j == 3 || j == 9 || j == 10 || j == 11 || j == 13 || j == 19)) ||
                        (i == 30 && (j == 1 || j == 5 || j == 6 || j == 7 || j == 9 || j == 17 || j == 18 || j == 19)) ||
                        (i == 31 && (j == 1 || j == 4 || j == 5 || j == 7 || j == 9 || j == 10 || j == 11 || j == 14 || j == 15 || j == 19)) ||
                        (i == 32 && (j == 3 || j == 4 || j == 7 || j == 9 || j == 13 || j == 15 || j == 16)) ||
                        (i == 33 && (j == 2 || j == 3 || j == 6 || j == 7 || j == 8 || j == 9 || j == 11 || j == 16 || j == 17 || j == 18)) ||
                        (i == 34 && (j == 1 || j == 2 || j == 5 || j == 6 || j == 11 || j == 12 || j == 13 || j == 14)) ||
                        (i == 35 && (j == 4 || j == 5 || j == 6 || j == 9 || j == 14 || j == 15 || j == 17 || j == 18)) ||
                        (i == 36 && (j == 2 || j == 3 || j == 4 || j == 7 || j == 8 || j == 9 || j == 11 || j == 17)) ||
                        (i == 37 && (j == 0 || j == 1 || j == 2 || j == 6 || j == 7 || j == 8 || j == 9 || j == 11 || j == 13 || j == 14 || j == 15 || j == 17)) ||
                        (i == 38 && (j == 0 || j == 4 || j == 5 || j == 6 || j == 7 || j == 8 || j == 9 || j == 11 || j == 13 || j == 15 || j == 17 || j == 18)) ||
                        (i == 39 && (j == 0 || j == 2 || j == 4 || j == 5 || j == 6 || j == 7 || j == 8 || j == 9 || j == 11 || j == 15 || j == 17)) ||
                        (i == 40 && (j == 0 || j == 11 || j == 12 || j == 13 || j == 14 || j == 15 || j == 17)))
                    {
                        labParts[i, j].BackColor = Color.Black;
                    }
                    /*3*/
                    if ((i == 0 && (j == 23 || j == 35 || j == 39 || j == 41)) ||
                        (i == 1 && (j == 23 || j == 35 || j == 39 || j == 41)) ||
                        (i == 2 && (j == 21 || j == 23 || j == 25 || j == 26 || j == 27 || j == 28 || j == 29 || j == 30 || j == 31 || j == 32 || j == 33 || j == 35 || j == 37 || j == 39)) ||
                        (i == 3 && (j == 21 || j == 23 || j == 25 || j == 33 || j == 35 || j == 37 || j == 39)) ||
                        (i == 4 && (j == 21 || j == 23 || j == 25 || j == 27 || j == 28 || j == 29 || j == 30 || j == 31 || j == 33 || j == 35 || j == 37 || j == 39)) ||
                        (i == 5 && (j == 21 || j == 23 || j == 25 || j == 27 || j == 31 || j == 33 || j == 35 || j == 37 || j == 39)) ||
                        (i == 6 && (j == 21 || j == 23 || j == 25 || j == 27 || j == 29 || j == 31 || j == 33 || j == 35 || j == 37 || j == 39)) ||
                        (i == 7 && (j == 21 || j == 23 || j == 25 || j == 27 || j == 28 || j == 29 || j == 31 || j == 33 || j == 35 || j == 37 || j == 39)) ||
                        (i == 8 && (j == 21 || j == 23 || j == 25 || j == 31 || j == 33 || j == 35 || j == 37 || j == 39)) ||
                        (i == 9 && (j == 21 || j == 23 || j == 25 || j == 26 || j == 27 || j == 28 || j == 29 || j == 30 || j == 31 || j == 33 || j == 35 || j == 37 || j == 39)) ||
                        (i == 10 && (j == 21 || j == 35 || j == 37 || j == 39)) ||
                        (i == 11 && (j == 24 || j == 25 || j == 26 || j == 27 || j == 28 || j == 29 || j == 30 || j == 31 || j == 32 || j == 33 || j == 35 || j == 37 || j == 39)) ||
                        (i == 12 && (j == 22 || j == 32 || j == 35 || j == 37 || j == 39)) ||
                        (i == 13 && (j == 22 || j == 24 || j == 25 || j == 26 || j == 27 || j == 28 || j == 29 || j == 30 || j == 32 || j == 34 || j == 35 || j == 37 || j == 39)) ||
                        (i == 14 && (j == 22 || j == 25 || j == 30 || j == 32 || j == 34 || j == 37 || j == 39)) ||
                        (i == 15 && (j == 22 || j == 24 || j == 26 || j == 27 || j == 28 || j == 30 || j == 32 || j == 34 || j == 36 || j == 37 || j == 39)) ||
                        (i == 16 && (j == 22 || j == 24 || j == 25 || j == 26 || j == 27 || j == 28 || j == 30 || j == 32 || j == 34 || j == 36 || j == 39)) ||
                        (i == 17 && (j == 22 || j == 30 || j == 32 || j == 34 || j == 36 || j == 38)) ||
                        (i == 18 && (j == 22 || j == 23 || j == 24 || j == 25 || j == 26 || j == 27 || j == 28 || j == 29 || j == 30 || j == 32 || j == 34 || j == 36 || j == 38)) ||
                        (i == 19 && (j == 31 || j == 36)))
                    {
                        labParts[i, j].BackColor = Color.Black;
                    }
                    /*4*/
                    if ((i == 21 && (j == 24 || j == 25 || j == 30 || j == 31 || j == 33 || j == 34 || j == 35 || j == 36 || j == 37 || j == 38 || j == 39 || j == 40)) ||
                        (i == 22 && (j == 21 || j == 22 || j == 24 || j == 25 || j == 27 || j == 28 || j == 30 || j == 31 || j == 33 || j == 34 || j == 35 || j == 36 || j == 37 || j == 38 || j == 40)) ||
                        (i == 23 && (j == 21 || j == 22 || j == 27 || j == 28 || j == 37 || j == 38 || j == 40)) ||
                        (i == 24 && (j == 25 || j == 26 || j == 30 || j == 31 || j == 32 || j == 33 || j == 34 || j == 36 || j == 37 || j == 38 || j == 40)) ||
                        (i == 25 && (j == 22 || j == 23 || j == 25 || j == 26 || j == 30 || j == 31 || j == 32 || j == 33 || j == 34 || j == 36 || j == 37 || j == 38 || j == 40)) ||
                        (i == 26 && (j == 22 || j == 23 || j == 27 || j == 28 || j == 30 || j == 31 || j == 32 || j == 33 || j == 34 || j == 36 || j == 37 || j == 38 || j == 40)) ||
                        (i == 27 && (j == 24 || j == 25 || j == 27 || j == 28 || j == 30 || j == 31 || j == 32 || j == 33 || j == 34 || j == 36 || j == 37 || j == 38 || j == 40)) ||
                        (i == 28 && (j == 21 || j == 22 || j == 24 || j == 25 || j == 30 || j == 31 || j == 32 || j == 3 || j == 34 || j == 36 || j == 37 || j == 38 || j == 40)) ||
                        (i == 29 && (j == 21 || j == 22 || j == 23 || j == 27 || j == 28 || j == 33 || j == 34 || j == 40)) ||
                        (i == 30 && (j == 23 || j == 25 || j == 27 || j == 28 || j == 30 || j == 31 || j == 34 || j == 39 || j == 40)) ||
                        (i == 31 && (j == 21 || j == 25 || j == 27 || j == 30 || j == 31 || j == 35 || j == 36 || j == 38 || j == 39 || j == 40)) ||
                        (i == 32 && (j == 21 || j == 23 || j == 24 || j == 27 || j == 30 || j == 32 || j == 31 || j == 33 || j == 35 || j == 36 || j == 38 || j == 39)) ||
                        (i == 33 && (j == 21 || j == 23 || j == 24 || j == 26 || j == 30 || j == 31 || j == 32 || j == 33 || j == 35 || j == 36 || j == 39)) ||
                        (i == 34 && (j == 21 || j == 22 || j == 26 || j == 31 || j == 32 || j == 35 || j == 36 || j == 37 || j == 39)) ||
                        (i == 35 && (j == 21 || j == 22 || j == 24 || j == 25 || j == 29 || j == 35 || j == 36 || j == 37 || j == 39)) ||
                        (i == 36 && (j == 22 || j == 24 || j == 25 || j == 29 || j == 30 || j == 31 || j == 32 || j == 33 || j == 37)) ||
                        (i == 37 && (j == 23 || j == 29 || j == 30 || j == 31 || j == 32 || j == 33 || j == 34 || j == 36 || j == 37 || j == 38 || j == 39)) ||
                        (i == 38 && (j == 22 || j == 23 || j == 25 || j == 26 || j == 36 || j == 37 || j == 38 || j == 39)) ||
                        (i == 39 && (j == 25 || j == 26 || j == 28 || j == 29 || j == 30 || j == 31 || j == 32 || j == 33 || j == 34 || j == 36 || j == 37 || j == 38 || j == 39)) ||
                        (i == 40 && (j == 22 || j == 23 || j == 24 || j == 36 || j == 37 || j == 38 || j == 39)))
                    {
                        labParts[i, j].BackColor = Color.Black;
                    }



                    this.Controls.Add(labParts[i, j]);
                }
            }
        }
Esempio n. 32
0
 /// <summary>
 /// 取消订阅事件处理函数。
 /// </summary>
 /// <param name="id">事件类型编号。</param>
 /// <param name="handler">要取消订阅的事件处理函数。</param>
 public void Unsubscribe(int id, EventHandler <GameEventArgs> handler)
 {
     mEventPool.Unsubscribe(id, handler);
 }
 public EventFireCounter(Action <EventHandler> subscribe, Action <EventHandler> unsubscribe)
 {
     this.unsubscribe = unsubscribe;
     handler          = new EventHandler(OnEvent);
     subscribe(OnEvent);
 }
Esempio n. 34
0
        private static OleMenuCommand CreateMenuCommand([NotNull] IMenuCommandService mcs, int cmdId, [CanBeNull] EventHandler invokeHandler)
        {
            Contract.Requires(mcs != null);
            Contract.Ensures(Contract.Result <OleMenuCommand>() != null);

            var menuCommandId = new CommandID(GuidList.guidResXManager_VSIXCmdSet, cmdId);
            var menuCommand   = new OleMenuCommand(invokeHandler, menuCommandId);

            mcs.AddCommand(menuCommand);
            return(menuCommand);
        }
Esempio n. 35
0
        void InvokeAsync(string method, EventHandler <ResultEventArgs> completedEvent, object userState, object[] args)
        {
            var invokeUserState = new InvokeUserState(userState, completedEvent);

            InvokeAsync(method, args, OnAsyncOperationCompleted, invokeUserState);
        }
Esempio n. 36
0
 public InvokeUserState(object userState, EventHandler <ResultEventArgs> handler)
 {
     UserState = userState;
     Handler   = handler;
 }
Esempio n. 37
0
        /// <summary>
        /// Begins asynchronous progress display in the progress bar</summary>
        /// <param name="message">Message to display with progress meter</param>
        /// <param name="argument">Worker argument</param>
        /// <param name="workHandler">Background thread delegate</param>
        /// <param name="progressCompleteHandler">Event handler for work completion event</param>
        /// <param name="autoIncrement">Whether to auto increment the progress meter</param>
        public void RunProgressInStatusBarAsync(string message, object argument, DoWorkEventHandler workHandler, EventHandler <ProgressCompleteEventArgs> progressCompleteHandler, bool autoIncrement)
        {
            var statusItem = new ProgressViewModel()
            {
                Cancellable     = false,
                Description     = message,
                IsIndeterminate = autoIncrement
            };

            // Add the part to the status bar
            ComposablePart part = m_composer.AddPart(statusItem);

            statusItem.Tag = new StatusBarProgressContext(progressCompleteHandler, part);

            statusItem.RunWorkerThread(argument, workHandler);
            statusItem.RunWorkerCompleted += statusItem_RunWorkerCompleted;
        }
Esempio n. 38
0
 public CheckRole()
 {
     InitializeComponent();
     Load += new EventHandler(Form1_Load);
 }
Esempio n. 39
0
        // Инициализация DataGridView для работы с массивами (различные настройки и обработчики событий);
        // при добавление кнопок управления кол-вом строк и столбцов уменьшает размеры DataGridView
        public static void InitGridForArr(DataGridView dgv,
                                          int defaultColWidth, bool readOnly,
                                          bool showRowsIndexes, bool showColsIndexes,
                                          bool changeRowsCountButtons, bool changeColsCountButtons,
                                          bool square,
                                          int changeButtonsSize = 22, int changeButtonsMargin = 6)
        {
            List <Button> buttons = new List <Button>();

            int shiftSize = changeButtonsSize + changeButtonsMargin;

            if (changeRowsCountButtons)
            {
                // -
                Button minusButton = new Button {
                    Width  = changeButtonsSize,
                    Height = changeButtonsSize,
                    Left   = dgv.Left,
                    Top    = dgv.Top + (changeColsCountButtons ? shiftSize : 0),
                    Text   = "\u2014", // длинное тире (один символ Unicode с кодом 0x2014)
                    Parent = dgv.Parent,
                    Name   = dgv.Name + "_MinusRowButton",
                };
                if (square)
                {
                    minusButton.Click += (sender, e) =>
                    {
                        if (dgv.RowCount > 1)
                        {
                            dgv.ColumnCount--;
                            dgv.RowCount--;
                        }
                    }
                }
                ;
                else
                {
                    minusButton.Click += (sender, e) => {
                        if (dgv.RowCount > 1)
                        {
                            dgv.RowCount--;
                        }
                    }
                };

                buttons.Add(minusButton);
                // +
                Button plusButton = new Button {
                    Width  = changeButtonsSize,
                    Height = changeButtonsSize,
                    Left   = minusButton.Left,
                    Top    = minusButton.Top + shiftSize,
                    Text   = "+",
                    Parent = dgv.Parent,
                    Name   = dgv.Name + "_PlusRowButton",
                };
                if (square)
                {
                    plusButton.Click += (sender, e) => {
                        dgv.RowCount++;
                        dgv.ColumnCount++;
                    }
                }
                ;
                else
                {
                    plusButton.Click += (sender, e) =>
                    {
                        dgv.RowCount++;
                    }
                };
                buttons.Add(plusButton);

                // уменьшение размера и сдвиг грида
                dgv.Width -= shiftSize;
                dgv.Left  += shiftSize;
            }
            if (changeColsCountButtons)
            {
                // -
                Button minusButton = new Button {
                    Width  = changeButtonsSize,
                    Height = changeButtonsSize,
                    Left   = dgv.Left,
                    Top    = dgv.Top,
                    Text   = "\u2014", // длинное тире (один символ Unicode с кодом 0x2014)
                    Parent = dgv.Parent,
                    Name   = dgv.Name + "_MinusColButton",
                };
                if (square)
                {
                    minusButton.Click += (sender, e) => {
                        if (dgv.ColumnCount > 1)
                        {
                            dgv.ColumnCount--;
                            dgv.RowCount--;
                        }
                    }
                }
                ;
                else
                {
                    minusButton.Click += (sender, e) => {
                        if (dgv.ColumnCount > 1)
                        {
                            dgv.ColumnCount--;
                        }
                    }
                };

                buttons.Add(minusButton);
                // +
                Button plusButton = new Button {
                    Width  = changeButtonsSize,
                    Height = changeButtonsSize,
                    Left   = minusButton.Left + shiftSize,
                    Top    = minusButton.Top,
                    Text   = "+",
                    Parent = dgv.Parent,
                    Name   = dgv.Name + "_PlusColButton",
                };
                if (square)
                {
                    plusButton.Click += (sender, e) => {
                        dgv.ColumnCount++;
                        dgv.RowCount++;
                    }
                }
                ;
                else
                {
                    plusButton.Click += (sender, e) => {
                        dgv.ColumnCount++;
                    }
                };
                buttons.Add(plusButton);

                // уменьшение размера грида и сдвиг кнопок
                dgv.Height -= minusButton.Height + changeButtonsMargin;
                dgv.Top    += minusButton.Height + changeButtonsMargin;
            }

            // запрет добавления новых строк
            dgv.AllowUserToAddRows = false;
            // запрет удаления строк
            dgv.AllowUserToDeleteRows = false;
            // запрет менять столбцы местами
            dgv.AllowUserToOrderColumns = false;
            // запрет изменять ширину столбцов
            dgv.AllowUserToResizeColumns = false;
            // запрет изменять ширину строк
            dgv.AllowUserToResizeRows = false;
            // запрет менять ширину заголовка строк (серые ячейки)
            dgv.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            // запрет менять ширину заголовка столбцов (серые ячейки)
            dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;

            // разрешаем прокрутку содержимого (на всякий случай)
            dgv.ScrollBars = ScrollBars.Both;

            // установить ширину заголовка строк в 65 пикселей
            dgv.RowHeadersWidth = defaultColWidth;
            // установить высоту заголовка столбцов равной высоте строки по умолчанию
            dgv.ColumnHeadersHeight = dgv.RowTemplate.Height;

            dgv.RowHeadersVisible    = showRowsIndexes;
            dgv.ColumnHeadersVisible = showColsIndexes;
            dgv.ReadOnly             = readOnly;

            // делегат (анонимный метод), который настраивает строки и столбцы
            // (задает заголовки и, где надо, размеры)
            Action updateHeaders = () => {
                if (showRowsIndexes)
                {
                    for (int r = 0; r < dgv.RowCount; r++)
                    {
                        dgv.Rows[r].HeaderCell.Value = string.Format("[ {0} ]", r);
                    }
                }
                if (showColsIndexes)
                {
                    for (int c = 0; c < dgv.ColumnCount; c++)
                    {
                        DataGridViewColumn column = dgv.Columns[c];
                        column.SortMode         = DataGridViewColumnSortMode.NotSortable;
                        column.HeaderCell.Value = string.Format("[ {0} ]", c);
                    }
                }
            };

            // привязываем обработчик события добавления столбца, чтобы изменять его размер
            dgv.ColumnAdded += (sender, e) => {
                e.Column.Width    = defaultColWidth;
                e.Column.SortMode = DataGridViewColumnSortMode.NotSortable;
                updateHeaders();
            };
            dgv.RowsAdded += (sender, e) => {
                updateHeaders();
            };

            // привязываем обработчик событий, который очищает выделенные ячейки по клавише delete
            dgv.PreviewKeyDown += (sender, e) => {
                if (dgv.Enabled && !dgv.ReadOnly && e.KeyValue == 46)
                {
                    foreach (var cell in dgv.SelectedCells)
                    {
                        ((DataGridViewCell)cell).Value = null;
                    }
                }
            };

            // обработчик событий, который активирует и дективирует кнопки в зависимости от состояния dgv
            EventHandler eh = (sender, e) => {
                foreach (Button b in buttons)
                {
                    b.Enabled = dgv.Enabled && !dgv.ReadOnly;
                }
            };

            // привязываем созданный выше обработчик к событиям изменения свойств Enabled и ReadOnly DataGridView
            dgv.EnabledChanged  += eh;
            dgv.ReadOnlyChanged += eh;
            eh(dgv, EventArgs.Empty);

            // привязываем обработчик событий, который меняет выравнивание в ячейках в зависимости от содержимого
            // (целые числа - выравнивание вправо, иначе - влево)
            dgv.CellValidated += (sender, e) => {
                DataGridViewCell cell = dgv[e.ColumnIndex, e.RowIndex];
                int temp;
                // выравнивание (если конвертится в int - по правому краю, иначе - по левому)
                cell.Style.Alignment =
                    int.TryParse("" + cell.Value, out temp) ? DataGridViewContentAlignment.MiddleRight : DataGridViewContentAlignment.MiddleLeft;
            };

            // привязываем обработчик событий, который нужным образом отрисовывает содержимое ячеек заголовков
            // (чтобы не рисовались всякие стрелки-звездочки и умещался весь текст)
            StringFormat sf = new StringFormat {
                Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center,
            };

            dgv.CellPainting += (sender, e) => {
                if (e.ColumnIndex < 0 || e.RowIndex < 0)
                {
                    e.PaintBackground(e.CellBounds, false);
                    if (e.RowIndex >= 0 || e.ColumnIndex >= 0)
                    {
                        e.Graphics.DrawString(
                            (e.ColumnIndex < 0 ? dgv.Rows[e.RowIndex].HeaderCell.Value : dgv.Columns[e.ColumnIndex].HeaderCell.Value).ToString(),
                            dgv.RowHeadersDefaultCellStyle.Font,
                            new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor),
                            e.CellBounds,
                            sf
                            );
                    }
                    e.Handled = true;
                }
            };

            // установка минимального кол-ва столбцов и строк
            // (обязательно после привязки обработчика события добавления столбца)
            if (dgv.RowCount == 0)
            {
                dgv.RowCount = 3;
            }
        }
Esempio n. 40
0
 /// <summary>
 /// Rawlerのroot用のクラス。
 /// </summary>
 public RawlerRoot()
     : base()
 {
     this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(backgroundWorker_DoWork);
     reportevent = new EventHandler <RawlerLib.Event.EventStringArgs>(r_ReportEvent);
 }
 ToolStripMenuItem Add(string txt, EventHandler onClick)
 {
     return(Add(null, txt, onClick));
 }
Esempio n. 42
0
 public MruMenuItem(String _filename, String entryname, EventHandler eventHandler)
     : base(entryname, eventHandler)
 {
     filename = _filename;
 }
Esempio n. 43
0
        /// <summary>
        ///     Removes an image from the image manager so it is no longer animated.
        /// </summary>
        public static void StopAnimate(Image image, EventHandler onFrameChangedHandler)
        {
            // Make sure we have a list of images
            if (image == null || s_imageInfoList == null)
            {
                return;
            }

            // Acquire a writer lock to modify the image info list - See comments on Animate() about this locking.

            bool readerLockHeld = s_rwImgListLock.IsReaderLockHeld;
            LockCookie lockDowngradeCookie = default;

            t_threadWriterLockWaitCount++;

            try
            {
                if (readerLockHeld)
                {
                    lockDowngradeCookie = s_rwImgListLock.UpgradeToWriterLock(Timeout.Infinite);
                }
                else
                {
                    s_rwImgListLock.AcquireWriterLock(Timeout.Infinite);
                }
            }
            finally
            {
                t_threadWriterLockWaitCount--;
                Debug.Assert(t_threadWriterLockWaitCount >= 0, "threadWriterLockWaitCount less than zero.");
            }

            try
            {
                // Find the corresponding reference and remove it
                for (int i = 0; i < s_imageInfoList.Count; i++)
                {
                    ImageInfo imageInfo = s_imageInfoList[i];

                    if (image == imageInfo.Image)
                    {
                        if ((onFrameChangedHandler == imageInfo.FrameChangedHandler) || (onFrameChangedHandler != null && onFrameChangedHandler.Equals(imageInfo.FrameChangedHandler)))
                        {
                            s_imageInfoList.Remove(imageInfo);
                        }
                        break;
                    }
                }
            }
            finally
            {
                if (readerLockHeld)
                {
                    s_rwImgListLock.DowngradeFromWriterLock(ref lockDowngradeCookie);
                }
                else
                {
                    s_rwImgListLock.ReleaseWriterLock();
                }
            }
        }
Esempio n. 44
0
        private async void App_OnStartup(object sender, StartupEventArgs e)
        {
            try
            {
                Log.Info("Boot strapping the services and UI.");

                //Apply theme
                applyTheme();

                //Define MainViewModel before services so I can setup a delegate to call into the MainViewModel
                //This is to work around the fact that the MainViewModel is created after the services.
                MainViewModel     mainViewModel         = null;
                Action <KeyValue> fireKeySelectionEvent = kv =>
                {
                    if (mainViewModel != null) //Access to modified closure is a good thing here, for once!
                    {
                        mainViewModel.FireKeySelectionEvent(kv);
                    }
                };

                //Create services
                var                          errorNotifyingServices      = new List <INotifyErrors>();
                IAudioService                audioService                = new AudioService();
                IDictionaryService           dictionaryService           = new DictionaryService();
                IPublishService              publishService              = new PublishService();
                ISuggestionStateService      suggestionService           = new SuggestionStateService();
                ICalibrationService          calibrationService          = CreateCalibrationService();
                ICapturingStateManager       capturingStateManager       = new CapturingStateManager(audioService);
                ILastMouseActionStateManager lastMouseActionStateManager = new LastMouseActionStateManager();
                IKeyStateService             keyStateService             = new KeyStateService(suggestionService, capturingStateManager, lastMouseActionStateManager, calibrationService, fireKeySelectionEvent);
                IInputService                inputService                = CreateInputService(keyStateService, dictionaryService, audioService, calibrationService, capturingStateManager, errorNotifyingServices);
                IKeyboardOutputService       keyboardOutputService       = new KeyboardOutputService(keyStateService, suggestionService, publishService, dictionaryService, fireKeySelectionEvent);
                IMouseOutputService          mouseOutputService          = new MouseOutputService(publishService);
                errorNotifyingServices.Add(audioService);
                errorNotifyingServices.Add(dictionaryService);
                errorNotifyingServices.Add(publishService);
                errorNotifyingServices.Add(inputService);

                //Release keys on application exit
                ReleaseKeysOnApplicationExit(keyStateService, publishService);

                //Compose UI
                var mainWindow = new MainWindow(audioService, dictionaryService, inputService);

                Thread.CurrentThread.CurrentCulture   = Settings.Default.Language.ToCultureInfo();
                Thread.CurrentThread.CurrentUICulture = Settings.Default.Language.ToCultureInfo();
                OptiKey.Properties.Resources.Culture  = Settings.Default.Language.ToCultureInfo();

                IWindowManipulationService mainWindowManipulationService = new WindowManipulationService(
                    mainWindow,
                    () => Settings.Default.MainWindowOpacity,
                    () => Settings.Default.MainWindowState,
                    () => Settings.Default.MainWindowPreviousState,
                    () => Settings.Default.MainWindowFloatingSizeAndPosition,
                    () => Settings.Default.MainWindowDockPosition,
                    () => Settings.Default.MainWindowDockSize,
                    () => Settings.Default.MainWindowFullDockThicknessAsPercentageOfScreen,
                    () => Settings.Default.MainWindowCollapsedDockThicknessAsPercentageOfFullDockThickness,
                    () => Settings.Default.MainWindowMinimisedPosition,
                    o => Settings.Default.MainWindowOpacity                               = o,
                    state => Settings.Default.MainWindowState                             = state,
                    state => Settings.Default.MainWindowPreviousState                     = state,
                    rect => Settings.Default.MainWindowFloatingSizeAndPosition            = rect,
                    pos => Settings.Default.MainWindowDockPosition                        = pos,
                    size => Settings.Default.MainWindowDockSize                           = size,
                    t => Settings.Default.MainWindowFullDockThicknessAsPercentageOfScreen = t,
                    t => Settings.Default.MainWindowCollapsedDockThicknessAsPercentageOfFullDockThickness = t);

                errorNotifyingServices.Add(mainWindowManipulationService);

                mainViewModel = new MainViewModel(
                    audioService, calibrationService, dictionaryService, keyStateService,
                    suggestionService, capturingStateManager, lastMouseActionStateManager,
                    inputService, keyboardOutputService, mouseOutputService, mainWindowManipulationService, errorNotifyingServices);

                mainWindow.MainView.DataContext = mainViewModel;

                //Setup actions to take once main view is loaded (i.e. the view is ready, so hook up the services which kicks everything off)
                Action postMainViewLoaded = mainViewModel.AttachServiceEventHandlers;
                if (mainWindow.MainView.IsLoaded)
                {
                    postMainViewLoaded();
                }
                else
                {
                    RoutedEventHandler loadedHandler = null;
                    loadedHandler = (s, a) =>
                    {
                        postMainViewLoaded();
                        mainWindow.MainView.Loaded -= loadedHandler; //Ensure this handler only triggers once
                    };
                    mainWindow.MainView.Loaded += loadedHandler;
                }

                //Show the main window
                mainWindow.Show();

                //Display splash screen and check for updates (and display message) after the window has been sized and positioned for the 1st time
                EventHandler sizeAndPositionInitialised = null;
                sizeAndPositionInitialised = async(_, __) =>
                {
                    mainWindowManipulationService.SizeAndPositionInitialised -= sizeAndPositionInitialised; //Ensure this handler only triggers once
                    await ShowSplashScreen(inputService, audioService, mainViewModel);

                    inputService.RequestResume(); //Start the input service
                    await CheckForUpdates(inputService, audioService, mainViewModel);
                };
                if (mainWindowManipulationService.SizeAndPositionIsInitialised)
                {
                    sizeAndPositionInitialised(null, null);
                }
                else
                {
                    mainWindowManipulationService.SizeAndPositionInitialised += sizeAndPositionInitialised;
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error starting up application", ex);
                throw;
            }
        }
Esempio n. 45
0
        public static void Main(string[] args)
        {
            FunctionsContainer funcList = new FunctionsContainer(); // Creating the mission conatiner

            funcList["Double"] = val => val * 2;                    // Double the Value
            funcList["Triple"] = val => val * 3;                    // Triple the Value
            funcList["Square"] = val => val * val;                  // Square the Value
            funcList["Sqrt"]   = val => Math.Sqrt(val);             // Taking the square root
            funcList["Plus2"]  = val => val + 2;                    // Double the Value

            PrintAvailableFunctions(funcList);

            // This handler will output the screen every mission that was activated and it's value
            EventHandler <double> LogHandler = (sender, val) =>
            {
                IMission mission = sender as IMission;

                if (mission != null)
                {
                    Console.WriteLine($"Mission of Type: {mission.Type} with the Name {mission.Name} returned {val}");
                }
            };

            EventHandler <double> SqrtHandler = (sender, val) =>
            {
                // This function will Create a sqrt mission and will continue to sqrt until a number less than 2
                SingleMission sqrtMission = new SingleMission(funcList["Sqrt"], "SqrtMission");

                double newVal;
                do
                {
                    newVal = sqrtMission.Calculate(val);     // getting the new Val
                    Console.WriteLine($"sqrt({val}) = {newVal}");

                    val = newVal;                           // Storing the new Val;
                } while (val > 2);
                Console.WriteLine("----------------------------------------");
            };

            ComposedMission mission1 = new ComposedMission("mission1")
                                       .Add(funcList["Square"])
                                       .Add(funcList["Sqrt"]);

            ComposedMission mission2 = new ComposedMission("mission2")
                                       .Add(funcList["Triple"])
                                       .Add(funcList["Plus2"])
                                       .Add(funcList["Square"]);

            SingleMission mission3 = new SingleMission(funcList["Double"], "mission3");

            ComposedMission mission4 = new ComposedMission("mission4")
                                       .Add(funcList["Triple"])
                                       .Add(funcList["Stam"]) // Notice that this function does not exist and still it works
                                       .Add(funcList["Plus2"]);

            PrintAvailableFunctions(funcList);

            funcList["Stam"] = val => val + 100;
            SingleMission mission5 = new SingleMission(funcList["Stam"], "mission5");

            var missionList = new List <IMission>()
            {
                mission1, mission2, mission3, mission4, mission5
            };

            foreach (var m in missionList)
            {
                m.OnCalculate += LogHandler;
                m.OnCalculate += SqrtHandler;
            }

            missionList.Add(mission2);
            missionList.Add(mission1);
            missionList.Add(mission3);
            missionList.Add(mission5);

            RunMissions(missionList, 100);
            RunMissions(missionList, 2);

            PrintAvailableFunctions(funcList);
        }
Esempio n. 46
0
 private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
Esempio n. 47
0
 /// <summary>
 /// Unsubscribe from the PortletChanged event.
 /// </summary>
 public static void Unsubscribe(EventHandler <EventArgs <string> > eventHandler)
 {
     lock (EventSync)
         Providers.Instance.CacheProvider.Events.PortletChanged.Unsubscribe(eventHandler);
 }
Esempio n. 48
0
        /// <summary>
        ///     Adds an image to the image manager.  If the image does not support animation this method does nothing.
        ///     This method creates the image list and spawns the animation thread the first time it is called.
        /// </summary>
        public static void Animate(Image image, EventHandler onFrameChangedHandler)
        {
            if (image == null)
            {
                return;
            }

            ImageInfo? imageInfo = null;

            // See comment in the class header about locking the image ref.
            lock (image)
            {
                // could we avoid creating an ImageInfo object if FrameCount == 1 ?
                imageInfo = new ImageInfo(image);
            }

            // If the image is already animating, stop animating it
            StopAnimate(image, onFrameChangedHandler);

            // Acquire a writer lock to modify the image info list.  If the thread has a reader lock we need to upgrade
            // it to a writer lock; acquiring a reader lock in this case would block the thread on itself.
            // If the thread already has a writer lock its ref count will be incremented w/o placing the request in the
            // writer queue.  See ReaderWriterLock.AcquireWriterLock method in the MSDN.

            bool readerLockHeld = s_rwImgListLock.IsReaderLockHeld;
            LockCookie lockDowngradeCookie = default;

            t_threadWriterLockWaitCount++;

            try
            {
                if (readerLockHeld)
                {
                    lockDowngradeCookie = s_rwImgListLock.UpgradeToWriterLock(Timeout.Infinite);
                }
                else
                {
                    s_rwImgListLock.AcquireWriterLock(Timeout.Infinite);
                }
            }
            finally
            {
                t_threadWriterLockWaitCount--;
                Debug.Assert(t_threadWriterLockWaitCount >= 0, "threadWriterLockWaitCount less than zero.");
            }

            try
            {
                if (imageInfo.Animated)
                {
                    // Construct the image array
                    //
                    if (s_imageInfoList == null)
                    {
                        s_imageInfoList = new List<ImageInfo>();
                    }

                    // Add the new image
                    //
                    imageInfo.FrameChangedHandler = onFrameChangedHandler;
                    s_imageInfoList.Add(imageInfo);

                    // Construct a new timer thread if we haven't already
                    //
                    if (s_animationThread == null)
                    {
                        s_animationThread = new Thread(new ThreadStart(AnimateImages));
                        s_animationThread.Name = nameof(ImageAnimator);
                        s_animationThread.IsBackground = true;
                        s_animationThread.Start();
                    }
                }
            }
            finally
            {
                if (readerLockHeld)
                {
                    s_rwImgListLock.DowngradeFromWriterLock(ref lockDowngradeCookie);
                }
                else
                {
                    s_rwImgListLock.ReleaseWriterLock();
                }
            }
        }
Esempio n. 49
0
 public void CreateShipTypePayType(ShipTypePayTypeInfoVM _viewInfo, EventHandler<RestClientEventArgs<dynamic>> callback)
 {
     string relativeUrl = "/CommonService/ShipTypePayType/Create";
     var msg = _viewInfo.ConvertVM<ShipTypePayTypeInfoVM, ShipTypePayTypeInfo>();
     restClient.Create(relativeUrl, msg, callback);
 }
Esempio n. 50
0
 private MenuItem CreateMenuItem(string text, EventHandler click)
 {
     return(new MenuItem(I18N.GetString(text), click));
 }
        public DashWidgetView(DashSquare square)
        {
            RelativeLayout layout = new RelativeLayout();

            var tapGestureRecognizer = new TapGestureRecognizer();

            tapGestureRecognizer.Tapped += (s, e) => {
                EventHandler <WidgetTappedEventArgs> handler = Tapped;

                if (handler != null)
                {
                    handler(this, new WidgetTappedEventArgs(square.NavigateType));
                }
            };
            layout.GestureRecognizers.Add(tapGestureRecognizer);

            var backgroundImage = new Image()
            {
                Source = new FileImageSource()
                {
                    File = square.BackgroundImage
                },
                Aspect           = Aspect.AspectFill,
                InputTransparent = false
            };

            layout.Children.Add(backgroundImage,
                                Constraint.Constant(0),
                                Constraint.Constant(0),
                                Constraint.RelativeToParent((parent) => {
                return(parent.Width);
            }),
                                Constraint.RelativeToParent((parent) => {
                return(parent.Height);
            }));

            var iconImage = new Image()
            {
                Source = new FileImageSource()
                {
                    File = square.IconImage
                },
                InputTransparent = true
            };

            layout.Children.Add(
                iconImage,
                Constraint.RelativeToParent((parent) => {
                return((parent.Width / 2) - (iconImage.Width / 2));
            }),
                Constraint.RelativeToParent((parent) => {
                return(parent.Height * .25);
            }),
                Constraint.RelativeToParent((parent) => {
                return(parent.Width * .45);
            }),
                Constraint.RelativeToParent((parent) => {
                return(parent.Width * .45);
            })
                );

            iconImage.SizeChanged += (sender, e) => {
                layout.ForceLayout();
            };

            var dashlabel = new Label()
            {
                Text             = square.Text,
                XAlign           = TextAlignment.Center,
                TextColor        = Color.White,
                FontFamily       = Device.OnPlatform("AvenirNextCondensed-Bold", "sans-serif-condensed", null),
                InputTransparent = true
            };

            layout.Children.Add(dashlabel,
                                Constraint.Constant(0),
                                Constraint.RelativeToParent((parent) => {
                return(parent.Height - 30);
            }),
                                Constraint.RelativeToParent((parent) => {
                return(parent.Width);
            }),
                                Constraint.RelativeToParent((parent) => {
                return(parent.Height);
            }));

            Content = layout;
        }
Esempio n. 52
0
 public void DeleteBatchShipTypePayType(List<int?> sysNos, EventHandler<RestClientEventArgs<dynamic>> callback)
 {
     string relativeUrl = "/CommonService/ShipTypePayType/Delete";
     restClient.Delete(relativeUrl, sysNos, callback);
 }
Esempio n. 53
0
 /// <summary>
 /// Factory method. Asynchronously loads a <see cref="SupplierList"/> collection, based on given parameters.
 /// </summary>
 /// <param name="name">The Name parameter of the SupplierList to fetch.</param>
 /// <param name="callback">The completion callback method.</param>
 public static void GetSupplierList(string name, EventHandler <DataPortalResult <SupplierList> > callback)
 {
     DataPortal.BeginFetch <SupplierList>(name, callback);
 }
Esempio n. 54
0
 public static void GetPTIdentity(string username, string password, EventHandler <DataPortalResult <PTIdentity> > callback)
 {
     DataPortal.BeginFetch <PTIdentity>(new UsernameCriteria(username, password), callback);
 }
Esempio n. 55
0
        /// <summary>
        /// Constructor specifying the target object.
        /// </summary>
        /// <param name="targetObject">The target object the behavior is attached to.</param>
        public CommandBehaviorBase(T targetObject)
        {
            _targetObject = new WeakReference(targetObject);

            _commandCanExecuteChangedHandler = CommandCanExecuteChanged;
        }
Esempio n. 56
0
        /// <summary>
        /// Initialize a new instance of the ButtonSpecView class.
        /// </summary>
        /// <param name="redirector">Palette redirector.</param>
        /// <param name="paletteMetric">Source for metric values.</param>
        /// <param name="metricPadding">Padding metric for border padding.</param>
        /// <param name="manager">Reference to owning manager.</param>
        /// <param name="buttonSpec">Access</param>
        public ButtonSpecView(PaletteRedirect redirector,
                              IPaletteMetric paletteMetric,
                              PaletteMetricPadding metricPadding,
                              ButtonSpecManagerBase manager,
                              ButtonSpec buttonSpec)
        {
            Debug.Assert(redirector != null);
            Debug.Assert(manager != null);
            Debug.Assert(buttonSpec != null);

            // Remember references
            _redirector     = redirector;
            Manager         = manager;
            ButtonSpec      = buttonSpec;
            _finishDelegate = OnFinishDelegate;

            // Create delegate for paint notifications
            NeedPaintHandler needPaint = OnNeedPaint;

            // Intercept calls from the button for color remapping and instead use
            // the button spec defined map and the container foreground color
            RemapPalette = Manager.CreateButtonSpecRemap(redirector, buttonSpec);

            // Use a redirector to get button values directly from palette
            _palette = new PaletteTripleRedirect(RemapPalette,
                                                 PaletteBackStyle.ButtonButtonSpec,
                                                 PaletteBorderStyle.ButtonButtonSpec,
                                                 PaletteContentStyle.ButtonButtonSpec,
                                                 needPaint);


            // Create the view for displaying a button
            ViewButton = new ViewDrawButton(_palette, _palette, _palette, _palette,
                                            paletteMetric, this, VisualOrientation.Top, false);

            // Associate the view with the source component (for design time support)
            if (buttonSpec.AllowComponent)
            {
                ViewButton.Component = buttonSpec;
            }

            // Use a view center to place button in centre of given space
            ViewCenter = new ViewLayoutCenter(paletteMetric, metricPadding, VisualOrientation.Top)
            {
                ViewButton
            };

            // Create a controller for managing button behavior
            ButtonSpecViewControllers controllers = CreateController(ViewButton, needPaint, OnClick);

            ViewButton.MouseController  = controllers.MouseController;
            ViewButton.SourceController = controllers.SourceController;
            ViewButton.KeyController    = controllers.KeyController;

            // We need notifying whenever a button specification property changes
            ButtonSpec.ButtonSpecPropertyChanged += OnPropertyChanged;

            // Associate the button spec with the view that is drawing it
            ButtonSpec.SetView(ViewButton);

            // Finally update view with current button spec settings
            UpdateButtonStyle();
            UpdateVisible();
            UpdateEnabled();
            UpdateChecked();
        }
Esempio n. 57
0
 public MessageAction(string label, EventHandler handler) : this(label, false, handler)
 {
 }
        // "Creating" a new SearchAgent here was not buying us much that we shouldn't just create it when it was called.

        // TODO: TBD: a bit on the fence about the prospect of a "for-each-solution"; could make for an interesting API, but is it necessary?

        /// <summary>
        ///
        /// </summary>
        /// <param name="agent"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        public static ISearchAgent ForEachSolution(this ISearchAgent agent, EventHandler <ProcessVariablesEventArgs> handler)
        {
            agent.ProcessVariables += handler;
            return(agent);
        }
Esempio n. 59
0
 /// <summary>
 /// 检查订阅事件处理函数。
 /// </summary>
 /// <param name="id">事件类型编号。</param>
 /// <param name="handler">要检查的事件处理函数。</param>
 /// <returns>是否存在事件处理函数。</returns>
 public bool Check(int id, EventHandler <GameEventArgs> handler)
 {
     return(mEventPool.Check(id, handler));
 }
Esempio n. 60
0
		/// <summary>
		/// 获得比较最适合的用于处理响应的类型
		/// </summary>
		/// <typeparam name="T">当前希望获得的结果</typeparam>
		/// <param name="client">当前的HTTP客户端</param>
		/// <param name="ctx">当前的上下文环境</param>
		/// <param name="responseContent">当前用来处理结果的对象</param>
		/// <param name="streamInvoker">如果希望能按流处理,那么用来处理响应的事件委托</param>
		/// <param name="result">当前希望获得的结果实例</param>
		/// <param name="targetStream">要将相应内容写入的流</param>
		/// <param name="saveToFilePath">要将当前请求写入的文件路径</param>
		/// <returns></returns>
		public HttpResponseContent GetPreferedResponseType<T>(HttpClient client, HttpContext ctx, HttpResponseContent responseContent, EventHandler<ResponseStreamContent.RequireProcessStreamEventArgs> streamInvoker = null, T result = default(T), Stream targetStream = null, string saveToFilePath = null)
		{
			return responseContent;
		}