我有一个应用程序,我必须以管理员身份运行。

该应用程序的一小部分是使用Process.Start启动其他应用程序

启动的应用程序也将作为管理员运行,但我宁愿看到它们作为“普通”用户运行。

我该如何做到这一点?

/约翰/

WinSafer API允许一个进程作为有限的,普通的或升级的用户启动。

样品用法:

CreateSaferProcess(@"calc.exe","",SaferLevel.normalUser);

源代码:

//http://odetocode.com/Blogs/scott/archive/2004/10/28/602.aspx
public static void CreateSaferProcess(String fileName,String arguments,SaferLevel saferLevel)
{
   IntPtr saferLevelHandle = IntPtr.Zero;

   //Create a SaferLevel handle to match what was requested
   if (!WinSafer.SaferCreateLevel(
         SaferLevelScope.User,saferLevel,SaferOpen.Open,out saferLevelHandle,IntPtr.Zero))
   {
      throw new Win32Exception(Marshal.GetLastWin32Error());
   }
   try
   {
      //Generate the access token to use,based on the safer level handle.
      IntPtr hToken = IntPtr.Zero;

      if (!WinSafer.SaferComputetokenFromLevel(
            saferLevelHandle,// SAFER Level handle
            IntPtr.Zero,// NULL is current thread token.
            out hToken,// Target token
            SaferTokenBehavIoUr.Default,// No flags
            IntPtr.Zero))      // Reserved
      {
         throw new Win32Exception(Marshal.GetLastWin32Error());
      }
      try
      {
         //Now that we have a security token,we can lauch the process
         //using the standard CreateProcessAsUser API
         STARTUPINFO si = new STARTUPINFO();
         si.cb = Marshal.SizeOf(si);
         si.lpDesktop = String.Empty;

         PROCESS_informatION pi = new PROCESS_informatION();

         // Spin up the new process
         Boolean bResult = Windows.CreateProcessAsUser(
               hToken,fileName,arguments,IntPtr.Zero,//process attributes
               IntPtr.Zero,//thread attributes
               false,//inherit handles
               0,//CREATE_NEW_CONSOLE
               IntPtr.Zero,//environment
               null,//current directory
               ref si,//startup info
               out pi); //process info

         if (!bResult)
            throw new Win32Exception(Marshal.GetLastWin32Error());

         if (pi.hProcess != IntPtr.Zero)
            Windows.CloseHandle(pi.hProcess);

         if (pi.hThread != IntPtr.Zero)
            Windows.CloseHandle(pi.hThread);
      }
      finally
      {
         if (hToken != IntPtr.Zero)
            Windows.CloseHandle(hToken);
      }
   }
   finally
   {
      WinSafer.SaferCloseLevel(saferLevelHandle);
   }
}

