在Windows保存文件对话框中设置文件的名称

时间:2014-09-19 01:54:30

标签: windows winapi savefiledialog

下面是一个更新的示例,其中通过Excel(vba),子打开记事本,添加文本,然后提示输出文件名。它的工作原理除了将文件名从vba代码传递到Windows Save File对话框外。

Option Explicit
  Private Declare Function AllowSetForegroundWindow Lib "user32.dll" (ByVal dwProcessId As Long) As Long
  Private Declare Function BringWindowToTop Lib "user32" (ByVal lngHWnd As Long) As Long
  Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpszClass As String, ByVal lpszTitle As String) As Long
  Private Declare Function LockSetForegroundWindow Lib "user32.dll" (ByVal uLockCode As Long) As Long
  Private Declare Function SendMessageString Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
  Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
  Private Declare Sub keybd_event Lib "user32.dll" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

  Private Const WM_SETTEXT As Long = &HC
  Private Const LSFW_LOCK = 1
  Private Const VK_CONTROL = &H11    '0x11
  Private Const VK_S = &H53      '0x53

Sub WriteToNotepad()
  Dim hwndNotepad&, hwndTextbox&, hwndSaveAs&, hwndSaveLocation, hwndFileName&, Retval

ResumeHere:
' Start "Notepad"
  Retval = Shell("C:\Windows\System32\NotePad.exe", 4)

' Identify handle for "Notepad" window
  hwndNotepad = FindWindowEx(0, 0, "Notepad", vbNullString)
  hwndTextbox = FindWindowEx(hwndSaveAs, 0, "Edit", vbNullString)

' Write message
  SendMessageString hwndTextbox, WM_SETTEXT, 0, "My message goes here"

' Lock the window for futher input
  BringWindowToTop (hwndNotepad)
  AllowSetForegroundWindow (hwndNotepad)
  SetForegroundWindow (hwndNotepad)
  LockSetForegroundWindow (LSFW_LOCK)

' Show Save As dialog box
 'Press Ctrl key down, but don't release
  keybd_event VK_CONTROL, 0, 0, 0
 'Press the letter "S" then release
  keybd_event VK_S, 0, 0, 0
  keybd_event VK_S, 0, 2, 0
 'Release the Alt key
  keybd_event VK_CONTROL, 0, 2, 0

' Find SaveAs window before continuing
  hwndSaveAs = FindWindowEx(0, 0, "#32770", vbNullString)
  hwndFileName = FindWindowEx(hwndSaveAs, 0, "Edit", vbNullString)

' Write file name
  SendMessageString hwndFileName, WM_SETTEXT, 0, "Testing file.txt"

End Sub

1 个答案:

答案 0 :(得分:2)

嗯,你肯定不是通过合成击键来做到的。在“保存”(或“打开”)对话框中预填文件名字段的正确方法是将所需的字符串放在OPENFILENAME structurelpstrFile成员中,并将其传递给GetSaveFileName function

当用户关闭对话框时,该字段将使用所选的文件名和路径进行更新。