| 利用键盘精确移动控件和设置控件尺寸
选中控件,按Ctl+上下左右键就可以以一个Grid为单位移动控件.按Shift+上下左右键就可以以一个Grid为单位扩大缩小控件.
返回
按字母或数字顺序排列列表框中的列表项
将以下代码加入到你的程序中.
Sub ReSort(L As Control)
Dim P%, PP%, C%, Pre$, S$, V&, NewPos%, CheckIt%
Dim TempL$, TempItemData&, S1$
For P = 0 To L.ListCount - 1
S = L.List(P)
For C = 1 To Len(S)
V = Val(Mid$(S, C))
If V > 0 Then Exit For
Next
If V > 0 Then
If C > 1 Then Pre = Left$(S, C - 1)
NewPos = -1
For PP = P + 1 To L.ListCount - 1
CheckIt = False
S1 = L.List(PP)
If Pre <> "" Then
If InStr(S1, Pre) = 1 Then CheckIt = True
Else
If Val(S1) > 0 Then CheckIt = True
End If
If CheckIt Then
If Val(Mid$(S1, C)) < V Then NewPos = PP
Else
Exit For
End If
Next
If NewPos > -1 Then
TempL = L.List(P)
TempItemData = L.ItemData(P)
L.RemoveItem (P)
L.AddItem TempL, NewPos
L.ItemData(L.NewIndex) = TempItemData
P = P - 1
End If
End If
Next
Exit Sub
返回
Tag属性的妙用
在VB编程中,我们经常要动态的控制很多不同控件的属性,例如我们要将一个CommandButton阵列共20各控件中的第1、4、6、7、8、11、18、20号删除。该怎么半呢?这时只要将要删除的控件的Tag属性设置为1,然后加入以下代码就可以了。
For i=1 To 20
If Command1(i).Tag=1 Then
Unload Command1(i)
End If
Next i
返回
使两个列表框(ListBox)的选项同步
步骤1
在Form中添加两个ListBox和一个CommandButton一个Timer,不要改动他们的属性.
步骤2
在Form中添加如下代码:
Private Sub Form_Load()
Dim X As Integer
For X = 1 To 26
List1.AddItem Chr$(X + 64)
Next X
For X = 1 To 26
List2.AddItem Chr$(X + 64)
Next X
Timer1.Interval = 1
Timer1.Enabled = True
End Sub
Private Sub Command1_Click()
End
End Sub
Private Sub timer1_Timer()
Static PrevList1
Dim TopIndex_List1 As Integer
TopIndex_List1 = List1.TopIndex
If TopIndex_List1 <> PrevList1 Then
List2.TopIndex = TopIndex_List1
PrevList1 = TopIndex_List1
End If
If List1.ListIndex <> List2.ListIndex Then
List2.ListIndex = List1.ListIndex
End If
End Sub
运行程序,当选中其中一个列表框中的某一项后,另外一个列表框中的相应项就会被选中.
返回
在 Caption 中显示 & 符号
大家知道,& 符号是 Windows 的快捷键表示符号,如果要在 Caption 中显示 & ,方法很简单,连续输入
两个 & 符号即可。如在 Caption 中输入 Save && Exit,则显示 Save & Exit。
返回
快速选择全部项目
我们在使用 List 控件时,经常需要全部选择其中的项目,在项目较少时,我们可以逐项设置 Selected 来选择全部的项目,但当项目较多时,这样做就比较费时,其实,我们可以用
API 函数来简单实现此功能:
Dim nRet As Long
Dim bState as Boolean
bState=True
nRet = SendMessage(lstList.hWnd, LB_SETSEL, bState, -1)
函数声明:
Public Declare Function SendMessage Lib "User32" Alias "SendMessageA"
( ByVal hWnd As Long, ByVal wMsg As Integer, ByVal wParam As Long, ByVal
lParam As Long) As Long
Public Const WM_USER = &H400
Public Const LB_SETSEL = (WM_USER + 6)
返回
怎样得到文本框(TextBox)中的文本行数?
计算文本框中输入文本的行数可以使用SendMessage函数返回,当一行文字发生环绕时,它将被当作新的一行,而被非简单的计算文本中的换行符个数。
把以下API函数的声明添入模块文件的general declarations区域,如果您使用的是VB4-32或VB5,也可以把此声明添入Form1的general
declarations中,并把所有的“Public”更换为“Private”。
Option Explicit
Public Declare Function SendMessageLong Lib _
"user32" Alias "SendMessageA" _
(ByVal hwnd As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long
Public Const EM_GETLINECOUNT = &HBA
Form Code
Sub Text1_Change()
Dim lineCount as Long
On Local Error Resume Next
'得到/显示文本行数
lineCount = SendMessageLong(Text1.hwnd, EM_GETLINECOUNT,
0&, 0&)
Label1 = Format$(lineCount, "##,###")
End Sub
注释:
为了使本程序成功,请在设计阶段把文本框的Multiline属性设为True。
返回
Use the Timer
control for longer than 1 minute
As you know, the Timer control provides a great way to schedule
events in a VB project. When you enable the control, it fires off
its Timer event every n milliseconds, as determined by the
TimeInterval property. However, the TimeInterval property only
accepts numbers up to 65,535, or just over one minute. As a result,
you may have wondered how to use this control for periods longer
than that.
To do so, use a form, or project level, variable to keep track of
how many times the Timer event fires. Then, in the Timer event,
re-enable the control if enough time hasn't passed. For example,
consider the code below that we attached to a standard form.
Option Explicit
Dim iElapsedMin As Integer
Const cMax_Min As Integer = 2
Private Sub Form_Load()
Timer1.Enabled = True
iElapsedMin = 1
End Sub
Private Sub Timer1_Timer()
lblText.Visible = (iElapsedMin = cMax_Min)
Timer1.Enabled = (iElapsedMin < cMax_Min)
iElapsedMin = iElapsedMin + 1
End Sub
Here, the iElapsedMin variable maintains the elapsed minutes. We
also created a constant to hold the maximum time we want to wait
before turning the lblText control visible, (in this case 2
minutes). After one minute, the Timer event fires and disables the
Timer control. However, if the elapsed time is less than the maximum
time, then the procedure enables the control once more, starting
the process all over again.
返回
Delete all
selected items in a multiselect listbox
To delete selected items from a multiselect listbox, loop backwards
through the items, then remove those where the Selected property
tests True. For example, suppose you have a list box with item1,
item2, item3, item4, item5. You've set the control's MultiSelect
property to Extended or Simple and have selected item1, item3, and
item5. To remove them from the listbox use code similar to the
following:
Private Sub cmdDeleteListItems_Click()
Dim i As Integer
For i = List1.ListCount - 1 To 0 Step -1
If List1.Selected(i) Then List1.RemoveItem i
Next i
End Sub
返回
Enabling
the horizontal scrollbar in a RichTextbox control
By default, when you add a RichTextbox control to a form, VB sets
the RightMargin property to 0. This means that the text you enter
wraps in the control. To display the horizontal scroll bar, you
must set the RightMargin property to a value greater than the
control's width. Otherwise, even if you set the ScrollBars property
to 1-rtfHorizontal, the RTB won't display the scrollbar.
As an example, add a 3200 wide RTB to a form, then set the
RightMargin to 3300 and the ScrollBars to 1-rtfHorizontal. Run the
project and type text into the control until it extends beyond the
RTB's boundaries. When you do, VB displays the horizontal scroll bar
返回
Retrieve
subitem values from a VB ListView control
When you use the ListView control in Report view, the control
shows a table-like list. It's the same view that appears in the
file dialog boxes (Open, Save, etc.) when you click the Details
button. Each row displays additional subitem information about
the main item. For example, in the file dialog boxes, the main
item is the file itself, while the Size and Type columns are the
subitems. When you use the ListView control in your own
applications, VB makes it easy to determine which item you've
selected. When you select an item in Report view, VB triggers the
ItemClick event, which passes a ListItem object (the item you just
clicked). From this object, you can determine it's value. So, for
example, the entire event procedure might look like this
Private Sub lstvwFiles_ItemClick _
ByVal Item As MSComctlLib.ListItem)
strFileSelected = Item
End Sub
This statement would pass the selected item's value (Value being
the object's default property) into the strFileSelected variable.
However, you may have wondered how to retrieve the Item's associated
subitem values. Fortunately, VB provides the ListSubItems collection,
which contains all the subitems of an individual item. So, continuing
with the example above, the Size and Type items are both subitems of
the main File item. To ascertain the values of these subitems, you
simply loop through the collection, like so
Private Sub lstvwFiles_ItemClick _
(ByVal Item As MSComctlLib.ListItem)
Dim itm As ListSubItem
Dim strSubs As String
MsgBox "ItemClicked: " & Item
For Each itm In Item.ListSubItems
strSubs = strSubs & itm & ": "
Next itm
MsgBox "SubItems: " & strSubs
End Sub
返回
Maintain a Visual
Basic DBGrid's runtime column widths
The DBGrid is a great way to display data as a familiar grid-style
output. However, if you change the column widths on the grid at
runtime, Visual Basic doesn't use these new widths the next time
you run the application. Fortunately, the following procedure will
maintain the column widths for you:
Sub DBGridLayout(Operation As String)
'save width of columns
Dim lWidth As Long
Dim clm As Column
Dim lDefWidth As Long
lDefWidth = DBGrid1.DefColWidth
For Each clm In DBGrid1.Columns
With clm
Select Case LCase(Operation)
Case "save"
lWidth = .Width
SaveSetting App.Title, "Cols", CStr(.ColIndex), _
lWidth
Case "load"
lWidth = GetSetting(App.Title, "Cols", _
CStr(.ColIndex), lDefWidth)
.Width = lWidth
End Select
End With
Next clm
End Sub
As you can see, this procedure uses the SaveSetting and GetSetting
functions to store the current width values in VB's portion of the
registry. To use the procedure, call it from the parent form's Load
and Unload events. Then, indicate which operation you want the
procedure to perform, as in:
Private Sub Form_Load()
DBGridLayout "Load"
End Sub
Private Sub Form_Unload(Cancel As Integer)
DBGridLayout "Save"
End Sub
返回
Add a Custom Font
Property to a User Control
PRODUCT :Microsoft Visual Basic for Windows
PROD/VER:WINDOWS:5.0,6.0
OPER/SYS:WINDOWS
KEYWORDS:kbVBp500 kbVBp600 kbCtrlCreate kbAPI kbUserGrp kbPropSheet
======================================================================
---------------------------------------------------------------------
The information in this article applies to:
- Microsoft Visual Basic Learning, Professional, and Enterprise Editions
for Windows, versions 5.0, 6.0
---------------------------------------------------------------------
SUMMARY
=======
When you create a user control, you can add a custom property page that
allows the user to set some or all of the properties you have created.
This
article describes a sample that demonstrates how to create a custom font
property so that you can filter which fonts the user can select. It uses
a
custom property page from which you call the Font common dialog box so
that
it allows your users to select only from fixed pitch fonts.
MORE INFORMATION
================
You can create the properties you want and then you can either set them
directly from the Property Page dialog box, or you can load a form or
call
the CommonDialog from the property page to set them. In steps 1 through
12
of the following example, you can create a version that requires going
through one additional screen, the property page, but otherwise works
substantially like the built-in Font property of the intrinsic controls.
The instructions beginning with step 13 add code that hides the property
page so that the effect is more like the built-in Font property.
Step-by-Step Procedures
-----------------------
1. Create a new Standard EXE project. Form1 is created by default.
2. From the Project menu, add a new UserControl Project. UserControl1
is
created by default.
3. Add a TextBox and a Label to UserControl1.
4. Paste the following code into the UserControl code window:
Option Explicit
Private UseFont As String
Private UseFontSize As Long
Public Property Let MyFont(NewFont As String)
Dim Ctrl As Control
UseFont = NewFont
PropertyChanged "MyFont"
On Error Resume Next ' For Controls without a Font property
For Each Ctrl In Controls
Ctrl.Font.Name = NewFont
Next
End Property
Public Property Get MyFont() As String
MyFont = UseFont
End Property
Public Property Get MyFontSize() As Long
MyFontSize = UseFontSize
End Property
Private Property Let MyFontSize(NewValue As Long)
Dim Ctrl As Control
UseFontSize = NewValue
PropertyChanged "MyFontSize"
On Error Resume Next ' For Controls without a Font property
For Each Ctrl In Controls
Ctrl.Font.Size = NewValue
Next
End Property
5. From the Project menu, add a new Property Page.
6. From the Project menu, click Components, click Microsoft Common
Dialog Control, and click OK.
7. Add a CommonDialog, a CommandButton, and two TextBoxes (named txtMyFont
and txtMyFontSize) to the Property Page.
8. Add the following code to the PropertyPage1 code window:
Option Explicit
Private Sub Command1_Click()
CommonDialog1.Flags = cdlCFBoth Or cdlCFFixedPitchOnly
CommonDialog1.FontName = SelectedControls(0).MyFont
CommonDialog1.FontSize = SelectedControls(0).MyFontSize
CommonDialog1.ShowFont
txtMyFont.Text = CommonDialog1.FontName
txtMyFontSize.Text = CommonDialog1.FontSize
End Sub
Private Sub txtMyFont_Change()
Changed = True
End Sub
Private Sub txtMyFontSize_Change()
Changed = True
End Sub
Private Sub PropertyPage_ApplyChanges()
SelectedControls(0).MyFont = txtMyFont.Text
SelectedControls(0).MyFontSize = txtMyFontSize.Text
End Sub
Private Sub PropertyPage_SelectionChanged()
If SelectedControls(0).MyFont = "" Then
txtMyFont.Text = "Courier" ' Default
Else
txtMyFont.Text = SelectedControls(0).MyFont
End If
If SelectedControls(0).MyFontSize > 0 Then
txtMyFontSize.Text = SelectedControls(0).MyFontSize
Else
txtMyFontSize.Text = 8 ' Default
End If
End Sub
9. Select the UserControl and click the PropertyPages property. Click
the ellipsis button ("..."), select PropertyPage1, and
click OK. This associates the Property Page you created with
UserControl1.
10. Click the UserControl to make sure it is selected. From the Tools
menu,
click Procedure Attributes and select MyFont from the Name drop-down
list. Click Advanced and select PropertyPage1 from the list under Use
this Page in Property Browser:. This makes an ellipsis button ("...")
appear when the user selects the MyFont property.
11. Close all design windows except for Form1. Add the UserControl
to Form1.
12. When the UserControl has the focus, you will see a MyFont property
in
the Properties Window. Click MyFont to get the ellipsis button. Click
the ellipsis button to go to the property page. From here the
CommandButton brings up the filtered Font common dialog where you can
choose your font. If you click OK or Apply, you set these properties.
To
demonstrate that this works, it also applies these settings to the
TextBox and Label. You can also get to this dialog box by right-clicking
on the UserControl and clicking Properties, or through the (Custom)
property in the Properties Window.
Follow the instructions below to skip the intermediate property page and
go
straight to the Font dialog from the ellipsis button. Note that you would
only want to consider this feature if this were the only property you
were
setting through the property page.
13. Using the previous example, add a timer to the property page and add
the following code to the top of the timer code window, just under
Option Explicit:
Private Declare Function GetParent Lib "user32" _
(ByVal hwnd As Long) As Long
Private Declare Function SetWindowPos Lib "user32" _
(ByVal hwnd As Long, ByVal hWndInsertAfter As Long, _
ByVal x As Long, ByVal y As Long, ByVal cx As Long, _
ByVal cy As Long, ByVal wFlags As Long) As Long
Private Declare Function PostMessage Lib "user32" Alias _
"PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, ByVal lParam As Long) As Long
Private Const HWND_TOP = 0
Private Const SWP_NOSIZE = &H1
Private Const SWP_HIDEWINDOW = &H80
Private Const WM_CLOSE = &H10
Dim hwndPP As Long
Private Sub PropertyPage_Paint()
Dim lresult As Long
lresult = GetParent(PropertyPage.hwnd) ' Work back to the
hwndPP = GetParent(lresult) ' dialog window.
lresult = SetWindowPos(hwndPP, HWND_TOP, 200&, 200&, &O0,
&O0, _
SWP_HIDEWINDOW Or SWP_NOSIZE)
End Sub
Private Sub Timer1_Timer()
Dim lRet As Long
Timer1.Enabled = False ' You will not need the Timer again.
Command1.Value = True ' Click the CommandButton.
PropertyPage_ApplyChanges ' Apply the new settings.
lRet = PostMessage(hwndPP, WM_CLOSE, 0, 0) ' Close the dialog box.
End Sub
14. Select the timer and set the Interval property to 1, then close all
design windows.
15. Open the design window for Form1 and click the UserControl to give
it
focus. A MyFont property appears in the Properties window. Click on the
MyFont property. An ellipsis button appears. If you click it, a filtered
Font common dialog box appears (you never see the actual property page).
This is fairly smooth, but there is a brief flicker as the dialog box
opens and closes.
返回
Enable Communications
Between UserDocuments/UserControls
PRODUCT :Microsoft Visual Basic for Windows
PROD/VER:WINDOWS:5.0,6.0
OPER/SYS:WINDOWS
KEYWORDS:kbVBp kbVBp500 kbVBp600 kbCtrl kbCodeSam
======================================================================
---------------------------------------------------------------------
The information in this article applies to:
- Microsoft Visual Basic Professional and Enterprise Editions for
Windows, versions 5.0, 6.0
---------------------------------------------------------------------
SUMMARY
=======
This article covers how to enable communications between UserControls
and
UserDocuments and other programs. There are times when both UserControls
and UserDocuments need to communicate with other forms that are part of
the
entire program. Making public functions and public subroutines only enables
communications from parent forms and processes. Using GLOBAL instead of
PUBLIC allows information to be shared between controls, classes, and
forms.
MORE INFORMATION
================
The project code below is an example of Global Variables being shared:
1. Create a Standard EXE project in Visual Basic. Form1 is created by
default.
2. Select ActiveX Document EXE.
3. Add two additional UserDocuments and one module to the project.
Cut and paste the following code into the module's code pane:
Option Explicit
Global MyNumber As Variant
4. For Document1, add two commandbuttons, a label. and one textbox. Place
the label above the textbox and clear text1.Text. Cut and paste the
following code into its code pane:
Private Sub UserDocument_Initialize()
Command2.Caption = ">>"
Label1.Caption = "Set the number below"
End Sub
Private Sub Command1_Click()
MyNumber = Text1.Text
End Sub
Private Sub Command2_Click()
UserDocument.Hyperlink.NavigateTo App.Path & "\UserDocument2.Vbd"
End Sub
5. For Document2, add two command buttons, a label and one textbox. Place
the label above the textbox and clear text1.Text. Cut and paste the
following code into its code pane:
Private Sub Command1_Click()
UserDocument.Hyperlink.GoBack
End Sub
Private Sub Command2_Click()
UserDocument.Hyperlink.NavigateTo App.Path & "\UserDocument3.vbd"
End Sub
Private Sub UserDocument_Initialize()
Command1.Caption = "<<"
Command2.Caption = ">>"
Label1.Caption = "The Magic Number Is"
Text1.Text = MyNumber
End Sub
6. For Document3, add two command buttons, a label and one textbox. Place
the label above the textbox and clear text1.Text. Cut and paste the
following code into its code pane:
Private Sub Command1_Click()
UserDocument.Hyperlink.GoBack
End Sub
Private Sub UserDocument_Initialize()
Command1.Caption = "<<"
Label1.Caption = "The Magic Number Is"
Text1.Text = MyNumber
End Sub
7. Run the project. Type a number in the text box and click the Command1
button. Next, navigate to the other two documents and notice your number
shows up. Navigate back. When you navigate back to UserDocument1, the
number you placed in the text will be gone. Also notice that no matter
how many times you navigate back and forth between the documents, the
number you added to the Global variable is always the same and always
available.
返回
Back to top
|