P /调用声明:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace PInvoke
{
   public class WinSafer
   {
      /// <summary>
      /// The SaferCreateLevel function opens a SAFER_LEVEL_HANDLE.
      /// </summary>
      /// <param name="scopeId">The scope of the level to be created.</param>
      /// <param name="levelId">The level of the handle to be opened.</param>
      /// <param name="openFlags">Must be SaferOpenFlags.Open</param>
      /// <param name="levelHandle">The returned SAFER_LEVEL_HANDLE. When you have finished using the handle,release it by calling the SaferCloseLevel function.</param>
      /// <param name="reserved">This parameter is reserved for future use. IntPtr.Zero</param>
      /// <returns></returns>
      [DllImport("advapi32",SetLastError = true,CallingConvention = CallingConvention.StdCall)]
      public static extern bool SaferCreateLevel(SaferLevelScope scopeId,SaferLevel levelId,SaferOpen openFlags,out IntPtr levelHandle,IntPtr reserved);

      /// <summary>
      /// The SaferComputetokenFromLevel function restricts a token using restrictions specified by a SAFER_LEVEL_HANDLE.
      /// </summary>
      /// <param name="levelHandle">SAFER_LEVEL_HANDLE that contains the restrictions to place on the input token. Do not pass handles with a LevelId of SAFER_LEVELID_FULLYTRUSTED or SAFER_LEVELID_disALLOWED to this function. This is because SAFER_LEVELID_FULLYTRUSTED is unrestricted and SAFER_LEVELID_disALLOWED does not contain a token.</param>
      /// <param name="inAccesstoken">Token to be restricted. If this parameter is NULL,the token of the current thread will be used. If the current thread does not contain a token,the token of the current process is used.</param>
      /// <param name="outAccesstoken">The resulting restricted token.</param>
      /// <param name="flags">Specifies the behavior of the method.</param>
      /// <param name="lpReserved">Reserved for future use. This parameter should be set to IntPtr.EmptyParam.</param>
      /// <returns></returns>
      [DllImport("advapi32",CallingConvention = CallingConvention.StdCall)]
      public static extern bool SaferComputetokenFromLevel(IntPtr levelHandle,IntPtr inAccesstoken,out IntPtr outAccesstoken,SaferTokenBehavIoUr flags,IntPtr lpReserved);

      /// <summary>
      /// The SaferCloseLevel function closes a SAFER_LEVEL_HANDLE that was opened by using the SaferIdentifyLevel function or the SaferCreateLevel function.</summary>
      /// <param name="levelHandle">The SAFER_LEVEL_HANDLE to be closed.</param>
      /// <returns>TRUE if the function succeeds; otherwise,FALSE. For extended error information,call GetLastWin32Error.</returns>
      [DllImport("advapi32",CallingConvention = CallingConvention.StdCall)]
      public static extern bool SaferCloseLevel(IntPtr levelHandle);
   } //class WinSafer

   /// <summary>
   /// Specifies the behavIoUr of the SaferComputetokenFromLevel method
   /// </summary>
   public enum SaferTokenBehavIoUr : uint
   {
      /// <summary></summary>
      Default = 0x0,/// <summary>If the OutAccesstoken parameter is not more restrictive than the InAccesstoken parameter,the OutAccesstoken parameter returns NULL.</summary>
      NullIfEqual = 0x1,/// <summary></summary>
      CompareOnly = 0x2,/// <summary></summary>
      MakeInert = 0x4,/// <summary></summary>
      WantFlags = 0x8
   }

   /// <summary>
   /// The level of the handle to be opened.
   /// </summary>
   public enum SaferLevel : uint
   {
      /// <summary>Software will not run,regardless of the user rights of the user.</summary>
      disallowed = 0,/// <summary>Allows programs to execute with access only to resources granted to open well-kNown groups,blocking access to Administrator and Power User privileges and personally granted rights.</summary>
      Untrusted = 0x1000,/// <summary>Software cannot access certain resources,such as cryptographic keys and credentials,regardless of the user rights of the user.</summary>
      Constrained = 0x10000,/// <summary>Allows programs to execute as a user that does not have Administrator or Power User user rights. Software can access resources accessible by normal users.</summary>
      normalUser = 0x20000,/// <summary>Software user rights are determined by the user rights of the user.</summary>
      FullyTrusted = 0x40000
   }

   /// <summary>
   /// The scope of the level to be created.
   /// </summary>
   public enum SaferLevelScope : uint
   {
      /// <summary>The created level is scoped by computer.</summary>
      Machine = 1,/// <summary>The created level is scoped by user.</summary>
      User = 2
   }

   public enum SaferOpen : uint
   {
      Open = 1
   }
} //namespace PInvoke

