CreateProcessAsUser,C#写的windows服务弹框提示消息或者启动子进程

时间: 2024-03-02 16:51:00 浏览: 26
您好,针对您的问题,可以使用以下代码实现: ```csharp using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Windows.Forms; namespace WindowsServiceDialog { public partial class ServiceDialog : Form { [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", SetLastError = true)] private static extern bool OpenProcessToken( IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle); [DllImport("userenv.dll", SetLastError = true)] private static extern bool CreateEnvironmentBlock( out IntPtr lpEnvironment, IntPtr hToken, bool bInherit); [DllImport("userenv.dll", SetLastError = true)] private static extern bool DestroyEnvironmentBlock( IntPtr lpEnvironment); private const uint TOKEN_QUERY = 0x0008; private const uint TOKEN_DUPLICATE = 0x0002; private const uint TOKEN_ASSIGN_PRIMARY = 0x0001; private const uint GENERIC_ALL_ACCESS = 0x10000000; private const uint CREATE_NEW_CONSOLE = 0x00000010; private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400; private const int SW_SHOW = 5; private IntPtr _userToken; private IntPtr _envBlock; [StructLayout(LayoutKind.Sequential)] private struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public uint dwProcessId; public uint dwThreadId; } [StructLayout(LayoutKind.Sequential)] private struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; } [StructLayout(LayoutKind.Sequential)] private struct STARTUPINFO { public int 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; } public ServiceDialog() { InitializeComponent(); } private void ServiceDialog_Load(object sender, EventArgs e) { // 获取当前用户的令牌 WindowsIdentity currentUser = WindowsIdentity.GetCurrent(); if (currentUser != null) { if (!OpenProcessToken(currentUser.Token, TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_QUERY, out _userToken)) { MessageBox.Show("无法获取当前用户的令牌!"); } } } private void btnShowDialog_Click(object sender, EventArgs e) { MessageBox.Show("Hello World!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void btnStartProcess_Click(object sender, EventArgs e) { if (_userToken != IntPtr.Zero) { // 构造启动进程的信息结构体 STARTUPINFO startupInfo = new STARTUPINFO(); startupInfo.cb = Marshal.SizeOf(startupInfo); startupInfo.lpDesktop = "winsta0\\default"; startupInfo.dwFlags = 0x00000100; // 创建进程的安全属性 SECURITY_ATTRIBUTES processAttributes = new SECURITY_ATTRIBUTES(); processAttributes.nLength = Marshal.SizeOf(processAttributes); processAttributes.bInheritHandle = true; // 创建线程的安全属性 SECURITY_ATTRIBUTES threadAttributes = new SECURITY_ATTRIBUTES(); threadAttributes.nLength = Marshal.SizeOf(threadAttributes); IntPtr environmentPtr = IntPtr.Zero; if (CreateEnvironmentBlock(out environmentPtr, _userToken, false)) { _envBlock = environmentPtr; } else { MessageBox.Show("无法创建环境块!"); } // 启动进程 PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION(); if (!CreateProcessAsUser( _userToken, null, "notepad.exe", ref processAttributes, ref threadAttributes, false, CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT, _envBlock, null, ref startupInfo, out processInfo)) { MessageBox.Show("无法启动进程!"); } DestroyEnvironmentBlock(_envBlock); } else { MessageBox.Show("未获取到当前用户的令牌!"); } } private void ServiceDialog_FormClosing(object sender, FormClosingEventArgs e) { if (_userToken != IntPtr.Zero) { CloseHandle(_userToken); } } [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(IntPtr hObject); } } ``` 以上代码实现了一个 Windows 窗体程序,其中包含两个按钮,分别用于弹出提示框和启动子进程。在服务中使用时,可以将此程序安装为 Windows 服务,并在需要弹出提示框或启动子进程的时候,调用相应的方法即可。需要注意的是,如果要启动的子进程需要与当前用户交互,需要获取当前用户的令牌,并使用 `CreateProcessAsUser` 函数创建进程。

相关推荐

#include "mainwindow.h" #include <QApplication> #include <windows.h> #include <wtsapi32.h> #pragma comment(lib, "Wtsapi32.lib") int main(int argc, char *argv[]) { QApplication a(argc, argv); HANDLE hToken = NULL; DWORD dwSessionId = WTSGetActiveConsoleSessionId(); if (!WTSQueryUserToken(dwSessionId, &hToken)) { QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("获取用户令牌失败!")); return -1; } HANDLE mutex = ::CreateMutex(Q_NULLPTR,true,(LPCWSTR)qApp->applicationName().toStdWString().c_str()); if(GetLastError() == ERROR_ALREADY_EXISTS) { QMessageBox waringBox(QMessageBox::Warning,QStringLiteral("警告"),QStringLiteral("程序[文本数据同步客户端]只能运行一个!")); waringBox.setButtonText(QMessageBox::Ok,QStringLiteral("确定")); waringBox.setStandardButtons(QMessageBox::Ok); waringBox.exec(); ::CloseHandle(mutex); CloseHandle(hToken); // 添加关闭句柄语句 return 0; } else { ::ReleaseMutex(mutex); } STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.lpDesktop = (LPWSTR)L"winsta0\\default"; PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); if (!CreateProcessAsUser(hToken, NULL, (LPWSTR)qApp->applicationFilePath().toStdWString().data(), NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) { QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("创建进程失败!")); CloseHandle(hToken); return -1; } CloseHandle(hToken); MainWindow w; w.show(); return a.exec(); } 以上是限制程序在windows Server2016系统中多个用户界面也只能运行一个程序的QT C++代码,: 但是如果在windows Server2016系统中两个用户界面可同时运行程序。 在还未有程序运行时,运行第一个也会直接提示 "获取用户令牌失败!",程序直接关闭,请帮我修复后给我完整代码

