当前位置: 首页>>代码示例>>C++>>正文


C++ QueryServiceStatus函数代码示例

本文整理汇总了C++中QueryServiceStatus函数的典型用法代码示例。如果您正苦于以下问题:C++ QueryServiceStatus函数的具体用法?C++ QueryServiceStatus怎么用?C++ QueryServiceStatus使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了QueryServiceStatus函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: ControlSSDPService

bool ControlSSDPService(bool start)
{
	bool result = false;
	
	SC_HANDLE hscm = NULL;
	hscm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
	if(hscm == NULL)
		return result;

	SC_HANDLE hsrv = NULL;
	hsrv = OpenService(hscm, _T("ssdpsrv"), SERVICE_ALL_ACCESS);
	if(hsrv)
	{
		SERVICE_STATUS srvstatus;

		if(QueryServiceStatus(hsrv, &srvstatus))
		{
			HANDLE hevent = CreateEvent(0, true, false, _T("dummyevent"));
			
			// if service_*_pending then wait for complete operation
			switch(srvstatus.dwCurrentState)
			{
			case SERVICE_START_PENDING :
			case SERVICE_STOP_PENDING :
				for(int i = 0; i < 10; ++i)
				{
					if(!QueryServiceStatus(hsrv, &srvstatus))
						break;
					if(srvstatus.dwCurrentState == SERVICE_RUNNING || srvstatus.dwCurrentState == SERVICE_STOPPED)
						break;
					WaitForSingleObject(hevent, 1000);
				}
				break;
			}

			// operation completed, so change current state
			if(QueryServiceStatus(hsrv, &srvstatus))
			{
				switch(srvstatus.dwCurrentState)
				{
				case SERVICE_RUNNING : // stop it
					if(!start && ControlService(hsrv, SERVICE_CONTROL_STOP, &srvstatus))
						result = true;
					break;
				case SERVICE_STOPPED : // start it
					if(start && StartService(hsrv, 0, NULL))
						result = true;
					break;
				}

				// wait for complete operation
				if(result)
				{
					for(int i = 0; i < 10; ++i)
					{
						if(!QueryServiceStatus(hsrv, &srvstatus))
							break;
						if(srvstatus.dwCurrentState == SERVICE_RUNNING || srvstatus.dwCurrentState == SERVICE_STOPPED)
						{
							// notify scm
							//ControlService(hsrv, SERVICE_CONTROL_INTERROGATE, &srvstatus);
							break;
						}
						WaitForSingleObject(hevent, 1000);
					}
				}
			}
		}
		
		CloseServiceHandle(hsrv);
	}

	CloseServiceHandle(hscm);
	
	return result;
}
开发者ID:DennisHeerema,项目名称:ultravnc,代码行数:76,代码来源:firewall.cpp

示例2: remove_service

int remove_service(TCHAR *installdir, int check_only) {
	HKEY hKey;
	int done = 0;

	if(wcslen(installdir) < 3) {
		WcaLog(LOGMSG_STANDARD, "INSTALLDIR is suspiciously short, better not do anything.");
		return 0;
	}

	if(check_only == 0) {
		WcaLog(LOGMSG_STANDARD, "Determining number of matching services...");
		int servicecount = remove_service(installdir, 1);
		if(servicecount <= 0) {
			WcaLog(LOGMSG_STANDARD, "No services found, not removing anything.");
			return 0;
		} else if(servicecount == 1) {
			TCHAR buf[256];
			swprintf_s(buf, sizeof(buf), TEXT("There is a service called '%ls' set up to run from this installation. Do you wish me to stop and remove that service?"), last_service_name);
			int rc = MessageBox(NULL, buf, TEXT("Removing MySQL Server"), MB_ICONQUESTION|MB_YESNOCANCEL|MB_SYSTEMMODAL);
			if(rc == IDCANCEL) return -1;
			if(rc != IDYES) return 0;
		} else if(servicecount > 0) {
			TCHAR buf[256];
			swprintf_s(buf, sizeof(buf), TEXT("There appear to be %d services set up to run from this installation. Do you wish me to stop and remove those services?"), servicecount);
			int rc = MessageBox(NULL, buf, TEXT("Removing MySQL Server"), MB_ICONQUESTION|MB_YESNOCANCEL|MB_SYSTEMMODAL);
			if(rc == IDCANCEL) return -1;
			if(rc != IDYES) return 0;
		}
	}

	if(check_only == -1) check_only = 0;

	WcaLog(LOGMSG_STANDARD, "Looking for service...");
	WcaLog(LOGMSG_STANDARD, "INSTALLDIR = %ls", installdir);
	if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, TEXT("SYSTEM\\CurrentControlSet\\services"), 0, KEY_READ, &hKey)==ERROR_SUCCESS) {
		DWORD index = 0;
		TCHAR keyname[1024];
		DWORD keylen = sizeof(keyname);
		FILETIME t;
		/* Go through all services in the registry */
		while(RegEnumKeyExW(hKey, index, keyname, &keylen, NULL, NULL, NULL, &t) == ERROR_SUCCESS) {
			HKEY hServiceKey = 0;
			TCHAR path[1024];
			DWORD pathlen = sizeof(path)-1;
			if (RegOpenKeyExW(hKey, keyname, NULL, KEY_READ, &hServiceKey) == ERROR_SUCCESS) {
				/* Look at the ImagePath value of each service */
				if (RegQueryValueExW(hServiceKey, TEXT("ImagePath"), NULL, NULL, (LPBYTE)path, &pathlen) == ERROR_SUCCESS) {
					path[pathlen] = 0;
					TCHAR *p = path;
					if(p[0] == '"') p += 1;
					/* See if it is similar to our install directory */
					if(wcsncmp(p, installdir, wcslen(installdir)) == 0) {
						WcaLog(LOGMSG_STANDARD, "Found service '%ls' with ImagePath '%ls'.", keyname, path);
						swprintf_s(last_service_name, sizeof(last_service_name), TEXT("%ls"), keyname);
						/* If we are supposed to stop and remove the service... */
						if(!check_only) {
							WcaLog(LOGMSG_STANDARD, "Trying to stop the service.");
							SC_HANDLE hSCM = NULL; 
							hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
							if(hSCM != NULL) {
								SC_HANDLE hService = NULL;
								hService = OpenService(hSCM, keyname, SERVICE_STOP|SERVICE_QUERY_STATUS|DELETE);
								if(hService != NULL) {
									WcaLog(LOGMSG_STANDARD, "Waiting for the service to stop...");
									SERVICE_STATUS status;
									/* Attempt to stop the service */
									if(ControlService(hService, SERVICE_CONTROL_STOP, &status)) {
										/* Now wait until it's stopped */
										while("it's one big, mean and cruel world out there") {
											if(!QueryServiceStatus(hService, &status)) break;
											if(status.dwCurrentState == SERVICE_STOPPED) break;
											Sleep(1000);
										}
										WcaLog(LOGMSG_STANDARD, "Stopped the service.");
									}
									/* Mark the service for deletion */
									DeleteService(hService);
									CloseServiceHandle(hService);
								}
								CloseServiceHandle(hSCM);
							}
						}
						done++;
					}
				}
				RegCloseKey(hServiceKey);
			}
			index++;
			keylen = sizeof(keyname)-1;
		}
		RegCloseKey(hKey);
	} else {
		WcaLog(LOGMSG_STANDARD, "Can't seem to go through the list of installed services in the registry.");
	}
	return done;
}
开发者ID:Longhui,项目名称:mysql-5.7.9-readcode,代码行数:96,代码来源:CustomAction.cpp

