在C#/ .NET/WinForms程序中构建RUNAS/NETONLY功能,可以通过以下步骤实现:
using System;
using System.Runtime.InteropServices;
public class ProcessUtil
{
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool CreateProcessWithLogonW(
string userName,
string domain,
string password,
LogonFlags logonFlags,
string appName,
string cmdLine,
CreationFlags creationFlags,
IntPtr environmentBlock,
string currentDirectory,
ref STARTUPINFO startupInfo,
out PROCESS_INFORMATION processInformation);
}
private void button1_Click(object sender, EventArgs e)
{
string username = "username";
string domain = "domain";
string password = "password";
string appName = "notepad.exe";
string cmdLine = "";
IntPtr environmentBlock = IntPtr.Zero;
string currentDirectory = "";
STARTUPINFO startupInfo = new STARTUPINFO();
PROCESS_INFORMATION processInformation = new PROCESS_INFORMATION();
bool result = ProcessUtil.CreateProcessWithLogonW(
username,
domain,
password,
LogonFlags.LOGON_WITH_PROFILE,
appName,
cmdLine,
CreationFlags.NORMAL_PRIORITY_CLASS,
environmentBlock,
currentDirectory,
ref startupInfo,
out processInformation);
if (result)
{
MessageBox.Show("Process created successfully.");
}
else
{
MessageBox.Show("Failed to create process.");
}
}
public enum LogonFlags
{
LOGON_WITH_PROFILE = 1,
LOGON_NETCREDENTIALS_ONLY = 2
}
public enum CreationFlags
{
NORMAL_PRIORITY_CLASS = 0x00000020
}
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public int cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public int dwX;
public int dwY;
public int dwXSize;
public int dwYSize;
public int dwXCountChars;
public int dwYCountChars;
public int dwFillAttribute;
public int dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
通过以上步骤,可以在C#/ .NET/WinForms程序中构建RUNAS/NETONLY功能。
领取专属 10元无门槛券
手把手带您无忧上云