#include "mainwindow.h" #include <QApplication> #include <windows.h> #include <wtsapi32.h> #pragma comment(lib, "Wtsapi32.lib") int main(int argc, char *argv[]) { QApplication a(argc, argv); HANDLE hToken = NULL; DWORD dwSessionId = WTSGetActiveConsoleSessionId(); if (dwSessionId == 0xFFFFFFFF) { QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("获取会话ID失败!")); return -1; } if (!WTSQueryUserToken(dwSessionId, &hToken)) { QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("获取用户令牌失败!")); return -1; } HANDLE mutex = ::CreateMutex(Q_NULLPTR, true, (LPCWSTR)qApp->applicationName().toStdWString().c_str()); if (!mutex) { QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("创建互斥量失败!")); CloseHandle(hToken); return -1; } if (GetLastError() == ERROR_ALREADY_EXISTS) { QMessageBox waringBox(QMessageBox::Warning,QStringLiteral("警告"),QStringLiteral("程序[文本数据同步客户端]只能运行一个!")); waringBox.setButtonText(QMessageBox::Ok,QStringLiteral("确定")); waringBox.setStandardButtons(QMessageBox::Ok); waringBox.exec(); ::CloseHandle(mutex); CloseHandle(hToken); return 0; } STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.lpDesktop = (LPWSTR)L"winsta0\\default"; PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); if (!CreateProcessAsUser(hToken, NULL, (LPWSTR)qApp->applicationFilePath().toStdWString().data(), NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) { QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("创建进程失败!")); CloseHandle(mutex); CloseHandle(hToken); return -1; } CloseHandle(hToken); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); ::ReleaseMutex(mutex); MainWindow w; w.show(); return a.exec(); } 以上是限制程序在windows Server2016系统中多个用户界面也只能运行一个程序的QT C++代码,: 但在运行第一个也会直接提示 "获取用户令牌失败!"而导致程序直接关闭,请帮我修复后给我完整代码

#include "mainwindow.h" #include <QApplication> #include <windows.h> #include <wtsapi32.h> #include <QLibrary> typedef BOOL(WINAPI *WTSSendMessageFunc)(HANDLE, DWORD, LPWSTR, DWORD, LPWSTR, DWORD, DWORD, LPDWORD, BOOL); int main(int argc, char *argv[]) { QApplication a(argc, argv); // 加载wtsapi32.dll QLibrary lib("wtsapi32.dll"); // 判断是否加载成功 if (!lib.load()) { QMessageBox::warning(NULL, "Warning", QString("Failed to load wtsapi32.dll: %1").arg(lib.errorString())); return 1; } // 获取函数指针 WTSSendMessageFunc WTSSendMessage = (WTSSendMessageFunc)lib.resolve("WTSSendMessageW"); if (WTSSendMessage == NULL) { QMessageBox::warning(NULL, "Warning", QString("Failed to resolve WTSSendMessageW: %1").arg(lib.errorString())); return 1; } // 获取当前会话ID DWORD dwSessionId = WTSGetActiveConsoleSessionId(); if (dwSessionId == 0xFFFFFFFF) { QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("获取会话ID失败!")); return -1; } // 获取当前会话令牌 HANDLE hToken = NULL; if (!WTSQueryUserToken(dwSessionId, &hToken)) { QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("获取用户令牌失败!")); return -1; } // 创建互斥量,确保程序只能运行一个实例 HANDLE mutex = ::CreateMutex(Q_NULLPTR, true, (LPCWSTR)qApp->applicationName().toStdWString().c_str()); if (!mutex) { QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("创建互斥量失败!")); CloseHandle(hToken); return -1; } if (GetLastError() == ERROR_ALREADY_EXISTS) { QMessageBox waringBox(QMessageBox::Warning, QStringLiteral("警告"), QStringLiteral("程序[文本数据同步客户端]只能运行一个!")); waringBox.setButtonText(QMessageBox::Ok, QStringLiteral("确定")); waringBox.setStandardButtons(QMessageBox::Ok); waringBox.exec(); ::CloseHandle(mutex); CloseHandle(hToken); return 0; } // 创建新进程,确保程序在当前会话中运行 STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.lpDesktop = (LPWSTR)L"winsta0\\default"; PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); if (!CreateProcessAsUser(hToken, NULL, (LPWSTR)qApp->applicationFilePath().toStdWString().data(), NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) { QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("创建进程失败!")); CloseHandle(mutex); CloseHandle(hToken); return -1; } // 关闭会话令牌和新进程句柄 CloseHandle(hToken); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); // 释放互斥量 ::ReleaseMutex(mutex); // 启动主窗口 MainWindow w; w.show(); return a.exec(); } 在以上代码中会提示:"获取用户令牌失败!",导致无法打开程序,这是什么原因,并给我解决办法

最新推荐

recommend-type

华为OD机试D卷 - 用连续自然数之和来表达整数 - 免费看解析和代码.html

私信博主免费获取真题解析以及代码
recommend-type

Screenshot_2024-05-10-20-21-01-857_com.chaoxing.mobile.jpg

Screenshot_2024-05-10-20-21-01-857_com.chaoxing.mobile.jpg
recommend-type

数字图像处理|Matlab-频域增强实验-彩色图像的频域滤波.zip

数字图像处理|Matlab-频域增强实验-彩色图像的频域滤波.zip
recommend-type

2024-2030中国定向转向膜市场现状研究分析与发展前景预测报告.docx

2024-2030中国定向转向膜市场现状研究分析与发展前景预测报告
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

spring添加xml配置文件

1. 创建一个新的Spring配置文件,例如"applicationContext.xml"。 2. 在文件头部添加XML命名空间和schema定义,如下所示: ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依