Automating WinCC Advanced V15 HMI Screenshots with VBScript

David Krause14 min read
HMI ProgrammingSiemensTutorial / How-to
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

Automating WinCC Advanced V15 HMI Screenshots with VBScript

This technical reference documents a robust method for capturing and persisting HMI screen images from a Siemens WinCC Advanced V15 (TIA Portal) runtime without operator intervention. The implementation centers on a VBScript that triggers the runtime's PrintScreen function, redirects the captured bitmap through a PDF virtual printer, suppresses the manual "Save As" prompt by driving the dialog through WScript.Shell, and then renames the resulting file with the Windows FileSystemObject.

Scope: This article targets Windows-based panels running WinCC RT Advanced and PC-based RT Advanced stations configured in TIA Portal V15. The same code applies to TIA Portal V15.1, V16, and V17 with only minor adaptations because the VBScript runtime has remained compatible across these versions. For Unified Comfort Panels and WinCC Unified, refer to the corresponding Unified Scripting (JavaScript) documentation since the API surface differs.

1. Problem Overview

Capturing a screenshot of an HMI screen in WinCC Advanced is built into the runtime and exposed via the system function PrintScreen or the equivalent runtime API HMIRuntime.PrintScreen. By default, PrintScreen writes a bitmap of the active screen to the clipboard. To persist it as a file, two paths are common in the field:

  1. Configure a PDF virtual printer (e.g., Microsoft Print to PDF) as the default printer, then trigger a clipboard-to-printer sequence. The PDF printer raises a "Save Print Output As" dialog where the operator must type a name and confirm.
  2. Use an external command-line tool (e.g., NirCmd) and pass parameters that include the destination path.

Both paths force a dialog. In unattended logging, alarming, or batch-mode reporting, the dialog becomes an obstacle. The challenge is to dismiss the dialog programmatically with reliable timing using only VBScript and the Windows Script Host objects available in the WinCC VBS environment.

2. WinCC Advanced V15 Runtime Environment

WinCC Advanced V15 (TIA Portal) provides two HMI runtimes:

Runtime Host Script Engine External Object Access
RT Advanced (PC-based) Windows 7 SP1 / Windows 10 / Windows Server 2012 R2 or newer VBScript 5.8 WScript.Shell, Scripting.FileSystemObject, Scripting.Dictionary, ADODB
RT Advanced (Panel-based) Comfort Panels (TP/MP), IPCs VBScript 5.x embedded Restricted; limited Shell and FSO access

On PC-based stations, the runtime hosts a Microsoft VBScript engine that can instantiate any COM object registered on the host. This makes CreateObject("WScript.Shell") and CreateObject("Scripting.FileSystemObject") fully available. On Comfort Panels, the same functions exist but COM instantiation is restricted by the secure-runtime policy and may be blocked.

For the screenshot automation discussed here, use a PC-based RT Advanced station. Confirm your runtime configuration under Project > Runtime Settings > Services in TIA Portal.

3. The PrintScreen Mechanism

In a WinCC VBScript, the PrintScreen statement captures the active HMI screen and forwards it to the default printer configured at the runtime station. On a Windows 10 host, the default Microsoft Print to PDF device creates a PDF and opens a Save dialog named "Save Print Output As" with a file name text box and a Save button.

The key task is therefore to populate the file name field and trigger the Save button without human input. The two mechanisms for doing so are:

  • WScript.Shell.SendKeys — synthesizes keystrokes into the focused window. Requires the Save dialog to have focus and a deterministic delay before sending keys.
  • WScript.Shell.AppActivate — brings the target window to the foreground so SendKeys reaches it.

4. Why WScript.Sleep Fails in HMI Context

A common first attempt uses WScript.Sleep between the PrintScreen call and the SendKeys call:

Set Shell = CreateObject("WScript.Shell")
Shell.Sleep 10000
Shell.SendKeys "test"

On PC-based RT Advanced this approach frequently hangs. The reasons are documented in the Windows Script Host behavior and confirmed in the field:

  1. The runtime's VBScript execution context can suspend WScript.Sleep when the script is invoked from inside the HMI scheduler because the scheduler runs the script inside a STA apartment with a message pump that interacts poorly with WScript's idle wait.
  2. The default printer dialog is itself modal and processes its own message loop. If the dialog appears before Sleep completes its wait, the runtime's UI thread may not release the script until the dialog closes, which then blocks the keystroke send.
  3. The thread that invoked PrintScreen may not be the same thread that owns the dialog window, so SendKeys routed to the wrong window has no effect.

The reliable fix is to abandon Sleep in favor of a busy-loop based on DateAdd, which keeps the script's message pump responsive and avoids the suspended-wait condition. This pattern is also used in industrial VBScript deployments for similar reasons and is the recommended approach for timeouts in WinCC scripts.

