Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如果(结果==false) { int error=Marshal.GetLastWin32Error(); string message=string.Format(“CreateProcessAsUser错误:{0}”,错误); Debug.WriteLine(消息); } 返回结果; } /// ///当用户重载窗口模式时启动进程 /// /// /// /// /// /// 专用静态bool LaunchProcessAsUser(字符串cmdLine、IntPtr令牌、IntPtr envBlock、uint WindowMode) { 布尔结果=假; 流程信息pi=新流程信息(); 安全属性saProcess=新的安全属性(); SECURITY_ATTRIBUTES saThread=新的SECURITY_ATTRIBUTES(); saProcess.nLength=(uint)Marshal.SizeOf(saProcess); saThread.nLength=(uint)Marshal.SizeOf(saThread); STARTUPINFO si=新的STARTUPINFO(); si.cb=(uint)marshall.SizeOf(si); //如果此成员为NULL,则新进程将继承桌面 //和其父进程的窗口站。如果此成员 //如果为空字符串,则进程不会继承桌面和 //其父进程的窗口站;而是系统 //确定是否需要创建新的桌面和窗口工作站。 //如果模拟用户已经有桌面,系统将使用 //现有桌面。 si.lpDesktop=@“WinSta0\Default”;//默认Vista/7桌面会话 si.dwFlags=STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK; //检查进程的启动模式 如果(WindowMode==1) si.wShowWindow=SW_SHOW; 否则如果(WindowMode==2) {//什么也不做 } 否则如果(WindowMode==3) si.wShowWindow=0;//隐藏窗口 否则如果(WindowMode==4) si.wShowWindow=3;//最大化窗口 否则如果(WindowMode==5) si.wShowWindow=6;//最小化窗口 其他的 si.wShowWindow=SW_SHOW; //根据需要设置其他si属性。 结果=CreateProcessAsUser( 代币 无效的 cmdLine, 参考saProcess, 参考saThread, 假,, 创建UNICODE环境, 环境块, 无效的 参考si, 输出pi); 如果(结果==false) { int error=Marshal.GetLastWin32Error(); string message=string.Format(“CreateProcessAsUser错误:{0}”,错误); Debug.WriteLine(消息); } 返回结果; } 私有静态IntPtr GetPrimaryToken(int进程ID) { IntPtr令牌=IntPtr.Zero; IntPtr primaryToken=IntPtr.Zero; bool-retVal=false; 进程p=null; 尝试 { p=Process.GetProcessById(processId); } 捕获(异常) { string details=string.Format(“ProcessID{0}不可用”,ProcessID); Debug.WriteLine(细节); 投掷; } //获取模拟令牌 retVal=OpenProcessToken(p.Handle,TOKEN\u DUPLICATE,ref TOKEN); 如果(retVal==true) { 安全属性sa=新的安全属性(); sa.nLength=(uint)marshall.SizeOf(sa); //将模拟令牌转换为主令牌 retVal=DuplicateTokenEx( 代币 令牌|分配|主|令牌|重复|令牌|查询, 参考sa, (int)安全性\模拟\级别安全性标识, (int)TOKEN_TYPE.TokenPrimary, ref primaryToken); //关闭以前打开的令牌。 闭合手柄(令牌); 如果(retVal==false) { string message=string.Format(“DuplicateTokenEx错误:{0}”,Marshal.GetLastWin32Error()); Debug.WriteLine(消息); } } 其他的 { string message=string.Format(“OpenProcessToken错误:{0}”,Marshal.GetLastWin32Error()); Debug.WriteLine(消息); } //我们将在使用此令牌后关闭它。 返回主令牌; } 专用静态IntPtr GetEnvironmentBlock(IntPtr令牌) { IntPtr envBlock=IntPtr.Zero; bool retVal=CreateEnvironmentBlock(ref envBlock,token,false); 如果(retVal==false) { //环境块,例如指向我的文档的公共路径等。 //如果为“false”,则不会创建 //它不应影响CreateProcessAsUser。 string message=string.Format(“CreateEnvironmentBlock错误:{0}”,Marshal.GetLastWin32Error()); Debug.WriteLine(消息); } 返回块; } 公共静态bool启动(字符串appCmdLine/*,int-processId*/) { bool-ret=假; //或者显式指定processID //或者尝试从用户拥有的进程获取它。 //在这种情况下,假设只有一个explorer.exe Process[]ps=Process.getProcessByName(“资源管理器”); int processId=-1;//=processId 如果(ps.Length>0) { processId=ps[0].Id; } 如果(进程ID>1) { IntPtr-token=GetPrimaryToken(processId); if(令牌!=IntPtr.Zero) { IntPtr envBlock=GetEnvironmentBlock(令牌); ret=启动ProcessAsUser(appCmdLine、令牌、envBlock); if(envBlock!=IntPtr.Zero) 破坏环境块(envBlock); 闭合手柄(令牌); } } 返回ret; }_C#_.net_Process_Admin Rights - Fatal编程技术网

