### Run pywin32 post-install script globally Source: https://github.com/mhammond/pywin32/blob/main/README.md Execute this script after a global pip installation to set up COM objects and services. Running with elevated permissions installs for the machine; otherwise, it installs for the user. ```shell python -m pywin32_postinstall -install ``` ```shell pywin32_postinstall -install ``` -------------------------------- ### Example nmake Path Source: https://github.com/mhammond/pywin32/blob/main/pythonwin/Scintilla/README_pythonwin.md An example of the full path to the nmake executable, typically found within Visual Studio Build Tools. ```shell C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.41.34120\bin\Hostx86\x86\nmake.exe ``` -------------------------------- ### Install pywin32 using pip Source: https://github.com/mhammond/pywin32/blob/main/README.md Use this command to install or upgrade pywin32. It is recommended to run this outside of virtual environments for global installations. ```shell python -m pip install --upgrade pywin32 ``` -------------------------------- ### Verify Compiler Installation Source: https://github.com/mhammond/pywin32/blob/main/build_env.md After configuring the build environment, running 'cl' should display the installed C/C++ compiler version. ```shell cl ``` -------------------------------- ### Deprecated Installation Executables Source: https://github.com/mhammond/pywin32/blob/main/CHANGES.md As of build 305, installation .exe files are deprecated. Refer to the provided URL for more information. ```url https://mhammond.github.io/pywin32_installers.html ``` -------------------------------- ### Install Built Wheel Source: https://github.com/mhammond/pywin32/blob/main/build_env.md Copy the generated wheel file to the target ARM64 machine and install it using pip. Replace with the actual path to your wheel file. ```shell pip install "" -v ``` -------------------------------- ### Install pywin32 Package Source: https://github.com/mhammond/pywin32/blob/main/build_env.md This command installs the pywin32 package from the local directory with verbose output enabled to show build details. ```shell pip install . -v ``` -------------------------------- ### Example: Interacting with Excel COM Object Source: https://github.com/mhammond/pywin32/blob/main/com/win32com/HTML/QuickStartClientCom.html This example demonstrates how to use the `Dispatch` method to create an Excel application object, make it visible, add a new workbook, and set a value in a cell. ```python o = win32com.client.Dispatch("Excel.Application") o.Visible = 1 o.Workbooks.Add() o.Cells(1,1).Value = "Hello" ``` -------------------------------- ### Setup Cross-Compilation Environment Source: https://github.com/mhammond/pywin32/blob/main/build_env.md Initialize the build environment for cross-compiling from x86 to ARM64 using the vcvarsall.bat script. Ensure you replace XXXX with your Visual Studio version. ```shell "C:\Program Files (x86)\Microsoft Visual Studio\XXXX\BuildTools\vc\Auxiliary\Build\vcvarsall.bat" x86_arm64 ``` -------------------------------- ### Running adodbapi Server Module Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/readme.txt Example command to run the adodbapi server module, which allows a Windows computer to serve ADO databases via PyRO. The server supports connection string macros. ```bash C:>python -m adodbapi.server ``` -------------------------------- ### run(cmd, globals=None, locals=None) Source: https://github.com/mhammond/pywin32/blob/main/pythonwin/doc/debugger/general.html Starts debugging a command within the specified globals and locals context. ```APIDOC ## run(cmd, globals=None, locals=None) ### Description Starts debugging a command within the specified globals and locals context. ### Parameters - **cmd**: The command to debug. - **globals** (optional): The global context for the command. - **locals** (optional): The local context for the command. ### Usage `run(cmd, globals, locals)` ``` -------------------------------- ### Basic initscore.py Structure Source: https://github.com/mhammond/pywin32/blob/main/pythonwin/doc/EmbeddingWin32ui.html The initscore.py file is the entry point for Python code when embedding win32ui. This minimal example shows the basic imports required. ```python import sys import win32ui ``` -------------------------------- ### Numeric parameter style example (not implemented in adodbapi) Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md This is an example of the 'numeric' parameter style, which uses numbers to denote parameter positions (e.g., :1, :2). Note that this style is not implemented in adodbapi. ```sql UPDATE cheese SET qtyonhand = :1 WHERE name = :2 ``` -------------------------------- ### Execute Python Function Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Example of calling a Python function from the script. ```python is64bit.Python() ``` -------------------------------- ### Execute OS Function Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Example of calling an OS-related Python function. ```python is64bit.os() ``` -------------------------------- ### Raising a COM Exception Source: https://github.com/mhammond/pywin32/blob/main/com/win32com/HTML/QuickStartServerCom.html This example demonstrates how to raise a COM exception with detailed error information. The `COMException` class from `win32com.server.exception` helps in providing attributes like `scode`, `code`, `description`, `source`, `helpfile`, and `helpcontext` to the COM client. ```python raise COMException(desc="Must be a string",scode=winerror.E_INVALIDARG,helpfile="myhelp.hlp",...) ``` -------------------------------- ### Example of executemany internal logic Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Illustrates how cursor.executemany() is implemented internally using .prepare() and .execute(). This shows the flow for executing a single operation multiple times with different parameters. ```python def executemany(self, operation, sequence_of_parameter_sequences): self.prepare(operation) for params in sequence_of_parameter_sequences: self.execute(self.command, params) ``` -------------------------------- ### Write to IE Document Directly with Python Source: https://github.com/mhammond/pywin32/blob/main/com/win32comext/axscript/demos/client/ie/docwrite.htm This example demonstrates writing HTML content directly to an IE document using Python's COM interface. The document must be opened before writing and closed afterward. ```Python ax.document.write("

