Private Sub btnCreateTreeData(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateTreeData.Click
'create buffer for storing string data
Dim buffer As New System.Text.StringBuilder
'loop through each of the treeview's root nodes
For Each rootNode As TreeNode In yourTreeView.Nodes
'call recursive function
BuildTreeString(rootNode, buffer)
Next
'write data to file
IO.File.WriteAllText("C:\treeTest.txt", buffer.ToString)
End Sub
file create successful but no tree node there
Here I get tree nods successfully
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
For Each nd As TreeNode In TreeView1.Nodes
If nd.Nodes.Count > 0 Then 'it has children, lets look at them
For Each ndChild As TreeNode In nd.Nodes
If ndChild.Nodes.Count > 0 Then 'it has children, lets look at them
Dim outputText As String = String.Concat(ndChild.Text, " ", ndChild.Nodes.Count)
For Each ndSubChild As TreeNode In ndChild.Nodes
outputText = String.Concat(outputText, " ", ndSubChild.Text)
TextBox4.Text += vbTab & outputText & vbNewLine
Next
Debug.Print(outputText)
'TextBox4.Text += vbTab & vbTab & vbTab & vbTab & outputText
End If
Next
End If
Next
End Sub
I can save it to a text file as :
Dim Save As New SaveFileDialog()
Dim myStreamWriter As System.IO.StreamWriter
Save.Filter = "Text [*.txt*]|*.txt|All Files [*.*]|*.*"
Save.CheckPathExists = True
Save.Title = "Save File"
Save.FileName = My.Computer.FileSystem.SpecialDirectories.Desktop & "\Treee Data"
Save.ShowDialog(Me)
Try
myStreamWriter = System.IO.File.AppendText(Save.FileName)
myStreamWriter.Write(TextBox4.Text)
myStreamWriter.Flush()
Catch ex As Exception
End Try
Dim ProcessProperties As New ProcessStartInfo
ProcessProperties.FileName = "notepad"
ProcessProperties.Arguments = Save.FileName
ProcessProperties.WindowStyle = ProcessWindowStyle.Maximized
Dim myProcess As Process = Process.Start(ProcessProperties)
Related
I need to make an application that needs to retrieve data from an external terminal booking device to my application, with a telnet connection and show it on the txtOutput textbox.
I am pretty new in VB and used some time to learn the basics of the language.
First I created a Standard EXE project and added the Winsock control to the form.
I made a ping-request to the IP address I wanted to have connection too and it works.
Then I want to send a command to the external device. I want the booking-terminal to give me feedback to the txtOutput for me to read.
I made the connection and as much as I can see, I do send my messages to the terminal. But I don't get any responses from it! Nothing from it is viewed on my txtOutput.
How can that be?
Here is my code:
Dim IPAddress As String
Dim PortNum As Integer
Private Sub cmdConnect_Click()
Winsock.Close
Winsock.RemoteHost = txtIpaddress.Text
IPAddress = Winsock.RemoteHost
PortNum = CStr(txtPortnr.Text)
If (Val(PortNum) > 65535) Then
Winsock.RemotePort = (Val(PortNum) - 65535)
PortNum = Winsock.RemotePort
Else
Winsock.RemotePort = Val(PortNum)
PortNum = Winsock.RemotePort
End If
Winsock.Connect
Module1.send_to_buffer ("Attempting connection to: " & IPAddress & ":" & CStr(PortNum))
Call wsock_status
End Sub
Private Sub Winsock_Connect()
Module1.send_to_buffer ("Succeeded connection to: " & IPAddress & ":" & CStr(PortNum))
txtSend.SetFocus
End Sub
Private Sub cmdSend_Click()
Dim strSData As String
Dim message_to_send As String
If (Winsock.State = 0) Then
Module1.send_to_buffer ("You need to connect first!")
txtSend.Text = ""
Else
strSData = txtSend.Text
Winsock.SendData strSData & vbCrLf
message_to_send = txtSend.Text
If (message_to_send <> "") Then
Winsock.SendData message_to_send & vbCrLf
Module1.send_to_buffer_norm (txtSend.Text)
txtSend.Text = ""
txtSend.SetFocus
Else
Module1.send_to_buffer ("Nothing to send!")
txtSend.Text = ""
txtSend.SetFocus
End If
End If
End Sub
Private Sub terminalConnector_DataArrival(ByVal bytesTotal As Long)
Dim strData As String
Winsock.GetData strData
If (Len(txtOutput.Text) = 0) Then
txtOutput.Text = strData & vbCrLf
Else
txtOutput.Text = txtOutput.Text & strData & vbCrLf
End If
End Sub
Private Sub cmdDisconnect_Click()
Dim Counter As Long
If (Winsock.State <> 0) Then
Winsock.Close
Call wsock_status
Module1.send_to_buffer ("Connection to " & IPAddress & ":" & CStr(PortNum) & " closed.")
End If
End Sub
Private Sub Winsock_Close()
Module1.send_to_buffer ("Disconnected from: " & IPAddress & ":" & CStr(PortNum))
Winsock.Close
End Sub
and Module1 code:
Public Function send_to_buffer(text_to_display As String)
If (Len(terminalConnector.txtOutput.Text) = 0) Then
terminalConnector.txtOutput.Text = "*** " & text_to_display
Else
terminalConnector.txtOutput.Text = terminalConnector.txtOutput.Text & vbCrLf & "*** " & text_to_display & vbCrLf & vbCrLf
End If
End Function
Public Function send_to_buffer_norm(text_to_input As String)
If (Len(terminalConnector.txtOutput.Text) = 0) Then
terminalConnector.txtOutput.Text = "> " & text_to_input & vbCrLf
Else
terminalConnector.txtOutput.Text = terminalConnector.txtOutput.Text & "> " & text_to_input & vbCrLf
End If
End Function
Thanks in advance
The DataArrival event is named wrongly :
in your code it is :
Private Sub terminalConnector_DataArrival(ByVal bytesTotal As Long)
but it should be the name of your winsock control :
Private Sub Winsock_DataArrival(ByVal bytesTotal As Long)
You can always select the controlname in the combobox on the left above your code window in the IDE and then select the eventname in the combobox on the right above your code window in the IDE, which will put the outlines of the event code in your code window.
Or you can double-click the control on the design window in the IDE, which will bring you to the code window and put the outlines of an event code in your code window .. you can then select the event you want in the combobox on the right above your code window
A side comment : Winsock might is not the best name for a winsock control, it is best to give it a more unique same, which could be as simple as wskConnection or wskTerminal
When you download MZ-tools you can "Review Source Code" which will show you any procedures and variables that will not be called or used in your program ... this will often give an extra hint to misnamed variables or procedures
You Send routine is wrong :
Private Sub cmdSend_Click()
Dim strSData As String
txtSend.Text = strSData
Winsock.SendData strSData
End Sub
You are showing strSata in txtSend ... while strSData is still an empty string .. after that you send the empty string via the Winsock control
you probably meant :
Private Sub cmdSend_Click()
Dim strSData As String
strSData = txtSend.Text
Winsock.SendData strSData
End Sub
Which reads txtSend.Text into your string variable, and then sends that via the Winsock control
The server probably wants some special character at the end of your string, so dont forget to add that ... usually you have to add a cariage return :
strSData = strSData & vbCr
can any one help me to add all the drives of my computer in tree view..
Dim fs As New FileSystemObject
Private Sub Form_Load()
Dim path As String
path = "D:\MP3"
TreeView1.Nodes.Add , , path, path
Call addtotree(path, TreeView1)
End Sub
Private Sub addtotree(path As String, tv As TreeView)
Dim folder1 As Folder
For Each folder1 In fs.GetFolder(path).SubFolders
tv.Nodes.Add path, tvwChild, path & "\" & folder1.Name, folder1.Name
Call addtotree(path & "\" & folder1.Name, tv)
Next
End Sub
i am doing like this to add nodes and sub nodes but i don't know how to add dynamically all the drives and folder like window explorer.
I'm not sure from your code sample what you're trying to do. If you want to add the drives to your treeview iterate the FileSystemObject.Drives collection. If you are trying to populate the folders under the drives, get the drives, and as the user expands them find the folders under them. Here is a sample that gets drives.
Option Explicit
Private Const EXPANDING = " (expanding...)"
Private Sub LoadDrives(ByVal TreeviewCtrl As TreeView)
Dim objFso As FileSystemObject
Dim objDrive As Drive
Dim objNode As MSComctlLib.Node
On Error GoTo errLoadDrives
Me.MousePointer = vbHourglass
TreeviewCtrl.Nodes.Clear
Set objFso = New FileSystemObject
For Each objDrive In objFso.Drives
Set objNode = TreeView1.Nodes.Add(, tvwFirst, objDrive.Path, objDrive.Path & "\" & IIf(Len(objDrive.ShareName) > 0, " (" & Replace$(objDrive.ShareName, "\\", "") & ")", ""))
If objDrive.IsReady Then
If objDrive.RootFolder.SubFolders.Count > 0 Then
TreeviewCtrl.Nodes.Add objNode, tvwChild
End If
End If
Next objDrive
Me.MousePointer = vbDefault
Exit Sub
errLoadDrives:
Set objFso = Nothing
Me.MousePointer = vbDefault
End Sub
Private Sub TreeView1_Expand(ByVal Node As MSComctlLib.Node)
On Error GoTo errTreeView1_Expand
Me.MousePointer = vbHourglass
Node.Text = Node.Text & EXPANDING ' user feedback for longer operations
TreeView1.Refresh
Call AddToTree(Node)
Node.Text = Replace$(Node.Text, EXPANDING, "")
Me.MousePointer = vbDefault
Exit Sub
errTreeView1_Expand:
Me.MousePointer = vbDefault
MsgBox "There was an error getting the child folders." & vbCrLf & vbCrLf & "Error " & CStr(Err.Number) & ", " & Err.Description, vbOKOnly + vbCritical, Err.Source
End Sub
Private Sub AddToTree(ByVal Node As MSComctlLib.Node)
Dim strPath As String
Dim objParentNode As MSComctlLib.Node
Dim objFso As FileSystemObject
Dim objFolder As Folder
Dim objSubFolder As Folder
Dim objFile As File
Dim objNode As MSComctlLib.Node
On Error GoTo errAddToTree
' remove any place holder node
If Node.Child.Key = "" Then
TreeView1.Nodes.Remove Node.Child.Index
End If
strPath = Node.Key & "\" ' get the path of the current node
Set objFso = New FileSystemObject
Set objFolder = objFso.GetFolder(strPath)
For Each objSubFolder In objFolder.SubFolders
Set objNode = TreeView1.Nodes.Add(Node, tvwChild, objSubFolder.Path, objSubFolder.Name)
If objSubFolder.SubFolders.Count > 0 Or objSubFolder.Files.Count > 0 Then ' add an empty place holder node
TreeView1.Nodes.Add objNode, tvwChild
End If
Next objSubFolder
For Each objFile In objFolder.Files
TreeView1.Nodes.Add Node, tvwChild, Node.Key & "\" & objFile.Name, objFile.Name, "leaf"
Next objFile
Node.EnsureVisible
Exit Sub
errAddToTree:
If Err.Number = 70 Then 'permission denied - ignore it and move on
Resume Next
End If
End Sub
This code is an on the fly label creator for each textbox on a form. Make sure every text box needed on your form is linked to the event handler using double/single click.. I've found this code works but if anyone has a tidier version of this code feel free to post a revision.
Public Class Form1
Private Sub MyEventRoutine( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox2.DoubleClick, TextBox1.DoubleClick
'get textbox
Dim myTextBox As TextBox = sender
'decl label associated with textbox
Dim thelabeltochange As Control
'decl label-name finder code
Dim lblname As String
lblname = myTextBox.Name & "label"
If Me.Controls.Find(lblname, True).Length = 0 Then
Dim lab As New Label
lab.Name = myTextBox.Name & "label"
lab.Size = New Size(40, 20)
lab.Text = "Correct"
lab.Location = New Point(myTextBox.Left + 89, myTextBox.Top)
Me.Controls.Add(lab) 'this should newly created label to your form
lab.BringToFront()
Debug.Write("LABEL name >" & lblname & "< generated on first double click" & vbCrLf)
Else
For Each tmp As Control In Me.Controls
If tmp.Name = myTextBox.Name & "label" Then
Debug.Write("label exists and has name" & vbCrLf)
thelabeltochange = tmp
If thelabeltochange.Text = "Correct" Then
Debug.Write("label set as correct and is now wrong" & vbCrLf)
thelabeltochange.Text = "Wrong"
thelabeltochange.BringToFront()
ElseIf thelabeltochange.Text = "Wrong" Then
Debug.Write("label set as wrong and is now To do" & vbCrLf)
thelabeltochange.Text = "To do"
thelabeltochange.BringToFront()
ElseIf thelabeltochange.Text = "To do" Then
Debug.Write("label set as To do and is now deleted" & vbCrLf)
Me.Controls.Remove(thelabeltochange)
End If
End If
Next
End If
End Sub
End Class
As you can see down there i made a programme that scans a document and optionally get the page info and material & size infos and date info.
When i use OCR scanning like this:
Dim Mdoc As MODI.Document
Dim Mlay As MODI.Layout
Dim fso As Scripting.FileSystemObject
Dim logfile As Object
Public Function ScanMan(ByVal Name As String, ByVal Path As String) As String
Set Mdoc = New MODI.Document
'Set Mdoc = CreateObject("MODI.Document")
Set fso = New Scripting.FileSystemObject
DoEvents
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''' Create OCRLog File '''''''''''''''''''
OCRPath = App.Path & "\OCR Results Log\"
OCRName = Str(DateTime.Date) & " OCRresults"
If fso.FolderExists(OCRPath) = False Then
fso.CreateFolder (OCRPath)
End If
If fso.FileExists(OCRPath & OCRName & ".txt") = False Then
fso.CreateTextFile OCRPath & OCRName & ".txt"
End If
Set logfile = fso.OpenTextFile(OCRPath & OCRName & ".txt", ForAppending)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
On Error GoTo OCRErr
DoEvents
Mdoc.Create Path & "\" & Name
Mdoc.Images(0).OCR miLANG_ENGLISH, True, True
logfile.Write Mdoc.Images(0).Layout.Text
ScanMan = Mlay.Text
Mdoc.Close False
Set Mlay = Nothing
Set Mdoc = Nothing
Exit Function
OCRErr:
logfile.WriteLine "OCR given (" & Err.Number & ") numbered (" & Err.Description & ") error."
logfile.Close
End Function
This gets the whole page but i just want those 3 spesific area to be scanned so how can i achive that? Is there any function for that? Which scans only X,Y coordinates?
A vb6 snippet
Sub TestTextSelection()
Dim miTextSel As MODI.IMiSelectableItem
Dim miSelectRects As MODI.miSelectRects
Dim miSelectRect As MODI.miSelectRect
Dim strTextSelInfo As String
Set miTextSel = MiDocView1.TextSelection
Set miSelectRects = miTextSel.GetSelectRects
strTextSelInfo = _
"Bounding rectangle page & coordinates: " & vbCrLf
For Each miSelectRect In miSelectRects
With miSelectRect
strTextSelInfo = strTextSelInfo & _
.PageNumber & ", " & .Top & ", " & _
.Left & ", " & .Bottom & ", " & _
.Right & vbCrLf
End With
Next
MsgBox strTextSelInfo, vbInformation + vbOKOnly, _
"Text Selection Info"
Set miSelectRect = Nothing
Set miSelectRects = Nothing
Set miTextSel = Nothing
End Sub
Though the question is tagged as vb6 but answer is from vb.Net 2010. I hope vb.NET could easily be converted to vb6, only matters is just a few more time.
The basic idea is to create an xml file from image and then run a query over the xml file to fetch text of the required block surrounded by (x1,y1) and (x2,y2).
The core class
Imports System
Imports System.IO
Imports System.Xml
Imports System.Linq
Imports MODI
Public Class clsCore
Public Sub New()
'blah blah blah
End Sub
Public Function GetTextFromCoordinates(ByVal iPath$, ByVal x1&, ByVal y1&, ByVal x2&, ByVal y2&) As String
Try
Dim xDoc As XElement = Me.ConvertImage2XML(iPath)
If IsNothing(xDoc) = False Then
Dim result As New XElement(<text/>)
Dim query = xDoc...<wd>.Where(Function(c) Val(CStr(c.#left)) >= x1 And Val(CStr(c.#right)) <= x2 And Val(CStr(c.#top)) >= y1 And Val(CStr(c.#bottom)) <= y2)
For Each ele As XElement In query
result.Add(CStr(ele.Value) & " ")
Next ele
Return Trim(result.Value)
Else
Return ""
End If
Catch ex As Exception
Console.WriteLine(ex.ToString)
Return ex.ToString
End Try
End Function
Private Function ConvertImage2XML(ByVal iPath$) As XElement
Try
If File.Exists(iPath) = True Then
Dim miDoc As New MODI.Document
Dim result As New XElement(<image path=<%= iPath %>/>)
miDoc.Create(iPath)
For Each miImg As MODI.Image In miDoc.Images
Dim page As New XElement(<page id=<%= result...<page>.Count + 1 %>/>)
miImg.OCR()
For Each miWord As MODI.Word In miImg.Layout.Words
Dim wd As New XElement(<wd block=<%= miWord.RegionId.ToString %>><%= miWord.Text %></wd>)
For Each miRect As MODI.MiRect In miWord.Rects
wd.Add(New XAttribute("left", miRect.Left))
wd.Add(New XAttribute("top", miRect.Top))
wd.Add(New XAttribute("right", miRect.Right))
wd.Add(New XAttribute("bottom", miRect.Bottom))
Next miRect
page.Add(wd)
Next miWord
result.Add(page)
Next miImg
Return result
Else
Return Nothing
End If
Catch ex As Exception
Console.WriteLine(ex.ToString)
Return Nothing
End Try
End Function
End Class
the main module
Imports System
Imports System.IO
Imports System.Text.RegularExpressions
Module modMain
Sub Main()
Dim iPath$ = "", iPos$ = "150,825,1400,1200"
Console.WriteLine("Enter path to file:")
iPath = Console.ReadLine()
Console.WriteLine("")
Console.WriteLine("Enter co-ordinates(i.e., x1,y1,x2,y2 or 150,825,1400,1200):")
iPos = Console.ReadLine()
Dim tmp As String() = Regex.Split(iPos, "\D+")
Dim outText$ = New clsCore().GetTextFromCoordinates(iPath, tmp(0), tmp(1), tmp(2), tmp(3))
Console.WriteLine("")
Console.WriteLine(String.Format("{0}[({1},{2})-({3},{4})]:{5}{5}{6}", Dir(iPath), tmp(0), tmp(1), tmp(2), tmp(3), vbCrLf, outText))
Console.ReadLine()
End Sub
End Module
UPDATE
The following example reports the page number and the coordinates of the bounding rectangle around the user's image selection in the viewer control. And which can be used later within picturebox.
Sub TestImageSelection()
Dim miImageSel As MODI.IMiSelectableImage
Dim lngPageNo As Long
Dim lngLeft As Long, lngTop As Long
Dim lngRight As Long, lngBottom As Long
Dim strImageSelInfo As String
Set miImageSel = MiDocView1.ImageSelection
miImageSel.GetBoundingRect lngPageNo, _
lngLeft, lngTop, lngRight, lngBottom
strImageSelInfo = _
"Page number: " & lngPageNo & vbCrLf & _
"Bounding rectangle coordinates: " & vbCrLf & _
lngLeft & ", " & lngTop & ", " & _
lngRight & ", " & lngBottom
MsgBox strImageSelInfo, vbInformation + vbOKOnly, _
"Image Selection Info"
Set miImageSel = Nothing
End Sub
Hope this helps.
I used image and pic boxes to crop and resize a picture exactly to HD pixels and size for inclusion in a HD movie. I moved the picture about with slider controls (eg PicSize.Value)
The picture box is set to 1900x1080 pixels off screen with Visible=false.
The image box size has Stretch set to true with size is not critical and shows a smaller version of the final cropped pic.
I save the picture box as a bmp so it nicely integrates with my AVCHD video in the Adobe editor being the same frame size as the video.
This was the main subroutine:
-Private Sub Convert()
'Creates a cropped and/or magnified fixed pixel 1900x1080 picture
Dim file_name As String, LeftPos As Long
Picture2.Picture = LoadPicture("")
DoEvents
' Resize the picture.
LeftPos = 950 + HPos.Value - PicSize.Value / 2 + PicWidth.Value * 20
Picture2.PaintPicture Picture1.Picture, _
LeftPos, VPos.Value, _
PicSize.Value - (PicSize.Value * (PicWidth.Value / 50)), _
PicSize.Value * (Aspect.Value / 100)
Picture2.Picture = Picture2.Image
TopValue.Caption = VPos.Value
HPosValue.Caption = HPos.Value
SizeValue.Caption = PicSize.Value
AspectValue.Caption = Aspect.Value - 75
StretchValue.Caption = PicWidth.Value
Image1.Picture = Picture2.Image 'preview it
End Sub
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