C# 使用其他用户启动程序

一下代码转载自CodeProject,经过删减:

/// <summary>
		/// Logon option. 
		/// </summary>
		[FlagsAttribute]
		public enum LogonFlags
		{
			/// <summary>
			/// Log on, then load the user's profile in the HKEY_USERS registry key. The function returns after the profile has been loaded. Loading the profile can be time-consuming, so it is best to use this value only if you must access the information in the HKEY_CURRENT_USER registry key.
			/// </summary>
			WithProfile = 1,
			/// <summary>
			/// Log on, but use the specified credentials on the network only. The new process uses the same token as the caller, but the system creates a new logon session within LSA, and the process uses the specified credentials as the default credentials.
			/// </summary>
			NetworkCredentialsOnly = 2
		}

/// <summary>
		/// Controls how the process is created. The DefaultErrorMode, NewConsole, and NewProcessGroup flags are enabled by default・even if you do not set the flag, the system will function as if it were set.
		/// </summary>
		[FlagsAttribute]
		public enum CreationFlags
		{
			/// <summary>
			/// The primary thread of the new process is created in a suspended state, and does not run until the ResumeThread function is called.
			/// </summary>
			Suspended = 0x00000004,
			/// <summary>
			/// The new process has a new console, instead of inheriting the parent's console.
			/// </summary>
			NewConsole = 0x00000010,
			/// <summary>
			/// The new process is the root process of a new process group.
			/// </summary>
			NewProcessGroup = 0x00000200,
			/// <summary>
			/// This flag is only valid starting a 16-bit Windows-based application. If set, the new process runs in a private Virtual DOS Machine (VDM). By default, all 16-bit Windows-based applications run in a single, shared VDM. 
			/// </summary>
			SeperateWOWVDM = 0x00000800,
			/// <summary>
			/// Indicates the format of the lpEnvironment parameter. If this flag is set, the environment block pointed to by lpEnvironment uses Unicode characters.
			/// </summary>
			UnicodeEnvironment = 0x00000400,
			/// <summary>
			/// The new process does not inherit the error mode of the calling process.
			/// </summary>
			DefaultErrorMode = 0x04000000,
		}

/// <summary>
		/// The STARTUPINFO structure is used with the CreateProcess, CreateProcessAsUser, and CreateProcessWithLogonW functions to specify the window station, desktop, standard handles, and appearance of the main window for the new process.
		/// </summary>
		[StructLayout(LayoutKind.Sequential)]
		public struct StartUpInfo 
		{
			/// <summary>
			/// Size of the structure, in bytes.
			/// </summary>
			public int cb;
			/// <summary>
			/// Reserved. Set this member to NULL before passing the structure to CreateProcess.
			/// </summary>
			[MarshalAs(UnmanagedType.LPTStr)]
			public string lpReserved;
			/// <summary>
			/// Pointer to a null-terminated string that specifies either the name of the desktop, or the name of both the desktop and window station for this process. A backslash in the string indicates that the string includes both the desktop and window station names.
			/// </summary>
			[MarshalAs(UnmanagedType.LPTStr)]
			public string lpDesktop;
			/// <summary>
			/// For console processes, this is the title displayed in the title bar if a new console window is created. If NULL, the name of the executable file is used as the window title instead. This parameter must be NULL for GUI or console processes that do not create a new console window.
			/// </summary>
			[MarshalAs(UnmanagedType.LPTStr)]
			public string lpTitle;
			/// <summary>
			/// The x offset of the upper left corner of a window if a new window is created, in pixels.
			/// </summary>
			public int dwX;
			/// <summary>
			/// The y offset of the upper left corner of a window if a new window is created, in pixels.
			/// </summary>
			public int dwY;
			/// <summary>
			/// The width of the window if a new window is created, in pixels.
			/// </summary>
			public int dwXSize;
			/// <summary>
			/// The height of the window if a new window is created, in pixels.
			/// </summary>
			public int dwYSize;
			/// <summary>
			/// If a new console window is created in a console process, this member specifies the screen buffer width, in character columns.
			/// </summary>
			public int dwXCountChars;
			/// <summary>
			/// If a new console window is created in a console process, this member specifies the screen buffer height, in character rows.
			/// </summary>
			public int dwYCountChars;
			/// <summary>
			/// The initial text and background colors if a new console window is created in a console application.
			/// </summary>
			public int dwFillAttribute;
			/// <summary>
			/// Bit field that determines whether certain StartUpInfo members are used when the process creates a window.
			/// </summary>
			public int dwFlags;
			/// <summary>
			/// This member can be any of the SW_ constants defined in Winuser.h.
			/// </summary>
			public short wShowWindow;
			/// <summary>
			/// Reserved for use by the C Runtime; must be zero.
			/// </summary>
			public short cbReserved2;
			/// <summary>
			/// Reserved for use by the C Runtime; must be null.
			/// </summary>
			public IntPtr lpReserved2;
			/// <summary>
			/// A handle to be used as the standard input handle for the process.
			/// </summary>
			public IntPtr hStdInput;
			/// <summary>
			/// A handle to be used as the standard output handle for the process.
			/// </summary>
			public IntPtr hStdOutput;
			/// <summary>
			/// A handle to be used as the standard error handle for the process.
			/// </summary>
			public IntPtr hStdError;
		}

