C# crea e inicia un nuevo proceso

        En la programación C#, ProcessStartInfouna clase solía contener información sobre un proceso que se iba a iniciar. Se utiliza en métodos Processde clase Startpara determinar cómo iniciar un nuevo proceso.

        ProcessStartInfoAlgunas propiedades importantes de las clases incluyen:

  • FileName: El nombre del archivo que se ejecutará, que puede incluir la ruta (ruta absoluta o ruta relativa).
  • Arguments: argumentos de la línea de comando pasados ​​al archivo.
  • WorkingDirectory: La ruta al directorio de trabajo.
  • UseShellExecute: valor booleano que determina si se debe utilizar el shell del sistema operativo para iniciar el proceso.
  • RedirectStandardInput, RedirectStandardOutput, RedirectStandardError: Valor booleano, determina si se redirigen los flujos de entrada, salida y error estándar del proceso.
  • StandardOutputEncoding, StandardErrorEncoding: Codificación utilizada para leer la salida estándar y el error del proceso.
  • CreateNoWindow: Un valor booleano que determina si se debe iniciar el proceso en una nueva ventana.
  • WindowStyle: Estilo de ventana (maximizar, minimizar, ocultar, etc.).
  • LoadUserProfile: valor booleano que determina si se carga el perfil del usuario.
  • EnvironmentVariables: un diccionario de cadenas utilizadas para establecer variables de entorno.
  • UserName, Password, Domain: Credenciales utilizadas para la autenticación.

        1. Ejemplo sencillo:

string arg1 = "a", arg2 = "b";
string args = $@"{arg1} {arg2}";

ProcessStartInfo info = new ProcessStartInfo();
//指定exe文件
info.FileName = "D:\Test\Test.exe";
//传入参数,多个参数用英文空格隔开
info.Arguments = args;
//已管理员身份运行,可消除打开的确认弹窗
info.Verb = "runas";
//设置不在新窗口中启动新的进程
info.CreateNoWindow = true;
//不使用操作系统使用的shell启动进程
info.UseShellExecute = false;
//将输出信息重定向
info.RedirectStandardOutput = true;

Process pro = Process.Start(info);

        Nota sobre los argumentos de los parámetros: la entrada es de tipo cadena. Si necesita ingresar varios parámetros, sepárelos con espacios en inglés. El programa exe que se abre al mismo tiempo necesita modificar el punto de entrada Función principal de la aplicación en el archivo Program.cs para recibir los parámetros entrantes. Este proceso analizará automáticamente los parámetros en matrices de cadenas separadas por espacios en inglés, de la siguiente manera :

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    //调用WinForm的窗体有参构造函数
    Application.Run(new TestFrom(args));
}

/// <summary>
/// 有参构造函数
/// </summary>
/// <param name="args">ProcessStartInfo传入的参数</param>
public TestFrom(string[] args)
{
    InitializeComponent();
}

        2. Utilice la cuenta de dominio especificada para abrir el programa exe.

        Nombre de usuario: cuenta de dominio de usuario;

        Contraseña: la contraseña de la cuenta del dominio del usuario;

        Dominio: nombre de dominio.

        Necesita usar la clase de herramienta para compartir ShareTool: se usa para iniciar sesión

using System;
using System.Runtime.InteropServices;

namespace ShareToolClass
{
    public class ShareTool : IDisposable
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
            int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        // closes open handes returned by LogonUser       
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        extern static bool CloseHandle(IntPtr handle);

        [DllImport("Advapi32.DLL")]
        static extern bool ImpersonateLoggedOnUser(IntPtr hToken);

        [DllImport("Advapi32.DLL")]
        static extern bool RevertToSelf();
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_NEWCREDENTIALS = 9;
        const int LOGON32_LOGON_INTERACTIVE = 2;
        private bool disposed;

        public ShareTool(string username, string password, string ip)
        {
            // initialize tokens       
            IntPtr pExistingTokenHandle = new IntPtr(0);
            IntPtr pDuplicateTokenHandle = new IntPtr(0);

            try
            {
                // get handle to token       
                bool bImpersonated = LogonUser(username, ip, password,
                    LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);

                if (bImpersonated)
                {
                    if (!ImpersonateLoggedOnUser(pExistingTokenHandle))
                    {
                        int nErrorCode = Marshal.GetLastWin32Error();
                        throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode);
                    }
                }
                else
                {
                    int nErrorCode = Marshal.GetLastWin32Error();
                    throw new Exception("LogonUser error;Code=" + nErrorCode);
                }
            }
            finally
            {
                // close handle(s)       
                if (pExistingTokenHandle != IntPtr.Zero)
                    CloseHandle(pExistingTokenHandle);
                if (pDuplicateTokenHandle != IntPtr.Zero)
                    CloseHandle(pDuplicateTokenHandle);
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                RevertToSelf();
                disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }
    }
}

        Ejemplo:

string user = "admin";
string userpsw = "123456";
string domain = "TestDomain";

using (ShareToolClass.ShareTool tool = new ShareTool.ShareTool(user, userpsw, domain))
{
    //保密文本
    SecureString pwd = new SecureString();
    foreach (char c in userpsw)
        pwd.AppendChar(c);

    //使用线程打开
    Thread t = new Thread(new ThreadStart(delegate
    {
        try
        {
            ProcessStartInfo info = new ProcessStartInfo();
            info.FileName = "D:\Test\Test.exe";
            
            info.UserName = user;//域账号
            info.Password = pwd;//密码
            info.Domain = domain;//域名

            //设置不在新窗口中启动新的进程
            info.CreateNoWindow = true;
            //不使用操作系统使用的shell启动进程
            info.UseShellExecute = false;
            //将输出信息重定向
            //info.RedirectStandardOutput = true;
            Process pro = Process.Start(info);
        }
        catch (Exception ex)
        {
            PubLibrary.WriteErrLog("打开出错:" + ex.ToString());
        }
    }));
    t.Start();
}

Supongo que te gusta

Origin blog.csdn.net/weixin_50478033/article/details/133273786
Recomendado
Clasificación