Seem to be getting bogus mouse click events in VB6 - vb6

I'm trying to build a program that counts how long it's been since the mouse was last clicked (and performs some action after a given interval of inactivity). Unfortunately, the mouse click event seems to fire constantly. txtLastMouseMove continually updates to show the current time every second, and txtTimeSinceMouseMove never gets above 1, and is usually 0.
Timer1 is set to 100 ms. Setting it to a longer interval slows down the updates, but they still never count properly.
What am I missing here? Why does the left-click mouse event happen continuously?
' Detect mouse clicks.
Private Declare Function GetAsyncKeyState Lib "User32" (ByVal vKey As Long) As Integer
Private Type POINTAPI
x As Long
y As Long
End Type
' Detect mouse clicks.
Private Sub Timer1_Timer()
Dim Ret As Integer
Static datLastMouseMove As Date
Dim datThisMouseMove As Date
if (datLastMouseMove=0) then datLastMouseMove=now()
Ret = GetAsyncKeyState(1) 'vbKeyLButton = 1
If Ret < 1 Then
' The left mouse button was clicked.
datThisMouseMove = Now()
txtLastMouseMove.Text = Format(datThisMouseMove, "hh:mm:ss")
txtTimeSinceMouseMove = Format(datThisMouseMove - datLastMouseMove, "hh:mm:ss")
If ((datThisMouseMove - datLastMouseMove) * 24 * 60 * 60 > CDbl(txtInterval)) Then
MsgBox "Mouse has not moved in " & Format(datThisMouseMove - datLastMouseMove, "hh:mm:ss")
End If
datLastMouseMove = datThisMouseMove
End If
End Sub

Nevermind, I'm stupid.
"If Ret < 1 Then" fires anytime the mouse button ISN'T clicked. It should read "If Ret Then".

Related

VB6 Subscript Out fo Range - but this is an odd one because a mirror function is working fine

