Пример #1
0
        public static int Main(string[] args)
        {
            // Attach to the parent process's console so we can display help, version information, and command-line errors.
            Kernel32.AttachConsole(dwProcessId: Helpers.AttachParentProcess);

            // Ensure that we are the only instance of the Mouse Jiggler currently running.
            var instance = new Mutex(initiallyOwned: false, name: "single instance: ArkaneSystems.MouseJiggler");

            try
            {
                if (instance.WaitOne(millisecondsTimeout: 0))
                {
                    // Parse arguments and do the appropriate thing.
                    return(Program.GetCommandLineParser().Invoke(args: args));
                }
                else
                {
                    return(1);
                }
            }
            finally
            {
                instance.Close();

                // Detach from the parent console.
                Kernel32.FreeConsole();
            }
        }
Пример #2
0
 /// <summary>
 /// Safely attach to the console of the associated process
 /// </summary>
 public void AttachToConsoleForProcess()
 {
     if (!ConsoleExtensions.IsConsole)
     {
         Kernel32.AttachConsole(currentProcess.Id);
     }
 }
Пример #3
0
 public override void Call()
 {
     if (args.Length == 1)
     {
         AssemblerExecute.registers.EAX = Kernel32.AttachConsole(Convert.ToUInt32(args[0].value)) ? 1 : 0;
     }
 }
Пример #4
0
        private bool SelectWindow(FamiliarCommandLineArguments resolvedArgs, Process currentProcess, out int parentPid, out IntPtr targetWindow)
        {
            if (resolvedArgs.SelectWindow)
            {
                var attachSelector = new AttachSelector();
                attachSelector.ShowDialog();

                parentPid    = attachSelector.ParentPid;
                targetWindow = attachSelector.TargetWindow;

                if (parentPid == 0)
                {
                    Current.Shutdown(ExitCodes.UserCanceledAttach);
                    return(false);
                }
            }
            else
            {
                parentPid = GetParentProcessId(currentProcess);

                var attached = Kernel32.AttachConsole((uint)parentPid);
                _trace.TraceVerbose("{0} returned {1}", nameof(Kernel32.AttachConsole), attached);

                targetWindow = Kernel32.GetConsoleWindow();
                if (targetWindow == IntPtr.Zero)
                {
                    _trace.TraceWarning("No console window detected.");
                    MessageBox.Show("Console not detected.\r\nPlease, start the familiar from Command Prompt.", "Familiar Notification", MessageBoxButton.OK, MessageBoxImage.Information);
                    Current.Shutdown(ExitCodes.ConsoleNotDetected);
                    return(false);
                }
            }

            return(true);
        }
Пример #5
0
        /// <summary>
        /// Attempts to allocate and attach a console, if this was built in debug mode,
        /// or if the calling assembly is not this assembly.
        /// </summary>
        public static void CreateConsole()
        {
            bool shouldCreateConsole = IsDebugBuild ||
                                       Assembly.CallingAssembly != System.Reflection.Assembly.GetAssembly(typeof(Debug));

            if (shouldCreateConsole)
            {
                Kernel32.AllocConsole();
                Kernel32.AttachConsole(-1);
            }
        }
Пример #6
0
        private void ConsoleNeeded(bool redirectLogs = false)
        {
            if (redirectLogs)
            {
                var listener = new OutputTraceListener();
                listener.Other = LogViewTraceListener.Actual;
                LogViewTraceListener.Actual = listener;
            }

            if (Kernel32.GetConsoleWindow() == IntPtr.Zero)
            {
                var parentPid = GetParentProcessId(Process.GetCurrentProcess());
                Kernel32.AttachConsole((uint)parentPid);
                if (Kernel32.GetConsoleWindow() == IntPtr.Zero)
                {
                    Kernel32.AllocConsole();
                }
            }

            Terminal.WriteLine();
        }
Пример #7
0
        public static void RestartDetached()
        {
            Kernel32.FreeConsole();
            Kernel32.AttachConsole(-1);

            if (Marshal.GetLastWin32Error() != 87)
            {
                Kernel32.FreeConsole();
                var process = new System.Diagnostics.Process {
                    StartInfo =
                    {
                        UseShellExecute  = false,
                        WorkingDirectory = Environment.CurrentDirectory,
                        CreateNoWindow   = true,
                        FileName         = Assembly.GetEntryAssembly().Location,
                        Arguments        = EnvironmentUtility.CommandLineArguments, // just the arguments, not the exe itself
                        WindowStyle      = ProcessWindowStyle.Hidden,
                    }
                }.Start();
                Environment.Exit(0);
            }
        }
