How to get file properties in vb6? - vb6

I want to get the file properties like "Description"、"ProductName"
How to get these properties in vb6?
I've tried use FileSystemObject, but it seems like can't get the "Description" properties.
Thanks for reply.
I use code below to get the file properties.
Hope this will help others who have the same problem with me.
Private Declare Function GetFileVersionInfo Lib "Version.dll" Alias "GetFileVersionInfoA" (ByVal lptstrFilename As String, ByVal dwhandle As Long, ByVal dwlen As Long, lpData As Any) As Long
Private Declare Function GetFileVersionInfoSize Lib "Version.dll" Alias "GetFileVersionInfoSizeA" (ByVal lptstrFilename As String, lpdwHandle As Long) As Long
Private Declare Function VerQueryValue Lib "Version.dll" Alias "VerQueryValueA" (pBlock As Any, ByVal lpSubBlock As String, lplpBuffer As Any, puLen As Long) As Long
Private Declare Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" (dest As Any, ByVal Source As Long, ByVal length As Long)
Private Declare Function lstrcpy Lib "kernel32" Alias "lstrcpyA" (ByVal lpString1 As String, ByVal lpString2 As Long) As Long
Public Function GetFileInformation(ByVal fileFullPath As String) As String
Dim lDummy As Long, lSize As Long, rc As Long
Dim lVerbufferLen As Long
Dim sBuffer() As Byte
Dim lBufferLen As Long
Dim bytebuffer(255) As Byte
Dim Lang_Charset_String As String
Dim HexNumber As Long
Dim buffer As String
Dim lVerPointer As Long
Dim ProdName As String
GetFileInformation = ""
buffer = String(255, 0)
lBufferLen = GetFileVersionInfoSize(fileFullPath, lDummy)
If lBufferLen >= 1 Then
ReDim sBuffer(lBufferLen)
rc = GetFileVersionInfo(fileFullPath, 0&, lBufferLen, sBuffer(0))
If rc <> 0 Then
rc = VerQueryValue(sBuffer(0), "\VarFileInfo\Translation", lVerPointer, lBufferLen)
If rc <> 0 Then
MoveMemory bytebuffer(0), lVerPointer, lBufferLen
HexNumber = bytebuffer(2) + bytebuffer(3) * &H100 + bytebuffer(0) * &H10000 + bytebuffer(1) * &H1000000
Lang_Charset_String = Hex(HexNumber)
Do While Len(Lang_Charset_String) < 8
Lang_Charset_String = "0" & Lang_Charset_String
Loop
.sCompanyName = GetStringValue("\StringFileInfo\" & Lang_Charset_String & "\" & "CompanyName", lVerPointer, lBufferLen, sBuffer)
.sFileDescription = GetStringValue("\StringFileInfo\" & Lang_Charset_String & "\" & "FileDescription", lVerPointer, lBufferLen, sBuffer)
.sFileVersion = GetStringValue("\StringFileInfo\" & Lang_Charset_String & "\" & "FileVersion", lVerPointer, lBufferLen, sBuffer)
.sInternalName = GetStringValue("\StringFileInfo\" & Lang_Charset_String & "\" & "InternalName", lVerPointer, lBufferLen, sBuffer)
.sLegalCopyright = GetStringValue("\StringFileInfo\" & Lang_Charset_String & "\" & "LegalCopyright", lVerPointer, lBufferLen, sBuffer)
.sOriginalFileName = GetStringValue("\StringFileInfo\" & Lang_Charset_String & "\" & "OriginalFileName", lVerPointer, lBufferLen, sBuffer)
.sProductName = GetStringValue("\StringFileInfo\" & Lang_Charset_String & "\" & "ProductName", lVerPointer, lBufferLen, sBuffer)
.sProductVersion = GetStringValue("\StringFileInfo\" & Lang_Charset_String & "\" & "ProductVersion", lVerPointer, lBufferLen, sBuffer)
GetFileInformation = GetStringValue("\StringFileInfo\" & Lang_Charset_String & "\" & "ProductName", lVerPointer, lBufferLen, sBuffer)
End If
End If
End If
End Function
Private Function GetStringValue(ByRef searchString As String, ByVal lVerPointer As Long, ByVal lBufferLen As Long, ByRef sBuffer() As Byte) As String
Dim buffer As String
Dim strTemp As String
Dim rc As Long
GetStringValue = ""
buffer = String(255, 0)
rc = VerQueryValue(sBuffer(0), searchString, lVerPointer, lBufferLen)
If rc <> 0 Then
lstrcpy buffer, lVerPointer
GetStringValue = Mid$(buffer, 1, InStr(buffer, Chr(0)) - 1)
End If
End Function

This requires Windows 2000 or later. I'm not sure the property system had been extended to this level of coverage in older OSs like Windows XP yet so you may need Windows Vista or later:
Option Explicit
Private Sub Form_Load()
Const ssfDESKTOP = 0
Const COL2 = 20
Show
With CommonDialog1
.DialogTitle = "Select a PE file"
.CancelError = True
.Flags = cdlOFNExplorer _
Or cdlOFNFileMustExist _
Or cdlOFNPathMustExist _
Or cdlOFNLongNames _
Or cdlOFNShareAware
.InitDir = App.Path
.Filter = "Programs (*.exe)|*.exe|Libraries (*.dll;*.ocx)|*.dll;*.ocx"
On Error Resume Next
.ShowOpen
If Err Then
Unload Me
Exit Sub
End If
On Error GoTo 0
End With
With CreateObject("Shell.Application")
With .NameSpace(ssfDESKTOP).ParseName(CommonDialog1.FileName)
AutoRedraw = True
Print "Name:"; Tab(COL2);
Print .Name
Print "Product Name:"; Tab(COL2);
Print .ExtendedProperty("System.Software.ProductName")
Print "Size:"; Tab(COL2);
Print Format$(.Size, "#,##0"); " bytes"
Print "File Version:"; Tab(COL2);
Print .ExtendedProperty("System.FileVersion")
Print "Date Accessed:"; Tab(COL2);
Print .ExtendedProperty("System.DateAccessed")
Print "Date Created:"; Tab(COL2);
Print .ExtendedProperty("System.DateCreated")
Print "Date Modified:"; Tab(COL2);
Print .ExtendedProperty("System.DateModified")
Print "Company:"; Tab(COL2);
Print .ExtendedProperty("System.Company")
Print "Copyright:"; Tab(COL2);
Print .ExtendedProperty("System.Copyright")
Print "File Description:"; Tab(COL2);
Print .ExtendedProperty("System.FileDescription")
End With
End With
End Sub
See propkey.h in a recent Windows SDK for the definitions of the available extended properties.

Related

String Search in files and populate results as Drop Down list or Combo Box in VB6(Visual basic)

I want to store string variable from the user and then I want to search that string in files of a specific folder. I want to match the stored string within each file. If I find a match to the string, I want a list box or Combo box to be populated with the name of the files. I am working in Visual basic (VB6).
I tried Some VB.net code like getfiles() but those are not working in VB6.
If you index the target folder you can use Windows Search:
Option Explicit
Private Const INDEXED_FOLDER_PATH As String = _
"C:\Program Files\Windows Kits\10\Include\10.0.16299.0\um"
Private WithEvents CN As ADODB.Connection
Private Sub CN_ExecuteComplete( _
ByVal RecordsAffected As Long, _
ByVal pError As ADODB.Error, _
ByRef adStatus As ADODB.EventStatusEnum, _
ByVal pCommand As ADODB.Command, _
ByVal pRecordset As ADODB.Recordset, _
ByVal pConnection As ADODB.Connection)
If adStatus <> adStatusOK Then
MousePointer = vbDefault
'Sadly this DSO is lazy about providing a Description here, so it
'will often be empty along with an empty Errors collection.
MsgBox "Error " & pError.Number & vbNewLine _
& vbNewLine _
& pError.Description
Else
With pRecordset
If .EOF Then
List1.AddItem "*no hits*"
Else
Do Until .EOF
List1.AddItem .Fields(0).Value
.MoveNext
Loop
End If
.Close
End With
MousePointer = vbDefault
End If
Text1.SetFocus
End Sub
Private Sub Command1_Click()
MousePointer = vbHourglass
List1.Clear
'We are doing an async request here because depending on what we are asking
'for it might take a few seconds:
CN.Execute "SELECT System.ItemNameDisplay" _
& " FROM SystemIndex" _
& " WHERE DIRECTORY='file:" & Replace$(INDEXED_FOLDER_PATH, "\", "/") & "'" _
& " AND FREETEXT('" & Text1.Text & "')", _
, _
adCmdText Or adAsyncExecute
End Sub
Private Sub Form_Load()
Set CN = New ADODB.Connection
CN.Open "Provider=Search.CollatorDSO;Extended Properties='Application=Windows'"
End Sub
Private Sub Form_Unload(Cancel As Integer)
CN.Close
End Sub
More info: Querying the Index with Windows Search SQL Syntax

Move macro forward when caught/stuck in process

I have written a macro that uses the paping.exe program to cycle through a list of device IP addresses by sending pings and recording their return values. While the macro works as intended for the majority of the time, there are spare moments when the ping command appears to be stuck or caught up and stops moving forward. This causes me to have to manually break the execution and start the process over.
From a more broad perspective, is there a way to handle this runtime error. My thought was to break the list of devices into groupings, and if the program becomes stuck, I could tell the macro to move forward to the next grouping. While just an idle idea, I wanted to reach out to the community for advice, tips and ideas on ways I could more eloquently handle this issue. The list of devices that I am pinging is set to grow in time as well.
Public Sub getPingStatusCode(IPvalue As String, portValue As String)
ret = WshShell.Run("C:\Users\*******\paping.exe " & IPvalue & " -p " & portValue & " -c " & pingCount & " -t " & pingTime, 0, True) 'CHANGEEEEEEE
totalCounter = totalCounter + 1
Select Case ret
Case 0: strResult = "Connected"
Case 1: strResult = "Fail"
Case 11001: strResult = "Buffer too small"
Case 11002: strResult = "Destination net unreachable"
Case 11003: strResult = "Destination host unreachable"
Case 11004: strResult = "Destination protocol unreachable"
Case 11005: strResult = "Destination port unreachable"
Case 11006: strResult = "No resources"
Case 11007: strResult = "Bad option"
Case 11008: strResult = "Hardware error"
Case 11009: strResult = "Packet too big"
Case 11010: strResult = "Request timed out"
Case 11011: strResult = "Bad request"
Case 11012: strResult = "Bad route"
Case 11013: strResult = "TTL expired transit"
Case 11014: strResult = "TTL expired reassembly"
Case 11015: strResult = "Parameter problem"
Case 11016: strResult = "Source quench"
Case 11017: strResult = "Option too big"
Case 11018: strResult = "Bad destination"
Case 11032: strResult = "Negotiating IPSEC"
Case 11050: strResult = "General failure"
Case Else: strResult = "Unknown host"
End Select
'if statement on return value for bolding and font color
'and counters
If ret = 0 Then 'CONNECTED
With pingSheet.Cells(i, 4)
.Value = strResult
End With
totalOn = totalOn + 1
onOff = 1
'set the rawDataSheet value to connected status...assumes that the sheet starts with all rawdata values as "connected"
rawDataSheet.Cells(4, i).Value = strResult
ElseIf ret = 1 Then 'FAILED
With pingSheet.Cells(i, 4)
.Value = strResult
.Font.Color = vbRed
.Font.bold = True
End With
failCounter = failCounter + 1
onOff = 0
'give RawData sheet a "down since" date value
If rawDataSheet.Cells(4, i).Value = "Connected" Then
rawDataSheet.Cells(4, i).Value = Now
End If
''''''''''''''
pdfDeviceDump
Else
With pingSheet.Cells(i, 4)
.Value = strResult
.Font.Color = vbRed
.Font.bold = True
End With
failCounter = failCounter + 1
onOff = 0
End If
End Sub
I could not get paping.exe to run on my machine so I wrote some code using ping.exe instead.
In principle one can shell out and redirect output to file and then pick up the file later when finished. We use Windows API calls to wait for a process to finish.
Option Explicit
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32.dll" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Const INFINITE = &HFFFF
Private Const PROCESS_ALL_ACCESS = &H1F0FFF
Sub TestShellAndRedirectPingToFile()
Dim vIPAddresses As Variant
vIPAddresses = Array("bbc.co.uk", "wikipedia.org", "cnn.com")
Dim dicFilesToPickUp As Scripting.Dictionary
Set dicFilesToPickUp = ShellAndRedirectPingToFile(vIPAddresses)
Dim vKeyLoop As Variant
For Each vKeyLoop In dicFilesToPickUp.Keys
Dim lPID As Long
lPID = dicFilesToPickUp.Item(vKeyLoop)
Dim hProc As Long
hProc = OpenProcess(PROCESS_ALL_ACCESS, 0&, lPID)
Debug.Print "Waiting on " & vKeyLoop & " (" & lPID & ")"
WaitForSingleObject hProc, INFINITE
CloseHandle hProc '* be nice and close handles
Next
Debug.Print "Done! Files ready to read."
End Sub
Function ShellAndRedirectPingToFile(ByVal vIPAddresses As Variant) As Scripting.Dictionary
Dim dicFilesToPickUp As Scripting.Dictionary
Set dicFilesToPickUp = New Scripting.Dictionary
Dim sTempFolder As String
sTempFolder = Environ$("TEMP")
If Right$(sTempFolder, 1) <> "\" Then sTempFolder = sTempFolder & "\"
Dim vAddressLoop As Variant
For Each vAddressLoop In vIPAddresses
Dim sTempFile As String
sTempFile = sTempFolder & vAddressLoop & ".txt"
Dim sCmd As String
sCmd = Environ$("comspec") & " /S /C ping.exe " & vAddressLoop & " > " & sTempFile
Dim lPID As Long
lPID = VBA.Shell(sCmd)
dicFilesToPickUp.Add sTempFile, lPID
Next
Set ShellAndRedirectPingToFile = dicFilesToPickUp
End Function

VBS: How to get the filesize with special FileDialog?

Function FileDialog()
Dim oExec1: Set oExec1=CreateObject("WScript.Shell").Exec( "mshta.exe ""about:" & "<" & "input type=file id=FILE" & ">" & "<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>""" )
Dim sPathfile: sPathfile = oExec1.StdOut.ReadAll
sPathfile = Replace( sPathfile, vbCRLF, "" )
FileDialog = sPathfile
End Function
change to:
Function FileDialog(filesize)
filesize will return the value of bytes of the selected file
Read Function Statement (VBScript) document and pass the argument by reference as follows:
option explicit
On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim nFileSize: nFileSize = -1 ' for test that `byRef` declaration works
strResult = strResult & vbNewLine & FileDialog( nFileSize)
strResult = strResult & vbNewLine & nFileSize
Wscript.Echo strResult
Wscript.Quit
Function FileDialog( byRef xSize)
Dim oExec1
Set oExec1=CreateObject("WScript.Shell").Exec( "mshta.exe ""about:" & "<" & "input type=file id=FILE" & ">" & "<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>""" )
Dim sPathfile: sPathfile = oExec1.StdOut.ReadAll
sPathfile = Replace( sPathfile, vbCRLF, "" )
If Len(sPathfile) > 0 Then
With CreateObject("Scripting.FileSystemObject").GetFile(sPathfile)
xSize = .Size ' the size, in bytes, of the specified file
End With
Else
' No file chosen: red "×" or Esc or Cancel pressed
xSize = 0
End If
FileDialog = sPathfile
End Function
Read ByRef and ByVal Parameters article as well.

Function returns empty result

I am getting empty msgBox when i call the function . Have a look on code as bellow
Public Function Custom(ByVal TableName As String, _
ByVal EmployeeCode As String, ByVal FieldName As String, ByVal DataToCheck As String, _
Optional ByVal CodeFieldName As String = Empty, Optional ByVal CodeFieldValue As String = Empty) As Boolean
Dim lstrSQL1 As String
Dim lrsTemp1 As ADODB.Recordset
lstrSQL1 = " Select " & FieldName & " from " & TableName & " Where ID_CARD_NO =" & DataToCheck & ""
'MsgBox (lstrSQL1)
If Len(Trim$(CodeFieldName)) <> 0 And Len(Trim$(CodeFieldValue)) <> 0 Then
lstrSQL1 = lstrSQL1 & " AND " & CodeFieldName & " <> '" & CodeFieldValue & "'"
End If
Set lrsTemp1 = cObjDBConn.ExecuteSQL(lstrSQL1)
If lrsTemp1 Is Nothing Then
Custom = False
ElseIf Not (lrsTemp1.BOF And lrsTemp1.EOF) Then
Custom = True
ElseIf lrsTemp1.RecordCount = 0 Then
Custom = False
Else
Custom = False
End If
If lrsTemp1.State = adStateOpen Then lrsTemp1.Close
Set lrsTemp1 = Nothing
Exit Function
ErrorHandle:
Custom = False
End Function
The calling code is here:
If gobjValidation.Custom(fstrTableName, gEmployeeCode, "EMPLOYEE_CODE", _
Trim$(TxtIDcardNo.text)) = True Then
MsgBox (gEmployeeCode)
Call MessageBox("This ID Number is already existing for another employee. Cannot enter duplicate number!Using By Employee Code:" & gEmployerCode & " ", OKOnly, Information, DefaultButton1, Me.Caption)
sstInformationTab.Tab = 0
As #Arvo said, you need to make youre EmployeeCode variable ByRef, then assign it a value in your function Custom()
Public Function Custom(ByVal TableName As String, _
**ByRef EmployeeCode As String**, ByVal FieldName As String, ByVal DataToCheck As String, _
Optional ByVal CodeFieldName As String = Empty, Optional ByVal CodeFieldValue As String = Empty) As Boolean
Dim lstrSQL1 As String
Dim lrsTemp1 As ADODB.Recordset
lstrSQL1 = " Select " & FieldName & " from " & TableName & " Where ID_CARD_NO =" & DataToCheck & ""
'MsgBox (lstrSQL1)
If Len(Trim$(CodeFieldName)) <> 0 And Len(Trim$(CodeFieldValue)) <> 0 Then
lstrSQL1 = lstrSQL1 & " AND " & CodeFieldName & " <> '" & CodeFieldValue & "'"
End If
Set lrsTemp1 = cObjDBConn.ExecuteSQL(lstrSQL1)
If lrsTemp1 Is Nothing Then
Custom = False
ElseIf Not (lrsTemp1.BOF And lrsTemp1.EOF) Then
Custom = True
**lrsTemp1.MoveFirst**
**EmployeeCode = lrsTemp1.Fields("EMPLOYEE_CODE")**
ElseIf lrsTemp1.RecordCount = 0 Then
Custom = False
Else
Custom = False
End If
If lrsTemp1.State = adStateOpen Then lrsTemp1.Close
Set lrsTemp1 = Nothing
Exit Function
ErrorHandle:
Custom = False
End Function
The double asterisks are just to highlight the changes I made to your original code.

Need Visual Studio macro to add banner to all C# files

Can someone post a Visual Studio macro which goes through all C# source files in a project and adds a file banner? Extra credit if it works for any type of source file (.cs, .xaml, etc).
Here you go, I provide an example for .cs and .vb but shouldn't be hard for you to adjust it to your other file type needs: Edited to recursively add header to sub-folders
Sub IterateFiles()
Dim solution As Solution = DTE.Solution
For Each prj As Project In solution.Projects
IterateProjectFiles(prj.ProjectItems)
Next
End Sub
Private Sub IterateProjectFiles(ByVal prjItms As ProjectItems)
For Each file As ProjectItem In prjItms
If file.SubProject IsNot Nothing Then
AddHeaderToItem(file)
IterateProjectFiles(file.ProjectItems)
ElseIf file.ProjectItems IsNot Nothing AndAlso file.ProjectItems.Count > 0 Then
AddHeaderToItem(file)
IterateProjectFiles(file.ProjectItems)
Else
AddHeaderToItem(file)
End If
Next
End Sub
Private Sub AddHeaderToItem(ByVal file As ProjectItem)
DTE.ExecuteCommand("View.SolutionExplorer")
If file.Name.EndsWith(".cs") OrElse file.Name.EndsWith(".vb") Then
file.Open()
file.Document.Activate()
AddHeader()
file.Document.Save()
file.Document.Close()
End If
End Sub
Private Sub AddHeader()
Dim cmtHeader As String = "{0} First Line"
Dim cmtCopyright As String = "{0} Copyright 2008"
Dim cmtFooter As String = "{0} Footer Line"
Dim cmt As String
Select Case DTE.ActiveDocument.Language
Case "CSharp"
cmt = "//"
Case "Basic"
cmt = "'"
End Select
DTE.UndoContext.Open("Header Comment")
Dim ts As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection)
ts.StartOfDocument()
ts.Text = String.Format(cmtHeader, cmt)
ts.NewLine()
ts.Text = String.Format(cmtCopyright, cmt)
ts.NewLine()
ts.Text = String.Format(cmtFooter, cmt)
ts.NewLine()
DTE.UndoContext.Close()
End Sub
Visual Studio macro to add file headers
Here is the jist of it. No, I have not debugged this, that is an excercise for the reader. And, this is done off the top of my head. (Except the File commenter...That's a real Macro that I use).
function CommentAllFiles
option explicit
Dim ActiveProjectFullName
Dim dte80 As EnvDTE80.Solution2
ActiveProjectFullName = dte80.Projects.Item(0).FullName
If ActiveProjectFullName = "" Then
MsgBox("No project loaded!")
Exit Sub
End If
Err.Number = 0
doc.Open(ActiveProjectFullName, "Text", True)
If Err.Number <> 0 Then
MsgBox("Open " + ActiveProjectFullName + " failed: " & Hex(Err.Number))
Exit Sub
End If
ActiveDocument.Goto(1, 1, vsMovementOptions.vsMovementOptionsMove)
' Build search string
Dim SearchString
Dim vsFindOptionsValue As Integer
SearchString = "^SOURCE=.*" + dn + "$"
while ActiveDocument.Selection.FindText(SearchString, vsFindOptions.vsFindOptionsFromStart + vsFindOptions.vsFindOptionsRegularExpression)
Dim TheFile
TheFile = ActiveDocument.Selection.Text
TheFile = Mid(TheFile, 8)
doc.Open(TheFile)
wend
ActiveDocument.Close()
end function
Tried and true "Flower Box" adder:
Function IsClassDef()
Dim ColNum
Dim LineNum
Dim sText
sText = ActiveDocument.Selection.ToString()
If sText = "" Then
'ActiveDocument.Selection.WordRight(dsExtend)
'sText = ActiveDocument.Selection
'sText = ucase(trim(sText))
End If
If (sText = "CLASS") Then
IsClassDef = True
Else
IsClassDef = False
End If
End Function
Sub AddCommentBlock()
'DESCRIPTION: Add Commecnt block to header, CPP files and Class Defs
AddCPPFileDesc()
End Sub
Sub AddCPPFileDesc()
'DESCRIPTION: Add File desc block to the top of a CPP file
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
Dim bOk, sExt, IsCpp, IsHdr, sHeader, IsCSharp
bOk = True
IsCpp = False
IsCSharp = False
If ActiveDocument.Selection.CurrentLine > 10 Then
If MsgBox("You are not at the top of the file. Are you sure you want to continue?", vbYesNo + vbDefaultButton2) = vbNo Then
bOk = False
End If
End If
If (bOk) Then
sExt = ucase(right(ActiveDocument.Name, 4))
IsCpp = sExt = ".CPP"
IsHdr = Right(sExt, 2) = ".H"
IsCSharp = sExt = ".CS"
If (IsCpp) Then
sHeader = left(ActiveDocument.Name, len(ActiveDocument.Name) - 3) + "h"
FileDescTopBlock(1)
editPoint.Insert("#include " + Chr(34) + "StdAfx.h" + Chr(34) + vbLf)
editPoint.Insert("#include " + Chr(34) + sHeader + Chr(34) + vbLf)
ElseIf (IsCSharp) Then
FileDescTopBlock(1)
Else
If IsHdr Then
'If IsCLassDef() Then
'AddClassDef()
'Else
AddHeaderFileDesc()
'End If
Else
FileDescTopBlock(1)
End If
End If
End If
End Sub
Sub AddHeaderFileDesc()
FileDescTopBlock(0)
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
editPoint.Insert("#pragma once" + vbLf)
End Sub
Sub FileDescTopBlock(ByVal HasRevHistory)
'DESCRIPTION: Add File desc block to the top of a CPP file
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
ActiveDocument.Selection.EndOfLine()
Dim sComment
sComment = ActiveDocument.Selection.ToString()
If Left(sComment, 2) = "//" Then
ActiveDocument.Selection.Delete()
sComment = LTrim(Mid(sComment, 3))
Else
sComment = ""
End If
Dim sLineBreak
Dim sFileName
Dim sBlock
sLineBreak = "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"
sFileName = ActiveDocument.Name
ActiveDocument.Selection.StartOfDocument()
sBlock = sLineBreak & vbLf & _
"// File : " & sFileName & vbLf & _
"// Author : Larry Frieson" & vbLf & _
"// Desc : " & sComment & vbLf & _
"// Date : " & CStr(Now.Date()) & vbLf & _
"//" & vbLf & _
"// Copyright © 20" + Right(CStr(Now.Year.ToString()), 2) + " MLinks Technologies. All rights reserved" + vbLf
If (HasRevHistory > 0) Then
sBlock = sBlock & _
"//" & vbLf & _
"// Revision History: " & vbLf & _
"// " & CStr(Now) & " created." & vbLf & _
"// " & vbLf
End If
sBlock = sBlock + sLineBreak + vbLf
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
editPoint.Insert(sBlock)
End Sub
Hope this helps, or at least gives you some ideas. Again, I didn't test/debug the "source file looper", I figure you can handle that.
Larry

Resources