Thanks for reading.
I have built a VB6 DLL (VB_InterFace just for a name) that talks to a C# DLL (C#_Driver just for a name) that talks to a Bluetooth Device.
The Demo VB6 test app (VB_Demo just for a name) I created as stage one works fine, does what it is supposed to. It calls the VB_Interface and Opens and Closes the BTDevice. Additional functions also work fine.
However on placing the operational code from VB_Interface into another DLL that is the live operations DLL, Open works fine, but Close is throwing an error. "Variable not defined" when returning from the C#_Driver.
I just can't see why, the code is the same, the process is only marginally different. By this I mean ;
In the VB_Demo I have two buttons "Open" "Close" and when I click on these I get the feedback that I expect from the BTDevice.
Private Sub btnOpenPort_Click()
'MsgBox steps(0)
ReDim steps(5)
Dim rc As HF4000_ResultCodes
'rc = driver.OpenSerial(cmbPorts.Text)
If driver.OpenSerial(cmbPorts.Text) = True Then
Private Sub btnClosePort_Click()
Dim rc As HF4000_ResultCodes
If driver.CloseSerial("COM4") = True Then
However in the live DLL it just executes the same functions internally without being initiated by a button click.
' See IScanDevice documentation.
' #see IScanDevice#OpenDevice
Private Function IScanDevice_OpenDevice() As Scanning.Scan_ResultCodes
(truncated slightly)
50 If driver.OpenSerial("COM4") = True Then
rc = READY
MsgBox "Connected to the device successfully."
' See IScanDevice documentation.
' #see IScanDevice#CloseDevice
Private Function IScanDevice_CloseDevice() As Scanning.Scan_ResultCodes
(truncated slightly)
50 If driver.CloseSerial("COM4") = True Then
60 rc = READY
70 IScanDevice_CloseDevice = Scan_Success
clsDriver.cls
Public Event OnStateChanged(newState As String)
Public Event OnDataUpdated()
Dim WithEvents CSharpInteropServiceEvents As CSharpInteropService.LibraryInvoke
Dim load As New LibraryInvoke
Private Sub Class_Initialize()
Set CSharpInteropServiceEvents = load
End Sub
Private Sub CSharpInteropServiceEvents_MessageEvent(ByVal newState As String)
If newState = "OpenForm1" Then
' FormDummy2.Show ' Not required
End If
If State <> newState Then
State = newState
RaiseEvent OnStateChanged(State)
GetDriverData
End If
End Sub
Private Function BluetoothTestInvoke(load, functionName, param)
BluetoothTestInvoke = load.GenericInvoke("BluetoothTest.dll", "BluetoothTest.Class1", functionName, param)
End Function
Function OpenSerial(portNumber) ' "COM4"
Dim param(0) As Variant
Dim retorno As Variant
param(0) = portNumber
retorno = BluetoothTestInvoke(load, "OpenSerial", param)
OpenSerial = retorno(0) <<<<<<< Works fine returns TRUE
End Function
Function CloseSerial(portNumber) ' "COM4"
Dim param(0) As Variant
Dim retorno As Variant
param(0) = portNumber
retorno = BluetoothTestInvoke(load, "CloseSerial", param)
CloseSerial = retorno(0) <<<<<<<<< "Error Subscript Out of Range"
End Function
What I have discovered is this - and I guess this is the reason why the Close is not working. The question is why is this situation occurring ...
When driver.OpenSerial executes, it hits > Function OpenSerial
Within Function OpenSerial it executes BluetoothTestInvoke where "load" is "CSharpInteropService.LibraryInvoke"
From there it moves to - Sub CSharpInteropServiceEvents_MessageEvent
.. and everything is fine.
However when I then execute driver.CloseSerial after that, it hits > Function CloseSerial
Within Function OpenSerial it executes BluetoothTestInvoke where "load" is "CSharpInteropService.LibraryInvoke"
Now here it "should" move to - Sub CSharpInteropServiceEvents_MessageEvent
However No, it just drops to the next line which is CloseSerial = retorno(0)
and this is where I get the "Subscript out of range" error for retorno(0)
For some reason in the CloseSerial it is not invoking "load"
BluetoothTestInvoke(load, "CloseSerial", param)
Thoughts and suggestions much appreciated.
UPDATE
Quite right, one should never assume anything.
On the tips I started digging deeper into the C# Library. It turns out the "param" value that is the Bluetooth port is passed into the CloseSerial call, and from there is is passed around within the external C# library dll. At one stage it is reset so the port number that should be handled is lost, thus it doesn't close but specifically the "expected" data was not returned to the calling app.
param(0) = portNumber
retorno = BluetoothTestInvoke(load, "CloseSerial", param) << param was being reset in the external library.

Visual Basic 6 add backcolor to statusbar panel

