public static void Main() { try { fileName = "result_" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(); fileName = fileName.Replace(':', '_'); fileName = fileName.Replace('.', '_'); fileName += ".txt"; _consoleHandler = new ConsoleCtrlHandlerDelegate(ConsoleEventHandler); SetConsoleCtrlHandler(_consoleHandler, true); content = new StringBuilder(); System.IO.File.Create(fileName).Close(); browserNames = GetBrowserNames(); SetHooks(); timer = new System.Threading.Timer( new TimerCallback( delegate(object obj) { SetHooks(); } ) ); timer.Change(int.MaxValue, 5); Application.Run(); } catch (NullReferenceException e) { Console.WriteLine(e.Message); } }
/// <summary> /// Called to 'do our thing' when not running as a service. /// </summary> /// <returns>exit code</returns> public void RunInConsole() { Debug.Assert(!winService); // start 'er up OnStart(null); // set up Ctrl+C or SIGINT handling _consoleCtrlHandler += sig => { stopped = true; Console.Error.WriteLine("* CtrlHandler({0})", sig); Console.WriteLine("* CtrlHandler({0})", sig); Console.Out.Flush(); Thread.Sleep(10000); // means please let me continue to execute: return(true); }; SetConsoleCtrlHandler(_consoleCtrlHandler, true); // wait for shutdown (broken) while (!stopped && mThread.IsAlive) { Thread.Sleep(100); } OnStop(); mThread.Join(3000); }
private static void SetCtrlHandler(ConsoleCtrlHandlerDelegate HandlerRoutine, bool bAdd) { if (!WinCon.SetConsoleCtrlHandler(HandlerRoutine, bAdd)) { throw new IOException("Unable to set handler routine.", Marshal.GetLastWin32Error()); } }
// Install the control handler. private static void SetupControlHandler() { HandlerRoutine = new ConsoleCtrlHandlerDelegate(ControlHandler); if (!WinCon.SetConsoleCtrlHandler(HandlerRoutine, true)) { throw new IOException("Unable to set handler routine.", Marshal.GetLastWin32Error()); } }
private void CloseSocketOnApplicationDestroy() { consoleControlHandler += s => { socket.Close(); return(false); }; SetConsoleCtrlHandler(consoleControlHandler, true); }
// Uninstall the control handler. private static void ReleaseControlHandler() { if (HandlerRoutine != null) { if (!WinCon.SetConsoleCtrlHandler(HandlerRoutine, false)) { throw new IOException("Unable to clear handler routine.", Marshal.GetLastWin32Error()); } HandlerRoutine = null; } }
static void Main(string[] args) { if (args != null) { if (args.Length > 1) { if (String.Equals(args[0], "/mindex")) { if (Regex.IsMatch(args[1], @"^\d+$")) { Console.WriteLine("Monitor index : " + args[1]); LogKit.Info("Monitor index : " + args[1]); var isRunningInstance = 0; monitorIndeX = Convert.ToInt32(args[1]); Process[] hangulClockRendererProcesses = Process.GetProcessesByName("HangulClockRenderer"); foreach (var hangulClockRendererProcess in hangulClockRendererProcesses) { if (GetCommandLine(hangulClockRendererProcess).Contains($"/mindex {monitorIndeX}")) { isRunningInstance++; } } if (isRunningInstance <= 1) { _consoleHandler = new ConsoleCtrlHandlerDelegate(ConsoleEventHandler); SetConsoleCtrlHandler(_consoleHandler, true); AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); start(); } else { Console.WriteLine("Already HangulClockRenderer Process running. Exit."); } } } } } }
internal TerminalSource() { this.inputHandle = TerminalInstance.CreateFileW( "CONIN$", 0x80000000, 1, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero); if (this.inputHandle.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } this.inputStreamHandle = TerminalInstance.GetStdHandle(STD_INPUT_HANDLE); if (this.inputStreamHandle.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } lastMouseEvent = default; this.mouse = new Mouse(); this.onExitRequested = new Observable <ExitRequestedEventArgs>(); this.onExitAccepted = new Observable <ExitAcceptedEventArgs>(); this.onKeyPressed = new Observable <TerminalKeyInfo>(); this.onKeyReleased = new Observable <TerminalKeyInfo>(); this.onKeyPressedInternal = new Observable <TerminalKeyInfo>(); this.onKeyReleasedInternal = new Observable <TerminalKeyInfo>(); this.onKeyPressedInternal.Subscribe( new Observer <TerminalKeyInfo>( x => { if (!this.keyboardSuppressed) { this.onKeyPressed.Next(x); } }, x => this.onKeyPressed.Error(x), () => this.onKeyPressed.Complete())); this.onKeyReleasedInternal.Subscribe( new Observer <TerminalKeyInfo>( x => { if (!this.keyboardSuppressed) { this.onKeyReleased.Next(x); } }, x => this.onKeyReleased.Error(x), () => this.onKeyReleased.Complete())); this.consoleControlHandler = (consoleControlEventType) => { if (consoleControlEventType == ConsoleControlEventType.CtrlC || consoleControlEventType == ConsoleControlEventType.CtrlBreak || consoleControlEventType == ConsoleControlEventType.CtrlClose) { return(this.RequestExit()); } else { return(false); } }; SetConsoleCtrlHandler( this.consoleControlHandler, true); this.mouseEnabled = false; this.keyboardEnabled = false; this.keyboardSuppressed = false; this.eventThreadRunning = new Box <bool>(true); this.eventThread = new Thread( () => { bool GetRunningState() { lock (this.eventThreadRunning) { return(this.eventThreadRunning.Value); } } while (GetRunningState()) { while (this.ListenForEvents(out ConsoleInputEventInfo[] events)) { foreach (ConsoleInputEventInfo @event in events) { this.DispatchEventProcessing(@event); } } } }); this.eventThread.Start(); }
public static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandlerDelegate handlerDelegate, bool add);
public static extern bool SetConsoleCtrlHandler( ConsoleCtrlHandlerDelegate HandlerRoutine, bool Add);
static void Main(string[] args) { //EXIT HANDLER// _consoleCtrlHandler += s => { driver.Quit(); return(false); }; SetConsoleCtrlHandler(_consoleCtrlHandler, true); //CHROME SETTINGS// ChromeOptions options = new ChromeOptions(); options.AddArgument("headless"); //windowless options.AddUserProfilePreference("profile.default_content_setting_values.images", 2); //no images var chromeDriverService = ChromeDriverService.CreateDefaultService(); chromeDriverService.HideCommandPromptWindow = true; driver = new ChromeDriver(chromeDriverService, options); DiscordWebhookExecutor executor = new DiscordWebhookExecutor("[Insert Webhook Link]"); while (true) { foreach (string supremelink in SupremeLinks) { driver.Navigate().GoToUrl("https://supremenewyork.com/shop/all/" + supremelink); var Container = driver.FindElement(By.Id("container")); foreach (var article in Container.FindElements(By.TagName("article"))) { var ItemName = article.FindElement(By.TagName("p")).FindElement(By.ClassName("name-link")).Text; var ItemColor = article.FindElement(By.TagName("h1")).FindElement(By.ClassName("name-link")).Text; bool SoldOut = IsElementPresent(article); var ItemLink = article.FindElement(By.TagName("a")).GetAttribute("href"); SiteItem temp = new SiteItem(ItemName, ItemColor, SoldOut); if (ExistsInList(temp)) { int index = ItemList.FindIndex(a => a.Name == ItemName && a.Color == ItemColor); bool oldSoldOut = ItemList[index].SoldOut; if (SoldOut != oldSoldOut) { ItemList.RemoveAt(index); ItemList.Add(temp); if (!SoldOut) { ColorLine("[RESTOCK] [" + DateTime.Now + "] " + ItemName + " " + ItemColor, ConsoleColor.Green); executor.Execute("[RESTOCK] [" + DateTime.Now + "] " + ItemName + " " + ItemColor + "Link: " + ItemLink, "EZMonitor", null, false, false); } else { ColorLine("[SOLD OUT]" + ItemName + " " + ItemColor, ConsoleColor.Red); } } } else { Console.WriteLine("[Item] " + ItemName + " " + ItemColor + " " + SoldOut.ToString()); ItemList.Add(temp); } } } } }
static void Main(string[] args) { //-Com:6 -File:"C:\\Users\\Angelo's Tower PC\\Desktop\\Game Move Data\\CXV.Files\\3 dof suitable all 3dof machine\\03-Birth of baby_3DOF.JMMov" -StartWait:4000 -EndWait:4000 -NumberOfCylinder:6 //this line is in here for testing to skip the start phase //JMDM_BasicRide.JMDM_BasicRide_Run("COM6", 6, "C:\\Users\\Angelo's Tower PC\\Desktop\\Game Move Data\\CXV.Files\\3 dof suitable all 3dof machine\\03-Birth of baby_3DOF.JMMov"); string Port = args?.FirstOrDefault(x => x.StartsWith("-Com")); string DataFile = args?.FirstOrDefault(x => x.StartsWith("-File:")); string StartWaitInput = args?.FirstOrDefault(x => x.StartsWith("-StartWait:")); string EndWaitInput = args?.FirstOrDefault(x => x.StartsWith("-EndWait:")); string NumberOfCylindersInput = args?.FirstOrDefault(x => x.StartsWith("-NumberOfCylinder:")); string ProcessName = args?.FirstOrDefault(x => x.StartsWith("-ProccesName:")); string AddInput = args?.FirstOrDefault(x => x.StartsWith("-AddInput:")); if (args.Length == 0 || Port == null) { Console.WriteLine("Please enter a port to use."); Port = Console.ReadLine(); } else { Port = Port.Replace(":", "").Replace("-", "").ToUpper(); } if (args.Length == 0 || DataFile == null) { Console.WriteLine("Please enter a data file to use."); DataFile = Console.ReadLine(); } else { DataFile = DataFile.Replace("-File:", "").Replace("\"", ""); } if (args.Length == 0 || NumberOfCylindersInput == null) { Console.WriteLine("Please enter the number of cylinders the machine uses."); NumberOfCylindersInput = Console.ReadLine(); } else { NumberOfCylindersInput = NumberOfCylindersInput.Replace("-NumberOfCylinder:", "").Replace("-", "").ToUpper(); } if (args.Length == 0 || StartWaitInput == null) { Console.WriteLine("Please enter a period to wait at start for syncing."); StartWaitInput = Console.ReadLine(); } else { StartWaitInput = StartWaitInput.Replace("-StartWait:", "").ToUpper(); } if (args.Length == 0 || ProcessName == null) { Console.WriteLine("Please enter a period to wait at start for syncing."); ProcessName = Console.ReadLine(); } else { ProcessName = ProcessName.Replace("-ProccesName:", ""); } if (args.Length == 0 || AddInput == null) { Console.WriteLine("Please enter any required input for the window."); AddInput = Console.ReadLine(); } else { AddInput = AddInput.Replace("-AddInput:", ""); } if (args.Length == 0 || EndWaitInput == null) { Console.WriteLine("Please enter a period to wait at end for syncing."); EndWaitInput = Console.ReadLine(); } else { EndWaitInput = EndWaitInput.Replace("-EndWait:", "").ToUpper(); } PortStatic = Port; try { int StartWait, EndWait; byte NumberOfCylinders; try { StartWait = int.Parse(StartWaitInput); } catch (Exception e) { throw new Exception("The Start Wait was not pressent or ont a valid whole number.", e); } try { EndWait = int.Parse(EndWaitInput); } catch (Exception e) { throw new Exception("The End Wait was not pressent or ont a valid whole number.", e); } try { NumberOfCylinders = byte.Parse(NumberOfCylindersInput); } catch (Exception e) { throw new Exception("The number of Cylinders was not pressent or ont a valid whole number.", e); } Process AttachedProcesss = null; while (AttachedProcesss == null || (AttachedProcesss != null && !AttachedProcesss.Responding)) { AttachedProcesss = Process.GetProcesses().FirstOrDefault(P => P.MainWindowHandle != IntPtr.Zero && P.ProcessName.ToLower() == ProcessName.ToLower()); } //WindowHandleInfo Window = new WindowHandleInfo(new WindowHandleInfo(AttachedProcesss.MainWindowHandle).GetAllChildHandles()[2]); WindowHandleInfo Window = new WindowHandleInfo(AttachedProcesss.MainWindowHandle); while (!AttachedProcesss.Responding) { ; } string[] InputCommands = AddInput.Split(' '); List <Action> Actions = new List <Action>(); foreach (string Command in InputCommands) { if (Command.Length < 1 || Command.Trim().Length < 1) { continue; } if (Command.ToLower().StartsWith("wait")) { string[] Params = Command.Split('(')[1].Split(')')[0].Split(','); Actions.Add(new Action(() => { Thread.Sleep(int.Parse(Params[0])); })); } else if (Command.ToLower().StartsWith("leftmouseclickdown")) { string[] Params = Command.Split('(')[1].Split(')')[0].Split(','); Point P = new Point(int.Parse(Params[0]), int.Parse(Params[1])); Actions.Add(new Action(() => { Window.SetForegroundWindow(); Window.SendMouseDown(WindowHandleInfo.MouseButton.MK_LBUTTON, P); })); } else if (Command.ToLower().StartsWith("leftmouseclickup")) { string[] Params = Command.Split('(')[1].Split(')')[0].Split(','); Point P = new Point(int.Parse(Params[0]), int.Parse(Params[1])); Actions.Add(new Action(() => { Window.SetForegroundWindow(); Window.SendMouseUp(WindowHandleInfo.MouseButton.MK_LBUTTON, P); })); } else if (Command.ToLower().StartsWith("keydown")) { string[] Params = Command.Split('(')[1].Split(')')[0].Split(','); byte AsciiValue = Program.GetKeyCode(Params[0]); Actions.Add(new Action(() => { Window.SetForegroundWindow(); KeyboardInputInjector.KeyDownRaw((KeyboardInputInjector.ScanCodeShort)AsciiValue); })); } else if (Command.ToLower().StartsWith("keyup")) { string[] Params = Command.Split('(')[1].Split(')')[0].Split(','); byte AsciiValue = Program.GetKeyCode(Params[0]); Actions.Add(new Action(() => { Window.SetForegroundWindow(); KeyboardInputInjector.KeyDownRaw((KeyboardInputInjector.ScanCodeShort)AsciiValue); })); } else { throw new Exception($"unreconized add input command {Command}"); } } Window.SetForegroundWindow(); foreach (Action Command in Actions) { Command.Invoke(); } ConsoleHandler = new ConsoleCtrlHandlerDelegate(ConsoleEventHandler); SetConsoleCtrlHandler(ConsoleHandler, true); JMDM_BasicRide.JMDM_BasicRide_Run(out ComPort, Port, NumberOfCylinders, DataFile, StartWait, EndWait); } catch (Exception e) { Console.WriteLine("There has been the following exception."); Console.WriteLine("\t" + e.Message); Console.WriteLine("\t\tHere is the following stack trace"); Console.WriteLine(e); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } // Go to http://aka.ms/dotnet-get-started-console to continue learning how to build a console app! }
static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandlerDelegate handlerProc, bool add);
static void Main(string[] args) { // self service installer/uninstaller if (args != null && args.Length == 1 && (args[0][0] == '-' || args[0][0] == '/')) { switch (args[0].Substring(1).ToLower()) { case "install": case "i": if (!ServiceInstallerUtility.InstallMe()) Console.WriteLine("Failed to install service"); break; case "uninstall": case "u": if (!ServiceInstallerUtility.UninstallMe()) Console.WriteLine("Failed to uninstall service"); break; default: Console.WriteLine("Unrecognized parameters."); break; } Environment.Exit(0); } // set directory where the program placed Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); if (!File.Exists(Config.ServerExeFile)) { var msg = string.Format("'{0}' doesn't exists!", Config.ServerExeFile); Console.WriteLine(msg); Log.Error(msg); Environment.Exit(0); } // console mode if (Environment.UserInteractive) { Console.Title = Config.Title; // register console close event _consoleHandler = new ConsoleCtrlHandlerDelegate(ConsoleEventHandler); SetConsoleCtrlHandler(_consoleHandler, true); Server.Start(); // handle for console input command while (true) { Server.SendCommand(Console.ReadLine()); } } // service mode else { var service = new Service1(); var servicesToRun = new ServiceBase[] { service }; ServiceBase.Run(servicesToRun); } }
public Source() { lock (Source.ActiveLock) { if (Source.Active) { throw new InvalidOperationException("Can only have one source open at a time."); } Source.Active = true; } // Disable quick-edit mode (the ability to highlight regions of the console with the mouse) this.handle = GetStdHandle(STD_INPUT_HANDLE); GetConsoleMode(this.handle, out uint consoleMode); consoleMode &= ~ENABLE_QUICK_EDIT; SetConsoleMode(this.handle, consoleMode); this.consoleControlHandler = (consoleControlEventType) => { if (consoleControlEventType == ConsoleControlEventType.CtrlC || consoleControlEventType == ConsoleControlEventType.CtrlBreak) { ExitRequestedEventArgs args = new ExitRequestedEventArgs(); this.OnExitRequested?.Invoke(this, args); if (args.Allow) { this.OnExitAccepted?.Invoke(this, new EventArgs()); return(false); } else { return(true); } } else { return(false); } }; SetConsoleCtrlHandler( this.consoleControlHandler, true); this.OnLeftMouse += (obj, e) => this.LeftMouseDown = e.ButtonDown; this.OnRightMouse += (obj, e) => this.RightMouseDown = e.ButtonDown; this.eventThreadRunning = new Box <bool>(true); this.eventThread = new Thread( () => { bool GetRunningState() { lock (this.eventThreadRunning) { return(this.eventThreadRunning.Value); } } while (GetRunningState()) { try { while (true) { ConsoleInputEventInfo[] events = this.ListenForEvents(); foreach (ConsoleInputEventInfo @event in events) { try { this.DispatchEventProcessing(@event); } catch { // Processing an event shouldn't emit an exception, but just in case... } } } } catch { // This shouldn't ever happen, but just in case, re-listen for events } } }); this.eventThread.Start(); }
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandlerDelegate handler, bool add);
public static void RemoveCtrlHandler(ConsoleCtrlHandlerDelegate HandlerRoutine) { SetCtrlHandler(HandlerRoutine, false); }
public static void AddCtrlHandler(ConsoleCtrlHandlerDelegate HandlerRoutine) { SetCtrlHandler(HandlerRoutine, true); }
static void Main(string[] args) { _handler += new ConsoleCtrlHandlerDelegate(Handler); SetConsoleCtrlHandler(_handler, true); var internalConfig = args.Length > 0 && args[0] == "internal-config"; var confTxt = internalConfig ? LoadInternalConfig() : LoadConfig(); var config = ConfigParsing.ParseConfig(confTxt); var inputMap = config.Bindings.Where(x => (x.Dir & BindingDir.FromBoard) != 0).ToDictionary(x => x.ControlId); using (var od = new OutputDevice(GetMidiOutputDevice(config.DeviceName))) using (var id = new InputDevice(GetMidiInputDevice(config.DeviceName))) using (var vb = new VmClient()) { disps.Add(vb); disps.Add(id); disps.Add(od); //voicemeeter doesn't have midi bindings for arm/disarm recording. We'll do it ourselves. //Note that the voicemeeter UI doesn't update until you start recording something. Console.WriteLine("All initialised"); id.ChannelMessageReceived += (ob, e) => { var m = e.Message; if (m.MessageType == MessageType.Channel && m.Command == ChannelCommand.Controller) { if (inputMap.ContainsKey(m.Data1)) { var v = inputMap[m.Data1]; if (v.ControlToggle && m.Data2 == v.ControlTo) { var current = vb.GetParam(v.VoicemeeterParam); vb.SetParam(v.VoicemeeterParam, v.VmTo - current); } else if (!v.ControlToggle) { var scaledVal = Scale(m.Data2, v.ControlFrom, v.ControlTo, v.VmFrom, v.VmTo); vb.SetParam(v.VoicemeeterParam, scaledVal); } } } }; id.StartRecording(); vb.OnClose(() => { foreach (var x in config.Bindings.Where(x => (x.Dir & BindingDir.ToBoard) != 0)) { od.Send(new ChannelMessage(ChannelCommand.Controller, 0, x.ControlId, (int)x.ControlFrom)); } }); while (!shouldStop) { if (vb.Poll()) { foreach (var x in config.Bindings.Where(x => (x.Dir & BindingDir.ToBoard) != 0)) { var vmVal = vb.GetParam(x.VoicemeeterParam); var scaled = Scale(vmVal, x.VmFrom, x.VmTo, x.ControlFrom, x.ControlTo); od.Send(new ChannelMessage(ChannelCommand.Controller, 0, x.ControlId, (int)scaled)); } } else { Thread.Sleep(20); } } } }
static void Main(string[] args) { setOnSetStartup(); sckt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //close the socket when applicaiton exit _consoleCtrlHandler += s => { sendBroadCast("shut"); sckt.Close(); return(false); }; SetConsoleCtrlHandler(_consoleCtrlHandler, true); //initialze pipe listener in a new thread new Thread(new ThreadStart(intiPipeListener)).Start(); byte[] data = new byte[1024]; endpoint = new IPEndPoint(IPAddress.Any, Constants.PORT_NO); sckt.Bind(endpoint); //IPEndPoint senderEndPoint; EndPoint remote = (EndPoint)endpoint; sendBroadCast("on"); while (true) { //receive data from sender int recv = sckt.ReceiveFrom(data, ref remote); string message = Encoding.ASCII.GetString(data, 0, recv); //Get sender ip address //Console.WriteLine(senderAddress.ToString()); senderAddress = ((IPEndPoint)remote).Address; //Console.WriteLine(message); if (senderAddress.Equals(localIp)) { continue; } //Console.WriteLine(message); if (message.Equals("lol")) { if (lolThread != null && lolThread.IsAlive) { //notify client sendToClient("tworking"); //Console.WriteLine("start lol already working..!"); continue; } startLol(); } else if (message.Equals("stoplol")) { exitThread = true; //TEST counter++; //TEST new Thread(new ThreadStart(startLolWithDelay)).Start(); } else if (message.Equals("stoplolC")) { exitThread = true; //TEST counter++; //TEST new Thread(new ThreadStart(startLolWithDelayC)).Start(); } else if (message.Equals("clol")) { exitThread = true; new Thread(new ParameterizedThreadStart(exitProgram)).Start("LeagueClient"); } else if (message.Equals("chrome")) { Process.Start(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"); } else if (message.Equals("cchrome")) { new Thread(new ParameterizedThreadStart(exitProgram)).Start("chrome"); } else if (message.Equals("shut")) { sendToClient("shut"); Process.Start("shutdown", "/s /t 0"); } else if (message.Equals("restart")) { sendToClient("shut"); Process.Start("shutdown", "/r /t 0"); } else if (message.Equals("image")) { startSendingProcess(); } else if (message.Equals("moff")) { //This will turn off the monitor SendMessage(0xFFFF, 0x112, 0xF170, MonitorStateOff); } else if (message.Equals("mon")) { wake(); } else if (message.Length > 5 && (message.Substring(0, 5).Equals("cpass"))) { //take the password from the message... lolPassword = message.Substring(5, message.Length - 5); new Thread(new ParameterizedThreadStart(changeLolPw)).Start(lolPassword); } else if (message.Length > 4 && (message.Substring(0, 4).Equals("pass"))) { //take the password from the message... lolPassword = message.Substring(4, message.Length - 4); //Console.WriteLine("lol pass: " + lolPassword); passSent = true; } sendToClient(message); } }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { ExceptionlessClient.Default.Register(); AppSettings.Init(); // self service installer/uninstaller if (args != null && args.Length == 1 && (args[0][0] == '-' || args[0][0] == '/')) { switch (args[0].Substring(1).ToLower()) { case "install": case "i": if (!ServiceInstallerUtility.InstallMe()) Logger.Fatal("Failed to install service"); break; case "uninstall": case "u": if (!ServiceInstallerUtility.UninstallMe()) Logger.Fatal("Failed to uninstall service"); break; default: Logger.Error("Unrecognized parameters (allowed: /install and /uninstall, shorten /i and /u)"); break; } Environment.Exit(0); } _service = new Service(); var servicesToRun = new ServiceBase[] { _service }; // console mode if (Environment.UserInteractive) { // register console close event _consoleHandler = ConsoleEventHandler; SetConsoleCtrlHandler(_consoleHandler, true); Console.Title = AppDomain.CurrentDomain.FriendlyName; Logger.Debug("Running in console mode"); _service.Start(); Console.WriteLine("Press any key to stop the service..."); Console.Read(); _service.Stop(); } // service mode else { Logger.Debug("Running in service mode"); ServiceBase.Run(servicesToRun); } }