How can I create a process in Windows with administrator rights from another software in C++ but without being dependent on that software?

StackOverflow https://stackoverflow.com/questions/11335542

  •  19-06-2021
  •  | 
  •  

سؤال

Imagine that some software in your Windows PC needs to be run in a given time and it was supposed that it's user would start it, but he forgot to do it. And that software was supposed to run as administrator (i.e. with administrator rights). So, in order to garantee that the given software will be open at that time, you put a watchdog than can perform what the user should have done.

This is not exactly my situation, but that's what I need. It must work in C++ and I'm using Qt (though I think that will not make much difference).

I searched almost all files in MSDN about CreateProcess() and similar functions and saw some dozens of examples in the net, but till now I wasn't able to do what I want (in fact, I wasn't even capable of running the software, much less with the details).

It's important to notice that the watchdog is supposed to just open the software as administrator and immediately "forget it"; it should have no control and the opened software must not be in anyway dependent on the watchdog (e.g. if the watchdog is closed, the opened software continue to run normally).

I'ld be glad if somebody helps.

Momergil

هل كانت مفيدة؟

المحلول

Typically, if a program requires Administrator Rights to run, then a user with Administrator Rights is required to install it.

This gives Administrator Rights to the program.

Update: Based on your comment about trying to get another process to run another application with Admin Rights, you should look into the following code:

using System.Security.Principal;

public static void ProcessStart(string fileName, string arguments) {
  ProcessStartInfo startInfo = new ProcessStartInfo(fileName, arguments);
#if !PocketPC
  try {
    WindowsIdentity id = WindowsIdentity.GetCurrent();
    WindowsPrincipal pal = new WindowsPrincipal(id);
    if (pal.IsInRole(WindowsBuiltInRole.Administrator)) {
      Process.Start(startInfo);
    }
  } catch (Exception e) {
    Console.WriteLine(e.Message);
  }
#else
  Process.Start(startInfo);
#endif
}

This code excludes Microsoft PocketPC devices and only executes if the person running the program is in the Administrator group.

What you would need to do is initiate a WindowsIdentity for an account (on the PC you want to run your application on) that has Administrator rights and Impersonate that account to run your application.

There is a working example of how to do this on CodeProject entitled User Impersonation in .NET that can give you a lot more information.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top