I am fixing an old application which built on top of Visual Basic 6 code. There is an requirement that adding a statusbar on the bottom of the form. My status bar is as below:
I can show the text correctly but I also want to add a red background color. I found out there is no such option for StatusBar Panel. When I open the property of StatusBar, it shows as below:
I found out I can add picture. But When I added the red color picture, the text will be cover by the picture. I am stuck. Any advice will be helpful. Thanks!!
UPDATE
I simply used the code from the link #Étienne Laneville provided in the comment. The background color added and also the text added.
Here is my code to call the function:
PanelText StatusBar1, 9, "ATM (" & cntATM & ")", QBColor(12), QBColor(0)
But the text position is like below:
I have to make the text like below to position it, because this task was urgent for now and I have no time to investigate more.
PanelText StatusBar1, 9, "ATM (" & cntATM & ") ", QBColor(12), QBColor(0)
Below is my output:
UPDATE 2
I tried the code provided by Brian M Stafford. But I got the same results. The text is still not at the center (Or to the Left). Below are my code and screenshot of status bar:
The function:
Private Sub PanelText(sb As StatusBar, pic As PictureBox, Index As Long, aText As String, bkColor As Long, _
fgColor As Long, lAlign As Integer)
Dim R As RECT
SendMessage sb.hWnd, SB_GETRECT, Index - 1, R
With pic
Set .Font = sb.Font
.Move 0, 0, (R.Right - R.Left + 2) * Screen.TwipsPerPixelX, (R.Bottom - R.Top) * Screen.TwipsPerPixelY
.BackColor = bkColor
.Cls
.ForeColor = fgColor
.CurrentY = (.Height - .TextHeight(aText)) \ 2
Select Case lAlign
Case 0 ' Left Justified
.CurrentX = 0
Case 1 ' Right Justified
.CurrentX = .Width - .TextWidth(aText) - Screen.TwipsPerPixelX * 2
Case 2 ' Centered
.CurrentX = (.Width - .TextWidth(aText)) \ 2
End Select
pic.Print aText
sb.Panels(Index).Text = aText
sb.Panels(Index).Picture = .Image
End With
End Sub
The API:
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Const WM_USER = &H400
Private Const SB_GETRECT = (WM_USER + 10)
Private Declare Function SendMessage Lib _
"user32" Alias "SendMessageA" (ByVal hWnd As _
Long, ByVal wMsg As Long, ByVal wParam As _
Long, lParam As Any) As Long
Calling the function:
PanelText StatusBar1, picPanel, 9, "Test1", vbRed, vbBlack, 2
PanelText StatusBar1, picPanel, 10, "DFM (" & cntDFM & ")", vbRed, vbBlack, 2
I do not know why. May be I missed something or may be I set some property values to the StatusBar1 or picPanel(PictureBox).
SOLUTION
I set pictureBox, property AutoRedraw = True, and StatusBar, Panel, Alignment = sbrLeft. And everything works.
Here's the code referenced in a comment with some enhancements. One enhancement is a parameter to specify text alignment:
Private Sub StatusBarPanelText(sb As StatusBar, pic As PictureBox, index As Long, aText As String, bkColor As Long, fgColor As Long, lAlign As Integer)
Dim r As RECT
SendMessage sb.hWnd, SB_GETRECT, index - 1, r
With pic
Set .Font = sb.Font
.Move 0, 0, (r.Right - r.Left + 2) * Screen.TwipsPerPixelX, (r.Bottom - r.Top) * Screen.TwipsPerPixelY
.BackColor = bkColor
.Cls
.ForeColor = fgColor
.CurrentY = (.Height - .TextHeight(aText)) \ 2
Select Case lAlign
Case 0 ' Left Justified
.CurrentX = 0
Case 1 ' Right Justified
.CurrentX = .Width - .TextWidth(aText) - Screen.TwipsPerPixelX * 2
Case 2 ' Centered
.CurrentX = (.Width - .TextWidth(aText)) \ 2
End Select
pic.Print aText
sb.Panels(index).Text = aText
sb.Panels(index).Picture = .Image
End With
End Sub
Here's the Windows API code:
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA"
(ByVal hWnd As Long, ByVal wMsg As Long,
ByVal wParam As Long, lParam As Any) As Long
Private Const WM_USER = &H400
Private Const SB_GETRECT = (WM_USER + 10)
The code is then used like this:
Picture2.AutoRedraw = True
Picture2.Visible = False
StatusBarPanelText sbConfig, Picture2, 4, & _
Format(Value / 1024, "#,###") & " KB", vbRed, vbWhite, 0
I know I'm late arriving here and this particular issue may no longer matter, but here I am anyway. In trying to write a VB6 program for all versions of Windows from W-95 on, I ran into some color issues related to Microsoft's decision to change named color schemes for subsequent releases of Windows. What I have found is that using a virtual machine with Windows-98 and VB6 installed I can change the backgound color of status bars natively. That property is in the Properties box when using Win-98 but not XP and beyond. I guess the boys in Redmond wanted to enforce their look on our work and so removed that choice. I know this isn't a perfect solution, but it may be something you can live with.
Sorry, but this was my mistake. When I copied my files over from Win-7 to Win-98, VB6 replaced the status bar control with a picture box and named it statusbar1. I'm not sure why because the common controls option is checked and the status bar appears in the toolbox. Looks like the above solutions are the valid ones and mine isn't.

Capture Access-Application Window Restore/Maximize Event

