⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 vncservice.cpp

📁 teamviewer source code vc++
💻 CPP
📖 第 1 页 / 共 4 页
字号:
{
	// Save the current thread identifier
	g_servicethread = GetCurrentThreadId();

    // report the status to the service control manager.
    //
    if (!ReportStatus(
        SERVICE_RUNNING,       // service state
        NO_ERROR,              // exit code
        0))                    // wait hint
		return;

	DWORD pid = 0, tid = 0; 
	HWND shell = FindWindowEx(NULL, NULL, __T("Progman"), NULL);
    vnclog.Print(LL_INTINFO, VNCLOG("shell=%x"), shell);
	if(shell != 0)
	{
		tid = GetWindowThreadProcessId(shell, &pid); 
		if(tid != 0)
		{
			vnclog.Print(LL_INTINFO, VNCLOG("pid=%d"), pid);
			vncService::ProcessUserHelperMessage(pid);
		}
	}

	// RUN!
	WinVNCAppMain();

	if(vncService::m_impersonationtoken)	
		CloseHandle(vncService::m_impersonationtoken);

	// Mark that we're no longer running
	g_servicethread = NULL;

	// Tell the service manager that we've stopped.
    ReportStatus(
		SERVICE_STOPPED,
		g_error,
		0);
}

// SERVICE STOP ROUTINE - post a quit message to the relevant thread
void ServiceStop()
{
	// Post a quit message to the main service thread
	if (g_servicethread != NULL)
	{
		vnclog.Print(LL_INTINFO, VNCLOG("quitting from ServiceStop"));
		PostThreadMessage(g_servicethread, WM_QUIT, 0, 0);
	}
}

// SERVICE INSTALL ROUTINE
int
vncService::ReinstallService() {
  RemoveService(1);
  Sleep(1000);
  InstallService(1);
  return 0;
}


int
vncService::InstallService(BOOL silent)
{
	HRESULT result = S_OK;

	const int pathlength = 2048;
	char path[pathlength];
	char servicecmd[pathlength];

	// Get the filename of this executable
  if (GetModuleFileName(NULL, path, pathlength-(strlen(winvncRunService)+2)) == 0) {
    if (!silent) {
		  MessageBox(NULL, sz_ID_UNABLE_INST, szAppName, MB_ICONEXCLAMATION | MB_OK);
    }
	return S_FALSE;
  }

	// Append the service-start flag to the end of the path:
	if (strlen(path) + 4 + strlen(winvncRunService) < pathlength)
		sprintf(servicecmd, "\"%s\" -%s", path, winvncRunService);
	else
		return S_FALSE;

	// How to add the WinVNC service depends upon the OS
	switch (g_platform_id)
	{

		// Windows 95/98
	case VER_PLATFORM_WIN32_WINDOWS:
		{
			// Locate the RunService registry entry
			HKEY runservices;
			if (RegCreateKey(HKEY_LOCAL_MACHINE, 
				"Software\\Microsoft\\Windows\\CurrentVersion\\RunServices",
				&runservices) != ERROR_SUCCESS)
			{
			if (!silent) 
			{
				  MessageBox(NULL, sz_ID_SCM_NOT_HERE, szAppName, MB_ICONEXCLAMATION | MB_OK);
			}
			break;
			}

			// Attempt to add a WinVNC key
			if (RegSetValueEx(runservices, szAppName, 0, REG_SZ, (unsigned char *)servicecmd, strlen(servicecmd)+1) != ERROR_SUCCESS)
			{
				RegCloseKey(runservices);
				if (!silent) 
				{
					  MessageBox(NULL, sz_ID_SERV_NOT_REG, szAppName, MB_ICONEXCLAMATION | MB_OK);
				}
				break;
			}

			RegCloseKey(runservices);

			// We have successfully installed the service!

			if (!silent)vncTimedMsgBox::Do(
				sz_ID_SERV_SUCCESS_INST,
				szAppName,
				MB_ICONINFORMATION | MB_OK);


			// Run the service...
			STARTUPINFO si;
			si.cb = sizeof(si);
			si.cbReserved2 = 0;
			si.lpReserved = NULL;
			si.lpReserved2 = NULL;
			si.dwFlags = 0;
			si.lpTitle = NULL;
			PROCESS_INFORMATION pi;
			if (!CreateProcess(
				NULL, servicecmd,							// Program name & path
				NULL, NULL,									// Security attributes
				FALSE,										// Inherit handles?
				NORMAL_PRIORITY_CLASS,						// Extra startup flags
				NULL,										// Environment table
				NULL,										// Current directory
				&si,
				&pi
				))
			{
        if(!silent) {
				  MessageBox(NULL, sz_ID_SERV_FAIL_ST,
            szAppName, MB_ICONSTOP | MB_OK);
        }
				break;
			}
		}
		break;

		// Windows NT
	case VER_PLATFORM_WIN32_NT:
		{
			SC_HANDLE   hservice;
		  SC_HANDLE   hsrvmanager;

			// Open the default, local Service Control Manager database
		  hsrvmanager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
			if (hsrvmanager == NULL)
			{
				result = S_FALSE;
				if (!silent) {
					MessageBox(NULL,
							sz_ID_SERV_CT_MISS,
							szAppName,
							MB_ICONEXCLAMATION | MB_OK);
				}
				break;
			}
			// Create an entry for the WinVNC service
			hservice = CreateService(
				hsrvmanager,				// SCManager database
				VNCSERVICENAME,				// name of service
				VNCSERVICEDISPLAYNAME,		// name to display
				SERVICE_ALL_ACCESS,			// desired access
				SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
											// service type
				SERVICE_AUTO_START,			// start type
				SERVICE_ERROR_NORMAL,		// error control type
				servicecmd,					// service's binary
				NULL,						// no load ordering group
				NULL,						// no tag identifier
				VNCDEPENDENCIES,			// dependencies
				NULL,						// LocalSystem account
				NULL);						// no password
			if (hservice == NULL)
			{
				result = S_FALSE;

				DWORD error = GetLastError();
				if (!silent) {
				 if (error == ERROR_SERVICE_EXISTS) {
					  MessageBox(NULL,
						  sz_ID_SERV_OLD_REG,
						  szAppName,
						  MB_ICONEXCLAMATION | MB_OK);
				  } else {
					  MessageBox(NULL,
						  sz_ID_SERV_NOT_REG,
						  szAppName,
						  MB_ICONEXCLAMATION | MB_OK);
				  }
			 }
 			
			 CloseServiceHandle(hsrvmanager);
			 break;
			}
			CloseServiceHandle(hsrvmanager);
			CloseServiceHandle(hservice);

			// Now install the servicehelper registry setting...
			// Locate the RunService registry entry
			HKEY runapps;
			if (RegCreateKey(HKEY_LOCAL_MACHINE, 
				"Software\\Microsoft\\Windows\\CurrentVersion\\Run",
				&runapps) != ERROR_SUCCESS)
			{
        if (!silent) {
				  MessageBox(NULL, sz_ID_SERVHELP_UNAB, szAppName, MB_ICONEXCLAMATION | MB_OK);
        }
			} else {
				char servicehelpercmd[pathlength];

				// Append the service-helper-start flag to the end of the path:
				if (strlen(path) + 4 + strlen(winvncRunServiceHelper) < pathlength)
					sprintf(servicehelpercmd, "\"%s\" -%s", path, winvncRunServiceHelper);
				else
					return 0;

				// Add the VNCserviceHelper entry
				if (RegSetValueEx(runapps, szAppName, 0, REG_SZ,
					(unsigned char *)servicehelpercmd, strlen(servicehelpercmd)+1) != ERROR_SUCCESS)
				{
          if (!silent) {
					  MessageBox(NULL, sz_ID_SERVHELP_UNAB, szAppName, MB_ICONEXCLAMATION | MB_OK);
          }
        }
				RegCloseKey(runapps);
			}
			result = S_OK;
			// Everything went fine
			if (!silent)vncTimedMsgBox::Do(
				sz_ID_SERV_SUCCESS_REG,
				szAppName,
				MB_ICONINFORMATION | MB_OK);

		}
		break;
	};

	return result;
}

