Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
Esempio n. 1
0
        public static void KillEmulator(bool forceBypass = false)
        {
            if (!ShouldKillswitchFire || (UICore.FirstConnect && !forceBypass) || (!S.GET <UI_CoreForm>().cbUseAutoKillSwitch.Checked&& !forceBypass))
            {
                return;
            }

            ShouldKillswitchFire = false;

            //Nuke netcore
            UI_VanguardImplementation.RestartServer();

            SyncObjectSingleton.FormExecute(() =>
            {
                //Stop the old timer and eat any exceptions
                try
                {
                    BoopMonitoringTimer?.Stop();
                    BoopMonitoringTimer?.Dispose();
                }
                catch
                {
                }

                killswitchSpamPreventTimer          = new Timer();
                killswitchSpamPreventTimer.Interval = 5000;
                killswitchSpamPreventTimer.Tick    += KillswitchSpamPreventTimer_Tick;
                killswitchSpamPreventTimer.Start();


                PlayCrashSound(true);

                if (CorruptCore.RtcCore.EmuDir == null)
                {
                    MessageBox.Show("Couldn't determine what emulator to start! Please start it manually.");
                    return;
                }
            });
            var info = new ProcessStartInfo();

            oldEmuDir             = CorruptCore.RtcCore.EmuDir;
            info.WorkingDirectory = oldEmuDir;
            info.FileName         = Path.Combine(oldEmuDir, "RESTARTDETACHEDRTC.bat");
            if (!File.Exists(info.FileName))
            {
                MessageBox.Show($"Couldn't find {info.FileName}! Killswitch will not work.");
                return;
            }

            Process.Start(info);
        }
