如何通过win32com的Dispatch将指定Excel窗口设为最顶层
How to Set an Excel Window as Topmost Using win32com
Perfect scenario—let's solve this! Excel's COM object model doesn't have a built-in "always on top" property, but we can combine win32com.client.Dispatch with Windows API calls (part of the same pywin32 package) to make this happen. Here's exactly how to keep your second Excel window topmost without closing it, even after reopening the first file:
Step-by-Step Explanation
- Open each workbook in a separate Excel instance: This ensures each file has its own independent window (instead of tabs in one window).
- Retrieve the window handle of the second Excel instance.
- Call the Windows API
SetWindowPosfunction to mark that window as topmost. - Close and reopen the first workbook—the second window stays on top.
Complete Code Example
import win32com.client import win32api import win32con # Define your file paths (use raw strings to avoid escape character issues) path1 = r'C:\Todolist.xls' path2 = r'C:\Todolist2.xlsx' # Open first workbook in its own Excel instance excel_app1 = win32com.client.Dispatch("Excel.Application") excel_app1.DisplayAlerts = False # Skip save prompts when closing excel_app1.Visible = True wb1 = excel_app1.Workbooks.Open(path1) # Open second workbook in a separate Excel instance excel_app2 = win32com.client.Dispatch("Excel.Application") excel_app2.DisplayAlerts = False excel_app2.Visible = True wb2 = excel_app2.Workbooks.Open(path2) # Function to set a window as always topmost def set_topmost_window(hwnd): # Use Windows API to set the window position # HWND_TOPMOST = -1 (keeps window above all others) # SWP_NOMOVE + SWP_NOSIZE = keep current position/size win32api.SetWindowPos( hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE ) # Apply topmost to the second Excel window set_topmost_window(excel_app2.Hwnd) # Simulate closing and reopening the first workbook wb1.Close() excel_app1.Quit() # Reopen first workbook excel_app1 = win32com.client.Dispatch("Excel.Application") excel_app1.DisplayAlerts = False excel_app1.Visible = True wb1 = excel_app1.Workbooks.Open(path1) # Now your second Excel window stays on top!
Key Notes
- If your workbooks are in the same Excel instance (tabs), replace
excel_app2.Hwndwithwb2.Windows(1).Hwndto target the specific workbook's window tab. - The
win32apiandwin32conmodules are part of the pywin32 package, which you already have installed if you're usingwin32com.client. DisplayAlerts = Falseprevents Excel from asking to save changes when closing workbooks (adjust this if you need to save unsaved changes).
内容的提问来源于stack exchange,提问作者superx
相关产品推荐
相关产品推荐