/// <summary>
		/// The ProcessInformation structure is filled in by either the CreateProcess, CreateProcessAsUser, CreateProcessWithLogonW, or CreateProcessWithTokenW function with information about the newly created process and its primary thread.
		/// </summary>
		[StructLayout(LayoutKind.Sequential)]
		public struct ProcessInformation 
		{
			/// <summary>
			/// Handle to the newly created process. The handle is used to specify the process in all functions that perform operations on the process object.
			/// </summary>
			public IntPtr hProcess;
			/// <summary>
			/// Handle to the primary thread of the newly created process. The handle is used to specify the thread in all functions that perform operations on the thread object.
			/// </summary>
			public IntPtr hThread;
			/// <summary>
			/// Value that can be used to identify a process. The value is valid from the time the process is created until the time the process is terminated.
			/// </summary>
			public int dwProcessId;
			/// <summary>
			/// Value that can be used to identify a thread. The value is valid from the time the thread is created until the time the thread is terminated.
			/// </summary>
			public int dwThreadId;
		}

/// <summary>
		/// The CreateProcessWithLogonW function creates a new process and its primary thread. The new process then runs the specified executable file in the security context of the specified credentials (user, domain, and password). It can optionally load the user profile for the specified user.
		/// </summary>
		[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
		private static extern bool CreateProcessWithLogonW(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonFlags, string applicationName, StringBuilder commandLine, uint creationFlags, IntPtr environment, string currentDirectory, ref StartUpInfo sui, out ProcessInformation processInfo);

		/// <summary>
		/// Closes an open object handle.
		/// </summary>
		[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
		private static extern bool CloseHandle(IntPtr handle);

/// <summary>
		/// Creates a new process and its primary thread. The new process then runs the
		///  specified executable file in the security context of the specified
		///  credentials (user, domain, and password). It can optionally load the user
		///  profile for the specified user.
		/// </summary>
		/// <remarks>
		/// This method is untested.
		/// </remarks>
		/// <param name="userName">
		/// This is the name of the user account to log on to. If you use the UPN format,
		///  user@domain, the Domain parameter must be NULL. The user account must have
		///  the Log On Locally permission on the local computer.
		/// </param>
		/// <param name="domain">
		/// Specifies the name of the domain or server whose account database contains the
		///  user account. If this parameter is NULL, the user name must be specified in
		///  UPN format.
		/// </param>
		/// <param name="password">
		/// Specifies the clear-text password for the user account.
		/// </param>
		/// <param name="logonFlags">
		/// Logon option. This parameter can be zero or one value from the LogonFlags enum.
		/// </param>
		/// <param name="applicationName">
		/// Specifies the module to execute. The specified module can be a Windows-based
		///  application. It can be some other type of module (for example, MS-DOS or OS/2)
		///  if the appropriate subsystem is available on the local computer. The string
		///  can specify the full path and file name of the module to execute or it can
		///  specify a partial name. In the case of a partial name, the function uses the
		///  current drive and current directory to complete the specification. The function
		///  will not use the search path. If the file name does not contain an extension,
		///  .exe is assumed. Therefore, if the file name extension is .com, this parameter
		///  must include the .com extension. The appname parameter can be NULL. In that
		///  case, the module name must be the first white space-delimited token in the
		///  commandline string. If the executable module is a 16-bit application, appname
		///  should be NULL, and the string pointed to by commandline should specify the
		///  executable module as well as its arguments.
		/// </param>
		/// <param name="commandLine">
		/// Specifies the command line to execute. The maximum length of this string is
		///  32,000 characters. The commandline parameter can be NULL. In that case, the
		///  function uses the string pointed to by appname as the command line. If the
		///  file name does not contain an extension, .exe is appended. Therefore, if the
		///  file name extension is .com, this parameter must include the .com extension.
		///  If the file name ends in a period with no extension, or if the file name
		///  contains a path, .exe is not appended. If the file name does not contain a
		///  directory path, the system searches for the executable file.
		/// </param>
		/// <param name="creationFlags">
		/// Use CreationFlags and PriorityFlags enums. Controls how the process is created.
		///  Also controls the new process's priority class, which is used to determine the
		///  scheduling priorities of the process's threads.
		/// </param>
		/// <param name="currentDirectory">
		/// Specifies the full path to the current directory for the process. The string
		///  can also specify a UNC path. If this parameter is NULL, the new process will
		///  have the same current drive and directory as the calling process.
		/// </param>
		/// <param name="environment">
		/// Pointer to an environment block for the new process. If this parameter is NULL,
		///  the new process uses the environment of the specified user instead of the
		///  environment of the calling process.
		/// </param>
		/// <param name="startupInfo">
		/// Specifies the window station, desktop, standard handles, and appearance of the
		///  main window for the new process.
		/// </param>
		/// <param name="processInfo">
		/// ProcessInformation structure that receives identification information for the
		///  new process, including a handle to the process.
		/// </param>
		/// <returns>
		/// Returns a System.Diagnostic.Process which will be null if the call failed.
		/// </returns>
		/// <exception cref="System.ComponentModel.Win32Exception">
		/// Throws a System.ComponentModel.Win32Exception containing the last error if the
		///  call failed.
		/// </exception>
		public static System.Diagnostics.Process StartProcess(string userName,
			string domain, string password, LogonFlags logonFlags, string applicationName,
			string commandLine, CreationFlags creationFlags, IntPtr environment,
			string currentDirectory, ref StartUpInfo startupInfo,
			out ProcessInformation processInfo)
		{
			StringBuilder cl = new StringBuilder(commandLine.Length);
			cl.Append(commandLine);
			bool retval = CreateProcessWithLogonW(userName, domain, password,
				(int)logonFlags, applicationName, cl, (uint)creationFlags, environment,
				currentDirectory, ref startupInfo, out processInfo);
			if (!retval)
			{
				throw new System.ComponentModel.Win32Exception();
			}
			else
			{
				CloseHandle(processInfo.hProcess);
				CloseHandle(processInfo.hThread);
				return System.Diagnostics.Process.GetProcessById(processInfo.dwProcessId);
			}
		}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值