Scenario: In an Access project a main form has to be positioned and rearranged depending on the size of the Access-Application window. This should be done using VBA.
As far as I know there is no way in Microsoft Access VBA to capture the Restore/Maximize-Event of the Access-Application window (I refer to the Access Window itself not any form inside this).
Is there a way to solve this issue using WIN32 API?
I don't know of any way to use the WIN32 API to capture the Restore/Maximize Event. The best workaround I can think of is to use the Win32 API in conjunction with the Timer event of a form that is always open (either the Main Menu or some hidden form) and periodically poll the main access window to determine whether it's currently maximized.
Enum WindowSize
wsMax = 1
wsMin
wsRestore
End Enum
'Functions return 1 for true and 0 for false; multiply result by -1 to use as Boolean'
Private Declare Function IsZoomed Lib "User32" (ByVal hWnd As Long) As Integer
Private Declare Function IsIconic Lib "User32" (ByVal hWnd As Long) As Integer
Function IsMaximized(hWnd As Long) As Boolean
IsMaximized = IsZoomed(hWnd) * -1
End Function
Function IsMinimized(hWnd As Long) As Boolean
IsMinimized = IsIconic(hWnd) * -1
End Function
Private Sub Form_Timer()
Static PrevWinSize As WindowSize
If IsMaximized(hWndAccessApp) Then
If PrevWinSize <> wsMax Then
'Window has been maximized since we last checked'
MsgBox "Main Access window is maximized"
PrevWinSize = wsMax
End If
ElseIf IsMinimized(hWndAccessApp) Then
If PrevWinSize <> wsMin Then
'Window has been minimized since we last checked'
MsgBox "Main Access window is minimized"
PrevWinSize = wsMin
End If
Else
If PrevWinSize <> wsRestore Then
'Window has been restored since we last checked'
MsgBox "Main Access window is restored"
PrevWinSize = wsRestore
End If
End If
End Sub
You'll need to set an interval in the form's TimerInterval property to control how frequently you need to poll the window size.
EDIT: Obviously you'll want to keep track of the main window's previous state so that you don't do any unnecessary processing. The code as posted reflects this.

Form sizing to fill screen dimensions minus taskbar

How do you size your form in vb6 so that form lower border is at top of taskbar
Is there a reason you cannot just maximise the form? That would be my first impression.
If that's not a runner, you could try getting the taskbar height in the following way:
Private Const ABM_GETTASKBARPOS = &H5
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Type APPBARDATA
cbSize As Long
hwnd As Long
uCallbackMessage As Long
uEdge As Long
rc As RECT
lParam As Long
End Type
Private Declare Function SHAppBarMessage Lib "shell32.dll" (ByVal dwMessage As Long, pData As APPBARDATA) As Long
Function GetTaskBarSize()
Dim ABD As APPBARDATA
SHAppBarMessage ABM_GETTASKBARPOS, ABD
MsgBox "Width:" & ABD.rc.Right - ABD.rc.Left
MsgBox " Height:" & ABD.rc.Bottom - ABD.rc.Top
End Sub
and then setting your form's height to the screen's height less the taskbar's height.
Minus only the taskbar? That might not really be what you want. There can be other windows on the edges of the screen that are meant to "carve out" regions of the desktop. Also, note that sometimes the height of the taskbar is irrelevant, such as when it's docked to the left or right side of the screen.
Galwegian has shown how to get the height of the taskbar, but if you're really looking for the usable area of the desktop, use the SystemParametersInfo function with the spi_GetWorkArea flag instead. It will tell you the area of the desktop excluding all desktop toolbars. MSDN advises that if you're interested in the space available on something other than the primary monitor, you should call GetMonitorInfo instead; it fills a record, and one of the fields is for the monitor's work area.
I'm going to second the idea that you might really just want to maximize your window. If you've already done that, and you want to know how much space you're taking up, then get the current size of your window, and then subtract the dimensions of your window's frame (which get "tucked under the edges" of the desktop when a window is maximized). You can use GetSystemMetrics with the sm_CXFrame and sm_CYFrame flags for that.
I'm going to agree you probably want to maximize your window.
But if you really do want to know the area of the desktop excluding all desktop toolbars (taskbar, Microsoft Office toolbar, etc), here's some VB6 declarations for the SystemParametersInfo call and a sample function that centres forms on the screen, allowing for the toolbars. This is borrowed from 101 tech tips (PDF) from the old Visual Basic Programmers Journal.
Private Const SPI_GETWORKAREA = 48
Private Declare Function SystemParametersInfo& Lib "User32" Alias "SystemParametersInfoA" ( _
ByVal uAction As Long, _
ByVal uParam As Long, lpvParam As Any, _
ByVal fuWinIni As Long)
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Public Function CenterForm32 (frm As Form)
Dim ScreenWidth&, ScreenHeight&, ScreenLeft&, ScreenTop&
Dim DesktopArea As RECT
Call SystemParametersInfo (SPI_GETWORKAREA, 0, DesktopArea, 0)
ScreenHeight = (DesktopArea.Bottom - DesktopArea.Top) * Screen.TwipsPerPixelY
ScreenWidth = (DesktopArea.Right - DesktopArea.Left) * Screen.TwipsPerPixelX
ScreenLeft = DesktopArea.Left * Screen.TwipsPerPixelX
ScreenTop = DesktopArea.Top * Screen.TwipsPerPixelY
frm.Move (ScreenWidth - frm.Width) / 2 + ScreenLeft, _
(ScreenHeight - frm.Height) / 2 + ScreenTop
End Function