Esempio n. 2
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (!int.TryParse(textBox2.Text, out int port))
            {
                MessageBox.Show("端口输入不正确!");
                return;
            }


            try
            {
                busTcpServer        = new HslCommunication.ModBus.ModbusTcpServer( );                // 实例化对象
                busTcpServer.LogNet = new HslCommunication.LogNet.LogNetSingle("logs.txt");          // 配置日志信息
                busTcpServer.LogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
                busTcpServer.OnDataReceived          += BusTcpServer_OnDataReceived;
                busTcpServer.IsMultiWordReverse       = checkBox2.Checked;
                busTcpServer.IsStringReverse          = checkBox3.Checked;
                busTcpServer.ServerStart(port);

                button1.Enabled  = false;
                panel2.Enabled   = true;
                button4.Enabled  = true;
                button11.Enabled = true;

                timerSecond?.Dispose( );
                timerSecond          = new System.Windows.Forms.Timer( );
                timerSecond.Interval = 1000;
                timerSecond.Tick    += TimerSecond_Tick;
                timerSecond.Start( );
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 3
0
        private void button1_Click(object sender, EventArgs e)
        {
            // 启动服务
            if (!int.TryParse(textBox2.Text, out int port))
            {
                MessageBox.Show(DemoUtils.PortInputWrong);
                return;
            }

            try
            {
                s7NetServer = new Communication.Profinet.Siemens.SiemensS7Server();// 实例化对象
                s7NetServer.OnDataReceived += BusTcpServer_OnDataReceived;

                s7NetServer.ServerStart(port);// 启动服务器的引擎

                button1.Enabled  = false;
                panel2.Enabled   = true;
                button4.Enabled  = true;
                button11.Enabled = true;

                timerSecond?.Dispose();
                timerSecond          = new System.Windows.Forms.Timer();
                timerSecond.Interval = int.MaxValue;//1000
                timerSecond.Tick    += TimerSecond_Tick;
                timerSecond.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 4
0
 internal bool Run()
 {
     bool flag;
     if (this._insideModalLoop)
     {
         throw new InvalidOperationException(Microsoft.ManagementConsole.Internal.Utility.LoadResourceString(Microsoft.ManagementConsole.Internal.Strings.ExceptionInternalConsoleDialogHostAlreadyInsideModalLoop));
     }
     Timer timer = new Timer();
     try
     {
         Application.UseWaitCursor = true;
         this._insideModalLoop = true;
         timer.Tick += new EventHandler(this.OnTimer);
         timer.Interval = (int) this.Timeout.TotalMilliseconds;
         timer.Start();
         this.InnerStart();
         ModalLoop.Run();
         flag = !this._timedOut;
     }
     finally
     {
         timer.Dispose();
         this._timedOut = false;
         this._quitMessagePosted = false;
         this._insideModalLoop = false;
         Application.UseWaitCursor = false;
     }
     return flag;
 }
Esempio n. 5
0
        private void CopyRandomButton_Click(object sender, EventArgs e)
        {
            var users = DataStore.GetOnlineUsers();
            var r     = new Random();

            if (users.Count > 0)
            {
                var winner = users[(int)Math.Round(r.NextDouble() * (users.Count - 1))];
                Clipboard.SetText(winner);
                ((Button)sender).Text = winner;
            }
            else
            {
                ((Button)sender).Text = @"NO ENTRIES";
            }
            copyRandomUserTimer?.Dispose();

            copyRandomUserTimer       = new Timer();
            copyRandomUserTimer.Tick += delegate
            {
                ((Button)sender).Text = @"Copy Random User";
                copyRandomUserTimer.Stop();
                copyRandomUserTimer.Dispose();
                copyRandomUserTimer = null;
            };
            copyRandomUserTimer.Interval = 1500;
            copyRandomUserTimer.Start();
        }
Esempio n. 6
0
 public static void CallLater(TimeSpan delay, Action method)
 {
     var delayMilliseconds = (int) delay.TotalMilliseconds;
     if (delayMilliseconds < 0)
     {
         throw new ArgumentOutOfRangeException("delay", delay, Properties.Resources.ValueMustBePositive);
     }
     if (method == null)
     {
         throw new ArgumentNullException("method");
     }
     SafeThreadAsyncCall(delegate
     {
         var t = new Timer
         {
             Interval = Math.Max(1, delayMilliseconds)
         };
         t.Tick += delegate
         {
             t.Stop();
             t.Dispose();
             method();
         };
         t.Start();
     });
 }
        private void button1_Click(object sender, EventArgs e)
        {
            if (!int.TryParse(textBox2.Text, out int port))
            {
                MessageBox.Show(DemoUtils.PortInputWrong);
                return;
            }


            try
            {
                lSisServer = new HslCommunication.Profinet.LSIS.LSisServer( );                       // 实例化对象
                //lSisServer.LogNet = new HslCommunication.LogNet.LogNetSingle( "logs.txt" );                  // 配置日志信息
                //lSisServer.LogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
                lSisServer.OnDataReceived += BusTcpServer_OnDataReceived;

                lSisServer.ServerStart(port);

                button1.Enabled  = false;
                panel2.Enabled   = true;
                button4.Enabled  = true;
                button11.Enabled = true;

                timerSecond?.Dispose( );
                timerSecond          = new System.Windows.Forms.Timer( );
                timerSecond.Interval = 1000;
                timerSecond.Tick    += TimerSecond_Tick;
                timerSecond.Start( );
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 8
0
 private void LoadShader(string fileName)
 {
     try
     {
         var log = visualContext.AddUpdateFragmentShader(fileName);
         var correctedLineEndings = log.Replace("\n", Environment.NewLine).Trim();
         CallOnChange("Loading '+" + fileName + "' with success!" + Environment.NewLine + correctedLineEndings);
     }
     catch (ShaderLoadException e)
     {
         var correctedLineEndings = e.Message.Replace("\n", Environment.NewLine);
         CallOnChange("Error while compiling shader '" + fileName + "'" + Environment.NewLine + correctedLineEndings);
     }
     catch (FileNotFoundException e)
     {
         CallOnChange(e.Message);
     }
     catch (Exception e)
     {
         //try reload in 2 seconds, because sometimes file system is still busy
         Timer timer = new Timer(); //todo: is this executed on main thread?
         timer.Interval = 2000;
         timer.Tick += (a, b) =>
         {
             timer.Stop();
             timer.Dispose();
             LoadShader(shaderFileName); //if fileName is used here timer will always access fileName of first call and not a potential new one
         };
         timer.Start();
         CallOnChange("Error while accessing shaderfile '" + fileName + "'! Will retry shortly..." + Environment.NewLine + e.Message);
     }
 }
Esempio n. 9
0
        private void StartButton_Click(object sender, EventArgs e)
        {
            var width  = int.Parse(WidthInput.Text);
            var height = int.Parse(HeightInput.Text);
            var randomElementsNumber = int.Parse(RandomElementsNumberInput.Text);
            var interval             = int.Parse(IntervalInput.Text);
            var gridValidator        = new GridValidator();

            if (!gridValidator.Validate(width, height, randomElementsNumber, interval))
            {
                return;
            }
            PauseButton.Enabled = true;
            Grid = null;
            Timer?.Dispose();
            GlobalWidth      = width;
            GlobalHeight     = height;
            Grid             = new Grid(width, height, randomElementsNumber);
            PauseButton.Text = "Pause";
            Timer            = new Timer {
                Interval = interval
            };
            Timer.Tick += (localSender, locale) => Simulation();
            Timer.Start();
        }
Esempio n. 10
0
        private Control[] AddToUI(Host host)
        {
            var siteLabel = new Label() {
                AutoSize = true,
                Dock = DockStyle.Fill,
                TabIndex = 1,
                Text = host.HOST,
                TextAlign = System.Drawing.ContentAlignment.MiddleCenter
            };
            var timeLabel = new Label() {
                AutoSize = true,
                Dock = DockStyle.Fill,
                TabIndex = 2,
                TextAlign = System.Drawing.ContentAlignment.MiddleCenter
            };
            var removeButton = new Button() {
                Dock = DockStyle.Fill,
                TabIndex = 3,
                Text = "remove",
                UseVisualStyleBackColor = true
            };

            if (host.END_TIME.HasValue) {
                timeLabel.Text = host.END_TIME.ToString();

                var t = new Timer() {
                    Enabled = true,
                    Interval = 1000
                };

                t.Tick += (sender, e) => {
                    if ((host.END_TIME.Value - DateTime.Now).TotalSeconds > 0) {
                        timeLabel.Text = TimeSpan.Parse(timeLabel.Text).Subtract(new TimeSpan(0, 0, 1)).ToString();
                        t.Dispose();
                    }
                    else {
                        host.Unblock();
                    }
                };

                removeButton.Click += (sender, e) => {
                    host.Unblock();
                };
            } else {
                timeLabel.Text = "routed to " + host.REDIRECT;

                removeButton.Click += (sender, e) => {
                    host.Unblock();
                };
            }

            MainTablePanel.RowCount++;
            MainTablePanel.RowStyles.Add(new RowStyle());
            MainTablePanel.Controls.Add(siteLabel, 0, -1);
            MainTablePanel.Controls.Add(timeLabel, 1, -1);
            MainTablePanel.Controls.Add(removeButton, 2, -1);

            return new Control[] { siteLabel, timeLabel, removeButton };
        }
Esempio n. 11
0
 public Bomb(int x, int y)
 {
     base.X = x;
     base.Y = y;
     t = new Timer();
     t.Interval = Settings.BOMB_DURATION;
     t.Tick += (o, e) => { t.Stop(); t.Dispose(); Alive = false; };
     t.Start();
 }
Esempio n. 12
0
        private void ChangeTimerGaussParameters(float x, float y)
        {
            _gaussTimer?.Stop();
            _gaussTimer?.Dispose();
            _gaussTimer          = new Timer();
            _gaussTimer.Interval = _gaussRefreshTime;
            _gaussTimer.Tick    += (s, ea) =>
            {
                textBoxPosition.Text = "X: " + x.ToString() + "; " + "Y: " + y.ToString();
                Bitmap bitmap = (Bitmap)_bitmap.Clone();
                Dictionary <string, List <double> > fitting = Analyzer.GaussianFittingXY(bitmap, (int)x, (int)y, (int)_gaussSize);

                //Refresh crop
                Bitmap    cropImage = new Bitmap(bitmap);
                Rectangle rect      = new Rectangle((int)((x - _gaussSize / 2) < 0 ? 0 : (x - _gaussSize / 2)), (int)((y - _gaussSize / 2) < 0 ? 0 : (y - _gaussSize / 2)), (int)_gaussSize, (int)_gaussSize);
                if (rect.X + rect.Width > bitmap.Width || rect.Y + rect.Height > bitmap.Height)
                {
                    rect.Width  = Math.Min(bitmap.Width - rect.X, bitmap.Height - rect.Y);
                    rect.Height = rect.Width;
                    _gaussSize  = rect.Height;
                }
                cropImage = cropImage.Clone(rect, cropImage.PixelFormat);

                BeginInvoke((Action)(() =>
                {
                    pictureBoxSnap.Image = cropImage;

                    _chartXLine.Clear();
                    List <List <double> > input = new List <List <double> >();
                    input.Add(fitting["xLine"]);
                    input.Add(fitting["gXLine"]);
                    _chartXLine.Values = input;
                    _chartXLine.Draw();
                    splitContainer3.Panel1.Controls.Clear();
                    splitContainer3.Panel1.Controls.Add(_chartXLine);

                    _chartYLine.Clear();
                    input = new List <List <double> >();
                    input.Add(fitting["yLine"]);
                    input.Add(fitting["gYLine"]);
                    _chartYLine.Values = input;
                    _chartYLine.Draw();
                    splitContainer3.Panel2.Controls.Clear();
                    splitContainer3.Panel2.Controls.Add(_chartYLine);
                }));

                if (_followLight)
                {
                    Point newPosition = Analyzer.FollowLight((Bitmap)cropImage.Clone(), (int)x, (int)y, (int)_gaussSize);
                    if (newPosition != new Point(x, y))
                    {
                        ChangeTimerGaussParameters(newPosition.X, newPosition.Y);
                    }
                }
            };
            _gaussTimer.Start();
        }
Esempio n. 13
0
        public static void Main()
        {
            try
            {
                Settings.Configurate();

                //database = new Database();
                felhasználó = null;
                database = new Database();

                LoginForm loginform = new LoginForm();
                Application.Run(loginform);
                database = new Database();
                if (loginform.felhasználó != null)
                {
                    felhasználó = loginform.felhasználó;
                    loginform.Dispose();

                    refresher = new Timer();
                    refresher.Interval = Settings.ui_refresh * 1000;
                    refresher.Tick += Refresher_Elapsed;
                    refresher.Start();

                    MainForm mainform = new MainForm();
                    Application.Run(mainform);

                    refresher.Dispose();
                    mainform.Dispose();
                }
            }
            catch (Exception _e)
            {
                MessageBox.Show("Kezeletlen globális hiba a program futása során!\nKérem jelezze a hibát a rendszergazdának!\nHiba adatai:\n" + _e.Message, "Hiba", MessageBoxButtons.OK, MessageBoxIcon.Error);

                string file_name = string.Format("crash-{0:yyyy-MM-dd_hh-mm-ss}.data", DateTime.Now);

                try
                {
                    StreamWriter file = new StreamWriter(file_name);
                    file.WriteLine("Message:\t" + _e.Message);
                    file.WriteLine("Source:\t" + _e.Source);
                    file.WriteLine("Data:\t" + _e.Data);
                    file.WriteLine("Stack:\t" + _e.StackTrace);
                    file.Close();
                }
                catch (Exception _ex)
                {
                    MessageBox.Show("További hiba a kivétel mentésekor!\n" + _ex.Message, "Hiba", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Environment.Exit(1);
                }

                MessageBox.Show("A hiba adatait a " + file_name + " nevű file tartalmazza!", "Hiba adatainak elérése", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Environment.Exit(0);
            }
        }
Esempio n. 14
0
        public void RefreshStop()
        {
            if (_refreshTimer == null)
            {
                return;
            }

            _refreshTimer.Tick -= RefreshTimerTick;
            _refreshTimer?.Stop();
            _refreshTimer?.Dispose();
        }
Esempio n. 15
0
        // This api receives javascript errors with stack dumps that have not been converted to source.
        // Javascript code will then attempt to convert them and report using HandleJavascriptError.
        // In case that fails, after 200ms we will make the report using the unconverted stack.
        public void HandlePreliminaryJavascriptError(ApiRequest request)
        {
            lock (request)
            {
                lock (lockJsError)
                {
                    if (preliminaryJavascriptError != null)
                    {
                        // If we get more than one of these without a real report, the first is most likely to be useful, I think.
                        // This also avoids ever having more than one timer running.
                        request.PostSucceeded();
                        return;
                    }
                    preliminaryJavascriptError = request.RequiredPostJson();
                }

                var form = Application.OpenForms.Cast <Form>().Last();
                // If we don't have an active Bloom form, I think we can afford to discard this report.
                if (form != null)
                {
                    form.BeginInvoke((Action)(() =>
                    {
                        // Arrange to report the error if we don't get a better report of it in 200ms.
                        jsErrorTimer?.Stop();                         // probably redundant
                        jsErrorTimer?.Dispose();                      // left over from previous report that had follow-up?
                        jsErrorTimer = new Timer {
                            Interval = 200
                        };
                        jsErrorTimer.Tick += (sender, args) =>
                        {
                            jsErrorTimer.Stop();                             // probably redundant?
                            // not well documented but found some evidence this is OK inside event handler.
                            jsErrorTimer.Dispose();
                            jsErrorTimer = null;

                            dynamic temp;
                            lock (lockJsError)
                            {
                                temp = preliminaryJavascriptError;
                                preliminaryJavascriptError = null;
                            }

                            if (temp != null)
                            {
                                ReportJavascriptError(temp);
                            }
                        };
                        jsErrorTimer.Start();
                    }));
                }
                request.PostSucceeded();
            }
        }
Esempio n. 16
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="milliseconds"></param>
		/// <param name="action"></param>
		public static void Delay(int milliseconds, Action action)
		{
			Timer timer = new Timer();
			timer.Interval = milliseconds;
			timer.Tick += (object sender, EventArgs e) =>
			{
				action.Invoke();
				timer.Stop();
				timer.Dispose();
			};
			timer.Start();
		}
Esempio n. 17
0
 public void Stop()
 {
     if (s_current.Value == this)
     {
         s_current.Value = null;
         _timer?.Dispose();
         Application.Idle -= OnIdle;
         Cursor.Hide();
         Cursor.Current = _oldCursor ?? Cursors.Default;
         Cursor.Show();
     }
 }
Esempio n. 18
0
        public void SetReadWriteServer(NetworkDataServerBase dataServerBase, string address, int strLength = 10)
        {
            this.dataServerBase        = dataServerBase;
            this.dataServerBase.LogNet = new HslCommunication.LogNet.LogNetSingle("");
            this.dataServerBase.LogNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;
            userControlReadWriteOp1.SetReadWriteNet(dataServerBase, address, false, strLength);

            timerSecond?.Dispose( );
            timerSecond          = new System.Windows.Forms.Timer( );
            timerSecond.Interval = 1000;
            timerSecond.Tick    += TimerSecond_Tick;
            timerSecond.Start( );
        }
Esempio n. 19
0
    private void LightWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        //Save Settings
        UserSettings.Save();

        if (Stage != RecorderStages.Stopped)
        {
            _capture.Stop();
            _capture.Dispose();
        }

        GC.Collect();
    }
Esempio n. 20
0
 private void T2_Tick(object sender, EventArgs e)
 {
     cnt           += 3;
     this.BackColor = Color.FromArgb(cnt, cnt, cnt);
     LuckyNumber.Update();
     LuckyNumber.Refresh();
     if (cnt >= 255)
     {
         cnt--;
         t2.Dispose();
         LuckyNumber.Visible = false;
         setYt(yt);
     }
 }
Esempio n. 21
0
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            formUpdateTimer.Stop();
            pidTimeStep.Stop();
            formUpdateTimer.Enabled = false;
            pidTimeStep.Enabled     = false;
            formUpdateTimer.Dispose();
            pidTimeStep.Dispose();

            if (temperatureController != null)
            {
                temperatureController.Dispose();
            }
        }
Esempio n. 22
0
        private void pictureBox4_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == -1)
            {
                return;
            }
            if (ExceptionCaught)
            {
                return;
            }
            var f     = FolderCreator();
            var timer = new System.Windows.Forms.Timer();

            if (f)
            {
                IsClicked = !IsClicked;
                if (IsClicked)
                {
                    try
                    {
                        CaptureStopped = false;
                        CapTure        = new Capture(comboBox1.SelectedIndex);
                        timer.Interval = 1000 / Fps;
                        timer.Tick    += ProcessFrame;
                        timer.Start();
                    }
                    catch (Exception)
                    {
                        MessageBox.Show(@"Cannot read from the chosen device.", @"Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Application.Exit();
                    }
                    comboBox1.Enabled = false;
                    ToolTip.SetToolTip(pictureBox4, "Stop the Camera");
                }
                else
                {
                    CaptureStopped = true;
                    CapTure.Stop();
                    timer.Dispose();
                    ToolTip.SetToolTip(pictureBox4, "Start the Camera");
                    comboBox1.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show(@"There is no training data available. Please add at least one user.", @"Ooops",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 private void MQCShowForm_FormClosed(object sender, FormClosedEventArgs e)
 {
     nGPanel.Dispose();
     nGRework.Dispose();
     nGPanel = null;
     nGRework = null;
     bgWorker.DoWork -= new DoWorkEventHandler(bg_DoWork);
     bgWorker.ProgressChanged -= BgWorker_ProgressChanged;
     bgWorker.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
     tmrCallBgWorker.Tick -= new EventHandler(tmrCallBgWorker_Tick);
     tmrCallBgWorker.Stop();
     bgWorker.Dispose();
     tmrCallBgWorker.Dispose();
 }
 private void btnAddCurrentProcess_Click(object sender, System.EventArgs e)
 {
     MessageBox.Show("After you click OK, you have 3 seconds to select the process", "Select process",
         MessageBoxButtons.OK, MessageBoxIcon.Information);
     Timer lvSelectProcessTimer = new Timer();
     lvSelectProcessTimer.Tick += delegate
     {
         tbxTitle.Text = NativeWin32.GetActiveProcessWindow().Title;
         lvSelectProcessTimer.Stop();
         lvSelectProcessTimer.Dispose();
     };
     lvSelectProcessTimer.Interval = 3000;
     lvSelectProcessTimer.Start();
 }
 public override void Unload()
 {
     base.Unload();
     updateTimer.Stop();
     updateTimer.Dispose();
     imageTexture.Dispose();
     imagePanel.Dispose();
     updateTimer      = null;
     imagePanel       = null;
     statusStrip      = null;
     visualizerCanvas = null;
     imageTexture     = null;
     visualizerImage  = null;
 }
Esempio n. 26
0
 private void btnStop_Click(object sender, EventArgs e)
 {
     btnStart.Enabled     = true;
     btnStop.Enabled      = false;
     btnSpeedUp.Enabled   = false;
     btnSpeedDown.Enabled = false;
     if (timer != null)
     {
         timer.Stop();
         timer.Dispose();
         timer = null;
     }
     this.Opacity = 100;
 }
Esempio n. 27
0
 private void tickCountdown()
 {
     if (currentSec == 0)
     {
         timer.Dispose();
         this.Close();
         OnTimeout?.Invoke();
     }
     else
     {
         txtCountdown.Text = currentSec.ToString();
         currentSec       -= 1;
     }
 }
Esempio n. 28
0
        // postpones executing this function
        public static void postpone(void_func f, int time_ms)
        {
            Timer t = new Timer()
            {
                Interval = time_ms
            };

            t.Tick += (sender, args) => {
                t.Enabled = false;
                t.Dispose();
                f();
            };
            t.Enabled = true;
        }
 public void Dispose()
 {
     if (this._top != 0)
     {
         int retries = 0;
         Timer tmr = new Timer {
             Interval = 1,
             Enabled = true
         };
         tmr.Tick += delegate (object sender, EventArgs e) {
             if (++retries > 2)
             {
                 tmr.Dispose();
             }
             try
             {
                 object domDocument = this._browser.Document.DomDocument;
                 object target = domDocument.GetType().InvokeMember("documentElement", BindingFlags.GetProperty, null, domDocument, null);
                 int height = this._top;
                 if (height == -1)
                 {
                     HtmlElement body = this._browser.Document.Body;
                     if (body == null)
                     {
                         return;
                     }
                     height = body.ScrollRectangle.Height;
                 }
                 target.GetType().InvokeMember("scrollTop", BindingFlags.SetProperty, null, target, new object[] { height });
                 tmr.Dispose();
             }
             catch
             {
             }
         };
     }
 }
Esempio n. 30
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="fDisposeManagedObjs"><c>true</c> to release both managed and unmanaged
        /// resources; <c>false</c> to release only unmanaged resources.</param>
        ///
        /// <developernote>
        /// We don't implement a finalizer. Finalizers should only be implemented if we have to
        /// free unmanaged resources. We have COM objects, but those are wrapped in a managed
        /// wrapper, so they aren't considered unmanaged here.
        /// <see href="http://code.logos.com/blog/2008/02/the_dispose_pattern.html"/>
        /// </developernote>
        /// ------------------------------------------------------------------------------------
        private void Dispose(bool fDisposeManagedObjs)
        {
            if (fDisposeManagedObjs)
            {
                Close();
                if (!m_fDisposed)
                {
                    s_Instances.Remove(m_LinkSet);
                }

                if (m_timer != null)
                {
                    m_timer.Stop();
                    m_timer.Dispose();
                }

                if (m_pollTimer != null)
                {
                    m_pollTimer.Stop();
                    m_pollTimer.Dispose();
                }

                if (m_MarshalingControl != null)
                {
                    m_MarshalingControl.Dispose();
                }

                //Application.ThreadExit -= OnThreadExit;
            }

            m_cookies           = null;
            m_timer             = null;
            m_pollTimer         = null;
            m_MarshalingControl = null;

            m_fDisposed = true;
        }
Esempio n. 31
0
        // Set initial state of controls.
        // Called from worker thread using delegate and Control.Invoke
        private void ThreadFinishedMethod(String artist, String title, String message, String site)
        {
            if (_timer != null)
            {
                _timer.Enabled = false;
                _timer.Stop();
                _timer.Dispose();
                _timer = null;
                _hour  = 0;
                _min   = 0;
                _sec   = 0;
            }

            if (_lyricsController != null)
            {
                _lyricsController.StopSearches = true;
                DatabaseUtil.SerializeDBs();
                _lyricsLibraryUserControl.UpdateLyricsTree(false);
            }
            bgWorkerSearch.CancelAsync();
            StopThread();
            progressBar.ResetText();
            progressBar.Enabled = false;

            if (site.Equals("error"))
            {
                lbStep1a.Text = "-";
                lbStep2a.Text = "-";
            }
            else
            {
                lbStep1a.Text = "Completed";
                lbStep2a.Text = "Completed";
            }

            lbMessage.Text += message + Environment.NewLine;

            btStartBatchSearch.Enabled = true;
            btCancel.Enabled           = false;
            IsSearching(false);

            var logText = string.Format("The search has ended with {0} found and {1} missed.", _mLyricsFound,
                                        _mLyricsNotFound);

            lbLastActivity2.Text = logText;

            BatchLogger.Info("{0}", logText);
            BatchLogger.Info("Batch search ended.");
        }
        void progress_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            // show/hide dialog as required by ShowingDialog
            if (dlg.Visible == collector.ShowingDialog)
            {
                if (collector.ShowingDialog)
                {
                    dlg.Hide();
                }
                else if (!reshowTimerRunning)
                {
                    reshowTimerRunning = true;
                    var timer = new System.Windows.Forms.Timer();
                    timer.Interval = 100;
                    timer.Tick    += delegate {
                        timer.Dispose();
                        reshowTimerRunning = false;
                        if (!collector.ShowingDialog)
                        {
                            if (runningInOwnThread)
                            {
                                dlg.Show();
                            }
                            else
                            if (!collector.ProgressMonitorIsDisposed && !dlg.Visible)
                            {
                                dlg.ShowDialog();
                            }
                        }
                    };
                    timer.Start();
                }
            }

            // update task name and progress
            if (e.PropertyName == "TaskName")
            {
                dlg.taskLabel.Text = collector.TaskName ?? defaultTaskName;
            }
            if (double.IsNaN(collector.Progress))
            {
                dlg.progressBar.Style = ProgressBarStyle.Marquee;
            }
            else
            {
                dlg.progressBar.Style = ProgressBarStyle.Continuous;
                dlg.progressBar.Value = Math.Max(0, Math.Min(100, (int)(collector.Progress * 100)));
            }
        }
Esempio n. 33
0
        public void Show(int showTimeMSec)
        {
            if (this._viewClock != null)
            {
                _viewClock.Stop();
                _viewClock.Dispose();
            }

            base.Show();

            _viewClock          = new System.Windows.Forms.Timer();
            _viewClock.Tick    += new System.EventHandler(viewTimer);
            _viewClock.Interval = showTimeMSec;
            _viewClock.Start();
        }
 private void ProductionMain_FormClosed(object sender, FormClosedEventArgs e)
 {
     bgWorker.DoWork             -= new DoWorkEventHandler(bg_DoWork);
     bgWorker.ProgressChanged    -= BgWorker_ProgressChanged;
     bgWorker.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
     tmrCallBgWorker.Tick        -= new EventHandler(tmrCallBgWorker_Tick);
     if (line != null)
     {
         line.Dispose();
         line = null;
     }
     tmrCallBgWorker.Stop();
     bgWorker.Dispose();
     tmrCallBgWorker.Dispose();
 }
Esempio n. 35
0
        /// <summary>
        /// 定时执行任务
        /// </summary>
        private static void DelayRun(int ms, Action method)
        {
            var t = new System.Windows.Forms.Timer {
                Interval = ms
            };

            t.Tick += (S, E) =>
            {
                t.Stop();
                GC.KeepAlive(t);
                t.Dispose();
                method();
            };
            t.Start();
        }
Esempio n. 36
0
        private void stop()
        {
            if (!(m_timerGetDate == null))
            {
                //m_timerGetDate.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                m_timerGetDate.Stop();
                m_timerGetDate.Dispose();
                m_timerGetDate = null;
            }

            else
            {
                ;
            }
        }
Esempio n. 37
0
        protected virtual void Dispose(bool _Disposing)
        {
            if (IsDisposed)
            {
                return;
            }

            if (_Disposing)
            {
                handle.Dispose();
                HideTimer.Dispose();
            }

            IsDisposed = true;
        }
Esempio n. 38
0
 private void DisposeGDIObjects()
 {
     if (gdiInitialized)
     {
         brushContent.Dispose();
         cncfont.Dispose();
         cncpen.Dispose();
         HeaderGrad.Dispose();
         _contgrad.Dispose();
         brushButtonHover.Dispose();
         penButtonBorder.Dispose();
         penContent.Dispose();
         anim.Dispose();
     }
 }
Esempio n. 39
0
        public void checkOpFinished(Object obj, System.EventArgs arg)
        {
            timer1.Stop();

            progressBar1.PerformStep();
            Invalidate();
            progressBar1.Update();

            if (Finished)
            {
                timer1.Dispose();
                return;
            }
            timer1.Enabled = true;
        }
Esempio n. 40
0
 public static DialogResult ShowWithTimeout(this Form form, TimeSpan timeout)
 {
     form.TopMost = true;
     form.AutoSize = true;
     var timoutTimer = new Timer
     {
         Interval = (int)timeout.TotalMilliseconds,
         Enabled = true
     };
     form.Disposed += delegate { timoutTimer.Dispose(); };
     timoutTimer.Tick += delegate
     {
         form.DialogResult = DialogResult.Abort;
         form.Close();
         Console.WriteLine("timed out");
     };
     return form.ShowDialog();
 }
        public static void SpringScanner_RetryGetResourceInfo(object sender, ZkData.CancelEventArgs<ZkData.SpringScanner.CacheItem> e)
        {
            if (thisInstance != null)
                thisInstance.Dispose();

            if (rememberedResult != null)
            {
                e.Cancel = rememberedResult=="cancel";
                return;
            }

            thisInstance = new PromptForm();
            countDown = new Timer();
            countDown.Tick += (s, e1) => { 
                counter++;
                thisInstance.noButton.Text = "No (" + (30 - counter).ToString() + ")";
                if (counter==31)
                    thisInstance.DialogResult = DialogResult.Cancel;
            };
            countDown.Interval = 1000;
            countDown.Enabled = true;
            counter = 0;
            thisInstance.FormClosed += (s, e1) => { countDown.Dispose(); };
            thisInstance.detailBox.Visible = true;
            thisInstance.Text = "New resource found!";
            thisInstance.questionText.Text = Environment.NewLine + "Server connection failed. Extract \"" + e.Data.FileName + "\" information manually?";
            thisInstance.noButton.Text = "No,Wait";
            Program.ToolTip.SetText(thisInstance.okButton, "Perform UnitSync on this file immediately if UnitSync is available");
            Program.ToolTip.SetText(thisInstance.noButton, "Reask server for map/mod information after 2 minute");
            Program.ToolTip.SetText(thisInstance.rememberChoiceCheckbox, "Remember choice for this session only");
            thisInstance.detailText.WordWrap = false;
            var detailText = "File name: " + e.Data.FileName + Environment.NewLine;
            detailText = detailText + "MD5: " + e.Data.Md5.ToString() + Environment.NewLine;
            detailText = detailText + "Internal name: " + e.Data.InternalName + Environment.NewLine;
            detailText = detailText + "Recommended action: Restore Connection & Wait";
            thisInstance.detailText.Text = detailText;
            thisInstance.ShowDialog();

            e.Cancel = (thisInstance.DialogResult == DialogResult.OK);

            if (thisInstance.rememberChoiceCheckbox.Checked)
                rememberedResult = e.Cancel ? "cancel" : "ok";
        }
        public static void SpringScanner_UploadUnitsyncData(object sender, ZkData.CancelEventArgs<ZkData.IResourceInfo> e)
        {
            if (thisInstance != null)
                thisInstance.Dispose();

            if (rememberedResult != null)
            {
                e.Cancel = rememberedResult == "cancel";
                return;
            }

            thisInstance = new PromptForm();
            countDown = new Timer();
            countDown.Tick += (s, e1) => { 
                counter++;
                thisInstance.okButton.Text = "Ok (" + (30 - counter).ToString() + ")";
                if (counter == 31)
                    thisInstance.DialogResult = DialogResult.OK;
            };
            countDown.Interval = 1000;
            countDown.Enabled = true;
            counter = 0;
            thisInstance.FormClosed += (s, e1) => { countDown.Dispose(); };
            thisInstance.detailBox.Visible = true;
            thisInstance.Text = "New information extracted!";
            thisInstance.questionText.Text = Environment.NewLine + "No server data regarding this file hash. Upload \"" + e.Data.Name + "\" information to server?";
            thisInstance.okButton.Text = "Ok,Share";
            Program.ToolTip.SetText(thisInstance.okButton, "This map/mod will be listed on both ZKL and Springie");
            Program.ToolTip.SetText(thisInstance.noButton, "This map/mod will be listed only on this ZKL");
            Program.ToolTip.SetText(thisInstance.rememberChoiceCheckbox, "Remember choice for this session only");
            thisInstance.detailText.WordWrap = false;
            var detailText = "Resource name: " + e.Data.Name + Environment.NewLine;
            detailText = detailText + "Archive name: " + e.Data.ArchiveName + Environment.NewLine;
            detailText = detailText + "Recommended action: Share multiplayer resource";
            thisInstance.detailText.Text = detailText;
            thisInstance.ShowDialog();

            e.Cancel = (thisInstance.DialogResult == DialogResult.Cancel);

            if (thisInstance.rememberChoiceCheckbox.Checked)
                rememberedResult = e.Cancel ? "cancel" : "ok";
        }
Esempio n. 43
0
		static void SafeSetClipboard(object dataObject)
		{
			// Work around ExternalException bug. (SD2-426)
			// Best reproducable inside Virtual PC.
			int version = unchecked(++SafeSetClipboardDataVersion);
			try {
				Clipboard.SetDataObject(dataObject, true);
			} catch (ExternalException) {
				Timer timer = new Timer();
				timer.Interval = 100;
				timer.Tick += delegate {
					timer.Stop();
					timer.Dispose();
					if (SafeSetClipboardDataVersion == version) {
						try {
							Clipboard.SetDataObject(dataObject, true, 10, 50);
						} catch (ExternalException) { }
					}
				};
				timer.Start();
			}
		}
Esempio n. 44
0
        public void Test()
        {
            var close = false;
            var form = new Form();
            form.Closing += (s, e) => close = true;
            var xLabel = new Label { Parent = form };
            var yLabel = new Label { Parent = form, Top = 40 };
            var zLabel = new Label { Parent = form, Top = 80 };

            var inputDevices = new XnaInputDevices();
            var keyboard = inputDevices.Keyboard;
            keyboard.On(Button.X).IsDown().Do(() => close = true);
            keyboard.On(Button.Escape).WasReleased().Do(() => close = true);
            keyboard.On(Button.W).WasReleased().Do(() => form.Text = "Pressed");
            keyboard.On(Button.S).IsDown().Do(() => form.Text = "Down");

            var mouse = inputDevices.Mouse;
            mouse.On(Button.LeftMouse).IsDown().Do(() => form.Text = "Left Mouse down");
            mouse.On(Button.RightMouse).WasReleased().Do(() => form.Text = "Right Mouse was pressed");

            mouse.On(Axis.X).Do(delta => xLabel.Text = "X: " + delta);
            mouse.On(Axis.Y).Do(delta => yLabel.Text = "Y: " + delta);
            mouse.On(Axis.Z).Do(delta => zLabel.Text = "Z: " + delta);

            form.Show();

            var timer = new Timer { Interval = 10 };
            timer.Tick += (s, e) => inputDevices.Update();

            timer.Start();

            while (!close)
            {
                Application.DoEvents();
            }
            timer.Stop();
            timer.Dispose();
        }
        public override EventResult BrowserDocumentComplete()
        {
            MessageHandler.Info("Url: {0}, login: {1}, clicked: {2}, maximized: {3}", Url, login.ToString(), clicked.ToString(), maximized.ToString());
            if (login)
            {
                if (refreshed)
                {
                    login = false;
                    ProcessComplete.Finished = true;
                    ProcessComplete.Success = true;
                }
                else
                {
                    if (!clicked)
                    {
                        string js = " function doLogin() { ";
                        js += "document.getElementsByName('username')[0].value = '" + username + "'; ";
                        js += "document.getElementsByName('password')[0].value = '" + password + "'; ";
                        js += "document.getElementsByClassName('btn')[0].click(); }; ";
                        js += "setTimeout(\"doLogin()\", 1500); ";
                        InvokeScript(js);
                        clicked = true;
                        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                        timer.Tick += (object sender, EventArgs e) =>
                        {
                            refreshed = true;
                            timer.Stop();
                            timer.Dispose();
                            //Browser.Refresh();
                            Url = "https://www.tv4play.se/";
                        };
                        timer.Interval = 3000;
                        timer.Start();
                    }
                }
            }
            else
            {
                
                InvokeScript("setTimeout(\"document.getElementById('player').setAttribute('style', 'position: fixed; z-index: 11000; top: 0px; left: 0px; width: 100%; height: 100%')\", 1000);");
                if (startTimer)
                {
                    startTimer = false;
                    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                    timer.Tick += (object sender, EventArgs e) =>
                    {
                        if (showLoading) HideLoading();
                        timer.Stop();
                        timer.Dispose();
                    };

                    timer.Interval = 2250;
                    timer.Start();

                    System.Windows.Forms.Timer maxTimer = new System.Windows.Forms.Timer();
                    maxTimer.Tick += (object sender, EventArgs e) =>
                    {
                        Cursor.Position = new System.Drawing.Point(Browser.FindForm().Right - 100, Browser.FindForm().Bottom - 100);
                        Application.DoEvents();
                        Cursor.Position = new System.Drawing.Point(Browser.FindForm().Right - 35, Browser.FindForm().Bottom - 35);
                        Application.DoEvents();
                        CursorHelper.DoLeftMouseClick();
                        Application.DoEvents();
                        Cursor.Position = new System.Drawing.Point(Browser.FindForm().Right - 100, Browser.FindForm().Bottom - 100);
                        Application.DoEvents();
                        //Workaround for keeping maximized flashplayer on top
                        Browser.FindForm().Activated += FormActivated;
                        InvokeScript("document.getElementById('player').focus();"); //Prevent play/pause problem
                        maximized = true;
                        maxTimer.Stop();
                        maxTimer.Dispose();
                    };
                    maxTimer.Interval = isPremium ? 15000 : 60000;
                    maxTimer.Start();
                }
                ProcessComplete.Finished = true;
                ProcessComplete.Success = true;
            }
            return EventResult.Complete();
        }
        public override EventResult BrowserDocumentComplete()
        {
            MessageHandler.Info("Url: {0}, login: {1}, clicked: {2}, maximized: {3}", Url, login.ToString(), clicked.ToString(), maximized.ToString());
            if (login)
            {
                if (Url == "about:blank")
                {
                    login = false;
                    ProcessComplete.Finished = true;
                    ProcessComplete.Success = true;

                }
                else if (clicked && Url != loginUrl)
                {
                    login = false;
                    ProcessComplete.Finished = true;
                    ProcessComplete.Success = true;
                }
                else
                {
                    InvokeScript("document.getElementById('login-email').value = '" + username + "';");
                    InvokeScript("document.getElementById('login-password').value = '" + password + "';");
                    InvokeScript("document.getElementById('remember-me-checkbox').checked = false;");
                    InvokeScript("setTimeout(\"document.getElementsByClassName('button-submit')[0].click()\", 2000);");
                    clicked = true;
                }
            }
            else
            {
                InvokeScript("setTimeout(\"document.getElementsByClassName('play-button')[0].click()\", 2000);");
                System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                timer.Tick += (object sender, EventArgs e) =>
                {
                    if (_showLoading) HideLoading();
                    if (!maximized)
                    {
                        maximized = true;
                        //Workaround for keeping maximized flashplayer on top
                        Browser.FindForm().Activated += FormActivated;
                        Cursor.Position = new System.Drawing.Point(Browser.FindForm().Location.X + 20, Browser.Location.Y + 200);
                        Application.DoEvents();
                        Thread.Sleep(1000);
                        //Click only once
                        CursorHelper.DoLeftMouseClick();
                        Application.DoEvents();
                        Thread.Sleep(500);
                    }
                    System.Windows.Forms.SendKeys.Send("f");
                    timer.Stop();
                    timer.Dispose();
                };

                timer.Interval = 4500;
                timer.Start();
                ProcessComplete.Finished = true;
                ProcessComplete.Success = true;

            }
            return EventResult.Complete();
        }
Esempio n. 47
0
        void SessionThreadStart()
        {
            Monitor.Enter(sessionThread);
            {
                try
                {
                    sessionThreadControl = new Control();
                    sessionThreadControl.CreateControl();

                    session = TtlLiveSingleton.Get();

                    dataTimer = new Timer();
                    dataTimer.Interval = 100;
                    dataTimer.Tick += new EventHandler(dataTimer_Tick);

                    notificationTimer = new Timer();
                    notificationTimer.Interval = 100;
                    notificationTimer.Tick += new EventHandler(notificationTimer_Tick);
                    notificationTimer.Start();
                }
                catch (Exception ex)
                {
                    sessionThreadInitException = ex;
                    TtlLiveSingleton.Dispose();
                }
                Monitor.Pulse(sessionThread);
            }
            Monitor.Exit(sessionThread);

            //Create a message pump for this thread
            Application.Run(applicationContext);

            //Dispose of all stuff on this thread
            dataTimer.Stop();
            dataTimer.Dispose();

            notificationTimer.Stop();
            notificationTimer.Dispose();

            TtlLiveSingleton.Dispose();
            sessionThreadControl.Dispose();

            return;
        }
 public override Entities.EventResult BrowserDocumentComplete()
 {
     MessageHandler.Info("KatsomoConnector - Url: {0}", Url);
     if (Url != "about:blank")
     {
         System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
         timer.Tick += (object sender, EventArgs e) =>
         {
             timer.Stop();
             timer.Dispose();
             InvokeScript(Properties.Resources.Katsomo);
             InvokeScript("setTimeout(\"myZoom()\", 500);");
             if (showLoading)
                 HideLoading();
         };
         timer.Interval = 4500;
         timer.Start();
     }
     ProcessComplete.Finished = true;
     ProcessComplete.Success = true;
     return EventResult.Complete();
 }
Esempio n. 49
0
        public void Initialize()
        {
            this.ClientSize = new Size(600, 600);
            this.MinimumSize = new Size(600, 530);
            this.BackColor = Color.WhiteSmoke;
            this.Text = null;
            ResourceManager resourcemanager
            = new ResourceManager("MyMap.Properties.Resources"
                     , Assembly.GetExecutingAssembly());
            this.Icon = (Icon)resourcemanager.GetObject("F_icon");
            MainFormText();
            //this.DoubleBuffered = true;

            // Hide the form so it seems like it closes faster
            this.Closing += (sender, e) => {
                this.Hide();
            };

            // Sends the scroll event to the map.
            this.MouseWheel += (object o, MouseEventArgs mea) =>
            {
                map.OnMouseScroll(o, new MouseEventArgs(mea.Button,
                                                        mea.Clicks,
                                                        mea.X - map.Location.X,
                                                        mea.Y - map.Location.Y,
                                                        mea.Delta));
            };

            #region UI Elements

            StreetSelectBox fromBox, toBox, viaBox;
            Label fromLabel, toLabel, viaLabel, checkLabel;
            MapDragButton startButton, endButton, viaButton, myBike, myCar;
            GroupBox radioBox;
            RadioButton fastButton, shortButton;
            ToolTip toolTipStart = new ToolTip(),
                    toolTipEnd = new ToolTip(),
                    toolTipVia = new ToolTip(),
                    toolTipBike = new ToolTip(),
                    toolTipCar = new ToolTip(),
                    toolTipCheckBike = new ToolTip(),
                    toolTipCheckCar = new ToolTip(),
                    toolTipCheckPT = new ToolTip(),
                    toolTipStartBox = new ToolTip(),
                    toolTipViaBox = new ToolTip(),
                    toolTipEndBox = new ToolTip();

            map = new MapDisplay(10, 110, this.ClientSize.Width - 20, this.ClientSize.Height - 120, loadingThread);
            map.Anchor = (AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom);
            this.Controls.Add(map);

            fromLabel = new Label();
            toLabel = new Label();
            viaLabel = new Label();
            ptCheck = new CheckBox();
            carCheck = new CheckBox();
            bikeCheck = new CheckBox();
            checkLabel = new Label();
            radioBox = new GroupBox();
            fastButton = new RadioButton();
            shortButton = new RadioButton();

            startButton = new MapDragButton(map, (Bitmap)resourcemanager.GetObject("start"), ButtonMode.From, this, true);
            endButton = new MapDragButton(map, (Bitmap)resourcemanager.GetObject("end"), ButtonMode.To, this, true);
            viaButton = new MapDragButton(map, (Bitmap)resourcemanager.GetObject("via"), ButtonMode.Via, this, false);
            myBike = new MapDragButton(map, (Bitmap)resourcemanager.GetObject("bike"), ButtonMode.NewBike, this, false);
            myCar = new MapDragButton(map, (Bitmap)resourcemanager.GetObject("car"), ButtonMode.NewCar, this, false);

            fromBox = new StreetSelectBox(map, loadingThread, IconType.Start, startButton, this);
            toBox = new StreetSelectBox(map, loadingThread, IconType.End, endButton, this);
            viaBox = new StreetSelectBox(map, loadingThread, IconType.Via, viaButton, this);

            fromBox.Location = new Point(100, 8);
            fromBox.Size = new Size(200, 30);
            toolTipStartBox.SetToolTip(fromBox, "Search for streets, press Enter to place from icon.");
            this.Controls.Add(fromBox);

            viaBox.Location = new Point(100, 38);
            viaBox.Size = new Size(200, 30);
            toolTipStartBox.SetToolTip(fromBox, "Search for streets, press Enter to place via icon.");
            this.Controls.Add(viaBox);

            toBox.Location = new Point(100, 68);
            toBox.Size = new Size(200, 30);
            toolTipStartBox.SetToolTip(fromBox, "Search for streets, press Enter to place to icon.");
            this.Controls.Add(toBox);

            fromLabel.Text = "From:";
            fromLabel.Font = new Font("Microsoft Sans Serif", 10);
            fromLabel.Location = new Point(10, 8);
            fromLabel.Size = new Size(45, 20);
            this.Controls.Add(fromLabel);

            viaLabel.Text = "Via:";
            viaLabel.Font = new Font("Microsoft Sans Serif", 10);
            viaLabel.Location = new Point(10, 38);
            viaLabel.Size = new Size(45, 20);
            this.Controls.Add(viaLabel);

            toLabel.Text = "To:";
            toLabel.Font = new Font("Microsoft Sans Serif", 10);
            toLabel.Location = new Point(10, 68);
            toLabel.Size = new Size(45, 20);
            this.Controls.Add(toLabel);

            startButton.Location = new Point(55, 3);
            startButton.Size = new Size(40, 32);
            //startButton.Click += (object o, EventArgs ea) => { map.BMode = ButtonMode.From; };
            startButton.FlatStyle = FlatStyle.Flat;
            startButton.BackgroundImage = (Bitmap)resourcemanager.GetObject("start");
            startButton.FlatAppearance.BorderColor = backColor;
            startButton.FlatAppearance.MouseOverBackColor = backColor;
            startButton.FlatAppearance.MouseDownBackColor = backColor;
            toolTipStart.SetToolTip(startButton, "Drag icon to map to set your start location");
            this.Controls.Add(startButton);

            viaButton.Location = new Point(55, 33);
            viaButton.Size = new Size(40, 32);
            //viaButton.Click += (object o, EventArgs ea) => { map.BMode = ButtonMode.Via; };
            viaButton.BackgroundImage = (Bitmap)resourcemanager.GetObject("via");
            viaButton.FlatStyle = FlatStyle.Flat;
            viaButton.FlatAppearance.BorderColor = backColor;
            viaButton.FlatAppearance.MouseOverBackColor = backColor;
            viaButton.FlatAppearance.MouseDownBackColor = backColor;
            toolTipVia.SetToolTip(viaButton, "Drag icon to map to add a through location");
            this.Controls.Add(viaButton);

            endButton.Location = new Point(55, 63);
            endButton.Size = new Size(40, 32);
            //endButton.Click += (object o, EventArgs ea) => { map.BMode = ButtonMode.To;};
            endButton.BackgroundImage = (Bitmap)resourcemanager.GetObject("end");
            endButton.FlatStyle = FlatStyle.Flat;
            endButton.FlatAppearance.BorderColor = backColor;
            endButton.FlatAppearance.MouseOverBackColor = backColor;
            endButton.FlatAppearance.MouseDownBackColor = backColor;
            toolTipEnd.SetToolTip(endButton, "Drag icon to map to set your end location");
            this.Controls.Add(endButton);

            checkLabel.Location = new Point(309, 8);
            checkLabel.Text = "Enable/Disable";
            checkLabel.Font = new Font("Microsoft Sans Serif", 10);
            checkLabel.Size = new Size(130, 20);
            this.Controls.Add(checkLabel);

            bikeCheck.Location = new Point(309, 29);
            bikeCheck.Size = new Size(34, 34);
            bikeCheck.Appearance = Appearance.Button;
            bikeCheck.BackgroundImage = (Bitmap)resourcemanager.GetObject("bike_check");
            bikeCheck.FlatStyle = FlatStyle.Flat;
            bikeCheck.FlatAppearance.CheckedBackColor = Color.FromArgb(224, 224, 224);
            bikeCheck.Checked = true;
            bikeCheck.FlatAppearance.CheckedBackColor = Color.LightGreen;
            bikeCheck.BackColor = Color.Red;
            bikeCheck.CheckedChanged += (object o, EventArgs ea) => { map.UpdateRoute(); };
            toolTipCheckBike.SetToolTip(bikeCheck, "Disable Bicycles");
            bikeCheck.CheckedChanged += (object o, EventArgs ea) =>
            {
                toolTipCheckBike.RemoveAll();
                if (bikeCheck.Checked)
                    toolTipCheckBike.SetToolTip(bikeCheck, "Disable Bicycles");
                else
                    toolTipCheckBike.SetToolTip(bikeCheck, "Enable Bicycles");
            };
            this.Controls.Add(bikeCheck);

            carCheck.Location = new Point(354, 29);
            carCheck.Size = new Size(34, 34);
            carCheck.Appearance = Appearance.Button;
            carCheck.BackgroundImage = (Bitmap)resourcemanager.GetObject("car_check");
            carCheck.FlatStyle = FlatStyle.Flat;
            carCheck.FlatAppearance.CheckedBackColor = Color.FromArgb(224, 224, 224);
            carCheck.Checked = true;
            carCheck.FlatAppearance.CheckedBackColor = Color.LightGreen;
            carCheck.BackColor = Color.Red;
            carCheck.CheckedChanged += (object o, EventArgs ea) => { map.UpdateRoute(); };
            toolTipCheckCar.SetToolTip(carCheck, "Disable Cars");
            carCheck.CheckedChanged += (object o, EventArgs ea) =>
            {
                toolTipCheckCar.RemoveAll();
                if (carCheck.Checked)
                    toolTipCheckCar.SetToolTip(carCheck, "Disable Cars");
                else
                    toolTipCheckCar.SetToolTip(carCheck, "Enable Cars");
            };
            this.Controls.Add(carCheck);

            ptCheck.Location = new Point(399, 29);
            ptCheck.Size = new Size(34, 34);
            ptCheck.Appearance = Appearance.Button;
            ptCheck.BackgroundImage = (Bitmap)resourcemanager.GetObject("ov");
            ptCheck.FlatStyle = FlatStyle.Flat;
            ptCheck.FlatAppearance.CheckedBackColor = Color.FromArgb(224, 224, 224);
            ptCheck.Checked = true;
            ptCheck.FlatAppearance.CheckedBackColor = Color.LightGreen;
            ptCheck.BackColor = Color.Red;
            ptCheck.CheckedChanged += (object o, EventArgs ea) => { map.UpdateRoute(); };
            toolTipCheckPT.SetToolTip(ptCheck, "Disable Public Transport");
            ptCheck.CheckedChanged += (object o, EventArgs ea) =>
            {
                toolTipCheckPT.RemoveAll();
                if (ptCheck.Checked)
                    toolTipCheckPT.SetToolTip(ptCheck, "Disable Public Transport");
                else
                    toolTipCheckPT.SetToolTip(ptCheck, "Enable Public Transport");
            };
            this.Controls.Add(ptCheck);

            myBike.Location = new Point(310, 74);
            myBike.Size = new Size(32, 32);
            myBike.BackgroundImage = (Bitmap)resourcemanager.GetObject("bike");
            myBike.FlatStyle = FlatStyle.Flat;
            myBike.FlatAppearance.BorderColor = backColor;
            myBike.FlatAppearance.MouseOverBackColor = backColor;
            myBike.FlatAppearance.MouseDownBackColor = backColor;
            myBike.FlatAppearance.BorderSize = 0;
            toolTipBike.SetToolTip(myBike, "Drag icon to map to place a personal bycicle");
            this.Controls.Add(myBike);

            myCar.Location = new Point(355, 74);
            myCar.Size = new Size(32, 32);
            myCar.BackgroundImage = (Bitmap)resourcemanager.GetObject("car");
            myCar.FlatStyle = FlatStyle.Flat;
            myCar.FlatAppearance.BorderColor = backColor;
            myCar.FlatAppearance.MouseOverBackColor = backColor;
            myCar.FlatAppearance.MouseDownBackColor = backColor;
            myCar.FlatAppearance.BorderSize = 0;
            toolTipCar.SetToolTip(myCar, "Drag icon to map to place a personal car");
            this.Controls.Add(myCar);

            radioBox.Location = new Point(445, 8);
            radioBox.Size = new Size(80, 65);
            radioBox.Text = "Route Options";

            fastButton.Location = new Point(450, 23);
            fastButton.Size = new Size(67, 17);
            fastButton.Text = "Fastest";
            fastButton.Checked = true;
            fastButton.CheckedChanged += (object o, EventArgs ea) => { if (fastButton.Checked) { map.RouteMode = RouteMode.Fastest; } };
            this.Controls.Add(fastButton);

            shortButton.Location = new Point(450, 48);
            shortButton.Size = new Size(67, 17);
            shortButton.Text = "Shortest";
            shortButton.CheckedChanged += (object o, EventArgs ea) => { if (shortButton.Checked) { map.RouteMode = RouteMode.Shortest; } };
            this.Controls.Add(shortButton);

            this.Controls.Add(radioBox);

            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = 10;
            timer.Tick += (object o, EventArgs ea) => {
                if (loadingThread.Graph != null && User != -1) { GraphLoaded(loadingThread.Graph, new EventArgs()); timer.Dispose(); } };
            timer.Start();

            this.GraphLoaded += (object o, EventArgs ea) => { Addvehicle(); this.Save(); };

            #endregion
        }
        private void CollapseFoldersWithSameNames()
        {
            if (needFolderCollapse == false)
            {
                return;
            }

            if (addon == null)
            {
                // this method can be called as a delegate after the timer expires
                // if the xml import fails addon will be null so we have nothing to 
                // do in that case.

                // this prevents a null reference exception on addon.Project line below
                return;
            }


            if ((addon.Project.ProjectStatus & 8) != 0)
            {
                System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                timer.Tick += (sender, args) =>
                {
                    this.CollapseFoldersWithSameNames();
                    timer.Stop();
                    timer.Dispose();
                };
                timer.Interval = 1;
                timer.Start();
                return;
            }

            addon.Project.BeginTransactionInNewTerr();
            try
            {
                needFolderCollapse = false;
                GMEConsole.Info.WriteLine("Collapse duplicate folder names into one...");
                this.CollapseFolders(this.project.RootFolder);
                this.CollapseLibraries(this.project.RootFolder);
                GMEConsole.Info.WriteLine("Removing empty duplicated folders...");
                this.RemoveEmptyDuplicatedFolders(this.project.RootFolder);
                GMEConsole.Info.WriteLine("Done.");
            }
            catch (Exception e)
            {
                GMEConsole.Info.WriteLine("Exception occurred while collapsing folders: " + e.Message);
                addon.Project.AbortTransaction();
                return;
            }
            addon.Project.CommitTransaction();
        }
Esempio n. 51
0
        static void Main(string[] Args)
        {
            // Connect the application to console to have proper output there if requested.
              bool consoleRedirectionWorked = Win32Api.RedirectConsole();

              // Start with command line parsing.
              string userDir = System.IO.Path.Combine(System.IO.Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
            "MySQL"), "Workbench");
              Logger.InitLogger(userDir);

              if (!consoleRedirectionWorked)
            Logger.LogError("Workbench", "Console redirection failed.\n");

              System.Reflection.Assembly asm = System.Reflection.Assembly.GetEntryAssembly();
              string baseDir = System.IO.Path.GetDirectoryName(asm.Location);
              WbOptions wbOptions = new WbOptions(baseDir, userDir, true);

              if (!wbOptions.parse_args(Args, asm.Location))
              {
            Logger.LogInfo("Workbench", "Command line params told us to shut down.\n");
            return;
              }

              PrintInitialLogInfo();

              Application.EnableVisualStyles();
              Application.SetCompatibleTextRenderingDefault(false);

              // Hook into the exception handling to establish our own handling.
              AppDomain currentDomain = AppDomain.CurrentDomain; // CLR
              currentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);

              Application.ThreadException += // Windows Forms
             new System.Threading.ThreadExceptionEventHandler(OnGuiUnhandledException);

              // Read some early values which cannot be stored in the preferences (since they are loaded
              // later) from registry.
              bool singleInstance = true;
              string lastVersion = "";
              string currentVersion = GetApplicationMetaInfo(ApplicationMetaInfo.Version);
              Logger.LogInfo("Workbench", "Current version given by meta info is: " + currentVersion + '\n');
              RegistryKey wbKey = Registry.CurrentUser;
              try
              {
            wbKey = wbKey.OpenSubKey(@"Software\Oracle\MySQL Workbench", false);
            if (wbKey != null)
            {
              if (wbKey.GetValue("DisableSingleInstance", 0).ToString() == "1")
            singleInstance = false;
              lastVersion = wbKey.GetValue("LastStartedAs", "").ToString();
            }
            else
              Registry.CurrentUser.CreateSubKey(@"Software\Oracle\MySQL Workbench");
              }
              catch (Exception e)
              {
            Logger.LogError("Workbench", "Error while checking single instance reg key: " + e.Message + '\n');
              }
              finally
              {
            if (wbKey != null)
              wbKey.Close();
              }

              // First check if this is the first instance of Workbench (if enabled).
              // The setting for single-instance is stored in the registry as it is Windows-only
              // and loading of the application settings happens later.
              if (singleInstance)
              {
            if (!ApplicationInstanceManager.CreateSingleInstance(
              Assembly.GetExecutingAssembly().GetName().Name, Args, SingleInstanceCallback))
            {
              Logger.LogInfo("Workbench", "Exiting as another instance of WB is already running.\n");
              return;
            }
              }

              // Give the main thread a proper name, so we can later check for it when needed.
              Thread.CurrentThread.Name = "mainthread";

              // Change the working dir to to application path.
              // This is necessary because all our internal data files etc. are located under the app dir
              // and WB could have been called from a different dir.
              string workdir = System.IO.Directory.GetCurrentDirectory();
              System.IO.Directory.SetCurrentDirectory(baseDir);

              // Next check if this is the first start of a new version of WB. In this case remove all
              // compiled python files. They will be automatically recreated and can produce problems
              // under certain circumstances.
              if (currentVersion != lastVersion)
              {
            Logger.LogInfo("Workbench", "This is the first start of a new version. Doing some clean up.\n");
            List<string> failed = new List<string>();
            RemoveCompiledPythonFiles(baseDir, failed);

            // TODO: decide if we wanna ask the user to remove those files manually or just ignore them.
              }

              // Some people don't have c:\windows\system32 in PATH, so we need to set it here
              // for WBA to find the needed commands
              String systemFolder = Environment.GetFolderPath(Environment.SpecialFolder.System);
              String cleanedPath = Environment.GetEnvironmentVariable("PATH");

              String []paths= cleanedPath.Split(new char[]{';'});
              cleanedPath = "";

              // Strip all python related dirs from PATH to avoid conflicts with other Python installations.
              foreach (String path in paths)
              {
            if (!path.ToLower().Contains("python"))
              cleanedPath = cleanedPath + ";" + path;
              }
              Environment.SetEnvironmentVariable("PATH", systemFolder + cleanedPath);
              Logger.LogInfo("Workbench", "Setting PATH to: " + systemFolder + cleanedPath + '\n');

              // Clear PYTHONPATH environment variable, as we do not need it but our python impl
              // seriously gets confused with it.
              Environment.SetEnvironmentVariable("PYTHONPATH", workdir + "\\python\\Lib;" + workdir + "\\python\\DLLs;" + workdir + "\\python");
              Environment.SetEnvironmentVariable("PYTHONHOME", workdir + "\\python");

              // Initialize forms stuff.
              MySQL.Forms.Manager formsManager = MySQL.Forms.Manager.get_instance(); // Creates the singleton.

              // init extra mforms things that are delegated to the frontend, indirectly through RecordsetWrapper in wbpublic
              MySQL.Grt.Db.RecordsetWrapper.init_mforms(MySQL.Grt.Db.RecordsetView.create);

              #region Runtime path check

              // Currently WB has trouble running from a path containing non-ASCII characters.
              // Actually, our third party libraries have (namely lua, python, ctemplate),
              // as they don't consider Unicode file names (encoded as UTF-8) which leads to file-not-found
              // errors. Refuse to work in such a path for now.
              foreach (Char c in baseDir)
            if (c > 0x7f)
            {
              MessageBox.Show("MySQL Workbench cannot be executed from a path that contains non-ASCII characters.\n"+
            "This problem is imposed by used third-party libraries.\n" +
            "Please run this application from the default installation path or at least a path which is all ASCII characters.",
            "MySQL Workbench Execution Problem", MessageBoxButtons.OK, MessageBoxIcon.Error);
              return;
            }

              #endregion

              #region Release check (outdated beta or rc version)

              // check the date of the executable and suggest to install a new version if this is a beta or rc
              if (GetApplicationMetaInfo(ApplicationMetaInfo.Configuration).ToUpper().IndexOf("BETA") >= 0 ||
            GetApplicationMetaInfo(ApplicationMetaInfo.Configuration).ToUpper().IndexOf("RC") >= 0)
              {
            DateTime fileDate = System.IO.File.GetCreationTime(Application.ExecutablePath);

            if (DateTime.Now.Subtract(fileDate).TotalDays > 45)
            {
              Logger.LogInfo("Workbench", "Found an old WB pre release. Showing warning.\n");
              if (MessageBox.Show("This version of MySQL Workbench is older than 45 days and most probably outdated. "
            + Environment.NewLine
            + "It is recommended to upgrade to a newer version if available. "
            + Environment.NewLine
            + "Press [OK] to check for a new version and exit the application. "
            + "Press [Cancel] to continue using this version.",
            "MySQL Workbench Version Outdated", MessageBoxButtons.OKCancel,
            MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.OK)
              {
            CheckForNewVersion();
            return;
              }
            }
              }

              #endregion

              #region Variables and Splashscreen

              #endregion

              #region Initialize GRT

              // Try to instantiate the Workbench context and the GRT Manager and catch exceptions
              try
              {
            // Create Workbench Context
            wbContext = new WbContext(wbOptions.Verbose);

            if (wbContext != null)
            {
              // Create the GRT Manager instance
              grtManager = wbContext.get_grt_manager();
            }
              }
              catch (Exception ex)
              {
            HandleException(ex);
              }

              #endregion

              // If the Workbench Context and GRT Manager were successfully created,
              // initialize the application
              if (wbContext != null && grtManager != null)
              {
            #region Initialize Callbacks and Mainform

            mainForm = new MainForm(wbContext);

            // Initialize the Workbench context
            ManagedApplication formsApplication = new ManagedApplication(
              new AppCommandDelegate(mainForm.ApplicationCommand),
              mainForm.dockDelegate);

            callbacks = new WbFrontendCallbacks(
              new WbFrontendCallbacks.StrStrStrStrDelegate(mainForm.ShowFileDialog),
              new WbFrontendCallbacks.VoidStrDelegate(mainForm.ShowStatusText),
              new WbFrontendCallbacks.BoolStrStrFloatDelegate(mainForm.ShowProgress),
              new WbFrontendCallbacks.CanvasViewStringStringDelegate(mainForm.CreateNewDiagram),
              new WbFrontendCallbacks.VoidCanvasViewDelegate(mainForm.DestroyView),
              new WbFrontendCallbacks.VoidCanvasViewDelegate(mainForm.SwitchedView),
              new WbFrontendCallbacks.VoidCanvasViewDelegate(mainForm.ToolChanged),
              new WbFrontendCallbacks.IntPtrGRTManagerModuleStrStrGrtListFlagsDelegate(mainForm.OpenPlugin),
              new WbFrontendCallbacks.VoidIntPtrDelegate(mainForm.ShowPlugin),
              new WbFrontendCallbacks.VoidIntPtrDelegate(mainForm.HidePlugin),
              new WbFrontendCallbacks.VoidRefreshTypeStringIntPtrDelegate(mainForm.RefreshGUI),
              new WbFrontendCallbacks.VoidBoolDelegate(mainForm.LockGUI),
              new WbFrontendCallbacks.VoidStrDelegate(mainForm.PerformCommand),
              new WbFrontendCallbacks.BoolDelegate(mainForm.QuitApplication));

            // TODO: check return value and show error message.
            // Currently the return value is always true. In case of an error an exception is raised.
            // That should change.
            wbContext.init(callbacks, wbOptions,
              new WbContext.VoidStrUIFormDelegate(mainForm.CreateMainFormView)
            );

            // command registration must be done after WBContext init
            mainForm.PostInit();

            // Set the Application.Idle event handler
            Application.Idle += new EventHandler(OnApplicationIdle);

            // Don't call the idle handler too often.
            timer = new System.Windows.Forms.Timer();
            timer.Interval = 100;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();

            // Trigger GRT idle tasks
            grtManager.perform_idle_tasks();

            // Setup Menus
            wbContext.validate_edit_menu();
            mainForm.Show();
            Logger.LogInfo("Workbench", "UI is up\n");

            // Tell the backend our main UI is ready. This will also load a model if it was given via command line
            // and opens the overview form for it.
            wbContext.finished_loading(wbOptions);

            // Right before we go to work and everything was loaded write the current version to registry
            // to allow us later to find out if we ran a new version the first time.
            try
            {
              wbKey = Registry.CurrentUser.OpenSubKey(@"Software\Oracle\MySQL Workbench", true);
              if (wbKey != null)
            wbKey.SetValue("LastStartedAs", currentVersion);
            }
            catch (Exception e)
            {
              Logger.LogError("Workbench", "Couldn't write regkey LastStartedAs: " + e.Message + '\n');
            }
            finally
            {
              if (wbKey != null)
            wbKey.Close();
            }

            // Start the Application if we are not already shutting down.
            if (!wbContext.is_quitting())
            {
              try
              {
            Logger.LogInfo("Workbench", "Running the application\n");
            Application.Run(new ApplicationContext(mainForm));
              }
              catch (Exception e)
              {
            HandleException(e);
              }
            }

            #endregion

            Logger.LogInfo("Workbench", "Shutting down Workbench\n");

            timer.Stop();
            timer.Dispose();

            // shutdown wb context
            if (wbContext != null)
            {
              while (wbContext.is_busy())
            wbContext.flush_idle_tasks();

              wbContext.finalize();
              wbContext.Dispose();
            }
            formsApplication.Dispose();
            formsManager.Dispose();

            GC.Collect();
              }

              Win32Api.ReleaseConsole();

              Logger.LogInfo("Workbench", "Done\n");
        }
Esempio n. 52
0
        private void btnThrowPassKey_Click(object sender, EventArgs e)
        {
            ((Button)sender).Enabled = false;
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
            t.Interval = 5000; // 5sec
            t.Tick += (s, ea) => { ((Button)sender).Enabled = true; t.Stop(); t.Dispose(); };

            InputSimulator.SimulateKeyDown(VirtualKeyCode.RETURN);        // 'Enter'
            InputSimulator.SimulateTextEntry(@"God_H\,g,d@13");
            InputSimulator.SimulateKeyDown(VirtualKeyCode.RETURN);        // 'Enter'

            t.Start();
        }
Esempio n. 53
0
		private AnsiLog Init_AnsiLog([NotNull] ConEmuStartInfo startinfo)
		{
			var ansilog = new AnsiLog(_dirTempWorkingFolder);
			_lifetime.Add(() => ansilog.Dispose());
			if(startinfo.AnsiStreamChunkReceivedEventSink != null)
				ansilog.AnsiStreamChunkReceived += startinfo.AnsiStreamChunkReceivedEventSink;

			// Do the pumping periodically (TODO: take this to async?.. but would like to keep the final evt on the home thread, unless we go to tasks)
			// TODO: if ConEmu writes to a pipe, we might be getting events when more data comes to the pipe rather than poll it by timer
			var timer = new Timer() {Interval = (int)TimeSpan.FromSeconds(.1).TotalMilliseconds, Enabled = true};
			timer.Tick += delegate { ansilog.PumpStream(); };
			_lifetime.Add(() => timer.Dispose());

			return ansilog;
		}
Esempio n. 54
0
        private void ShowTipMessage(string msg)
        {
            ShowGeneralMessage(msg);

            var s = new System.Windows.Forms.Timer();
            s.Interval = 5000;
            s.Start();
            s.Tick += (sender, args) => { generalmsg.Visible = false; s.Stop(); s.Dispose(); };
        }
Esempio n. 55
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            if (Environment.OSVersion.Version.Major >= 6.0) // если версия выше, делаём всё черным (черный GDI прозрачен)
            {
                if (DwmApi.DwmIsCompositionEnabled())
                {
                    button1.BackColor = Color.Black;
                    button2.BackColor = Color.Black;
                    button3.BackColor = Color.Black;
                    button4.BackColor = Color.Black;
                    button5.BackColor = Color.Black;
                    panel1.BackColor = Color.Black;
                    OnClientArea();
                }
            }

            if (!System.IO.Directory.Exists(vars.VARS.Directory)) // если директории каким-то образом не оказалось, создаём её и кидаем туда файл ошибок
            {
                System.IO.Directory.CreateDirectory(vars.VARS.Directory);
                System.IO.File.Create(vars.VARS.Directory + "errors.txt");
            }

            bool flag = true;
            InternetConnectionState flags = 0;
            bool InternetConnect = InternetGetConnectedState(ref flags, 0); // проверяем соединение с интернетом

            while (!InternetConnect) // пока не появится, будет цикл повторяться
            {
                if (flag)
                {
                    MessageBox.Show("Сервер временно недоступен!\nПрограмма подключится, когда появится соединение!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    flag = false;
                    notifyIcon1.Visible = true;
                }
                Application.DoEvents();
                Thread.Sleep(2000);
                InternetConnect = InternetGetConnectedState(ref flags, 0);
            }

            AccessForm acc = new AccessForm(); // создаём форму авторизации
            if (acc.ShowDialog() == DialogResult.OK) // если ок, выполняем
            {
                GeneralMethods.tryGetSettings(); // читаем настройки
                if (!vars.VARS.ExitOnCloser) // устанавливаем режим сворачивания
                    MinimizeBox = false;
                if (!vars.VARS.Sound) // устанавливаем в верное положение картинку звука
                    button1.Image = global::IMV.Properties.Resources._1299773905_no_sound;
                wait = new System.Windows.Forms.Timer(); // создаём таймер
                wait.Interval = 4000;
                wait.Tick += new EventHandler(wait_Tick);
                wait.Start(); // запускаем таймер
                Thread newThrd = new Thread(new ThreadStart(start.getProfiles)); // Получение списка контактов
                newThrd.Start();
                while (newThrd.IsAlive) // приложение отправляет сообщения виндовс пока поток не завершился
                    Application.DoEvents();
                wait.Stop();
                wait.Dispose();
                if (wtcreate) // если открывалось окно ожидания, то уничтожаем его
                    wt.Dispose();
                acc.Dispose();
                GeneralMethods.AddItem(); // добавляем контакты в список
                if (vars.VARS.Frequency) // если включена настройка
                    GeneralMethods.tryGetFrequency(); // пытаемся загрузить частоту
                myContactList1.Sort(); // сортируем
                StartWork(); // Запуск "отлова" обновлений
            }
            else
                Application.Exit();
        }
Esempio n. 56
0
 private void MenuViewForm_Shown(object sender, EventArgs e)
 {
     var timer = new Timer
     {
         Interval = 1,
         Enabled = true
     };
     timer.Tick += (o, args) =>
     {
         if (Opacity < _windowOpacity)
         {
             var opacity = _windowOpacity / _windowFadeInDuration + Opacity;
             if (opacity <= _windowOpacity)
             {
                 Opacity = opacity;
                 return;
             }
         }
         if (WinApi.UnsafeNativeMethods.GetForegroundWindow() != Handle)
             WinApi.UnsafeNativeMethods.SetForegroundWindow(Handle);
         timer.Dispose();
     };
 }
Esempio n. 57
0
        private void UnpackStart_Click(object sender, EventArgs e)
        {
            if (!isAnalogSignals.Checked && !isDiscreteSignals.Checked) return;

            if (AnalogSignalListBox.SelectedIndices.Count > 256 || DiscreteSignalListBox.SelectedIndices.Count > 256)
            {
                DialogResult dr = MessageBox.Show("You have selected more than 256 signals. Unfortunately, old versions of MS Excel can't read more than 256 columns, so use newer versions of MS Excel to represent more signals. Do you want to continue unpacking?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dr != DialogResult.Yes) return;
            }

            UnpackStart.Text = "Wait...";
            UnpackStart.Enabled = false;

            Thread treadAnalog;
            Thread treadDiscrete;

            DateTime fieldStartTime = new DateTime((int)numericStartYear.Value, (int)numericStartMonth.Value, (int)numericStartDay.Value, (int)numericStartHour.Value, (int)numericStartMinute.Value, (int)numericStartSecond.Value);
            DateTime fieldStopTime = new DateTime((int)numericStartYear.Value, (int)numericEndMonth.Value, (int)numericEndDay.Value, (int)numericEndHour.Value, (int)numericEndMinute.Value, (int)numericEndSecond.Value);

            long fieldStartTimeInSeconds = ConvertDateTimeToSeconds(fieldStartTime);
            long fieldStopTimeInSeconds = ConvertDateTimeToSeconds(fieldStopTime);

            try
            {
                if (fieldStartTimeInSeconds >= _stopTimeInSeconds || fieldStartTimeInSeconds < _startTimeInSeconds) throw new Exception("Wrong starting time period!");
                if (fieldStopTimeInSeconds > _stopTimeInSeconds || fieldStopTimeInSeconds <= _startTimeInSeconds) throw new Exception("Wrong ending time period!");

                List<int> analogIndexes = new List<int>();
                List<int> discreteIndexes = new List<int>();

                analogIndexes.AddRange(AnalogSignalListBox.SelectedIndices.Cast<int>());
                discreteIndexes.AddRange(DiscreteSignalListBox.SelectedIndices.Cast<int>());

                RegistrationReader regReader = new RegistrationReader(projectPath + registrationPath, analogIndexes, discreteIndexes, _registrationIndecies[RegFragments.SelectedIndex], _regPointerAnalog, _regPointerDiscrete, fieldStartTimeInSeconds, fieldStopTimeInSeconds, _aSignalBase, _dSignalBase);

                treadAnalog = new Thread(regReader.UnpackAnalogSignals);
                treadDiscrete = new Thread(regReader.UnpackDiscreteSignals);

                bool unpackAnalogIsFinished = !isAnalogSignals.Checked, unpackDiscreteIsFinished = !isDiscreteSignals.Checked;

                int maximumOfBar = Convert.ToInt32
                        (((float)(fieldStopTimeInSeconds) - (float)(fieldStartTimeInSeconds)) * 100 / ((float)(_stopTimeInSeconds) - (float)(_startTimeInSeconds))
                        );

                AnalogSignalsProgressBar.Maximum = maximumOfBar == 0 ? 1 : maximumOfBar;
                DiscreteSignalsProgressBar.Maximum = maximumOfBar == 0 ? 1 : maximumOfBar;

                if (isAnalogSignals.Checked)
                {
                    treadAnalog.Start();

                    var timer = new System.Windows.Forms.Timer();

                    timer.Interval = 100;
                    timer.Tick += (s, a) =>
                        {
                            if (regReader.AnalogSignalsUnpackingCompleted) AnalogSignalsProgressBar.Value = AnalogSignalsProgressBar.Maximum;
                            else AnalogSignalsProgressBar.Value = regReader.AnalogSignalsProgress;

                            if (regReader.AnalogSignalsProgress >= AnalogSignalsProgressBar.Maximum)
                            {
                                timer.Stop();
                                unpackAnalogIsFinished = true;
                            }
                            if (unpackAnalogIsFinished && unpackDiscreteIsFinished)
                            {
                                timer.Dispose();
                                UnpackStart.Enabled = true;
                                UnpackStart.Text = "Unpack";
                            }
                        };
                    timer.Start();
                }

                if (isDiscreteSignals.Checked)
                {
                    treadDiscrete.Start();

                    var timer = new System.Windows.Forms.Timer();

                    timer.Interval = 100;
                    timer.Tick += (s, a) =>
                    {
                        if (regReader.DiscreteSignalsUnpackingCompleted) DiscreteSignalsProgressBar.Value = DiscreteSignalsProgressBar.Maximum;
                        else DiscreteSignalsProgressBar.Value = regReader.DiscreteSignalsProgress;

                        if (regReader.DiscreteSignalsProgress >= DiscreteSignalsProgressBar.Maximum)
                        {
                            timer.Stop();
                            unpackDiscreteIsFinished = true;
                        }
                        if (unpackAnalogIsFinished && unpackDiscreteIsFinished)
                        {
                            timer.Dispose();
                            UnpackStart.Enabled = true;
                            UnpackStart.Text = "Unpack";
                        }
                    };
                    timer.Start();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 public void fadeInOut(Func<int> call)
 {
     System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
     timer.Interval = 2;
     int currentStep = 0;
     int fadeSteps = 20;
     int totalSteps = fadeSteps * 2 + 16;
     Boolean runTick = true;
     timer.Tick += (arg1, arg2) =>
     {
         if (runTick)
         {
             currentStep++;
             if (currentStep <= fadeSteps)
             {
                 Opacity = ((double)(fadeSteps - currentStep) / fadeSteps);
             }
             else if (currentStep == fadeSteps + 1)
             {
                 runTick = false;
                 call();
                 runTick = true;
             }
             else if (currentStep <= totalSteps)
             {
                 Opacity = ((double)(fadeSteps - totalSteps + currentStep)) / fadeSteps;
             }
             else
             {
                 timer.Stop();
                 timer.Dispose();
             }
         }
     };
     timer.Start();
 }
        public override Entities.EventResult BrowserDocumentComplete()
        {
            string jsCode;
            switch (_currentState)
            {
                case State.Login:

                    if (Url.Contains("/Login?"))
                    {
                        jsCode = "document.getElementById('email').value = '" + _username + "'; ";
                        jsCode += "document.getElementById('password').value = '" + _password + "'; ";
                        if (_rememberLogin)
                        {
                            jsCode += "document.getElementById('RememberMe').checked = true; ";
                        }
                        else
                        {
                            jsCode += "document.getElementById('RememberMe').checked = false; ";
                        }
                        jsCode += "document.getElementById('login-form-contBtn').click();";
                        InvokeScript(jsCode);
                        _currentState = State.Profile;
                    }
                    else
                    {
                        //Url = "http://www.netflix.com/browse";
                        Url = "https://www.netflix.com/SwitchProfile?tkn=" + _profile;
                        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                        timer.Tick += (object sender, EventArgs e) =>
                        {
                            timer.Stop();
                            timer.Dispose();
                            Url = @"http://www.netflix.com/Kids";
                            _currentState = State.ReadyToPlay;
                        };
                        timer.Interval = 3000;
                        timer.Start();
                    }
                    break;
                case State.Profile:
                    if (Url.Contains("/browse") || Url.Contains("/WiHome") || Url.Contains("/Kids") || Url.Contains("/ProfilesGate"))
                    {
                        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                        timer.Tick += (object sender, EventArgs e) =>
                        {
                            timer.Stop();
                            timer.Dispose();
                            Url = @"http://www.netflix.com/Kids";
                            _currentState = State.ReadyToPlay;
                        };
                        timer.Interval = 3000;
                        timer.Start();
                        Url = "https://www.netflix.com/SwitchProfile?tkn=" + _profile;
                    } 
                    break;
                case State.ReadyToPlay:
                    if (Url.Contains("/browse") || Url.Contains("/WiHome") || Url.Contains("/Kids"))
                    {
                        ProcessComplete.Finished = true;
                        ProcessComplete.Success = true;
                    }
                    break;
                case State.StartPlay:
                case State.Playing:
                    if (Url.Contains("movieid"))
                    {
                        if (_showLoading)
                            HideLoading();
                        _currentState = State.Playing;
                        ProcessComplete.Finished = true;
                        ProcessComplete.Success = true;
                    }
                    break;
            }
            return EventResult.Complete();
        }
        private void CleanupAndExit(Timer timer)
        {
            // safely dispose timer
            try
            {
                if (timer != null)
                {
                    timer.Tick -= new EventHandler(timer_Tick);
                    timer.Stop();
                    timer.Dispose();
                }
            }
            catch (Exception ex)
            {
                Trace.Fail("Unexpected exception disposing exception: " + ex.ToString());
            }

            // close the form
            Close();
        }