如何运行在Vista(.NET)中没有提升的更多相关文章

  1. ios – 我可以安全地在@try catch块中包装’CoreData无法解决错误’错误

    )是的,我偶尔会得到’CoreData无法完成故障’的错误.在我的特定应用程序中,这通常发生在一种“数据绑定”过程中,因此我可以安全地丢弃故障对象并继续前进.我想通过在@try-catch块中包装数据绑定的循环内部并且只跳过我得到CoreData错误的行来完成此操作.我可以使用CoreData安全地执行此操作吗?

  2. 你如何压缩iOS上的Realm DB?

    我想定期在iOS上压缩一个Realm实例来恢复空间.我认为该过程是将数据库复制到临时位置,然后将其复制回来并使用新的default.realm文件.我的问题是Realm()就像一个单例并且回收对象,所以我无法真正关闭它并告诉它打开新的default.realm文件.这里的文档(https://realm.io/docs/objc/latest/api/Classes/RLMRealm.html)建

  3. ios – 捕获NSKeyedUnarchiver异常

    在Swift中,如果无法取消存档数据,NSKeyedUnarchiver.unarchiveObjectWithData(data)将抛出异常.在某些情况下,我们无法保证数据是否未损坏,例如从文件读取时.我不知道Swift中的try/catch机制,也不知道像canUnarchive这样有助于防止异常的方法.除了在Obj-C中实现try/catch之外,还有一个纯Swift解决方案来解决这个问题吗

  4. ios – 使用swift进行异常处理

    catch来处理它.如果故事板中没有视图控制器,则无法执行任何操作.这是程序员的错误,创建它的人应该处理这些问题.你不能因为这种错误而责怪iOS运行时.

  5. ios – Swift 3 – 将文件夹从主包复制到文档目录

    我的主要包中包含文件夹,我想在首次启动应用程序时将它们复制/剪切到文档目录,以便从那里访问它们.我见过一些例子,但他们都在Obj-C中,我正在使用Swift3.我怎么能这样做?解决方法我设法使用2个功能:

  6. Swift 2.0 try? 的替代方法

    你可以配合着if-let或者guard语句来使用try?但你可以试着写出try?实际上我也不太喜欢tryit这个名字,你用你喜欢的名字代替就好。你可以以同样的方法调用它:你仍然不能基于错误类型和错误细节来制定错误处理策略,但是这种实现方式也不像try?你也可以修改tryit函数,让它也能接受做错误处理的代码块,但因为要处理两种不同的代码块,这个函数就会变得相当臃肿。如果要用try而且又需要进行错误处理的话,你就必须得用do-catch或者像结果枚举之类的其它方法了。

  7. The Swift Programming Language 翻译 —— 错误处理

    Swift支持抛出、捕获、传递和操作等四种方式来处理程序运行时出现的可恢复性错误。表示错误类型在Swift中,错误类型用继承了ErrorType协议的类型来表示。Swift中处理错误的方式有如下四种:使用throw关键字继续向上传递这个错误、使用do-catch表达式处理这个错误、使用try?下面例子中的buyFavoriteSnack方法调用了vend方法,任何vend方法抛出的错误都将传递给他,他选择继续向上传递这些错误。x和y的类型是someThrowingFunction()的返回值类型对应的可选

  8. Swift 2 jSON Call can throw but it is not marked with try

    NSDictionary第一种用法:第二种用法:letjsonData=tryNSJSONSerialization.JSONObjectWithData(urlData!

  9. Swift2.0提供所try catch异常捕捉

    原代码中,AVAudioPlayer的构造函数有了可抛出错误的重载函数,现在的原型不接受第二个error参数,函数不再为failable,应使用trycatch捕捉异常

  10. Swift 读取本地json文件时的异常捕获(try catch)的使用

    Swift读取本地json文件时的异常捕获(trycatch)的使用

随机推荐

  1. static – 在页面之间共享数据的最佳实践

    我想知道在UWP的页面之间发送像’selectedItem’等变量的最佳做法是什么?创建一个每个页面都知道的静态全局变量类是一个好主意吗?

  2. .net – 为Windows窗体控件提供百分比宽度/高度

    WindowsForm开发的新手,但在Web开发方面经验丰富.有没有办法为Windows窗体控件指定百分比宽度/高度,以便在用户调整窗口大小时扩展/缩小?当窗口调整大小时,可以编写代码来改变控件的宽度/高度,但我希望有更好的方法,比如在HTML/CSS中.在那儿?

  3. 使用Windows Azure查询表存储数据

    我需要使用特定帐户吗?>将应用程序部署到Azure服务后,如何查询数据?GoogleAppEngine有一个数据查看器/查询工具,Azure有类似的东西吗?>您可以看到的sqlExpressintance仅在开发结构中,并且一旦您表示没有等效,所以请小心使用它.>您可以尝试使用Linqpad查询表格.看看JamieThomson的thispost.

  4. windows – SetupDiGetClassDevs是否与文档中的设备实例ID一起使用?

    有没有更好的方法可以使用DBT_DEVICEARRIVAL事件中的数据获取设备的更多信息?您似乎必须指定DIGCF_ALLCLASSES标志以查找与给定设备实例ID匹配的所有类,或者指定ClassGuid并使用DIGCF_DEFAULT标志.这对我有用:带输出:

  5. Windows Live ID是OpenID提供商吗?

    不,WindowsLiveID不是OpenID提供商.他们使用专有协议.自从他们的“测试版”期结束以来,他们从未宣布计划继续它.

  6. 如果我在代码中进行了更改,是否需要重新安装Windows服务?

    我写了一个Windows服务并安装它.现在我对代码进行了一些更改并重新构建了解决方案.我还应该重新安装服务吗?不,只需停止它,替换文件,然后重新启动它.

  7. 带有双引号的字符串回显使用Windows批处理输出文件

    我正在尝试使用Windows批处理文件重写配置文件.我循环遍历文件的行并查找我想要用指定的新行替换的行.我有一个’函数’将行写入文件问题是%Text%是一个嵌入双引号的字符串.然后失败了.可能还有其他角色也会导致失败.如何才能使用配置文件中的所有文本?尝试将所有“在文本中替换为^”.^是转义字符,因此“将被视为常规字符你可以尝试以下方法:其他可能导致错误的字符是:

  8. .net – 将控制台应用程序转换为服务?

    我正在寻找不同的优势/劣势,将我们长期使用的控制台应用程序转换为Windows服务.我们为ActiveMQ使用了一个叫做java服务包装器的东西,我相信人们告诉我你可以用它包装任何东西.这并不是说你应该用它包装任何东西;我们遇到了这个问题.控制台应用程序是一个.NET控制台应用程序,默认情况下会将大量信息记录到控制台,尽管这是可配置的.任何推荐?我们应该在VisualStudio中将其重建为服务吗?我使用“-install”/“-uninstall”开关执行此操作.例如,seehere.

  9. windows – 捕获外部程序的STDOUT和STDERR *同时*它正在执行(Ruby)

    哦,我在Windows上:-(实际上,它比我想象的要简单,这看起来很完美:…是的,它适用于Windows!

  10. windows – 当我试图批量打印变量时,为什么我得到“Echo is on”

    我想要执行一个简单的批处理文件脚本:当我在XP中运行时,它给了我预期的输出,但是当我在Vista或Windows7中运行它时,我在尝试打印值时得到“EchoisOn”.以下是程序的输出:摆脱集合表达式中的空格.等号(=)的两侧可以并且应该没有空格BTW:我通常在@echo关闭的情况下启动所有批处理文件,并以@echo结束它们,所以我可以避免将代码与批处理文件的输出混合.它只是使您的批处理文件输出更好,更清洁.

返回
顶部