C# 如果(结果==false) { int error=Marshal.GetLastWin32Error(); string message=string.Format(“CreateProcessAsUser错误:{0}”,错误); Debug.WriteLine(消息); } 返回结果; } /// ///当用户重载窗口模式时启动进程 /// /// /// /// /// /// 专用静态bool LaunchProcessAsUser(字符串cmdLine、IntPtr令牌、IntPtr envBlock、uint WindowMode) { 布尔结果=假; 流程信息pi=新流程信息(); 安全属性saProcess=新的安全属性(); SECURITY_ATTRIBUTES saThread=新的SECURITY_ATTRIBUTES(); saProcess.nLength=(uint)Marshal.SizeOf(saProcess); saThread.nLength=(uint)Marshal.SizeOf(saThread); STARTUPINFO si=新的STARTUPINFO(); si.cb=(uint)marshall.SizeOf(si); //如果此成员为NULL,则新进程将继承桌面 //和其父进程的窗口站。如果此成员 //如果为空字符串,则进程不会继承桌面和 //其父进程的窗口站;而是系统 //确定是否需要创建新的桌面和窗口工作站。 //如果模拟用户已经有桌面,系统将使用 //现有桌面。 si.lpDesktop=@“WinSta0\Default”;//默认Vista/7桌面会话 si.dwFlags=STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK; //检查进程的启动模式 如果(WindowMode==1) si.wShowWindow=SW_SHOW; 否则如果(WindowMode==2) {//什么也不做 } 否则如果(WindowMode==3) si.wShowWindow=0;//隐藏窗口 否则如果(WindowMode==4) si.wShowWindow=3;//最大化窗口 否则如果(WindowMode==5) si.wShowWindow=6;//最小化窗口 其他的 si.wShowWindow=SW_SHOW; //根据需要设置其他si属性。 结果=CreateProcessAsUser( 代币 无效的 cmdLine, 参考saProcess, 参考saThread, 假,, 创建UNICODE环境, 环境块, 无效的 参考si, 输出pi); 如果(结果==false) { int error=Marshal.GetLastWin32Error(); string message=string.Format(“CreateProcessAsUser错误:{0}”,错误); Debug.WriteLine(消息); } 返回结果; } 私有静态IntPtr GetPrimaryToken(int进程ID) { IntPtr令牌=IntPtr.Zero; IntPtr primaryToken=IntPtr.Zero; bool-retVal=false; 进程p=null; 尝试 { p=Process.GetProcessById(processId); } 捕获(异常) { string details=string.Format(“ProcessID{0}不可用”,ProcessID); Debug.WriteLine(细节); 投掷; } //获取模拟令牌 retVal=OpenProcessToken(p.Handle,TOKEN\u DUPLICATE,ref TOKEN); 如果(retVal==true) { 安全属性sa=新的安全属性(); sa.nLength=(uint)marshall.SizeOf(sa); //将模拟令牌转换为主令牌 retVal=DuplicateTokenEx( 代币 令牌|分配|主|令牌|重复|令牌|查询, 参考sa, (int)安全性\模拟\级别安全性标识, (int)TOKEN_TYPE.TokenPrimary, ref primaryToken); //关闭以前打开的令牌。 闭合手柄(令牌); 如果(retVal==false) { string message=string.Format(“DuplicateTokenEx错误:{0}”,Marshal.GetLastWin32Error()); Debug.WriteLine(消息); } } 其他的 { string message=string.Format(“OpenProcessToken错误:{0}”,Marshal.GetLastWin32Error()); Debug.WriteLine(消息); } //我们将在使用此令牌后关闭它。 返回主令牌; } 专用静态IntPtr GetEnvironmentBlock(IntPtr令牌) { IntPtr envBlock=IntPtr.Zero; bool retVal=CreateEnvironmentBlock(ref envBlock,token,false); 如果(retVal==false) { //环境块,例如指向我的文档的公共路径等。 //如果为“false”,则不会创建 //它不应影响CreateProcessAsUser。 string message=string.Format(“CreateEnvironmentBlock错误:{0}”,Marshal.GetLastWin32Error()); Debug.WriteLine(消息); } 返回块; } 公共静态bool启动(字符串appCmdLine/*,int-processId*/) { bool-ret=假; //或者显式指定processID //或者尝试从用户拥有的进程获取它。 //在这种情况下,假设只有一个explorer.exe Process[]ps=Process.getProcessByName(“资源管理器”); int processId=-1;//=processId 如果(ps.Length>0) { processId=ps[0].Id; } 如果(进程ID>1) { IntPtr-token=GetPrimaryToken(processId); if(令牌!=IntPtr.Zero) { IntPtr envBlock=GetEnvironmentBlock(令牌); ret=启动ProcessAsUser(appCmdLine、令牌、envBlock); if(envBlock!=IntPtr.Zero) 破坏环境块(envBlock); 闭合手柄(令牌); } } 返回ret; }