5. Loop-Based Timing Pattern

Replace WScript.Sleep(N) with the following pattern, which yields the CPU back to the runtime without suspending the VBScript host:

Dim dteWait
dteWait = DateAdd("s", 5, Now())
Do Until (Now() > dteWait)
    ' optional: DoEvents for cooperative multitasking on RT Advanced
Loop

This loop polls the system clock and exits once the desired delay has elapsed. The empty loop body may be augmented with DoEvents (when available in the host) to permit the Windows message pump to dispatch queued messages while waiting. On WinCC RT Advanced, DoEvents is not always exposed; the empty loop is sufficient because the host's own scheduler yields at each iteration on modern VBScript engines.

6. Complete Working Script

The following script captures the active screen, names the file "test_file.pdf", and renames it to a known location. Paste this into a WinCC VBScript action triggered by a button press or a scheduled event.

' ------------------------------------------------------------------
' WinCC Advanced V15 - Automatic HMI Screenshot Capture
' Trigger: Button event or scheduled task
' Requires: Default printer = Microsoft Print to PDF
' ------------------------------------------------------------------

' Step 1: Trigger the print screen -> goes to default printer
PrintScreen

' Step 2: Wait for the Save Print Output As dialog to appear
Dim dteWait
dteWait = DateAdd("s", 5, Now())
Do Until (Now() > dteWait)
Loop

' Step 3: Type the desired file name and confirm Save
Dim Shell
Set Shell = CreateObject("WScript.Shell")

Shell.SendKeys "test_file"
dteWait = DateAdd("s", 2, Now())
Do Until (Now() > dteWait)
Loop

Shell.SendKeys "{ENTER}"
dteWait = DateAdd("s", 2, Now())
Do Until (Now() > dteWait)
Loop

' Step 4: Rename the resulting PDF to a deterministic location
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

Dim strSource, strDest
strSource = "C:\Users\Public\Documents\test_file.pdf"
strDest   = "C:\HMI_Archive\Screenshot_001.pdf"

If fso.FileExists(strSource) Then
    If fso.FolderExists("C:\HMI_Archive") = False Then
        fso.CreateFolder "C:\HMI_Archive"
    End If
    fso.MoveFile strSource, strDest
End If

Set fso = Nothing
Set Shell = Nothing
Critical typo to avoid: The original implementation in the user's source used SendKeys("{ENTER]") with a closing square bracket. The correct VBScript syntax for the Enter key is SendKeys "{ENTER}" with curly braces and a closing curly brace. The square-bracket typo causes the SendKeys call to silently fail or throw an error.

7. Parameter Reference

Element Type Default Recommended Notes
Initial wait (dialog open) Integer seconds 5 3 - 5 s Tune to your host's print queue latency
Filename keystroke wait Integer seconds 2 1 - 2 s Allow text input to register
Save keystroke wait Integer seconds 2 1 - 3 s Wait for file to be written before FSO access
Source PDF path String User profile Documents C:\HMI_Archive\Temp\ Use a deterministic folder, not the user profile
Destination PDF path String n/a C:\HMI_Archive\ Use a network share for remote retrieval
Filename prefix String "test_file" Timestamp-based Use FormatDateTime(Now, ...) to avoid collisions

8. Timestamped File Names

Static names like test_file.pdf overwrite each other on repeated captures. Build dynamic names to preserve history:

Dim strName, dteStamp
dteStamp = Now
strName = "HMI_" & _
          Year(dteStamp) & _
          Right("0" & Month(dteStamp), 2) & _
          Right("0" & Day(dteStamp), 2) & "_" & _
          Right("0" & Hour(dteStamp), 2) & _
          Right("0" & Minute(dteStamp), 2) & _
          Right("0" & Second(dteStamp), 2) & ".pdf"

Shell.SendKeys strName

The resulting name looks like HMI_20260215_143012.pdf and is safe for sequential captures within a day.

9. Alternative Path: System Function StartProgram

WinCC Advanced exposes a built-in system function StartProgram that launches an external executable from a configured event. This avoids VBScript-driven dialogs entirely if an external tool is used. The Siemens documentation for system functions is part of the TIA Portal Help under WinCC Advanced > Working with HMI devices > System functions.

Field Value
Program name C:\Tools\nircmd.exe
Program parameters savescreenshot "C:\HMI_Archive\screen.png"
Display mode Hidden (so no console window flashes)
Execution On button press or scheduler tick

StartProgram requires the executable to support a non-interactive command-line interface. NirCmd by Nir Sofer is a widely used free utility with a savescreenshot command that takes a full-screen capture and writes it directly to a file path, with no dialog.

10. Comparative Method Selection