Пример #8
0
        /// <summary>
        /// Creates and attaches a console window if necessary
        /// </summary>
        public void AttachConsole()
        {
            if (_consoleAttached)
            {
                throw new InvalidOperationException();
            }

            lock (_lockObject)
            {
                if (!Kernel32.AttachConsole(0xFFFFFFFF) && !Kernel32.AllocConsole())
                {
                    throw new Win32Exception();
                }

                Console.SetOut(new StreamWriter(Console.OpenStandardOutput(), Console.OutputEncoding)
                {
                    AutoFlush = true
                });

                _consoleAttached = true;
            }
        }
Пример #9
0
 public static void RedirectConsoleOutput()
 {
     Kernel32.AttachConsole(ATTACH_PARENT_PROCESS);
 }
Пример #10
0
        public static void Start(string[] args)
        {
            bool          isAlreadyRunning = false;
            List <string> filesToOpen      = new List <string>();

            // Init Log4NET
            LogFileLocation = LogHelper.InitializeLog4NET();
            // Get logger
            LOG = log4net.LogManager.GetLogger(typeof(MainForm));

            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // Log the startup
            LOG.Info("Starting: " + EnvironmentInfo.EnvironmentToString(false));

            IniConfig.Init();
            AppConfig.UpgradeToIni();
            // Read configuration
            conf = IniConfig.GetIniSection <CoreConfiguration>();
            try
            {
                // Fix for Bug 2495900, Multi-user Environment
                // check whether there's an local instance running already

                try
                {
                    // Added Mutex Security, hopefully this prevents the UnauthorizedAccessException more gracefully
                    // See an example in Bug #3131534
                    SecurityIdentifier sid           = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    MutexSecurity      mutexsecurity = new MutexSecurity();
                    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow));
                    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny));
                    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny));

                    bool created = false;
                    // 1) Create Mutex
                    applicationMutex = new Mutex(false, @"Local\F48E86D3-E34C-4DB7-8F8F-9A0EA55F0D08", out created, mutexsecurity);
                    // 2) Get the right to it, this returns false if it's already locked
                    if (!applicationMutex.WaitOne(0, false))
                    {
                        LOG.Debug("Greenshot seems already to be running!");
                        isAlreadyRunning = true;
                        // Clean up
                        applicationMutex.Close();
                        applicationMutex = null;
                    }
                }
                catch (AbandonedMutexException e)
                {
                    // Another Greenshot instance didn't cleanup correctly!
                    // we can ignore the exception, it happend on the "waitone" but still the mutex belongs to us
                    LOG.Warn("Greenshot didn't cleanup correctly!", e);
                }
                catch (UnauthorizedAccessException e)
                {
                    LOG.Warn("Greenshot is most likely already running for a different user in the same session, can't create mutex due to error: ", e);
                    isAlreadyRunning = true;
                }
                catch (Exception e)
                {
                    LOG.Warn("Problem obtaining the Mutex, assuming it was already taken!", e);
                    isAlreadyRunning = true;
                }

                if (args.Length > 0 && LOG.IsDebugEnabled)
                {
                    StringBuilder argumentString = new StringBuilder();
                    for (int argumentNr = 0; argumentNr < args.Length; argumentNr++)
                    {
                        argumentString.Append("[").Append(args[argumentNr]).Append("] ");
                    }
                    LOG.Debug("Greenshot arguments: " + argumentString.ToString());
                }

                for (int argumentNr = 0; argumentNr < args.Length; argumentNr++)
                {
                    string argument = args[argumentNr];
                    // Help
                    if (argument.ToLower().Equals("/help"))
                    {
                        // Try to attach to the console
                        bool attachedToConsole = Kernel32.AttachConsole(Kernel32.ATTACHCONSOLE_ATTACHPARENTPROCESS);
                        // If attach didn't work, open a console
                        if (!attachedToConsole)
                        {
                            Kernel32.AllocConsole();
                        }
                        StringBuilder helpOutput = new StringBuilder();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("Greenshot commandline options:");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/help");
                        helpOutput.AppendLine("\t\tThis help.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/exit");
                        helpOutput.AppendLine("\t\tTries to close all running instances.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/reload");
                        helpOutput.AppendLine("\t\tReload the configuration of Greenshot.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/language [language code]");
                        helpOutput.AppendLine("\t\tSet the language of Greenshot, e.g. greenshot /language en-US.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t[filename]");
                        helpOutput.AppendLine("\t\tOpen the bitmap files in the running Greenshot instance or start a new instance");
                        Console.WriteLine(helpOutput.ToString());

                        // If attach didn't work, wait for key otherwise the console will close to quickly
                        if (!attachedToConsole)
                        {
                            Console.ReadKey();
                        }
                        FreeMutex();
                        return;
                    }

                    if (argument.ToLower().Equals("/exit"))
                    {
                        // unregister application on uninstall (allow uninstall)
                        try
                        {
                            LOG.Info("Sending all instances the exit command.");
                            // Pass Exit to running instance, if any
                            SendData(new CopyDataTransport(CommandEnum.Exit));
                        }
                        catch (Exception e)
                        {
                            LOG.Warn("Exception by exit.", e);
                        }
                        FreeMutex();
                        return;
                    }

                    // Reload the configuration
                    if (argument.ToLower().Equals("/reload"))
                    {
                        // Modify configuration
                        LOG.Info("Reloading configuration!");
                        // Update running instances
                        SendData(new CopyDataTransport(CommandEnum.ReloadConfig));
                        FreeMutex();
                        return;
                    }

                    // Stop running
                    if (argument.ToLower().Equals("/norun"))
                    {
                        // Make an exit possible
                        FreeMutex();
                        return;
                    }

                    // Language
                    if (argument.ToLower().Equals("/language"))
                    {
                        conf.Language = args[++argumentNr];
                        IniConfig.Save();
                        continue;
                    }

                    // Files to open
                    filesToOpen.Add(argument);
                }

                // Finished parsing the command line arguments, see if we need to do anything
                CopyDataTransport transport = new CopyDataTransport();
                if (filesToOpen.Count > 0)
                {
                    foreach (string fileToOpen in filesToOpen)
                    {
                        transport.AddCommand(CommandEnum.OpenFile, fileToOpen);
                    }
                }

                if (MainForm.instance == null)
                {
                    MainForm.instance = new MainForm(transport);
                }

                // if language is not set, show language dialog
                if (string.IsNullOrEmpty(conf.Language))
                {
                    LanguageDialog languageDialog = LanguageDialog.GetInstance();
                    languageDialog.ShowDialog();
                    conf.Language = languageDialog.SelectedLanguage;
                    IniConfig.Save();
                }

                // Check if it's the first time launch?
                if (conf.IsFirstLaunch)
                {
                    conf.IsFirstLaunch = false;
                    IniConfig.Save();
                    transport.AddCommand(CommandEnum.FirstLaunch);
                }
            }
            catch (Exception ex)
            {
                LOG.Error("Exception in startup.", ex);
                Application_ThreadException(MainForm.ActiveForm, new ThreadExceptionEventArgs(ex));
            }
        }