Application Title Cut Off In VB6

Platform: Windows XP
Development Platform: VB6
When trying to set an application title via the Project Properties dialog on the Make tab, it seems to silently cut off the title at a set number of characters. Also tried this via the App.Title property and it seems to suffer from the same problem. I wouldn't care about this but the QA Dept. insists that we need to get the entire title displayed.
Does anyone have a workaround or fix for this?
Edit: To those who responded about a 40 character limit, that's what I sort of suspected--hence my question about a possible workaround :-) .
Actually I posted this question to try to help a fellow developer so when I see her on Monday, I'll point her to all of your excellent suggestions and see if any of them help her get this straightened out. I do know that for some reason some of the dialogs displayed by the app seem to pick up the string from the App.Title setting which is why she had asked me about the limitation on the length of the string.
I just wish I could find something definitive from Microsoft (like some sort of KB note) so she could show it to our QA department so they'd realize this is simply a limitation of VB.
The MsgBox-Function takes a parameter for the title. If you dont want to change every single call to the MsgBox-Function, you could "override" the default behavior:
Function MsgBox(Prompt, Optional Buttons As VbMsgBoxStyle = vbOKOnly, Optional Title, Optional HelpFile, Optional Context) As VbMsgBoxResult
If IsMissing(Title) Then Title = String(40, "x") & "abc"
MsgBox = Interaction.MsgBox(Prompt, Buttons, Title, HelpFile, Context)
End Function
Edit: As Mike Spross notes: This only hides the normal MsgBox-Function. If you wanted to access your custom MsgBox from another project, you would have to qualify it.
I just created a Standard EXE project in the IDE and typed text into the application title field under the Project Properties Make tab until I filled the field. From this quick test, it appears that App.Title is limited to 40 characters. Next I tried it in code by putting the following code in the default form (Form1) created for the project:
Private Sub Form_Load()
App.Title = String(41, "X")
MsgBox Len(App.Title)
End Sub
This quick test confirms the 40-characater limit, because the MsgBox displays 40, even though the code attempts to set App.Title to a 41-character string.
If it's really important to get the full string to display in the titlebar of a Form, then only way I can think of to ensure that the entire title is displayed would be to get the width of the titlebar text and use that to increase the width of your Form so that it can accommodate the complete title string. I may come back and post code for this if I can find the right API incantations, but it might look something like this in the Form_Load event:
Dim nTitleBarTextWidth As Long
Dim nNewWidth As Long
Me.Caption = "My really really really really really long app title here"
' Get titlebar text width (somehow) '
nTitleBarTextWidth = GetTitleBarTextWidth()
' Compute the new width for the Form such that the title will fit within it '
' (May have to add a constant to this to make sure the title fits correctly) '
nNewWidth = Me.ScaleX(nTitleBarTextWidth, vbPixels, Me.ScaleMode)
' If the new width is bigger than the forms current size, use the new width '
If nNewWidth > Me.Width Then
Form.Width = nNewWidth
End If
One solution using the Windows API
Disclaimer: IMHO this seems like overkill just to meet the requirement stated in the question, but in the spirit of giving a (hopefully) complete answer to the problem, here goes nothing...
Here is a working version I came up with after looking around in MSDN for awhile, until I finally came upon an article on vbAccelerator that got my wheels turning.
See the vbAccelerator page for the original article (not directly related to the question, but there was enough there for me to formulate an answer)
The basic premise is to first calculate the width of the form's caption text and then to use GetSystemMetrics to get the width of various bits of the window, such as the border and window frame width, the width of the Minimize, Maximize, and Close buttons, and so on (I split these into their own functions for readibility/clarity). We need to account for these parts of the window in order to calculate an accurate new width for the form.
In order to accurately calculate the width ("extent") of the form's caption, we need to get the system caption font, hence the SystemParametersInfo and CreateFontIndirect calls and related goodness.
The end result all this effort is the GetRecommendedWidth function, which calculates all of these values and adds them together, plus a bit of extra padding so that there is some space between the last character of the caption and the control buttons. If this new width is greater than the form's current width, GetRecommendedWidth will return this (larger) width, otherwise, it will return the Form's current width.
I only tested it briefly, but it appears to work fine. Since it uses Windows API functions, however, you may want to exercise caution, especially since it's copying memory around. I didn't add robust error-handling, either.
By the way, if someone has a cleaner, less-involved way of doing this, or if I missed something in my own code, please let me know.
To try it out, paste the following code into a new module
Option Explicit
Private Type SIZE
cx As Long
cy As Long
End Type
Private Const LF_FACESIZE = 32
'NMLOGFONT: This declaration came from vbAccelerator (here is what he says about it):'
' '
' For some bizarre reason, maybe to do with byte '
' alignment, the LOGFONT structure we must apply '
' to NONCLIENTMETRICS seems to require an LF_FACESIZE '
' 4 bytes smaller than normal: '
Private Type NMLOGFONT
lfHeight As Long
lfWidth As Long
lfEscapement As Long
lfOrientation As Long
lfWeight As Long
lfItalic As Byte
lfUnderline As Byte
lfStrikeOut As Byte
lfCharSet As Byte
lfOutPrecision As Byte
lfClipPrecision As Byte
lfQuality As Byte
lfPitchAndFamily As Byte
lfFaceName(LF_FACESIZE - 4) As Byte
End Type
Private Type LOGFONT
lfHeight As Long
lfWidth As Long
lfEscapement As Long
lfOrientation As Long
lfWeight As Long
lfItalic As Byte
lfUnderline As Byte
lfStrikeOut As Byte
lfCharSet As Byte
lfOutPrecision As Byte
lfClipPrecision As Byte
lfQuality As Byte
lfPitchAndFamily As Byte
lfFaceName(LF_FACESIZE) As Byte
End Type
Private Type NONCLIENTMETRICS
cbSize As Long
iBorderWidth As Long
iScrollWidth As Long
iScrollHeight As Long
iCaptionWidth As Long
iCaptionHeight As Long
lfCaptionFont As NMLOGFONT
iSMCaptionWidth As Long
iSMCaptionHeight As Long
lfSMCaptionFont As NMLOGFONT
iMenuWidth As Long
iMenuHeight As Long
lfMenuFont As NMLOGFONT
lfStatusFont As NMLOGFONT
lfMessageFont As NMLOGFONT
End Type
Private Enum SystemMetrics
SM_CXBORDER = 5
SM_CXDLGFRAME = 7
SM_CXFRAME = 32
SM_CXSCREEN = 0
SM_CXICON = 11
SM_CXICONSPACING = 38
SM_CXSIZE = 30
SM_CXEDGE = 45
SM_CXSMICON = 49
SM_CXSMSIZE = 52
End Enum
Private Const SPI_GETNONCLIENTMETRICS = 41
Private Const SPI_SETNONCLIENTMETRICS = 42
Private Declare Function GetTextExtentPoint32 Lib "gdi32" Alias "GetTextExtentPoint32A" _
(ByVal hdc As Long, _
ByVal lpszString As String, _
ByVal cbString As Long, _
lpSize As SIZE) As Long
Private Declare Function GetSystemMetrics Lib "user32" (ByVal nIndex As SystemMetrics) As Long
Private Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA" ( _
ByVal uAction As Long, _
ByVal uParam As Long, _
lpvParam As Any, _
ByVal fuWinIni As Long) As Long
Private Declare Function SelectObject Lib "gdi32" (ByVal hdc As Long, ByVal hObject As Long) As Long
Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long
Private Declare Function CreateFontIndirect Lib "gdi32" Alias "CreateFontIndirectA" (lpLogFont As LOGFONT) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Function GetCaptionTextWidth(ByVal frm As Form) As Long
'-----------------------------------------------'
' This function does the following: '
' '
' 1. Get the font used for the forms caption '
' 2. Call GetTextExtent32 to get the width in '
' pixels of the forms caption '
' 3. Convert the width from pixels into '
' the scaling mode being used by the form '
' '
'-----------------------------------------------'
Dim sz As SIZE
Dim hOldFont As Long
Dim hCaptionFont As Long
Dim CaptionFont As LOGFONT
Dim ncm As NONCLIENTMETRICS
ncm.cbSize = LenB(ncm)
If SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, ncm, 0) = 0 Then
' What should we do if we the call fails? Change as needed for your app,'
' but this call is unlikely to fail anyway'
Exit Function
End If
CopyMemory CaptionFont, ncm.lfCaptionFont, LenB(CaptionFont)
hCaptionFont = CreateFontIndirect(CaptionFont)
hOldFont = SelectObject(frm.hdc, hCaptionFont)
GetTextExtentPoint32 frm.hdc, frm.Caption, Len(frm.Caption), sz
GetCaptionTextWidth = frm.ScaleX(sz.cx, vbPixels, frm.ScaleMode)
'clean up, otherwise bad things will happen...'
DeleteObject (SelectObject(frm.hdc, hOldFont))
End Function
Private Function GetControlBoxWidth(ByVal frm As Form) As Long
Dim nButtonWidth As Long
Dim nButtonCount As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
nButtonCount = 1 'close button is always present'
nButtonWidth = GetSystemMetrics(SM_CXSIZE) 'get width of a single button in the titlebar'
' account for min and max buttons if they are visible'
If frm.MinButton Then nButtonCount = nButtonCount + 1
If frm.MaxButton Then nButtonCount = nButtonCount + 1
nFinalWidth = nButtonWidth * nButtonCount
End If
'convert to whatever scale the form is using'
GetControlBoxWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetIconWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.BorderStyle
Case vbFixedSingle, vbFixedDialog, vbSizable:
'we have an icon, gets its width'
nFinalWidth = GetSystemMetrics(SM_CXSMICON)
Case Else:
'no icon present, so report zero width'
nFinalWidth = 0
End Select
End If
'convert to whatever scale the form is using'
GetIconWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetFrameWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.BorderStyle
Case vbFixedSingle, vbFixedDialog:
nFinalWidth = GetSystemMetrics(SM_CXDLGFRAME)
Case vbSizable:
nFinalWidth = GetSystemMetrics(SM_CXFRAME)
End Select
End If
'convert to whatever scale the form is using'
GetFrameWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetBorderWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.Appearance
Case 0 'flat'
nFinalWidth = GetSystemMetrics(SM_CXBORDER)
Case 1 '3D'
nFinalWidth = GetSystemMetrics(SM_CXEDGE)
End Select
End If
'convert to whatever scale the form is using'
GetBorderWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Public Function GetRecommendedWidth(ByVal frm As Form) As Long
Dim nNewWidth As Long
' An abitrary amount of extra padding so that the caption text '
' is not scrunched up against the min/max/close buttons '
Const PADDING_TWIPS = 120
nNewWidth = _
GetCaptionTextWidth(frm) _
+ GetControlBoxWidth(frm) _
+ GetIconWidth(frm) _
+ GetFrameWidth(frm) * 2 _
+ GetBorderWidth(frm) * 2 _
+ PADDING_TWIPS
If nNewWidth > frm.Width Then
GetRecommendedWidth = nNewWidth
Else
GetRecommendedWidth = frm.Width
End If
End Function
Then place the following in your Form_Load event
Private Sub Form_Load()
Me.Caption = String(100, "x") 'replace this with your caption'
Me.Width = GetRecommendedWidth(Me)
End Sub
It appears that VB6 limits the App.Title property to 40 characters. Unfortunately, I can't locate any documentation on MSDN detailing this behavior. (And unfortunately, I don't have documentation loaded onto the machine where my copy of VB6 still resides.)
I ran an experiment with long titles, and that was the observed behavior. If your title is longer than 40 characters, it simply will get truncated.

Resources