Criterion VBScript + SendKeys StartProgram + NirCmd VBScript + PowerShell
External dependency None nircmd.exe PowerShell 5.1+
Dialog suppression Timing-dependent Native Native
File format PDF (via PDF printer) PNG / BMP / JPG PNG (default)
Reliability under load Moderate High High
Implementation effort Low Low Medium
Maintenance burden High (timing tuning) Low Low
Recommended for production Prototype only Yes Yes (Win 10+ only)

11. PowerShell Alternative

For stations on Windows 10 or Windows Server 2016 and newer, you can launch a PowerShell capture from VBScript via WScript.Shell.Run and avoid any dialog:

Dim Shell
Set Shell = CreateObject("WScript.Shell")
Shell.Run "powershell -NoProfile -Command """Add-Type -AssemblyName System.Windows.Forms; """"" _
    & "[System.Windows.Forms.Screen]::PrimaryScreen.Bounds | " _
    & "ForEach-Object { $b = $_; $bmp = New-Object System.Drawing.Bitmap $b.Width, $b.Height; " _
    & "$g = [System.Drawing.Graphics]::FromImage($bmp); $g.CopyFromScreen($b.Location, [System.Drawing.Point]::Empty, $b.Size); " _
    & "$bmp.Save('C:\HMI_Archive\screen.png'); $g.Dispose(); $bmp.Dispose() }""""", 0, True

The trailing 0 argument hides the PowerShell window and True makes the call synchronous so subsequent code can rely on the file being written.

12. Configuration of the PDF Printer

For the SendKeys path, the Windows default printer must be Microsoft Print to PDF before the runtime starts. Configure this in the Windows Settings > Printers & Scanners menu or by setting the default printer at runtime via PowerShell:

(Get-WmiObject -Class Win32_Printer -Filter "Name='Microsoft Print to PDF'").SetDefaultPrinter()

Validate by opening Notepad, pressing Ctrl+P, and confirming that the default selected printer is Microsoft Print to PDF. If a different printer is selected, the captured bitmap will be sent there instead and the Save dialog will never appear.

Group Policy conflict: In locked-down environments, the default printer may be re-set by Windows at each user logon. Verify the printer persists across reboots and logon sessions. If not, set it via a logon script or use the StartProgram method to bypass the printer entirely.

13. File System Hardening

Once the PDF is written to a deterministic source path, move or copy it to a network archive. Recommended setup:

  1. Create C:\HMI_Archive\Temp\ on the runtime PC. Set NTFS permissions so the runtime user (typically SYSTEM or the configured RT Advanced user) has read/write/delete.
  2. Mount a network share at \\fileserver\HMIArchive\ with write access for the runtime user.
  3. Use fso.CopyFile rather than MoveFile if the source must be retained for diagnostic purposes.
  4. Implement a 24-hour cleanup: schedule a Windows Task Manager task that deletes files in the Temp folder older than 24 hours.

14. Error Handling

Wrap the sequence in an On Error Resume Next block with a logging tail. WinCC VBScript supports inline error handling:

On Error Resume Next

PrintScreen

Dim dteWait
dteWait = DateAdd("s", 5, Now())
Do Until (Now() > dteWait)
Loop

Dim Shell
Set Shell = CreateObject("WScript.Shell")
If Err.Number <> 0 Then
    HMIRuntime.Trace "Shell create failed: " & Err.Description
    Err.Clear
    Exit Sub
End If

Shell.SendKeys strName
' ... rest of script ...

If Err.Number <> 0 Then
    HMIRuntime.Trace "MoveFile failed: " & Err.Description
    Err.Clear
End If

On Error Goto 0

HMIRuntime.Trace writes to the WinCC diagnostic window, accessible via the Trace Viewer applet or the HMI's diagnostic page. Use this output for offline analysis when the script fails silently.

15. Common Failure Modes and Fixes

Symptom Likely Cause Fix
Script stops at CreateObject("WScript.Shell") STA threading or COM security blocking instantiation Move from panel runtime to PC-based runtime; verify DCOM launch permissions
SendKeys writes nothing to text box Dialog not focused, or wrong window targeted Add Shell.AppActivate "Save Print Output As" before SendKeys
File ends up with literal "test_file" plus junk characters Typing happens before text box is focused Increase initial wait from 5 s to 8 s on slower hosts
MoveFile throws "Path not found" Source path differs from PDF printer's save location Check Documents folder for the user account under which the runtime runs
Capture only captures black screen Runtime not in foreground, or session is locked Disable screen lock, ensure interactive logon, ensure no RDP session is disconnected
Capture includes cursor Cursor visible during print Move cursor to a corner, or use sendscreenshot via NirCmd which excludes the cursor
Two captures collide and one is overwritten Static file name Use timestamped names per Section 8
Runtime service cannot reach network share RT Advanced running as SYSTEM lacks credentials Configure RT Advanced to run as a domain user with share write access