Hello from Python") ax.document.close() ``` -------------------------------- ### List All User Accounts with Full Names using NetUserEnum Source: https://github.com/mhammond/pywin32/blob/main/win32/help/win32net.html Enumerates all 'normal' user accounts on a server and retrieves their full names. It uses NetUserEnum to get account names and NetUserGetInfo to fetch the full name for each user. ```python def getall_users(server): 'This functions returns a list of id and full_names on an NT server' j=1 res=1 users=[] user_list=[] try: while res: (users,total,res) = win32net.NetUserEnum(server,3,win32netcon.FILTER_NORMAL_ACCOUNT,res,win32netcon.MAX_PREFERRED_LENGTH) for i in users: add=0 login=str(i['name']) info_dict=win32net.NetUserGetInfo(server, login, 3) full_name=str(info_dict['full_name']) j=j+1 user_list.append(login+'\t'+full_name) return user_list except win32net.error: print(traceback.format_tb(sys.exc_info()[2]),'\n',sys.exc_type,'\n',sys.exc_value) print(getall_users(r'\\dino')) ``` -------------------------------- ### Execute with 'qmark' parameter style Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Use 'qmark' for queries where parameters are represented by question marks. Pass parameters as a sequence in the correct order. ```python sql = "UPDATE cheese SET qtyonhand = ? WHERE name = ?" args = [0, 'MUNSTER'] crsr.execute(sql, args) ``` -------------------------------- ### Create COM Record from GUIDs in Python Source: https://github.com/mhammond/pywin32/blob/main/com/win32com/HTML/COM_Records.html Use pythoncom.GetRecordFromGuids to create a COM Record instance when makepy-support is unavailable. Ensure the Type Library is registered and provide the necessary GUIDs, versions, and LCID. ```python import pythoncom PyCOMTestLib_GUID = '{6bcdcb60-5605-11d0-ae5f-cadd4c000000}' MAJVER = 1 MINVER = 1 LCID = 0 TestStruct1_GUID = '{7a4ce6a7-7959-4e85-a3c0-b41442ff0f67}' record1 = pythoncom.GetRecordFromGuids(PyCOMTestLib_GUID, MAJVER, MINVER, LCID, TestStruct1_GUID) ``` -------------------------------- ### Connect using a Full Connection String Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Establish a connection by providing a detailed ADO connection string. This method is useful when a pre-configured data source name is not available. ```python import adodbapi myhost = r".\SQLEXPRESS" mydatabase = "Northwind" myuser = "guest" mypassword = "12345678" connStr = """Provider=SQLOLEDB.1; User ID=%s; Password=%s; Initial Catalog=%s;Data Source= %s""" myConnStr = connStr % (myuser, mypassword, mydatabase, myhost) myConn = adodbapi.connect(myConnStr) ``` -------------------------------- ### Instantiate and Inspect a Dialog Object in Pythonwin Source: https://github.com/mhammond/pywin32/blob/main/pythonwin/doc/architecture.html Demonstrates how to import win32ui and a custom dialog class, instantiate a dialog, and inspect its underlying C++ object details. ```python >>> import win32ui # import the base win32ui module. >>> import dialog # import dialog.py >>> d=dialog.Dialog(win32ui.IDD_SIMPLE_INPUT) >>> d

``` ```python >>> d._obj_ object 'PyCDialog' - assoc is 002F3278, vf=True, ch=0, mh=2, kh=0 >>> ``` -------------------------------- ### Get Directory Permissions Source: https://github.com/mhammond/pywin32/blob/main/win32/help/security_directories.html Retrieves a dictionary of user/group access masks for a given file path. Requires the 'fileperm' module. ```python import fileperm all_perms=fileperm.get_perms(r'\\Simon\share\db\a.txt') ``` ```python print(all_perms) ``` ```python {'\\Everyone': 2032127L, 'Domain\\fred': 1179817L, 'BUILTIN\\Users': 1179817L} ``` -------------------------------- ### Accessing Table Names with adodbapi Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/readme.txt Example of using the `get_table_names()` method on a connection object to retrieve a list of table names in the database. ```python conn.get_table_names() ``` -------------------------------- ### Initialize win32ui in CWinApp::InitInstance Source: https://github.com/mhammond/pywin32/blob/main/pythonwin/doc/EmbeddingWin32ui.html Modify your CWinApp derived class's InitInstance method to initialize the win32ui extension. This involves calling DynamicApplicationInit with the Python command to execute and an optional PythonPath. ```cpp BOOL GameApp::InitInstance() { ... if (!glue.DynamicApplicationInit("import initscore", csScripts)) { // Assuming you have a ReportError method - do whatever makes sense! ReportError("Could not attach to the Python win32ui extensions"); return FALSE; } ... ``` -------------------------------- ### Fetch Rows by Index Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Demonstrates fetching rows using the standard PEP sequence-like indexing. The loop continues until fetchone() returns None. ```python crsr.execute("SELECT prodname, price, qtyonhand FROM cheese") row = crsr.fetchone() while row: value = row[1] * row[2] print("Your {:10s} is worth {:10.2f}".format(row[0], value)) row = crsr.fetchone() # returns None when no data remains ``` -------------------------------- ### Acquire ADSI and LDAP Provider Objects Source: https://github.com/mhammond/pywin32/blob/main/com/help/adsi.html Instantiates the ADSI namespace and gets an LDAP provider object. This is a prerequisite for most ADSI operations. ```python adsi = win32com.client.Dispatch('ADsNameSpaces') ldap = adsi.getobject("","LDAP:") ``` -------------------------------- ### Get Process IDs (Python) Source: https://github.com/mhammond/pywin32/blob/main/win32/help/process_info.html Retrieves process IDs by iterating through process instances and using PDH functions. Requires pywin32 library. ```python for instance, max_instances in proc_dict.items(): for inum in xrange(max_instances+1): try: hq = win32pdh.OpenQuery() # initializes the query handle path = win32pdh.MakeCounterPath( (None,self.object,instance, None, inum, self.item) ) counter_handle=win32pdh.AddCounter(hq, path) #convert counter path to counter handle win32pdh.CollectQueryData(hq) #collects data for the counter type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG) proc_ids.append(instance+'\t'+str(val)) win32pdh.CloseQuery(hq) except: raise COMException("Problem getting process id") ``` -------------------------------- ### Connect using Positional Arguments with Formatting Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Connect using positional arguments where placeholders in the connection string are filled using Python's old-style string formatting. The order of arguments is user, password, host, database. ```python connStr = """Provider=SQLOLEDB.1; User ID=%(user)s; Password=%(password)s;"Initial Catalog=%(database)s; Data Source= %(host)s""" myConn=adodbapi.connect(connStr, myuser, mypassword, myhost, mydatabase) ``` -------------------------------- ### Execute with 'pyformat' parameter style Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Use 'pyformat' for queries where parameters are represented by '%(name)s'. Pass parameters as a dictionary where keys match the names within the parentheses. ```python UPDATE cheese SET qtyonhand = %(qty)s WHERE name =%(prodname)s args = {'qty' : 0, 'prodname' : 'MUNSTER'} crsr.execute(sql, args) ``` -------------------------------- ### Get and Modify User Information Source: https://github.com/mhammond/pywin32/blob/main/com/help/adsi.html Retrieves user information from Exchange and demonstrates how to modify user attributes. Changes are made permanent by calling SetInfo(). ```python ex_path="LDAP://server/cn=fredflint,cn=Recipients,ou=rubble,o=bedrock" myDSObject = ldap.OpenDSObject(ex_path,logon_ex,password,0) myDSObject.Getinfo() # To access a user's data try: attribute = myDSObject.Get('Extension-Attribute-1') print(attribute) # To modify a user try: myDSObject.Put('Extension-Attribute-1','barney was here') myDSObject.Setinfo() ``` -------------------------------- ### Fetch Rows by Column Name Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Shows an extension where rows can be accessed using column names as dictionary keys. This example also uses the cursor as an iterator. ```python crsr.execute("SELECT prodname, price, qtyonhand FROM cheese") for row in crsr: # note extension: using crsr as an iterator value = row["price"] * row["qtyonhand"] print("Your {:10s} is worth {:10.2f}".format(row["prodname"], value)) ``` -------------------------------- ### Setuptools SDK Environment Variable Source: https://github.com/mhammond/pywin32/blob/main/build_env.md Set the DISTUTILS_USE_SDK environment variable to 1 to ensure setuptools uses the SDK for building. ```shell set DISTUTILS_USE_SDK=1 ``` -------------------------------- ### Initialize Custom Pythonwin Application Source: https://github.com/mhammond/pywin32/blob/main/pythonwin/doc/EmbeddingWin32ui.html This snippet shows how to create a custom application class inheriting from InteractivePythonApp and overriding the InitInstance method to perform application-specific initialization, such as minimizing the interactive window. ```Python import win32con from pywin.framework import intpyapp, app class ScoreApp(intpyapp.InteractivePythonApp): def InitInstance(self): # Call the base class (if you want) intpyapp.InteractivePythonApp.InitInstance(self) # Do domething useful, specific to your app. # Here, we minimise the interactive window. # (after painting the main frame) win32ui.PumpWaitingMessages() interact.edit.currentView.GetParent().ShowWindow(win32con.SW_MINIMIZE) app = ScoreApp() ``` -------------------------------- ### Define Subclass of pythoncom.com_record Source: https://github.com/mhammond/pywin32/blob/main/com/win32com/HTML/COM_Records.html Define a Python subclass for a COM Record type by specifying the TLBID, MJVER, MNVER, LCID, and GUID as class attributes. This is a prerequisite for registering the class. ```python import pythoncom class TestStruct1(pythoncom.com_record): TLBID = '{6bcdcb60-5605-11d0-ae5f-cadd4c000000}' MJVER = 1 MNVER = 1 LCID = 0 GUID = '{7a4ce6a7-7959-4e85-a3c0-b41442ff0f67}' ``` -------------------------------- ### Create COM Record Instance with Early Binding Source: https://github.com/mhammond/pywin32/blob/main/com/win32com/HTML/COM_Records.html Use `win32com.client.Record` to create COM Record instances by specifying the COM Record name and an interface object. The returned instance will always be of the generic `com_record` type. ```python import win32com.client com_test = win32com.client.Dispatch("PyCOMTest.PyCOMTest") record1 = win32com.client.Record('TestStruct1' ,com_test) ``` -------------------------------- ### Fetch Rows by Attribute Access Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Illustrates accessing row data using column names as object attributes, offering a more readable syntax. This example also uses the cursor as an iterator. ```python crsr.execute("SELECT prodname, price, qtyonhand FROM cheese") for row in crsr: value = row.price * row.qtyonhand print("Your {:10s} is worth {:10.2f}".format(row.prodname, value)) ``` -------------------------------- ### Check Engine Registration with JavaScript Source: https://github.com/mhammond/pywin32/blob/main/com/win32comext/axscript/demos/client/ie/demo_check.htm This JavaScript code attempts to open a new window to 'demo_intro.htm'. If successful, it indicates the engine is registered. If an error occurs, it navigates back. ```JavaScript try { window.open("demo_intro.htm", "Body") } except: history.back() ``` -------------------------------- ### Connect using Keyword Arguments Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Establish a connection using keyword arguments, which is a more readable alternative to positional arguments for specifying connection details. ```python myConn = adodbapi.connect(connStr, user=myuser, password=mypassword, host=myhost, database=mydatabase) ``` -------------------------------- ### adodbapi Module Attributes for Python 3 Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md In Python 3, import only the necessary symbols from apibase and ado_consts to keep the namespace clean. This example shows the recommended imports for Python 3. ```python if sys.version_info < (3,0): # in Python 2, define all symbols, just like before from apibase import * from ado_consts import * else: # but if the user is running Python 3, then keep the dictionary clean from apibase import apilevel, threadsafety, paramstyle from apibase import Warning, Error, InterfaceError, DatabaseError, DataError from apibase import OperationalError, IntegrityError from apibase import InternalError, ProgrammingError, NotSupportedError from apibase import NUMBER, STRING, BINARY, DATETIME, ROWID from adodbapi import connect, Connection, __version__ version = 'adodbapi v' + __version__ ``` -------------------------------- ### Download ARM64 Python Libraries Source: https://github.com/mhammond/pywin32/blob/main/build_env.md Use this script to download prebuilt Python ARM64 binaries that match your Python version. Specify a target directory for the downloaded libraries. ```shell python .github\workflows\download-arm64-libs.py ./arm64libs ``` -------------------------------- ### Get Base Permissions for a File Source: https://github.com/mhammond/pywin32/blob/main/win32/help/security_directories.html Retrieves all security permissions for a given file using the `fileperm.get_perms` function. It then iterates through these permissions, extracts domain and user/group IDs, and formats them into a comma-separated string. ```python def get_perm_base(file): all_perms=fileperm.get_perms(file) for (domain_id,mask) in all_perms.items(): (domain,sys_id)=domain_id.split('\\',1) mask_name=get_mask(mask) Results.append(file+','+sys_id+','+mask_name) ``` -------------------------------- ### Get File Permissions in C/Python Integration Source: https://github.com/mhammond/pywin32/blob/main/win32/help/security_directories.html This C function, designed for Python integration, retrieves the DACL for a given file or directory and populates a structure with permission information. It uses GetNamedSecurityInfo and acl_info. ```c static PyObject *get_perms(PyObject *self, PyObject *args) { PyObject *py_perms = PyDict_New(); //get file or directory name char *file; if (!PyArg_ParseTuple(args, "s", &file)) return NULL; //setup security code PSECURITY_DESCRIPTOR pSD; PACL pDACL; //GetNamedSecurityInfo() will give you the DACL when you ask for //DACL_SECURITY_INFORMATION. At this point, you have SIDs in the ACEs contained in the DACL. ULONG result = GetNamedSecurityInfo(file,SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSD); if (result != ERROR_SUCCESS){ return NULL;} if (result == ERROR_SUCCESS){ ACL_SIZE_INFORMATION aclSize = {0}; if(pDACL != NULL){ if(!GetAclInformation(pDACL, &aclSize, sizeof(aclSize), AclSizeInformation)){ return NULL; } } file_perms *fp = new file_perms[aclSize.AceCount]; acl_info(pDACL, aclSize.AceCount, fp ); //Dict for (ULONG i=0;i ``` -------------------------------- ### Enumerate Process Instances (C++) Source: https://github.com/mhammond/pywin32/blob/main/win32/help/process_info.html Enumerates process instances and their counts using PdhEnumObjectItems. Requires careful handling of buffer sizes and memory. ```cpp HRESULT getinst (map < string,int > & m_inst) { map::iterator iter; USES_CONVERSION; LPTSTR szCountersBuf = NULL; DWORD dwCountersSize = 0; LPTSTR szInstancesBuf = NULL; DWORD dwInstancesSize = 0; LPTSTR szTemp = NULL; PDH_STATUS status; std::string str_obj="Process"; status = PdhEnumObjectItems( NULL, NULL, A2CT(str_obj.c_str()), NULL, &dwCountersSize, szInstancesBuf, &dwInstancesSize, PERF_DETAIL_WIZARD, 0 ); if ( ERROR_SUCCESS != status ) return E_FAIL; if (dwCountersSize) { szCountersBuf = (LPTSTR)malloc (dwCountersSize * sizeof (TCHAR)); if (szCountersBuf==NULL) { return E_FAIL; } } else szCountersBuf=NULL; if (dwInstancesSize) { szInstancesBuf = (LPTSTR)malloc (dwInstancesSize * sizeof (TCHAR)); if (szInstancesBuf==NULL) { free(szCountersBuf); return E_FAIL; } } else szInstancesBuf = NULL; status = PdhEnumObjectItems( NULL, NULL, A2CT(str_obj.c_str()), szCountersBuf, &dwCountersSize, szInstancesBuf, &dwInstancesSize, PERF_DETAIL_WIZARD, 0); if ( ERROR_SUCCESS != status ) return E_FAIL; // it's a series of contiguous NULL terminated strings, ending w/zero length string if (szInstancesBuf){ for (szTemp = szInstancesBuf;*szTemp != 0;szTemp += lstrlen(szTemp) + 1) { m_inst[T2A(szTemp)]++; //increment instance counter //default value is zero for arith element } } return S_OK; } ``` -------------------------------- ### QueryInterface for Unknown IID and Release Source: https://github.com/mhammond/pywin32/blob/main/com/win32com/HTML/PythonCOM.html Shows how to query for an unknown IID, obtain a PyIUnknown object, and then query for IDispatch. It is important to call Release() on the PyIUnknown object to clean up resources. ```Python >>> unk=someobj.QueryInterface(SomeUnknownIID) # returns PyIUnknown >>> disp=unk.QueryInterface(win32com.IID_Dispatch) >>> unk.Release() # Clean up now, rather than waiting for unk death. ``` -------------------------------- ### Get Process IDs with Formatted Values (C++) Source: https://github.com/mhammond/pywin32/blob/main/win32/help/process_info.html Obtains process IDs and formats them as doubles using PDH functions. This C++ implementation involves detailed error checking and manual string conversion. ```cpp HRESULT getprocid (map& m_inst, vector &v_ids) { USES_CONVERSION; PDH_STATUS status = 0; HQUERY hQuery = NULL; HCOUNTER hCounter = NULL; DWORD dwType = 0; map m_idinst; std::string objname="Process"; std::string counter="ID Process"; char *buffer; int junk,junk2; // initialize the query handle map < string, int>::iterator iter; for (iter=m_inst.begin();iter != m_inst.end();++iter) { for (int i=0;i<= iter->second;++i) { status = PdhOpenQuery( NULL, 0, &hQuery ); if ( status != ERROR_SUCCESS ) return status; TCHAR szCounterPath[2048]; DWORD dwPathSize = 2048; PDH_COUNTER_PATH_ELEMENTS pdh_elm; pdh_elm.szMachineName = NULL; pdh_elm.szObjectName = A2T(objname.c_str()); pdh_elm.szInstanceName = A2T(iter->first.c_str()); pdh_elm.szParentInstance = NULL; pdh_elm.dwInstanceIndex = i; pdh_elm.szCounterName = A2T(counter.c_str()); status = PdhMakeCounterPath( &pdh_elm, szCounterPath, &dwPathSize, 0 ); if ( status != ERROR_SUCCESS ) { return E_FAIL; } // Add the counter to the query //PdhAddCounter converts each counter path into a counter handle status = PdhAddCounter( hQuery, szCounterPath, 0, &hCounter ); if ( status != ERROR_SUCCESS ) { return E_FAIL; } //PdhCollectQueryData gets raw data for the counters status = PdhCollectQueryData(hQuery); if ( status != ERROR_SUCCESS ) { return E_FAIL; } //PdhGetFormattedCounterValue formats counter values for display DWORD dwFormat = PDH_FMT_DOUBLE; PDH_FMT_COUNTERVALUE fmtValue; status = PdhGetFormattedCounterValue (hCounter, dwFormat, (LPDWORD)NULL, &fmtValue); if (status == ERROR_SUCCESS) { buffer=_fcvt( fmtValue.doubleValue, 0, &junk,&junk2 ); string id=buffer; v_ids.push_back(iter->first+'\t'+id); } } status = PdhCloseQuery (hQuery); //PdhCloseQuery closes the query handle and it's counters } return S_OK; } ``` -------------------------------- ### Connect using a Data Set Name Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Connect to a database using a pre-configured data set name. Ensure the data source is set up in 'Control Panel' -> 'Administrative Tools' -> 'Data Sources (ODBC)'. ```python import adodbapi myConn = adodbapi.connect('myDataSetName') ``` -------------------------------- ### Open, Write, and Close IE Document with Python Source: https://github.com/mhammond/pywin32/blob/main/com/win32comext/axscript/demos/client/ie/docwrite.htm This snippet illustrates the complete process of opening an IE document, writing content to it, and then closing it using Python COM. This is useful for dynamically generating HTML content. ```Python ax.document.open() ax.document.write("