Пример #11
0
        protected override void OnStartup(StartupEventArgs e)
        {
            /*
             * Some sample invocations to try:
             *
             * From the terminal:
             * dotnet run -- --help
             * dotnet run -- --version
             * dotnet run -- --message "This is a message"
             * dotnet run -- --message "Some other message" --no-window
             *
             * From Properties/launchSettings.json
             * "commandLineArgs": "--version"
             * "commandLineArgs": "--help"
             * "commandLineArgs": "--message \"This is a test message\""
             * "commandLineArgs": "--message \"This is a test message\" --no-window"
             */

            Option <string> messageOption  = new Option <string>("--message", "The message to display in the window");
            Option <bool>   noWindowOption = new Option <bool>("--no-window", "Do not display the WPF window and simply write to the console");

            //This is a bit of a hack since we need to know if the parser.Invoke to detect cases where the args are --help or --version
            bool wasHandled = true;
            var  builder    = new CommandLineBuilder()
                              .UseDefaults()
                              .AddOption(messageOption)
                              .AddOption(noWindowOption);

            //The names of the handler parameters must match the option names above
            builder.Command.Handler = CommandHandler.Create((IConsole console, string message, bool noWindow) =>
            {
                if (noWindow)
                {
                    console.Out.WriteLine($"Message: {message}");
                }
                else
                {
                    wasHandled = false;
                }
            });

            Parser parser = builder.Build();

            ParseResult parseResult = parser.Parse(e.Args);

            Kernel32.AttachConsole(-1);
            int result = parser.Invoke(parseResult);

            Kernel32.FreeConsole();

            if (result != 0 || wasHandled)
            {
                Shutdown(result);
                return;
            }

            base.OnStartup(e);

            //Removed the StartupUri and manually setting the MainWindow here
            //Pick any mechanism you like to transport the parsed data from the CLI to your app
            var window = new MainWindow
            {
                TextValue = { Text = parseResult.CommandResult.ValueForOption <string>(messageOption.Name) }
            };

            MainWindow = window;
            window.Show();
        }