16. Verification Procedure

Validate the script end-to-end with the following steps before deploying to production:

  1. Open TIA Portal V15 and load the project. Confirm the HMI device target is a PC-based runtime.
  2. In the project tree, navigate to HMI Tags > [your trigger tag] or insert a button configured with the OnClick event tied to your VBScript function.
  3. Compile the project and start RT Advanced on the development PC.
  4. Click the trigger button.
  5. Verify within 10 seconds that a PDF file appears in C:\HMI_Archive\ with the expected timestamped name.
  6. Open the PDF and confirm the captured screen matches the active HMI screen at trigger time.
  7. Repeat five times consecutively to confirm no race conditions or collisions occur.
  8. Check HMIRuntime.Trace output for any logged errors.
  9. Restart the runtime and confirm the default printer is still Microsoft Print to PDF.

17. Scheduler-Based Periodic Capture

To capture screenshots on a fixed schedule, configure a WinCC scheduler:

  1. In the project tree, open Schedules under the HMI device.
  2. Add a new event with the desired recurrence (e.g., every 5 minutes).
  3. Attach your VBScript function to the event.
  4. Compile and download to the runtime.

For sub-minute intervals, multiple events can be configured. Keep in mind that each capture writes a PDF and triggers FSO activity, which on a busy runtime can compete for disk I/O. A 30-second or longer interval is typical.

18. Performance and Footprint

Operation Typical Duration CPU Impact
PrintScreen trigger < 100 ms Negligible
PDF rendering by Microsoft Print to PDF 1 - 3 s Low
Dialog appearance to keyboard focus 0.5 - 2 s None
FSO MoveFile < 50 ms (local) / 100 - 500 ms (network) Negligible
Total elapsed per capture 8 - 12 s Brief spike
PDF size (single HMI screen) 50 - 500 kB n/a

19. Security Considerations

  • RT Advanced scripts run with the privileges of the runtime user. Configure this user to have only the minimum permissions needed: write to the archive folder, access the configured network share, and read the default printer configuration.
  • Do not embed credentials in VBScript. Use Windows integrated authentication on the share.
  • Disable any anti-virus real-time scan on the Temp archive folder to avoid file-lock collisions during FSO operations.
  • Audit folder access by enabling NTFS auditing on C:\HMI_Archive\.

20. Migration to WinCC Unified (Optional)

For projects migrating to WinCC Unified (TIA Portal V17+), the VBScript approach is replaced by JavaScript. The Unified scripting model exposes HMIRuntime.Screens and a browser-based canvas capture API. The Shell and FSO objects are not available; equivalent functionality is provided through the Unified Tags and Files system APIs. Plan a dedicated porting effort when migrating.

21. Reference Documentation

Consult the official Siemens documentation for TIA Portal V15 and the WinCC Advanced runtime:

22. Frequently Asked Questions

Why does my WinCC VBScript hang at CreateObject("WScript.Shell") on a Comfort Panel?

Comfort Panels run a restricted VBScript runtime that blocks instantiation of COM objects such as WScript.Shell for security. Use a PC-based RT Advanced station instead, or migrate to the StartProgram system function with a command-line screenshot tool.

What is the correct SendKeys syntax for the Enter key in WinCC VBScript?

Use Shell.SendKeys "{ENTER}" with curly braces on both sides. The closing character must be a curly brace, not a square bracket. Common typos like "{ENTER]" cause the keystroke to be silently discarded.

Can I avoid the Save dialog entirely instead of driving it with SendKeys?

Yes. Configure the runtime's default printer to a tool that writes directly to a path without a dialog (such as a commercial direct-to-PDF printer), or use the StartProgram system function with a command-line utility such as NirCmd's savescreenshot or a PowerShell one-liner. Both bypass the dialog and are more reliable for production deployments.

Where does Microsoft Print to PDF save the file by default?

On Windows 10, the default save location is the current user's Documents folder (typically C:\Users\<user>\Documents). For a runtime running as SYSTEM or a service account, this path may differ. Confirm by triggering a manual print and inspecting the resulting path before automating the move step.

How do I prevent each new screenshot from overwriting the previous file?

Use timestamped file names built from the Now() function. A common format is HMI_YYYYMMDD_HHMMSS.pdf with the date parts padded to two digits. Pass this dynamic string to the SendKeys call so the PDF printer writes to a unique file every time.

Can the screenshot script run unattended while a user is logged off?

Only if the runtime station has an active interactive session or is configured with the appropriate auto-logon and session keep-alive policy. Locked or disconnected sessions may capture a black screen. For true headless capture, use NirCmd's savescreenshot invoked via StartProgram, which works in non-interactive sessions.

Back to blog