Source file: /~heha/hsn/maus32.zip/PnP/disableport.cpp

#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <setupapi.h>
#include <cfgmgr32.h>
#include <devguid.h>
#define elemof(x) (sizeof(x)/sizeof(*(x)))
#define T(x) TEXT(x)
/* ... dann versuchen wir mal, ein COM-Port aus- und einzuschalten!
*/

EXTERN_C int mainCRTStartup() {
 int argc;
 LPWSTR *argv=CommandLineToArgvW(GetCommandLine(),&argc);

 if (argc<2) {
  printf(
       "Deaktivieren oder Aktivieren eines COM- oder LPT-Ports, h#s 120208\n"
       "Argument: COMx oder LPTx\n");
  return 0;
 }

 HDEVINFO Devs=SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS,NULL,0,DIGCF_PRESENT);
 
 SP_DEVINFO_DATA devInfo;
 devInfo.cbSize=sizeof(devInfo);
 for (int j=0; SetupDiEnumDeviceInfo(Devs,j,&devInfo); j++) {
  HKEY hKey;
  TCHAR val[16];
  DWORD valsize=sizeof(val);
  DWORD status,problem;
  if (!CM_Open_DevNode_Key(devInfo.DevInst,KEY_QUERY_VALUE,0,RegDisposition_OpenExisting,&hKey,CM_REGISTRY_HARDWARE)) {
   if (!RegQueryValueEx(hKey,T("PortName"),NULL,NULL,(LPBYTE)val,&valsize)
   && !_tcsicmp(val,argv[1])
   && !CM_Get_DevNode_Status(&status,&problem,devInfo.DevInst,0)
   && (!(status&DN_HAS_PROBLEM) || problem==CM_PROB_DISABLED)) {
    SP_PROPCHANGE_PARAMS pcp;
    pcp.ClassInstallHeader.cbSize=sizeof(pcp.ClassInstallHeader);
    pcp.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
    pcp.StateChange = status&DN_HAS_PROBLEM ? DICS_ENABLE : DICS_DISABLE;
    pcp.Scope = DICS_FLAG_CONFIGSPECIFIC;
    pcp.HwProfile = 0;
    if (SetupDiSetClassInstallParams(Devs,&devInfo,&pcp.ClassInstallHeader,sizeof(pcp)) &&
        SetupDiCallClassInstaller(DIF_PROPERTYCHANGE,Devs,&devInfo)) {
     printf("OK\n");
    }else{
     TCHAR buf[256];
     FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
       NULL,GetLastError(),0,buf,elemof(buf),NULL);
     printf("Fehler: %S",buf);
    }
   }
   RegCloseKey(hKey);
  }
 }
 SetupDiDestroyDeviceInfoList(Devs);
 ExitProcess(0);
}
Detected encoding: ASCII (7 bit)2