示例3: start_and_watch_server

THREAD_ENTRY_DECLARE start_and_watch_server(THREAD_ENTRY_PARAM)
{
/**************************************
 *
 *	s t a r t _ a n d _ w a t c h _ s e r v e r
 *
 **************************************
 *
 * Functional description
 *
 *      This function is where the server process is created and
 * the thread waits for this process to exit.
 *
 **************************************/
	Firebird::ContextPoolHolder threadContext(getDefaultMemoryPool());

	HANDLE procHandle = NULL;
	bool done = true;
	const UINT error_mode = SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
		SEM_NOOPENFILEERRORBOX | SEM_NOALIGNMENTFAULTEXCEPT;
	SC_HANDLE hScManager = 0, hService = 0;

	// get the guardian startup information
	const short option = Config::getGuardianOption();

	char prefix_buffer[MAXPATHLEN];
	GetModuleFileName(NULL, prefix_buffer, sizeof(prefix_buffer));
	Firebird::PathName path = prefix_buffer;
	path = path.substr(0, path.rfind(PathUtils::dir_sep) + 1) + FBSERVER;
	path = "\"" + path + "\"";
	Firebird::PathName prog_name = path + " -a -n";

	// if the guardian is set to FOREVER then set the error mode
	UINT old_error_mode = 0;
	if (option == START_FOREVER)
		old_error_mode = SetErrorMode(error_mode);

	// Spawn the new process
	do {
		SERVICE_STATUS ServiceStatus;
		char out_buf[1024];
		BOOL success;
		int error = 0;

		if (service_flag)
		{
			if (hService)
			{
				while ((QueryServiceStatus(hService, &ServiceStatus) == TRUE) &&
					(ServiceStatus.dwCurrentState != SERVICE_STOPPED))
				{
					Sleep(500);
				}
			}

			procHandle = CreateMutex(NULL, FALSE, mutex_name->c_str());

			// start as a service.  If the service can not be found or
			// fails to start, close the handle to the mutex and set
			// success = FALSE
			if (!hScManager)
				hScManager = OpenSCManager(NULL, NULL, GENERIC_READ);
			if (!hService)
			{
				hService = OpenService(hScManager, remote_name->c_str(),
					GENERIC_READ | GENERIC_EXECUTE);
			}
			success = StartService(hService, 0, NULL);
			if (success != TRUE)
				error = GetLastError();
			// if the server is already running, then inform it that it should
			// open the guardian mutex so that it may be governed.
			if (!error || error == ERROR_SERVICE_ALREADY_RUNNING)
			{
				// Make sure that it is actually ready to receive commands.
				// If we were the one who started it, then it will need a few
				// seconds to get ready.
				while ((QueryServiceStatus(hService, &ServiceStatus) == TRUE) &&
					(ServiceStatus.dwCurrentState != SERVICE_RUNNING))
				{
					Sleep(500);
				}
				ControlService(hService, SERVICE_CREATE_GUARDIAN_MUTEX, &ServiceStatus);
				success = TRUE;
			}
		}
		else
		{
			HWND hTmpWnd = FindWindow(szClassName, szWindowName);
			if (hTmpWnd == NULL)
			{
				STARTUPINFO si;
				SECURITY_ATTRIBUTES sa;
				PROCESS_INFORMATION pi;
				ZeroMemory(&si, sizeof(si));
				si.cb = sizeof(si);
				sa.nLength = sizeof(sa);
				sa.lpSecurityDescriptor = NULL;
				sa.bInheritHandle = TRUE;
				success = CreateProcess(NULL, const_cast<char*>(prog_name.c_str()),
//.........这里部分代码省略.........
开发者ID:tux-mind,项目名称:platform_external_firebird,代码行数:101,代码来源:iscguard.cpp

示例4: send_signal_to_service

int send_signal_to_service(char *display_name, char *sig, 
                           int argc, char **argv)
{
    DWORD       service_pid;
    HANDLE      hwnd;
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;
    char       *service_name;
    int success = FALSE;

    enum                        { start,      restart,      stop, unknown } action;
    static char *param[] =      { "start",    "restart",    "shutdown" };
    static char *participle[] = { "starting", "restarting", "stopping" };
    static char *past[]       = { "started",  "restarted",  "stopped"  };

    for (action = start; action < unknown; action++)
        if (!strcasecmp(sig, param[action]))
            break;

    if (action == unknown) {
        printf("signal must be start, restart, or shutdown\n");
        return FALSE;
    }

    service_name = get_service_name(display_name);

    if (isWindowsNT()) 
    {
        schSCManager = OpenSCManager(
                            NULL,                   // machine (NULL == local)
                            NULL,                   // database (NULL == default)
                            SC_MANAGER_ALL_ACCESS   // access required
                            );
        if (!schSCManager) {
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "OpenSCManager failed");
            return FALSE;
        }
        
        schService = OpenService(schSCManager, service_name, SERVICE_ALL_ACCESS);

        if (schService == NULL) {
            /* Could not open the service */
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "OpenService failed");
            CloseServiceHandle(schSCManager);
            return FALSE;
        }
        
        if (!QueryServiceStatus(schService, &globdat.ssStatus)) {
            ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_WIN32ERROR, NULL,
                         "QueryService failed");
            CloseServiceHandle(schService);
            CloseServiceHandle(schSCManager);
        }
    }
    else /* !isWindowsNT() */
    {
        /* Locate the window named service_name of class ApacheWin95ServiceMonitor
         * from the active top level windows
         */
        hwnd = FindWindow("ApacheWin95ServiceMonitor", service_name);
        if (hwnd && GetWindowThreadProcessId(hwnd, &service_pid))
            globdat.ssStatus.dwCurrentState = SERVICE_RUNNING;
        else
            globdat.ssStatus.dwCurrentState = SERVICE_STOPPED;
    }

    if (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED 
            && action == stop) {
        printf("The %s service is not started.\n", display_name);
        return FALSE;
    }
    else if (globdat.ssStatus.dwCurrentState == SERVICE_RUNNING 
                 && action == start) {
        printf("The %s service has already been started.\n", display_name);
        strcpy(sig, "");
        return FALSE;
    }
    else
    {
        printf("The %s service is %s.\n", display_name, participle[action]);

        if (isWindowsNT()) 
        {
            if (action == stop)
                success = ap_stop_service(schService);
            else if ((action == start) 
                     || ((action == restart) 
                            && (globdat.ssStatus.dwCurrentState 
                                    == SERVICE_STOPPED)))
            {
                /* start NT service needs service args */
                char **args = malloc(argc * sizeof(char*));
                int i, j;
                for (i = 1, j = 0; i < argc; i++) {
                    if ((argv[i][0] == '-') && ((argv[i][1] == 'k') 
                                             || (argv[i][1] == 'n')))
                        ++i;
                    else
//.........这里部分代码省略.........
开发者ID:AzerTyQsdF,项目名称:osx,代码行数:101,代码来源:service.c

示例5: s

void Diagnostics::run()
{
	QString info;
	QTextStream s( &info );

	s << "<b>" << tr("Locale (time-, number format / codepage):") << "</b> ";
	QLocale::Language language = QLocale::system().language();
	QString locale = (language == QLocale::C ? "English/United States" : QLocale::languageToString( language ) );
	CPINFOEX CPInfoEx;
	if( GetCPInfoEx( GetConsoleCP(), 0, &CPInfoEx ) != 0 )
		locale.append( " / " ).append( QString( (QChar*)CPInfoEx.CodePageName ) );
	s << locale << "<br />";
	emit update( info );
	info.clear();

	s << "<b>" << tr("User rights: ") << "</b>" << getUserRights() << "<br />";
	emit update( info );
	info.clear();

	QStringList base = Common::packages( QStringList() << "Eesti ID-kaardi tarkvara", false );
	if( !base.isEmpty() )
		s << "<b>" << tr("Base version:") << "</b> " << base.join( "<br />" ) << "<br />";
	s << "<b>" << tr("Application version:") << "</b> "<< QCoreApplication::applicationVersion()
#ifdef INTERNATIONAL
		<< " INTERNATIONAL"
#endif
		<< "<br />";
	emit update( info );
	info.clear();

	s << "<b>" << tr("OS:") << "</b> " << Common::applicationOs() << "<br />";
	SYSTEM_INFO sysinfo;
	GetSystemInfo( &sysinfo );
	s << "<b>" << tr("CPU:") << "</b> " << QString::number( sysinfo.dwProcessorType ) << "<br /><br />";
	emit update( info );
	info.clear();

	s << "<b>" << tr("URLs:") << "</b>";
	const QHash<QString,QString> urls = qApp->urls();
	for(auto i = urls.constBegin(); i != urls.constEnd(); ++i)
		s << "<br />" << i.key() << ": " << i.value();
	s << "<br /><br />";

	s << "<b>" << tr("Arguments:") << "</b> " << qApp->arguments().join(" ") << "<br />";
	s << "<b>" << tr("Library paths:") << "</b> " << QCoreApplication::libraryPaths().join( ";" ) << "<br />";

	s << "<b>" << tr("Libraries") << ":</b><br />" << "QT (" << qVersion() << ")<br />";
	Q_FOREACH( const QString &lib, QStringList()
			<< "digidoc" << "digidocpp" << "qdigidocclient.exe" << "qesteidutil.exe" << "id-updater.exe"
			<< "esteidcsp" << "esteidcm" << "EsteidShellExtension" << "esteid-plugin-ie"
			<< "npesteid-firefox-plugin" << "opensc-pkcs11" << "esteid-pkcs11"
			<< "libeay32" << "ssleay32" << "advapi32" << "crypt32" << "winscard" )
	{
		DWORD infoHandle = 0;
		LONG sz = GetFileVersionInfoSize( LPCWSTR(lib.utf16()), &infoHandle );
		if( !sz )
			continue;
		QByteArray data( sz * 2, 0 );
		if( !GetFileVersionInfoW( LPCWSTR(lib.utf16()), 0, sz, data.data() ) )
			continue;
		VS_FIXEDFILEINFO *info = 0;
		UINT len = 0;
		if( !VerQueryValueW( data.constData(), L"\\", (LPVOID*)&info, &len ) )
			continue;
		s << QString( "%1 (%2.%3.%4.%5)" ).arg( lib )
			.arg( HIWORD(info->dwFileVersionMS) )
			.arg( LOWORD(info->dwFileVersionMS) )
			.arg( HIWORD(info->dwFileVersionLS) )
			.arg( LOWORD(info->dwFileVersionLS) ) << "<br />";
	}
	s << "<br />";
	emit update( info );
	info.clear();

	enum {
		Running,
		Stopped,
		NotFound
	} atrfiltr = NotFound, certprop = NotFound;
	if( SC_HANDLE h = OpenSCManager( 0, 0, SC_MANAGER_CONNECT ) )
	{
		if( SC_HANDLE s = OpenService( h, L"atrfiltr", SERVICE_QUERY_STATUS ) )
		{
			SERVICE_STATUS status;
			QueryServiceStatus( s, &status );
			atrfiltr = (status.dwCurrentState == SERVICE_RUNNING) ? Running : Stopped;
			CloseServiceHandle( s );
		}
		if( SC_HANDLE s = OpenService( h, L"CertPropSvc", SERVICE_QUERY_STATUS ))
		{
			SERVICE_STATUS status;
			QueryServiceStatus( s, &status );
			certprop = (status.dwCurrentState == SERVICE_RUNNING) ? Running : Stopped;
			CloseServiceHandle( s );
		}
		CloseServiceHandle( h );
	}
	s << "<br /><b>" << tr("ATRfiltr service status: ") << "</b>" << " ";
	switch( atrfiltr )
	{
//.........这里部分代码省略.........
开发者ID:mihkelvain,项目名称:qt-common,代码行数:101,代码来源:Diagnostics_win.cpp

示例6: StartDriver

/****************************************************************************
*
*    FUNCTION: StartDriver( IN SC_HANDLE, IN LPCTSTR)
*
*    PURPOSE: Starts the driver service.
*
****************************************************************************/
BOOL StartDriver( IN SC_HANDLE SchSCManager, IN LPCTSTR DriverName )
{
    SC_HANDLE  schService;
    BOOL       ret;
	SERVICE_STATUS ServiceStatus;
	char LogZeile[128];
    DWORD Service_Error ;
	

	schService = OpenService( SchSCManager,
                              DriverName,
                              SERVICE_ALL_ACCESS
                              );
    if ( schService == NULL ) {
    Service_Error  = GetLastError();
	sprintf(LogZeile,"OpenService %s Fail ( Return %x ",DriverName,Service_Error);
	if ( Service_Error == ERROR_ACCESS_DENIED ) strcat(LogZeile,"ACCESS_DENIED");
	 else if ( Service_Error == ERROR_INVALID_HANDLE ) strcat(LogZeile,"INVALID_HANDLE");
	 else if ( Service_Error == ERROR_INVALID_NAME ) strcat(LogZeile,"INVALID_NAME");
	 else if ( Service_Error == ERROR_SERVICE_DOES_NOT_EXIST ) strcat(LogZeile,"SERVICE_DOES_NOT_EXIST");
	 strcat(LogZeile,")");
	Write_Log(LogZeile);
    return(FALSE);
	};


	if ( QueryServiceStatus(schService,&ServiceStatus ) == FALSE ) {
    Service_Error  = GetLastError();
	sprintf(LogZeile,"QueryServiceStatus %s Fail ( Return %x ",DriverName,Service_Error);
	if ( Service_Error == ERROR_ACCESS_DENIED ) strcat(LogZeile,"ACCESS_DENIED");
	 else if ( Service_Error == ERROR_INVALID_HANDLE ) strcat(LogZeile,"INVALID_HANDLE");
	 strcat(LogZeile,")");
	 Write_Log(LogZeile);
     CloseServiceHandle( schService );
	 return(FALSE);
	};

    if ( ServiceStatus.dwCurrentState == SERVICE_RUNNING ) return(TRUE);


    ret = StartService( schService, 0, NULL );

    if ( ret == FALSE )
    {
       Service_Error  = GetLastError();
        if( Service_Error   == ERROR_SERVICE_ALREADY_RUNNING)
        {
           CloseServiceHandle( schService );
		   return(TRUE);
        } else {
            
	    sprintf(LogZeile,"StartService %s Fail ( Return %x ",DriverName,Service_Error);
		if ( Service_Error == ERROR_ACCESS_DENIED ) strcat(LogZeile,"ACCESS_DENIED");
			else if ( Service_Error == ERROR_INVALID_HANDLE ) strcat(LogZeile,"INVALID_HANDLE");
			else if ( Service_Error == ERROR_PATH_NOT_FOUND ) strcat(LogZeile,"PATH_NOT_FOUND");
			else if ( Service_Error == ERROR_SERVICE_DATABASE_LOCKED ) strcat(LogZeile,"SERVICE_DATABASE_LOCKED");
			else if ( Service_Error == ERROR_SERVICE_DEPENDENCY_DELETED ) strcat(LogZeile,"DEPENDENCY_DELETED");
			else if ( Service_Error == ERROR_SERVICE_DEPENDENCY_FAIL ) strcat(LogZeile,"DEPENDENCY_FAIL");
			else if ( Service_Error == ERROR_SERVICE_DISABLED ) strcat(LogZeile,"SERVICE_DISABLED");
			else if ( Service_Error == ERROR_SERVICE_LOGON_FAILED ) strcat(LogZeile,"SERVICE_LOGON_FAILED");
			else if ( Service_Error == ERROR_SERVICE_MARKED_FOR_DELETE ) strcat(LogZeile,"SERVICE_MARKED_FOR_DELETE");
			else if ( Service_Error == ERROR_SERVICE_NO_THREAD ) strcat(LogZeile,"SERVICE_NO_THREAD");
			else if ( Service_Error == ERROR_SERVICE_REQUEST_TIMEOUT ) strcat(LogZeile,"SERVICE_REQUEST_TIMEOUT");
		strcat(LogZeile,")");
		Write_Log(LogZeile);
		RemoveDriver(SchSCManager, DriverName);
        return(FALSE);
        }
    }
 


    CloseServiceHandle( schService );

    return ret;
}
开发者ID:denizkoekden,项目名称:Multi_Dec,代码行数:83,代码来源:SERVICE.C

示例7: OpenSCManager

void driver::load(const std::wstring &name, const std::wstring &file, const std::wstring &devfile) {
	if(m_loaded) throw std::exception("driver already loaded", 0);

	m_name = name;
	m_file = file;
	m_devfile = devfile;

	SC_HANDLE manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if(!manager) throw win32_error("OpenSCManager");

	SC_HANDLE service = CreateService(manager, m_name.c_str(), m_name.c_str(),
		SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
		m_file.c_str(), NULL, NULL, NULL, NULL, NULL);

	if(!service) {
		service = OpenService(manager, m_name.c_str(), SERVICE_ALL_ACCESS);

		if(!service) {
			DWORD err = GetLastError();

			CloseServiceHandle(manager);
			throw win32_error("OpenService", err);
		}

		// make sure it has the same path as m_file.

		DWORD bytes;
		BOOL ret = QueryServiceConfig(service, NULL, 0, &bytes);

		DWORD err;
		if(ret || (err = GetLastError()) != ERROR_INSUFFICIENT_BUFFER) {
			CloseServiceHandle(service);
			CloseServiceHandle(manager);
			throw win32_error("QueryServiceConfig");
		}

		QUERY_SERVICE_CONFIG *qsc = (QUERY_SERVICE_CONFIG*)malloc(bytes);
		if(!qsc) {
			CloseServiceHandle(service);
			CloseServiceHandle(manager);
			throw std::bad_alloc("unable to allocate memory for QueryServiceConfig");
		}

		ret = QueryServiceConfig(service, qsc, bytes, &bytes);
		if(!ret) {
			CloseServiceHandle(service);
			CloseServiceHandle(manager);
			throw win32_error("QueryServiceConfig");
		}

		bool del = _wcsicmp(qsc->lpBinaryPathName, m_file.c_str()) != 0;

		free(qsc);

		// paths don't match, remove service and recreate.
		if(del) {
			// if it's not removable, bail out.
			if(!this->removable) {
				CloseServiceHandle(service);
				CloseServiceHandle(manager);
				throw std::exception("unremovable service mismatch", 0);
			}

			// check if its running
			SERVICE_STATUS status;
			ret = QueryServiceStatus(service, &status);
			if(!ret) {
				DWORD err = GetLastError();

				CloseServiceHandle(service);
				CloseServiceHandle(manager);
				throw win32_error("QueryServiceStatus", err);
			}

			// and stop it if it is.
			if(status.dwCurrentState != SERVICE_STOPPED && status.dwCurrentState != SERVICE_STOP_PENDING) {
				ret = ControlService(service, SERVICE_CONTROL_STOP, &status);
				if(!ret) {
					DWORD err = GetLastError();

					CloseServiceHandle(service);
					CloseServiceHandle(manager);
					throw win32_error("ControlService", err);
				}
			}

			// now delete the service.
			ret = DeleteService(service);
			CloseServiceHandle(service);

			if(!ret && (err = GetLastError()) != ERROR_SERVICE_MARKED_FOR_DELETE) {
				CloseServiceHandle(manager);
				throw win32_error("DeleteService", err);
			}

			// finally recreate it.
			service = CreateService(manager, m_name.c_str(), m_name.c_str(),
				SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
				m_file.c_str(), NULL, NULL, NULL, NULL, NULL);

//.........这里部分代码省略.........
开发者ID:Tudi,项目名称:PG2-firewall,代码行数:101,代码来源:driver.cpp

示例8: DokanServiceControl

static BOOL DokanServiceControl(LPCWSTR ServiceName, ULONG Type) {
  SC_HANDLE controlHandle;
  SC_HANDLE serviceHandle;
  SERVICE_STATUS ss;
  BOOL result = TRUE;

  controlHandle = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);

  if (controlHandle == NULL) {
    DokanDbgPrint("DokanServiceControl: Failed to open Service Control "
                  "Manager. error = %d\n",
                  GetLastError());
    return FALSE;
  }

  serviceHandle =
      OpenService(controlHandle, ServiceName,
                  SERVICE_START | SERVICE_STOP | SERVICE_QUERY_STATUS | DELETE);

  if (serviceHandle == NULL) {
    DokanDbgPrintW(
        L"DokanServiceControl: Failed to open Service (%s). error = %d\n",
        ServiceName, GetLastError());
    CloseServiceHandle(controlHandle);
    return FALSE;
  }

  QueryServiceStatus(serviceHandle, &ss);

  if (Type == DOKAN_SERVICE_DELETE) {
    if (DeleteService(serviceHandle)) {
      DokanDbgPrintW(L"DokanServiceControl: Service (%s) deleted\n",
                     ServiceName);
      result = TRUE;
    } else {
      DokanDbgPrintW(
          L"DokanServiceControl: Failed to delete service (%s). error = %d\n",
          ServiceName, GetLastError());
      result = FALSE;
    }

  } else if (ss.dwCurrentState == SERVICE_STOPPED &&
             Type == DOKAN_SERVICE_START) {
    if (StartService(serviceHandle, 0, NULL)) {
      DokanDbgPrintW(L"DokanServiceControl: Service (%s) started\n",
                     ServiceName);
      result = TRUE;
    } else {
      DokanDbgPrintW(
          L"DokanServiceControl: Failed to start service (%s). error = %d\n",
          ServiceName, GetLastError());
      result = FALSE;
    }

  } else if (ss.dwCurrentState == SERVICE_RUNNING &&
             Type == DOKAN_SERVICE_STOP) {

    if (ControlService(serviceHandle, SERVICE_CONTROL_STOP, &ss)) {
      DokanDbgPrintW(L"DokanServiceControl: Service (%s) stopped\n",
                     ServiceName);
      result = TRUE;
    } else {
      DokanDbgPrintW(
          L"DokanServiceControl: Failed to stop service (%s). error = %d\n",
          ServiceName, GetLastError());
      result = FALSE;
    }
  }

  CloseServiceHandle(serviceHandle);
  CloseServiceHandle(controlHandle);

  Sleep(100);
  return result;
}
开发者ID:shinyhaskett,项目名称:dokany,代码行数:75,代码来源:mount.c

示例9: _tWinMain

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	if( lpCmdLine[0] == _T('-') || lpCmdLine[0] == _T('/') ){
		if( lstrcmpi(_T("install"), lpCmdLine + 1) == 0 ){
			bool installed = false;
			TCHAR exePath[512];
			if( GetModuleFileName(NULL, exePath, _countof(exePath)) != 0 ){
				SC_HANDLE hScm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE);
				if( hScm != NULL ){
					SC_HANDLE hSrv = CreateService(
						hScm, SERVICE_NAME, SERVICE_NAME, 0, SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
						SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, exePath, NULL, NULL, NULL, NULL, NULL);
					if( hSrv != NULL ){
						installed = true;
						CloseServiceHandle(hSrv);
					}
					CloseServiceHandle(hScm);
				}
			}
			if( installed == false ){
				//コンソールがないのでメッセージボックスで伝える
				MessageBox(NULL, L"Failed to install/remove " SERVICE_NAME L".\r\nRun as Administrator on Vista and later.", NULL, MB_ICONERROR);
			}
			return 0;
		}else if( lstrcmpi(_T("remove"), lpCmdLine + 1) == 0 ){
			bool removed = false;
			SC_HANDLE hScm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
			if( hScm != NULL ){
				SC_HANDLE hSrv = OpenService(hScm, SERVICE_NAME, DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
				if( hSrv != NULL ){
					SERVICE_STATUS srvStatus;
					if( QueryServiceStatus(hSrv, &srvStatus) != FALSE ){
						if( srvStatus.dwCurrentState == SERVICE_STOPPED || ControlService(hSrv, SERVICE_CONTROL_STOP, &srvStatus) != FALSE ){
							removed = DeleteService(hSrv) != FALSE;
						}
					}
					CloseServiceHandle(hSrv);
				}
				CloseServiceHandle(hScm);
			}
			if( removed == false ){
				MessageBox(NULL, L"Failed to install/remove " SERVICE_NAME L".\r\nRun as Administrator on Vista and later.", NULL, MB_ICONERROR);
			}
			return 0;
		}
	}


	if( IsInstallService(SERVICE_NAME) == FALSE ){
		//普通にexeとして起動を行う
		HANDLE hMutex = CreateMutex(NULL, TRUE, EPG_TIMER_BON_SRV_MUTEX);
		if( hMutex != NULL ){
			if( GetLastError() != ERROR_ALREADY_EXISTS ){
				StartDebugLog();
				//メインスレッドに対するCOMの初期化
				CoInitialize(NULL);
				CEpgTimerSrvMain* pMain = new CEpgTimerSrvMain;
				if( pMain->Main(false) == false ){
					OutputDebugString(_T("_tWinMain(): Failed to start\r\n"));
				}
				delete pMain;
				CoUninitialize();
				StopDebugLog();
			}
			ReleaseMutex(hMutex);
			CloseHandle(hMutex);
		}
	}else if( IsStopService(SERVICE_NAME) == FALSE ){
		//サービスとして実行
		HANDLE hMutex = CreateMutex(NULL, TRUE, EPG_TIMER_BON_SRV_MUTEX);
		if( hMutex != NULL ){
			if( GetLastError() != ERROR_ALREADY_EXISTS ){
				StartDebugLog();
				SERVICE_TABLE_ENTRY dispatchTable[] = {
					{ SERVICE_NAME, service_main },
					{ NULL, NULL }
				};
				if( StartServiceCtrlDispatcher(dispatchTable) == FALSE ){
					OutputDebugString(_T("_tWinMain(): StartServiceCtrlDispatcher failed\r\n"));
				}
				StopDebugLog();
			}
			ReleaseMutex(hMutex);
			CloseHandle(hMutex);
		}
	}else{
		//Stop状態なのでサービスの開始を要求
		bool started = false;
		SC_HANDLE hScm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
		if( hScm != NULL ){
			SC_HANDLE hSrv = OpenService(hScm, SERVICE_NAME, SERVICE_START);
			if( hSrv != NULL ){
				started = StartService(hSrv, 0, NULL) != FALSE;
				CloseServiceHandle(hSrv);
			}
			CloseServiceHandle(hScm);
		}
//.........这里部分代码省略.........
开发者ID:9060,项目名称:EDCB.local,代码行数:101,代码来源:EpgTimerSrv.cpp

示例10: UninstallService

//
//   FUNCTION: UninstallService
//
//   PURPOSE: Stop and remove the service from the local service control 
//   manager database.
//
//   PARAMETERS: 
//   * pszServiceName - the name of the service to be removed.
//
//   NOTE: If the function fails to uninstall the service, it prints the 
//   error in the standard output stream for users to diagnose the problem.
//
void UninstallService(PWSTR pszServiceName)
{
    SC_HANDLE schSCManager = NULL;
    SC_HANDLE schService = NULL;
    SERVICE_STATUS ssSvcStatus = {};

    // Open the local default service control manager database
    schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
    if (schSCManager == NULL)
    {
        wprintf(L"OpenSCManager failed w/err 0x%08lx\n", GetLastError());
        goto Cleanup;
    }

    // Open the service with delete, stop, and query status permissions
    schService = OpenService(schSCManager, pszServiceName, SERVICE_STOP | 
        SERVICE_QUERY_STATUS | DELETE);
    if (schService == NULL)
    {
        wprintf(L"OpenService failed w/err 0x%08lx\n", GetLastError());
        goto Cleanup;
    }

    // Try to stop the service
    if (ControlService(schService, SERVICE_CONTROL_STOP, &ssSvcStatus))
    {
        wprintf(L"Stopping %s.", pszServiceName);
        Sleep(1000);

        while (QueryServiceStatus(schService, &ssSvcStatus))
        {
            if (ssSvcStatus.dwCurrentState == SERVICE_STOP_PENDING)
            {
                wprintf(L".");
                Sleep(1000);
            }
            else break;
        }

        if (ssSvcStatus.dwCurrentState == SERVICE_STOPPED)
        {
            wprintf(L"\n%s is stopped.\n", pszServiceName);
        }
        else
        {
            wprintf(L"\n%s failed to stop.\n", pszServiceName);
        }
    }

    // Now remove the service by calling DeleteService.
    if (!DeleteService(schService))
    {
        wprintf(L"DeleteService failed w/err 0x%08lx\n", GetLastError());
        goto Cleanup;
    }

    wprintf(L"%s is removed.\n", pszServiceName);

Cleanup:
    // Centralized cleanup for all allocated resources.
    if (schSCManager)
    {
        CloseServiceHandle(schSCManager);
        schSCManager = NULL;
    }
    if (schService)
    {
        CloseServiceHandle(schService);
        schService = NULL;
    }
}
开发者ID:thiagomg,项目名称:service,代码行数:83,代码来源:ServiceInstaller.cpp

示例11: SERVICE_STATE

int	SERVICE_STATE(AGENT_REQUEST *request, AGENT_RESULT *result)
{
	SC_HANDLE	mgr, service;
	char		*name;
	wchar_t		*wname;
	wchar_t		service_name[MAX_STRING_LEN];
	DWORD		max_len_name = MAX_STRING_LEN;
	int		i;
	SERVICE_STATUS	status;

	if (1 < request->nparam)
	{
		SET_MSG_RESULT(result, zbx_strdup(NULL, "Too many parameters."));
		return SYSINFO_RET_FAIL;
	}

	name = get_rparam(request, 0);

	if (NULL == name || '\0' == *name)
	{
		SET_MSG_RESULT(result, zbx_strdup(NULL, "Invalid first parameter."));
		return SYSINFO_RET_FAIL;
	}

	if (NULL == (mgr = OpenSCManager(NULL, NULL, GENERIC_READ)))
	{
		SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot obtain system information."));
		return SYSINFO_RET_FAIL;
	}

	wname = zbx_utf8_to_unicode(name);

	service = OpenService(mgr, wname, SERVICE_QUERY_STATUS);
	if (NULL == service && 0 != GetServiceKeyName(mgr, wname, service_name, &max_len_name))
		service = OpenService(mgr, service_name, SERVICE_QUERY_STATUS);

	zbx_free(wname);

	if (NULL == service)
	{
		SET_UI64_RESULT(result, 255);
	}
	else
	{
		if (0 != QueryServiceStatus(service, &status))
		{
			for (i = 0; i < ARRSIZE(service_states) && status.dwCurrentState != service_states[i]; i++)
				;

			SET_UI64_RESULT(result, i);
		}
		else
			SET_UI64_RESULT(result, 7);

		CloseServiceHandle(service);
	}

	CloseServiceHandle(mgr);

	return SYSINFO_RET_OK;
}
开发者ID:HenryGeek,项目名称:auto_deploy,代码行数:61,代码来源:services.c

示例12: SERVICE_INFO

int	SERVICE_INFO(AGENT_REQUEST *request, AGENT_RESULT *result)
{
	QUERY_SERVICE_CONFIG	*qsc = NULL;
	SERVICE_DESCRIPTION	*scd = NULL;
	SERVICE_STATUS		status;
	SC_HANDLE		h_mgr, h_srv;
	DWORD			sz = 0;
	int			param_type, i;
	char			*name, *param;
	wchar_t			*wname, service_name[MAX_STRING_LEN];
	DWORD			max_len_name = MAX_STRING_LEN;

	if (2 < request->nparam)
	{
		SET_MSG_RESULT(result, zbx_strdup(NULL, "Too many parameters."));
		return SYSINFO_RET_FAIL;
	}

	name = get_rparam(request, 0);
	param = get_rparam(request, 1);

	if (NULL == name || '\0' == *name)
	{
		SET_MSG_RESULT(result, zbx_strdup(NULL, "Invalid first parameter."));
		return SYSINFO_RET_FAIL;
	}

	if (NULL == param || '\0' == *param || 0 == strcmp(param, "state"))	/* default second parameter */
		param_type = ZBX_SRV_PARAM_STATE;
	else if (0 == strcmp(param, "displayname"))
		param_type = ZBX_SRV_PARAM_DISPLAYNAME;
	else if (0 == strcmp(param, "path"))
		param_type = ZBX_SRV_PARAM_PATH;
	else if (0 == strcmp(param, "user"))
		param_type = ZBX_SRV_PARAM_USER;
	else if (0 == strcmp(param, "startup"))
		param_type = ZBX_SRV_PARAM_STARTUP;
	else if (0 == strcmp(param, "description"))
		param_type = ZBX_SRV_PARAM_DESCRIPTION;
	else
	{
		SET_MSG_RESULT(result, zbx_strdup(NULL, "Invalid second parameter."));
		return SYSINFO_RET_FAIL;
	}

	if (NULL == (h_mgr = OpenSCManager(NULL, NULL, GENERIC_READ)))
	{
		SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot obtain system information."));
		return SYSINFO_RET_FAIL;
	}

	wname = zbx_utf8_to_unicode(name);

	h_srv = OpenService(h_mgr, wname, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG);
	if (NULL == h_srv && 0 != GetServiceKeyName(h_mgr, wname, service_name, &max_len_name))
		h_srv = OpenService(h_mgr, service_name, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG);

	zbx_free(wname);

	if (NULL == h_srv)
	{
		int	ret;

		if (ZBX_SRV_PARAM_STATE == param_type)
		{
			SET_UI64_RESULT(result, 255);
			ret = SYSINFO_RET_OK;
		}
		else
		{
			SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot find the specified service."));
			ret = SYSINFO_RET_FAIL;
		}

		CloseServiceHandle(h_mgr);
		return ret;
	}

	if (ZBX_SRV_PARAM_STATE == param_type)
	{
		if (0 != QueryServiceStatus(h_srv, &status))
		{
			for (i = 0; i < ARRSIZE(service_states) && status.dwCurrentState != service_states[i]; i++)
				;

			SET_UI64_RESULT(result, i);
		}
		else
			SET_UI64_RESULT(result, 7);
	}
	else if (ZBX_SRV_PARAM_DESCRIPTION == param_type)
	{
		QueryServiceConfig2(h_srv, SERVICE_CONFIG_DESCRIPTION, NULL, 0, &sz);

		if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
		{
			SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot obtain service description: %s",
					strerror_from_system(GetLastError())));
			CloseServiceHandle(h_srv);
			CloseServiceHandle(h_mgr);
//.........这里部分代码省略.........
开发者ID:HenryGeek,项目名称:auto_deploy,代码行数:101,代码来源:services.c

示例13: unregister_service

static void
unregister_service(int argc, char *argv[])
{
	SC_HANDLE service, scm;
	BOOL success;
	SERVICE_STATUS status;

	sw_debug(SW_LOG_NOTICE, "starting...\n");

	//
	// Open a connection to the SCM
	//
	scm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
	if (!scm)
	{
		service_error_handler("In OpenScManager", GetLastError());
		exit(0);
	}

	// Get the service's handle
	service = OpenService(scm, SERVICE_NAME, SERVICE_ALL_ACCESS | DELETE);
	if (!service)
	{
		service_error_handler("In OpenService", GetLastError());
	}
	
	//
	// Stop the service if necessary
	//
	success = QueryServiceStatus(service, &status);
	if (!success)
	{
		service_error_handler("In QueryServiceStatus", GetLastError());
	}

	if (status.dwCurrentState != SERVICE_STOPPED)
	{
		sw_debug(SW_LOG_NOTICE, "stopping service...\n");
		success = ControlService(service, SERVICE_CONTROL_STOP, &status);
		if (!success)
		{
			service_error_handler("In ControlService", GetLastError());
		}
		Sleep(500);
	}
	
	//
	// Remove the service
	//
	success = DeleteService(service);
	if (success)
	{
		sw_debug(SW_LOG_NOTICE, "service unregistered\n");
	}
	else
	{
		service_error_handler("DeleteService", GetLastError());
	}

	//
	// Clean up
	//
	CloseServiceHandle(service);
	CloseServiceHandle(scm);
}
开发者ID:daddyreb,项目名称:Bigit_Genie,代码行数:65,代码来源:win32_main.c

示例14: CmdRemoveService

//
//  FUNCTION: CmdRemoveService()
//
//  PURPOSE: Stops and removes the service
//
//  PARAMETERS:
//    none
//
//  RETURN VALUE:
//    0 if success
//
//  COMMENTS:
//
int CmdRemoveService()
{
   SC_HANDLE   schService;
   SC_HANDLE   schSCManager;

   int ret = 0;

   schSCManager = OpenSCManager(
                               NULL,                   // machine (NULL == local)
                               NULL,                   // database (NULL == default)
                               SC_MANAGER_CONNECT   // access required
                               );
   if ( schSCManager )
   {
      schService = OpenService(schSCManager, TEXT(SZSERVICENAME), DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);

      if (schService)
      {
         // try to stop the service
         if ( ControlService( schService, SERVICE_CONTROL_STOP, &ssStatus ) )
         {
            _tprintf(TEXT("Stopping %s."), TEXT(SZSERVICEDISPLAYNAME));
            Sleep( 1000 );

            while ( QueryServiceStatus( schService, &ssStatus ) )
            {
               if ( ssStatus.dwCurrentState == SERVICE_STOP_PENDING )
               {
                  _tprintf(TEXT("."));
                  Sleep( 1000 );
               }
               else
                  break;
            }

            if ( ssStatus.dwCurrentState == SERVICE_STOPPED )
               _tprintf(TEXT("\n%s stopped.\n"), TEXT(SZSERVICEDISPLAYNAME) );
            else
         {
               _tprintf(TEXT("\n%s failed to stop.\n"), TEXT(SZSERVICEDISPLAYNAME) );
      ret = 1;
         }

         }

         // now remove the service
         if ( DeleteService(schService) )
            _tprintf(TEXT("%s removed.\n"), TEXT(SZSERVICEDISPLAYNAME) );
         else
      {
            _tprintf(TEXT("DeleteService failed - %s\n"), GetLastErrorText(szErr,256));
        ret = 1;
      }


         CloseServiceHandle(schService);
      }
      else
   {
         _tprintf(TEXT("OpenService failed - %s\n"), GetLastErrorText(szErr,256));
     ret = 1;
   }

      CloseServiceHandle(schSCManager);
   }
   else
     {
      _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256));
       ret = 1;
     }
   return ret;
}
开发者ID:felipebuarque,项目名称:PL-Stats,代码行数:85,代码来源:win32_cservice.c

示例15: EspRestartServiceDlgProc

static INT_PTR CALLBACK EspRestartServiceDlgProc(
    _In_ HWND hwndDlg,
    _In_ UINT uMsg,
    _In_ WPARAM wParam,
    _In_ LPARAM lParam
    )
{
    PRESTART_SERVICE_CONTEXT context;

    if (uMsg == WM_INITDIALOG)
    {
        context = (PRESTART_SERVICE_CONTEXT)lParam;
        SetProp(hwndDlg, L"Context", (HANDLE)context);
    }
    else
    {
        context = (PRESTART_SERVICE_CONTEXT)GetProp(hwndDlg, L"Context");

        if (uMsg == WM_DESTROY)
            RemoveProp(hwndDlg, L"Context");
    }

    if (!context)
        return FALSE;

    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            PhCenterWindow(hwndDlg, GetParent(hwndDlg));

            // TODO: Use the progress information.
            PhSetWindowStyle(GetDlgItem(hwndDlg, IDC_PROGRESS), PBS_MARQUEE, PBS_MARQUEE);
            SendMessage(GetDlgItem(hwndDlg, IDC_PROGRESS), PBM_SETMARQUEE, TRUE, 75);

            SetDlgItemText(hwndDlg, IDC_MESSAGE, PhaFormatString(L"Attempting to stop %s...", context->ServiceItem->Name->Buffer)->Buffer);

            if (PhUiStopService(hwndDlg, context->ServiceItem))
            {
                SetTimer(hwndDlg, 1, 250, NULL);
            }
            else
            {
                EndDialog(hwndDlg, IDCANCEL);
            }
        }
        break;
    case WM_COMMAND:
        {
            switch (LOWORD(wParam))
            {
            case IDCANCEL:
                {
                    EndDialog(hwndDlg, IDCANCEL);
                }
                break;
            }
        }
        break;
    case WM_TIMER:
        {
            if (wParam == 1 && !context->DisableTimer)
            {
                SERVICE_STATUS serviceStatus;

                if (QueryServiceStatus(context->ServiceHandle, &serviceStatus))
                {
                    if (!context->Starting && serviceStatus.dwCurrentState == SERVICE_STOPPED)
                    {
                        // The service is stopped, so start the service now.

                        SetDlgItemText(hwndDlg, IDC_MESSAGE,
                            PhaFormatString(L"Attempting to start %s...", context->ServiceItem->Name->Buffer)->Buffer);
                        context->DisableTimer = TRUE;

                        if (PhUiStartService(hwndDlg, context->ServiceItem))
                        {
                            context->DisableTimer = FALSE;
                            context->Starting = TRUE;
                        }
                        else
                        {
                            EndDialog(hwndDlg, IDCANCEL);
                        }
                    }
                    else if (context->Starting && serviceStatus.dwCurrentState == SERVICE_RUNNING)
                    {
                        EndDialog(hwndDlg, IDOK);
                    }
                }
            }
        }
        break;
    }

    return FALSE;
}
开发者ID:blaquee,项目名称:processhacker2,代码行数:97,代码来源:srvprgrs.c


注:本文中的QueryServiceStatus函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。