Hello again from Python") ax.document.close() ``` -------------------------------- ### Use a COM object from Python Source: https://github.com/mhammond/pywin32/blob/main/com/win32com/HTML/QuickStartClientCom.html Import the `win32com.client` module and use `Dispatch` to create an instance of a COM object. You can then call its methods and set its properties. ```python import win32com.client o = win32com.client.Dispatch("Object.Name") o.Method() o.property = "New Value" print(o.property) ``` -------------------------------- ### Extending PythonCOM Supported Types Source: https://github.com/mhammond/pywin32/blob/main/com/win32com/HTML/PythonCOM.html Illustrates how an external extension module can register its own COM interfaces and types with PythonCOM. The extension module would typically perform the equivalent of mapping a GUID to a Python type object. ```Python >>> import myextracom # external .pyd supporting some interface. # myextracom.pyd will do the equivalent of # pythoncom.mapSupportedTypes(myextracom.IID_Extra, myextracom.ExtraType) >>> someobj.QueryInterface(myextracom.IID_Extra) ``` -------------------------------- ### Execute with 'format' parameter style Source: https://github.com/mhammond/pywin32/blob/main/adodbapi/quick_reference.md Use 'format' for queries where parameters are represented by '%s'. Pass parameters as a sequence in the correct order. This style is often expected by frameworks like Django. ```python sql = "UPDATE cheese SET qtyonhand = %s WHERE name = %s" args = [0, 'MUNSTER'] crsr.execute(sql, args) ```