C# 如果(结果==false) { int error=Marshal.GetLastWin32Error(); string message=string.Format(“CreateProcessAsUser错误:{0}”,错误); Debug.WriteLine(消息); } 返回结果; } /// ///当用户重载窗口模式时启动进程 /// /// /// /// /// /// 专用静态bool LaunchProcessAsUser(字符串cmdLine、IntPtr令牌、IntPtr envBlock、uint WindowMode) { 布尔结果=假; 流程信息pi=新流程信息(); 安全属性saProcess=新的安全属性(); SECURITY_ATTRIBUTES saThread=新的SECURITY_ATTRIBUTES(); saProcess.nLength=(uint)Marshal.SizeOf(saProcess); saThread.nLength=(uint)Marshal.SizeOf(saThread); STARTUPINFO si=新的STARTUPINFO(); si.cb=(uint)marshall.SizeOf(si); //如果此成员为NULL,则新进程将继承桌面 //和其父进程的窗口站。如果此成员 //如果为空字符串,则进程不会继承桌面和 //其父进程的窗口站;而是系统 //确定是否需要创建新的桌面和窗口工作站。 //如果模拟用户已经有桌面,系统将使用 //现有桌面。 si.lpDesktop=@“WinSta0\Default”;//默认Vista/7桌面会话 si.dwFlags=STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK; //检查进程的启动模式 如果(WindowMode==1) si.wShowWindow=SW_SHOW; 否则如果(WindowMode==2) {//什么也不做 } 否则如果(WindowMode==3) si.wShowWindow=0;//隐藏窗口 否则如果(WindowMode==4) si.wShowWindow=3;//最大化窗口 否则如果(WindowMode==5) si.wShowWindow=6;//最小化窗口 其他的 si.wShowWindow=SW_SHOW; //根据需要设置其他si属性。 结果=CreateProcessAsUser( 代币 无效的 cmdLine, 参考saProcess, 参考saThread, 假,, 创建UNICODE环境, 环境块, 无效的 参考si, 输出pi); 如果(结果==false) { int error=Marshal.GetLastWin32Error(); string message=string.Format(“CreateProcessAsUser错误:{0}”,错误); Debug.WriteLine(消息); } 返回结果; } 私有静态IntPtr GetPrimaryToken(int进程ID) { IntPtr令牌=IntPtr.Zero; IntPtr primaryToken=IntPtr.Zero; bool-retVal=false; 进程p=null; 尝试 { p=Process.GetProcessById(processId); } 捕获(异常) { string details=string.Format(“ProcessID{0}不可用”,ProcessID); Debug.WriteLine(细节); 投掷; } //获取模拟令牌 retVal=OpenProcessToken(p.Handle,TOKEN\u DUPLICATE,ref TOKEN); 如果(retVal==true) { 安全属性sa=新的安全属性(); sa.nLength=(uint)marshall.SizeOf(sa); //将模拟令牌转换为主令牌 retVal=DuplicateTokenEx( 代币 令牌|分配|主|令牌|重复|令牌|查询, 参考sa, (int)安全性\模拟\级别安全性标识, (int)TOKEN_TYPE.TokenPrimary, ref primaryToken); //关闭以前打开的令牌。 闭合手柄(令牌); 如果(retVal==false) { string message=string.Format(“DuplicateTokenEx错误:{0}”,Marshal.GetLastWin32Error()); Debug.WriteLine(消息); } } 其他的 { string message=string.Format(“OpenProcessToken错误:{0}”,Marshal.GetLastWin32Error()); Debug.WriteLine(消息); } //我们将在使用此令牌后关闭它。 返回主令牌; } 专用静态IntPtr GetEnvironmentBlock(IntPtr令牌) { IntPtr envBlock=IntPtr.Zero; bool retVal=CreateEnvironmentBlock(ref envBlock,token,false); 如果(retVal==false) { //环境块,例如指向我的文档的公共路径等。 //如果为“false”,则不会创建 //它不应影响CreateProcessAsUser。 string message=string.Format(“CreateEnvironmentBlock错误:{0}”,Marshal.GetLastWin32Error()); Debug.WriteLine(消息); } 返回块; } 公共静态bool启动(字符串appCmdLine/*,int-processId*/) { bool-ret=假; //或者显式指定processID //或者尝试从用户拥有的进程获取它。 //在这种情况下,假设只有一个explorer.exe Process[]ps=Process.getProcessByName(“资源管理器”); int processId=-1;//=processId 如果(ps.Length>0) { processId=ps[0].Id; } 如果(进程ID>1) { IntPtr-token=GetPrimaryToken(processId); if(令牌!=IntPtr.Zero) { IntPtr envBlock=GetEnvironmentBlock(令牌); ret=启动ProcessAsUser(appCmdLine、令牌、envBlock); if(envBlock!=IntPtr.Zero) 破坏环境块(envBlock); 闭合手柄(令牌); } } 返回ret; },c#,.net,process,admin-rights,C#,.net,Process,Admin Rights,Ref: // //Vista或更高版本检查 if (System.Environment.OSVersion.Version.Major >= 6) { p.StartInfo.Verb = "runas"; } Ref:ASP.net论坛 另一种方法是模拟管理员用户。你可以这样做 调用登录函数并模拟其tok的用户 Process process = null; ProcessStartInfo processStartInfo = new ProcessStartInfo(