// SERVICE REMOVE ROUTINE
int
vncService::RemoveService(BOOL silent)
{
	// How to remove the WinVNC service depends upon the OS

	switch (g_platform_id)
	{

		// Windows 95/98
	case VER_PLATFORM_WIN32_WINDOWS:
		{
			// Locate the RunService registry entry
			HKEY runservices;
			if (RegOpenKey(HKEY_LOCAL_MACHINE, 
				"Software\\Microsoft\\Windows\\CurrentVersion\\RunServices",
				&runservices) != ERROR_SUCCESS)
			{
        if (!silent) {
				  MessageBox(NULL, sz_ID_SERV_CT_UNREG, szAppName, MB_ICONEXCLAMATION | MB_OK);
			  }
      }
			else
			{
				// Attempt to delete the WinVNC key
				if (RegDeleteValue(runservices, szAppName) != ERROR_SUCCESS)
				{
					/////// Staudenmeyer: registry key should not be closed twice!
					///RegCloseKey(runservices);
          if (!silent) {
					  MessageBox(NULL, sz_ID_SERV_NOT_UNRG, szAppName, MB_ICONEXCLAMATION | MB_OK);
				  }
        }
				
				RegCloseKey(runservices);
				break;
			}

			// Try to kill any running copy of WinVNC
			if (!KillRunningCopy())
			{
        if (!silent) {
				  MessageBox(NULL,
					  sz_ID_SERV_NCONTACT,
					  szAppName,
					  MB_ICONEXCLAMATION | MB_OK);
        }
				break;
			}

			// We have successfully removed the service!
			if (!silent) vncTimedMsgBox::Do(sz_ID_SERV_SUCCESS_UNREG, szAppName, MB_ICONINFORMATION | MB_OK);

		}
		break;

		// Windows NT
	case VER_PLATFORM_WIN32_NT:
		{
			SC_HANDLE   hservice;
			SC_HANDLE   hsrvmanager;

			// Attempt to remove the service-helper hook
			HKEY runapps;
			if (RegOpenKey(HKEY_LOCAL_MACHINE, 
				"Software\\Microsoft\\Windows\\CurrentVersion\\Run",
				&runapps) == ERROR_SUCCESS)
			{
				// Attempt to delete the WinVNC key
				if (RegDeleteValue(runapps, szAppName) != ERROR_SUCCESS)
				{
          if (!silent) {
					  MessageBox(NULL, sz_ID_SERVHELP_NREM, szAppName, MB_ICONEXCLAMATION | MB_OK);
          }
        }
				RegCloseKey(runapps);
			}

			// Open the SCM
		    hsrvmanager = OpenSCManager(
                        NULL,                   // machine (NULL == local)
                        NULL,                   // database (NULL == default)
                        SC_MANAGER_ALL_ACCESS   // access required
                        );
		    if (hsrvmanager)
		    {
		        hservice = OpenService(hsrvmanager, VNCSERVICENAME, SERVICE_ALL_ACCESS);

				if (hservice != NULL)
				{
					SERVICE_STATUS status;

					// Try to stop the WinVNC service
					if (ControlService(hservice, SERVICE_CONTROL_STOP, &status))
					{
						while(QueryServiceStatus(hservice, &status))
						{
							if (status.dwCurrentState == SERVICE_STOP_PENDING)
								Sleep(1000);
							else
								break;
						}

            if (status.dwCurrentState != SERVICE_STOPPED) {
              if (!silent) {
							  MessageBox(NULL, sz_ID_SERV_NOT_STOP, szAppName, MB_ICONEXCLAMATION | MB_OK);
              }
            }
          }

					// Now remove the service from the SCM
					if(DeleteService(hservice)) {

						if (!silent) vncTimedMsgBox::Do(sz_ID_SERV_SUCCESS_UNREG, szAppName, MB_ICONINFORMATION | MB_OK);

					} else {
						DWORD error = GetLastError();
						if (error == ERROR_SERVICE_MARKED_FOR_DELETE) {
              if (!silent)
							  MessageBox(NULL, sz_ID_SERV_MK_UNREG, szAppName, MB_ICONEXCLAMATION | MB_OK);
						} else {
              if (!silent)
							  MessageBox(NULL, sz_ID_SERV_NOT_UNRG, szAppName, MB_ICONEXCLAMATION | MB_OK);
						}
					}
					CloseServiceHandle(hservice);
				}
        else if (!silent)
					MessageBox(NULL, sz_ID_SERV_NT_FOUND, szAppName, MB_ICONEXCLAMATION | MB_OK);

				CloseServiceHandle(hsrvmanager);
			}
			else if (!silent)
				MessageBox(NULL, sz_ID_SERV_CT_UNREG, szAppName, MB_ICONEXCLAMATION | MB_OK);
		}
		break;
	};
	return 0;
}