Ref:

//

//Vista或更高版本检查

if (System.Environment.OSVersion.Version.Major >= 6)
{
   p.StartInfo.Verb = "runas";
}
Ref:ASP.net论坛

另一种方法是模拟管理员用户。你可以这样做 调用登录函数并模拟其tok的用户
Process process = null;
ProcessStartInfo processStartInfo = new ProcessStartInfo();

processStartInfo.FileName = "WINZIP32.EXE";

processStartInfo.Verb = "runas";
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
processStartInfo.UseShellExecute = true;

process = Process.Start(processStartInfo);
    [StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_INFORMATION
{
    public IntPtr hProcess;
    public IntPtr hThread;
    public uint dwProcessId;
    public uint dwThreadId;
}

[StructLayout(LayoutKind.Sequential)]
internal struct SECURITY_ATTRIBUTES
{
    public uint nLength;
    public IntPtr lpSecurityDescriptor;
    public bool bInheritHandle;
}

[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
    public uint cb;
    public string lpReserved;
    public string lpDesktop;
    public string lpTitle;
    public uint dwX;
    public uint dwY;
    public uint dwXSize;
    public uint dwYSize;
    public uint dwXCountChars;
    public uint dwYCountChars;
    public uint dwFillAttribute;
    public uint dwFlags;
    public short wShowWindow;
    public short cbReserved2;
    public IntPtr lpReserved2;
    public IntPtr hStdInput;
    public IntPtr hStdOutput;
    public IntPtr hStdError;

}

internal enum SECURITY_IMPERSONATION_LEVEL
{
    SecurityAnonymous,
    SecurityIdentification,
    SecurityImpersonation,
    SecurityDelegation
}

internal enum TOKEN_TYPE
{
    TokenPrimary = 1,
    TokenImpersonation
}

public class ProcessAsUser
{

    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool CreateProcessAsUser(
    IntPtr hToken,
    string lpApplicationName,
    string lpCommandLine,
    ref SECURITY_ATTRIBUTES lpProcessAttributes,
    ref SECURITY_ATTRIBUTES lpThreadAttributes,
    bool bInheritHandles,
    uint dwCreationFlags,
    IntPtr lpEnvironment,
    string lpCurrentDirectory,
    ref STARTUPINFO lpStartupInfo,
    out PROCESS_INFORMATION lpProcessInformation);

    [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx", SetLastError = true)]
    private static extern bool DuplicateTokenEx(
    IntPtr hExistingToken,
    uint dwDesiredAccess,
    ref SECURITY_ATTRIBUTES lpThreadAttributes,
    Int32 ImpersonationLevel,
    Int32 dwTokenType,
    ref IntPtr phNewToken);

    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool OpenProcessToken(
    IntPtr ProcessHandle,
    UInt32 DesiredAccess,
    ref IntPtr TokenHandle);

    [DllImport("userenv.dll", SetLastError = true)]
    private static extern bool CreateEnvironmentBlock(
    ref IntPtr lpEnvironment,
    IntPtr hToken,
    bool bInherit);

    [DllImport("userenv.dll", SetLastError = true)]
    private static extern bool DestroyEnvironmentBlock(
    IntPtr lpEnvironment);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool CloseHandle(
    IntPtr hObject);

    private const short SW_SHOW = 5;
    private const uint TOKEN_QUERY = 0x0008;
    private const uint TOKEN_DUPLICATE = 0x0002;
    private const uint TOKEN_ASSIGN_PRIMARY = 0x0001;
    private const int GENERIC_ALL_ACCESS = 0x10000000;
    private const int STARTF_USESHOWWINDOW = 0x00000001;
    private const int STARTF_FORCEONFEEDBACK = 0x00000040;
    private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
    private const int STARTF_RUNFULLSCREEN = 0x00000020;

    private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock)
    {
        bool result = false;

        PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
        SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
        SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
        saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
        saThread.nLength = (uint)Marshal.SizeOf(saThread);

        STARTUPINFO si = new STARTUPINFO();
        si.cb = (uint)Marshal.SizeOf(si);

        //if this member is NULL, the new process inherits the desktop
        //and window station of its parent process. If this member is
        //an empty string, the process does not inherit the desktop and
        //window station of its parent process; instead, the system
        //determines if a new desktop and window station need to be created.
        //If the impersonated user already has a desktop, the system uses the
        //existing desktop.

        si.lpDesktop = @"WinSta0\Default"; //Modify as needed
        si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;
        si.wShowWindow = SW_SHOW;

        //Set other si properties as required.

        result = CreateProcessAsUser(
        token,
        null,
        cmdLine,
        ref saProcess,
        ref saThread,
        false,
        CREATE_UNICODE_ENVIRONMENT,
        envBlock,
        null,
        ref si,
        out pi);

        if (result == false)
        {
            int error = Marshal.GetLastWin32Error();
            string message = String.Format("CreateProcessAsUser Error: {0}", error);
            Debug.WriteLine(message);

        }

        return result;
    }

    /// <summary>
    /// LaunchProcess As User Overloaded for Window Mode 
    /// </summary>
    /// <param name="cmdLine"></param>
    /// <param name="token"></param>
    /// <param name="envBlock"></param>
    /// <param name="WindowMode"></param>
    /// <returns></returns>
    private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock,uint WindowMode)
    {
        bool result = false;

        PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
        SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
        SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
        saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
        saThread.nLength = (uint)Marshal.SizeOf(saThread);

        STARTUPINFO si = new STARTUPINFO();
        si.cb = (uint)Marshal.SizeOf(si);

        //if this member is NULL, the new process inherits the desktop
        //and window station of its parent process. If this member is
        //an empty string, the process does not inherit the desktop and
        //window station of its parent process; instead, the system
        //determines if a new desktop and window station need to be created.
        //If the impersonated user already has a desktop, the system uses the
        //existing desktop.

        si.lpDesktop = @"WinSta0\Default"; //Default Vista/7 Desktop Session
        si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;

        //Check the Startup Mode of the Process 
        if (WindowMode == 1)
            si.wShowWindow = SW_SHOW;
        else if (WindowMode == 2)
        { //Do Nothing
        }
        else if (WindowMode == 3)
            si.wShowWindow = 0; //Hide Window 
        else if (WindowMode == 4)
            si.wShowWindow = 3; //Maximize Window
        else if (WindowMode == 5)
            si.wShowWindow = 6; //Minimize Window
        else
            si.wShowWindow = SW_SHOW;


        //Set other si properties as required.
        result = CreateProcessAsUser(
        token,
        null,
        cmdLine,
        ref saProcess,
        ref saThread,
        false,
        CREATE_UNICODE_ENVIRONMENT,
        envBlock,
        null,
        ref si,
        out pi);

        if (result == false)
        {
            int error = Marshal.GetLastWin32Error();
            string message = String.Format("CreateProcessAsUser Error: {0}", error);
            Debug.WriteLine(message);

        }

        return result;
    }

    private static IntPtr GetPrimaryToken(int processId)
    {
        IntPtr token = IntPtr.Zero;
        IntPtr primaryToken = IntPtr.Zero;
        bool retVal = false;
        Process p = null;

        try
        {
            p = Process.GetProcessById(processId);
        }

        catch (ArgumentException)
        {

            string details = String.Format("ProcessID {0} Not Available", processId);
            Debug.WriteLine(details);
            throw;
        }

        //Gets impersonation token
        retVal = OpenProcessToken(p.Handle, TOKEN_DUPLICATE, ref token);
        if (retVal == true)
        {

            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
            sa.nLength = (uint)Marshal.SizeOf(sa);

            //Convert the impersonation token into Primary token
            retVal = DuplicateTokenEx(
            token,
            TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY,
            ref sa,
            (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
            (int)TOKEN_TYPE.TokenPrimary,
            ref primaryToken);

            //Close the Token that was previously opened.
            CloseHandle(token);
            if (retVal == false)
            {
                string message = String.Format("DuplicateTokenEx Error: {0}", Marshal.GetLastWin32Error());
                Debug.WriteLine(message);
            }

        }

        else
        {

            string message = String.Format("OpenProcessToken Error: {0}", Marshal.GetLastWin32Error());
            Debug.WriteLine(message);

        }

        //We'll Close this token after it is used.
        return primaryToken;

    }

    private static IntPtr GetEnvironmentBlock(IntPtr token)
    {

        IntPtr envBlock = IntPtr.Zero;
        bool retVal = CreateEnvironmentBlock(ref envBlock, token, false);
        if (retVal == false)
        {

            //Environment Block, things like common paths to My Documents etc.
            //Will not be created if "false"
            //It should not adversley affect CreateProcessAsUser.

            string message = String.Format("CreateEnvironmentBlock Error: {0}", Marshal.GetLastWin32Error());
            Debug.WriteLine(message);

        }
        return envBlock;
    }

    public static bool Launch(string appCmdLine /*,int processId*/)
    {

        bool ret = false;

        //Either specify the processID explicitly
        //Or try to get it from a process owned by the user.
        //In this case assuming there is only one explorer.exe

        Process[] ps = Process.GetProcessesByName("explorer");
        int processId = -1;//=processId
        if (ps.Length > 0)
        {
            processId = ps[0].Id;
        }

        if (processId > 1)
        {
            IntPtr token = GetPrimaryToken(processId);

            if (token != IntPtr.Zero)
            {

                IntPtr envBlock = GetEnvironmentBlock(token);
                ret = LaunchProcessAsUser(appCmdLine, token, envBlock);
                if (envBlock != IntPtr.Zero)
                    DestroyEnvironmentBlock(envBlock);

                CloseHandle(token);
            }

        }
        return ret;
    }
  var psi = new ProcessStartInfo
    {
        FileName = "notepad",
        UserName = "admin",
        Domain = "",
        Password = pass,
        UseShellExecute = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        Verb = "runas";
    };
    Process.Start(psi);
var pass = new SecureString();
pass.AppendChar('s');
pass.AppendChar('e');
pass.AppendChar('c');
pass.AppendChar('r');
pass.AppendChar('e');
pass.AppendChar('t');
Process.Start("notepad", "admin", pass, "");
if (System.Environment.OSVersion.Version.Major >= 6)
{
   p.StartInfo.Verb = "runas";
}
System.Diagnostics.Process process = null;
System.Diagnostics.ProcessStartInfo processStartInfo;

processStartInfo = new System.Diagnostics.ProcessStartInfo();

processStartInfo.FileName = "regedit.exe";

if (System.Environment.OSVersion.Version.Major >= 6)  // Windows Vista or higher
{
   processStartInfo.Verb = "runas";
}
else
{
   // No need to prompt to run as admin
}

processStartInfo.Arguments = "";
processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
processStartInfo.UseShellExecute = true;

try
{
   process = System.Diagnostics.Process.Start(processStartInfo);
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
   if (process != null)
   {
      process.Dispose();
   }
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

        // Test harness.
        // If you incorporate this code into a DLL, be sure to demand FullTrust.
        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        private void button1_Click(object sender, EventArgs e)
        {
            SafeTokenHandle safeTokenHandle;
            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;
            bool returnValue = LogonUser("administrator", "", "password",
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                out safeTokenHandle);

            Console.WriteLine("LogonUser called.");

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                Console.WriteLine("LogonUser failed with error code : {0}", ret);
                throw new System.ComponentModel.Win32Exception(ret);
            }
            using (safeTokenHandle)
            {
                Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);

                // Check the identity.
                Console.WriteLine("Before impersonation: "
                    + WindowsIdentity.GetCurrent().Name);
                // Use the token handle returned by LogonUser.
                WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                {
                    System.Diagnostics.Process process = null;
                    System.Diagnostics.ProcessStartInfo processStartInfo;


                    processStartInfo = new System.Diagnostics.ProcessStartInfo();

                    processStartInfo.FileName = "regedit.exe";

                    //if (System.Environment.OSVersion.Version.Major >= 6)  // Windows Vista or higher
                    //{
                    //    processStartInfo.Verb = "runas";
                    //}
                    //else
                    //{
                    //    // No need to prompt to run as admin
                    //}

                    processStartInfo.Arguments = "";
                    processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                    processStartInfo.UseShellExecute = true;

                    try
                    {
                        process = System.Diagnostics.Process.Start(processStartInfo);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        if (process != null)
                        {
                            process.Dispose();
                        }
                    }

                    // Check the identity.
                    Console.WriteLine("After impersonation: "
                        + WindowsIdentity.GetCurrent().Name);
                }
                // Releasing the context object stops the impersonation
                // Check the identity.
                Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
            }
        }