bool vncService::IsInstallAutostartAllowed()
{
	if (InstallAutostart())
	{
		RemoveAutostart();
		return true;
	}
	return false;
}

bool vncService::InstallAutostart() 
{
	HRESULT hres; 
    IShellLink* psl; 
	bool success = false;

	if SUCCEEDED (CoInitialize(NULL))
	{
		// Get a pointer to the IShellLink interface. 
		hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, 
								IID_IShellLink, (LPVOID*)&psl); 
		if (SUCCEEDED(hres)) 
		{ 
			IPersistFile* ppf; 
			//strcat (szPathObj," -a");
			// Set the path to the shortcut target and add the description. 
			string sPath;

			if (!GetSpecialFolderPath(CSIDL_STARTUP,sPath))
			{
				/*
				  some paths are not available so we get here.
				  Reasons : 
				    1. path was removed from registry
					2. running as service that does not host the path
				      - GetSpecialFolderPath tries to impersonate, maybe it failed?
				*/
			}
			// hres = SHGetFolderPath(NULL,CSIDL_STARTUP, NULL, 0, szPath); doesn磘 work on Win98
			//strcat (szPath,"\\TeamViewer.lnk");
			sPath += "\\TeamViewer.lnk";

			
			char path[MAX_PATH] = "";
			GetModuleFileName(NULL, path, sizeof(path));
			
			psl->SetPath(path); 
						
			
			// psl->SetArguments (roVNCAutoStart);
			// Query IShellLink for the IPersistFile interface for saving the 
			// shortcut in persistent storage. 
			hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); 
	 
			if (SUCCEEDED(hres)) 
			{ 
				WCHAR wsz[MAX_PATH]; 
				
				// Ensure that the string is Unicode. 
				MultiByteToWideChar(CP_ACP, 0, sPath.c_str(), -1, wsz, MAX_PATH); 
				
				// TODO: Check return value from MultiByteWideChar to ensure success.
			
				// Save the link by calling IPersistFile::Save. 
				hres = ppf->Save(wsz, TRUE);
				
				ppf->Release(); 

				if (hres != S_OK)
					success = false;
				else
					success = true;
			} 
			psl->Release();
		}
		CoUninitialize();

    } 

	return success;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -