--- url: /en/official/Reference/Core/Minus.md --- # - and -= operators Used to find the difference between two numbers, or to indicate the negative value of a numeric expression. The compound form **-=** subtracts-and-assigns in one step. Syntax: > *result* **=** *number1* **-** *number2*\ > **-** *number*\ > *variable* **-=** *number* *(twinBASIC)* *result* : Any numeric variable. *variable* : *(twinBASIC)* Any numeric variable or writable property. *number*, *number1*, *number2* : Any numeric expressions. In the binary form, **-** is the arithmetic subtraction operator that returns the difference between *number1* and *number2*. In the unary form, **-** is the negation operator that returns the negative of *number*. The data type of *result* is usually the same as that of the most precise expression. The order of precision, from least to most precise, is **Byte**, **Integer**, **Long**, **LongLong**, **Single**, **Double**, **Currency**. The following are exceptions: | If | Then *result* is | |:-----------------------------------------------------------------------------------------|:---------------------------------------| | Subtraction involves a **Single** and a **Long** | Converted to a **Double**. | | *result* is a **Long**, **Single**, or **Date** variant that overflows its legal range | Converted to a **Variant** containing a **Double**. | | *result* is a **Byte** variant that overflows its legal range | Converted to an **Integer** variant. | | *result* is an **Integer** variant that overflows its legal range | Converted to a **Long** variant. | | Subtraction involves a **Date** and any other data type | A **Date**. | | Subtraction involves two **Date** expressions | A **Double**. | If one or both expressions are **Null** expressions, *result* is **Null**. If an expression is **Empty**, it is treated as 0. ::: info The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication. ::: ### Compound assignment `x -= y` is the twinBASIC shorthand for `x = x - y`. The left-hand side is evaluated once; the result follows the same type-promotion and **Null** / **Empty** rules described above. **-=** is a statement, not an expression --- it does not produce a value. ```vb Dim Total As Long = 100 Total -= 5 ' Total is now 95. Total -= 5 ' Total is now 90. ``` ### Example This example uses the **-** operator to calculate the difference between two numbers. ```vb Dim MyResult MyResult = 4 - 2 ' Returns 2. MyResult = 459.35 - 334.90 ' Returns 124.45. MyResult = -MyResult ' Unary negation: returns -124.45. ``` ### See Also * [**+** operator](/en/official/Reference/Core/Plus) * [**\*** operator](/en/official/Reference/Core/Multiply) * [**/** operator](/en/official/Reference/Core/Divide) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Minus.md --- # - 和 -= 运算符 用于求两数之差,或指示数值表达式的负值。复合形式 **-=** 在一步中完成相减并赋值。 语法: > *result* **=** *number1* **-** *number2*\ > **-** *number*\ > *variable* **-=** *number* *(twinBASIC)* *result* : 任意数值变量。 *variable* : *(twinBASIC)* 任意数值变量或可写属性。 *number*, *number1*, *number2* : 任意数值表达式。 在二元形式中,**-** 是算术减法运算符,返回 *number1* 和 *number2* 的差。在一元形式中,**-** 是取负运算符,返回 *number* 的负值。 *result* 的数据类型通常与最精确的表达式相同。精度从低到高的顺序为 **Byte**、**Integer**、**Long**、**LongLong**、**Single**、**Double**、**Currency**。以下是例外: | 如果 | 则 *result* 为 | |:-----------------------------------------------------------------------------------------|:---------------------------------------| | 减法涉及 **Single** 和 **Long** | 转换为 **Double**。 | | *result* 是溢出其合法范围的 **Long**、**Single** 或 **Date** 变体 | 转换为包含 **Double** 的 **Variant**。 | | *result* 是溢出其合法范围的 **Byte** 变体 | 转换为 **Integer** 变体。 | | *result* 是溢出其合法范围的 **Integer** 变体 | 转换为 **Long** 变体。 | | 减法涉及 **Date** 和任何其他数据类型 | **Date**。 | | 减法涉及两个 **Date** 表达式 | **Double**。 | 如果一个或两个表达式为 **Null**,则 *result* 为 **Null**。如果表达式为 **Empty**,则被视为0。 ::: info 加法和减法使用的精度顺序与乘法使用的精度顺序不同。 ::: ### 复合赋值 `x -= y` 是twinBASIC中 `x = x - y` 的简写。左侧仅求值一次;结果遵循上述相同的类型提升和 **Null** / **Empty** 规则。**-=** 是语句而非表达式——它不产生值。 ```vb Dim Total As Long = 100 Total -= 5 ' Total is now 95. Total -= 5 ' Total is now 90. ``` ### 示例 本示例使用 **-** 运算符计算两个数的差。 ```vb Dim MyResult MyResult = 4 - 2 ' Returns 2. MyResult = 459.35 - 334.90 ' Returns 124.45. MyResult = -MyResult ' Unary negation: returns -124.45. ``` ### 另请参阅 * [**+** 运算符](/official/Reference/Core/Plus) * [**\*** 运算符](/official/Reference/Core/Multiply) * [**/** 运算符](/official/Reference/Core/Divide) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Reference/VBA/HiddenModule.md --- # (Default) module The **(Default)** module --- known internally as **\_HiddenModule** --- gathers together the unqualified intrinsic procedures that the compiler emits calls into and that are also callable directly: raw-memory helpers, atomic operations, compile-time reflection, codegen and stack-inspection primitives, and a long tail of runtime utilities. Members of this module are referenced without a qualifier, the same way **MsgBox** and **CStr** are. Most of these procedures are deliberately hidden from IntelliSense and exist for advanced or low-level use; use them only when the higher-level alternatives in **[Math](/en/official/Reference/VBA/Math/)**, **[Strings](/en/official/Reference/VBA/Strings/)**, **[Information](/en/official/Reference/VBA/Information/)**, or **[Interaction](/en/official/Reference/VBA/Interaction/)** don't cover the case. Several have additional internal-only members that are not listed here at all. The pointer functions [**ObjPtr**](/en/official/Reference/VBA/Information/ObjPtr), [**StrPtr**](/en/official/Reference/VBA/Information/StrPtr), and [**VarPtr**](/en/official/Reference/VBA/Information/VarPtr) and the [**Array**](/en/official/Reference/VBA/Information/Array) constructor are documented under the [**Information**](/en/official/Reference/VBA/Information/) module; [**Input**](/en/official/Reference/VBA/FileSystem/Input), [**InputB**](/en/official/Reference/VBA/FileSystem/InputB), and [**Width**](/en/official/Reference/VBA/FileSystem/Width) under [**FileSystem**](/en/official/Reference/VBA/FileSystem/). ## Reading and writing memory Memory at a known address is read and written one machine word at a time with the **GetMem**\* / **PutMem**\* family --- [**GetMem1**](/en/official/Reference/VBA/HiddenModule/GetMem1), [**GetMem2**](/en/official/Reference/VBA/HiddenModule/GetMem2), [**GetMem4**](/en/official/Reference/VBA/HiddenModule/GetMem4), [**GetMem8**](/en/official/Reference/VBA/HiddenModule/GetMem8), and [**GetMemPtr**](/en/official/Reference/VBA/HiddenModule/GetMemPtr) for reads, with matching [**PutMem1**](/en/official/Reference/VBA/HiddenModule/PutMem1), [**PutMem2**](/en/official/Reference/VBA/HiddenModule/PutMem2), [**PutMem4**](/en/official/Reference/VBA/HiddenModule/PutMem4), [**PutMem8**](/en/official/Reference/VBA/HiddenModule/PutMem8), and [**PutMemPtr**](/en/official/Reference/VBA/HiddenModule/PutMemPtr). [**vbaCopyBytes**](/en/official/Reference/VBA/HiddenModule/vbaCopyBytes) and [**vbaCopyBytesZero**](/en/official/Reference/VBA/HiddenModule/vbaCopyBytesZero) move blocks; [**AllocMem**](/en/official/Reference/VBA/HiddenModule/AllocMem) and [**FreeMem**](/en/official/Reference/VBA/HiddenModule/FreeMem) manage heap allocations. The pointer constructors that feed these helpers --- [**ObjPtr**](/en/official/Reference/VBA/Information/ObjPtr), [**StrPtr**](/en/official/Reference/VBA/Information/StrPtr), [**VarPtr**](/en/official/Reference/VBA/Information/VarPtr) --- live in [**Information**](/en/official/Reference/VBA/Information/). ```vb Dim Buffer As LongPtr = AllocMem(16) PutMem4 Buffer, &HDEADBEEF Dim Magic As Long GetMem4 Buffer, Magic FreeMem Buffer ``` [**vbaRefVarAry**](/en/official/Reference/VBA/HiddenModule/vbaRefVarAry) and [**vbaAryMove**](/en/official/Reference/VBA/HiddenModule/vbaAryMove) are lower-level helpers used when interfacing with C-side array layouts. ## Object references and casting [**vbaObjAddref**](/en/official/Reference/VBA/HiddenModule/vbaObjAddref), [**vbaObjSet**](/en/official/Reference/VBA/HiddenModule/vbaObjSet), and [**vbaObjSetAddref**](/en/official/Reference/VBA/HiddenModule/vbaObjSetAddref) manipulate COM reference counts directly. [**vbaCastObj**](/en/official/Reference/VBA/HiddenModule/vbaCastObj) returns the object reinterpreted as another COM interface, given its IID. [**CreateGUID**](/en/official/Reference/VBA/HiddenModule/CreateGUID) generates a fresh GUID and returns it as a registry-formatted string. ## Atomic operations The **Interlocked**\* family wraps the corresponding Windows kernel atomics --- building blocks for lock-free counters and pointer swaps: [**InterlockedExchangePointer**](/en/official/Reference/VBA/HiddenModule/InterlockedExchangePointer), [**InterlockedCompareExchangePointer**](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer), [**InterlockedCompareExchange32**](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32), [**InterlockedCompareExchange64**](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64), [**InterlockedIncrement32**](/en/official/Reference/VBA/HiddenModule/InterlockedIncrement32), and [**InterlockedDecrement32**](/en/official/Reference/VBA/HiddenModule/InterlockedDecrement32). ## Compile-time reflection A few intrinsics ask questions about the surrounding type without running anything; they are resolved by the compiler and embedded as constants. [**GetDeclaredTypeProgId**](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId), [**GetDeclaredTypeClsid**](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid), [**GetDeclaredTypeIid**](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid), and [**GetDeclaredTypeEventIid**](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid) report a type's COM identifiers. [**GetDeclaredMinEnumValue**](/en/official/Reference/VBA/HiddenModule/GetDeclaredMinEnumValue) and [**GetDeclaredMaxEnumValue**](/en/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue) return the minimum and maximum value of a declared enumeration. ## Codegen injection and stack inspection [**Emit**](/en/official/Reference/VBA/HiddenModule/Emit) and [**EmitAny**](/en/official/Reference/VBA/HiddenModule/EmitAny) splice raw bytes or typed literals into the codegen output of the enclosing procedure --- the vehicle for inline assembly. [**StackOffset**](/en/official/Reference/VBA/HiddenModule/StackOffset) and [**StackArgsSize**](/en/official/Reference/VBA/HiddenModule/StackArgsSize) report layout information at the current call site; [**UnprotectedAccess**](/en/official/Reference/VBA/HiddenModule/UnprotectedAccess) returns an object reference that bypasses the usual access checks on private members. ## Runtime expression evaluation [**Eval**](/en/official/Reference/VBA/HiddenModule/Eval) compiles and evaluates a twinBASIC expression supplied as a string, using a freshly built [**TbExpressionService**](/en/official/Reference/VBA/TbExpressionService/) configured with the standard library binder. ## Pictures, bitmaps, and icons [**PictureToByteArray**](/en/official/Reference/VBA/HiddenModule/PictureToByteArray) serialises an **IPicture** to a byte array; [**CreateStdPictureFromHandle**](/en/official/Reference/VBA/HiddenModule/CreateStdPictureFromHandle) wraps a GDI handle in an **stdole.StdPicture**; [**ConvertIconToBitmap**](/en/official/Reference/VBA/HiddenModule/ConvertIconToBitmap) does the obvious. ## Other helpers [**GetInheritedOwner**](/en/official/Reference/VBA/HiddenModule/GetInheritedOwner) returns the inherited owner object of a control. [**GetShortcutTextByEnum**](/en/official/Reference/VBA/HiddenModule/GetShortcutTextByEnum) returns the localised display text for a built-in keyboard shortcut. [**SetThreadGlobalErrorTrap**](/en/official/Reference/VBA/HiddenModule/SetThreadGlobalErrorTrap) registers a callback that fires when an unhandled run-time error escapes the active error handler chain on the calling thread. ## Members * [AllocMem](/en/official/Reference/VBA/HiddenModule/AllocMem) -- allocates a block of native memory and returns its address * [ConvertIconToBitmap](/en/official/Reference/VBA/HiddenModule/ConvertIconToBitmap) -- converts an icon picture to a bitmap picture * [CreateGUID](/en/official/Reference/VBA/HiddenModule/CreateGUID) -- generates a fresh GUID and returns it as a registry-formatted string * [CreateStdPictureFromHandle](/en/official/Reference/VBA/HiddenModule/CreateStdPictureFromHandle) -- wraps a GDI bitmap or icon handle in an **stdole.StdPicture** * [Emit](/en/official/Reference/VBA/HiddenModule/Emit) -- injects custom **Byte** values into the codegen stream of the enclosing procedure * [EmitAny](/en/official/Reference/VBA/HiddenModule/EmitAny) -- injects custom typed values into the codegen stream of the enclosing procedure * [Eval](/en/official/Reference/VBA/HiddenModule/Eval) -- compiles and evaluates a twinBASIC expression supplied as a string * [FreeMem](/en/official/Reference/VBA/HiddenModule/FreeMem) -- frees memory allocated with [**AllocMem**](/en/official/Reference/VBA/HiddenModule/AllocMem) * [GetDeclaredMaxEnumValue](/en/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue) -- returns the maximum value of a declared enumeration type, resolved at compile time * [GetDeclaredMinEnumValue](/en/official/Reference/VBA/HiddenModule/GetDeclaredMinEnumValue) -- returns the minimum value of a declared enumeration type, resolved at compile time * [GetDeclaredTypeClsid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid) -- returns the COM CLSID associated with the declared type, resolved at compile time * [GetDeclaredTypeEventIid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid) -- returns the COM event-interface IID associated with the declared type, resolved at compile time * [GetDeclaredTypeIid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid) -- returns the COM interface IID associated with the declared type, resolved at compile time * [GetDeclaredTypeProgId](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId) -- returns the COM ProgID associated with the declared type, resolved at compile time * [GetInheritedOwner](/en/official/Reference/VBA/HiddenModule/GetInheritedOwner) -- returns the inherited owner object of a control * [GetMem1](/en/official/Reference/VBA/HiddenModule/GetMem1) -- reads one byte from a memory address into a **Byte** variable * [GetMem2](/en/official/Reference/VBA/HiddenModule/GetMem2) -- reads two bytes from a memory address into an **Integer** variable * [GetMem4](/en/official/Reference/VBA/HiddenModule/GetMem4) -- reads four bytes from a memory address into a **Long** variable * [GetMem8](/en/official/Reference/VBA/HiddenModule/GetMem8) -- reads eight bytes from a memory address into a **Currency** variable * [GetMemPtr](/en/official/Reference/VBA/HiddenModule/GetMemPtr) -- reads a pointer-sized value from a memory address into a **LongPtr** variable * [GetShortcutTextByEnum](/en/official/Reference/VBA/HiddenModule/GetShortcutTextByEnum) -- returns the localized text for a built-in keyboard shortcut by its enumeration ID * [InterlockedCompareExchange32](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32) -- atomically compares and exchanges a 32-bit value * [InterlockedCompareExchange64](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64) -- atomically compares and exchanges a 64-bit value * [InterlockedCompareExchangePointer](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer) -- atomically compares and exchanges a pointer-sized value * [InterlockedDecrement32](/en/official/Reference/VBA/HiddenModule/InterlockedDecrement32) -- atomically decrements a 32-bit value and returns the new value * [InterlockedExchangePointer](/en/official/Reference/VBA/HiddenModule/InterlockedExchangePointer) -- atomically exchanges a pointer-sized value and returns the previous value * [InterlockedIncrement32](/en/official/Reference/VBA/HiddenModule/InterlockedIncrement32) -- atomically increments a 32-bit value and returns the new value * [PictureToByteArray](/en/official/Reference/VBA/HiddenModule/PictureToByteArray) -- serialises an **IPicture** into a **Byte** array * [PutMem1](/en/official/Reference/VBA/HiddenModule/PutMem1) -- writes one byte to a memory address * [PutMem2](/en/official/Reference/VBA/HiddenModule/PutMem2) -- writes two bytes to a memory address * [PutMem4](/en/official/Reference/VBA/HiddenModule/PutMem4) -- writes four bytes to a memory address * [PutMem8](/en/official/Reference/VBA/HiddenModule/PutMem8) -- writes eight bytes to a memory address * [PutMemPtr](/en/official/Reference/VBA/HiddenModule/PutMemPtr) -- writes a pointer-sized value to a memory address * [RuntimeCreateGetMessageHook](/en/official/Reference/VBA/HiddenModule/RuntimeCreateGetMessageHook) -- creates an [**IGetMessageHook**](./#igetmessagehook-interface) for filtering window messages * [SetThreadGlobalErrorTrap](/en/official/Reference/VBA/HiddenModule/SetThreadGlobalErrorTrap) -- registers a global callback invoked when an unhandled error is raised on the calling thread * [StackArgsSize](/en/official/Reference/VBA/HiddenModule/StackArgsSize) -- returns the total size, in bytes, of the arguments on the current procedure's stack frame * [StackOffset](/en/official/Reference/VBA/HiddenModule/StackOffset) -- returns the stack-frame offset of a variable * [UnprotectedAccess](/en/official/Reference/VBA/HiddenModule/UnprotectedAccess) -- returns an object reference that bypasses access checks on private members * [vbaAryMove](/en/official/Reference/VBA/HiddenModule/vbaAryMove) -- moves the contents of one array variable into another * [vbaCastObj](/en/official/Reference/VBA/HiddenModule/vbaCastObj) -- returns an object reinterpreted as another COM interface * [vbaCopyBytes](/en/official/Reference/VBA/HiddenModule/vbaCopyBytes) -- copies a block of bytes from one address to another * [vbaCopyBytesZero](/en/official/Reference/VBA/HiddenModule/vbaCopyBytesZero) -- copies a block of bytes from one address to another, then zeros the source * [vbaObjAddref](/en/official/Reference/VBA/HiddenModule/vbaObjAddref) -- increments the COM reference count of an object at a given address * [vbaObjSet](/en/official/Reference/VBA/HiddenModule/vbaObjSet) -- assigns an object pointer to an object variable, releasing any prior reference * [vbaObjSetAddref](/en/official/Reference/VBA/HiddenModule/vbaObjSetAddref) -- assigns an object pointer to an object variable, adding a reference and releasing any prior reference * [vbaRefVarAry](/en/official/Reference/VBA/HiddenModule/vbaRefVarAry) -- returns a pointer to the **SAFEARRAY** descriptor inside a **Variant** array ## IGetMessageHook interface The **IGetMessageHook** interface hooks into the Windows message stream for a chosen window --- and optionally its descendants --- and forwards messages of a chosen type to a user-supplied callback. Obtain an instance with [**RuntimeCreateGetMessageHook**](/en/official/Reference/VBA/HiddenModule/RuntimeCreateGetMessageHook); connect callbacks with [**RegisterMessage**](/en/official/Reference/VBA/HiddenModule/RegisterMessage); then call [**Start**](/en/official/Reference/VBA/HiddenModule/Start) to activate every registered subscription, and [**Stop**](/en/official/Reference/VBA/HiddenModule/Stop) to remove them. The interface inherits directly from **stdole.IUnknown** (it is not dispatch-based), and the callbacks supplied to **RegisterMessage** are typed as [**GetMessageHookHelper.GetMessageHandler**](#getmessagehandler). ```vb Const WM_LBUTTONDOWN = &H201 Sub Demo() Dim Hook As IGetMessageHook = RuntimeCreateGetMessageHook Hook.RegisterMessage Me.hWnd, AllDescendants, _ WM_LBUTTONDOWN, AddressOf OnLButtonDown Hook.Start End Sub Function OnLButtonDown(ByRef msg As GetMessageHookHelper.HookMSG) As LongPtr Debug.Print "Click at"; msg.pt.x, msg.pt.y ' Return zero to let the message continue normal processing. End Function ``` ### Members * [RegisterMessage](/en/official/Reference/VBA/HiddenModule/RegisterMessage) -- subscribes a callback to a single message type for a window and a chosen descendant scope * [Start](/en/official/Reference/VBA/HiddenModule/Start) -- activates every registered subscription * [Stop](/en/official/Reference/VBA/HiddenModule/Stop) -- deactivates every registered subscription ### EnumDescendantsModeFlags Selects the window scope passed to [**RegisterMessage**](/en/official/Reference/VBA/HiddenModule/RegisterMessage): | Constant | Value | Description | |------------------------------------------|-------|-------------| | **ExactWindow** | 1 | Hook only the specified window. | | **AllDescendants** | 2 | Hook the specified window and every descendant --- children, grandchildren, and so on. | | **DirectChildren** | 4 | Hook the specified window and its immediate children only. | ## GetMessageHookHelper module The **GetMessageHookHelper** module is a small companion to [**IGetMessageHook**](#igetmessagehook-interface) that holds the structures and the delegate type used by its callback. There is nothing to construct; the names exist only for use in declarations. ### HookMSG A copy of the Windows `MSG` structure, passed by reference into a [**GetMessageHandler**](#getmessagehandler) callback. ```vb Type HookMSG hwnd As LongPtr ' Window the message is destined for. message As Long ' The WM_* identifier. wParam As LongPtr ' Message-specific parameter. lParam As LongPtr ' Message-specific parameter. time As Long ' Time the message was posted, in milliseconds since system start. pt As HookPOINT ' Cursor position when the message was posted. End Type ``` ### HookPOINT A 2D point with **Long** coordinates, used by [**HookMSG**](#hookmsg) to hold the cursor position. ```vb Type HookPOINT x As Long y As Long End Type ``` ### GetMessageHandler The callback signature accepted by [**IGetMessageHook.RegisterMessage**](/en/official/Reference/VBA/HiddenModule/RegisterMessage). Returning zero generally lets the message continue normal processing. ```vb Public Delegate Function GetMessageHandler (ByRef msg As HookMSG) As LongPtr ``` --- --- url: /zh/official/Reference/VBA/HiddenModule.md --- # (Default)模块 **(Default)**模块——内部称为**\_HiddenModule**——汇集了编译器生成调用的未限定内联过程,这些过程也可以直接调用:原始内存辅助函数、原子操作、编译时反射、代码生成和栈检查原语,以及一大堆运行时实用工具。此模块的成员无需限定符即可引用,与**MsgBox**和**CStr**的使用方式相同。 这些过程大多有意对IntelliSense隐藏,仅在高级或低级场景下使用;仅当\*\*[Math](/official/Reference/VBA/Math/)**、**[Strings](/official/Reference/VBA/Strings/)**、**[Information](/official/Reference/VBA/Information/)**或**[Interaction](/official/Reference/VBA/Interaction/)\*\*中的高级替代方案不适用时才使用。有几个还有此处未列出的仅限内部使用的成员。 指针函数[**ObjPtr**](/official/Reference/VBA/Information/ObjPtr)、[**StrPtr**](/official/Reference/VBA/Information/StrPtr)和[**VarPtr**](/official/Reference/VBA/Information/VarPtr)以及[**Array**](/official/Reference/VBA/Information/Array)构造函数记录在[**Information**](/official/Reference/VBA/Information/)模块下;[**Input**](/official/Reference/VBA/FileSystem/Input)、[**InputB**](/official/Reference/VBA/FileSystem/InputB)和[**Width**](/official/Reference/VBA/FileSystem/Width)记录在[**FileSystem**](/official/Reference/VBA/FileSystem/)下。 ## 读写内存 已知地址的内存使用**GetMem**\*/**PutMem**\*系列一次一个机器字地读取和写入——[**GetMem1**](/official/Reference/VBA/HiddenModule/GetMem1)、[**GetMem2**](/official/Reference/VBA/HiddenModule/GetMem2)、[**GetMem4**](/official/Reference/VBA/HiddenModule/GetMem4)、[**GetMem8**](/official/Reference/VBA/HiddenModule/GetMem8)和[**GetMemPtr**](/official/Reference/VBA/HiddenModule/GetMemPtr)用于读取,对应的[**PutMem1**](/official/Reference/VBA/HiddenModule/PutMem1)、[**PutMem2**](/official/Reference/VBA/HiddenModule/PutMem2)、[**PutMem4**](/official/Reference/VBA/HiddenModule/PutMem4)、[**PutMem8**](/official/Reference/VBA/HiddenModule/PutMem8)和[**PutMemPtr**](/official/Reference/VBA/HiddenModule/PutMemPtr)用于写入。[**vbaCopyBytes**](/official/Reference/VBA/HiddenModule/vbaCopyBytes)和[**vbaCopyBytesZero**](/official/Reference/VBA/HiddenModule/vbaCopyBytesZero)移动块;[**AllocMem**](/official/Reference/VBA/HiddenModule/AllocMem)和[**FreeMem**](/official/Reference/VBA/HiddenModule/FreeMem)管理堆分配。为这些辅助函数提供指针的构造函数——[**ObjPtr**](/official/Reference/VBA/Information/ObjPtr)、[**StrPtr**](/official/Reference/VBA/Information/StrPtr)、[**VarPtr**](/official/Reference/VBA/Information/VarPtr)——位于[**Information**](/official/Reference/VBA/Information/)中。 ```vb Dim Buffer As LongPtr = AllocMem(16) PutMem4 Buffer, &HDEADBEEF Dim Magic As Long GetMem4 Buffer, Magic FreeMem Buffer ``` [**vbaRefVarAry**](/official/Reference/VBA/HiddenModule/vbaRefVarAry)和[**vbaAryMove**](/official/Reference/VBA/HiddenModule/vbaAryMove)是在与C端数组布局交互时使用的低级辅助函数。 ## 对象引用和转换 [**vbaObjAddref**](/official/Reference/VBA/HiddenModule/vbaObjAddref)、[**vbaObjSet**](/official/Reference/VBA/HiddenModule/vbaObjSet)和[**vbaObjSetAddref**](/official/Reference/VBA/HiddenModule/vbaObjSetAddref)直接操作COM引用计数。[**vbaCastObj**](/official/Reference/VBA/HiddenModule/vbaCastObj)根据给定IID返回重新解释为另一个COM接口的对象。[**CreateGUID**](/official/Reference/VBA/HiddenModule/CreateGUID)生成新的GUID并以注册表格式字符串返回。 ## 原子操作 **Interlocked**\*系列封装了对应的Windows内核原子操作——无锁计数器和指针交换的基础构建块:[**InterlockedExchangePointer**](/official/Reference/VBA/HiddenModule/InterlockedExchangePointer)、[**InterlockedCompareExchangePointer**](/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer)、[**InterlockedCompareExchange32**](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32)、[**InterlockedCompareExchange64**](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64)、[**InterlockedIncrement32**](/official/Reference/VBA/HiddenModule/InterlockedIncrement32)和[**InterlockedDecrement32**](/official/Reference/VBA/HiddenModule/InterlockedDecrement32)。 ## 编译时反射 一些内联函数询问周围类型的问题而不运行任何东西;它们由编译器解析并作为常量嵌入。[**GetDeclaredTypeProgId**](/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId)、[**GetDeclaredTypeClsid**](/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid)、[**GetDeclaredTypeIid**](/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid)和[**GetDeclaredTypeEventIid**](/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid)报告类型的COM标识符。[**GetDeclaredMinEnumValue**](/official/Reference/VBA/HiddenModule/GetDeclaredMinEnumValue)和[**GetDeclaredMaxEnumValue**](/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue)返回已声明枚举的最小值和最大值。 ## 代码生成注入和栈检查 [**Emit**](/official/Reference/VBA/HiddenModule/Emit)和[**EmitAny**](/official/Reference/VBA/HiddenModule/EmitAny)将原始字节或类型化字面值拼接到封闭过程的代码生成输出中——内联汇编的载体。[**StackOffset**](/official/Reference/VBA/HiddenModule/StackOffset)和[**StackArgsSize**](/official/Reference/VBA/HiddenModule/StackArgsSize)报告当前调用点的布局信息;[**UnprotectedAccess**](/official/Reference/VBA/HiddenModule/UnprotectedAccess)返回绕过私有成员常规访问检查的对象引用。 ## 运行时表达式求值 [**Eval**](/official/Reference/VBA/HiddenModule/Eval)编译并计算以字符串形式提供的twinBASIC表达式,使用配置了标准库绑定器的新构建的[**TbExpressionService**](/official/Reference/VBA/TbExpressionService/)。 ## 图片、位图和图标 [**PictureToByteArray**](/official/Reference/VBA/HiddenModule/PictureToByteArray)将**IPicture**序列化为字节数组;[**CreateStdPictureFromHandle**](/official/Reference/VBA/HiddenModule/CreateStdPictureFromHandle)将GDI句柄包装在**stdole.StdPicture**中;[**ConvertIconToBitmap**](/official/Reference/VBA/HiddenModule/ConvertIconToBitmap)执行图标到位图的转换。 ## 其他辅助函数 [**GetInheritedOwner**](/official/Reference/VBA/HiddenModule/GetInheritedOwner)返回控件的继承所有者对象。[**GetShortcutTextByEnum**](/official/Reference/VBA/HiddenModule/GetShortcutTextByEnum)返回内置键盘快捷键的本地化显示文本。[**SetThreadGlobalErrorTrap**](/official/Reference/VBA/HiddenModule/SetThreadGlobalErrorTrap)注册一个回调,当未处理的运行时错误逃离调用线程上的活动错误处理程序链时触发。 ## 成员 * [AllocMem](/official/Reference/VBA/HiddenModule/AllocMem) —— 分配本机内存块并返回其地址 * [ConvertIconToBitmap](/official/Reference/VBA/HiddenModule/ConvertIconToBitmap) —— 将图标图片转换为位图图片 * [CreateGUID](/official/Reference/VBA/HiddenModule/CreateGUID) —— 生成新的GUID并以注册表格式字符串返回 * [CreateStdPictureFromHandle](/official/Reference/VBA/HiddenModule/CreateStdPictureFromHandle) —— 将GDI位图或图标句柄包装在**stdole.StdPicture**中 * [Emit](/official/Reference/VBA/HiddenModule/Emit) —— 将自定义**Byte**值注入封闭过程的代码生成流 * [EmitAny](/official/Reference/VBA/HiddenModule/EmitAny) —— 将自定义类型化值注入封闭过程的代码生成流 * [Eval](/official/Reference/VBA/HiddenModule/Eval) —— 编译并计算以字符串形式提供的twinBASIC表达式 * [FreeMem](/official/Reference/VBA/HiddenModule/FreeMem) —— 释放使用[**AllocMem**](/official/Reference/VBA/HiddenModule/AllocMem)分配的内存 * [GetDeclaredMaxEnumValue](/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue) —— 返回已声明枚举类型的最大值,在编译时解析 * [GetDeclaredMinEnumValue](/official/Reference/VBA/HiddenModule/GetDeclaredMinEnumValue) —— 返回已声明枚举类型的最小值,在编译时解析 * [GetDeclaredTypeClsid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid) —— 返回与已声明类型关联的COM CLSID,在编译时解析 * [GetDeclaredTypeEventIid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid) —— 返回与已声明类型关联的COM事件接口IID,在编译时解析 * [GetDeclaredTypeIid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid) —— 返回与已声明类型关联的COM接口IID,在编译时解析 * [GetDeclaredTypeProgId](/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId) —— 返回与已声明类型关联的COM ProgID,在编译时解析 * [GetInheritedOwner](/official/Reference/VBA/HiddenModule/GetInheritedOwner) —— 返回控件的继承所有者对象 * [GetMem1](/official/Reference/VBA/HiddenModule/GetMem1) —— 从内存地址读取一个字节到**Byte**变量中 * [GetMem2](/official/Reference/VBA/HiddenModule/GetMem2) —— 从内存地址读取两个字节到**Integer**变量中 * [GetMem4](/official/Reference/VBA/HiddenModule/GetMem4) —— 从内存地址读取四个字节到**Long**变量中 * [GetMem8](/official/Reference/VBA/HiddenModule/GetMem8) —— 从内存地址读取八个字节到**Currency**变量中 * [GetMemPtr](/official/Reference/VBA/HiddenModule/GetMemPtr) —— 从内存地址读取指针大小的值到**LongPtr**变量中 * [GetShortcutTextByEnum](/official/Reference/VBA/HiddenModule/GetShortcutTextByEnum) —— 根据枚举ID返回内置键盘快捷键的本地化文本 * [InterlockedCompareExchange32](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32) —— 原子地比较并交换32位值 * [InterlockedCompareExchange64](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64) —— 原子地比较并交换64位值 * [InterlockedCompareExchangePointer](/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer) —— 原子地比较并交换指针大小的值 * [InterlockedDecrement32](/official/Reference/VBA/HiddenModule/InterlockedDecrement32) —— 原子地将32位值减一并返回新值 * [InterlockedExchangePointer](/official/Reference/VBA/HiddenModule/InterlockedExchangePointer) —— 原子地交换指针大小的值并返回之前的值 * [InterlockedIncrement32](/official/Reference/VBA/HiddenModule/InterlockedIncrement32) —— 原子地将32位值加一并返回新值 * [PictureToByteArray](/official/Reference/VBA/HiddenModule/PictureToByteArray) —— 将**IPicture**序列化为**Byte**数组 * [PutMem1](/official/Reference/VBA/HiddenModule/PutMem1) —— 向内存地址写入一个字节 * [PutMem2](/official/Reference/VBA/HiddenModule/PutMem2) —— 向内存地址写入两个字节 * [PutMem4](/official/Reference/VBA/HiddenModule/PutMem4) —— 向内存地址写入四个字节 * [PutMem8](/official/Reference/VBA/HiddenModule/PutMem8) —— 向内存地址写入八个字节 * [PutMemPtr](/official/Reference/VBA/HiddenModule/PutMemPtr) —— 向内存地址写入指针大小的值 * [RuntimeCreateGetMessageHook](/official/Reference/VBA/HiddenModule/RuntimeCreateGetMessageHook) —— 创建用于过滤窗口消息的[**IGetMessageHook**](./#igetmessagehook-interface) * [SetThreadGlobalErrorTrap](/official/Reference/VBA/HiddenModule/SetThreadGlobalErrorTrap) —— 注册在调用线程上引发未处理错误时调用的全局回调 * [StackArgsSize](/official/Reference/VBA/HiddenModule/StackArgsSize) —— 返回当前过程栈帧上参数的总大小(以字节为单位) * [StackOffset](/official/Reference/VBA/HiddenModule/StackOffset) —— 返回变量的栈帧偏移量 * [UnprotectedAccess](/official/Reference/VBA/HiddenModule/UnprotectedAccess) —— 返回绕过私有成员访问检查的对象引用 * [vbaAryMove](/official/Reference/VBA/HiddenModule/vbaAryMove) —— 将一个数组变量的内容移动到另一个中 * [vbaCastObj](/official/Reference/VBA/HiddenModule/vbaCastObj) —— 返回重新解释为另一个COM接口的对象 * [vbaCopyBytes](/official/Reference/VBA/HiddenModule/vbaCopyBytes) —— 将一个字节块从一个地址复制到另一个地址 * [vbaCopyBytesZero](/official/Reference/VBA/HiddenModule/vbaCopyBytesZero) —— 将一个字节块从一个地址复制到另一个地址,然后清零源 * [vbaObjAddref](/official/Reference/VBA/HiddenModule/vbaObjAddref) —— 递增给定地址对象的COM引用计数 * [vbaObjSet](/official/Reference/VBA/HiddenModule/vbaObjSet) —— 将对象指针赋值给对象变量,释放任何先前的引用 * [vbaObjSetAddref](/official/Reference/VBA/HiddenModule/vbaObjSetAddref) —— 将对象指针赋值给对象变量,添加引用并释放任何先前的引用 * [vbaRefVarAry](/official/Reference/VBA/HiddenModule/vbaRefVarAry) —— 返回**Variant**数组内部**SAFEARRAY**描述符的指针 ## IGetMessageHook接口 **IGetMessageHook**接口钩入选定窗口——以及可选的其后代——的Windows消息流,并将选定类型的消息转发到用户提供的回调。使用[**RuntimeCreateGetMessageHook**](/official/Reference/VBA/HiddenModule/RuntimeCreateGetMessageHook)获取实例;使用[**RegisterMessage**](/official/Reference/VBA/HiddenModule/RegisterMessage)连接回调;然后调用[**Start**](/official/Reference/VBA/HiddenModule/Start)激活所有已注册订阅,调用[**Stop**](/official/Reference/VBA/HiddenModule/Stop)移除订阅。 该接口直接继承自**stdole.IUnknown**(非基于分派),提供给**RegisterMessage**的回调类型为[**GetMessageHookHelper.GetMessageHandler**](#getmessagehandler)。 ```vb Const WM_LBUTTONDOWN = &H201 Sub Demo() Dim Hook As IGetMessageHook = RuntimeCreateGetMessageHook Hook.RegisterMessage Me.hWnd, AllDescendants, _ WM_LBUTTONDOWN, AddressOf OnLButtonDown Hook.Start End Sub Function OnLButtonDown(ByRef msg As GetMessageHookHelper.HookMSG) As LongPtr Debug.Print "Click at"; msg.pt.x, msg.pt.y ' Return zero to let the message continue normal processing. End Function ``` ### 成员 * [RegisterMessage](/official/Reference/VBA/HiddenModule/RegisterMessage) —— 为窗口和选定的后代范围订阅单个消息类型的回调 * [Start](/official/Reference/VBA/HiddenModule/Start) —— 激活所有已注册订阅 * [Stop](/official/Reference/VBA/HiddenModule/Stop) —— 停用所有已注册订阅 ### EnumDescendantsModeFlags 选择传递给[**RegisterMessage**](/official/Reference/VBA/HiddenModule/RegisterMessage)的窗口范围: | 常量 | 值 | 描述 | |-------------------------------------|-----|------| | **ExactWindow** | 1 | 仅钩住指定窗口。 | | **AllDescendants** | 2 | 钩住指定窗口及所有后代——子级、孙级等。 | | **DirectChildren** | 4 | 仅钩住指定窗口及其直接子级。 | ## GetMessageHookHelper模块 **GetMessageHookHelper**模块是[**IGetMessageHook**](#igetmessagehook-interface)的小型伴随模块,包含其回调使用的结构和委托类型。无需构造任何内容;这些名称仅用于声明。 ### HookMSG Windows `MSG`结构的副本,按引用传递给[**GetMessageHandler**](#getmessagehandler)回调。 ```vb Type HookMSG hwnd As LongPtr ' Window the message is destined for. message As Long ' The WM_* identifier. wParam As LongPtr ' Message-specific parameter. lParam As LongPtr ' Message-specific parameter. time As Long ' Time the message was posted, in milliseconds since system start. pt As HookPOINT ' Cursor position when the message was posted. End Type ``` ### HookPOINT 具有**Long**坐标的2D点,[**HookMSG**](#hookmsg)使用它来保存光标位置。 ```vb Type HookPOINT x As Long y As Long End Type ``` ### GetMessageHandler [**IGetMessageHook.RegisterMessage**](/official/Reference/VBA/HiddenModule/RegisterMessage)接受的回调签名。返回零通常让消息继续正常处理。 ```vb Public Delegate Function GetMessageHandler (ByRef msg As HookMSG) As LongPtr ``` --- --- url: /en/official/Reference/Core/Multiply.md --- # \* and \*= operators Used to multiply two numbers. The compound form **\*=** multiplies-and-assigns in one step. Syntax: > *result* **=** *number1* **\*** *number2*\ > *variable* **\*=** *number* *(twinBASIC)* *result* : Any numeric variable. *variable* : *(twinBASIC)* Any numeric variable or writable property. *number*, *number1*, *number2* : Any numeric expressions. The data type of *result* is usually the same as that of the most precise expression. The order of precision, from least to most precise, is **Byte**, **Integer**, **Long**, **LongLong**, **Single**, **Currency**, **Double**. The following are exceptions: | If | Then *result* is | |:-----------------------------------------------------------------------------------------|:---------------------------------------| | Multiplication involves a **Single** and a **Long** | Converted to a **Double**. | | *result* is a **Long**, **Single**, or **Date** variant that overflows its legal range | Converted to a **Variant** containing a **Double**. | | *result* is a **Byte** variant that overflows its legal range | Converted to an **Integer** variant. | | *result* is an **Integer** variant that overflows its legal range | Converted to a **Long** variant. | If one or both expressions are **Null** expressions, *result* is **Null**. If an expression is **Empty**, it is treated as 0. ::: info The order of precision used by multiplication is not the same as the order of precision used by addition and subtraction. ::: ### Compound assignment `x *= y` is the twinBASIC shorthand for `x = x * y`. The left-hand side is evaluated once; the result follows the same type-promotion and **Null** / **Empty** rules described above. **\*=** is a statement, not an expression --- it does not produce a value. ```vb Dim Value As Long = 3 Value *= 4 ' Value is now 12. Value *= 2 ' Value is now 24. ``` ### Example This example uses the **\*** operator to multiply two numbers. ```vb Dim MyValue MyValue = 2 * 2 ' Returns 4. MyValue = 459.35 * 334.90 ' Returns 153836.315. ``` ### See Also * [**/** operator](/en/official/Reference/Core/Divide) * [**\\** operator](/en/official/Reference/Core/IntegerDivide) * [**^** operator](/en/official/Reference/Core/Exponent) * [**+** operator](/en/official/Reference/Core/Plus) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Multiply.md --- # \* 和 \*= 运算符 用于将两个数相乘。复合形式\*\*\*=\*\*一步完成乘法并赋值。 语法: > *result* **=** *number1* **\*** *number2*\ > *variable* **\*=** *number* *(twinBASIC)* *result* : 任意数值变量。 *variable* : *(twinBASIC)* 任意数值变量或可写属性。 *number*, *number1*, *number2* : 任意数值表达式。 *result*的数据类型通常与最精确的表达式相同。精度从低到高的顺序为**Byte**、**Integer**、**Long**、**LongLong**、**Single**、**Currency**、**Double**。以下是例外情况: | 如果 | 则 *result* 为 | |:-----------------------------------------------------------------------------------------|:---------------------------------------| | 乘法涉及**Single**和**Long** | 转换为**Double**。 | | *result*是**Long**、**Single**或**Date**变体,溢出了其合法范围 | 转换为包含**Double**的**Variant**。 | | *result*是**Byte**变体,溢出了其合法范围 | 转换为**Integer**变体。 | | *result*是**Integer**变体,溢出了其合法范围 | 转换为**Long**变体。 | 如果一个或两个表达式为**Null**表达式,则*result*为**Null**。如果表达式为**Empty**,则视为0。 ::: info 乘法使用的精度顺序与加法和减法使用的精度顺序不同。 ::: ### 复合赋值 `x *= y`是twinBASIC中`x = x * y`的简写。左侧只计算一次;结果遵循上述相同的类型提升和**Null**/**Empty**规则。\*\*\*=\*\*是语句,不是表达式——它不产生值。 ```vb Dim Value As Long = 3 Value *= 4 ' Value is now 12. Value *= 2 ' Value is now 24. ``` ### 示例 本示例使用\*\*\*\*\*运算符将两个数相乘。 ```vb Dim MyValue MyValue = 2 * 2 ' Returns 4. MyValue = 459.35 * 334.90 ' Returns 153836.315. ``` ### 另请参阅 * [**/** 运算符](/official/Reference/Core/Divide) * [**\\** 运算符](/official/Reference/Core/IntegerDivide) * [**^** 运算符](/official/Reference/Core/Exponent) * [**+** 运算符](/official/Reference/Core/Plus) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Reference/Core/Divide.md --- # / and /= operators Used to divide two numbers and return a floating-point result. The compound form **/=** divides-and-assigns in one step. Syntax: > *result* **=** *number1* **/** *number2*\ > *variable* **/=** *number* *(twinBASIC)* *result* : Any numeric variable. *variable* : *(twinBASIC)* Any numeric variable or writable property. *number*, *number1*, *number2* : Any numeric expressions. The data type of *result* is usually a **Double** or a **Double** variant. The following are exceptions: | If | Then *result* is | |:----------------------------------------------------------------|:---------------------------------------------------------------------------------------| | Both expressions are **Byte**, **Integer**, or **Single** | A **Single** unless it overflows its legal range, in which case an error occurs. | | Both expressions are **Byte**, **Integer**, or **Single** variants | A **Single** variant unless it overflows its legal range, in which case *result* is a **Variant** containing a **Double**. | If one or both expressions are **Null** expressions, *result* is **Null**. Any expression that is **Empty** is treated as 0. Dividing by zero is an error for integral types; for **Single** and **Double** it follows the IEEE-754 rules (positive infinity, negative infinity, or NaN). Use [**\\**](/en/official/Reference/Core/IntegerDivide) for truncating-integer division and [**Mod**](/en/official/Reference/Core/Mod) for remainder. ### Compound assignment `x /= y` is the twinBASIC shorthand for `x = x / y`. The left-hand side is evaluated once; the result follows the same type-promotion and **Null** / **Empty** rules described above. **/=** is a statement, not an expression --- it does not produce a value. ```vb Dim Value As Double = 100 Value /= 4 ' Value is now 25. Value /= 5 ' Value is now 5. ``` ### Example This example uses the **/** operator to perform floating-point division. ```vb Dim MyValue MyValue = 10 / 4 ' Returns 2.5. MyValue = 10 / 3 ' Returns 3.333333... ``` ### See Also * [**\\** operator](/en/official/Reference/Core/IntegerDivide) * [**Mod** operator](/en/official/Reference/Core/Mod) * [**\*** operator](/en/official/Reference/Core/Multiply) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Divide.md --- # / 和 /= 运算符 用于将两个数相除并返回浮点结果。复合形式 **/=** 在一步中完成相除并赋值。 语法: > *result* **=** *number1* **/** *number2*\ > *variable* **/=** *number* *(twinBASIC)* *result* : 任意数值变量。 *variable* : *(twinBASIC)* 任意数值变量或可写属性。 *number*, *number1*, *number2* : 任意数值表达式。 *result* 的数据类型通常为 **Double** 或 **Double** 变体。以下是例外: | 如果 | 则 *result* 为 | |:----------------------------------------------------------------|:---------------------------------------------------------------------------------------| | 两个表达式都是 **Byte**、**Integer** 或 **Single** | **Single**,除非溢出其合法范围,此时将发生错误。 | | 两个表达式都是 **Byte**、**Integer** 或 **Single** 变体 | **Single** 变体,除非溢出其合法范围,此时 *result* 为包含 **Double** 的 **Variant**。 | 如果一个或两个表达式为 **Null**,则 *result* 为 **Null**。任何为 **Empty** 的表达式被视为0。 对整数类型除以零是错误;对于 **Single** 和 **Double** 遵循IEEE-754规则(正无穷、负无穷或NaN)。使用 [**\\**](/official/Reference/Core/IntegerDivide) 进行截断整数除法,使用 [**Mod**](/official/Reference/Core/Mod) 求余数。 ### 复合赋值 `x /= y` 是twinBASIC中 `x = x / y` 的简写。左侧仅求值一次;结果遵循上述相同的类型提升和 **Null** / **Empty** 规则。**/=** 是语句而非表达式——它不产生值。 ```vb Dim Value As Double = 100 Value /= 4 ' Value is now 25. Value /= 5 ' Value is now 5. ``` ### 示例 本示例使用 **/** 运算符执行浮点除法。 ```vb Dim MyValue MyValue = 10 / 4 ' Returns 2.5. MyValue = 10 / 3 ' Returns 3.333333... ``` ### 另请参阅 * [**\\** 运算符](/official/Reference/Core/IntegerDivide) * [**Mod** 运算符](/official/Reference/Core/Mod) * [**\*** 运算符](/official/Reference/Core/Multiply) * [运算符](/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/IntegerDivide.md --- # \ 和 = 运算符 用于将两个数相除并返回整数结果。复合形式 **\\=** 在一步中完成相除并赋值。 语法: > *result* **=** *number1* **\\** *number2*\ > *variable* **\\=** *number* *(twinBASIC)* *result* : 任意数值变量。 *variable* : *(twinBASIC)* 任意数值变量或可写属性。 *number*, *number1*, *number2* : 任意数值表达式。 执行除法之前,数值表达式被舍入为 **Byte**、**Integer**、**Long** 或 **LongLong** 表达式。 通常,*result* 的数据类型为 **Byte**、**Byte** 变体、**Integer**、**Integer** 变体、**Long**、**Long** 变体或 **LongLong**,无论 *result* 是否为整数。 任何小数部分被截断。但如果任一表达式为 **Null**,则 *result* 为 **Null**。任何为 **Empty** 的表达式被视为0。 除以零会引发运行时错误。 ### 复合赋值 `x \= y` 是twinBASIC中 `x = x \ y` 的简写。左侧仅求值一次并按上述方式舍入为整数类型。**\\=** 是语句而非表达式——它不产生值。 ```vb Dim Value As Long = 100 Value \= 4 ' Value is now 25. Value \= 7 ' Value is now 3 (truncating). ``` ### 示例 本示例使用 **\\** 运算符执行整数除法。 ```vb Dim MyValue MyValue = 11 \ 4 ' Returns 2. MyValue = 9 \ 3 ' Returns 3. MyValue = 100 \ 3 ' Returns 33. ``` ### 另请参阅 * [**/** 运算符](/official/Reference/Core/Divide) * [**Mod** 运算符](/official/Reference/Core/Mod) * [运算符](/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Concat.md --- # & 和 &= 运算符 用于强制连接两个字符串表达式。复合形式 **&=** 在一步中完成连接并赋值。 语法: > *result* **=** *expression1* **&** *expression2*\ > *variable* **&=** *expression* *(twinBASIC)* *result* : 任意 **String** 或 **Variant** 变量。 *variable* : *(twinBASIC)* 任意 **String** 或 **Variant** 变量,或这些类型的可写属性。 *expression*, *expression1*, *expression2* : 任意表达式。 如果 *expression* 不是字符串,则转换为 **String** 变体。如果两个 *expression* 都是字符串表达式,*result* 的数据类型为 **String**;否则 *result* 为 **String** 变体。 如果两个表达式都是 **Null**,*result* 为 **Null**。但是,如果只有一个 *expression* 为 **Null**,则该表达式在与另一个表达式连接时被视为零长度字符串(`""`)。任何为 **Empty** 的表达式也被视为零长度字符串。 连接字符串时优先使用 **&** 而非 [**+**](/official/Reference/Core/Plus):**+** 也是加法运算符,因此其含义取决于操作数类型,可能在算术运算和连接之间静默切换。**&** 是明确的——它总是连接。 ::: info 当 **&** 紧跟在变量名之后时(例如 `x&`),它会被解析为标识符上的 **Long** 类型后缀而非连接运算符。连接时务必在 **&** 前加空格:`Result = x & y`,而非 `Result = x& y`。 ::: ### 复合赋值 `x &= y` 是twinBASIC中 `x = x & y` 的简写。*y* 在追加前转换为 **String**;如果两边都已是 **String**,结果仍为 **String**。**&=** 是语句而非表达式——它不产生值。 ```vb Dim Path As String = "C:\Users" Path &= "\Public" ' Path is now "C:\Users\Public". Path &= "\Documents" ' Path is now "C:\Users\Public\Documents". ``` ### 示例 本示例使用 **&** 运算符强制连接字符串。 ```vb Dim MyStr MyStr = "Hello" & " World" ' Returns "Hello World". MyStr = "Check " & 123 & " Check" ' Returns "Check 123 Check". ``` ### 另请参阅 * [**+** 运算符](/official/Reference/Core/Plus) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Reference/Core/Concat.md --- # & and &= operators Used to force string concatenation of two expressions. The compound form **&=** concatenates-and-assigns in one step. Syntax: > *result* **=** *expression1* **&** *expression2*\ > *variable* **&=** *expression* *(twinBASIC)* *result* : Any **String** or **Variant** variable. *variable* : *(twinBASIC)* Any **String** or **Variant** variable, or any writable property of those types. *expression*, *expression1*, *expression2* : Any expressions. If an *expression* is not a string, it is converted to a **String** variant. The data type of *result* is **String** if both *expressions* are string expressions; otherwise, *result* is a **String** variant. If both expressions are **Null**, *result* is **Null**. However, if only one *expression* is **Null**, that expression is treated as a zero-length string (`""`) when concatenated with the other expression. Any expression that is **Empty** is also treated as a zero-length string. Prefer **&** over [**+**](/en/official/Reference/Core/Plus) for joining strings: **+** is also the addition operator, so its meaning depends on the operand types and can silently switch between arithmetic and concatenation. **&** is unambiguous --- it always concatenates. ::: info When **&** immediately follows a variable name (for example `x&`), it is parsed as the **Long** type-suffix on the identifier rather than the concatenation operator. Always put a space before **&** when concatenating: `Result = x & y`, not `Result = x& y`. ::: ### Compound assignment `x &= y` is the twinBASIC shorthand for `x = x & y`. *y* is converted to **String** before being appended; if both sides are already **String**, the result stays **String**. **&=** is a statement, not an expression --- it does not produce a value. ```vb Dim Path As String = "C:\Users" Path &= "\Public" ' Path is now "C:\Users\Public". Path &= "\Documents" ' Path is now "C:\Users\Public\Documents". ``` ### Example This example uses the **&** operator to force string concatenation. ```vb Dim MyStr MyStr = "Hello" & " World" ' Returns "Hello World". MyStr = "Check " & 123 & " Check" ' Returns "Check 123 Check". ``` ### See Also * [**+** operator](/en/official/Reference/Core/Plus) * [Operators](/en/official/Reference/Operators) --- --- url: /en/official/Reference/Core/IntegerDivide.md --- # \ and = operators Used to divide two numbers and return an integer result. The compound form **\\=** divides-and-assigns in one step. Syntax: > *result* **=** *number1* **\\** *number2*\ > *variable* **\\=** *number* *(twinBASIC)* *result* : Any numeric variable. *variable* : *(twinBASIC)* Any numeric variable or writable property. *number*, *number1*, *number2* : Any numeric expressions. Before division is performed, the numeric expressions are rounded to **Byte**, **Integer**, **Long**, or **LongLong** expressions. Usually, the data type of *result* is a **Byte**, **Byte** variant, **Integer**, **Integer** variant, **Long**, **Long** variant, or **LongLong**, regardless of whether *result* is a whole number. Any fractional portion is truncated. However, if any expression is **Null**, *result* is **Null**. Any expression that is **Empty** is treated as 0. Dividing by zero raises a run-time error. ### Compound assignment `x \= y` is the twinBASIC shorthand for `x = x \ y`. The left-hand side is evaluated once and rounded to an integral type as described above. **\\=** is a statement, not an expression --- it does not produce a value. ```vb Dim Value As Long = 100 Value \= 4 ' Value is now 25. Value \= 7 ' Value is now 3 (truncating). ``` ### Example This example uses the **\\** operator to perform integer division. ```vb Dim MyValue MyValue = 11 \ 4 ' Returns 2. MyValue = 9 \ 3 ' Returns 3. MyValue = 100 \ 3 ' Returns 33. ``` ### See Also * [**/** operator](/en/official/Reference/Core/Divide) * [**Mod** operator](/en/official/Reference/Core/Mod) * [Operators](/en/official/Reference/Operators) --- --- url: /en/official/Reference/Core/RightShift.md --- # >> and >>= operators *(twinBASIC)* Shifts the bits of a numeric value right by a given number of positions, filling vacated high-order bits with zero. The compound form **>>=** shifts-and-assigns in one step. ::: info **>>** and **>>=** are twinBASIC extensions. Classic VBA has no bitshift operators; equivalent code divides by powers of two with [**\\\\**](/en/official/Reference/Core/IntegerDivide) (`x \ 2`, `x \ 4`, …). ::: Syntax: > *result* **=** *number* **>>** *count*\ > *variable* **>>=** *count* *result* : Any numeric variable. *variable* : Any numeric variable or writable property. *number* : Any numeric expression. Floating-point operands are truncated to an integer before shifting. *count* : Any numeric expression giving the number of bit positions to shift. The data type of *result* matches the (integral) type of *number*. The right shift is *logical*, not arithmetic: vacated high-order bits are filled with zero, so a negative *number* becomes a large positive value rather than retaining its sign. A shift of more bits than the type can hold yields `0`. ### Compound assignment `x >>= n` is the twinBASIC shorthand for `x = x >> n`. **>>=** is a statement, not an expression --- it does not produce a value. ```vb Dim Flags As Long = &H100 Flags >>= 4 ' Flags is now &H10 (16). Flags >>= 4 ' Flags is now 1. ``` ### Example ```vb Dim Value As Long Value = 16 >> 0 ' Returns 16. Value = 16 >> 4 ' Returns 1. Value = 1024 >> 3 ' Returns 128. Value = -1 >> 1 ' Returns &H7FFFFFFF (logical shift fills with 0). ``` ### See Also * [**<<** operator](/en/official/Reference/Core/LeftShift) * [**\\** operator](/en/official/Reference/Core/IntegerDivide) * [**And** operator](/en/official/Reference/Core/And) * [Operators](/en/official/Reference/Operators) --- --- url: /en/official/Reference/Core/LeftShift.md --- # << and <<= operators *(twinBASIC)* Shifts the bits of a numeric value left by a given number of positions, filling vacated low-order bits with zero. The compound form **<<=** shifts-and-assigns in one step. ::: info **<<** and **<<=** are twinBASIC extensions. Classic VBA has no bitshift operators; equivalent code multiplies by powers of two (`x * 2`, `x * 4`, …) and relies on overflow rules. ::: Syntax: > *result* **=** *number* **<<** *count*\ > *variable* **<<=** *count* *result* : Any numeric variable. *variable* : Any numeric variable or writable property. *number* : Any numeric expression. Floating-point operands are truncated to an integer before shifting. *count* : Any numeric expression giving the number of bit positions to shift. The data type of *result* matches the (integral) type of *number*. A shift of more bits than the type can hold yields `0` rather than wrapping. The sign bit is *not* preserved --- `<<` is a logical left shift, equivalent to multiplication by 2*count* within the available width. ### Compound assignment `x <<= n` is the twinBASIC shorthand for `x = x << n`. **<<=** is a statement, not an expression --- it does not produce a value. ```vb Dim Mask As Long = 1 Mask <<= 4 ' Mask is now &H10 (16). Mask <<= 4 ' Mask is now &H100 (256). ``` ### Example ```vb Dim Value As Long Value = 1 << 0 ' Returns 1. Value = 1 << 4 ' Returns 16. Value = 3 << 8 ' Returns 768. Value = 1 << 33 ' Returns 0 (shift exceeds Long width). ``` ### See Also * [**>>** operator](/en/official/Reference/Core/RightShift) * [**And** operator](/en/official/Reference/Core/And) * [**Or** operator](/en/official/Reference/Core/Or) * [Operators](/en/official/Reference/Operators) --- --- url: /en/official/Reference/Core/Topic-Preprocessor.md --- # #If...Then...#Else, #Const directives Compiler directives that conditionally include or exclude blocks of code at *compile time*, and define the constants those conditions are tested against. Unlike runtime [**If...Then...Else**](/en/official/Reference/Core/If-Then-Else) and [**Const**](/en/official/Reference/Core/Const), the directives operate during compilation: code in an inactive branch is omitted entirely from the compiled output and contributes no size or runtime cost. ## #If...Then...#Else directive Syntax: > **#If** *expression* **Then**\ >     *statements*\ > \[ **#ElseIf** *expression-n* **Then**\ >     \[ *elseifstatements* ] ] ...\ > \[ **#Else**\ >     \[ *elsestatements* ] ]\ > **#End If** *expression*, *expression-n* : An expression composed exclusively of conditional compiler constants, literals, and operators, evaluating to **True** or **False**. *statements*, *elseifstatements*, *elsestatements* : Source lines or further compiler directives included when the corresponding *expression* is **True**. The directive's behaviour mirrors the runtime [**If...Then...Else**](/en/official/Reference/Core/If-Then-Else) statement, with the following differences: * There is no single-line form --- `#If`, `#ElseIf`, `#Else`, and `#End If` must each appear on their own line. * All *expressions* are evaluated regardless of which branch is selected, so every constant they reference must be defined. Undefined conditional compiler constants evaluate as **Empty** (i.e. zero), which is treated as **False**. * Code in unselected branches is *removed* from the compilation rather than skipped at runtime. In twinBASIC, inactive code is not even checked for errors. The IDE greys out inactive blocks based on the current build configuration. ::: info The [**Option Compare**](/en/official/Reference/Core/Option) statement does not affect expressions in `#If`/`#ElseIf`. They are always evaluated as if **Option Compare Text** were in effect. ::: ## #Const directive Syntax: > **#Const** *constname* **=** *expression* *constname* : Name of the conditional compiler constant; follows standard variable naming conventions. *expression* : A literal, another conditional compiler constant, or any combination using arithmetic or logical operators (except [**Is**](/en/official/Reference/Core/Is)). Standard runtime constants (declared with [**Const**](/en/official/Reference/Core/Const)) are *not* allowed here. Conditional compiler constants declared with `#Const` are private to the module in which they appear. Project-wide conditional constants must be defined in the project's compilation settings --- `#Const` cannot create them. Conditional compiler constants are always evaluated at the module level regardless of where they appear in code; they can only be used in `#If`/`#ElseIf` expressions. ## Predefined compiler constants twinBASIC provides a set of built-in compiler constants --- `Win64`, `Win32`, `TWINBASIC`, `TWINBASIC_BUILD`, `VBA7`, etc. See the dedicated [Compiler Constants](/en/official/Reference/Compiler-Constants) page for the full list and what each one means. ### Example This example uses the `Win64` predefined constant to select platform-specific imports, and a project-defined `DEBUG_BUILD` constant to enable extra logging only in debug builds. ```vb #Const DEBUG_BUILD = 1 #If Win64 Then ' 64-bit-only declarations. Import Library "/Miscellaneous/sqlite3_64.obj" As SQLITE3 #Else ' 32-bit fallback. Import Library "/Miscellaneous/sqlite3_32.obj" As SQLITE3 #End If Public Sub DoWork() #If DEBUG_BUILD Then Debug.Print "Entering DoWork at "; Now #End If ' ... End Sub ``` ### See Also * [**If...Then...Else** statement](/en/official/Reference/Core/If-Then-Else) -- the runtime counterpart. * [**Const** statement](/en/official/Reference/Core/Const) -- the runtime counterpart of **#Const**. * [Compiler Constants](/en/official/Reference/Compiler-Constants) -- the full list of built-in conditional constants. --- --- url: /zh/official/Reference/Core/Topic-Preprocessor.md --- # #If...Then...#Else、#Const 指令 在*编译时*有条件地包含或排除代码块的编译器指令,并定义用于测试这些条件的常量。与运行时的[**If...Then...Else**](/official/Reference/Core/If-Then-Else)和[**Const**](/official/Reference/Core/Const)不同,这些指令在编译期间操作:非活动分支中的代码从编译输出中完全省略,不产生大小或运行时开销。 ## #If...Then...#Else 指令 语法: > **#If** *expression* **Then**\ >     *statements*\ > \[ **#ElseIf** *expression-n* **Then**\ >     \[ *elseifstatements* ] ] ...\ > \[ **#Else**\ >     \[ *elsestatements* ] ]\ > **#End If** *expression*, *expression-n* : 完全由条件编译常量、字面量和运算符组成的表达式,计算结果为**True**或**False**。 *statements*, *elseifstatements*, *elsestatements* : 当对应*expression*为**True**时包含的源代码行或进一步的编译器指令。 该指令的行为与运行时[**If...Then...Else**](/official/Reference/Core/If-Then-Else)语句类似,但有以下差异: * 没有单行形式——`#If`、`#ElseIf`、`#Else`和`#End If`必须各自出现在单独的行上。 * 所有*expressions*都会被计算,无论选择了哪个分支,因此它们引用的每个常量都必须已定义。未定义的条件编译常量计算为**Empty**(即零),被视为**False**。 * 未选择分支中的代码从编译中*移除*而非在运行时跳过。在twinBASIC中,非活动代码甚至不被检查错误。IDE根据当前构建配置将非活动块显示为灰色。 ::: info [**Option Compare**](/official/Reference/Core/Option)语句不影响`#If`/`#ElseIf`中的表达式。它们始终按**Option Compare Text**生效来计算。 ::: ## #Const 指令 语法: > **#Const** *constname* **=** *expression* *constname* : 条件编译常量的名称;遵循标准变量命名约定。 *expression* : 字面量、另一个条件编译常量,或使用算术或逻辑运算符([**Is**](/official/Reference/Core/Is)除外)的任意组合。不允许使用标准运行时常量(用[**Const**](/official/Reference/Core/Const)声明的)。 使用`#Const`声明的条件编译常量对其出现的模块是私有的。项目范围的条件常量必须在项目的编译设置中定义——`#Const`不能创建它们。 条件编译常量始终在模块级计算,无论它们出现在代码中的什么位置;它们只能在`#If`/`#ElseIf`表达式中使用。 ## 预定义编译器常量 twinBASIC提供了一组内置编译器常量——`Win64`、`Win32`、`TWINBASIC`、`TWINBASIC_BUILD`、`VBA7`等。完整列表及各常量的含义请参见[编译器常量](/official/Reference/Compiler-Constants)页面。 ### 示例 本示例使用`Win64`预定义常量选择特定平台的导入,并使用项目定义的`DEBUG_BUILD`常量仅在调试构建中启用额外日志记录。 ```vb #Const DEBUG_BUILD = 1 #If Win64 Then ' 64-bit-only declarations. Import Library "/Miscellaneous/sqlite3_64.obj" As SQLITE3 #Else ' 32-bit fallback. Import Library "/Miscellaneous/sqlite3_32.obj" As SQLITE3 #End If Public Sub DoWork() #If DEBUG_BUILD Then Debug.Print "Entering DoWork at "; Now #End If ' ... End Sub ``` ### 另请参阅 * [**If...Then...Else** 语句](/official/Reference/Core/If-Then-Else)——运行时对应语句。 * [**Const** 语句](/official/Reference/Core/Const)——**#Const**的运行时对应语句。 * [编译器常量](/official/Reference/Compiler-Constants)——内置条件常量完整列表。 --- --- url: /en/official/Reference/Core/Exponent.md --- # ^ and ^= operators Used to raise a number to the power of an exponent. The compound form **^=** raises-and-assigns in one step. Syntax: > *result* **=** *number* **^** *exponent*\ > *variable* **^=** *exponent* *(twinBASIC)* *result* : Any numeric variable. *variable* : *(twinBASIC)* Any numeric variable or writable property. *number*, *exponent* : Any numeric expressions. *number* can be negative only if *exponent* is an integer value. When more than one exponentiation is performed in a single expression, the **^** operator is evaluated as it is encountered from left to right. Usually, the data type of *result* is a **Double** or a **Variant** containing a **Double**. However, if either *number* or *exponent* is a **Null** expression, *result* is **Null**. ### Compound assignment `x ^= y` is the twinBASIC shorthand for `x = x ^ y`. The left-hand side is evaluated once; the result follows the same type-promotion and **Null** rules described above. **^=** is a statement, not an expression --- it does not produce a value. ```vb Dim Value As Double = 2 Value ^= 3 ' Value is now 8. Value ^= 2 ' Value is now 64. ``` ### Example This example uses the **^** operator to raise a number to the power of an exponent. ```vb Dim MyValue MyValue = 2 ^ 2 ' Returns 4. MyValue = 3 ^ 3 ^ 3 ' Returns 19683 (evaluated left-to-right as (3^3)^3). MyValue = (-5) ^ 3 ' Returns -125. ``` ### See Also * [**\*** operator](/en/official/Reference/Core/Multiply) * [**/** operator](/en/official/Reference/Core/Divide) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Exponent.md --- # ^ 和 ^= 运算符 用于将数提高到指数幂。复合形式 **^=** 在一步中完成求幂并赋值。 语法: > *result* **=** *number* **^** *exponent*\ > *variable* **^=** *exponent* *(twinBASIC)* *result* : 任意数值变量。 *variable* : *(twinBASIC)* 任意数值变量或可写属性。 *number*, *exponent* : 任意数值表达式。 只有当 *exponent* 为整数值时,*number* 才可以为负数。当在单个表达式中执行多次求幂时,**^** 运算符按从左到右的顺序求值。 通常,*result* 的数据类型为 **Double** 或包含 **Double** 的 **Variant**。但如果 *number* 或 *exponent* 为 **Null** 表达式,则 *result* 为 **Null**。 ### 复合赋值 `x ^= y` 是twinBASIC中 `x = x ^ y` 的简写。左侧仅求值一次;结果遵循上述相同的类型提升和 **Null** 规则。**^=** 是语句而非表达式——它不产生值。 ```vb Dim Value As Double = 2 Value ^= 3 ' Value is now 8. Value ^= 2 ' Value is now 64. ``` ### 示例 本示例使用 **^** 运算符将数提高到指数幂。 ```vb Dim MyValue MyValue = 2 ^ 2 ' Returns 4. MyValue = 3 ^ 3 ^ 3 ' Returns 19683 (evaluated left-to-right as (3^3)^3). MyValue = (-5) ^ 3 ' Returns -125. ``` ### 另请参阅 * [**\*** 运算符](/official/Reference/Core/Multiply) * [**/** 运算符](/official/Reference/Core/Divide) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Reference/Core/Plus.md --- # + and += operators Used to sum two numbers, or --- depending on operand types --- to concatenate two strings. The compound form **+=** adds-and-assigns in one step. Syntax: > *result* **=** *expression1* **+** *expression2*\ > *variable* **+=** *expression* *(twinBASIC)* *result* : Any numeric variable. *variable* : *(twinBASIC)* Any numeric or **String** variable, or any writable property. *expression*, *expression1*, *expression2* : Any expressions. When the **+** operator is used, it may not be obvious whether addition or string concatenation will occur. Use the [**&**](/en/official/Reference/Core/Concat) operator for concatenation to eliminate ambiguity and produce self-documenting code. If at least one expression is not a **Variant**, the following rules apply: | If | Then | |:--------------------------------------------------------------------------------|:------------------------------------------------------| | Both expressions are numeric (**Byte**, **Boolean**, **Integer**, **Long**, **LongLong**, **LongPtr**, **Single**, **Double**, **Date**, **Currency**) | Add. | | Both expressions are **String** | Concatenate. | | One expression is numeric and the other is any **Variant** except **Null** | Add. | | One expression is **String** and the other is any **Variant** except **Null** | Concatenate. | | One expression is an **Empty** **Variant** | Return the remaining expression unchanged as *result*.| | One expression is numeric and the other is a **String** | A `Type mismatch` error occurs. | | Either expression is **Null** | *result* is **Null**. | If both expressions are **Variant** expressions, the following rules apply: | If | Then | |:----------------------------------------------------------------|:-------------| | Both **Variant** expressions are numeric | Add. | | Both **Variant** expressions are strings | Concatenate. | | One **Variant** expression is numeric and the other is a string | Add. | For simple arithmetic addition involving only numeric expressions, the data type of *result* is usually the same as that of the most precise expression. The order of precision, from least to most precise, is **Byte**, **Integer**, **Long**, **LongLong**, **Single**, **Double**, **Currency**. The following are exceptions: | If | Then *result* is | |:------------------------------------------------------------------------------------------|:----------------------------------| | A **Single** and a **Long** are added | A **Double**. | | *result* is a **Long**, **Single**, or **Date** variant that overflows its legal range | Converted to a **Double** variant.| | *result* is a **Byte** variant that overflows its legal range | Converted to an **Integer** variant.| | *result* is an **Integer** variant that overflows its legal range | Converted to a **Long** variant. | | A **Date** is added to any data type | A **Date**. | If one or both expressions are **Null** expressions, *result* is **Null**. If both expressions are **Empty**, *result* is an **Integer**. However, if only one expression is **Empty**, the other expression is returned unchanged as *result*. ::: info The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication. ::: ### Compound assignment `x += y` is the twinBASIC shorthand for `x = x + y`. The left-hand side is evaluated once; the result follows the same type-promotion and **Null** / **Empty** rules described above. Like all of twinBASIC's compound-assignment operators, **+=** is a statement, not an expression --- it does not produce a value. ```vb Dim Total As Long = 0 Total += 5 ' Total is now 5. Total += 7 ' Total is now 12. Dim Greeting As String = "Hello" Greeting += ", world" ' Greeting is now "Hello, world". ``` ### Example This example uses the **+** operator to sum numbers. The **+** operator can also be used to concatenate strings, but to eliminate ambiguity use the [**&**](/en/official/Reference/Core/Concat) operator instead. ```vb Dim MyNumber, Var1, Var2 MyNumber = 2 + 2 ' Returns 4. MyNumber = 4257.04 + 98112 ' Returns 102369.04. Var1 = "34": Var2 = 6 ' Initialize mixed variables. MyNumber = Var1 + Var2 ' Returns 40. Var1 = "34": Var2 = "6" ' Initialize variables with strings. MyNumber = Var1 + Var2 ' Returns "346" (string concatenation). ``` ### See Also * [**-** operator](/en/official/Reference/Core/Minus) * [**&** operator](/en/official/Reference/Core/Concat) * [**\*** operator](/en/official/Reference/Core/Multiply) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Plus.md --- # + 和 += 运算符 用于将两个数相加,或——取决于操作数类型——连接两个字符串。复合形式\*\*+=\*\*一步完成加法并赋值。 语法: > *result* **=** *expression1* **+** *expression2*\ > *variable* **+=** *expression* *(twinBASIC)* *result* : 任意数值变量。 *variable* : *(twinBASIC)* 任意数值或**String**变量,或任何可写属性。 *expression*, *expression1*, *expression2* : 任意表达式。 使用\*\*+\*\*运算符时,可能不清楚是执行加法还是字符串连接。使用[**&**](/official/Reference/Core/Concat)运算符进行连接可以消除歧义并产生自文档化的代码。 如果至少有一个表达式不是**Variant**,则适用以下规则: | 如果 | 则 | |:--------------------------------------------------------------------------------|:------------------------------------------------------| | 两个表达式均为数值(**Byte**、**Boolean**、**Integer**、**Long**、**LongLong**、**LongPtr**、**Single**、**Double**、**Date**、**Currency**) | 相加。 | | 两个表达式均为**String** | 连接。 | | 一个表达式为数值,另一个为除**Null**外的任意**Variant** | 相加。 | | 一个表达式为**String**,另一个为除**Null**外的任意**Variant** | 连接。 | | 一个表达式为**Empty** **Variant** | 返回另一个表达式不变作为*result*。| | 一个表达式为数值,另一个为**String** | 产生`Type mismatch`错误。 | | 任一表达式为**Null** | *result*为**Null**。 | 如果两个表达式均为**Variant**表达式,则适用以下规则: | 如果 | 则 | |:----------------------------------------------------------------|:-------------| | 两个**Variant**表达式均为数值 | 相加。 | | 两个**Variant**表达式均为字符串 | 连接。 | | 一个**Variant**表达式为数值,另一个为字符串 | 相加。 | 对于仅涉及数值表达式的简单算术加法,*result*的数据类型通常与最精确的表达式相同。精度从低到高的顺序为**Byte**、**Integer**、**Long**、**LongLong**、**Single**、**Double**、**Currency**。以下是例外情况: | 如果 | 则 *result* 为 | |:------------------------------------------------------------------------------------------|:----------------------------------| | **Single**和**Long**相加 | **Double**。 | | *result*是**Long**、**Single**或**Date**变体,溢出了其合法范围 | 转换为**Double**变体。| | *result*是**Byte**变体,溢出了其合法范围 | 转换为**Integer**变体。| | *result*是**Integer**变体,溢出了其合法范围 | 转换为**Long**变体。 | | **Date**与任何数据类型相加 | **Date**。 | 如果一个或两个表达式为**Null**表达式,则*result*为**Null**。如果两个表达式均为**Empty**,则*result*为**Integer**。但是,如果仅一个表达式为**Empty**,则返回另一个表达式不变作为*result*。 ::: info 加法和减法使用的精度顺序与乘法使用的精度顺序不同。 ::: ### 复合赋值 `x += y`是twinBASIC中`x = x + y`的简写。左侧只计算一次;结果遵循上述相同的类型提升和**Null**/**Empty**规则。与所有twinBASIC的复合赋值运算符一样,\*\*+=\*\*是语句,不是表达式——它不产生值。 ```vb Dim Total As Long = 0 Total += 5 ' Total is now 5. Total += 7 ' Total is now 12. Dim Greeting As String = "Hello" Greeting += ", world" ' Greeting is now "Hello, world". ``` ### 示例 本示例使用\*\*+**运算符对数求和。**+\*\*运算符也可用于连接字符串,但为了消除歧义,请改用[**&**](/official/Reference/Core/Concat)运算符。 ```vb Dim MyNumber, Var1, Var2 MyNumber = 2 + 2 ' Returns 4. MyNumber = 4257.04 + 98112 ' Returns 102369.04. Var1 = "34": Var2 = 6 ' Initialize mixed variables. MyNumber = Var1 + Var2 ' Returns 40. Var1 = "34": Var2 = "6" ' Initialize variables with strings. MyNumber = Var1 + Var2 ' Returns "346" (string concatenation). ``` ### 另请参阅 * [**-** 运算符](/official/Reference/Core/Minus) * [**&** 运算符](/official/Reference/Core/Concat) * [**\*** 运算符](/official/Reference/Core/Multiply) * [运算符](/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/LeftShift.md --- # << 和 <<= 运算符 *(twinBASIC)* 将数值的位向左移动指定位置数,空出的低位用零填充。复合形式 **<<=** 在一步中完成移位并赋值。 ::: info **<<** 和 **<<=** 是twinBASIC扩展。经典VBA没有位移运算符;等价代码通过乘以2的幂(`x * 2`、`x * 4`、…)并依赖溢出规则实现。 ::: 语法: > *result* **=** *number* **<<** *count*\ > *variable* **<<=** *count* *result* : 任意数值变量。 *variable* : 任意数值变量或可写属性。 *number* : 任意数值表达式。浮点操作数在移位前被截断为整数。 *count* : 给出移位位数的任意数值表达式。 *result* 的数据类型与 *number* 的(整数)类型匹配。移位超过类型可容纳的位数时产生 `0` 而非环绕。符号位*不保留*——`<<` 是逻辑左移,等效于在可用宽度内乘以2*count*。 ### 复合赋值 `x <<= n` 是twinBASIC中 `x = x << n` 的简写。**<<=** 是语句而非表达式——它不产生值。 ```vb Dim Mask As Long = 1 Mask <<= 4 ' Mask is now &H10 (16). Mask <<= 4 ' Mask is now &H100 (256). ``` ### 示例 ```vb Dim Value As Long Value = 1 << 0 ' Returns 1. Value = 1 << 4 ' Returns 16. Value = 3 << 8 ' Returns 768. Value = 1 << 33 ' Returns 0 (shift exceeds Long width). ``` ### 另请参阅 * [**>>** 运算符](/official/Reference/Core/RightShift) * [**And** 运算符](/official/Reference/Core/And) * [**Or** 运算符](/official/Reference/Core/Or) * [运算符](/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/RightShift.md --- # >> 和 >>= 运算符 *(twinBASIC)* 将数值的位向右移动指定位置数,空出的高位用零填充。复合形式\*\*>>=\*\*一步完成移位并赋值。 ::: info \*\*>>**和**>>=\*\*是twinBASIC扩展。经典VBA没有位移运算符;等效代码使用[**\\\\**](/official/Reference/Core/IntegerDivide)除以2的幂(`x \ 2`、`x \ 4`等)。 ::: 语法: > *result* **=** *number* **>>** *count*\ > *variable* **>>=** *count* *result* : 任意数值变量。 *variable* : 任意数值变量或可写属性。 *number* : 任意数值表达式。浮点操作数在移位前截断为整数。 *count* : 给出要移位的位数的任意数值表达式。 *result*的数据类型匹配*number*的(整数)类型。右移是*逻辑*移位,不是算术移位:空出的高位用零填充,因此负的*number*变为大的正值而非保留符号。移位超过类型能容纳的位数产生`0`。 ### 复合赋值 `x >>= n`是twinBASIC中`x = x >> n`的简写。\*\*>>=\*\*是语句,不是表达式——它不产生值。 ```vb Dim Flags As Long = &H100 Flags >>= 4 ' Flags is now &H10 (16). Flags >>= 4 ' Flags is now 1. ``` ### 示例 ```vb Dim Value As Long Value = 16 >> 0 ' Returns 16. Value = 16 >> 4 ' Returns 1. Value = 1024 >> 3 ' Returns 128. Value = -1 >> 1 ' Returns &H7FFFFFFF (logical shift fills with 0). ``` ### 另请参阅 * [**<<** 运算符](/official/Reference/Core/LeftShift) * [**\\** 运算符](/official/Reference/Core/IntegerDivide) * [**And** 运算符](/official/Reference/Core/And) * [运算符](/official/Reference/Operators) --- --- url: /zh/official/Features/64bit.md --- # 64位编译 twinBASIC 除了编译 32 位外,还能编译原生 64 位可执行文件。其语法兼容 VBA7:使用 `LongPtr` 数据类型和标记 API 的标准关键字 `PtrSafe`。 使用 [Fusion](/official/Features/Fusion) 功能,还可以在 32 位*和* 64 位项目中同时使用 32 位和 64 位 ActiveX 控件。 ## 示例语法 ```vb Public Declare PtrSafe Sub foo Lib "bar" (ByVal hWnd As LongPtr) ``` ## 重要注意事项 ::: warning 要让大多数 32 位应用程序在 64 位下正常工作,还需要做更多工作。只有部分 `Long` 变量需要更改,这取决于它们对应的 C/C++ 数据类型(种类繁多)。需要改为 `LongPtr` 的示例包括:`HWND, HBITMAP, HICON` 和 `HANDLE` 等句柄;`void*, PVOID, ULONG_PTR, DWORD_PTR` 以及以 `Long` 传递时的 `LPWSTR/PWSTR/LPCWSTR/WCHAR*` 等指针;以及 CopyMemory 和内存分配函数中出现的 `SIZE_T` 类型。 ::: 虽然 `PtrSafe` 关键字并非强制要求,但这些更改仍然是必须的。此外,任何处理内存指针的代码都必须考虑到,所有上述类型(以及更多未提及的类型)以及 v-table 条目,现在可能是 4 或 8 字节,而大多数程序员传统上硬编码为 4 字节。UDT 对齐问题也更加频繁出现。这一切都非常复杂,在迁移到 64 位时应寻求资源和建议(不过请记住,32 位仍然受支持,因此这不是强制要求)。 对于常见的 Windows API 和 COM 接口,社区开发了一个提供 64 位兼容定义的包:[Windows Development Library for twinBASIC (WinDevLib)](https://github.com/fafalone/WinDevLib)。 --- --- url: /en/official/Features/64bit.md --- # 64bit Compilation twinBASIC can compile native 64bit executables in addition to 32bit. The syntax is compatible with VBA7 for this: the `LongPtr` data type and the standard to mark APIs `PtrSafe`. Using the [Fusion](/en/official/Features/Fusion) feature, it is also possible to use both 32bit and 64bit ActiveX controls in 32bit *and* 64bit projects. ## Example Syntax ```vb Public Declare PtrSafe Sub foo Lib "bar" (ByVal hWnd As LongPtr) ``` ## Important Considerations ::: warning There is a lot more required to get most 32bit apps to work properly as 64bit. Only some `Long` variables are to be changed, and this is determined by their C/C++ data types, of which there are many. Examples that need to be `LongPtr` include handles like `HWND, HBITMAP, HICON,` and `HANDLE`; pointers like `void*, PVOID, ULONG_PTR, DWORD_PTR,` and `LPWSTR/PWSTR/LPCWSTR/WCHAR*` when passed as `Long`; and the `SIZE_T` type found in CopyMemory and memory allocation functions. ::: While the `PtrSafe` keyword is not mandatory, these changes still must be made. Additionally, any code working with memory pointers must account for the fact all the types mentioned (and the many more not), as well as v-table entries, are now either 4 or 8 bytes, when most programmers have traditionally hard coded 4 bytes. There are also UDT alignment issues more frequently. This is all very complex and you should seek resources and advice when moving to 64bit (though remember, 32bit is still supported so this isn't a requirement). For common Windows APIs and COM interfaces, a community-developed package is available that provides 64bit compatible definitions: [Windows Development Library for twinBASIC (WinDevLib)](https://github.com/fafalone/WinDevLib). --- --- url: /zh/official/IDE/Menu/Help.md --- # 帮助菜单 ![Help Menu](/assets/Menu_Help.3Ygys9HS.png "Help Menu") * 关于 twinBASIC... * 许可协议... * 自动 IDE 错误报告... *** * 帮助与支持(Discord 服务器)... * 帮助与支持(GitHub 仓库)... * Twitter(新闻动态)... *** * 购买许可证... * 输入许可证密钥... * 请我们喝杯咖啡!(Ko-Fi)... *** * 编译器服务 TRACE 模式:已禁用 ## 关于 twinBASIC... ![About - Help Menu](/assets/Menu_Help_About.C_mmUuOm.png "About - Help Menu") ## 许可协议... ## 自动 IDE 错误报告... ## 帮助与支持(Discord 服务器)... ## 帮助与支持(GitHub 仓库)... ## Twitter(新闻动态)... ## 购买许可证... ## 输入许可证密钥... ## 请我们喝杯咖啡!(Ko-Fi)... ## 编译器服务 TRACE 模式:已禁用 --- --- url: /zh/official/Reference/Packages.md --- # 包 *包*将相关代码 --- 模块、类、控件和枚举 --- 组织在单一命名空间下,并作为单个依赖项从项目中引用。参见[功能 → 包](/official/Features/Packages/)了解包的构建和分发方式;以下页面记录twinBASIC自带的*内置*包。 ## 默认包 这些包默认包含在所有项目中。 * [VB包](/official/Reference/VB/) -- 标准控件(**CheckBox**、**CommandButton**、**TextBox**等)、窗体以及应用级单例(**App**、**Screen**、**Clipboard**、**Printer**等) * [VBA包](/official/Reference/VBA/) -- 标准运行时库 -- **MsgBox**、**CStr**、**Mid**、**Format**等按模块分组,加上**Collection**和**Err**内置类型以及twinBASIC的运行时表达式引擎 * [VBRUN包](/official/Reference/VBRUN/) -- 仅运行时类型 -- 环境属性、异步读取状态、结构化错误上下文、**PropertyBag**、剪贴板/拖放容器,以及经典VB6窗体和控件使用的枚举 ## 内置包 这些包内置于twinBASIC中,始终可用(即使离线)。要使用它们,请在项目 → 引用 (Ctrl-T) → 可用包中添加。 * [Assert包](/official/Reference/Assert/) -- 单元测试断言函数 -- 三个模块(**Exact**、**Strict**、**Permissive**)共享相同的十五个成员API,比较严格程度不同 * [CustomControls包](/official/Reference/CustomControls/) -- 自绘`Waynes…`自定义控件(按钮、窗体、框架、网格、标签、滑块、文本框、定时器)、共享的`Styles/`绘制辅助工具,以及用于创作新自定义控件的DESIGNER框架(接口、回调对象、**Canvas**、**SerializeInfo**) * [CEF包](/official/Reference/CEF/) -- 封装Chromium Embedded Framework的**CefBrowser**控件:跨平台浏览器嵌入,提供三种Chromium运行时选择(v49/v109/v145);目前处于BETA阶段 * [WebView2包](/official/Reference/WebView2/) -- 封装Microsoft Edge运行时的**WebView2**控件,及其周围的包装对象(请求/响应/头/环境选项)和`wv2…`枚举 * [WinEventLogLib包](/official/Reference/WinEventLogLib/) -- 从twinBASIC写入Windows事件日志;通用**EventLog**(*Of EventIds, Categories*)类处理注册、注册表设置和每个事件的`ReportEventW`调用,*EventIds*和*Categories*的消息表资源在编译时合成到EXE中 * [WinNamedPipesLib包](/official/Reference/WinNamedPipesLib/) -- Windows命名管道作为twinBASIC对象,采用异步IOCP驱动I/O模型;宿主端的**NamedPipeServer** + **NamedPipeServerConnection**,客户端的**NamedPipeClientManager** + **NamedPipeClientConnection**,具有消息边界语义和基于cookie的关联模式 * [WinServicesLib包](/official/Reference/WinServicesLib/) -- 将twinBASIC EXE作为一个或多个Windows服务运行;**Services**单例协调配置、安装/卸载和SCM调度循环,用户实现的[**ITbService**](/official/Reference/WinServicesLib/ITbService)类通过[**ServiceCreator**](/official/Reference/WinServicesLib/ServiceCreator)`(Of T)`实例化 * [tbIDE包](/official/Reference/tbIDE/) -- twinBASIC IDE的**插件SDK**:每个插件是一个标准DLL,导出`tbCreateCompilerAddin`,返回实现[**AddIn**](/official/Reference/tbIDE/AddIn)契约的对象,从那里可以访问IDE的工具栏、工具窗口DOM、虚拟文件系统、调试控制台、当前项目(及其`Evaluate`调试控制台钩子)、键盘快捷键和主题 -- 全部通过IDE传入的[**Host**](/official/Reference/tbIDE/Host)对象访问 * [WinNativeCommonCtls包](/official/Reference/WinNativeCommonCtls/) -- VB6兼容的**Microsoft Common Controls 6.0**(`MSCOMCTL.OCX`)替代方案,基于Win32 ComCtl32控件构建:八个控件([**DTPicker**](/official/Reference/WinNativeCommonCtls/DTPicker)、[**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/)、[**ListView**](/official/Reference/WinNativeCommonCtls/ListView/)、[**MonthView**](/official/Reference/WinNativeCommonCtls/MonthView)、[**ProgressBar**](/official/Reference/WinNativeCommonCtls/ProgressBar)、[**Slider**](/official/Reference/WinNativeCommonCtls/Slider)、[**TreeView**](/official/Reference/WinNativeCommonCtls/TreeView/)、[**UpDown**](/official/Reference/WinNativeCommonCtls/UpDown)),保留了原始成员名称,加上集合子对象([**ListItems**](/official/Reference/WinNativeCommonCtls/ListView/ListItems)、[**ColumnHeaders**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders)、[**Nodes**](/official/Reference/WinNativeCommonCtls/TreeView/Nodes)、[**ListImages**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages))和用户可见的枚举 --- --- url: /zh/official/IDE/Package-Publishing.md --- # 包发布 包发布面板管理当前项目发布为 twinBASIC 包时的元数据,包括包名称、版本和描述。 未打开项目时此面板为空。 ![Package Publishing](/assets/PackagePublishing.cttvMIko.png "Package Publishing") 打开项目后可以编辑属性。 ![Package Publishing](/assets/PackagePublishing_1.BNXsYHtO.png "Package Publishing") 点击"EDIT"将打开[项目设置](/official/IDE/Project-Settings)。 --- --- url: /zh/official/Features/Compiler-IDE/Package-Server.md --- # 包服务器 代码可以组合为包并发布到在线服务器。你可以拥有私有包(仅自己可见)或公开包(所有人可见)。 ![image](/assets/5951dab6-738e-4b63-83c4-3331ec6d36b9.CgLJrXeN.png) 更多信息请参见以下页面: * [什么是包](/official/Features/Packages/) * [创建 TWINPACK 包](/official/Features/Packages/Creating-a-TWINPACK-package) * [从 TWINPACK 文件导入包](/official/Features/Packages/Importing-a-package-from-a-TWINPACK-file) * [从 TWINSERV 导入包](/official/Features/Packages/Importing-a-package-from-TWINSERV) * [更新包](/official/Features/Packages/Updating-a-package) --- --- url: /zh/official/Features/Packages.md --- # 包管理 在 twinBASIC 中,*包* 是一组可以从另一个 twinBASIC 项目引用的组件。组件可以是模块、类或接口。 twinBASIC 内置了一个名为 TWINSERV\[^1] 的包管理器服务,允许你向其他 twinBASIC 开发者共享和分发 TWINPACK 包。 twinBASIC 包以 TWINPACK 文件分发,包含该包中组件所需的一切。引用 TWINPACK 包的项目会将整个包导入根项目的文件系统中,不会产生外部依赖。 通过 TWINPACK 包,你可以将常用组件组合到自己的命名空间中,同时允许便捷的代码重用,而无需面对使用外部 DLL 库时常见的问题。 请注意,TWINPACK 文件目前包含打包组件的完整源代码。计划在将来允许持有 twinBASIC 终极版许可证的开发者创建二进制(已编译)TWINPACK 文件。 ## 主题 * [创建 TWINPACK 包](/official/Features/Packages/Creating-a-TWINPACK-package) -- 将 twinBASIC 组件打包为可分发的 TWINPACK 文件。 * [从 TWINSERV 导入包](/official/Features/Packages/Importing-a-package-from-TWINSERV) -- 浏览和安装 TWINSERV 在线仓库中的包。 * [从 TWINPACK 文件导入包](/official/Features/Packages/Importing-a-package-from-a-TWINPACK-file) -- 从本地 TWINPACK 文件安装包。 * [链接包](/official/Features/Packages/Linked-Packages) -- 将包存储在共享位置而非嵌入每个项目文件中。 * [更新包](/official/Features/Packages/Updating-a-package) -- 移除过时的包并从 TWINSERV 安装更新版本。 \[^1]: TWINBASIC LTD 向用户社区提供的服务。 --- --- url: /zh/official/Reference/Core/Comparison-Operators.md --- # 比较运算符 用于比较表达式并返回 **Boolean** 结果。 语法: > *result* **=** *expression1* *comparisonoperator* *expression2*\ > *result* **=** *object1* **Is** *object2*\ > *result* **=** *string* **Like** *pattern* *result* : 任意数值变量。 *expression* : 任意表达式。 *comparisonoperator* : `<`、`<=`、`>`、`>=`、`=`、`<>` 中的任意一个。 *object* : 任意对象引用。 *string* : 任意字符串表达式。 *pattern* : 任意字符串表达式或字符范围。 下表列出了比较运算符以及确定 *result* 为 **True**、**False** 或 **Null** 的条件: | 运算符 | **True** 如果 | **False** 如果 | **Null** 如果 | |:----------------------------------|:---------------------------|:---------------------------|:-----------------------------------------| | `<` (小于) | *expression1* < *expression2* | *expression1* >= *expression2* | *expression1* 或 *expression2* = **Null** | | `<=` (小于或等于) | *expression1* <= *expression2* | *expression1* > *expression2* | *expression1* 或 *expression2* = **Null** | | `>` (大于) | *expression1* > *expression2* | *expression1* <= *expression2* | *expression1* 或 *expression2* = **Null** | | `>=` (大于或等于) | *expression1* >= *expression2* | *expression1* < *expression2* | *expression1* 或 *expression2* = **Null** | | `=` (等于) | *expression1* = *expression2* | *expression1* <> *expression2* | *expression1* 或 *expression2* = **Null** | | `<>` (不等于) | *expression1* <> *expression2* | *expression1* = *expression2* | *expression1* 或 *expression2* = **Null** | ::: info [**Is**](/official/Reference/Core/Is) 和 [**Like**](/official/Reference/Core/Like) 运算符有各自专用的比较语义,单独成文。 ::: `=` 符号也是赋值运算符(`*variable* = *expression*`)。上下文——`=` 出现在表达式中还是语句开头——决定了使用哪种含义;无需显式选择。 比较两个表达式时,判断它们是作为数字还是字符串比较可能并不明显。下表显示了表达式的比较方式,或当任一表达式不是 **Variant** 时的结果: | 如果 | 则 | |:-----------------------------------------------------------------------------------------|:------------------------------------------------------| | 两个表达式都是数值类型(**Byte**、**Boolean**、**Integer**、**Long**、**LongLong**、**Single**、**Double**、**Date**、**Currency**) | 执行数值比较。 | | 两个表达式都是 **String** | 执行字符串比较。 | | 一个表达式是数值类型,另一个是 **Variant** 且是或可以是数字 | 执行数值比较。 | | 一个表达式是数值类型,另一个是无法转换为数字的字符串 **Variant** | 发生 `Type Mismatch` 错误。 | | 一个表达式是 **String**,另一个是除 **Null** 外的任意 **Variant** | 执行字符串比较。 | | 一个表达式是 **Empty**,另一个是数值数据类型 | 执行数值比较,**Empty** 表达式使用 0。 | | 一个表达式是 **Empty**,另一个是 **String** | 执行字符串比较,**Empty** 表达式使用 `""`。 | 如果 *expression1* 和 *expression2* 都是 **Variant** 表达式,其底层类型决定比较方式: | 如果 | 则 | |:--------------------------------------------------------------------|:------------------------------------------------------| | 两个 **Variant** 表达式都是数值 | 执行数值比较。 | | 两个 **Variant** 表达式都是字符串 | 执行字符串比较。 | | 一个 **Variant** 表达式是数值,另一个是字符串 | 数值表达式小于字符串表达式。 | | 一个 **Variant** 表达式是 **Empty**,另一个是数值 | 执行数值比较,**Empty** 表达式使用 0。 | | 一个 **Variant** 表达式是 **Empty**,另一个是字符串 | 执行字符串比较,**Empty** 表达式使用 `""`。 | | 两个 **Variant** 表达式都是 **Empty** | 表达式相等。 | 当 **Single** 与 **Double** 比较时,**Double** 会被舍入到 **Single** 的精度。如果 **Currency** 与 **Single** 或 **Double** 比较,**Single** 或 **Double** 会被转换为 **Currency**。对于 **Currency**,小于 `.0001` 的小数值可能丢失,这可能导致两个实际不同的值比较结果为相等。 字符串比较受模块的 [**Option Compare**](/official/Reference/Core/Option) 设置控制——**Binary**(默认;区分大小写,按序比较)或 **Text**(不区分大小写,受区域设置影响)。 ### 示例 ```vb Dim MyResult, Var1, Var2 MyResult = (45 < 35) ' Returns False. MyResult = (45 = 45) ' Returns True. MyResult = (4 <> 3) ' Returns True. MyResult = ("5" > "4") ' Returns True. Var1 = "5": Var2 = 4 ' Initialize variables. MyResult = (Var1 > Var2) ' Returns True (string compared as string). Var1 = 5: Var2 = Empty MyResult = (Var1 > Var2) ' Returns True (Empty treated as 0). Var1 = 0: Var2 = Empty MyResult = (Var1 = Var2) ' Returns True. ``` ### 另请参阅 * [**Is** 运算符](/official/Reference/Core/Is) * [**IsNot** 运算符](/official/Reference/Core/IsNot) * [**Like** 运算符](/official/Reference/Core/Like) * [**Option** 语句](/official/Reference/Core/Option) * [运算符](/official/Reference/Operators) --- --- url: /zh/official/IDE/Menu/Edit.md --- # 编辑菜单 ![Edit Menu](/assets/Menu_Edit.Y09uiSar.png "Edit Menu") * 撤销 CTRL + Z * 重做 CTRL + Y *** * 剪切 CTRL + X / SHIFT + DELETE * 复制 CTRL + C / CTRL + INSERT * 粘贴 CTRL + V * 删除 DELETE * 全选 CTRL + A *** * 查找... CTRL + F * 替换... CTRL + H * 在项目中查找... CTRL + SHIFT + Y *** * 缩进 CTRL + ] * 减少缩进 CTRL + \[ * 格式化选定内容 * 格式化文档 *** * 快速查找... ALT + F * 快速替换... ALT + H * 全选匹配项 ALT + A *** * 折叠 CTRL + { * 折叠过程 CTRL + ALT + ARROWLEFT * 全部折叠 * 展开 CTRL + } * 展开过程 CTRL + ALT + ARROWRIGHT * 全部展开 *** * 转到行/列... *** * 转换为大写 * 转换为小写 * 转换为标题大小写 * 转换为蛇形命名 --- --- url: /zh/official/IDE/Editor.md --- # 编辑器 ![编辑器](/assets/Editor.DHImjvC5.png "编辑器") ## 选项 * 显示代码折叠 * 从不 * *悬停时* * 始终 * 渲染空白 * 全部 * *无* * 边界 * 选区 * 尾部 * 字体大小 * 8px * ... * *13px* * ... * 30px * 显示导航栏 * 上方 * 下方 * 无 * ✔ 显示缩进参考线 * ✔ 显示行号 * 代码提示始终可见 * 粘性滚动 * ✔ 显示缩略图 * 悬停时显示高级信息 * 显示单行标签页 * ✔ 自动美化代码 * ✔ 显示 CodeLens 运行过程 ## 标签页列表 当文件在*编辑器*中打开时,它会列在*标签页列表*中,你可以在此之间跳转。 ![编辑器标签页列表示例](Images/Editor_TabsList_Example.png "编辑器标签页列表示例") *最近关闭*。 ![编辑器标签页列表 - 最近关闭](Images/Editor_TabsList_RecentlyClosed.png "编辑器标签页列表 - 最近关闭") *最近关闭 - 列表* ![编辑器标签页列表 - 最近关闭示例](/assets/Editor_TabsList_RecentlyClosed_Example.CzbZXcDf.png "编辑器标签页列表 - 最近关闭示例") --- --- url: /zh/official/Reference/Compiler-Constants.md --- 本指南介绍twinBASIC中的内置编译器常量。它包含VBA文档中列出的常量,即使它们未定义也可以使用,因为未定义的编译器常量始终可用,但其值为0。 ## `Win16` **用途:** 指示16位Windows兼容平台。\ **值:** 始终为0(False);不支持16位Windows。 ## `Win32` **用途:** 指示32位兼容Windows平台\ **值:** 在受支持的Windows平台上始终为1(True),无论是32位还是64位。 ## `Win64` **用途:** 指示64位Windows AMD64平台。\ **值:** 编译器处于32位模式时为0(False),处于64位模式时为1(True)。 ## `VBA6` **用途:** 指示与VBA6语法的兼容性。\ **值:** 始终为1(True)。 ## `VBA7` **用途:** 指示与VBA7语法的兼容性。\ **值:** 始终为1(True)。 ## `MAC` **用途:** 指示是否在MacOS平台上运行。\ **值:** 始终为0(False)。目前不支持Mac,但将来会改变。 ## `TWINBASIC` **用途:** 指示与twinBASIC语法的兼容性。\ **值:** 始终为1(True)。 ## `TWINBASIC_BUILD` **用途:** 提供一个`Long`值,表示当前twinBASIC构建号。\ **值:** 目前与"BETA"编号相同,例如Beta 610的值为610。 ## `TWINBASIC_BUILD_TYPE` **用途:** 允许根据项目是exe、dll还是ocx进行条件编译。\ **值:** 一个`String`,可以是"Standard EXE"、"Standard DLL"、"ActiveX DLL"或"ActiveX Control",由项目设置中的"Build Type"选项决定。 # 用法 使用方式遵循在标准`If/Else/ElseIf`条件前加井号号的标准语法。例如,要区分32位和64位VBA与64位twinBASIC: ```vb #If VBA7 Then 'We're in either VBA7 or twinBASIC #If Win64 Then 'We're in either 64bit VBA7 or 64bit twinBASIC #If TWINBASIC Then 'We're in 64bit twinBASIC #If TWINBASIC_BUILD_TYPE = "ActiveX Control" Then 'And we're building an OCX #End If #Else 'We're in 64bit VBA7 #End If #Else 'We're in either 32bit VBA7 or 32bit twinBASIC #If TWINBASIC Then 'We're in 32bit twinBASIC #Else 'We're in 32bit VBA7 #End If #End If #Else 'We're in VB6 or VBA6. Win64 will always be False by default. TWINBASIC will always be False by default. #End If ``` 或者更简单地,判断是否使用`PtrSafe`、`DeclareWide`或其他tB功能: ```vb #If VBA7 Then #If TWINBASIC Then 'PtrSafe DeclareWide declares, if desired, also inline comments and `[ TypeHint() ]`, and function attributes. #Else 'PtrSafe declares not using DeclareWide or any new syntax #End If #Else 'Classic VB6/VBA6 declares without PtrSafe or other new syntax #End If ``` ::: warning 提醒:编译器常量不是`Boolean`值,因此不应使用`#If Not Win64 Then`这样的语法,因为结果可能不符合预期。例如,该表达式在32位和64位模式下都会求值为`True`,而你可能期望在64位下为`False`以使用仅限32位的代码。\ ::: 如果希望将它们视为`Boolean`,可以使用`CBool()`函数,例如`#If Not CBool(Win64) Then`。 # 外观 tB编辑器具有实时显示编译器常量是否处于活动状态的有用功能。`#If`块中不会在当前设置下执行的代码会显示为灰色。注意,与VBx不同,不活动的代码不会进行错误检查。 例如,在32位模式下:\ ![image](/assets/oHpCiV1.rjQ32Q75.png) 切换到64位模式后:\ ![image](/assets/TYizrRW.B6FJyjA6.png) *** *VB6、VBA、VBA6和VBA7是Microsoft Corporation的商标。*\ *MacOS是Apple, Inc.的商标。* --- --- url: /zh/official/Features/Compiler-IDE.md --- # 设计体验和编译器功能 twinBASIC 包含许多编译器功能和 IDE 增强,以改善开发体验。 ## 主题 * [编译器警告](/official/Features/Compiler-IDE/Compiler-Warnings) - 编译器警告和严格模式 * [调试](/official/Features/Compiler-IDE/Debugging) - 调试跟踪记录器和过期指针检测 * [CodeLens](/official/Features/Compiler-IDE/CodeLens) - 从 IDE 运行 Sub * [IDE 功能](/official/Features/Compiler-IDE/IDE-Features) - 现代 IDE 能力 * [包服务器](/official/Features/Compiler-IDE/Package-Server) - 包管理系统 --- --- url: /zh/official/Features/Compiler-IDE/Compiler-Warnings.md --- # 编译器警告 twinBASIC 在设计时提供编译器警告,用于提示常见的不良实践或可能的疏忽。 ## 可用警告 ### 可能不正确的十六进制字面量警告 非显式值首先被强制转换为最低可能的类型。因此,如果你将常量声明为 `&H8000`,编译器会将其视为 -32,768 `Integer`,而当你将其放入 `Long` 时,你几乎可以肯定不想要 -32,768,你想要的是**正** 32,768,这需要你改用 `&H8000&`。 此警告适用于 `&H8000`-`&HFFFF` 和 `&H80000000`-`&HFFFFFFFF`。 ### 使用 ReDim 隐式创建变量警告 当你使用 `ReDim myArray(1)` 时,`myArray` 变量会自动为你创建,而最佳实践是先声明所有变量。 ### 使用 DefType 的警告 不鼓励使用此功能,因为它使代码难以阅读,且容易导致难以调试的错误。 完整列表可以在项目的设置页面中找到: ![image](/assets/017bd6f8-4b35-43a9-b6be-84cba69daf64.DNFSosgo.png) ## 调整警告 每个警告都可以设置为忽略或转换为错误,既可以通过设置页面的项目级设置,也可以通过每个模块/类、每个过程使用 `[IgnoreWarnings(TB___)]`、`[EnforceWarnings(TB____)]` 和 `[EnforceErrors(TB____)]` 特性来设置,其中下划线替换为**完整**数字,例如 `[IgnoreWarnings(TB0001)]`;前导零必须包含。 ## 严格模式 twinBASIC 添加了以下警告消息以支持类似于 .NET 的严格模式,即不允许某些隐式转换,必须显式进行。默认情况下,这些都设置为忽略,必须在项目设置的"编译器警告"部分启用,或通过每个模块/过程使用 `[EnforceWarnings()]` 启用。所有这些都可以单独配置,并使用 `[IgnoreWarnings()]` 在过程/模块范围内忽略。 ### TB0018: 隐式窄化转换 例如将 Long 转换为 Integer;如果你有 `Dim i As Integer, l As Long`,那么 `i = l` 将触发警告,而需要使用 `i = CInt(l)` 来避免。 ### TB0019: 隐式枚举转换 当将一个枚举的成员赋值给另一个枚举类型的变量时,例如 `Dim day As VbDayOfWeek: day = vbBlack`。前面章节中描述了用于指针的 `CType(Of )` 运算符也可用于指定显式类型转换;`day = CType(Of VbDayOfWeek)(vbBlack)` 不会触发警告。 ### TB0020: 可疑的接口转换 如果声明的 coclass 没有显式命名支持的接口,转换为该接口将触发此警告,例如: ```vb Dim myPic As StdPicture Dim myFont As StdFont Set myFont = myPic ``` 你需要使用 `Set myFont = CType(OfStdFont)(myPic)` 来避免此警告。 ### TB0021: 隐式枚举与数值之间的转换 将数字字面量赋值给枚举类型的变量时触发,例如 `Dim day As VbDayOfWeek: day = 1`。要避免它,使用 `day = CType(Of VbDayOfWeek)(1)`。 --- --- url: /zh/official/Features/Project-Configuration/Compiler-Options.md --- # 编译器选项 twinBASIC 提供了多个编译器选项来控制代码的编译和优化方式。 ## COM 初始化 你可以使用以下选项指定隐藏入口点使用的调用:`CoInitialize STA`、`CoInitializeEx MTA`、`OleInitialize STA`。如果你不知道它们之间的区别,请不要更改默认值。 ## 符号表参数 你可以调整以下参数:Max Size Raw、Max Size Lookup 和 Data Type Lookup。这些选项允许编译非常大的项目(否则可能会有问题),编译器会在这些值需要增加时通知你。 ## Boolean 类型净化 内部布尔值是 2 字节类型。使用内存 API 或从外部代码接收时,可能会存储 `True` 和 `False` 之外的值。此选项验证来自外部来源的布尔值(例如 COM 对象和 API),确保只存储两个支持的值。 ## 附加选项 * **LARGEADDRESSAWARE**:项目可以标记为 `LARGEADDRESSAWARE`。 * **基址**:可以指定手动基址。 * **PE 重定位符号**:剥离 PE 重定位符号的选项。 ## 利用缓解 你可以启用以下安全功能: * **数据执行保护 (DEP)** * **地址空间布局随机化 (ASLR)** --- --- url: /zh/official/IDE/Variables.md --- # 变量 ![Variables](Images/Variables.png "Variables") 变量面板在调试时列出当前执行点作用域内的变量,显示每个变量的名称、类型和当前值。结构化类型——类和用户定义类型——可以展开以检查其各个成员。 --- --- url: /zh/official/Features/Standard-Library.md --- # 标准库增强 twinBASIC 通过 Unicode 支持、新函数和改进的文件 I/O 功能增强了标准库。 ## 主题 * [Unicode 支持](/official/Features/Standard-Library/Unicode-Support) - 原生 Unicode 和编码选项 * [文件 I/O](/official/Features/Standard-Library/File-IO) - 支持编码的增强文件操作 * [新函数](/official/Features/Standard-Library/New-Functions) - 新的内置函数和 App 对象属性 --- --- url: /zh/official/IDE/Menu.md --- # 菜单 ![Menu](Images/Menu.png "Menu") --- --- url: /zh/official/Reference.md --- # 参考章节 参考文档分为三层:编译器解析的语言构造(关键字、语句、运算符)、内置包中提供的运行时成员(函数、属性、类型、类),以及包本身。 **语言构造和运行时成员:** * [**分类索引**](/official/Reference/Categories) -- 按用途分组的语句、过程和函数(声明、控制流、字符串处理、文件I/O等) * [**语句**](/official/Reference/Statements) -- 所有语言语句的字母顺序索引 * [**过程和函数**](/official/Reference/Procedures-and-Functions) -- 所有可调用运行时成员的字母顺序索引 * [**运算符**](/official/Reference/Operators) -- 算术、比较、逻辑、位运算及twinBASIC新增运算符 * [**枚举**](/official/Reference/Enumerations) -- 全部12个包中所有141个枚举类型的索引,按包和字母顺序分组 * [**数据类型**](/official/Reference/Data-Types) -- 每个内置类型的存储大小、取值范围和类型后缀(从**Boolean**到**Variant**) * [**编译器常量**](/official/Reference/Compiler-Constants) -- 编译器识别的`#If`符号 * [**属性**](/official/Reference/Attributes) -- `[Documentation(...)]`、`[COMCreatable(...)]`及其他属性语法 * [**twinBASIC新增功能**](/official/Reference/twinBASIC-Additions) -- 超出标准VBA的语言和运行时新增功能精选列表 **控件和术语表:** * [**控件**](/official/Reference/Controls) -- 按用途分组的标准UI控件 * [**术语表**](/official/Reference/Glossary) -- 文档中使用的技术术语 **包:** * [**包**](/official/Reference/Packages) -- 全部12个内置包:默认运行时三件套(VBA、VBRUN、VB)、GUI扩展(CustomControls、WinNativeCommonCtls)、浏览器嵌入(WebView2、CEF)、Windows集成库(WinServicesLib、WinEventLogLib、WinNamedPipesLib)以及工具包(Assert、tbIDE) --- --- url: /zh/official/IDE/FindReplace.md --- # 查找/替换 ![Find / Replace](/assets/FindReplace.DytG1fIX.png "Find / Replace") 查找内容 替换为 * 当前过程 * 当前模块 * 当前文件 * 当前项目 * 选定文本 方向:全部/向下/向上 ![Find / Replace - Direction](Images/FindReplace_Direction.png "Find / Replace - Direction") * 全字匹配 * 区分大小写 * 模式匹配 * 正则表达式匹配 * 在包内搜索 查找下一个 取消 替换 全部替换 --- --- url: /zh/official/Miscellaneous/FAQs.md --- # 常见问题 ### [常规](#general) - [安装](#install-section) - [使用 twinBASIC](#using-twinbasic) ## 常规 ::: details 什么是 twinBASIC? twinBASIC 是一种新的 BASIC 语言和开发环境(IDE),目标是与 VB6/VBA 100% 向后兼容。 ::: ::: details 谁在开发 twinBASIC? twinBASIC 是 Wayne Phillips 的作品,他运营着 [Everything Access](https://www.everythingaccess.com/) 公司,这是一家成熟的 Microsoft Access 和 VBA 专业工具和服务提供商,包括流行的 vbWatchdog 软件。 ::: ::: details 我在哪里可以获取 twinBASIC? 最新版本可以从 [主 twinBASIC GitHub 仓库](https://github.com/twinbasic/twinbasic)的 [Releases 部分](https://github.com/twinbasic/twinbasic/releases)下载。有关安装的更多信息,请参见[如何安装 twinBASIC](#installation)。 ::: ::: details 项目当前状态如何? twinBASIC 目前处于 **Beta** 阶段后期,仍在开发中,尚未达到稳定的 1.0 版本。所有 VB6/VBA7 语法和内置函数已实现。所有基本控件(除 OLE 控件外)以及约一半的通用控件已实现。它支持窗体、类和 UserControl——既作为编译的 OCX/DLL 控件,也作为项目内代码(即类似 .ctl 文件)。但是,并非所有属性、事件和方法已完成。此外,ActiveX EXE 和 VBG 项目组支持尚未实现,还有相当数量的 bug。 不过,**tB 已经可以运行许多现有项目**,甚至是相当复杂和大型项目。许多社区成员已成功让他们的应用和其他开源项目运行起来,并从头创建了新项目。查看以下示例可以很好地了解项目进展: Krool 的 [VBCCR](https://github.com/Kr00l/VBCCR) 和 [VBFlexGrid](https://github.com/Kr00l/VBFLXGRD) 控件、Ben Clothier 的 [TwinBasicSevenZip](https://github.com/bclothier/TwinBasicSevenZip)、Carles PV 的 [Lemmings](https://github.com/fafalone/Lems64)、Don Jarrett 的 [basicNES](https://github.com/fafalone/basicNES) 任天堂模拟器,以及 Jon Johnson 的 [ucShellBrowse/ucShellTree](https://github.com/fafalone/ShellControls)、[FileActivityMon ETW 事件跟踪器](https://github.com/fafalone/EventTrace)、[cTaskDialog](https://github.com/fafalone/cTaskDialog64) 和[更多](https://github.com/fafalone)。 ::: ::: details 是否有预期功能的可用时间表? 是的,请参见 Issues 部分中的 [twinBASIC 路线图](https://github.com/twinbasic/twinbasic/issues/335) 获取时间表的最新更新。此路线图仅涵盖主要组件;较小的功能以不太正式的方式实现,通常在处理相关代码库部分时一并完成。 ::: ::: details twinBASIC 相比 VB6 有哪些新功能? **非常多!** 它有 64 位编译(使用兼容 VBA7x64 的语法)、泛型、重载、多线程(目前仅 API 方式,内置语法即将推出)、继承、使用 BASIC 风格语法定义接口和 coclass、所有控件和编辑器中的 Unicode 支持(仅 .twin 文件)、现代图像格式支持、对 *Implements* 的多项增强、创建标准 DLL 和内核模式驱动的能力、设置 UDT 对齐的能力等数十种功能,**现在就可使用**,未来还有更多计划。 有关目前所有新功能的完整列表,请参阅 Wiki 文章 [twinBASIC 新功能概览](/official/Features/)。 ::: ::: details 我在哪里可以了解更多 twinBASIC 信息、查找文档和参与社区? [twinBASIC 主页](https://twinbasic.com) twinBASIC GitHub:[主仓库](https://github.com/twinbasic/twinbasic) | [Issues](https://github.com/twinbasic/twinbasic/issues) | [讨论](https://github.com/twinbasic/twinbasic/discussions) | [语言设计](https://github.com/twinbasic/lang-design) | [语言规范](https://github.com/twinbasic/lang-spec) | [文档](https://docs.twinbasic.com) [twinBASIC Discord](https://discord.gg/UaW9GgKKuE) [VBForums 上的 twinBASIC 论坛](https://www.vbforums.com/forumdisplay.php?108-TwinBASIC) ::: ::: details twinBASIC 是开源的吗? 虽然未来可能采用开源模式,但编译器目前不是。IDE 的开源正在计划中。为解决由此带来的一些主要顾虑,一旦 tB 达到首个正式版本,源代码将被放入托管,以便在作者消失或因死亡或严重疾病/伤害无法继续工作时释放给社区。 ::: ::: details twinBASIC 多少钱? twinBASIC 有 3 个版本:社区版是免费的。编译的 64 位二进制文件会放置启动画面,某些功能如高级优化编译和未来的跨平台编译不可用,但对核心语言功能没有限制,也不收取版税。要获取这些功能,专业版和终极版提供订阅。有关更多详情,包括当前定价,[请参见此页面](https://twinbasic.com/preorder.html)。 **注意:** 你可以随时更改订阅级别,社区版始终可用。不会锁定(参见[前面关于托管的声明](#open-source)),因此你始终能够开发、测试和编译。 ::: ::: details 我可以一次性付费获取永久许可证吗? 由于需要持续收入来开发 twinBASIC,订阅是高级版本的主要模式,提供[按月或按年](https://twinbasic.com/preorder.html)选项。但目前限时提供一次性购买的永久许可证,形式为 [VIP Gold 终身许可证计划](https://twinbasic.com/vip.html)。这不仅提供包括更新和新版本在内的 twinBASIC 终身许可证,还有仅限购买此许可证的用户的众多额外福利。 ::: ::: details twinBASIC 可以用于开发商业产品吗?需要支付版税吗? 任何版本的 twinBASIC 都没有限制;它们都可以用于开发商业产品,**免版税**。使用 twinBASIC 创建的程序或其他产品的销售不需要支付任何费用。但 twinBASIC 软件本身未经适当许可不得再分发。 ::: ::: details "100% 向后兼容"在技术上是什么意思? 向后兼容性是指匹配所有公开记录的语法、包含的控件、组件和控件行为以及控件外观。不包括未记录的、专有的内部实现细节。因此,例如所有语言关键字、函数和方法都存在且应给出相同结果,窗体/类/UserControl 应实现所有相同的公开记录接口,但 twinBASIC 可执行文件的内部结构并不相同,并且与可执行文件中未记录的 VB 项目信息结构不兼容(其内容多年来已被社区逆向工程)。 目前,所有基本控件在 twinBASIC 中都有支持 Unicode 和 64 位编译的重新实现,除了 OLE 控件;还有一些主要通用控件也已重新实现。最终,VB6 企业版附带的所有控件都将被重新实现。在此之前,原始控件仍然可以在 32 位构建中工作,社区成员也提供了一些替代方案,例如 Krool 的 VBCCR 控件和 VBFlexGrid 控件都能工作并有 64 位兼容的 twinBASIC 版本。 ::: ::: details 那么我的一些项目不能工作了? 大多数项目不使用这些逆向工程的内部机制,但有些确实使用:最常见的是窗体/类/UserControl 内部的自子类化和回调;以及多线程和内联汇编。这些例程在 twinBASIC 中有原生支持,无需内部技巧,因此替换少数程序中的这些小部分非常简单:`AddressOf` 支持类成员,所以你可以使用常规子类化和回调方法,就像它们在 .bas 模块中一样。`CreateThread` 可以直接调用,无需任何特殊步骤。tB 还支持静态链接的 .obj 文件,允许从其他语言整合代码,通过 `Emit()`/`EmitAny()` 形式的内联汇编插入指令,未来还有更多支持计划。 此外,twinBASIC 重定向了用户最常使用的作为 `Declare` 语句的 msvbvm60.dll(也包括 msvbvm50.dll/vbe6.dll/vbe7.dll)函数,所有这些也都在 x64 中工作,只要你像其他 DLL 定义一样添加 `PtrSafe` 关键字。以下函数目前有重定向:`VarPtr, GetMem1, GetMem2, GetMem4, GetMem8, PutMem1, PutMem2, PutMem4, PutMem8, __vbaObjSet, __vbaObjSetAddRef, __vbaObjAddRef, __vbaCastObj, __vbaCopyBytes, __vbaCopyBytesZero, __vbaRefVarAry` 和 `__vbaAryMove`。你可以继续使用带 `Declare` 语句的这些函数来支持你偏好的特定签名。此外,olepro32.dll 的声明被重定向到 oleaut32.dll 中的相同函数,因为 olepro32 被 NT4 弃用且没有 64 位版本。 除了这些特殊情况外,项目依赖逆向工程内部机制的情况极为罕见。因此绝大多数项目可以零修改运行。 ::: ::: details 我如何报告 bug 或其他问题? 最好的方式是在 twinBASIC GitHub 仓库中[创建 Issue](https://github.com/twinbasic/twinbasic/issues)。 你也可以在 [twinBASIC Discord 服务器](https://discord.gg/UaW9GgKKuE)的 #bugs 频道发帖。 ::: ::: details twinBASIC IDE 是否支持其他语言? IDE 目前基本支持前端 UI 的本地化,翻译由社区成员提供。可以从 [tB Discord 服务器的 #langpacks 频道](https://discord.com/channels/927638153546829845/1329533568376115282)获取,目前大约有 10 种,包括法语、德语、意大利语、葡萄牙语、俄语、简体中文、繁体中文、日语、瑞典语、匈牙利语、希腊语、加泰罗尼亚语、印尼语(Bahasa)和马拉雅拉姆语。自撰写此文后可能已发布更多;请查看该频道。 内部文本如悬停信息尚不支持本地化,但这是未来的计划。 ::: ## 安装 ::: details twinBASIC 的系统要求是什么? twinBASIC IDE 支持 Windows 7 到 Windows 11。安装是便携式的;你只需解压下载的 zip 文件然后运行即可,没有安装程序。 需要 WebView2。这在较新版本的 Windows 上通常已预装,如果你安装了 Edge 浏览器也会一起安装。你也可以从 [Microsoft 网站](https://developer.microsoft.com/en-us/microsoft-edge/webview2?form=MA13LH#download-section)获取。选择 Standalone Evergreen x86 版本: ![image](/assets/94490c87-fafe-4d5b-ae39-d3cedba1c21d.DwCaeyAN.png) ::: ::: details twinBASIC 无法运行;提示无效入口点。 此问题有时出现在 Windows 7 上。要在 Windows 7 上使用,操作系统必须完全更新;此错误是由一个或多个缺少的更新导致的。运行 Windows Update 确保安装了所有最新更新。如果仍有问题,你可以到 Discord 或在 GitHub 上提交 Issue(参见[如何报告 bug 或其他问题?](#bug-reporting))。 ::: ::: details 启动 IDE 时报告缺少文件。 如果在启动 twinBASIC IDE 时收到缺少文件的通知,最可能的原因是你电脑上安装的杀毒软件将 twinBASIC 需要的一些文件隔离了,误认为它们包含病毒或其他恶意软件。这种错误检测在新发布的软件中很常见,所以请放心这只是误报——另请参见[上一条](#false-scanner-alerts)了解背景。 要使 twinBASIC IDE 成功启动,请配置杀毒软件忽略根目录及其 `bin` 子文件夹中的 twinBASIC 可执行文件(EXE 和 DLL)。这通常意味着将根目录和 `bin` 子文件夹添加到杀毒软件的"例外列表"中。 恢复缺少的 EXE 和 DLL 文件后,通过 `twinBASIC.exe` 文件启动 IDE 应该可以正常工作。 请将所有负面情绪指向你过于敏感的杀毒软件供应商 :) ::: ::: details 如何安装 twinBASIC? tB 不需要完整的安装过程,你只需解压 ZIP 文件。从 [Releases 页面](https://github.com/twinbasic/twinbasic/releases)下载最新版本,名为 `twinBASIC_IDE_BETA_xxx.zip`(其中 xxx 是版本号;点击 'Assets' 展开文件列表(如果尚未展开))。 ![img](/assets/ac019c1a-dcef-4964-a730-bc5b86c644ba.B4g1v4Fw.png) 下载 zip 并将其解压到**空**文件夹中。不要简单地覆盖以前的版本;要么删除文件夹中的所有内容,要么使用不同的文件夹。否则可能会出现奇怪的错误。它将从此文件夹运行;一些设置会放在 AppData 中。 ::: ::: details twinBASIC 安装有多大? IDE 非常小,目前只有 25MB 下载,解压后约 80MB,其中一半是因为 LLVM 库。 ::: ::: details twinBASIC IDE 数据存储在哪里? 除了你解压 IDE 的目录外,twinBASIC 在以下几个位置存储文件和设置: * `%APPDATA%\Local\twinBASIC` * `%APPDATA%\Local\twinBASIC_Admin` * `%APPDATA%\Local\twinBASIC_WebPanel` * `%APPDATA%\Local\twinBASIC_WebPanel_Admin` (WebView2 用户文件夹,这是 IDE 本身的,与你交互的文件/设置不直接相关。其中一些文件夹可能不存在。) * `%APPDATA%\Roaming\twinBASIC` (存储主题、链接包以及在删除以前的安装时你想保留的其他文件) * 以及注册表中的 `HKEY_CURRENT_USER\Software\VB and VBA Program Settings\twinBASIC_IDE` (当前 IDE 配置信息;最近项目列表、面板布局、许可证信息、选择的主题、键盘快捷键等) ::: ::: details twinBASIC 安全吗?(某个扫描器)说它是恶意的。 任何曾用多种 AV 引擎测试过自己程序的人都知道,除非你的 exe 是 64 位并用高级证书签名(也许即使如此,在被手动添加到信任列表之前),少数误报简直就是家常便饭。twinBASIC 的 IDE 和编译器可执行文件,像所有处于这种情况的应用一样,可能会在 VirusTotal 等服务上触发少量误报,特别是 32 位应用。这些几乎都不是来自主要供应商和/或基于"AI"的算法检测。 ::: ## 使用 twinBASIC ::: details 如何将 VB6 项目导入 twinBASIC? 最简单的方式是通过导入向导。当你首次启动 twinBASIC IDE 时,会显示新建项目对话框——其中包含"Import from VBP"选项: ![image](/assets/7e1cb69c-6db3-4f3f-aea1-c1fae25938a2.Tr3U6QbZ.png) 你可以通过 Add 菜单中的 Import 选项单独导入 .bas/.cls 文件,来自 VB 项目或任何类型,在 Project 下或右键点击项目资源管理器中所需的文件夹: ![img](/assets/2b32ab8c-fabc-4f42-9e6b-06e85574eaf4.DIphFkYh.png) **注意:** 你可以单独选择 .bas/.cls 文件,但要导入窗体、UserControl、属性页和资源文件,目前必须选择它们关联的 .vbp 文件。然后你会看到可以导入的文件列表(及其新的 twinBASIC 扩展名 .tbform/.twin 等——确保两者都导入,例如对于 Form1.frm 你会看到 Form1.frm.tbform 和 Form1.frm.twin: ![img](/assets/16833fae-4bd7-418f-bb16-691a611a5b01.DZtfkOsM.png)::: ::: details 为什么我看到很多错误说我的变量无法识别? ![image](/assets/e409ea37-96ad-44c5-8017-3699ef04b53d.DRKjo9w2.png) 虽然强烈推荐使用并被认为是最佳实践,twinBASIC **不**要求 `Option Explicit`。如果你看到这些错误,可能是你忽略了 twinBASIC 的一个新功能:自动启用项目范围的 `Option Explicit`。当你导入 VB6 项目或创建新项目时,会弹出一个小对话框: ![image](/assets/05306a72-4ff6-427d-8970-969ef0c582e6.oT97U_Pc.png) 如果保持"Option Explicit ON"勾选,意味着它将在项目范围内强制执行,无论窗体/模块等本身是否使用 `Option Explicit`。如果你取消勾选,你不会因此收到错误,只是一个警告:"This variable has been auto-declared by the compiler due to Option Explicit being OFF"。如果你想,可以在项目设置中禁用该警告: ![image](/assets/2a1c71fd-f81c-4bd3-b61a-0f2979e8961f.2xRWHNLi.png) 对于现有项目,项目范围 Option Explicit 可以在项目设置中打开或关闭,在"Project: Option Explicit On"下: ![image](/assets/01009879-fdbc-4a8e-8683-353aab6193df.BrJkHsI_.png) ::: ::: details twinBASIC 支持外接程序吗? VB6 和 VBA 的外接程序不被 twinBASIC IDE 支持。但是 tB 有基于现代 Web 技术的自己的外接程序基础设施。参见新建项目对话框"Samples"选项卡中的示例 10 到 16: ![image](/assets/0e24eb5c-c9af-49a9-a908-03968b211554.D4Bh5bza.png) twinBASIC 支持**创建** VBA 外接程序。它目前是唯一支持使用 100% 兼容语法的语言为 64 位 Office 创建这些外接程序的工具。参见示例 4 和示例 5。 外接程序可以安装到两个位置: 1. `%appdata%\twinBASIC\addins\` - 这是首选位置,因为 TwinBASIC 发行版本身不会被修改,升级到新版本时外接程序不会丢失。 2. `\addins` - 如果你想修改你的 TwinBASIC 安装。一般不建议这样做。 ::: ::: details 如何在 twinBASIC 中使用资源? 目前 tB 没有专用的资源编辑器;相反,资源通过项目资源管理器管理。在树中,你会看到一个 Resources 文件夹;默认情况下,标准 EXE 会包含 ICON,如果你选择启用视觉样式,还会有 MANIFEST: ![image](/assets/71ddde83-a091-47e3-b5b8-681954b0639d.C95CiN1h.png) 你可以在此创建其他文件夹,使用标准名称。例如可以添加 BITMAP 组,然后与 `LoadResImage` 一起使用。与其前任不同,tB 不限制资源类型:你可以创建任何类型的文件夹,并向其中导入二进制数据。例如,一些社区项目插入了 `UIFILE` 资源用于 Ribbon 控件和 `DIALOG` 资源用于属性表。资源可以通过右键点击你想要放入的文件夹,然后从菜单选择 Add->Import file... 来导入。 如果你导入项目,链接的 .res 文件中的资源将自动导入。 #### 字符串 字符串表资源目前被特殊处理;在 IDE 中以 JSON 编辑。如果你从带 .res 的 VBP 导入,字符串资源将自动转换。如果你右键点击'Resources'文件夹并进入'Add'子菜单,在底部你会找到"Add resource: String table"来添加一个填充了示例字符串的字符串表: ![image](/assets/97cc8655-7a8b-47f3-b52c-eb1ddfce662f.DnjPdcw0.png) #### 组名 如果你为标准资源类型创建新文件夹,twinBASIC 目前识别以下名称,你应在 Resources 下使用这些名称创建文件夹: BITMAP\ CUSTOM\ CURSOR\ ICON\ MANIFEST\ RCDATA\ STRING\ MESSAGETABLE 对于其他标准类型,你必须使用 #(井号)后跟其数字。例如,对于 DIALOG (RT\*DIALOG) 资源,不要将文件夹命名为 dialog,必须命名为 `#5`。ANICURSOR 应命名为 `#21`。依此类推,对于有 `RT*` 常量的[标准类型](https://learn.microsoft.com/en-us/windows/win32/menurc/resource-types)。对于任何其他类型,你可以使用任何你想要的名称,例如 UIFILE 可以直接命名为 UIFILE。 **注意:** 目前 .res 文件只能作为 VBP 的一部分导入。 ::: ::: details 如何为我的程序设置自己的图标? 默认情况下,新创建的项目使用 twinBASIC logo。导入的项目使用设置中选择的窗体的图标。这可以在所有项目中以相同方式修改或设置:在项目设置对话框中,有一个"Icon Form"选项,你可以选择哪个窗体的图标将用于你的 exe。 如果你没有设置该选项,或者你的项目没有窗体,图标可以通过 Resources 文件夹手动管理。 如果你不熟悉在 twinBASIC 中使用资源,请参见上面紧邻此条目。在这种场景下,你的应用程序在资源管理器中使用的图标是 Resources\ICON 文件夹中按字母顺序排在第一位的那个。如果你的项目中没有 ICON 文件夹,可以通过右键点击 Resources 文件夹并选择 Add->Add folder 来创建一个。 ![image](/assets/8611d12a-d7a6-48cc-9544-cb27c5299aa5.BD-jiLGi.png) 在上图中,MyOwnIcon.ico 将被资源管理器和其他应用用来表示你的 .exe,因为它在字母顺序上排在 twinBASIC.ico 之前。 **注意:** 这不会设置为任何窗体的图标;窗体的图标通过属性列表中的"Icon"属性设置。 你可以同时设置 Icon Form 选项并包含额外的 ICON 资源。在这种情况下,Icon Form 优先——它将被插入为 #1,使其成为第一个可能的条目,因此被资源管理器使用。在这种情况下,不要在 Resources 中为你的任何额外图标使用 #1,结果可能不可预测。 ::: ::: details twinBASIC 产生的 EXE/二进制文件的运行时要求是什么? twinBASIC 产生的程序和模块/控件除了标准 Windows 系统 DLL 外没有原生依赖,完全独立/可移植,当然不包括你的代码可能使用的第三方文件。不需要运行时。目前支持的最低 Windows 版本是 **Windows XP**,Windows 2000 支持可能在将来。目前没有计划支持 Windows ME、98、95、NT4 或更早版本,因为这些缺少 tB 提供的基本现代化所需的关键功能。某些新的 tB 独有功能(如子控件透明度)只有在较新版本上使用时才需要。所有功能在 WINE 和 ReactOS 下也应该工作,但测试虽然成功,数量有限。如果你尝试了,请分享你的经验。 ::: ::: details 为什么 twinBASIC 产生的 EXE 比 VB6 大? VB6 应用程序/组件的大部分功能(包括窗体引擎等重要部分)由 msvbvm60.dll 运行时提供,一个 1.4MB 的文件。twinBASIC 应用程序/组件没有这种外部依赖;窗体引擎和所有其他功能都包含在单个 exe 中,所以合并大小不会差太多。随着 LLVM 优化编译的引入,EXE 大小预计将显著减小,即将推出。 ::: --- --- url: /zh/official/Reference/VBRUN/Constants.md --- # Constants 模块 VBRUN **Constants**模块收集了经典VB6窗体、内在控件和运行时服务用于指定其选项值的命名整数枚举 --- 颜色、鼠标指针、键码、拖放状态、OLE容器行为、打印机设置值等。此模块中没有独立常量;所有内容都分组到枚举中,以便**IntelliSense**在每个属性或参数处提供正确的选项。 某些枚举在源代码中标记为\*\*\[MustBeQualified]\*\* --- 其成员必须通过枚举名引用(例如`ControlBorderStyleConstantsCustom.vbCustomBorder`),以避免与类似命名枚举的成员冲突。这在相应枚举页面上有注明。 ## 枚举 * [AlignConstants](/official/Reference/VBRUN/Constants/AlignConstants) -- **Align**属性的对齐值(无、顶部、底部、左侧、右侧) * [AlignmentConstants](/official/Reference/VBRUN/Constants/AlignmentConstants) -- 文本对齐值(左、右、居中) * [AlignmentConstantsNoCenter](/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter) -- 不含居中选项的文本对齐值 * [AppearanceConstants](/official/Reference/VBRUN/Constants/AppearanceConstants) -- 控件的平面或三维绘图样式 * [ApplicationStartConstants](/official/Reference/VBRUN/Constants/ApplicationStartConstants) -- 应用程序是独立启动还是通过Automation启动 * [AspectTypeConstants](/official/Reference/VBRUN/Constants/AspectTypeConstants) -- OLE对象的呈现方面(内容、缩略图、图标、打印) * [AsyncReadConstants](/official/Reference/VBRUN/Constants/AsyncReadConstants) -- **UserControl.AsyncRead**的标志 * [AsyncStatusCodeConstants](/official/Reference/VBRUN/Constants/AsyncStatusCodeConstants) -- **AsyncReadProgress**事件报告的状态代码 * [AsyncTypeConstants](/official/Reference/VBRUN/Constants/AsyncTypeConstants) -- **UserControl.AsyncRead**中正在读取的数据类型 * [BackFillStyleConstants](/official/Reference/VBRUN/Constants/BackFillStyleConstants) -- 控件背景填充是不透明还是透明 * [BorderStyleConstants](/official/Reference/VBRUN/Constants/BorderStyleConstants) -- 绘制形状的线条样式(实线、虚线、点线、透明...) * [ButtonConstants](/official/Reference/VBRUN/Constants/ButtonConstants) -- 标准或图形按钮样式 * [CheckBoxConstants](/official/Reference/VBRUN/Constants/CheckBoxConstants) -- 复选框的状态(未选中、选中、灰色) * [ClipboardConstants](/official/Reference/VBRUN/Constants/ClipboardConstants) -- 剪贴板格式标识符(`vbCFText`、`vbCFBitmap`...) * [ColorConstants](/official/Reference/VBRUN/Constants/ColorConstants) -- 常用命名颜色(`vbBlack`、`vbBlue`、`vbRed`...) * [ComboBoxConstants](/official/Reference/VBRUN/Constants/ComboBoxConstants) -- 组合框样式(下拉、简单、下拉列表) * [ControlBorderStyleConstants](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants) -- 单一边框样式(无或固定单线) * [ControlBorderStyleConstantsCustom](/official/Reference/VBRUN/Constants/ControlBorderStyleConstantsCustom) -- 带自定义绘制选项的单一边框样式 * [ControlTypeConstants](/official/Reference/VBRUN/Constants/ControlTypeConstants) -- 标准内在控件类型的标识符 * [DataBOFconstants](/official/Reference/VBRUN/Constants/DataBOFconstants) -- Data控件到达记录集开头时的操作 * [DataEOFConstants](/official/Reference/VBRUN/Constants/DataEOFConstants) -- Data控件到达记录集末尾时的操作 * [DataErrorConstants](/official/Reference/VBRUN/Constants/DataErrorConstants) -- 对数据绑定操作错误的响应 * [DataValidateConstants](/official/Reference/VBRUN/Constants/DataValidateConstants) -- Data控件**Validate**事件中报告的操作 * [DatabaseTypeConstants](/official/Reference/VBRUN/Constants/DatabaseTypeConstants) -- Data控件使用的数据库引擎(ODBC、Jet、ACE) * [DefaultCursorTypeConstants](/official/Reference/VBRUN/Constants/DefaultCursorTypeConstants) -- Data控件连接的游标类型 * [DockModeConstants](/official/Reference/VBRUN/Constants/DockModeConstants) -- 窗体和工具栏的停靠边缘值 * [DragConstants](/official/Reference/VBRUN/Constants/DragConstants) -- **DragDrop**/**DragOver**报告的状态 * [DragModeConstants](/official/Reference/VBRUN/Constants/DragModeConstants) -- 自动或手动拖动模式 * [DragOverConstants](/official/Reference/VBRUN/Constants/DragOverConstants) -- 拖动悬停事件期间的进入/离开/悬停状态值 * [DrawModeConstants](/official/Reference/VBRUN/Constants/DrawModeConstants) -- **PSet**/**Line**/**Circle**绘图的光栅操作 * [DrawStyleConstants](/official/Reference/VBRUN/Constants/DrawStyleConstants) -- 绘制线条和形状轮廓的线条样式 * [FillStyleConstants](/official/Reference/VBRUN/Constants/FillStyleConstants) -- 填充形状的填充图案 * [FillStyleConstantsEx](/official/Reference/VBRUN/Constants/FillStyleConstantsEx) -- 带twinBASIC渐变扩展的填充图案 * [FormArrangeConstants](/official/Reference/VBRUN/Constants/FormArrangeConstants) -- MDI子窗体排列模式(层叠、平铺...) * [FormBorderStyleConstants](/official/Reference/VBRUN/Constants/FormBorderStyleConstants) -- 窗体窗口边框样式(可调整大小、固定对话框、工具窗口...) * [FormShowConstants](/official/Reference/VBRUN/Constants/FormShowConstants) -- 窗体是模态还是非模态显示 * [FormWindowStateConstants](/official/Reference/VBRUN/Constants/FormWindowStateConstants) -- 正常、最小化或最大化窗口状态 * [HitResultConstants](/official/Reference/VBRUN/Constants/HitResultConstants) -- **UserControl** **HitTest**事件的返回值 * [KeyCodeConstants](/official/Reference/VBRUN/Constants/KeyCodeConstants) -- **KeyDown**/**KeyUp**的虚拟键代码值 * [LinkModeConstants](/official/Reference/VBRUN/Constants/LinkModeConstants) -- DDE链接模式(无、自动、手动、通知) * [ListBoxConstants](/official/Reference/VBRUN/Constants/ListBoxConstants) -- 列表框样式(标准、复选框、色块) * [LoadPictureColorConstants](/official/Reference/VBRUN/Constants/LoadPictureColorConstants) -- **LoadPicture**的颜色深度标志 * [LoadPictureSizeConstants](/official/Reference/VBRUN/Constants/LoadPictureSizeConstants) -- **LoadPicture**的大小选择器 * [LoadResConstants](/official/Reference/VBRUN/Constants/LoadResConstants) -- **LoadResPicture**的资源类型 * [LogEventTypeConstants](/official/Reference/VBRUN/Constants/LogEventTypeConstants) -- **LogEvent**的严重级别(错误、警告、信息) * [LogModeConstants](/official/Reference/VBRUN/Constants/LogModeConstants) -- 应用程序日志的目标和行为标志 * [MenuAccelConstants](/official/Reference/VBRUN/Constants/MenuAccelConstants) -- 菜单项的键盘快捷键代码 * [MenuControlConstants](/official/Reference/VBRUN/Constants/MenuControlConstants) -- 弹出菜单的对齐和触发选项 * [MouseButtonConstants](/official/Reference/VBRUN/Constants/MouseButtonConstants) -- 按下鼠标按钮的位标志(左、右、中) * [MousePointerConstants](/official/Reference/VBRUN/Constants/MousePointerConstants) -- **MousePointer**属性的光标形状 * [MultiSelectConstants](/official/Reference/VBRUN/Constants/MultiSelectConstants) -- 列表框的多选模式 * [NegotiatePositionConstants](/official/Reference/VBRUN/Constants/NegotiatePositionConstants) -- OLE协商菜单的定位 * [OLEContainerActivateConstants](/official/Reference/VBRUN/Constants/OLEContainerActivateConstants) -- **OLE**容器何时激活其嵌入对象 * [OLEContainerConstants](/official/Reference/VBRUN/Constants/OLEContainerConstants) -- 所有**OLE**容器选项值的组合枚举 * [OLEContainerDisplayTypeConstants](/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants) -- 显示内容还是图标 * [OLEContainerSizeModeConstants](/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants) -- 嵌入**OLE**对象的大小调整规则 * [OLEContainerTypesAllowedConstants](/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants) -- 链接、嵌入或任一对象类型 * [OLEContainerUpdateOptionsConstants](/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants) -- **OLE**链接对象的更新模式 * [OLEDragConstants](/official/Reference/VBRUN/Constants/OLEDragConstants) -- 自动或手动**OLE**拖动 * [OLEDropConstants](/official/Reference/VBRUN/Constants/OLEDropConstants) -- 无/手动/自动**OLE**放置目标 * [OLEDropEffectConstants](/official/Reference/VBRUN/Constants/OLEDropEffectConstants) -- **OLE**放置的效果(复制、移动、链接、滚动) * [OldLinkModeConstants](/official/Reference/VBRUN/Constants/OldLinkModeConstants) -- 旧式DDE链接模式(热、冷、服务器) * [PaletteModeConstants](/official/Reference/VBRUN/Constants/PaletteModeConstants) -- 窗体和控件的调色板来源 * [ParentControlsType](/official/Reference/VBRUN/Constants/ParentControlsType) -- [**ParentControls**](/official/Reference/VBRUN/ParentControls/)是否将项包装在其**Extender**中 * [PictureTypeConstants](/official/Reference/VBRUN/Constants/PictureTypeConstants) -- **StdPicture**的类型(位图、图标、元文件、增强元文件) * [PrinterObjectConstants](/official/Reference/VBRUN/Constants/PrinterObjectConstants) -- 所有打印机设置值的组合枚举 * [PrinterObjectConstants\_ColorMode](/official/Reference/VBRUN/Constants/PrinterObjectConstants_ColorMode) -- 彩色或单色打印 * [PrinterObjectConstants\_Duplex](/official/Reference/VBRUN/Constants/PrinterObjectConstants_Duplex) -- 单面或双面打印模式 * [PrinterObjectConstants\_Orientation](/official/Reference/VBRUN/Constants/PrinterObjectConstants_Orientation) -- 纵向或横向纸张方向 * [PrinterObjectConstants\_PaperBin](/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperBin) -- 打印机的纸张来源标识符 * [PrinterObjectConstants\_PaperSize](/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperSize) -- 打印机的纸张大小标识符 * [PrinterObjectConstants\_PrintQuality](/official/Reference/VBRUN/Constants/PrinterObjectConstants_PrintQuality) -- 草稿/低/中/高打印质量 * [QueryUnloadConstants](/official/Reference/VBRUN/Constants/QueryUnloadConstants) -- 窗体**QueryUnload**事件中报告的原因代码 * [RasterOpConstants](/official/Reference/VBRUN/Constants/RasterOpConstants) -- **PaintPicture**的光栅操作代码 * [RecordsetTypeConstants](/official/Reference/VBRUN/Constants/RecordsetTypeConstants) -- 表/动态集/快照记录集类型 * [ScaleModeConstants](/official/Reference/VBRUN/Constants/ScaleModeConstants) -- 窗体或容器**Scale**属性的测量单位 * [ScrollBarConstants](/official/Reference/VBRUN/Constants/ScrollBarConstants) -- 控件应显示哪些滚动条(无、水平、垂直、两者) * [ShapeConstants](/official/Reference/VBRUN/Constants/ShapeConstants) -- **Shape**控件的几何形状选择器 * [ShiftConstants](/official/Reference/VBRUN/Constants/ShiftConstants) -- 鼠标和键盘事件中**Shift**、**Ctrl**和**Alt**的位标志 * [ShortcutConstants](/official/Reference/VBRUN/Constants/ShortcutConstants) -- 菜单项的快捷键标识符 * [StartUpPositionConstants](/official/Reference/VBRUN/Constants/StartUpPositionConstants) -- 窗体的初始位置(手动、所有者、屏幕、默认) * [StorageTypeContants](/official/Reference/VBRUN/Constants/StorageTypeContants) -- **OLE**数据存储介质(`HGLOBAL`、文件、`IStream`、`IStorage`...) * [SystemColorConstants](/official/Reference/VBRUN/Constants/SystemColorConstants) -- 引用系统调色板条目的高值 * [VariantTypeConstants](/official/Reference/VBRUN/Constants/VariantTypeConstants) -- DAO字段类型标签(旧式) * [VerticalAlignmentConstants](/official/Reference/VBRUN/Constants/VerticalAlignmentConstants) -- 垂直文本对齐(顶部、中间、底部) * [ZOrderConstants](/official/Reference/VBRUN/Constants/ZOrderConstants) -- **BringToFront**/**SendToBack**的选择器 ::: info 枚举名称`StorageTypeContants`(注意缺少`s`)在此按运行时暴露的方式原样保留;此拼写错误是VB6的长期遗留问题。 ::: --- --- url: /zh/official/IDE/Menu/Window.md --- # 窗口菜单 ![窗口菜单](/assets/Menu_Window.7aWM8jFy.png "窗口菜单") * 面板布局 * 面板功能 * 键盘快捷键 *** * 主题 * 语言 ## 面板布局 ![窗口面板布局菜单](/assets/Menu_Window_PanelLayouts.2bQJsXZi.png "窗口面板布局菜单") * 默认内置布局 CTRL + # * 全屏编辑器布局 *** * ✔ 自定义布局(未保存) *** * 将当前面板布局另存为... * 管理面板布局... ### 管理面板布局... ![窗口面板布局默认菜单](/assets/Menu_Window_PanelLayouts_ManagePanelLayouts_Default.CrLKEOrw.png "窗口面板布局默认菜单") ```json { "docked": { "type": "horizontal", "variableSize": true, "size": "0%", "content": [ { "id": "TOOLBAR", "variableSize": false, "size": "fit-content" }, { "type": "vertical", "variableSize": true, "size": "0%", "content": [ { "type": "horizontal", "variableSize": false, "size": "79.0109%", "content": [ { "type": "vertical", "variableSize": false, "size": "73.8657%", "content": [ { "id": "TOOLBOX", "variableSize": false, "size": "13.0192%" }, { "id": "EDITOR", "variableSize": true, "size": "0%" } ] }, { "type": "vertical", "variableSize": true, "size": "0%", "content": [ { "type": "vertical", "variableSize": false, "size": "67.9395%", "content": [ { "id": "DEBUG CONSOLE", "variableSize": false, "size": "53.0193%" }, { "id": "PROBLEMS", "variableSize": true, "size": "0%" } ] }, { "type": "vertical", "variableSize": true, "size": "0%", "content": [ { "id": "CALL STACK", "variableSize": true, "size": "0%" }, { "id": "VARIABLES", "variableSize": true, "size": "0%" } ] } ] } ] }, { "type": "horizontal", "variableSize": true, "size": "0%", "content": [ { "id": "PROJECT EXPLORER", "variableSize": false, "size": "60.4237%" }, { "id": "PROPERTIES", "variableSize": true, "size": "0%" } ] } ] } ] }, "floating": [] } ``` ![窗口面板布局全屏菜单](/assets/Menu_Window_PanelLayouts_ManagePanelLayouts_Fullscreen.CqlwdyxE.png "窗口面板布局全屏菜单") ```json { "docked": { "type": "horizontal", "variableSize": true, "size": "0%", "content": [ { "id": "TOOLBAR", "variableSize": false, "size": "fit-content" }, { "type": "vertical", "variableSize": true, "size": "0%", "content": [ { "id": "TOOLBOX", "variableSize": false, "size": "8.49705%" }, { "type": "vertical", "variableSize": true, "size": "0%", "content": [ { "id": "EDITOR", "variableSize": false, "size": "81.8591%" }, { "id": "PROPERTIES", "variableSize": true, "size": "0%" } ] } ] } ] }, "floating": [] } ``` ## 面板功能 ![窗口面板功能菜单](/assets/Menu_Window_PanelFeatures.BY21vJMz.png "窗口面板功能菜单") * ✔ 允许调整停靠面板大小 * ✔ 允许重新排列停靠面板 * ✔ 允许拖出停靠面板 *** * ✔ 允许调整浮动面板大小 * ✔ 允许移动浮动面板 ## 键盘快捷键 ![窗口键盘快捷键菜单](/assets/Menu_Window_KeyboardShortcuts.C7obgwzO.png "窗口键盘快捷键菜单") * ✔ 默认内置键盘快捷键 *** * 管理键盘快捷键 ### 管理键盘快捷键 ![窗口键盘快捷键 - 管理键盘快捷键菜单](/assets/Menu_Window_KeyboardShortcuts_ManageKeyboardShortcuts.Bs5g8M16.png "窗口键盘快捷键 - 管理键盘快捷键菜单") ![窗口键盘快捷键 - 管理键盘快捷键菜单](/assets/Menu_Window_KeyboardShortcuts_ManageKeyboardShortcuts_1.BYjYJHyP.png "窗口键盘快捷键 - 管理键盘快捷键菜单") ```json { "tbMisc_PreventDefaultKeyBehaviour": [ "{KEYDOWN}{CTRL}A", "{KEYDOWN}TAB" ], "tbEditor_SelectAll": [ "{KEYDOWN}{CTRL}A" ], "tbEditor_ClipboardCopy": [ "{KEYDOWN}{CTRL}C", "{KEYDOWN}{CTRL}INSERT" ], "tbEditor_ClipboardCut": [ "{KEYDOWN}{CTRL}X", "{KEYDOWN}{SHIFT}DELETE" ], "tbEditor_ClipboardPaste": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}V" ], "tbEditor_Undo": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}Z" ], "tbEditor_Redo": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}Y" ], "tbEditor_DeleteLeft": [ "{KEYDOWN}{KEYDOWNREPEAT}BACKSPACE", "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}BACKSPACE" ], "tbEditor_DeleteRight": [ "{KEYDOWN}{KEYDOWNREPEAT}DELETE" ], "tbEditor_DeleteLeftWord": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}BACKSPACE" ], "tbEditor_DeleteRightWord": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}DELETE" ], "tbEditor_DeleteLines": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{SHIFT}DELETE" ], "tbEditor_CursorSelectLeft": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}ARROWLEFT" ], "tbEditor_CursorSelectRight": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}ARROWRIGHT" ], "tbEditor_CursorSelectUp": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}ARROWUP" ], "tbEditor_CursorSelectDown": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}ARROWDOWN" ], "tbEditor_CursorSelectLeftWord": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{SHIFT}ARROWLEFT" ], "tbEditor_CursorSelectRightWord": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{SHIFT}ARROWRIGHT" ], "tbEditor_CursorMoveLeft": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWLEFT" ], "tbEditor_CursorMoveRight": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWRIGHT" ], "tbEditor_CursorMoveUp": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWUP" ], "tbEditor_CursorMoveDown": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWDOWN" ], "tbEditor_CursorMoveLeftWord": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}ARROWLEFT" ], "tbEditor_CursorMoveRightWord": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}ARROWRIGHT" ], "tbEditor_CursorMoveStartOfLineHome": [ "{KEYDOWN}HOME" ], "tbEditor_CursorMoveEndOfLine": [ "{KEYDOWN}END" ], "tbEditor_CursorMoveTop": [ "{KEYDOWN}{CTRL}HOME" ], "tbEditor_CursorMoveBottom": [ "{KEYDOWN}{CTRL}END" ], "tbEditor_CursorSelectTop": [ "{KEYDOWN}{CTRL}{SHIFT}HOME" ], "tbEditor_CursorSelectBottom": [ "{KEYDOWN}{CTRL}{SHIFT}END" ], "tbEditor_CursorSelectLineStartHome": [ "{KEYDOWN}{SHIFT}HOME" ], "tbEditor_CursorSelectLineEnd": [ "{KEYDOWN}{SHIFT}END" ], "tbEditor_CursorMovePageUp": [ "{KEYDOWN}{KEYDOWNREPEAT}PAGEUP" ], "tbEditor_CursorMovePageDown": [ "{KEYDOWN}{KEYDOWNREPEAT}PAGEDOWN" ], "tbEditor_CursorSelectPageUp": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}PAGEUP" ], "tbEditor_CursorSelectPageDown": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}PAGEDOWN" ], "tbEditor_InsertLineBreak": [ "{KEYDOWN}{KEYDOWNREPEAT}ENTER" ], "tbEditor_InsertSpace": [ "{KEYDOWN}{KEYDOWNREPEAT}SPACE", "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}SPACE" ], "tbEditor_InsertComma": [ "{KEYDOWN}{KEYDOWNREPEAT}," ], "tbEditor_InsertPeriod": [ "{KEYDOWN}{KEYDOWNREPEAT}." ], "tbEditor_InsertEquals": [ "{KEYDOWN}{KEYDOWNREPEAT}=" ], "tbEditor_InsertPlus": [ "{KEYDOWN}{KEYDOWNREPEAT}+" ], "tbEditor_InsertMinus": [ "{KEYDOWN}{KEYDOWNREPEAT}-" ], "tbEditor_InsertBackslash": [ "{KEYDOWN}{KEYDOWNREPEAT}\\" ], "tbEditor_InsertSlash": [ "{KEYDOWN}{KEYDOWNREPEAT}/" ], "tbEditor_InsertColon": [ "{KEYDOWN}{KEYDOWNREPEAT}:" ], "tbEditor_InsertAmpersand": [ "{KEYDOWN}{KEYDOWNREPEAT}&" ], "tbEditor_InsertExclamation": [ "{KEYDOWN}{KEYDOWNREPEAT}!" ], "tbEditor_InsertMultiply": [ "{KEYDOWN}{KEYDOWNREPEAT}*" ], "tbEditor_MoveToProcedurePrev": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}ARROWUP" ], "tbEditor_MoveToProcedureNext": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}ARROWDOWN" ], "tbEditor_AddCursorAbove": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{ALT}ARROWUP" ], "tbEditor_AddCursorBelow": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{ALT}ARROWDOWN" ], "tbEditor_AddCursorsAtLineEndsOfSelection": [ "{KEYDOWN}{SHIFT}{ALT}I" ], "tbEditor_ClipboardCutPlain": [ "{KEYDOWN}{CTRL}{SHIFT}X" ], "tbEditor_ClipboardPlainCopy": [ "{KEYDOWN}{CTRL}{SHIFT}C" ], "tbEditor_ClipboardPlainPaste": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{SHIFT}V" ], "tbEditor_ClipboardPasteAsComment": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{ALT}V" ], "tbEditor_CommentSelection": [ "{KEYDOWN}{CTRL}K" ], "tbEditor_UncommentSelection": [ "{KEYDOWN}{CTRL}{SHIFT}K" ], "tbEditor_GoToDefinition": [ "{KEYDOWN}{SHIFT}F2", "{KEYDOWN}F12" ], "tbEditor_ToggleBookmark": [ "{KEYDOWN}{CTRL}B" ], "tbEditor_PrevBookmark": [ "{KEYDOWN}{CTRL}M" ], "tbEditor_Find": [ "{KEYDOWN}{CTRL}F" ], "tbFindWidget_ShowFind": [ "{KEYDOWN}{ALT}F" ], "tbFindWidget_ShowReplace": [ "{KEYDOWN}{ALT}H" ], "tbEditor_FindWidget_SelectAllMatches": [ "{KEYDOWN}{ALT}A" ], "tbEditor_FindReplace": [ "{KEYDOWN}{CTRL}H" ], "tbEditor_LastPosition": [ "{KEYDOWN}{CTRL}{SHIFT}F2" ], "tbEditor_InsertLineAbove": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{SHIFT}ENTER" ], "tbEditor_InsertLineBelow": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}ENTER" ], "tbEditor_IndentLine": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}]" ], "tbEditor_OutdentLine": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}[" ], "tbEditor_Fold": [ "{KEYDOWN}{CTRL}{" ], "tbEditor_Unfold": [ "{KEYDOWN}{CTRL}}" ], "tbEditor_FoldProcedures": [ "{KEYDOWN}{CTRL}{ALT}ARROWLEFT" ], "tbEditor_UnfoldProcedures": [ "{KEYDOWN}{CTRL}{ALT}ARROWRIGHT" ], "tbEditor_ToggleLineComment": [ "{KEYDOWN}{CTRL}/" ], "tbEditor_ShowContextMenu": [ "{KEYDOWN}{SHIFT}F10" ], "tbEditor_JumpToNextProblem": [ "{KEYDOWN}{KEYDOWNREPEAT}{ALT}F8" ], "tbEditor_JumpToPrevProblem": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}{ALT}F8" ], "tbEditor_FindWidget_Next": [ "{KEYDOWN}{KEYDOWNREPEAT}{ALT}F3" ], "tbEditor_FindWidget_Prev": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}{ALT}F3" ], "tbEditor_FindSelectedNext": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}F3" ], "tbEditor_FindSelectedPrev": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{SHIFT}F3" ], "tbEditor_ShrinkSelection": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}{ALT}ARROWLEFT" ], "tbEditor_ExpandSelection": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}{ALT}ARROWRIGHT" ], "tbEditor_ExpandLineSelection": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}L" ], "tbEditor_CursorUndo": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}U" ], "tbEditor_CopyLineDown": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}{ALT}ARROWDOWN" ], "tbEditor_CopyLineUp": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}{ALT}ARROWUP" ], "tbEditor_MoveLinesDown": [ "{KEYDOWN}{KEYDOWNREPEAT}{ALT}ARROWDOWN" ], "tbEditor_MoveLinesUp": [ "{KEYDOWN}{KEYDOWNREPEAT}{ALT}ARROWUP" ], "tbEditor_RenameSymbol": [ "{KEYDOWN}F2" ], "tbEditor_SelectAllMatches": [ "{KEYDOWN}{CTRL}{SHIFT}L" ], "tbEditor_ToggleBlockComment": [ "{KEYDOWN}{SHIFT}{ALT}A" ], "tbEditor_Indent": [ "{KEYDOWN}{KEYDOWNREPEAT}TAB" ], "tbEditor_Outdent": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}TAB" ], "tbEditor_IncreaseFontSize": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}+" ], "tbEditor_DecreaseFontSize": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}-" ], "tbEditor_CodeSelector1_Dropdown": [ "{KEYDOWN}{CTRL}1" ], "tbEditor_CodeSelector2_Dropdown": [ "{KEYDOWN}{CTRL}2" ], "tbEditor_CodeSelector3_Dropdown": [ "{KEYDOWN}{CTRL}3" ], "tbEditor_TurnShowCodeHintsOn": [ "{KEYDOWN}CONTROL" ], "tbEditor_TurnShowCodeHintsOff": [ "CONTROL" ], "tbEditor_ToggleWordWrap": [ "{KEYDOWN}{ALT}Z" ], "tbEditor_CloseTab": [ "{KEYDOWN}{CTRL}F4", "{KEYDOWN}{CTRL}W" ], "tbEditor_ReopenLastClosedTab": [ "{KEYDOWN}{CTRL}{SHIFT}T" ], "tbEditor_ActivateNextTab": [ "{KEYDOWN}{CTRL}TAB" ], "tbEditor_ActivatePrevTab": [ "{KEYDOWN}{CTRL}{SHIFT}TAB" ], "tbProject_SaveAllChanges": [ "{KEYDOWN}{CTRL}S" ], "tbEditor_SwitchToggleFormDesignCode": [], "tbEditor_SwitchToFormDesign": [ "{KEYDOWN}{SHIFT}F7" ], "tbProjectExplorer_SelectedItemsClipboardCut": [ "{KEYDOWN}{CTRL}X", "{KEYDOWN}{SHIFT}DELETE" ], "tbFormDesigner_ClipboardCut": [ "{KEYDOWN}{CTRL}X", "{KEYDOWN}{SHIFT}DELETE" ], "tbFormDesigner_ClipboardCopy": [ "{KEYDOWN}{CTRL}C", "{KEYDOWN}{CTRL}INSERT" ], "tbProjectExplorer_SelectedItemsClipboardCopy": [ "{KEYDOWN}{CTRL}C", "{KEYDOWN}{CTRL}INSERT" ], "tbFormDesigner_ClipboardPaste": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}V" ], "tbProjectExplorer_ClipboardPaste": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}V" ], "tbFindWidget_Hide": [ "{KEYDOWN}ESCAPE" ], "tbFindWidget_FindNext": [ "{KEYDOWN}{KEYDOWNREPEAT}ENTER" ], "tbFindWidget_FindPrevious": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}ENTER" ], "tbFindWidget_FindNextInSelection": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}F3" ], "tbFindWidget_FindPrevInSelection": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{SHIFT}F3" ], "tbFindWidget_HistoryCyclePrevious": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWUP" ], "tbFindWidget_HistoryCycleNext": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWDOWN" ], "tbProject_ShowReferences": [ "{KEYDOWN}{CTRL}T" ], "tbFindReplace_Cancel": [ "{KEYDOWN}ESCAPE" ], "tbFindReplace_Next": [ "{KEYDOWN}{KEYDOWNREPEAT}F3" ], "tbFindReplace_Prev": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}F3" ], "tbFindReplace_ReplaceNext": [ "{KEYDOWN}{ALT}R" ], "tbFindReplace_ReplaceAll": [ "{KEYDOWN}{ALT}A" ], "tbFindReplace_FocusNext": [ "{KEYDOWN}{ALT}N" ], "tbFindReplace_FocusFindWhat": [ "{KEYDOWN}{ALT}F" ], "tbFindReplace_FocusReplaceWith": [ "{KEYDOWN}{ALT}W" ], "tbFindReplace_FocusCurrentProcedure": [ "{KEYDOWN}{ALT}P" ], "tbFindReplace_FocusCurrentModule": [ "{KEYDOWN}{ALT}M" ], "tbFindReplace_FocusCurrentProject": [ "{KEYDOWN}{ALT}C" ], "tbFindReplace_FocusDirection": [ "{KEYDOWN}{ALT}D" ], "tbFindReplace_FocusWholeWordOnlyToggle": [ "{KEYDOWN}{ALT}O" ], "tbFindReplace_FocusMatchCaseToggle": [ "{KEYDOWN}{ALT}S" ], "tbFindReplace_FocusUsePatternMatchingToggle": [ "{KEYDOWN}{ALT}U" ], "tbFormDesigner_Undo": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}Z" ], "tbFormDesigner_Redo": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}Y" ], "tbProject_Export": [ "{KEYDOWN}{CTRL}E" ], "tbProject_FindInFiles": [ "{KEYDOWN}{CTRL}{SHIFT}F" ], "tbDebug_StartOrContinue": [ "{KEYDOWN}F5" ], "tbDebug_BreakInto": [ "{KEYDOWN}{CTRL}CANCEL" ], "tbDebug_StepOver": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}F8", "{KEYDOWN}{KEYDOWNREPEAT}F10" ], "tbDebug_StepInto": [ "{KEYDOWN}{KEYDOWNREPEAT}F8", "{KEYDOWN}{KEYDOWNREPEAT}F11" ], "tbDebug_StepOut": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{SHIFT}F8", "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}F11" ], "tbDebug_RunOrPreview": [ "{KEYDOWN}F6" ], "tbBuild_SwitchToWin64": [ "{KEYDOWN}{CTRL}F1" ], "tbBuild_SwitchToWin32": [ "{KEYDOWN}{CTRL}F2" ], "tbHelp_ToggleExpandSignatureHelp": [ "{KEYDOWN}F1" ], "tbDebug_SetNextExecutionStatement": [ "{KEYDOWN}{CTRL}F9" ], "tbDebug_ToggleBreakpoint": [ "{KEYDOWN}F9" ], "tbWatches_Add": [ "{KEYDOWN}{SHIFT}F9" ], "tbIde_IncreaseFontSize": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{ALT}+" ], "tbIde_DecreaseFontSize": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}{ALT}-" ], "tbIdeWindow_Close": [ "{KEYDOWN}{ALT}F4" ], "tbDebugConsole_FocusPanel": [ "{KEYDOWN}{CTRL}G" ], "tbFormDesigner_MenuEditorRename": [ "{KEYDOWN}F2" ], "tbFormDesigner_MenuEditorDelete": [ "{KEYDOWN}DELETE" ], "tbFormDesigner_MenuEditorMoveLeft": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}ARROWLEFT" ], "tbFormDesigner_MenuEditorMoveUp": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}ARROWUP" ], "tbFormDesigner_MenuEditorMoveRight": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}ARROWRIGHT" ], "tbFormDesigner_MenuEditorMoveDown": [ "{KEYDOWN}{KEYDOWNREPEAT}{CTRL}ARROWDOWN" ], "tbFormDesigner_MenuEditorToggleChecked": [ "{KEYDOWN}{KEYDOWNREPEAT}SPACE" ], "tbFormDesigner_SelectAllControls": [ "{KEYDOWN}{CTRL}A" ], "tbFormDesigner_DeleteSelectedControls": [ "{KEYDOWN}DELETE" ], "tbFormDesigner_SelectParentOfSelectedControl": [ "{KEYDOWN}ESCAPE" ], "tbFormDesigner_SelectToolboxPointer": [ "{KEYDOWN}ESCAPE" ], "tbFormDesigner_AlignSelectedControlsLeft": [ "{KEYDOWN}{ALT}ARROWLEFT" ], "tbFormDesigner_AlignSelectedControlsTop": [ "{KEYDOWN}{ALT}ARROWUP" ], "tbFormDesigner_AlignSelectedControlsRight": [ "{KEYDOWN}{ALT}ARROWRIGHT" ], "tbFormDesigner_AlignSelectedControlsBottom": [ "{KEYDOWN}{ALT}ARROWDOWN" ], "tbFormDesigner_ResizeSelectedControlsWidest": [ "{KEYDOWN}{CTRL}{SHIFT}ARROWRIGHT" ], "tbFormDesigner_ResizeSelectedControlsTallest": [ "{KEYDOWN}{CTRL}{SHIFT}ARROWDOWN" ], "tbFormDesigner_ResizeSelectedControlsNarrowest": [ "{KEYDOWN}{CTRL}{SHIFT}ARROWLEFT" ], "tbFormDesigner_ResizeSelectedControlsShortest": [ "{KEYDOWN}{CTRL}{SHIFT}ARROWUP" ], "tbFormDesigner_ResizeSelectedControlsNarrower": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}ARROWLEFT" ], "tbFormDesigner_MoveSelectedControlsLeft": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWLEFT" ], "tbFormDesigner_ResizeSelectedControlsWider": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}ARROWRIGHT" ], "tbFormDesigner_MoveSelectedControlsRight": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWRIGHT" ], "tbFormDesigner_ResizeSelectedControlsShorter": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}ARROWUP" ], "tbFormDesigner_MoveSelectedControlsUp": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWUP" ], "tbFormDesigner_ResizeSelectedControlsTaller": [ "{KEYDOWN}{KEYDOWNREPEAT}{SHIFT}ARROWDOWN" ], "tbFormDesigner_MoveSelectedControlsDown": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWDOWN" ], "tbFormDesigner_TurnShowTabIndexOn": [ "{KEYDOWN}CONTROL" ], "tbFormDesigner_TurnShowTabIndexOff": [ "CONTROL" ], "tbMenu_FocusAdjacentLeft": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWLEFT" ], "tbMenu_FocusAdjacentRight": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWRIGHT" ], "tbMenu_FocusAdjacentUp": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWUP" ], "tbMenu_FocusAdjacentDown": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWDOWN" ], "tbMenu_ExecuteFocusedEntry": [ "{KEYDOWN}{KEYDOWNREPEAT}ENTER" ], "tbMisc_SaveProjectMetaStateInTwinproj": [ "{KEYDOWN}{CTRL}{SHIFT}{ALT}M" ], "tbMisc_ShiftKeyStateDown": [ "{KEYDOWN}SHIFT" ], "tbMisc_ShiftKeyStateUp": [ "SHIFT" ], "tbMisc_AltKeyStateDown": [ "{KEYDOWN}ALT" ], "tbMisc_AltKeyStateUp": [ "ALT" ], "tbMenu_Cancel": [ "{KEYDOWN}ESCAPE" ], "tbProject_Open": [ "{KEYDOWN}{CTRL}O" ], "tbProject_New": [ "{KEYDOWN}{CTRL}N" ], "tbProjectExplorer_ToggleFileMode": [ "{KEYDOWN}{CTRL}R" ], "tbCallStack_ShowPanel": [ "{KEYDOWN}{CTRL}L" ], "tbDebugConsole_ShowPanel": [ "{KEYDOWN}{CTRL}G" ], "tbDebug_BreakpointsClear": [ "{KEYDOWN}{CTRL}{SHIFT}F9" ], "tbProjectExplorer_SelectedItemsRename": [ "{KEYDOWN}F2" ], "tbProjectExplorer_SelectedItemsDeletePermanently": [ "{KEYDOWN}DELETE" ], "tbDebugConsole_HistoryCyclePrevious": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWUP" ], "tbDebugConsole_HistoryCycleNext": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWDOWN" ], "tbIntellisense_SelectPrevious": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWUP" ], "tbIntellisense_SelectNext": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWDOWN" ], "tbIntellisense_AcceptSelectedEntry": [ "{KEYDOWN}TAB", "SPACE", "ENTER", ",", ".", "+", "-", "&", "(", ")", "!", "*", "\\", "/", ":", "=" ], "tbDebugConsole_ExecuteEnteredLine": [ "{KEYDOWN}ENTER" ], "tbDebugConsole_GoToDefinition": [ "{KEYDOWN}{SHIFT}F2", "{KEYDOWN}F12" ], "tbIntellisense_AcceptSelectedOrFirstEntry": [ "{KEYDOWN}TAB", "{KEYDOWN}SPACE" ], "tbIntellisense_Cancel": [ "{KEYDOWN}ESCAPE", "{KEYDOWN}ARROWLEFT", "{KEYDOWN}ARROWRIGHT", "{KEYDOWN}BACKSPACE" ], "tbSignatureHelpCancel": [ "{KEYDOWN}ESCAPE", "{KEYDOWN}ARROWUP", "{KEYDOWN}ARROWDOWN" ], "tbIntellisense_ShowNow": [ "{KEYDOWN}{CTRL}SPACE" ], "tbIntellisense_ShowAfterKeyPress": [ "{ALLEXCEPT}ARROWUP|ARROWDOWN|ARROWLEFT|ARROWRIGHT|ESCAPE|SHIFT|CONTROL|ALT|TAB|SPACE|ENTER|BACKSPACE|F1|F2|F3|F4|F5|F6|F7|F8|F9|F10|F11|F12|F13|F14|F15|F16|F17|F18|F19|F20|DELETE|HOME|END|CANCEL|PAGEUP|PAGEDOWN|&|+|-|*|/|\\|^" ], "tbDebugConsole_SelectAllEntryBox": [ "{KEYDOWN}{CTRL}A" ], "tbPanels_SetActiveLayoutDefault": [ "{KEYDOWN}{CTRL}#" ], "tbEditor_AddSelectionToNextFindMatch": [ "{KEYDOWN}{CTRL}D" ], "tbToolbox_SelectNextTool": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWDOWN", "{KEYDOWN}{KEYDOWNREPEAT}ARROWRIGHT" ], "tbToolbox_SelectPrevTool": [ "{KEYDOWN}{KEYDOWNREPEAT}ARROWUP", "{KEYDOWN}{KEYDOWNREPEAT}ARROWLEFT" ] } ``` ## 主题 ![窗口主题菜单](/assets/Menu_Window_Theme.BzuIyvgH.png "窗口主题菜单") * 经典(浅色) * ✔ 深色 * 浅色 *** * 从磁盘重新加载 ## 语言 ![窗口语言菜单](/assets/Menu_Window_Language.B7kwePIA.png "窗口语言菜单") * ... * 英语(英式英语) * ... --- --- url: /zh/packages/vbccr/text/windowedlabel.md description: 窗口化标签控件(WindowedLabel) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 窗口化标签控件(WindowedLabel) 提供具有窗口句柄的标签控件,支持省略号显示、垂直对齐、自动换行和透明背景等增强功能。 ## 枚举 ### WlbEllipsisFormatConstants 省略号格式常量。 | 常量 | 值 | 说明 | |------|-----|------| | WlbEllipsisNone | 0 | 不显示省略号 | | WlbEllipsisEnd | 1 | 在文本末尾显示省略号 | | WlbEllipsisPath | 2 | 在路径中间显示省略号(保留文件名) | | WlbEllipsisWord | 3 | 在单词边界显示省略号 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### Container ```vb Public Property Get Container() As Object Public Property Set Container(ByVal Value As Object) ``` 返回/设置对象的容器。 ### Left ```vb Public Property Get Left() As Single Public Property Let Left(ByVal Value As Single) ``` 返回/设置对象与其容器左边缘的距离。 ### Top ```vb Public Property Get Top() As Single Public Property Let Top(ByVal Value As Single) ``` 返回/设置对象与其容器顶边缘的距离。 ### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 返回/设置对象的宽度。 ### Height ```vb Public Property Get Height() As Single Public Property Let Height(ByVal Value As Single) ``` 返回/设置对象的高度。 ### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 返回/设置鼠标悬停时显示的提示文本。 ### WhatsThisHelpID ```vb Public Property Get WhatsThisHelpID() As Long Public Property Let WhatsThisHelpID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### DragIcon ```vb Public Property Get DragIcon() As IPictureDisp Public Property Let DragIcon(ByVal Value As IPictureDisp) Public Property Set DragIcon(ByVal Value As IPictureDisp) ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Public Property Get DragMode() As Integer Public Property Let DragMode(ByVal Value As Integer) ``` 返回/设置拖动模式。 ### hWnd ```vb Public Property Get hWnd() As LongPtr ``` 返回控件句柄。 ### Font ```vb Public Property Get Font() As StdFont Public Property Let Font(ByVal NewFont As StdFont) Public Property Set Font(ByVal NewFont As StdFont) ``` 返回/设置字体。 ### Appearance ```vb Public Property Get Appearance() As CCAppearanceConstants Public Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` 返回/设置外观样式。参见通用枚举。 ### BackColor ```vb Public Property Get BackColor() As OLE_COLOR Public Property Let BackColor(ByVal Value As OLE_COLOR) ``` 返回/设置背景色。 ### ForeColor ```vb Public Property Get ForeColor() As OLE_COLOR Public Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 返回/设置前景色。 ### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 返回/设置对象是否能响应用户事件。 ### OLEDropMode ```vb Public Property Get OLEDropMode() As OLEDropModeConstants Public Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` 返回/设置对象是否可以作为OLE放置目标。 ### MousePointer ```vb Public Property Get MousePointer() As CCMousePointerConstants Public Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 返回/设置鼠标悬停时显示的指针类型。参见通用枚举。 ### MouseIcon ```vb Public Property Get MouseIcon() As IPictureDisp Public Property Let MouseIcon(ByVal Value As IPictureDisp) Public Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Public Property Get MouseTrack() As Boolean Public Property Let MouseTrack(ByVal Value As Boolean) ``` 返回/设置是否在鼠标进入或离开控件时触发事件。 ### RightToLeft ```vb Public Property Get RightToLeft() As Boolean Public Property Let RightToLeft(ByVal Value As Boolean) ``` 返回/设置从右到左显示方向。 ### RightToLeftMode ```vb Public Property Get RightToLeftMode() As CCRightToLeftModeConstants Public Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 返回/设置从右到左模式。参见通用枚举。 ### Alignment ```vb Public Property Get Alignment() As VBRUN.AlignmentConstants Public Property Let Alignment(ByVal Value As VBRUN.AlignmentConstants) ``` 返回/设置文本水平对齐方式。 ### BorderStyle ```vb Public Property Get BorderStyle() As CCBorderStyleConstants Public Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` 返回/设置边框样式。参见通用枚举。 ### Caption ```vb Public Property Get Caption() As String Public Property Let Caption(ByVal Value As String) ``` 返回/设置标签文本。 ### Default ```vb Public Property Get Default() As String Public Property Let Default(ByVal Value As String) ``` 返回/设置默认文本。 ### UseMnemonic ```vb Public Property Get UseMnemonic() As Boolean Public Property Let UseMnemonic(ByVal Value As Boolean) ``` 返回/设置是否处理助记符前缀(&字符)。 ### AutoSize ```vb Public Property Get AutoSize() As Boolean Public Property Let AutoSize(ByVal Value As Boolean) ``` 返回/设置是否自动调整大小以适应内容。 ### WordWrap ```vb Public Property Get WordWrap() As Boolean Public Property Let WordWrap(ByVal Value As Boolean) ``` 返回/设置是否自动换行。 ### SingleLine ```vb Public Property Get SingleLine() As Boolean Public Property Let SingleLine(ByVal Value As Boolean) ``` 返回/设置是否强制单行显示。 ### EllipsisFormat ```vb Public Property Get EllipsisFormat() As WlbEllipsisFormatConstants Public Property Let EllipsisFormat(ByVal Value As WlbEllipsisFormatConstants) ``` 返回/设置省略号格式。 ### MimicTextBox ```vb Public Property Get MimicTextBox() As Boolean Public Property Let MimicTextBox(ByVal Value As Boolean) ``` 返回/设置是否模拟文本框外观(3D边框+白色背景)。 ### VerticalAlignment ```vb Public Property Get VerticalAlignment() As CCVerticalAlignmentConstants Public Property Let VerticalAlignment(ByVal Value As CCVerticalAlignmentConstants) ``` 返回/设置垂直对齐方式。参见通用枚举。 ### Transparent ```vb Public Property Get Transparent() As Boolean Public Property Let Transparent(ByVal Value As Boolean) ``` 返回/设置是否使用透明背景。 ### DisplayedCaption ```vb Public Property Get DisplayedCaption() As String ``` 返回实际显示的文本(包含省略号处理后的结果)。 ## 方法 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动OLE拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置Z顺序。 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘对象。 ## 事件 ### Click ```vb Public Event Click() ``` 用户单击控件时触发。 ### DblClick ```vb Public Event DblClick() ``` 用户双击控件时触发。 ### Change ```vb Public Event Change() ``` Caption属性改变时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件区域时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件区域时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE拖放操作完成时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE拖放操作放置时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE拖放操作悬停时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE拖放操作给反馈时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE拖放操作设置数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE拖放操作开始时触发。 ## 代码示例 ### 基本用法 ```vb ' 设置窗口化标签 With WindowedLabel1 .Caption = "C:\Users\Documents\Very\Long\Path\FileName.txt" .AutoSize = False .EllipsisFormat = WlbEllipsisPath .VerticalAlignment = CCVerticalAlignmentCenter .WordWrap = False .SingleLine = True .UseMnemonic = False End With ' 监听文本变化 Private Sub WindowedLabel1_Change() Debug.Print "显示文本: " & WindowedLabel1.DisplayedCaption End Sub ' 模拟文本框外观的标签 With WindowedLabel1 .MimicTextBox = True .BorderStyle = CCBorderStyleSunken End With ``` --- --- url: /zh/official/Features/GUI-Components/Forms.md --- # 窗体功能 twinBASIC 为窗体和窗体处理提供了大量增强。 ## 现代图像格式支持 你不再面对 tB 窗体和控件中极其有限的图像格式选择;不仅 Bitmap 和 Icon 格式支持其全部格式范围,你还可以加载 PNG 图像、JPEG 图像、Metafile(.emf/.wmf)和 SVG 矢量图形(.svg)。 ### 增强的 LoadPicture 此外,`LoadPicture` 可以直接从字节数组加载所有图像类型,而无需磁盘上的文件。你可以使用此功能从资源文件或其他来源加载图像。注意,如果你的项目引用了 stdole2.tlb(大多数都是),目前你必须限定为 `Global.LoadPicture` 以获取支持字节数组的 tB 自定义绑定。 ## 透明度和 Alpha 混合 ### Form.TransparencyKey 这个新属性指定一种颜色,该颜色对 z 序中其下方窗口(所有窗口,不只是你的项目中的)完全透明。设置此属性将使指定颜色变为 100% 透明。使用具有实心 `FillStyle` 的 Shape 控件是将窗体区域着色为透明色的有用工具。 ### Form.Opacity 这为整个窗体设置 Alpha 混合级别。与透明度一样,这是对紧邻其下方的所有窗口。注意,被 `TransparencyKey` 颜色覆盖的任何区域将保持 100% 透明。 下图展示了一个具有红色 `TransparencyKey` 的窗体,使用 Shape 控件定义透明区域,同时为整个窗体指定了 75% 的 `Opacity`: ![image](/assets/85f25aa2-abc8-4d42-8510-078f8ee4a324.CxpsK7Bj.png) ## 附加窗体功能 除了上述之外,窗体还有: * `DpiScaleX`/`DpiScaleY` 属性用于获取当前值 * `.MinWidth`、`.MinHeight`、`.MaxWidth` 和 `.MaxHeight` 属性,无需子类化即可实现 * `Form.TopMost` 属性 * 控件锚定:控件的 x/y/cx/cy 可以设为相对值,因此它们会随窗体自动移动/调整大小。例如,如果你将 TextBox 放在右下角,然后勾选右边和下边的锚定(除了上边和左边),右下角会随窗体调整大小。这节省了大量样板式的大小调整代码。 * 控件停靠:控件可以固定在窗体(或容器)的任一边,或填充整个窗体/容器。多个控件可以在停靠位置上进行组合和混搭。 有关控件锚定和控件停靠的更多信息,请参见[锚定和停靠页面](/official/Features/GUI-Components/Anchoring-Docking)。 ## 图像控件中的高质量缩放 图像控件现在提供 `StretchMode` 属性,允许你选择 Bilinear、Bicubic、Lanczos3 和 Lanczos8 拉伸算法,这些远优于默认拉伸算法。它们使用内置算法,不会增加额外的依赖或 API 调用。 ## DPI 缩放 窗体、UserControl 和 PictureBox 的 PictureDpiScaling 属性:PictureDpiScaling 属性允许你关闭图像的 DPI 缩放,使其以 1:1 显示而非让操作系统拉伸它们。这样做的想法是你可能希望手动选择不同的位图,而不是应用 somewhat 有限的操作系统拉伸。 --- --- url: /zh/official/Tutorials/Forms.md --- # 窗体基础 本教程构建一个小型温度转换器应用程序。完成后你将知道如何向窗体添加标准控件、在设计时和运行时设置其属性、编写事件处理程序以及验证用户输入。 ## 你将构建什么 一个带有一个窗体的标准EXE。用户输入温度值,选择转换方向(摄氏转华氏或华氏转摄氏),点击按钮,查看结果。完成的窗体大致如下: 这个示例足够小,不到十分钟就能完成,但它涉及了几乎所有VB6兼容程序中都会出现的控件和模式。 ## 步骤1:创建项目 打开twinBASIC,选择**文件 → 新建项目 → 标准EXE**。IDE会创建一个新项目,其中包含一个已在设计器中打开的窗体 `Form1`。 ## 步骤2:添加和排列控件 左侧的工具箱面板列出了当前项目中可用的控件。你需要四种控件类型:**Label**、**TextBox**、**Frame**(用于分组OptionButton)、**OptionButton**、**CommandButton**和第二个用于输出的**Label**。如果工具箱不可见,通过**视图 → 工具箱**打开它。 双击工具箱中的控件将其放置到窗体上,或在工具箱中单击一次然后在窗体上拖动矩形来放置和调整大小。 按顺序添加以下控件: | 控件 | 名称 | 标题/文本 | 用途 | |---------|------|----------------|---------| | Label | `lblInputPrompt` | `Temperature:` | 输入字段的提示 | | TextBox | `txtInput` | *(空白)* | 用户在此输入温度值 | | Frame | `fraDirection` | `Convert` | 分组两个OptionButton | | OptionButton | `optCtoF` | `Celsius → Fahrenheit` | 方向选择器 | | OptionButton | `optFtoC` | `Fahrenheit → Celsius` | 方向选择器 | | CommandButton | `cmdConvert` | `Convert` | 触发计算 | | Label | `lblResult` | *(空白)* | 显示结果 | 要重命名控件,选中它并在右侧的属性窗口中更改**Name**属性。通过设置**Caption**属性(用于标签、框架、选项按钮和命令按钮)或**Text**属性(用于文本框)来更改显示文本。 ::: info 将两个OptionButton放在Frame内部,方法是拖动它们到框架上而不是直接到窗体上。Frame内的控件形成互斥组——选择一个会自动取消选择其他。 ::: ### 在设计时设置属性 选中 `optCtoF` 并在属性窗口中将其**Value**属性设为 `True`。这使其成为窗体打开时的默认选择。 选中 `lblResult` 并设置其**Font**属性。点击Font值旁边的 `...` 按钮打开字体对话框。选择一个使结果易于阅读的大小,如12磅。 ## 步骤3:编写事件处理程序 在设计器中双击 `cmdConvert` 按钮。IDE切换到代码编辑器并为按钮的Click事件创建一个框架: ```vb Private Sub cmdConvert_Click() End Sub ``` 按以下内容填充: ```vb Private Sub cmdConvert_Click() If Not IsNumeric(txtInput.Text) Then lblResult.Caption = "Please enter a number." Exit Sub End If Dim value As Double value = CDbl(txtInput.Text) Dim result As Double Dim unit As String If optCtoF.Value Then result = value * 9 / 5 + 32 unit = "°F" Else result = (value - 32) * 5 / 9 unit = "°C" End If lblResult.Caption = Format(result, "0.00") & " " & unit End Sub ``` 处理程序: 1. 在转换前检查输入是否为数字。[**IsNumeric**](/official/Reference/VBA/Information/IsNumeric)对空字符串、字母或除小数点和前导负号外的标点符号返回 `False`。 2. 读取 `optCtoF.Value` 来确定方向。因为两个OptionButton在同一个Frame中,它们中恰好有一个始终为 `True`。 3. 调用[**Format**](/official/Reference/VBA/Strings/Format)将结果四舍五入到两位小数。 ## 步骤4:运行应用程序 按**F5**(或**运行 → 启动**)。窗体出现。在文本框中输入 `100`,确保选中了 `Celsius → Fahrenheit`,然后点击**Convert**。标签应显示 `212.00 °F`。 试试切换到 `Fahrenheit → Celsius` 并转换 `32`——结果应为 `0.00 °C`。 关闭窗体以停止应用程序并返回IDE。 ## 在运行时设置属性 设计时属性方便但有限。你可以随时从代码中读写大多数控件属性。添加一个 `Form_Load` 处理程序来设置窗体的标题栏文本并给 `lblResult` 一个初始标题: ```vb Private Sub Form_Load() Me.Caption = "Temperature Converter" lblResult.Caption = "Enter a value and click Convert." optCtoF.Value = True ' ensure the default is set in code too End Sub ``` `Me` 引用当前窗体——等同于在窗体自身模块内编写 `Form1`。 ## 处理KeyPress事件 当用户在文本框中按**Enter**键时触发转换通常很方便,无需点击按钮。在设计器中双击 `txtInput` 打开代码编辑器,然后从右上角的事件下拉框中选择 `KeyPress`: ```vb Private Sub txtInput_KeyPress(KeyAscii As Integer) If KeyAscii = vbKeyReturn Then KeyAscii = 0 ' suppress the beep cmdConvert_Click ' reuse the button's handler End If End Sub ``` [**vbKeyReturn**](/official/Reference/VBRUN/Constants/KeyCodeConstants)是Enter键的常量(ASCII 13)。将 `KeyAscii` 设为 `0` 告诉控件不再处理该按键——没有这行代码,在TextBox中按Enter会在大多数系统上发出蜂鸣声。 ## 关于锚定和停靠的说明 上面添加的控件使用绝对位置。如果用户调整窗体大小,控件会停留在你放置的位置,布局可能看起来不协调。twinBASIC支持**锚定**(控件与一个或多个窗体边缘保持固定距离)和**停靠**(控件填充边缘或整个客户区)。 这些行为通过VB包控件上的**Anchor**和**Dock**属性设置。完整说明见[特性 → 锚定和停靠](/official/Features/GUI-Components/Anchoring-Docking)。 ## 下一步 * **Windows API** —— 调用Win32函数读取系统信息和驱动平台功能:[调用Windows API](/official/Tutorials/Windows-API) * **自定义控件** —— 带渐变填充和逐像素绘制的自绘控件:[CustomControls教程](/official/Tutorials/CustomControls/) * **WebView2** —— 在窗体中嵌入Microsoft Edge浏览器引擎:[WebView2教程](/official/Tutorials/WebView2/) --- --- url: /zh/official/Features/Packages/Creating-a-TWINPACK-package.md --- # 创建 TWINPACK 包 要创建新的 TWINPACK 包,请导航到 twinBASIC 新建项目对话框,在"Samples"选项卡下选择标记为"Package"的选项: ![image](/assets/6ad7a172-0e1b-4276-ac89-042681552507.CUsDUXoA.png) 创建项目后,你应该会看到一个额外的"PACKAGE PUBLISHING"面板弹出: ![image](/assets/9eeffbcf-d73e-4a92-bce5-811ed60aba98.DcWbVPkf.png) 你现在应该通过包管理器的"EDIT"链接适当地编辑命名空间、描述、许可证和可见性属性,这将带你到 `Settings` 文件中的各个设置。编辑完成后,记得关闭(并保存)`Settings` 文件,以便更改反映在包管理器面板中。 * **命名空间:** 这是在引用你的包的项目中用于分组组件的符号。例如,提供一系列不同对话框类的包可能使用命名空间 `Dialogs`。 * **描述:** 这是将出现在 `Settings`->`References` 列表中的描述文本。如果你计划分享此包,请仔细考虑描述,以便他人可以通过 TWINSERV 发现你的包。 * **许可证:** 此短文本出现在 `Settings`->`References` 列表中,与描述一起显示。如果你计划分享此包,填写此字段很重要,输入的值应与 LICENCE.md 文件的内容适当匹配(例如 'MIT'、'LGPL' 等)。 * **可见性:** 决定包是仅你可见(PRIVATE)还是所有人可见(PUBLIC)。此处的值仅在使用"PUBLISH THIS PACKAGE"按钮将包发布到包管理器服务 TWINSERV 时生效。 *如果你不打算在 TWINSERV 上发布包,则无需填写**许可证**或**可见性**字段。* 你现在可以像平常一样在项目中创建组件(Class、Module、Interface),完成后,是时候完成包的构建了。你有两个选项; ## 选项 1 - 将包构建为 TWINPACK 文件 如果你想只创建一个可以在其他项目中使用的本地 TWINPACK 文件,请使用此选项。为此,构建过程与任何普通 twinBASIC 构建相同……只需点击 TWINBASIC 工具栏中的构建按钮: ![image](/assets/4d90f313-35d5-426d-8fc3-852ca03382fa.C14PwK_T.png) ![image](/assets/8d74d820-9907-4e76-ac42-71d0233187f1.CSUZ5DI5.png) 你将在 `DEBUG CONSOLE` 中看到构建输出通知,如上所示。 大功告成。参见[从 TWINPACK 文件导入包](/official/Features/Packages/Importing-a-package-from-a-TWINPACK-file)了解如何在其他 twinBASIC 项目中引用和使用 TWINPACK 文件。 ## 选项 2 - 直接将包发布到包管理器服务 (TWINSERV) 如果你要将包发布到 TWINSERV,无需手动创建 TWINPACK 文件。只需使用"PUBLISH THIS PACKAGE"按钮: ![Create Package](/assets/packPublishButton.BMiVB8Mz.png){style="width:45%; height:auto;"} ***将包发布到 TWINSERV 需要先创建发布者账户。如果尚未创建,你会在此时被提示创建。*** 然后你将被提示确认包详细信息: ![Create Package](/assets/packPublishPackage1.DgsLjXIA.png){style="width:65%; height:auto;"} 按 `YES` 后,包将被上传到 TWINSERV。检查 `DEBUG CONSOLE` 获取完成通知: ![Create Package](/assets/packPublishComplete1.DFxBYuMc.png){style="width:85%; height:auto;"} 如果包成功上传,它应该在几分钟后就可以通过 TWINSERV 使用。如果你创建了 `PUBLIC` 包,其他人此时将能够看到并下载它。 参见[从 TWINSERV 导入包](/official/Features/Packages/Importing-a-package-from-TWINSERV)了解如何引用和使用已上传的包。 ## 特殊文件 LICENCE.md 和 CHANGELOG.md 创建新包项目时,你会在项目文件系统中看到为你创建的两个额外文件: ![Create Package](/assets/packLicenceFiles.DCs-krDV.png){style="width:55%; height:auto;"} 如果你要将 `PUBLIC` 包发布到包管理器服务,在发布前编辑这两个文件很重要。它们都是 markdown 文件,将来会变得更容易被考虑从 TWINSERV 使用你包的用户访问。 --- --- url: /zh/official/Challenges/create-a-game.md --- # 🎮 twinBASIC 月度挑战 #2 - 二月 **创建游戏** 使用twinBASIC构建**任何你喜欢的游戏**。 可以是简单的卡牌游戏、街机游戏、益智游戏,或更具实验性的作品。鼓励创意——没有"正确"的类型或风格。 ## 📦 提交规则 * 使用twinBASIC构建 * 必须提供完整源代码,但许可证选择不受限制 * 提交必须是*单个* `.twinproj` 文件(必要时允许外部图片和音乐资源文件) * 生成**单个Windows EXE** * 在 **Windows 10 及更高版本**上运行 * 游戏可以是窗口模式或全屏模式 * 音乐为可选项 * ❌ 不能是现有VB6游戏的直接或近乎直接的移植 ## 🎵 额外加分 * 包含音乐或音效 * 包含控制器支持(如XInput) * 使用 **GDI+包** ⁠[GDI+ Package](https://discord.com/channels/927638153546829845/1460777854714515728) * 使用 **OpenGL** ⁠[twinBASIC + WinDevLib OpenGL De…](https://discord.com/channels/927638153546829845/1464785863702610053) * 巧妙或高效的渲染技术 * 使用较新的twinBASIC特性(如委托、泛型) * 整洁的架构和文档完善的代码 * 精致的UI、UX或游戏手感 * 有趣的技术技巧(碰撞检测、AI等) ## 🎁 奖品 **£100 twinBASIC账户额度** * 不可转让 * 无现金替代 * 仅可用于未来的twinBASIC许可证 ## 🏆 评审 参赛作品将在多个类别中评审,包括: * 原创性和创意 * 技术执行 * 性能 * 视觉表现 * 代码质量和结构 * 整体完成度和趣味性 额外加分由twinBASIC团队酌情授予。 **获奖者由twinBASIC团队在提交截止后7天内全权决定。** ## ⏰ 截止日期 参赛作品须在以下时间前提交: 🗓️ 3月1日 --- 12:00 PM (GMT) 截止日期后提交将锁定。 🔗: > AI生成 --- --- url: /zh/official/Features/Packages/Importing-a-package-from-a-TWINPACK-file.md --- # 从 TWINPACK 文件导入包 要直接从 TWINPACK 文件(而非通过 TWINSERV)导入包,请按照以下步骤操作。 * 打开要使用包的项目 * 打开其中的 `Settings` 文件 * 导航到 References 部分 * 选择"Available Packages"按钮 ![image](/assets/d9f1e4d9-1805-47e5-93aa-251151b4e914.Cqb69x_o.png) * 按"Import from file..."按钮: ![image](/assets/e35d5955-9e70-4d6e-abd7-748558da75ba.D3L2kNPh.png) * 选择要导入的 TWINPACK 文件,然后它应该出现在引用列表中(已勾选): ![image](/assets/4e4b8e4d-2a1c-42e5-8f4b-5a9b3f523ee8.ZfPs8_0L.png) * 保存 `Settings` 并在需要时重启编译器 现在你可以使用该包了!在上面的示例中,我添加了对 CSharpishStringFormater 包的引用,现在我可以确认可以在代码中访问该包的组件: ![image](Images/e9a3fd21-8e6a-4485-b52c-0c041600826b.png) --- --- url: /zh/official/Features/Packages/Importing-a-package-from-TWINSERV.md --- # 从 TWINSERV 导入包 打开要使用包的项目,打开其中的 `Settings` 文件并导航到 References 部分。选择"Available Packages"按钮,服务器上的所有包应该都会显示: ![432410211-d9f1e4d9-1805-47e5-93aa-251151b4e914](Images/e749e10f-e361-4f15-a977-d756fcb3b5dd.png) 如果你勾选一个可用的包,它将被下载并导入到项目中: ![432416432-4e4b8e4d-2a1c-42e5-8f4b-5a9b3f523ee8](Images/f2fd8374-fe46-40b0-8c66-2443df4dc5b3.png) 完成后,保存并关闭 Settings 文件,这将导致编译器重启。现在你可以使用该包了!在上面的示例中,我添加了对 CSharpishStringFormater 包的引用,现在我可以确认可以在代码中访问该包的组件: ![432417844-e9a3fd21-8e6a-4485-b52c-0c041600826b](/assets/e2a65dfe-4a9d-4524-b6d6-7a6d1bc35cdb.Bv2Q-O97.png) 注意:如果你有已发布的任何 PRIVATE 包,它们仅在登录后可用。如果你尚未登录,你会看到一个警告链接,点击即可登录: ![image](/assets/0fa1272d-41d6-4d0f-b19c-f47f24a47c4d.CMaXZ-xh.png) 登录后,再次按"Available"按钮刷新列表。 --- --- url: /zh/official/Tutorials/CEF/Driving-Monaco.md --- # 从twinBASIC驱动Monaco 结合前面教程所有内容的案例研究:一个包含**两个**[**CefBrowser**](/official/Reference/CEF/CefBrowser/)控件的窗体——左侧是Microsoft Monaco编辑器,右侧是实时HTML预览。用户输入时,Monaco将编辑的源代码发送给twinBASIC,后者将其镜像到预览面板。 完整项目以*示例1b——Chromium Embedded Framework示例*的形式在新项目对话框中提供(窗体*示例3*)。 ## 架构 ![](/assets/MonacoArchitecture.yN_RVrrc.svg) 编辑器作为本地Web应用在虚拟主机名下运行;预览面板通过[**NavigateToString**](/official/Reference/CEF/CefBrowser/#navigatetostring)接收原始HTML。 ## 运行时版本要求 Monaco使用较旧Chromium版本中不存在的现代JavaScript功能。示例在启动时检查并警告加载的运行时是否太旧: ```vb If WebView.CefMajorVersion < 109 Then MsgBox "Sorry, Monaco is not supported by this old version of CEF." End If ``` 实际上这意味着本教程需要**v109**或**v145**——**v49**缺少Monaco依赖的JavaScript API。参见[入门](/official/Tutorials/CEF/Getting-started)了解如何选择正确的包引用。 ## 设置编辑器资源 Monaco编辑器是一个约2MB的JavaScript、CSS和字体文件集合。将它们放入项目的 `Resources` 子文件夹——命名为 `MONACO_DEMO`——连同 `index.html`和一个小的引导 `script.js`。[托管本地Web资源](/official/Tutorials/CEF/Hosting-local-web-assets)教程描述了布局。 页面本身是一个 `
` 加上监听宿主*初始内容*消息的引导脚本: ```html
``` ```js window.chrome.webview.addEventListener('message', (event) => { let initialHTML = event.data; require.config({ paths: { 'vs': 'https://monaco.example/vs' } }); require(["vs/editor/editor.main"], () => { let editor = monaco.editor.create(document.getElementById('container'), { value: initialHTML, language: 'html', theme: 'vs-dark', minimap: { enabled: false } }); editor.onDidChangeModelContent(() => { // Inform the host of every edit. window.chrome.webview.postMessage(editor.getValue()); }); }); }); ``` ## BASIC端 在窗体上放置两个 `CefBrowser` 控件——`WebView`(编辑器)和 `WebViewPreview`(渲染器)。`Ready` 处理程序部署资源、注册虚拟主机并导航: ```vb Private localPath As String Private Sub WebView_Ready() Handles WebView.Ready localPath = Environ$("USERPROFILE") & "\Documents\tbMonacoDemo" CopyResourcesFolderContentsToLocalPath "MONACO_DEMO", localPath WebView.SetVirtualHostNameToFolderMapping _ "monaco.example", localPath & "\" WebView.Navigate "https://monaco.example/index.html" End Sub ``` (`CopyResourcesFolderContentsToLocalPath` 是[托管本地Web资源](/official/Tutorials/CEF/Hosting-local-web-assets)中的辅助过程。) 两个控件共享单个辅助浏览器进程——第一个到达[**Ready**](/official/Reference/CEF/CefBrowser/#ready)的**CefBrowser**启动它,第二个附加到现有进程。这种共享使双面板模式的成本很低。 ## 推送初始内容 Monaco加载完成后,引导脚本监听包含用于填充编辑器的HTML的 `message` 事件。在编辑器的[**NavigationComplete**](/official/Reference/CEF/CefBrowser/#navigationcomplete)后发送该消息: ```vb Private Sub WebView_NavigationComplete( _ ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) _ Handles WebView.NavigationComplete If WebView.DocumentURL <> "https://monaco.example/index.html" Then Exit Sub Dim initialHTML As String = _ StrConv(LoadResData("initial-editor-html.html", "MONACO_DEMO"), vbFromUTF8) WebView.PostWebMessage(initialHTML) WebViewPreview.NavigateToString(initialHTML) End Sub ``` [**LoadResData**](/official/Reference/VB/Global/#loadresdata)返回资源字节;`StrConv(..., vbFromUTF8)` 解码它们。[**PostWebMessage**](/official/Reference/CEF/CefBrowser/#postwebmessage)将字符串传递给Monaco的 `message` 监听器;[**NavigateToString**](/official/Reference/CEF/CefBrowser/#navigatetostring)用相同文本渲染HTML来填充预览面板。 顶部的 `If` 守卫很重要——[**NavigationComplete**](/official/Reference/CEF/CefBrowser/#navigationcomplete)对*每次*导航都会触发,包括内部Monaco资源加载。仅在导航到 `index.html` 时填充编辑器。 ## 实时预览 Monaco中的每次按键触发其 `onDidChangeModelContent` 回调,该回调将新内容 `postMessage` 回BASIC。这以[**JsMessage**](/official/Reference/CEF/CefBrowser/#jsmessage)事件到达——直接送入预览: ```vb Private Sub WebView_JsMessage(ByVal Message As Variant) Handles WebView.JsMessage WebViewPreview.NavigateToString(Message) End Sub ``` 就是这样——预览面板在每次编辑时重新渲染。 ## 检测缺失的运行时 相当一部分用户将在未安装CEF运行时ZIP的机器上运行应用程序。[**Error**](/official/Reference/CEF/CefBrowser/#error)事件报告此情况时附带控件搜索的确切路径: ```vb Private Sub WebView_Error(ByVal code As Long, ByVal msg As String) _ Handles WebView.Error MsgBox "Failed to initialize the CEF control." & vbCrLf & vbCrLf & _ "Code: " & Hex$(code) & vbCrLf & _ msg, vbExclamation, "CEF" End Sub ``` 修复方法是从[github.com/twinbasic/cef-runtimes](https://github.com/twinbasic/cef-runtimes/releases/)安装匹配的运行时ZIP,或者随应用程序一起提供运行时并在[**Create**](/official/Reference/CEF/CefBrowser/#create)事件期间将[**EnvironmentOptions.BrowserExecutableFolder**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#browserexecutablefolder)指向它。安装路径和ZIP文件参见[入门](/official/Tutorials/CEF/Getting-started)。 ## 下一步 * [托管本地Web资源](/official/Tutorials/CEF/Hosting-local-web-assets) —— 本教程基于的 `CopyResourcesFolderContentsToLocalPath` 辅助过程和虚拟主机模式。 * [JavaScript互操作](/official/Tutorials/CEF/JavaScript-interop) —— BASIC和JavaScript之间的两座桥。 * [重入性](/official/Tutorials/CEF/Re-entrancy) —— 为什么实时预览模式即使看起来大部分是同步的也是安全的。 * [CefBrowser参考](/official/Reference/CEF/CefBrowser/) —— 每个属性、方法和事件。 * [驱动Monaco(WebView2)](/official/Tutorials/WebView2/Driving-Monaco) —— 使用[**WebView2**](/official/Reference/WebView2/WebView2/)控件的并行实现。 --- --- url: /zh/official/Tutorials/WebView2/Driving-Monaco.md --- # 从twinBASIC驱动Monaco 结合前面教程所有内容的案例研究:一个包含**两个**[**WebView2**](/official/Reference/WebView2/WebView2/)控件的窗体——左侧是Microsoft Monaco编辑器,右侧是实时HTML预览。用户输入时,Monaco将编辑的源代码发送给twinBASIC,后者将其镜像到预览面板。 完整项目以*示例0——WebView2示例*的形式在新项目对话框中提供(窗体*示例3*)。 ## 架构 ![](/assets/MonacoArchitecture.yN_RVrrc.svg) 编辑器作为本地Web应用在虚拟主机名下运行;预览面板通过[**NavigateToString**](/official/Reference/WebView2/WebView2/#navigatetostring)接收原始HTML。 ## 设置编辑器资源 Monaco编辑器是一个约2MB的JavaScript、CSS和字体文件集合。将它们放入项目的 `Resources` 子文件夹——命名为 `MONACO_DEMO`——连同 `index.html`和一个小的引导 `script.js`。[托管本地Web资源](/official/Tutorials/WebView2/Hosting-local-web-assets)教程描述了布局。 页面本身是一个 `
` 加上监听宿主*初始内容*消息的引导脚本: ```html
``` ```js window.chrome.webview.addEventListener('message', (event) => { let initialHTML = event.data; require.config({ paths: { 'vs': 'https://monaco.example/vs' } }); require(["vs/editor/editor.main"], () => { let editor = monaco.editor.create(document.getElementById('container'), { value: initialHTML, language: 'html', theme: 'vs-dark', minimap: { enabled: false } }); editor.onDidChangeModelContent(() => { // Inform the host of every edit. window.chrome.webview.postMessage(editor.getValue()); }); }); }); ``` ## BASIC端 在窗体上放置两个 `WebView2` 控件——`WebView`(编辑器)和 `WebViewPreview`(渲染器)。`Ready` 处理程序部署资源、注册虚拟主机并导航: ```vb Private localPath As String Private Sub WebView_Ready() Handles WebView.Ready localPath = Environ$("USERPROFILE") & "\Documents\tbMonacoDemo" CopyResourcesFolderContentsToLocalPath "MONACO_DEMO", localPath WebView.SetVirtualHostNameToFolderMapping _ "monaco.example", localPath & "\", wv2ResourceAllow WebView.Navigate "https://monaco.example/index.html" End Sub ``` (`CopyResourcesFolderContentsToLocalPath` 是[托管本地Web资源](/official/Tutorials/WebView2/Hosting-local-web-assets)中的辅助过程。) ## 推送初始内容 Monaco加载完成后,引导脚本监听包含用于填充编辑器的HTML的 `message` 事件。在编辑器的[**NavigationComplete**](/official/Reference/WebView2/WebView2/#navigationcomplete)后发送该消息: ```vb Private Sub WebView_NavigationComplete( _ ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) _ Handles WebView.NavigationComplete Dim initialHTML As String = _ StrConv(LoadResData("initial-editor-html.html", "MONACO_DEMO"), vbFromUTF8) WebView.PostWebMessage(initialHTML) WebViewPreview.NavigateToString(initialHTML) End Sub ``` [**LoadResData**](/official/Reference/VB/Global/#loadresdata)返回资源字节;`StrConv(..., vbFromUTF8)` 解码它们。[**PostWebMessage**](/official/Reference/WebView2/WebView2/#postwebmessage)将字符串传递给Monaco的 `message` 监听器;[**NavigateToString**](/official/Reference/WebView2/WebView2/#navigatetostring)用相同文本渲染HTML来填充预览面板。 ## 实时预览 Monaco中的每次按键触发其 `onDidChangeModelContent` 回调,该回调将新内容 `postMessage` 回BASIC。这以[**JsMessage**](/official/Reference/WebView2/WebView2/#jsmessage)事件到达——直接送入预览: ```vb Private Sub WebView_JsMessage(ByVal Message As Variant) Handles WebView.JsMessage WebViewPreview.NavigateToString(Message) End Sub ``` 就是这样——预览面板在每次编辑时重新渲染。 ## 检测缺失的Edge运行时 相当一部分用户将在未安装WebView2 Evergreen运行时的机器上运行应用程序。[**Error**](/official/Reference/WebView2/WebView2/#error)事件将此情况报告为Win32错误代码 `&H80070002`(`ERROR_FILE_NOT_FOUND`): ```vb Private Sub WebView_Error(ByVal code As Long, ByVal msg As String) _ Handles WebView.Error Const ERROR_FILE_NOT_FOUND As Long = &H80070002 If code = ERROR_FILE_NOT_FOUND Then MsgBox "Failed to initialize the WebView2 control." & vbCrLf & _ "Please install the WebView2 (Evergreen) runtime.", _ vbExclamation, "WebView2" Else MsgBox "WebView2 error " & Hex$(code) & ": " & msg, _ vbExclamation, "WebView2" End If End Sub ``` 即使在单WebView应用中也值得处理此情况——你在此显示的消息是"什么都没发生"和"哦,我需要安装什么"之间的区别。 ## 下一步 * [托管本地Web资源](/official/Tutorials/WebView2/Hosting-local-web-assets) —— 本教程基于的 `CopyResourcesFolderContentsToLocalPath` 辅助过程和虚拟主机模式。 * [JavaScript互操作](/official/Tutorials/WebView2/JavaScript-interop) —— BASIC和JavaScript之间的三座桥。 * [WebView2参考](/official/Reference/WebView2/WebView2/) —— 每个属性、方法和事件。 --- --- url: /zh/official/IDE/Open-Editors.md --- # 打开的编辑器 未打开项目时此面板为空。 ![Open Editors](Images/OpenEditors.png "Open Editors") 打开项目后,将列出当前在[编辑器](/official/IDE/Editor)中打开的文件。 ![Open Editors](/assets/OpenEditors_1.BcjDvHpf.png "Open Editors") 点击列表中的文件可在编辑器中将其聚焦。 --- --- url: /zh/official/IDE/Outline.md --- # 大纲 大纲面板显示活动源文件中声明的结构概览——模块、类、过程和属性。 未打开项目时此面板为空。 ![Outline](Images/Outline.png "Outline") 打开项目后将列出 `模块`/`类` 等。 ![Outline](Images/Outline_1.png "Outline") 点击条目可跳转到代码文件中的对应位置。 --- --- url: /zh/official/Features/Compiler-IDE/Debugging.md --- # 调试功能 twinBASIC 包含多项有助于调试的功能。 ## 调试跟踪记录器 调试体验的新功能是跟踪日志功能,可自动创建详细日志到调试控制台或文件。消息可以通过 `Debug.TracePrint` 输出。记录器在从 IDE 运行和编译的可执行文件中都可以工作。 ![image](/assets/4fc2bf99-2bec-4943-837d-21038d791574.DRG1F5be.png) ```vb Public Sub ProcessOrder(ByVal orderId As Long) Debug.TracePrint "ProcessOrder called, orderId=" & CStr(orderId) ' ... processing ... End Sub ``` ## 过期/悬挂指针检测 使用已释放的 String 和 Variant 会导致 bug。如果内存尚未被覆盖,可能不会立即注意到,但有时很难检测,可能引起诸如 String 显示其先前值或乱码之类的问题。此调试选项检测释放后使用,并将数据替换为特殊符号以指示问题。 下图展示了一个示例,其中 ListView ColumnHeader 文本被已释放的字符串设置并被此功能检测到: ![image](/assets/021f6cbf-acce-445d-ade7-3fcad0af4927.CZs18HD4.png) 以前,它在每个列中都显示相同的文本——但只在特定情况下出现,导致该问题长期被忽视。 --- --- url: /zh/official/IDE/Menu/Debug.md --- # 调试菜单 ![调试菜单](/assets/Menu_Debug.DmTsmZ4_.png "调试菜单") * 逐语句 F8 / F11 * 逐过程 SHIFT + F8 / F10 *** * 添加监视... SHIFT + F9 * 清除监视 *** * 切换断点 F9 * 清除所有断点 CTRL + SHIFT + F9 *** * 设置下一语句(跳转到行) CTRL + F9 *** * 调试器选项 ## 调试器选项 ![调试器选项 - 调试菜单](/assets/Menu_Debug_DebuggerOptions.aRq1DFjy.png "调试器选项 - 调试菜单") * 遇到所有错误时中断 * ✔ 允许断点(可调试) ![调试器选项 - 调试菜单](Images/Menu_Debug_DebuggerOptions_2.png "调试器选项 - 调试菜单") --- --- url: /zh/official/IDE/Debug-Console.md --- # 调试控制台 ![Debug Console](/assets/DebugConsole.Bt37Zf5d.png "Debug Console") 调试控制台捕获运行时输出的 `Debug.Print` 语句及其他调试层消息,并显示在可滚动的日志中。 ## ![](Images/DebugConsole_AutoScroll.png) 自动滚动 ## ![](Images/DebugConsole_Clear.png) 清除调试控制台 ## ![](Images/DebugConsole_Options.png) 选项 * 反转输出方向 * 显示时间戳 ## ![](Images/DebugConsole_Input.png) 输入 --- --- url: /zh/official/IDE/Call-Stack.md --- # 调用堆栈 ![Call Stack](/assets/CallStack.BS03A-08.png "Call Stack") 调用堆栈面板在调试会话中列出当前执行点的活动过程调用链,最近的调用位于顶部。点击列表中的条目可跳转到编辑器中对应的调用位置。 --- --- url: /zh/official/Tutorials/Windows-API.md --- # 调用Windows API 本教程演示端到端的Windows API调用——编写 `Declare` 语句、调用函数、处理结果,以及在出错时读取错误信息。完成后你将拥有一个小型窗体,可以实时跟踪并显示当前鼠标光标位置。 ## 背景 Windows API是系统DLL(如 `user32.dll`、`kernel32.dll` 和 `gdi32.dll`)暴露的大量C函数集合。VBA和twinBASIC可以使用 `Declare` 语句直接调用这些函数,该语句将外部函数映射到模块的命名空间中并提供类型化签名。 编写Declare时最重要的两件事: 1. **每个参数的正确类型。** 错误的类型可能传递错误的字节数并破坏栈或堆。 2. **32位与64位兼容性。** 许多Win32类型是指针大小的;在32位构建中为4字节,在64位构建中为8字节。 twinBASIC通过**LongPtr**(指针宽度整数)和 `PtrSafe` 关键字(表示Declare在64位进程中安全使用)处理这两个问题。 ## 示例:跟踪鼠标坐标 `GetCursorPos` 读取鼠标指针的当前屏幕坐标,并将其写入调用方提供的 `POINT` 结构中。它是一个简单、安全且无副作用的函数——学习该模式的良好起点。 Windows SDK中的C原型: ```c BOOL GetCursorPos(LPPOINT lpPoint); ``` * 返回值:成功时非零,失败时为零。 * 唯一参数是指向 `POINT` 结构的指针,函数将填充该结构。 twinBASIC翻译: ```vb Private Type POINT x As Long y As Long End Type Private Declare PtrSafe Function GetCursorPos Lib "user32" _ (lpPoint As POINT) As Long ``` `POINT` 包含两个32位整数字段。即使在64位构建中,字段本身仍是32位的——只有指针值改变宽度。这里使用 `Long` 是正确的。 参数 `lpPoint As POINT` 默认按**ByRef**传递。ByRef意味着twinBASIC将局部 `POINT` 变量的地址传递给函数,函数通过该指针将坐标写回。这是Windows中类型为 `LP` 的输出参数的标准模式。 ## 步骤1:创建项目和窗体 创建一个新的标准EXE项目(或打开现有项目)。在 `Form1` 上添加: | 控件 | 名称 | 标题 | 备注 | |---------|------|---------|-------| | Label | `lblCoords` | `(waiting...)` | 显示当前坐标 | | Timer | `Timer1` | --- | 将**Interval**设为 `100`(毫秒),**Enabled**设为 `True` | Timer每100毫秒触发其 `Timer` 事件。每次触发将调用 `GetCursorPos` 并更新标签。 ## 步骤2:添加Declare和UDT 打开 `Form1` 的代码编辑器。在模块顶部、任何过程之前,添加UDT和Declare: ```vb Private Type POINT x As Long y As Long End Type Private Declare PtrSafe Function GetCursorPos Lib "user32" _ (lpPoint As POINT) As Long ``` ::: info `PtrSafe` 在任何将用于64位构建的 `Declare` 上都是必需的。它告诉编译器该签名已经过指针宽度正确性审查。在仅32位项目上包含 `PtrSafe` 没有影响,因此在所有地方使用它是良好实践。 ::: ## 步骤3:调用函数并处理结果 在设计器中双击Timer控件生成 `Timer1_Timer` 事件处理程序,然后填充内容: ```vb Private Sub Timer1_Timer() Dim pt As POINT Dim success As Long success = GetCursorPos(pt) If success <> 0 Then lblCoords.Caption = "X: " & pt.x & " Y: " & pt.y Else lblCoords.Caption = "(error)" End If End Sub ``` `GetCursorPos` 成功时返回非零值,失败时返回零。`POINT` 字段 `x` 和 `y` 仅在返回值为非零时有效。 ## 步骤4:运行应用程序 按**F5**。在窗体上移动鼠标。标签每秒更新十次,显示当前屏幕坐标(以像素为单位,从主显示器左上角测量)。 ## 使用GetLastError处理错误 当Win32函数返回失败代码时,扩展错误信息可通过 `GetLastError` 获取——另一个kernel32函数: ```vb Private Declare PtrSafe Function GetLastError Lib "kernel32" () As Long ``` ::: info 在VBA兼容代码中,你也可以通过[**Err.LastDllError**](/official/Reference/VBA/Information/Err)读取上一个Win32错误,该值在任何DLL调用后自动填充。两者返回相同的值;`Err.LastDllError` 不需要额外的Declare。 ::: Timer处理程序的健壮版本: ```vb Private Sub Timer1_Timer() Dim pt As POINT If GetCursorPos(pt) <> 0 Then lblCoords.Caption = "X: " & pt.x & " Y: " & pt.y Else lblCoords.Caption = "GetCursorPos failed (error " & Err.LastDllError & ")" End If End Sub ``` 实际上 `GetCursorPos` 几乎不会失败;检查返回代码对于处理文件句柄、网络连接或安全上下文的函数更为重要,这些场景中失败是常见的。 ## 32位与64位注意事项 对于 `GetCursorPos`,这种区别不会出现,因为其所有类型都是具体的32位整数。许多其他API函数使用指针大小的类型,需要小心处理: | C类型 | twinBASIC类型 | 原因 | |--------|----------------|-----| | `HWND`, `HANDLE` | **LongPtr** | 窗口和对象句柄是指针大小 | | `HINSTANCE`, `HMODULE` | **LongPtr** | 实例句柄是指针大小 | | `LPCWSTR`, `LPWSTR` | **LongPtr** (配合StrPtr) 或 **String** | 字符串指针是指针大小 | | `DWORD` | **Long** | 始终32位 | | `BOOL` | **Long** | 始终32位 | | `INT`, `int` | **Long** | 始终32位 | 使用 `Long` 作为句柄类型的Declare在32位模式下可以编译和运行,但在64位模式下会失败或崩溃,因为64位句柄无法放入4字节。对于句柄和指针参数,始终使用 `LongPtr`。 ### 示例:GetForegroundWindow ```vb Private Declare PtrSafe Function GetForegroundWindow Lib "user32" () As LongPtr Private Sub ShowActiveWindow() Dim hwnd As LongPtr hwnd = GetForegroundWindow() MsgBox "Active window handle: " & hwnd End Sub ``` 返回类型为 `LongPtr`,因为窗口句柄是指针大小的。在32位构建中 `LongPtr` 为4字节;在64位构建中为8字节。相同的Declare和相同的调用代码在两种目标下都能工作,无需任何 `#If Win64` 条件编译。 ## ANSI与Unicode函数变体 大多数Win32文本相关函数有两个变体:ANSI版本(后缀 `A`)接受 `LPSTR` / `char*` 字符串,Unicode版本(后缀 `W`)接受 `LPWSTR` / `wchar_t*` 字符串。twinBASIC字符串是Unicode(`BSTR`),因此始终优先使用 `W` 变体。 当无别名的名称会解析为ANSI变体时,在 `Alias` 子句中指定Unicode函数名: ```vb ' Without Alias, the linker resolves to the ANSI variant on some systems. ' Alias forces the Unicode variant explicitly: Private Declare PtrSafe Function GetWindowText Lib "user32" _ Alias "GetWindowTextW" _ (ByVal hwnd As LongPtr, _ ByVal lpString As Long, _ ByVal nMaxCount As Long) As Long ``` 对于twinBASIC可以直接传递**String**的函数,`DeclareWide` 是手动管理缓冲区指针的替代方案——参见[特性 → 增强的API声明](/official/Features/Advanced/API-Declarations)了解 `DeclareWide` 和 `CDecl` 扩展。 ## 完整代码 光标跟踪窗体的完整模块: ```vb Private Type POINT x As Long y As Long End Type Private Declare PtrSafe Function GetCursorPos Lib "user32" _ (lpPoint As POINT) As Long Private Sub Form_Load() Me.Caption = "Cursor position" lblCoords.Caption = "(waiting...)" Timer1.Interval = 100 Timer1.Enabled = True End Sub Private Sub Timer1_Timer() Dim pt As POINT If GetCursorPos(pt) <> 0 Then lblCoords.Caption = "X: " & pt.x & " Y: " & pt.y Else lblCoords.Caption = "GetCursorPos failed (error " & Err.LastDllError & ")" End If End Sub ``` ## 下一步 * **增强的API声明** —— `DeclareWide`、`CDecl`、`ByVal` UDT、可变参数:[特性 → 增强的API声明](/official/Features/Advanced/API-Declarations) * **窗体基础** —— 标准VB控件和事件模型:[窗体基础](/official/Tutorials/Forms) * **单元测试** —— 验证封装API调用的函数:[使用Assert编写单元测试](/official/Tutorials/Testing-with-Assert) --- --- url: /zh/official/Tutorials/CustomControls/Defining-a-CustomControl.md --- # 定义CustomControl CustomControl就是一个普通的twinBASIC类,带有一些额外的属性和要求。 ::: tip 强烈建议在尝试实现自己的CustomControl之前,先查看并实验twinBASIC提供的示例项目。 ::: ![Custom Control Sample Project](/assets/ccSampleProject.s4UMFguj.png) *** ## CustomControl()属性 ![CustomControl attribute](Images/ccCustomControlAttribute.png) 这是所有CustomControl的必需属性。你必须提供项目内图片文件的相对路径,用于在窗体设计器工具箱中标识你的控件。我们建议将图片文件放在项目的Miscellaneous文件夹中。 ![CustomControl GridImage Folder](/assets/ccGridButtonImage.DUOdFAFA.png) *** ## ClassId()属性 ![CustomControl ClassId Attribute](Images/ccClassIdAttribute.png) 这是所有CustomControl的必需属性。你必须提供唯一的CLSID(GUID),以便窗体引擎与你的控件配合工作。 ::: tip 如果你输入 `[ ClassId () ]`,twinBASIC会帮助你——只需点击"insert a randomly generated GUID"文本: ::: ![CustomControl ClassId auto-generate](Images/ccClassIdInsert.png) *** ## COMCreatable()属性 ![CustomControl COMCreatable attribute](/assets/ccCOMCreatable.Do5ABbox.png) 这是一个可选属性,但通常建议将此属性设为False,因为你不需要从外部COM环境实例化CustomControl。 *** ## 必须实现ICustomControl ![CustomControl ICustomControl interface](/assets/ccICustomControl.Efdgn67o.png) 所有CustomControl*必须*实现[`CustomControls.ICustomControl`](/official/Reference/CustomControls/Framework/ICustomControl)。该接口当前有3个你必须实现的方法: ```vb Sub Initialize(ByVal Context As CustomControlContext) ``` 此方法在你的控件附加到窗体时调用。你必须将提供的Context对象存储在类字段中,因为它提供了一个 `Repaint()` 方法,用于通知窗体引擎控件中的某些内容已更改并需要重绘。 ```vb Sub Destroy() ``` 此方法在你的控件从窗体分离时调用。这提供了打破循环引用的机会,以便你的对象实例可以正确析构。如果你不在对象中创建循环引用,此实现通常可以留空。 ```vb Sub Paint(ByVal Canvas As Canvas) ``` 这是CustomControl最有趣的部分。因此它有自己的章节,参见[绘制/绘图到你的控件](/official/Tutorials/CustomControls/Painting-drawing-to-your-control) *** ## 最小属性集 由于twinBASIC尚不支持继承,你必须为所有CustomControl暴露一组公共属性(类字段): ```vb Public Name As String Public Left As CustomControls.PixelCount Public Top As CustomControls.PixelCount Public Width As CustomControls.PixelCount Public Height As CustomControls.PixelCount Public Anchors As Anchors = New Anchors Public Dock As CustomControls.DockMode Public Visible As Boolean ``` 窗体设计器和窗体引擎使用这些属性,因此将它们包含在你的CustomControl类中很重要。这里使用的类型都在框架中定义:[`PixelCount`](/official/Reference/CustomControls/Enumerations/PixelCount)、[`DockMode`](/official/Reference/CustomControls/Enumerations/DockMode)和[`Anchors`](/official/Reference/CustomControls/Styles/Anchors)样式对象。 注意,窗体设计器使用的是未经DPI缩放的像素值。因此你的控件的Left/Top/Width/Height属性不反映DPI缩放。例如,如果你的控件宽度为50像素,则在DPI 150%时,实际绘制宽度为75像素(参见[绘制/绘图到你的控件](/official/Tutorials/CustomControls/Painting-drawing-to-your-control))。 *** ## 必须有序列化构造函数 CustomControl*必须*提供序列化构造函数: ```vb Public Sub New(Serializer As SerializationInfo) ``` 传入的Serializer对象提供了一个 `Deserialize()` 方法,你调用它来加载通过窗体设计器为控件设置的属性。更多信息参见[属性表和对象序列化](/official/Tutorials/CustomControls/Property-sheet-and-object-serialization)。 ::: info 当前框架将序列化器类型命名为[`SerializeInfo`](/official/Reference/CustomControls/Framework/SerializeInfo)(不是 `SerializationInfo`),`Deserialize()` 暴露为 `RuntimeUISrzDeserialize()`。参见参考页面了解当前成员名称以及该对象上也可用的设计模式/运行时模式标志。 ::: *** ## 另见 * [CustomControls包参考](/official/Reference/CustomControls/) —— 框架部分(接口、回调对象、[`Canvas`](/official/Reference/CustomControls/Framework/Canvas)绘图面、[`SerializeInfo`](/official/Reference/CustomControls/Framework/SerializeInfo)序列化器)和基于其构建的内置 `Waynes…` 控件的完整参考。 --- --- url: /zh/packages/vbccr/ranges/animation.md description: 动画控件(Animation) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 动画控件(Animation) 封装 SysAnimate32 系统动画控件,用于播放无声 AVI 动画。 ## 枚举 ### CCBackStyleConstants 参见通用枚举。 ## 属性 ### AutoPlay ```vb Property Get AutoPlay() As Boolean Property Let AutoPlay(ByVal Value As Boolean) ``` 自动播放,控件创建后立即开始播放。 ### BackStyle ```vb Property Get BackStyle() As CCBackStyleConstants Property Let BackStyle(ByVal Value As CCBackStyleConstants) ``` 背景样式,透明或不透明。 ### Center ```vb Property Get Center() As Boolean Property Let Center(ByVal Value As Boolean) ``` 是否将 AVI 动画居中显示。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示方向。 ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 从右到左镜像布局。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 动画控件的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 用户控件的窗口句柄。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针样式。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 是否启用鼠标进入/离开跟踪。 ### Playing ```vb Property Get Playing() As Boolean ``` 是否正在播放。只读。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` 帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "这是什么"帮助 ID。 ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` 拖动图标。 ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` 拖动模式。 ## 方法 ### Play ```vb Public Sub Play(Optional ByVal FromFrame As Variant, Optional ByVal ToFrame As Variant, Optional ByVal RepeatCount As Variant) ``` 播放动画。可指定起始帧、结束帧和重复次数。 ### StopPlay ```vb Public Sub StopPlay() ``` 停止播放动画。 ### LoadFile ```vb Public Sub LoadFile(ByVal PathName As String) ``` 从文件加载 AVI 动画。 ### LoadRes ```vb Public Sub LoadRes(ByVal ResourceID As Variant) ``` 从资源加载 AVI 动画。支持字符串或数字资源 ID。 ### Unload ```vb Public Sub Unload() ``` 卸载当前动画。 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘控件。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 调整 Z 顺序。 ### SetFocus ```vb Public Sub SetFocus() ``` 获取焦点。 ### Move ```vb Public Sub Move(ByVal Left As Single, Optional ByVal Top As Variant, Optional ByVal Width As Variant, Optional ByVal Height As Variant) ``` 移动并调整控件位置和大小。 ## 事件 ### Click ```vb Public Event Click() ``` 单击。 ### DblClick ```vb Public Event DblClick() ``` 双击。 ### Change ```vb Public Event Change() ``` 动画状态改变时触发。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(KeyCode As Integer, Shift As Integer) ``` 按键前事件,在 KeyDown 之前触发。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(KeyCode As Integer, Shift As Integer) ``` 按键释放前事件,在 KeyUp 之前触发。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按键按下。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 按键释放。 ### KeyPress ```vb Public Event KeyPress(KeyAscii As Integer) ``` 按键字符。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 鼠标按下。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 鼠标移动。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 鼠标释放。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放完成。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE 拖放落下。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放悬停。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 给出反馈。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE 设置数据。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 开始拖动。 ## 代码示例 ### 基本用法 ```vb ' 加载并播放 AVI 动画 Animation1.LoadFile "C:\Icons\filecopy.avi" Animation1.AutoPlay = True ' 从第 5 帧播放到第 20 帧,重复 3 次 Animation1.Play 5, 20, 3 ' 停止播放 Animation1.StopPlay ' 从资源加载 Animation1.LoadRes 101 ' 卸载动画 Animation1.Unload ``` --- --- url: /zh/official/Features/Advanced/Multithreading.md --- # 线程安全 / 多线程支持 虽然目前还没有原生语言语法(计划中),但你可以直接调用 `CreateThread` 而无需任何变通方法。以前,VBx 和其他 BASIC 语言通常需要复杂的变通方法才能使用 `CreateThread` 来做一些非常简单的事情之外的事情。在 twinBASIC 中,你可以直接调用它以及所有其他线程 API,除了当然需要谨慎管理这种底层的线程操作外,无需任何特殊步骤。 ## 示例 在新的标准 EXE 项目中,向窗体添加一个 CommandButton 和一个 TextBox: ```vb Private Declare PtrSafe Function GetCurrentThreadId Lib "kernel32" () As Long Private Declare PtrSafe Function CreateThread Lib "kernel32" ( _ ByRef lpThreadAttributes As Any, _ ByVal dwStackSize As Long, _ ByVal lpStartAddress As LongPtr, _ ByRef lpParameter As Any, _ ByVal dwCreationFlags As Long, _ ByRef lpThreadId As Long) As LongPtr Private Declare PtrSafe Function WaitForSingleObject Lib "kernel32" ( _ ByVal hHandle As LongPtr, _ ByVal dwMilliseconds As Long) As Long Private Const INFINITE = -1& Private Sub Command1_Click() Handles Command1.Click Dim lTID As Long Dim lCurTID As Long Dim hThreadNew As LongPtr lCurTID = GetCurrentThreadId() hThreadNew = CreateThread(ByVal 0, 0, AddressOf TestThread, ByVal 0, 0, lTID) Text1.Text = "Thread " & lCurTID & " is waiting on thread " & lTID Dim hr As Long hr = WaitForSingleObject(hThreadNew, 30000&) 'Wait 30s as a default. You can use INFINITE instead if you never want to time out. Text1.Text = "Wait end code " & CStr(hr) End Sub Public Sub TestThread() MsgBox "Hello thread" End Sub ``` 在单线程代码下,如果你在更新 `Text1.Text` 之前调用 `TestThread`,文本在你点击消息框的确定按钮之前不会更新。但在这里,消息框在单独的线程中启动,所以执行继续并更新了文本,之后我们手动选择等待消息框线程退出。 --- --- url: /zh/official/Features/Language/Generics.md --- # 泛型 ::: warning 泛型是"复制粘贴代码后搜索替换类型名"的语法糖。 泛型语法提供的所有功能都可以通过编写重复代码来实现。 ::: 然而这种重复既容易出错又乏味,因此泛型语法保持代码 DRY\[^1]。 泛型语法引入了*类型参数*/*类型变量*,其*类型值*在编译时存在,而常规参数及其值仅在运行时存在。 过程、**Class** 和 **Type**(UDT)可以声明为泛型。 ::: warning 泛型 **Type**(UDT)尚不支持成员过程(错误 TB5124)。 ::: ## 泛型过程 语法: * **定义** ( **Function** | ... ) *name* **(Of** *type-variable-list* **)** **(** *parameter-list* **)** **As** *return-type* * 详细形式: ( **Function** | **Sub** | **Property** (**Get** | **Let** | **Set**) ) *name* **(Of** *type-var1* \[ **,** *type-var2* ...]**)** **(** *parameter-list* **)** **As** *return-type* *parameter-list* 可以引用任何类型变量,例如 `Sub MyPrint(Of T)(ByVal file&, value As T)` * **调用**或**调用点** *name* \[ **(Of** *type-argument-list* **)** ] \[ **(** *argument-list* **)** ] * 详细形式: *name* \[ **(Of** *type-arg1* \[ **,** *type-arg2* ] **)** ] \[ **(** *argument-list* **)** ] 定义中 *parameter-list* 中的类型变量将被调用点 *argument-list* 中提供的具体类型替代,除非在 *type-argument-list* 中显式提供。 未在 *parameter-list* 中引用的类型变量必须在 *type-argument-list* 中作为*类型参数*提供。 在定义中,*type-variable-list*,即 **(Of** *type-var* ... **)**,引入泛型性。类型变量(*type-var*)引入任意类型的标识符,可以在以下位置引用: * *parameter-list*, * *return-type*,以及 * 过程体。 在调用中,*type-argument-list*,即 **(Of** *type-arg* ... **)**,根据需要可选,为那些不出现在定义 *parameter-list* 中的类型变量提供类型参数。在 *parameter-list* 中使用的类型变量将自动从调用点对应参数的类型推断出类型值,*除非在 *type-argument-list* 中显式提供了其值*。 ### 调用点类型参数 对应可从调用参数类型推断出的类型的类型变量必须构成 *type-variable-list* 的尾部: ```vb Sub MySub1(Of T, U, V)(argu As U, argv As V): End Sub MySub1(Of Long)(33%, 42%) ' Valid: deduced U, V = Integer MySub1(Of Long, Single)(33%, 42%) ' Valid: provided U = Single, deduced V = Integer MySub1(Of Long, Single, Double)(33%, 42%)' Valid: provided U = Single, provided V = Double MySub1(Of Long, , Double)(33%, 42%) ' Invalid: omitted deduced type must be trailing ``` 因此,要禁止推断,将类型变量放在类型列表中不可推断的类型参数*之前*: ```vb ' T must be provided, it won't be deduced Function MyFn1(Of T, U)(argu As T) As U: End Function MyFn1(Of Single, String)(10%) ' Valid: provided T = Single, U = String MyFn1(Of, String)(10%) ' Invalid: T is not trailing so it can't be omitted ' Effectively, the definition of MyFn1 ' suppresses deduction of T ``` 只有未使用的类型变量可以在 *type-variable-list* 中第一个位置*之后*省略其参数: ```vb Sub MySub2(Of T, U, V)(argt As T, argv As V): End Sub Sub MySub3(Of U, V)(argv As V): End Sub MySub2(Of Single, , Double)(1%, 2%) ' Valid: unused U can be omitted as it's not the first ' in the type-parameter-list MySub3(Of, Single)(22%) ' Invalid: unused U can't be omitted as it's the first ' variable in the type-parameter-list ``` ### 示例 1 在此示例中,泛型 **First** 和 **Last** Sub 的调用不需要显式提供类型参数值(即 **(Of** ... **)**),因为它们可以从参数类型推断。 ```vb Public Function First(Of T)(Array() As T) As T If IsArrayInitialized(Array) Then Return Array(LBound(Array)) End Function Public Function Last(Of T)(Array() As T) As T If IsArrayInitialized(Array) Then Return Array(UBound(Array)) End Function Sub Test() Dim data() As String = Array("A", "B", "C") Debug.Assert First(data) = "A" Debug.Assert Last(data) = "C" End Sub ``` 如果没有泛型语法,过程必须为每个使用的类型 *T* 单独编写。在下面的示例中,需要 `T=String` 和 `T=Integer`: ```vb Public Function First(Array() As String) As String If IsArrayInitialized(Array) Then Return Array(LBound(Array)) End Function Public Function First(Array() As Integer) As Integer If IsArrayInitialized(Array) Then Return Array(UBound(Array)) End Function Sub Test() Dim strings() As String = Array("A", "B", "C") Dim ints() As Integer = Array(1, 2, 3) Debug.Assert First(strings) = "A" AndAlso First(ints) = 1 End Sub ``` ### 示例 2:部分类型变量不出现在 *parameter-list* 中 类型变量可能不出现在 *parameter-list* 中的常见情况有两种: * 当它是*返回类型*时,和/或 * 当它在过程体中使用时。 以下示例说明了这些情况: ```vb Public Function Caster(Of R, U, T)(value As T) As R Dim intermediate As U = CType(Of U)(value) Return CType(Of R)(intermediate) End Function Sub Test() ' Type T is deduced to be Single, from the argument 1.23! Debug.Assert Example(Of String, Integer)(1.23!) = "1" ' Type T is explicitly provided as Double. The argument is cast to that type. Debug.Print Example(Of String, Integer, Double)(1.23!) = "1" End Sub ``` 函数 **Caster** 在其作用域内引入了三个类型变量: * **T** 默认从 **value** 参数的类型推断,或在调用时提供, * **R** 是返回类型,必须在调用时提供, * **U** 是函数体中使用的类型,必须在调用时提供。 ::: tip 定义中类型变量的顺序可以安排为尾部变量在 *parameter-list* 中使用。这样如果调用点从参数类型推断的类型合适,这些类型变量的类型值可以省略。 ::: 1. 在调用 `Example(Of String, Integer)(1.23!)` 中, *T* 被推断为 **Single**,*U* 被提供并设为 **Integer**,**R** 被提供并设为 **String**。 2. 在调用 `Example(Of String, Integer, Double)(1.23!)` 中, *T* 被提供并设为 **Double**,*U* 被提供并设为 **Integer**,**R** 被提供并设为 **String**。 * 首先,编译器将 `1.23!` 转换为形参的类型,即 **Double** `1.23#`。 * 然后,在函数体中,*value* 在赋值给 **intermediate** 时被转换为 **Integer**。 * 最后,同样在函数体中,**intermediate** 被转换为结果类型 **String** 并返回。 ## 泛型类和 UDT 语法: * **定义** \[ **Class** | ... ] *name* **(Of** *type-variable-list* **)** * 详细形式: \[ **Class** | **Type** ] *name* **(Of** *type-var1* \[ **,** *type-var2* ... ] **)** * **实例化** *name* **(Of** *type-argument-list* **)** * 详细形式: *name* **(Of** *type-arg1* \[ **,** *type-arg2* ... ] **)** 类型变量(*type-var*)引入任意类型的标识符,可以在类体内的任何位置引用。 ::: warning 实例化泛型类和 UDT 时,**所有类型参数**都必须提供。 如果未提供,可能会导致代码生成错误和运行时的静默失败。 ::: ### 正确和不正确实例化的示例 ```vb Class MyClass(Of T, U) Function DumpT%(value As T): Debug.Print value: End Function Function DumpU%(value As U): Debug.Print value: End Function End Class Dim i As New MyClass(Of Integer) ' Invalid, U is not provided, silent error i.DumpT(12) ' Valid, uses T = Integer i.DumpU(12) ' Invalid, uses undefined U, causes a codegen/silent error Dim j As New MyClass(Of Integer, Single) ' Correct instantiation j.DumpU(12) ' Valid, uses U = Single ``` ### 类型实例与对象实例 泛型类允许用实例化时提供的类型参数替换类型变量。每次使用泛型类名加类型参数都会将泛型类类型实例化为一个常规类类型。 ::: info 编译时:通过调用类名加参数来实例化泛型类。 运行时:可以创建那些实例化类型的对象。 ::: 在下面的示例中,实例化了两个类类型:**MyClass**(**Integer**) 和 **MyClass**(**String**)。这发生在编译时。运行时没有创建 **MyClass** 的实例,因为两个变量都默认为 **Nothing**: ```vb Class MyClass(Of T) ' ... Sub Test() Dim intVar As MyClass(Integer) Dim strVar As MyClass(String) Debug.Assert intVar Is Nothing AndAlso strVar Is Nothing End Sub ``` ### List 类示例 泛型类允许在整个类的方法中使用类型参数。以下示例展示了创建一个泛型 List 类: ```vb [COMCreatable(False)] Class List(Of T) Private mData() As T Sub New(preset() As T) mData = preset End Sub [DefaultMember] Function GetAt(ByVal index&) As T Return mData(index) End Function End Class Sub Test() Dim li As Any = New List(Of Integer)(Array(5, 6, 7)) Debug.Assert li(0) = 5 AndAlso li(2) = 7 End Sub ``` ### List UDT 示例 虽然 twinBASIC 中泛型 UDT 尚不支持成员过程,但数据成员是支持的: ```vb Type ListU(Of T) value() As T End Type Sub Test() Dim lu As ListU(Of Long) ReDim lu.value(10) lu.value(0) = 5 End Sub ``` \[^1]: DRY = Don't Repeat Yourself --- --- url: /zh/official/Reference/Categories.md --- 本章列出了构成twinBASIC语言核心的全局语句和过程。 # 分类列表 ## 编译器控制 * [Option](/official/Reference/Core/Option) - 配置编译器选项 * [#If ... Then ... Else](/official/Reference/Core/Topic-Preprocessor) - 启用或禁用所包含代码的编译 * [#Const](/official/Reference/Core/Topic-Preprocessor) - 定义模块私有的条件编译常量 ## 声明和定义 * [Class](/official/Reference/Core/Class), [Module](/official/Reference/Core/Module) - 定义类或模块 * [Interface](/official/Reference/Core/Interface), [CoClass](/official/Reference/Core/CoClass) - (twinBASIC) 使用twinBASIC语法定义COM接口或组件类 * [Sub](/official/Reference/Core/Sub) - 定义过程 * [Function](/official/Reference/Core/Function) - 定义函数 * [Property](/official/Reference/Core/Property) - 定义属性 * [ParamArray](/official/Reference/Core/ParamArray) - 将过程的最后一个参数声明为可变参数列表 * [Enum](/official/Reference/Core/Enum) - 定义具有关联常量的枚举类型 * [Type](/official/Reference/Core/Type) - 声明用户自定义数据类型(UDT)/结构体 * [Declare](/official/Reference/Core/Declare) - 声明外部/库过程或函数 * [Event](/official/Reference/Core/Event) - 声明事件 * [Implements](/official/Reference/Core/Implements) - 指定类实现给定接口 * [End](/official/Reference/Core/End) - 终止执行,结束Function、Sub、Property或Enum定义,结束Type声明,结束Class或Module,结束If、Select或With块 ## 流程控制 语句: * [Call](/official/Reference/Core/Call) - 调用过程或函数 * [Do ... Loop](/official/Reference/Core/Do-Loop), [For ... Next](/official/Reference/Core/For-Next), [For Each ... Next](/official/Reference/Core/For-Each-Next), [While ... Wend](/official/Reference/Core/While-Wend) - 循环 * [If ... Then ... Else](/official/Reference/Core/If-Then-Else) - 条件执行代码 * [Continue](/official/Reference/Core/Continue) - 跳到循环的下一次迭代 * [Exit](/official/Reference/Core/Exit) - 退出循环、过程、函数或属性 * [Return](/official/Reference/Core/Return) - 从**GoSub**子程序返回,或(twinBASIC)从**Function**或**Property Get**返回值并退出 * [Select Case](/official/Reference/Core/Select-Case) - 根据表达式选择执行代码块 * [With](/official/Reference/Core/With) - 将变量或表达式引入作用域 * [Goto](/official/Reference/Core/GoTo), [GoSub ... Return](/official/Reference/Core/GoSub-Return) - 将执行转移到另一位置 * [On ... GoTo](/official/Reference/Core/On-GoTo), [On ... GoSub](/official/Reference/Core/On-GoSub) - 根据表达式选择将执行转移到指定位置 * [Stop](/official/Reference/Core/Stop) - 中断执行 内联条件函数 --- 上述**If...Then...Else**和**Select Case**语句在表达式级别的替代方案: * [If](/official/Reference/VBA/Interaction/If) - 计算表达式并返回两个值之一;仅计算所选分支(twinBASIC新增) * [IIf](/official/Reference/VBA/Interaction/IIf) - 计算表达式并返回两个值之一;两个分支始终都会被计算 * [Choose](/official/Reference/VBA/Interaction/Choose) - 根据1起始索引从列表中返回一个值 * [Switch](/official/Reference/VBA/Interaction/Switch) - 在(条件, 值)对列表中返回第一个**True**条件对应的值 另见: * [End](/official/Reference/Core/End) - 终止执行。 * [On Error](/official/Reference/Core/On-Error), [Resume](/official/Reference/Core/Resume) - 运行时错误的流程控制(参见[错误处理](#error-handling)) ## 错误处理 语句: * [On Error](/official/Reference/Core/On-Error) - 指定发生错误时的处理方式 * [Resume](/official/Reference/Core/Resume) - 在捕获错误后恢复执行 * [Error](/official/Reference/Core/Error) 语句 - 模拟错误的发生(旧式;建议使用**Err.Raise**) 过程: * [Err](/official/Reference/VBA/Information/Err) - 返回描述当前运行时错误状态的**ErrObject** * [Erl](/official/Reference/VBA/Information/Erl) - 返回最近运行时错误发生的行号 * [Error$, Error](/official/Reference/VBA/Conversion/Error) 函数 - 返回与给定错误号对应的错误消息 * [CVErr](/official/Reference/VBA/Conversion/CVErr) - 将数值表达式包装为**Error**子类型的**Variant** * [SetThreadGlobalErrorTrap](/official/Reference/VBA/HiddenModule/SetThreadGlobalErrorTrap) - 注册一个回调,当未处理的运行时错误逃逸调用线程上的活动错误处理链时触发 ## 变量声明 语句: * [Dim](/official/Reference/Core/Dim) - 声明类型化标量或数组变量 * [Const](/official/Reference/Core/Const) - 声明常量 * [Public](/official/Reference/Core/Public) - 在类或模块中声明公共变量 * [Private](/official/Reference/Core/Private) - 在类或模块中声明私有变量 * [Protected](/official/Reference/Core/Protected) - (twinBASIC) 声明可在类及其派生类中访问的类成员 * [Static](/official/Reference/Core/Static) - 声明静态持续期的变量 ## 变量赋值和修改 语句: * [Let](/official/Reference/Core/Let) - 设置变量的值 * [Set](/official/Reference/Core/Set) - 更改变量引用的对象 * [New](/official/Reference/Core/New) - 创建类的新实例 * [LSet](/official/Reference/Core/LSet) - 赋值用户自定义类型,或左对齐字符串 * [RSet](/official/Reference/Core/RSet) - 右对齐字符串 运算符: * [Is](/official/Reference/Core/Is) - 比较两个对象引用是否同一 * [IsNot](/official/Reference/Core/IsNot) - (twinBASIC) **Is**的逻辑反运算 ## 数组 语句: * [ReDim](/official/Reference/Core/ReDim) - 分配或更改动态数组的大小 * [Erase](/official/Reference/Core/Erase) - 用默认值填充固定大小数组,或使动态数组无效 过程: * [LBound](/official/Reference/VBA/Information/LBound) - 数组某一维的最小有效下标 * [UBound](/official/Reference/VBA/Information/UBound) - 数组某一维的最大有效下标 * [IsArray](/official/Reference/VBA/Information/IsArray) - 返回变量是否为数组 * [IsArrayInitialized](/official/Reference/VBA/Information/IsArrayInitialized) - 返回数组是否已分配维度 另见: * [Dim](/official/Reference/Core/Dim) - 分配标量或数组变量 * [Array](/official/Reference/VBA/Information/Array), [Filter](/official/Reference/VBA/Strings/Filter), [Join](/official/Reference/VBA/Strings/Join), [Split](/official/Reference/VBA/Strings/Split) - 数组辅助函数 * [vbaAryMove](/official/Reference/VBA/HiddenModule/vbaAryMove), [vbaRefVarAry](/official/Reference/VBA/HiddenModule/vbaRefVarAry) - 底层**Variant**数组辅助函数(参见[内存和指针](#memory-and-pointers)) ## 文件I/O 语句: * [Open](/official/Reference/Core/Open), [Close](/official/Reference/Core/Close) - 打开/关闭文件进行I/O操作 * [Get](/official/Reference/Core/Get), [Put](/official/Reference/Core/Put) - 从打开的随机访问文件读取/写入数据 * [Line Input](/official/Reference/Core/Line-Input), [Print](/official/Reference/Core/Print) - 从/向打开的文本文件读取/写入一行 * [Input](/official/Reference/Core/Input), [Write](/official/Reference/Core/Write) - 从/向打开的顺序访问文件读取/写入数据 * [Seek](/official/Reference/Core/Seek) - 更改打开文件中的当前访问位置 * [Lock](/official/Reference/Core/Lock), [Unlock](/official/Reference/Core/Unlock) - 锁定/解锁打开文件中的记录范围 过程: * [Reset](/official/Reference/Core/Reset) - 关闭所有打开的磁盘文件 * [Width](/official/Reference/VBA/FileSystem/Width) - 设置打印时的行长度限制 * [Input, Input$](/official/Reference/VBA/FileSystem/Input) - 从顺序文件读取固定数量的字符 * [InputB, InputB$](/official/Reference/VBA/FileSystem/InputB) - 从顺序文件读取固定数量的字节 * [ChDir](/official/Reference/Core/ChDir), [ChDrive](/official/Reference/Core/ChDrive) - 更改当前工作目录和磁盘驱动器 * [MkDir](/official/Reference/Core/MkDir), [RmDir](/official/Reference/Core/RmDir) - 创建/删除磁盘上的目录 * [Name](/official/Reference/Core/Name) - 重命名磁盘上的文件或目录 * [SetAttr](/official/Reference/Core/SetAttr) - 设置磁盘文件的属性 * [FileCopy](/official/Reference/Core/FileCopy) - 复制磁盘上的文件 * [Kill](/official/Reference/Core/Kill) - 从磁盘删除文件 * [SavePicture](/official/Reference/Core/SavePicture) - 将`Picture`或`Image`写入磁盘文件 * [MacID](/official/Reference/VBA/Conversion/MacID) - 转换4字符Mac文件类型代码(旧式) ## 状态管理 过程: * [Load](/official/Reference/Core/Load), [Unload](/official/Reference/Core/Unload) - 将窗体或控件加载/卸载到内存 * [GetSetting](/official/Reference/VBA/Interaction/GetSetting), [SaveSetting](/official/Reference/VBA/Interaction/SaveSetting) - 从/向系统注册表检索/存储字符串值 * [GetAllSettings](/official/Reference/VBA/Interaction/GetAllSettings) - 检索应用程序注册表项中某个节的所有键值对 * [DeleteSetting](/official/Reference/VBA/Interaction/DeleteSetting) - 从系统注册表删除值 ## 事件 语句: * [RaiseEvent](/official/Reference/Core/RaiseEvent) - 引发可由事件处理器处理的事件 过程: * [RaiseEventByName](/official/Reference/VBA/Interaction/RaiseEventByName) - 按名称在对象上引发事件,以**Variant**数组形式接收参数 * [RaiseEventByName2](/official/Reference/VBA/Interaction/RaiseEventByName2) - 按名称在对象上引发事件,以可变长度参数列表接收参数 * [RuntimeCreateGetMessageHook](/official/Reference/VBA/HiddenModule/RuntimeCreateGetMessageHook) - 创建**IGetMessageHook**用于过滤发往窗口(及其后代,可选)的Windows消息 另见 * [Event](/official/Reference/Core/Event) - 声明事件 * [IGetMessageHook 接口](/official/Reference/VBA/HiddenModule/#igetmessagehook-interface) - 订阅Windows消息类型的回调,然后开始/停止消息传送 ## 用户对话框 过程: * [MsgBox](/official/Reference/VBA/Interaction/MsgBox) - 显示模态消息对话框并返回用户点击的按钮 * [InputBox](/official/Reference/VBA/Interaction/InputBox) - 提示用户输入一行文本并返回所输入的内容 * [Beep](/official/Reference/VBA/Interaction/Beep) - 发出系统提示音 ## 进程控制 过程: * [Shell](/official/Reference/VBA/Interaction/Shell) - 异步运行另一个程序并返回其任务ID * [AppActivate](/official/Reference/VBA/Interaction/AppActivate) - 将焦点切换到命名窗口或激活该窗口 * [SendKeys](/official/Reference/VBA/Interaction/SendKeys) - 向活动窗口发送按键 * [DoEvents](/official/Reference/VBA/Interaction/DoEvents) - 让出控制权到消息循环,以便处理挂起的事件 ## COM和自动化 过程: * [CreateObject](/official/Reference/VBA/Interaction/CreateObject) - 创建COM/Automation对象的新实例 * [GetObject](/official/Reference/VBA/Interaction/GetObject) - 获取从文件加载或正在运行的Automation对象的引用 * [CallByName](/official/Reference/VBA/Interaction/CallByName) - 按名称动态调用对象的方法或属性 * [CallByDispId](/official/Reference/VBA/Interaction/CallByDispId) - 按 IDispatch 调度ID动态调用对象的方法或属性(twinBASIC新增) * [CreateGUID](/official/Reference/VBA/HiddenModule/CreateGUID) - 生成新的GUID并以注册表格式字符串返回 * [vbaCastObj](/official/Reference/VBA/HiddenModule/vbaCastObj) - 将对象重新解释为另一个COM接口(类型化的`QueryInterface`) * [vbaObjSet](/official/Reference/VBA/HiddenModule/vbaObjSet), [vbaObjSetAddref](/official/Reference/VBA/HiddenModule/vbaObjSetAddref) - 将原始对象指针赋值给**Object**变量,可选是否增加引用计数 * [vbaObjAddref](/official/Reference/VBA/HiddenModule/vbaObjAddref) - 递增给定地址处对象的COM引用计数 另见: * [ObjPtr](/official/Reference/VBA/Information/ObjPtr) - 返回对象的COM标识地址(参见[内存和指针](#memory-and-pointers)) ## 命令行和环境 过程: * [Command$, Command](/official/Reference/VBA/Interaction/Command) - 返回传递给程序的命令行参数 * [Environ$, Environ](/official/Reference/VBA/Interaction/Environ) - 返回进程环境变量的值 ## 颜色 过程: * [RGB](/official/Reference/VBA/Information/RGB) - 从红、绿、蓝分量构建RGB颜色值 * [RGBA](/official/Reference/VBA/Information/RGBA) - 从红、绿、蓝和Alpha分量构建RGBA颜色值 * [RGB\_R](/official/Reference/VBA/Information/RGB_R), [RGB\_G](/official/Reference/VBA/Information/RGB_G), [RGB\_B](/official/Reference/VBA/Information/RGB_B), [RGBA\_A](/official/Reference/VBA/Information/RGBA_A) - 提取各个颜色分量 * [QBColor](/official/Reference/VBA/Information/QBColor) - 返回QuickBASIC颜色索引对应的RGB颜色值 * [TranslateColor](/official/Reference/VBA/Information/TranslateColor) - 将OLE颜色值转换为普通RGB颜色值 ## 数学 过程: * [Atn](/official/Reference/VBA/Math/Atn), [Cos](/official/Reference/VBA/Math/Cos), [Sin](/official/Reference/VBA/Math/Sin), [Tan](/official/Reference/VBA/Math/Tan) - 三角函数 * [Sqr](/official/Reference/VBA/Math/Sqr) - 求平方根 * [Exp](/official/Reference/VBA/Math/Exp) - 计算以$e$为底的指数 * [Log](/official/Reference/VBA/Math/Log) - 计算数的自然(以$e$为底)对数 * [Sgn](/official/Reference/VBA/Math/Sgn) - 返回数的符号 * [Abs](/official/Reference/VBA/Math/Abs) - 返回数的绝对值 * [Round](/official/Reference/VBA/Math/Round) - 将数舍入到指定小数位数 * [Rnd](/official/Reference/VBA/Math/Rnd) - 生成\[0.0, 1.0)范围内的随机数 * [Randomize](/official/Reference/VBA/Math/Randomize) - 为随机数生成器设置种子 * [Partition](/official/Reference/VBA/Interaction/Partition) - 返回字符串标签,标识值落入哪个等宽数值范围(直方图式分桶) 另见: * [Fix](/official/Reference/VBA/Conversion/Fix), [Int](/official/Reference/VBA/Conversion/Int) - 提取数的整数部分 * [CInt](/official/Reference/VBA/Conversion/CInt), [CLng](/official/Reference/VBA/Conversion/CLng), [CLngLng](/official/Reference/VBA/Conversion/CLngLng), [CLngPtr](/official/Reference/VBA/Conversion/CLngPtr) - 强制转换为整数类型(四舍五入到偶数) ## 类型转换 将表达式强制转换为特定类型的过程: * [CBool](/official/Reference/VBA/Conversion/CBool), [CByte](/official/Reference/VBA/Conversion/CByte), [CCur](/official/Reference/VBA/Conversion/CCur), [CDbl](/official/Reference/VBA/Conversion/CDbl), [CDec](/official/Reference/VBA/Conversion/CDec), [CInt](/official/Reference/VBA/Conversion/CInt), [CLng](/official/Reference/VBA/Conversion/CLng), [CLngLng](/official/Reference/VBA/Conversion/CLngLng), [CLngPtr](/official/Reference/VBA/Conversion/CLngPtr), [CSng](/official/Reference/VBA/Conversion/CSng) - 强制转换为特定数值类型 * [CStr](/official/Reference/VBA/Conversion/CStr) - 强制转换为**String**(识别区域设置;优于[Str](/official/Reference/VBA/Conversion/Str)) * [CVar](/official/Reference/VBA/Conversion/CVar) - 强制转换为**Variant** * [CDate](/official/Reference/VBA/Conversion/CDate) - 强制转换为**Date**;[CVDate](/official/Reference/VBA/Conversion/CVDate)返回**Date**子类型的**Variant**(旧式) * [CType](/official/Reference/VBA/Conversion/CType) - 具有调用方提供目标类型的显式强制转换运算符(twinBASIC扩展) 在数值和字符串之间转换的过程: * [Hex$, Hex](/official/Reference/VBA/Conversion/Hex) - 数值的十六进制字符串表示 * [Oct$, Oct](/official/Reference/VBA/Conversion/Oct) - 数值的八进制字符串表示 * [Str$, Str](/official/Reference/VBA/Conversion/Str) - 数值的十进制字符串表示 * [Val](/official/Reference/VBA/Conversion/Val) - 将字符串解析为**Double** * [ValDec](/official/Reference/VBA/Conversion/ValDec) - 将字符串解析为**Decimal** 提取数的整数部分的过程: * [Fix](/official/Reference/VBA/Conversion/Fix) - 向零截断 * [Int](/official/Reference/VBA/Conversion/Int) - 向负无穷舍入 其他: * [Nz](/official/Reference/VBA/Conversion/Nz) - 用默认值替换**Null** 另见: * [Format$, Format](/official/Reference/VBA/Strings/Format) - 识别区域设置的数值格式化 * [FormatNumber](/official/Reference/VBA/Strings/FormatNumber), [FormatPercent](/official/Reference/VBA/Strings/FormatPercent), [FormatCurrency](/official/Reference/VBA/Strings/FormatCurrency), [FormatDateTime](/official/Reference/VBA/Strings/FormatDateTime) - 类型化格式化函数 * [CVErr](/official/Reference/VBA/Conversion/CVErr), [Error$, Error](/official/Reference/VBA/Conversion/Error) 函数 - 错误辅助函数(参见[错误处理](#error-handling)) ## 类型检查 命名或标识变量子类型的过程: * [VarType](/official/Reference/VBA/Information/VarType) - 返回标识变量子类型的**VbVarType**代码 * [TypeName](/official/Reference/VBA/Information/TypeName) - 以**String**形式返回变量数据类型的名称 测试值状态或子类型的过程: * [IsDate](/official/Reference/VBA/Information/IsDate) - 返回表达式是否可作为日期计算 * [IsEmpty](/official/Reference/VBA/Information/IsEmpty) - 返回**Variant**是否未初始化 * [IsError](/official/Reference/VBA/Information/IsError) - 返回表达式是否为错误子类型 * [IsMissing](/official/Reference/VBA/Information/IsMissing) - 返回可选参数是否已提供 * [IsNull](/official/Reference/VBA/Information/IsNull) - 返回变量是否包含**Null**值 * [IsNumeric](/official/Reference/VBA/Information/IsNumeric) - 返回表达式是否可作为数值计算 * [IsObject](/official/Reference/VBA/Information/IsObject) - 返回变量是否引用对象 另见: * [IsArray](/official/Reference/VBA/Information/IsArray), [IsArrayInitialized](/official/Reference/VBA/Information/IsArrayInitialized) - 见[数组](#arrays) ## 字符串处理 修改字符串的语句: * [Mid =](/official/Reference/Core/Mid-equals), [MidB =](/official/Reference/Core/MidB-equals) - 赋值或替换字符或宽/窄字符串段 检查字符串属性的过程: * [Len](/official/Reference/VBA/Strings/Len), [LenB](/official/Reference/VBA/Strings/Len) - 字符串的长度 * [Asc](/official/Reference/VBA/Strings/Asc), [AscB](/official/Reference/VBA/Strings/Asc), [AscW](/official/Reference/VBA/Strings/Asc) - 返回字符串中第一个字母的字符代码 * [StrComp](/official/Reference/VBA/Strings/StrComp) - 比较两个字符串 * [InStr$](/official/Reference/VBA/Strings/InStr), [InStrB](/official/Reference/VBA/Strings/InStr), [InStr](/official/Reference/VBA/Strings/InStr) - 在字符串中查找给定子字符串的位置 创建字符串的过程: * [Chr$](/official/Reference/VBA/Strings/Chr), [Chr](/official/Reference/VBA/Strings/Chr), [ChrB$](/official/Reference/VBA/Strings/Chr), [ChrB](/official/Reference/VBA/Strings/Chr), [ChrW$](/official/Reference/VBA/Strings/Chr), [ChrW](/official/Reference/VBA/Strings/Chr) - 返回具有给定代码的字符 * [Space$](/official/Reference/VBA/Strings/Space), [Space](/official/Reference/VBA/Strings/Space) - 返回由空格组成的字符串 * [String$](/official/Reference/VBA/Strings/String), [String](/official/Reference/VBA/Strings/String) - 返回由指定字符组成的字符串 返回修改后字符串的过程: * [Left$](/official/Reference/VBA/Strings/Left), [Left](/official/Reference/VBA/Strings/Left), [LeftB$](/official/Reference/VBA/Strings/Left), [LeftB](/official/Reference/VBA/Strings/Left) - 提取字符串的左侧子串 * [Mid$](/official/Reference/VBA/Strings/Mid), [Mid](/official/Reference/VBA/Strings/Mid), [MidB$](/official/Reference/VBA/Strings/Mid), [MidB](/official/Reference/VBA/Strings/Mid) - 提取字符串的子串 * [Right$](/official/Reference/VBA/Strings/Right), [Right](/official/Reference/VBA/Strings/Right), [RightB$](/official/Reference/VBA/Strings/Right), [RightB](/official/Reference/VBA/Strings/Right) - 提取字符串的右侧子串 * [LTrim$](/official/Reference/VBA/Strings/LTrim), [LTrim](/official/Reference/VBA/Strings/LTrim), [RTrim$](/official/Reference/VBA/Strings/RTrim), [RTrim](/official/Reference/VBA/Strings/RTrim) - 删除字符串的前导/尾随空格 * [Trim$](/official/Reference/VBA/Strings/Trim), [Trim](/official/Reference/VBA/Strings/Trim) - 删除字符串的前导和尾随空格 * [StrReverse](/official/Reference/VBA/Strings/StrReverse) - 反转字符串中的字符顺序 * [LCase$](/official/Reference/VBA/Strings/LCase), [LCase](/official/Reference/VBA/Strings/LCase), [UCase$](/official/Reference/VBA/Strings/UCase), [UCase](/official/Reference/VBA/Strings/UCase) - 将字符串转换为大写或小写 * [StrConv](/official/Reference/VBA/Strings/StrConv) - 将字符串转换为指定格式 * [Join](/official/Reference/VBA/Strings/Join) - 使用给定分隔符连接字符串数组 * [Split](/official/Reference/VBA/Strings/Split) - 将字符串拆分为字符串数组 * [Replace](/official/Reference/VBA/Strings/Replace) - 替换字符串中的子串 * [Filter](/official/Reference/VBA/Strings/Filter) - 根据条件将字符串数组过滤为子集 * [InStrRev](/official/Reference/VBA/Strings/InStrRev) - 从末尾搜索,返回子字符串在字符串中的位置 * [Format$](/official/Reference/VBA/Strings/Format), [Format](/official/Reference/VBA/Strings/Format) - 以特定方式格式化数值表达式 * [FormatNumber](/official/Reference/VBA/Strings/FormatNumber) - 将表达式格式化为数值字符串 * [FormatPercent](/official/Reference/VBA/Strings/FormatPercent) - 将表达式格式化为百分比字符串 在数值和字符串之间转换的过程: * [CStr](/official/Reference/VBA/Conversion/CStr) - 将值强制转换为**String**(识别区域设置) * [Hex$, Hex](/official/Reference/VBA/Conversion/Hex) - 数值的十六进制字符串表示 * [Oct$, Oct](/official/Reference/VBA/Conversion/Oct) - 数值的八进制字符串表示 * [Str$, Str](/official/Reference/VBA/Conversion/Str) - 数值的十进制字符串表示 * [Val](/official/Reference/VBA/Conversion/Val) - 将字符串解析为**Double** * [ValDec](/official/Reference/VBA/Conversion/ValDec) - 将字符串解析为**Decimal** 另见: * [FormatCurrency](/official/Reference/VBA/Strings/FormatCurrency) - 将表达式格式化为货币字符串 * [FormatDateTime](/official/Reference/VBA/Strings/FormatDateTime) - 将表达式格式化为日期/时间字符串 ## 日期和时间 过程: * [Date](/official/Reference/Core/Date), [Time](/official/Reference/Core/Time) - 设置当前日期和时间 * [FormatDateTime](/official/Reference/VBA/Strings/FormatDateTime) - 将表达式格式化为日期/时间字符串 * [MonthName](/official/Reference/VBA/Strings/MonthName) - 返回指定月份的名称 * [WeekdayName](/official/Reference/VBA/Strings/WeekdayName) - 返回指定星期几的名称 另见: * [CDate](/official/Reference/VBA/Conversion/CDate), [CVDate](/official/Reference/VBA/Conversion/CVDate) - 将表达式强制转换为**Date**或**Variant**(子类型**Date**) ## 自省 过程: * [CurrentProjectName](/official/Reference/VBA/Compilation/CurrentProjectName) - 返回当前项目的名称 * [CurrentComponentName](/official/Reference/VBA/Compilation/CurrentComponentName) - 返回当前组件(模块或类)的名称 * [CurrentComponentCLSID](/official/Reference/VBA/Compilation/CurrentComponentCLSID) - 返回当前类的类ID(CLSID) * [CurrentProcedureName](/official/Reference/VBA/Compilation/CurrentProcedureName) - 返回调用该函数所在的过程名称 * [CurrentSourceFile](/official/Reference/VBA/Compilation/CurrentSourceFile) - 返回当前源文件的完整路径 * [ProcessorArchitecture](/official/Reference/VBA/Compilation/ProcessorArchitecture) - 返回运行应用程序的处理器架构 * [CompilerVersion](/official/Reference/VBA/Compilation/CompilerVersion) - 返回twinBASIC编译器版本号 * [GetDeclaredTypeProgId](/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId), [GetDeclaredTypeClsid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid), [GetDeclaredTypeIid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid), [GetDeclaredTypeEventIid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid) - 返回已声明类型的COM ProgID/CLSID/IID/事件IID,在编译时解析 * [GetDeclaredMinEnumValue](/official/Reference/VBA/HiddenModule/GetDeclaredMinEnumValue), [GetDeclaredMaxEnumValue](/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue) - 返回已声明枚举的最小/最大值,在编译时解析 另见: * [IMEStatus](/official/Reference/VBA/Information/IMEStatus) - 当前输入法编辑器模式(仅限东亚Windows) ## 内存和指针 过程: * [ObjPtr](/official/Reference/VBA/Information/ObjPtr) - 返回对象的COM标识地址 * [StrPtr](/official/Reference/VBA/Information/StrPtr) - 返回**String**底层缓冲区的地址 * [VarPtr](/official/Reference/VBA/Information/VarPtr) - 返回变量的地址 * [AllocMem](/official/Reference/VBA/HiddenModule/AllocMem), [FreeMem](/official/Reference/VBA/HiddenModule/FreeMem) - 分配/释放本机内存块 * [GetMem1](/official/Reference/VBA/HiddenModule/GetMem1), [GetMem2](/official/Reference/VBA/HiddenModule/GetMem2), [GetMem4](/official/Reference/VBA/HiddenModule/GetMem4), [GetMem8](/official/Reference/VBA/HiddenModule/GetMem8), [GetMemPtr](/official/Reference/VBA/HiddenModule/GetMemPtr) - 从内存地址读取N字节到类型化变量 * [PutMem1](/official/Reference/VBA/HiddenModule/PutMem1), [PutMem2](/official/Reference/VBA/HiddenModule/PutMem2), [PutMem4](/official/Reference/VBA/HiddenModule/PutMem4), [PutMem8](/official/Reference/VBA/HiddenModule/PutMem8), [PutMemPtr](/official/Reference/VBA/HiddenModule/PutMemPtr) - 将N字节的类型化值写入内存地址 * [vbaCopyBytes](/official/Reference/VBA/HiddenModule/vbaCopyBytes), [vbaCopyBytesZero](/official/Reference/VBA/HiddenModule/vbaCopyBytesZero) - 复制字节块;*Zero*形式在复制后清除源 另见: * [vbaAryMove](/official/Reference/VBA/HiddenModule/vbaAryMove), [vbaRefVarAry](/official/Reference/VBA/HiddenModule/vbaRefVarAry) - 底层**Variant**数组辅助函数(参见[数组](#arrays)) * [vbaObjSet](/official/Reference/VBA/HiddenModule/vbaObjSet), [vbaObjSetAddref](/official/Reference/VBA/HiddenModule/vbaObjSetAddref), [vbaObjAddref](/official/Reference/VBA/HiddenModule/vbaObjAddref) - 对象指针赋值和引用计数(参见[COM和自动化](#com-and-automation)) ## 线程和原子操作 过程: * [InterlockedExchangePointer](/official/Reference/VBA/HiddenModule/InterlockedExchangePointer) - 原子交换指针大小的值 * [InterlockedCompareExchangePointer](/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer) - 原子比较并交换指针大小的值 * [InterlockedCompareExchange32](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32), [InterlockedCompareExchange64](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64) - 原子32位/64位比较并交换 * [InterlockedIncrement32](/official/Reference/VBA/HiddenModule/InterlockedIncrement32), [InterlockedDecrement32](/official/Reference/VBA/HiddenModule/InterlockedDecrement32) - 原子32位递增/递减 另见: * [SetThreadGlobalErrorTrap](/official/Reference/VBA/HiddenModule/SetThreadGlobalErrorTrap) - 每线程错误陷阱(参见[错误处理](#error-handling)) ## 内联汇编和代码生成 过程: * [Emit](/official/Reference/VBA/HiddenModule/Emit) - 将自定义**Byte**值注入到所在过程的代码生成中 * [EmitAny](/official/Reference/VBA/HiddenModule/EmitAny) - 将自定义类型化值注入到所在过程的代码生成中(大小从每个值的数据类型推断) * [StackOffset](/official/Reference/VBA/HiddenModule/StackOffset) - 返回变量的栈帧偏移量,在编译时解析 * [StackArgsSize](/official/Reference/VBA/HiddenModule/StackArgsSize) - 返回所在过程的栈传参数总大小 * [UnprotectedAccess](/official/Reference/VBA/HiddenModule/UnprotectedAccess) - 返回绕过私有成员访问检查的对象引用 另见: * [直接汇编插入](/official/Features/Advanced/Assembly) - `Naked`修饰符和示例 ## 表达式求值 过程: * [Eval](/official/Reference/VBA/HiddenModule/Eval) - 编译并求值以字符串形式提供的twinBASIC表达式 另见: * [ExpressionService 模块](/official/Reference/VBA/TbExpressionService/) - 底层引擎,当需要对绑定器或已编译表达式复用进行更多控制时使用 ## 财务 过程: * [DDB](/official/Reference/VBA/Financial/DDB) - 使用双倍余额递减法计算资产折旧 * [FV](/official/Reference/VBA/Financial/FV) - 具有恒定存款和利率的投资的未来值 * [Pmt](/official/Reference/VBA/Financial/Pmt) - 具有恒定付款和利率的贷款的每期付款额 * [IPmt](/official/Reference/VBA/Financial/IPmt) - 具有恒定付款和利率的贷款的每期利息付款额 * [PPmt](/official/Reference/VBA/Financial/PPmt) - 具有恒定付款和利率的贷款的每期本金付款额 * [SYD](/official/Reference/VBA/Financial/SYD) - 年数总和法计算资产折旧 * [SLN](/official/Reference/VBA/Financial/SLN) - 在一个期间内的直线折旧 * [PV](/official/Reference/VBA/Financial/PV) - 投资的现值 * [IRR](/official/Reference/VBA/Financial/IRR) - 一系列现金流的内部收益率 * [MIRR](/official/Reference/VBA/Financial/MIRR) - 一系列现金流的修正内部收益率 * [Rate](/official/Reference/VBA/Financial/Rate) - 年金的每期利率 * [NPV](/official/Reference/VBA/Financial/NPV) - 投资的净现值 * [NPer](/official/Reference/VBA/Financial/NPer) - 具有恒定存款和利率的投资的期数 * [FormatCurrency](/official/Reference/VBA/Strings/FormatCurrency) - 将表达式格式化为货币字符串 ## 单元测试 [Assert](/official/Reference/Assert/)包的模块: * [Exact](/official/Reference/Assert/Exact) - 最严格的比较语义;数据类型必须匹配且不进行隐式转换 * [Strict](/official/Reference/Assert/Strict) - 区分大小写的字符串比较,否则使用标准twinBASIC相等比较 * [Permissive](/official/Reference/Assert/Permissive) - 不区分大小写的字符串比较,否则使用标准twinBASIC相等比较 每个模块公开相同的十五个断言:**Succeed**、**Fail**、**Inconclusive**、**AreEqual** / **AreNotEqual**、**AreSame** / **AreNotSame**、**IsTrue** / **IsFalse**、**IsNothing** / **IsNotNothing**、**IsNull** / **IsNotNull**、**SequenceEquals** / **NotSequenceEquals**。所有断言均标记`[DebugOnly(True)]`,在发布版本中不编译。 ## 已弃用 语句: * [DefBool, DefByte, DefInt, DefLng, DefCur, DefSng, DefDbl, DefDec, DefDate, DefStr, DefObj, DefVar](/official/Reference/Core/Deftype) - 用于为单字母变量赋予隐式类型 --- --- url: /zh/packages/vbccr/bars/pager.md description: 分页控件(Pager) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 分页控件(Pager) 封装 SysPager 系统分页控件,用于创建可滚动的控件区域,通过左右或上下按钮滚动关联的伙伴控件。 ## 枚举 ### PgrOrientationConstants | 常量 | 值 | 说明 | |------|-----|------| | PgrOrientationHorizontal | 0 | 水平方向 | | PgrOrientationVertical | 1 | 垂直方向 | ### PgrDirectionConstants | 常量 | 值 | 说明 | |------|-----|------| | PgrDirectionLeft | 0 | 向左滚动 | | PgrDirectionRight | 1 | 向右滚动 | | PgrDirectionUp | 2 | 向上滚动 | | PgrDirectionDown | 3 | 向下滚动 | ### PgrButtonConstants | 常量 | 值 | 说明 | |------|-----|------| | PgrButtonLeftTop | 0 | 左端/上端按钮 | | PgrButtonRightBottom | 1 | 右端/下端按钮 | ### PgrButtonStateConstants | 常量 | 值 | 说明 | |------|-----|------| | PgrButtonStateNormal | 0 | 正常 | | PgrButtonStateInvisible | 1 | 隐藏 | | PgrButtonStateGrayed | 2 | 灰色(禁用) | | PgrButtonStateInactive | 4 | 非活动 | | PgrButtonStateHot | 8 | 热态 | ### CCMousePointerConstants 参见通用枚举。 ## 属性 ### BuddyControl ```vb Property Get BuddyControl() As Variant Property Let BuddyControl(ByVal Value As Variant) ``` 关联的伙伴控件。可传递控件对象、控件名称或 hWnd。 ### Orientation ```vb Property Get Orientation() As PgrOrientationConstants Property Let Orientation(ByVal Value As PgrOrientationConstants) ``` 分页控件方向。 ### BorderWidth ```vb Property Get BorderWidth() As Long Property Let BorderWidth(ByVal Value As Long) ``` 边框宽度(像素)。 ### AutoScroll ```vb Property Get AutoScroll() As Boolean Property Let AutoScroll(ByVal Value As Boolean) ``` 是否自动滚动。 ### ButtonSize ```vb Property Get ButtonSize() As Long Property Let ButtonSize(ByVal Value As Long) ``` 按钮大小(像素)。 ### OLEDragDropScroll ```vb Property Get OLEDragDropScroll() As Boolean Property Let OLEDragDropScroll(ByVal Value As Boolean) ``` OLE 拖放时是否自动滚动。 ### Value ```vb Property Get Value() As Single Property Let Value(ByVal Value As Single) ``` 当前滚动位置。 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 分页控件的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 用户控件的窗口句柄。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针样式。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 是否启用鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示方向。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` 帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "这是什么"帮助 ID。 ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` 拖拽图标。 ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` 拖拽模式。 ## 方法 ### ReCalcSize ```vb Public Sub ReCalcSize() ``` 重新计算分页控件和伙伴控件的大小。 ### GetButtonState ```vb Public Function GetButtonState(ByVal Button As PgrButtonConstants) As PgrButtonStateConstants ``` 获取指定按钮的状态。 ### Drag ```vb Public Sub Drag([ByRef Action As Variant]) ``` 开始、结束或取消拖放操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移至控件。 ### ZOrder ```vb Public Sub ZOrder([ByRef Position As Variant]) ``` 设置控件的 Z 顺序。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放操作。 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘控件。 ## 事件 ### Scroll ```vb Public Event Scroll() ``` 滚动位置发生改变时触发。 ### CalcSize ```vb Public Event CalcSize() ``` 需要重新计算伙伴控件大小前触发。 ### HotChanged ```vb Public Event HotChanged() ``` 按钮热态改变时触发。 ### Click ```vb Public Event Click() ``` 单击控件时触发。 ### DblClick ```vb Public Event DblClick() ``` 双击控件时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE 拖放完成时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放经过控件时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 拖放需要更改光标时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 拖放开始时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放完成时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE 放置目标请求数据时触发。 ## 代码示例 ```vb ' 设置水平分页控件与图片框关联 Pager1.Orientation = PgrOrientationHorizontal Set Pager1.BuddyControl = Picture1 Pager1.ButtonSize = 16 Call Pager1.ReCalcSize ``` --- --- url: /zh/packages/vbccr/buttons/checkboxw.md description: 复选框控件(CheckBoxW) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 复选框控件(CheckBoxW) 增强型复选框控件,支持视觉样式、自绘、ImageList 图标和 PushLike 模式。 ## 枚举 ### ChkImageListAlignmentConstants | 常量 | 值 | 说明 | |------|-----|------| | ChkImageListAlignmentLeft | 0 | 左对齐 | | ChkImageListAlignmentRight | 1 | 右对齐 | | ChkImageListAlignmentTop | 2 | 顶部对齐 | | ChkImageListAlignmentBottom | 3 | 底部对齐 | | ChkImageListAlignmentCenter | 4 | 居中对齐 | ### ChkDrawModeConstants | 常量 | 值 | 说明 | |------|-----|------| | ChkDrawModeNormal | 0 | 正常模式,由系统绘制 | | ChkDrawModeOwnerDraw | 1 | 自绘模式,由代码绘制 | ## 属性 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。 ### Appearance ```vb Property Get Appearance() As CCAppearanceConstants Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` 外观样式。参见通用枚举。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景色。 ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 ### ImageList ```vb Property Get ImageList() As Variant Property Let ImageList(ByVal Value As Variant) Property Set ImageList(ByVal Value As Variant) ``` 关联的 ImageList 控件。 ### ImageListAlignment ```vb Property Get ImageListAlignment() As ChkImageListAlignmentConstants Property Let ImageListAlignment(ByVal Value As ChkImageListAlignmentConstants) ``` ImageList 图标对齐方式。 ### ImageListMargin ```vb Property Get ImageListMargin() As Single Property Let ImageListMargin(ByVal Value As Single) ``` ImageList 图标边距。 ### Value ```vb Property Get Value() As Integer Property Let Value(ByVal Value As Integer) ``` 复选框状态(0-未选中,1-选中,2-灰显)。 ### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` 标题文本。 ### Alignment ```vb Property Get Alignment() As CCLeftRightAlignmentConstants Property Let Alignment(ByVal Value As CCLeftRightAlignmentConstants) ``` 复选框的对齐方式。参见通用枚举。 ### TextAlignment ```vb Property Get TextAlignment() As VBRUN.AlignmentConstants Property Let TextAlignment(ByVal Value As VBRUN.AlignmentConstants) ``` 文本对齐方式。 ### PushLike ```vb Property Get PushLike() As Boolean Property Let PushLike(ByVal Value As Boolean) ``` 是否以按钮样式显示。 ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` 图片。 ### WordWrap ```vb Property Get WordWrap() As Boolean Property Let WordWrap(ByVal Value As Boolean) ``` 是否自动换行。 ### Transparent ```vb Property Get Transparent() As Boolean Property Let Transparent(ByVal Value As Boolean) ``` 是否透明背景(运行时有效)。 ### VerticalAlignment ```vb Property Get VerticalAlignment() As CCVerticalAlignmentConstants Property Let VerticalAlignment(ByVal Value As CCVerticalAlignmentConstants) ``` 垂直对齐。参见通用枚举。 ### Style ```vb Property Get Style() As VBRUN.ButtonConstants Property Let Style(ByVal Value As VBRUN.ButtonConstants) ``` 外观样式(标准或图形)。 ### DisabledPicture ```vb Property Get DisabledPicture() As IPictureDisp Property Let DisabledPicture(ByVal Value As IPictureDisp) Property Set DisabledPicture(ByVal Value As IPictureDisp) ``` 禁用状态图片。Style 为图形时有效。 ### DownPicture ```vb Property Get DownPicture() As IPictureDisp Property Let DownPicture(ByVal Value As IPictureDisp) Property Set DownPicture(ByVal Value As IPictureDisp) ``` 按下状态图片。Style 为图形时有效。 ### UseMaskColor ```vb Property Get UseMaskColor() As Boolean Property Let UseMaskColor(ByVal Value As Boolean) ``` 是否使用遮罩色。Style 为图形时有效。 ### MaskColor ```vb Property Get MaskColor() As OLE_COLOR Property Let MaskColor(ByVal Value As OLE_COLOR) ``` 遮罩色。Style 为图形时有效。 ### DrawMode ```vb Property Get DrawMode() As ChkDrawModeConstants Property Let DrawMode(ByVal Value As ChkDrawModeConstants) ``` 绘制模式。 ### Pushed ```vb Property Get Pushed() As Boolean ``` 是否处于按下状态。只读。 ### Hot ```vb Property Get Hot() As Boolean ``` 是否处于热状态(鼠标悬停)。只读。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 用户控件窗口句柄。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE 拖放模式。参见通用枚举。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 鼠标进入/离开跟踪。 ### Name / Tag / Parent / Container / Left / Top / Width / Height / Visible / ToolTipText / HelpContextID / WhatsThisHelpID / DragIcon / DragMode 参见标准扩展器属性。 ## 方法 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放。 ### Drag / ZOrder / SetFocus / Move 参见标准方法。 ## 事件 ### Click ```vb Public Event Click() ``` 单击。 ### DblClick ```vb Public Event DblClick() ``` 双击。 ### HotChanged ```vb Public Event HotChanged() ``` 热状态改变时触发。 ### OwnerDraw ```vb Public Event OwnerDraw(ByVal ItemAction As Long, ByVal ItemState As Long, ByVal hDC As LongPtr, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` 自绘事件。DrawMode 为 OwnerDraw 时触发。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` ### KeyPress ```vb Public Event KeyPress(KeyAscii As Integer) ``` ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` ### MouseEnter ```vb Public Event MouseEnter() ``` ### MouseLeave ```vb Public Event MouseLeave() ``` ### OLECompleteDrag / OLEDragDrop / OLEDragOver / OLEGiveFeedback / OLESetData / OLEStartDrag 参见 OLE 拖放事件。 ## 代码示例 ### 基本用法 ```vb ' 设置三态复选框 CheckBoxW1.Value = vbChecked ' 选中 CheckBoxW2.Value = vbUnchecked ' 未选中 CheckBoxW3.Value = vbGrayed ' 灰显 ' PushLike 按钮样式 CheckBoxW1.PushLike = True ' 关联 ImageList Set CheckBoxW1.ImageList = ImageList1 CheckBoxW1.ImageListAlignment = ChkImageListAlignmentLeft ``` ### 自绘模式 ```vb Private Sub CheckBoxW1_OwnerDraw(ByVal ItemAction As Long, ByVal ItemState As Long, _ ByVal hDC As LongPtr, ByVal Left As Long, ByVal Top As Long, _ ByVal Right As Long, ByVal Bottom As Long) ' 在此绘制自定义复选框 End Sub ``` --- --- url: /zh/packages/vbccr/text/richtextbox.md description: 富文本框控件(RichTextBox) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 富文本框控件(RichTextBox) 封装 RichEdit 系统富文本编辑控件,提供格式化文本编辑、RTF 文件读写、OLE 对象嵌入、打印、查找替换及自动超链接检测等功能。 ## 枚举 ### RtfLoadSaveFormatConstants | 常量 | 值 | 说明 | |------|-----|------| | RtfLoadSaveFormatRTF | 0 | RTF 格式 | | RtfLoadSaveFormatText | 1 | 纯文本格式 | | RtfLoadSaveFormatUnicodeText | 2 | Unicode 纯文本格式 | ### RtfFindOptionConstants | 常量 | 值 | 说明 | |------|-----|------| | RtfFindOptionWholeWord | \&H2 | 全字匹配 | | RtfFindOptionMatchCase | \&H4 | 区分大小写 | | RtfFindOptionNoHighlight | \&H8 | 不高亮匹配结果 | | RtfFindOptionReverse | \&H10 | 反向搜索 | ### RtfActionTypeConstants | 常量 | 值 | 说明 | |------|-----|------| | RtfActionTypeUnknown | 0 | 未知操作 | | RtfActionTypeTyping | 1 | 键入操作 | | RtfActionTypeDelete | 2 | 删除操作 | | RtfActionTypeDragDrop | 3 | 拖放操作 | | RtfActionTypeCut | 4 | 剪切操作 | | RtfActionTypePaste | 5 | 粘贴操作 | | RtfActionTypeAutoTable | 6 | 自动表格操作 | ### RtfSelAlignmentConstants | 常量 | 值 | 说明 | |------|-----|------| | RtfSelAlignmentLeft | 0 | 左对齐 | | RtfSelAlignmentRight | 1 | 右对齐 | | RtfSelAlignmentCenter | 2 | 居中对齐 | | RtfSelAlignmentJustified | 3 | 两端对齐 | ### RtfSelTypeConstants | 常量 | 值 | 说明 | |------|-----|------| | RtfSelTypeEmpty | 0 | 空选区 | | RtfSelTypeText | 1 | 文本 | | RtfSelTypeObject | 2 | OLE 对象 | | RtfSelTypeMultiChar | 4 | 多字符 | | RtfSelTypeMultiObject | 8 | 多 OLE 对象 | ### RtfTextModeConstants | 常量 | 值 | 说明 | |------|-----|------| | RtfTextModeRichText | 0 | 富文本模式 | | RtfTextModePlainText | 1 | 纯文本模式 | ### CCMousePointerConstants 参见通用枚举。 ### OLEDropModeConstants 参见通用枚举。 ### CCRightToLeftModeConstants 参见通用枚举。 ### CCIMEModeConstants 参见通用枚举。 ## 属性 ### Text ```vb Property Get Text() As String Property Let Text(ByVal Value As String) ``` 控件中包含的纯文本内容。默认属性。 ### TextLength ```vb Property Get TextLength() As Long ``` 文本长度(字符数)。只读。 ### TextRTF ```vb Property Get TextRTF() As String Property Let TextRTF(ByVal Value As String) ``` 包含所有 RTF 代码的 RTF 文本内容。 ### SelText ```vb Property Get SelText() As String Property Let SelText(ByVal Value As String) ``` 当前选区的文本内容。 ### SelRTF ```vb Property Get SelRTF() As String Property Let SelRTF(ByVal Value As String) ``` 当前选区的 RTF 文本(包含所有 RTF 代码)。 ### SelStart ```vb Property Get SelStart() As Long Property Let SelStart(ByVal Value As Long) ``` 选区的起始位置,无选区时为插入点位置。 ### SelLength ```vb Property Get SelLength() As Long Property Let SelLength(ByVal Value As Long) ``` 选区的字符数。 ### SelAlignment ```vb Property Get SelAlignment() As Variant Property Let SelAlignment(ByVal Value As Variant) ``` 段落对齐方式,值为 RtfSelAlignmentConstants 之一。 ### SelBold ```vb Property Get SelBold() As Variant Property Let SelBold(ByVal Value As Variant) ``` 当前选区的粗体格式。 ### SelItalic ```vb Property Get SelItalic() As Variant Property Let SelItalic(ByVal Value As Variant) ``` 当前选区的斜体格式。 ### SelStrikethru ```vb Property Get SelStrikethru() As Variant Property Let SelStrikethru(ByVal Value As Variant) ``` 当前选区的删除线格式。 ### SelUnderline ```vb Property Get SelUnderline() As Variant Property Let SelUnderline(ByVal Value As Variant) ``` 当前选区的下划线格式。 ### SelBullet ```vb Property Get SelBullet() As Variant Property Let SelBullet(ByVal Value As Variant) ``` 当前选区或插入点所在段落是否具有项目符号样式。 ### SelCharOffset ```vb Property Get SelCharOffset() As Variant Property Let SelCharOffset(ByVal Value As Variant) ``` 字符偏移量,确定文本显示在基线上(正常)、基线上方(上标)或基线下方(下标)。 ### SelColor ```vb Property Get SelColor() As Variant Property Let SelColor(ByVal Value As Variant) ``` 当前选区的文本颜色。 ### SelBkColor ```vb Property Get SelBkColor() As Variant Property Let SelBkColor(ByVal Value As Variant) ``` 当前选区的文本背景颜色。 ### SelFontName ```vb Property Get SelFontName() As Variant Property Let SelFontName(ByVal Value As Variant) ``` 当前选区的字体名称。 ### SelFontSize ```vb Property Get SelFontSize() As Variant Property Let SelFontSize(ByVal Value As Variant) ``` 当前选区的字体大小(磅)。 ### SelFontCharset ```vb Property Get SelFontCharset() As Variant Property Let SelFontCharset(ByVal Value As Variant) ``` 当前选区的字体字符集。 ### SelProtected ```vb Property Get SelProtected() As Variant Property Let SelProtected(ByVal Value As Variant) ``` 当前选区文本是否受保护(不可编辑)。 ### SelIndent ```vb Property Get SelIndent() As Variant Property Let SelIndent(ByVal Value As Variant) ``` 左缩进距离。 ### SelRightIndent ```vb Property Get SelRightIndent() As Variant Property Let SelRightIndent(ByVal Value As Variant) ``` 右缩进距离。 ### SelHangingIndent ```vb Property Get SelHangingIndent() As Variant Property Let SelHangingIndent(ByVal Value As Variant) ``` 首行缩进距离(相对于左缩进)。 ### SelVisible ```vb Property Get SelVisible() As Variant Property Let SelVisible(ByVal Value As Variant) ``` 当前选区文本是否可见。 ### SelLink ```vb Property Get SelLink() As Variant Property Let SelLink(ByVal Value As Variant) ``` 当前选区文本是否标记为超链接。 ### SelTabCount ```vb Property Get SelTabCount() As Variant Property Let SelTabCount(ByVal Value As Variant) ``` 当前选区的制表位数量。 ### SelTabs ```vb Property Get SelTabs(ByVal Element As Integer) As Variant Property Let SelTabs(ByVal Element As Integer, ByVal Value As Variant) ``` 当前选区的绝对制表位位置。 ### Modified ```vb Property Get Modified() As Boolean Property Let Modified(ByVal Value As Boolean) ``` 控件内容是否已被修改。设置 Text 属性将重置为 False,任何输入操作将设为 True。 ### UndoType ```vb Property Get UndoType() As RtfActionTypeConstants ``` 下一个撤销操作的类型。只读。 ### RedoType ```vb Property Get RedoType() As RtfActionTypeConstants ``` 下一个重做操作的类型。只读。 ### LeftMargin ```vb Property Get LeftMargin() As Single Property Let LeftMargin(ByVal Value As Single) ``` 左边距宽度。 ### RightMargin ```vb Property Get RightMargin() As Single Property Let RightMargin(ByVal Value As Single) ``` 右边距宽度。 ### ZoomFactor ```vb Property Get ZoomFactor() As Double Property Let ZoomFactor(ByVal Value As Double) ``` 当前缩放比例。 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。需要 comctl32.dll 6.0 或更高版本。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### AllowDropFiles ```vb Property Get AllowDropFiles() As Boolean Property Let AllowDropFiles(ByVal Value As Boolean) ``` 是否允许拖放文件。仅当没有 OLE 放置目标时适用。 ### OLEDragDropRTF ```vb Property Get OLEDragDropRTF() As Boolean Property Let OLEDragDropRTF(ByVal Value As Boolean) ``` 富文本框控件是否可作为 OLE 拖放源和放置目标。 ### OLEDragMode ```vb Property Get OLEDragMode() As VBRUN.OLEDragConstants Property Let OLEDragMode(ByVal Value As VBRUN.OLEDragConstants) ``` OLE 拖放模式。当 OLEDragDropRTF 为 True 时必须为 Manual。 ### OLEDragDropScroll ```vb Property Get OLEDragDropScroll() As Boolean Property Let OLEDragDropScroll(ByVal Value As Boolean) ``` OLE 拖放操作期间是否允许滚动。当 OLEDragDropRTF 为 True 时必须为 True。 ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE 放置目标模式。当 OLEDragDropRTF 为 True 时必须为 None。参见通用枚举。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针样式。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 是否启用鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示方向。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### BorderStyle ```vb Property Get BorderStyle() As Integer Property Let BorderStyle(ByVal Value As Integer) ``` 边框样式(vbBSNone 或 vbFixedSingle)。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景颜色。仅当 Enabled 为 True 时适用。 ### Locked ```vb Property Get Locked() As Boolean Property Let Locked(ByVal Value As Boolean) ``` 内容是否锁定为只读。 ### HideSelection ```vb Property Get HideSelection() As Boolean Property Let HideSelection(ByVal Value As Boolean) ``` 控件失去焦点时是否隐藏选区。 ### PasswordChar ```vb Property Get PasswordChar() As String Property Let PasswordChar(ByVal Value As String) ``` 密码字符,用于替代实际字符显示。当 UseSystemPasswordChar 为 True 时此属性无效。 ### UseSystemPasswordChar ```vb Property Get UseSystemPasswordChar() As Boolean Property Let UseSystemPasswordChar(ByVal Value As Boolean) ``` 是否使用默认系统密码字符。此属性优先于 PasswordChar。 ### MultiLine ```vb Property Get MultiLine() As Boolean Property Let MultiLine(ByVal Value As Boolean) ``` 是否允许多行文本。运行时只读。 ### MaxLength ```vb Property Get MaxLength() As Long Property Let MaxLength(ByVal Value As Long) ``` 可输入的最大字符数。 ### ScrollBars ```vb Property Get ScrollBars() As VBRUN.ScrollBarConstants Property Let ScrollBars(ByVal Value As VBRUN.ScrollBarConstants) ``` 滚动条样式。 ### WantReturn ```vb Property Get WantReturn() As Boolean Property Let WantReturn(ByVal Value As Boolean) ``` 按下回车键时是执行默认按钮还是换行。仅适用于多行富文本框且有默认按钮时。 ### DisableNoScroll ```vb Property Get DisableNoScroll() As Boolean Property Let DisableNoScroll(ByVal Value As Boolean) ``` 不需要滚动条时是否禁用而非隐藏。运行时只读。 ### AutoURLDetect ```vb Property Get AutoURLDetect() As Boolean Property Let AutoURLDetect(ByVal Value As Boolean) ``` 是否启用自动超链接检测。 ### BulletIndent ```vb Property Get BulletIndent() As Single Property Let BulletIndent(ByVal Value As Single) ``` 段落使用项目符号时的缩进量。 ### SelectionBar ```vb Property Get SelectionBar() As Boolean Property Let SelectionBar(ByVal Value As Boolean) ``` 是否在左边距添加选择栏,光标变为右上箭头,允许用户选择整行。 ### FileName ```vb Property Get FileName() As String Property Let FileName(ByVal Value As String) ``` 设计时加载到控件中的文件名。 ### TextMode ```vb Property Get TextMode() As RtfTextModeConstants Property Let TextMode(ByVal Value As RtfTextModeConstants) ``` 文本模式(富文本或纯文本)。 ### UndoLimit ```vb Property Get UndoLimit() As Long Property Let UndoLimit(ByVal Value As Long) ``` 撤销队列中可存储的最大操作数。0 表示禁用撤销功能。 ### IMEMode ```vb Property Get IMEMode() As CCIMEModeConstants Property Let IMEMode(ByVal Value As CCIMEModeConstants) ``` 输入法编辑器(IME)模式。参见通用枚举。 ### AllowOverType ```vb Property Get AllowOverType() As Boolean Property Let AllowOverType(ByVal Value As Boolean) ``` 是否允许激活改写模式。 ### OverTypeMode ```vb Property Get OverTypeMode() As Boolean Property Let OverTypeMode(ByVal Value As Boolean) ``` 改写模式是否激活。在改写模式下,输入的字符逐个替换已有字符。 ### UseCrLf ```vb Property Get UseCrLf() As Boolean Property Let UseCrLf(ByVal Value As Boolean) ``` 控件是否将每个 Cr 翻译为 CrLf 用于 Text 属性。 ### AutoVerbMenu ```vb Property Get AutoVerbMenu() As Boolean Property Let AutoVerbMenu(ByVal Value As Boolean) ``` 右键单击选中的 OLE 对象时是否显示其动词弹出菜单。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 富文本框控件的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 用户控件的窗口句柄。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` 帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "这是什么"帮助 ID。 ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` 拖拽图标。 ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` 拖拽模式。 ## 方法 ### Copy ```vb Public Sub Copy() ``` 将当前选区复制到剪贴板。 ### Cut ```vb Public Sub Cut() ``` 删除当前选区并将文本复制到剪贴板。 ### Paste ```vb Public Sub Paste() ``` 将剪贴板内容粘贴到当前插入点位置。 ### CanPaste ```vb Public Function CanPaste(Optional ByVal wFormat As Long) As Boolean ``` 确定剪贴板上是否有可粘贴的格式。 ### PasteSpecial ```vb Public Sub PasteSpecial(ByVal wFormat As Long) ``` 以指定剪贴板格式粘贴到富文本框。 ### PasteSpecialDlg ```vb Public Sub PasteSpecialDlg() ``` 显示"选择性粘贴"对话框。 ### Clear ```vb Public Sub Clear() ``` 清除当前选区。 ### Undo ```vb Public Sub Undo() ``` 撤销上一次操作(如果有)。 ### CanUndo ```vb Public Function CanUndo() As Boolean ``` 确定撤销队列中是否有可撤销的操作。 ### StopUndoAction ```vb Public Sub StopUndoAction() ``` 停止控件将后续键入操作收集到当前撤销操作中。 ### ResetUndoQueue ```vb Public Sub ResetUndoQueue() ``` 重置撤销队列。 ### Redo ```vb Public Sub Redo() ``` 重做下一个操作(如果有)。 ### CanRedo ```vb Public Function CanRedo() As Boolean ``` 确定重做队列中是否有可重做的操作。 ### GetTextRange ```vb Public Function GetTextRange(ByVal Min As Long, ByVal Max As Long) As String ``` 获取指定范围内的文本。 ### Find ```vb Public Function Find(ByVal Text As String, Optional ByVal Min As Long, Optional ByVal Max As Long = -1, Optional ByVal Options As RtfFindOptionConstants) As Long ``` 在富文本框中查找文本,返回找到的字符位置,未找到返回 -1。 ### Span ```vb Public Sub Span(ByVal CharacterSet As String, Optional ByVal Forward As Boolean, Optional ByVal Negate As Boolean) ``` 基于指定字符集选中文本。 ### UpTo ```vb Public Sub UpTo(ByVal CharacterSet As String, Optional ByVal Forward As Boolean, Optional ByVal Negate As Boolean) ``` 将插入点移动到但不包含指定字符集中的第一个字符。 ### SaveFile ```vb Public Sub SaveFile(ByVal FileName As String, Optional ByVal Format As RtfLoadSaveFormatConstants = RtfLoadSaveFormatRTF, Optional ByVal SelectionOnly As Boolean) ``` 将控件内容保存到文件。 ### LoadFile ```vb Public Sub LoadFile(ByVal FileName As String, Optional ByVal Format As RtfLoadSaveFormatConstants = RtfLoadSaveFormatRTF, Optional ByVal SelectionOnly As Boolean) ``` 加载 RTF 或文本文件到控件。 ### GetLine ```vb Public Function GetLine(ByVal LineNumber As Long) As String ``` 获取指定行的文本。0 表示当前行(包含插入点的行)。 ### GetLineCount ```vb Public Function GetLineCount() As Long ``` 获取行数。 ### ScrollToLine ```vb Public Sub ScrollToLine(ByVal LineNumber As Long) ``` 滚动以确保指定行可见。 ### ScrollToCaret ```vb Public Sub ScrollToCaret() ``` 将插入点滚动到可见区域。 ### CharFromPos ```vb Public Function CharFromPos(ByVal X As Single, ByVal Y As Single) As Long ``` 返回距离指定点最近的字符索引。 ### GetLineFromChar ```vb Public Function GetLineFromChar(ByVal CharIndex As Long) As Long ``` 获取包含指定字符索引的行号。字符索引 -1 返回当前行。 ### GetSelType ```vb Public Function GetSelType() As Integer ``` 确定当前选区类型,返回 RtfSelTypeConstants 标志组合。 ### SelPrint ```vb Public Sub SelPrint(ByVal hDC As LongPtr, Optional ByVal CallStartEndDoc As Boolean = True, Optional ByVal DocName As String = "RICHTEXT", Optional ByVal LeftMargin As Long, Optional ByVal TopMargin As Long, Optional ByVal RightMargin As Long, Optional ByVal BottomMargin As Long) ``` 将富文本框中的格式化文本发送到设备进行打印。若无选区则打印全部内容。 ### PrintDoc ```vb Public Sub PrintDoc(ByVal hDC As LongPtr, Optional ByVal CallStartEndDoc As Boolean = True, Optional ByVal DocName As String = "RICHTEXT", Optional ByVal LeftMargin As Long, Optional ByVal TopMargin As Long, Optional ByVal RightMargin As Long, Optional ByVal BottomMargin As Long) ``` 将富文本框中的全部格式化文本发送到设备进行打印。 ### GetOLEInterface ```vb Public Function GetOLEInterface() As IUnknown ``` 检索 IRichEditOle 对象,用于访问 COM 功能。 ### OLEObjectsAdd ```vb Public Sub OLEObjectsAdd(ByVal LpOleObject As LongPtr) ``` 插入一个 OLE 对象到富文本框。 ### OLEObjectsAddFromFile ```vb Public Sub OLEObjectsAddFromFile(ByVal FileName As String, Optional ByVal LinkToFile As Boolean) ``` 从文件插入一个 OLE 对象到富文本框。 ### OLEObjectsAddFromPicture ```vb Public Sub OLEObjectsAddFromPicture(ByVal Picture As IPictureDisp, Optional ByVal ClipFormat As Variant) ``` 从图片对象插入一个 OLE 对象到富文本框。 ### OLEObjectsGet ```vb Public Function OLEObjectsGet(ByVal IndexObj As Long, Optional ByVal CharPos As Long) As LongPtr ``` 检索富文本框中的 OLE 对象。 ### OLEObjectsCount ```vb Public Function OLEObjectsCount() As Long ``` 返回当前富文本框中包含的 OLE 对象数量。 ### Drag ```vb Public Sub Drag([ByRef Action As Variant]) ``` 开始、结束或取消拖放操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移至控件。 ### ZOrder ```vb Public Sub ZOrder([ByRef Position As Variant]) ``` 设置控件的 Z 顺序。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放操作。 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘控件。 ## 事件 ### Change ```vb Public Event Change() ``` 控件内容发生变化时触发。 ### MaxText ```vb Public Event MaxText() ``` 当前文本插入超出最大字符数时触发。 ### SelChange ```vb Public Event SelChange(ByVal SelType As Integer, ByVal SelStart As Long, ByVal SelEnd As Long) ``` 当前文本选区发生变化或插入点移动时触发。 ### LinkEvent ```vb Public Event LinkEvent(ByVal wMsg As Long, ByVal wParam As LongPtr, ByVal lParam As LongPtr, ByVal LinkStart As Long, ByVal LinkEnd As Long) ``` 鼠标点击或悬停在具有超链接格式的文本上时触发。 ### DropFiles ```vb Public Event DropFiles(ByRef FileList As Variant, ByVal X As Single, ByVal Y As Single, ByVal CharPos As Long, ByVal Protected As Boolean, ByRef Cancel As Boolean) ``` 用户将文件拖放到控件上时触发。仅当没有 OLE 放置目标且 AllowDropFiles 为 True 时适用。 ### ModifyProtected ```vb Public Event ModifyProtected(ByRef Allow As Boolean, ByVal SelStart As Long, ByVal SelEnd As Long) ``` 用户尝试编辑受保护文本时触发。 ### Scroll ```vb Public Event Scroll() ``` 重新定位滚动条时触发。 ### ContextMenu ```vb Public Event ContextMenu(ByRef Handled As Boolean, ByVal X As Single, ByVal Y As Single) ``` 用户右键单击或按 Shift+F10 时触发。设置 Handled 为 True 可取消默认菜单。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyDown 事件之前触发。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyUp 事件之前触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件时触发。 ### OLEDragDropDone ```vb Public Event OLEDragDropDone() ``` 富文本框控件完成或取消 OLE 拖放操作后触发。 ### OLEGetDropEffect ```vb Public Event OLEGetDropEffect(ByRef Effect As Long, ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` OLE 拖放操作期间由控件触发,用于指定放置操作的结果效果。 ### OLEGetDragEffect ```vb Public Event OLEGetDragEffect(ByRef AllowedEffects As Long) ``` 控件启动 OLE 拖放操作时触发。 ### OLEGetContextMenu ```vb Public Event OLEGetContextMenu(ByVal SelType As Integer, ByVal LpOleObject As LongPtr, ByVal SelStart As Long, ByVal SelEnd As Long, ByRef hMenu As LongPtr) ``` 请求提供弹出菜单供控件右键单击时使用。控件在完成后销毁此菜单。 ### OLEContextMenuClick ```vb Public Event OLEContextMenuClick(ByVal ID As Long) ``` 用户从 OLEGetContextMenu 事件提供的弹出菜单中选择项时触发。 ### OLEDeleteObject ```vb Public Event OLEDeleteObject(ByVal LpOleObject As LongPtr) ``` OLE 对象即将在控件中被删除时触发。OLE 对象不一定被释放。 ### Click ```vb Public Event Click() ``` 在控件上按下并释放鼠标按钮时触发。 ### DblClick ```vb Public Event DblClick() ``` 在控件上双击鼠标时触发。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下按键时触发。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放按键时触发。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按键字符输入时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放操作完成或取消后触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 数据通过 OLE 拖放操作放到控件上时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放操作期间鼠标移过控件时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 拖放操作中需要更改鼠标光标时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` 放置目标请求 OLEDragStart 期间未提供的数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 拖放操作启动时触发。 ## 代码示例 ```vb ' 加载 RTF 文件 RichTextBox1.LoadFile "C:\doc.rtf", RtfLoadSaveFormatRTF ' 设置选区格式 RichTextBox1.SelStart = 0 RichTextBox1.SelLength = 10 RichTextBox1.SelBold = True RichTextBox1.SelColor = vbRed RichTextBox1.SelFontSize = 14 ' 查找文本 Dim pos As Long pos = RichTextBox1.Find("关键字", 0, -1, RtfFindOptionMatchCase) ' 撤销/重做 If RichTextBox1.CanUndo Then RichTextBox1.Undo If RichTextBox1.CanRedo Then RichTextBox1.Redo ' 打印 RichTextBox1.SelPrint Printer.hDC ' 插入 OLE 对象 RichTextBox1.OLEObjectsAddFromPicture LoadPicture("C:\image.bmp") ' 保存为纯文本 RichTextBox1.SaveFile "C:\output.txt", RtfLoadSaveFormatText ``` --- --- url: /zh/official/Features/Advanced.md --- # 高级功能 twinBASIC 的高级功能,用于底层编程和系统集成。 ## 主题 * [多线程](/official/Features/Advanced/Multithreading) - 线程安全与多线程支持 * [汇编](/official/Features/Advanced/Assembly) - 使用 Emit() 直接插入汇编代码 * [静态链接](/official/Features/Advanced/Static-Linking) - OBJ 和 LIB 文件的静态链接 * [API 声明](/official/Features/Advanced/API-Declarations) - 增强的 API 和方法声明 * [类和模块功能](/official/Features/Advanced/Classes-and-Modules) - 参数化构造函数、ReadOnly 和导出 --- --- url: /zh/official/IDE/Menu/Format.md --- # 格式菜单 ![格式菜单](/assets/Menu_Format.C7B-ICY0.png "格式菜单") ![格式菜单](/assets/Menu_Format_1.BBLE3blt.png "格式菜单") * 对齐 * 统一大小 *** * 水平间距 * 垂直间距 *** * 在容器中居中(水平) * 在容器中居中(垂直) *** * 置于顶层 * 置于底层 *** * 锁定控件 ![格式对齐菜单](/assets/Menu_Format_Align.BHoU0xe7.png "格式对齐菜单") * 左对齐 ALT + ARROWLEFT * 居中(水平) * 右对齐 ALT + ARROWRIGHT *** * 顶部对齐 ALT + ARROWUP * 居中(垂直) * 底部对齐 ALT + ARROWDOWN *** * 对齐到网格 ![格式统一大小菜单](/assets/Menu_Format_MakeSameSize.BNcLwAv6.png "格式统一大小菜单") * 宽度(最宽) CTRL + SHIFT + ARROWRIGHT * 宽度(最窄) CTRL + SHIFT + ARROWLEFT * 高度(最高) CTRL + SHIFT + ARROWDOWN * 高度(最矮) CTRL + SHIFT + ARROWUP ![格式水平间距菜单](/assets/Menu_Format_HorizontalSpacing.D2rxkKWw.png "格式水平间距菜单") * 使相等 * 增加 * 减少 * 移除 ![格式垂直间距菜单](/assets/Menu_Format_VerticalSpacing.C9Uk5-Qe.png "格式垂直间距菜单") * 使相等 * 增加 * 减少 * 移除 --- --- url: /zh/official/Features/Packages/Updating-a-package.md --- # 更新包 当加载项目时,编译器会通知你 TWINSERV 上是否有项目中的包的新版本可用: ![image](/assets/db4636f6-d988-4e31-94a2-c4c170418e81.BIgQiyG9.png) 如果你发现 TWINSERV 上有更新的包可用,必须先通过取消勾选来移除项目中的旧包。打开 Settings 到 References,取消勾选框。然后你将被提示从文件系统中移除它: ![415937809-87a11bc3-9a9c-4551-86c2-69d206d95087](/assets/a1331a0e-3ba3-45cf-8dc3-2e24f0fa1fe6.Bz7ZsCJB.png) 选择"Remove it"。 然后转到 Available Packages 选项卡,勾选最新版本的框,**等下载完成后**(可能需要几秒钟,因为有些包有数 MB),保存更改。在调试控制台中你会首先看到 `[PACKAGES] downloading package '{1FCDB98D-617D-4995-9736-2ED0E4746A10}/8/7/0/498' from the online database... ` 然后当第二条消息 `[PACKAGES] downloading package '{1FCDB98D-617D-4995-9736-2ED0E4746A10}/8/7/0/498' from the online database... [DONE]` 出现时,表示完成并可以保存了。复选框也会从旋转状态变为条目移到顶部(在内置包下方),并在前面加上 `[IMPORTED]`。 如果保存后编译器没有自动重启,手动重启编译器,但通常会自动重启。 **注意:** 将来会有简单的更新选项。请留意该变化。 --- --- url: /zh/official/IDE/Menu/Tools.md --- # 工具菜单 ![工具菜单](Images/Menu_Tools.png "工具菜单") * IDE 选项... ![IDE 选项 - 工具菜单](/assets/Menu_Tools_IDEOptions.Dto2pgCF.png "IDE 选项 - 工具菜单") ::: info TODO: 添加每个 IDE 选项项。 ::: | 选项 | 值 | | -------- | ----- | | 制表符大小 | 4 | --- --- url: /zh/official/IDE/Toolbar.md --- # 工具栏 ![工具栏](/assets/Toolbar_1.C0WxKoji.png "工具栏") ![工具栏](/assets/Toolbar_2.CLivnZbt.png "工具栏") ![工具栏](/assets/Toolbar_3.CnQd3x-U.png "工具栏") ![工具栏](/assets/Toolbar_4.COwguJpa.png "工具栏") * 全部保存 (CTRL + S) * 在项目中查找... (CTRL + SHIFT + F) (CTRL + ⇧ + F) * 在窗体和代码之间切换 * 撤销 * 重做 * 启动/继续 (F5) * 中断到代码 (CTRL + BREAK) * 停止 * 逐过程 (SHIFT + F8 / F10) * 逐语句 (F8 / F10) * 跳出 (CTRL + SHIFT + F8 / SHIFT + F11) * 选择构建配置 * 重启编译器 * 清理(注销并删除构建) * 构建 * 注释选区 (CTRL + K) * 取消注释选区 (CTRL + SHIFT + K) * 缩进块 (CTRL + \[) * 减少缩进块 (CTRL + ]) * 将控件向左对齐 (ALT + ARROWLEFT) * 将控件向上对齐 (ALT + ARROWUP) * 将控件向右对齐 (ALT + ARROWRIGHT) * 将控件向下对齐 (ALT + ARROWDOWN) * 将控件调整为最宽 (CTRL + SHIFT + ARROWRIGHT) * 将控件调整为最高 (CTRL + SHIFT + ARROWDOWN) * 将控件调整为最窄 (CTRL + SHIFT + ARROWLEFT) * 将控件调整为最矮 (CTRL + SHIFT + ARROWUP) * 切换网格指示器开/关 * 将选定控件移到 z 序前面 * 将选定控件移到 z 序后面 * 窗体设计器缩放比例 * 隔离启动窗体以测试功能 * 更改 IDE 主题 * 全局搜索 --- --- url: /zh/packages/vbccr/bars/toolbar.md description: 工具栏控件(ToolBar) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 工具栏控件(ToolBar) 提供可自定义的工具栏,支持扁平/标准样式、下拉按钮、按钮菜单、用户自定义和OLE拖放。 ## 枚举 ### TbrStyleConstants 工具栏样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbrStyleStandard | 0 | 标准工具栏样式 | | TbrStyleFlat | 1 | 扁平工具栏样式 | ### TbrTextAlignConstants 按钮文本对齐方式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbrTextAlignBottom | 0 | 文本显示在按钮底部 | | TbrTextAlignRight | 1 | 文本显示在按钮右侧 | ### TbrOrientationConstants 工具栏方向常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbrOrientationHorizontal | 0 | 水平方向 | | TbrOrientationVertical | 1 | 垂直方向 | ### TbrButtonStyleConstants 按钮样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbrButtonDefault | 0 | 默认按钮样式 | | TbrButtonCheck | 1 | 复选按钮样式 | | TbrButtonCheckGroup | 2 | 复选组按钮样式(同组互斥) | | TbrButtonSeparator | 3 | 分隔符 | | TbrButtonDropDown | 4 | 下拉按钮样式 | | TbrButtonWholeDropDown | 5 | 整体下拉按钮样式 | ### TbrButtonValueConstants 按钮状态值常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbrButtonUnpressed | 0 | 未按下状态 | | TbrButtonPressed | 1 | 按下状态 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### Container ```vb Public Property Get Container() As Object Public Property Set Container(ByVal Value As Object) ``` 返回/设置对象的容器。 ### Left ```vb Public Property Get Left() As Single Public Property Let Left(ByVal Value As Single) ``` 返回/设置对象与其容器左边缘的距离。 ### Top ```vb Public Property Get Top() As Single Public Property Let Top(ByVal Value As Single) ``` 返回/设置对象与其容器顶边缘的距离。 ### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 返回/设置对象的宽度。 ### Height ```vb Public Property Get Height() As Single Public Property Let Height(ByVal Value As Single) ``` 返回/设置对象的高度。 ### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 返回/设置鼠标悬停时显示的提示文本。 ### WhatsThisHelpID ```vb Public Property Get WhatsThisHelpID() As Long Public Property Let WhatsThisHelpID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### Align ```vb Public Property Get Align() As Integer Public Property Let Align(ByVal Value As Integer) ``` 返回/设置控件在其窗体上的对齐方式。 ### DragIcon ```vb Public Property Get DragIcon() As IPictureDisp Public Property Let DragIcon(ByVal Value As IPictureDisp) Public Property Set DragIcon(ByVal Value As IPictureDisp) ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Public Property Get DragMode() As Integer Public Property Let DragMode(ByVal Value As Integer) ``` 返回/设置拖动模式(手动或自动)。 ### hWnd ```vb Public Property Get hWnd() As LongPtr ``` 返回控件句柄。 ### hWndUserControl ```vb Public Property Get hWndUserControl() As LongPtr ``` 返回UserControl句柄。 ### Font ```vb Public Property Get Font() As StdFont Public Property Let Font(ByVal NewFont As StdFont) Public Property Set Font(ByVal NewFont As StdFont) ``` 返回/设置字体。 ### VisualStyles ```vb Public Property Get VisualStyles() As Boolean Public Property Let VisualStyles(ByVal Value As Boolean) ``` 返回/设置是否启用视觉样式。需要comctl32.dll 6.0或更高版本。 ### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 返回/设置对象是否能响应用户事件。 ### OLEDropMode ```vb Public Property Get OLEDropMode() As OLEDropModeConstants Public Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` 返回/设置对象是否可以作为OLE放置目标。 ### MousePointer ```vb Public Property Get MousePointer() As CCMousePointerConstants Public Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 返回/设置鼠标悬停时显示的指针类型。参见通用枚举。 ### MouseIcon ```vb Public Property Get MouseIcon() As IPictureDisp Public Property Let MouseIcon(ByVal Value As IPictureDisp) Public Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Public Property Get MouseTrack() As Boolean Public Property Let MouseTrack(ByVal Value As Boolean) ``` 返回/设置是否在鼠标进入或离开控件时触发事件。 ### RightToLeft ```vb Public Property Get RightToLeft() As Boolean Public Property Let RightToLeft(ByVal Value As Boolean) ``` 返回/设置从右到左显示方向。 ### RightToLeftLayout ```vb Public Property Get RightToLeftLayout() As Boolean Public Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 返回/设置从右到左布局。 ### RightToLeftMode ```vb Public Property Get RightToLeftMode() As CCRightToLeftModeConstants Public Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 返回/设置从右到左模式。参见通用枚举。 ### ImageList ```vb Public Property Get ImageList() As Variant Public Property Let ImageList(ByVal Value As Variant) Public Property Set ImageList(ByVal Value As Variant) ``` 返回/设置关联的ImageList控件。可以是对象引用、字符串键名或LongPtr句柄。 ### DisabledImageList ```vb Public Property Get DisabledImageList() As Variant Public Property Let DisabledImageList(ByVal Value As Variant) Public Property Set DisabledImageList(ByVal Value As Variant) ``` 返回/设置按钮禁用状态使用的ImageList控件。 ### HotImageList ```vb Public Property Get HotImageList() As Variant Public Property Let HotImageList(ByVal Value As Variant) Public Property Set HotImageList(ByVal Value As Variant) ``` 返回/设置按钮热点状态使用的ImageList控件。 ### PressedImageList ```vb Public Property Get PressedImageList() As Variant Public Property Let PressedImageList(ByVal Value As Variant) Public Property Set PressedImageList(ByVal Value As Variant) ``` 返回/设置按钮按下状态使用的ImageList控件。 ### BackColor ```vb Public Property Get BackColor() As OLE_COLOR Public Property Let BackColor(ByVal Value As OLE_COLOR) ``` 返回/设置背景色。 ### Style ```vb Public Property Get Style() As TbrStyleConstants Public Property Let Style(ByVal Value As TbrStyleConstants) ``` 返回/设置工具栏样式。 ### TextAlignment ```vb Public Property Get TextAlignment() As TbrTextAlignConstants Public Property Let TextAlignment(ByVal Value As TbrTextAlignConstants) ``` 返回/设置按钮文本对齐方式。 ### Orientation ```vb Public Property Get Orientation() As TbrOrientationConstants Public Property Let Orientation(ByVal Value As TbrOrientationConstants) ``` 返回/设置工具栏方向。 ### Divider ```vb Public Property Get Divider() As Boolean Public Property Let Divider(ByVal Value As Boolean) ``` 返回/设置是否显示分隔线。 ### ShowTips ```vb Public Property Get ShowTips() As Boolean Public Property Let ShowTips(ByVal Value As Boolean) ``` 返回/设置是否显示工具提示。 ### Wrappable ```vb Public Property Get Wrappable() As Boolean Public Property Let Wrappable(ByVal Value As Boolean) ``` 返回/设置按钮是否自动换行。 ### AllowCustomize ```vb Public Property Get AllowCustomize() As Boolean Public Property Let AllowCustomize(ByVal Value As Boolean) ``` 返回/设置是否允许用户自定义工具栏。 ### AltDrag ```vb Public Property Get AltDrag() As Boolean Public Property Let AltDrag(ByVal Value As Boolean) ``` 返回/设置是否允许Alt+拖动来自定义工具栏。 ### DoubleBuffer ```vb Public Property Get DoubleBuffer() As Boolean Public Property Let DoubleBuffer(ByVal Value As Boolean) ``` 返回/设置是否启用双缓冲绘制。 ### ButtonHeight ```vb Public Property Get ButtonHeight() As Single Public Property Let ButtonHeight(ByVal Value As Single) ``` 返回/设置按钮高度。 ### ButtonWidth ```vb Public Property Get ButtonWidth() As Single Public Property Let ButtonWidth(ByVal Value As Single) ``` 返回/设置按钮宽度。 ### MinButtonWidth ```vb Public Property Get MinButtonWidth() As Single Public Property Let MinButtonWidth(ByVal Value As Single) ``` 返回/设置最小按钮宽度。 ### MaxButtonWidth ```vb Public Property Get MaxButtonWidth() As Single Public Property Let MaxButtonWidth(ByVal Value As Single) ``` 返回/设置最大按钮宽度。 ### InsertMarkColor ```vb Public Property Get InsertMarkColor() As OLE_COLOR Public Property Let InsertMarkColor(ByVal Value As OLE_COLOR) ``` 返回/设置插入标记颜色。 ### Transparent ```vb Public Property Get Transparent() As Boolean Public Property Let Transparent(ByVal Value As Boolean) ``` 返回/设置工具栏是否透明。 ### HotTracking ```vb Public Property Get HotTracking() As Boolean Public Property Let HotTracking(ByVal Value As Boolean) ``` 返回/设置是否启用热点跟踪。 ### HideClippedButtons ```vb Public Property Get HideClippedButtons() As Boolean Public Property Let HideClippedButtons(ByVal Value As Boolean) ``` 返回/设置是否隐藏被裁剪的按钮。 ### AnchorHot ```vb Public Property Get AnchorHot() As Boolean Public Property Let AnchorHot(ByVal Value As Boolean) ``` 返回/设置是否锚定热点。 ### MaxTextRows ```vb Public Property Get MaxTextRows() As Integer Public Property Let MaxTextRows(ByVal Value As Integer) ``` 返回/设置最大文本行数。 ### Buttons ```vb Public Property Get Buttons() As TbrButtons ``` 返回按钮集合。 ## 方法 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动OLE拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置Z顺序。 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘对象。 ## 事件 ### Click ```vb Public Event Click() ``` 用户单击控件时触发。 ### DblClick ```vb Public Event DblClick() ``` 用户双击控件时触发。 ### Resize ```vb Public Event Resize() ``` 控件大小改变时触发。 ### BeginCustomization ```vb Public Event BeginCustomization() ``` 开始自定义工具栏时触发。 ### InitCustomizationDialog ```vb Public Event InitCustomizationDialog(ByVal hDlg As LongPtr, ByRef HideHelpButton As Boolean) ``` 初始化自定义对话框时触发。hDlg为对话框句柄,HideHelpButton控制是否隐藏帮助按钮。 ### CustomizationChange ```vb Public Event CustomizationChange() ``` 自定义工具栏发生改变时触发。 ### ResetCustomizations ```vb Public Event ResetCustomizations(ByRef CloseDialog As Boolean) ``` 重置自定义时触发。CloseDialog控制是否关闭对话框。 ### CustomizationHelp ```vb Public Event CustomizationHelp() ``` 用户在自定义对话框中点击帮助时触发。 ### EndCustomization ```vb Public Event EndCustomization() ``` 结束自定义工具栏时触发。 ### ButtonClick ```vb Public Event ButtonClick(ByVal Button As TbrButton) ``` 用户单击按钮时触发。 ### ButtonDrag ```vb Public Event ButtonDrag(ByVal Button As TbrButton, ByVal MouseButton As Integer) ``` 用户拖动按钮时触发。 ### ButtonHotChanged ```vb Public Event ButtonHotChanged(ByVal Button As TbrButton, ByVal Hot As Boolean) ``` 按钮热点状态改变时触发。 ### ButtonDropDown ```vb Public Event ButtonDropDown(ByVal Button As TbrButton) ``` 下拉按钮被点击时触发。 ### ButtonMenuClick ```vb Public Event ButtonMenuClick(ByVal ButtonMenu As TbrButtonMenu) ``` 下拉菜单项被点击时触发。 ### ButtonMenuClick2 ```vb Public Event ButtonMenuClick2(ByVal Button As TbrButton, ByVal ID As Long) ``` 下拉菜单项被点击时触发,同时提供所属按钮和菜单项ID。 ### ButtonMouseEnter ```vb Public Event ButtonMouseEnter(ByVal Button As TbrButton) ``` 鼠标进入按钮区域时触发。 ### ButtonMouseLeave ```vb Public Event ButtonMouseLeave(ByVal Button As TbrButton) ``` 鼠标离开按钮区域时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件区域时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件区域时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE拖放操作完成时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE拖放操作放置时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE拖放操作悬停时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE拖放操作给反馈时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE拖放操作设置数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE拖放操作开始时触发。 ## 子对象 ### TbrButton 类 工具栏按钮对象。 #### TbrButton 属性 #### Index ```vb Public Property Get Index() As Long ``` 按钮在集合中的索引。 #### Key ```vb Public Property Get Key() As String Public Property Let Key(ByVal Value As String) ``` 按钮的唯一标识键。 #### Tag ```vb Public Property Get Tag() As Variant Public Property Let Tag(ByVal Value As Variant) ``` 额外数据。 #### ID ```vb Public Property Get ID() As Long ``` 按钮ID。 #### Caption ```vb Public Property Get Caption() As String Public Property Let Caption(ByVal Value As String) ``` 按钮标题。 #### Style ```vb Public Property Get Style() As TbrButtonStyleConstants Public Property Let Style(ByVal Value As TbrButtonStyleConstants) ``` 按钮样式。 #### Image ```vb Public Property Get Image() As Variant Public Property Let Image(ByVal Value As Variant) ``` 按钮图像。 #### ImageIndex ```vb Public Property Get ImageIndex() As Long ``` 图像索引。 #### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 #### Description ```vb Public Property Get Description() As String Public Property Let Description(ByVal Value As String) ``` 按钮描述。 #### Value ```vb Public Property Get Value() As TbrButtonValueConstants Public Property Let Value(ByVal Value As TbrButtonValueConstants) ``` 按钮值(按下/未按下状态)。 #### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 #### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 #### MixedState ```vb Public Property Get MixedState() As Boolean Public Property Let MixedState(ByVal Value As Boolean) ``` 是否处于混合状态(三态复选框)。 #### HighLighted ```vb Public Property Get HighLighted() As Boolean Public Property Let HighLighted(ByVal Value As Boolean) ``` 是否高亮显示。 #### NoImage ```vb Public Property Get NoImage() As Boolean Public Property Let NoImage(ByVal Value As Boolean) ``` 是否不显示图像。 #### NoPrefix ```vb Public Property Get NoPrefix() As Boolean Public Property Let NoPrefix(ByVal Value As Boolean) ``` 是否不处理助记符前缀(&)。 #### AutoSize ```vb Public Property Get AutoSize() As Boolean Public Property Let AutoSize(ByVal Value As Boolean) ``` 是否自动调整大小。 #### CustomWidth ```vb Public Property Get CustomWidth() As Single Public Property Let CustomWidth(ByVal Value As Single) ``` 自定义宽度。 #### ForeColor ```vb Public Property Get ForeColor() As OLE_COLOR Public Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 #### Position ```vb Public Property Get Position() As Long Public Property Let Position(ByVal Value As Long) ``` 按钮位置。 #### Hot ```vb Public Property Get Hot() As Boolean ``` 是否处于热点状态。 #### Left ```vb Public Property Get Left() As Single ``` 按钮左边距。 #### Top ```vb Public Property Get Top() As Single ``` 按钮顶边距。 #### Width ```vb Public Property Get Width() As Single ``` 按钮宽度。 #### Height ```vb Public Property Get Height() As Single ``` 按钮高度。 #### ButtonMenus ```vb Public Property Get ButtonMenus() As TbrButtonMenus ``` 下拉菜单集合。 #### hMenu ```vb Public Property Get hMenu() As LongPtr ``` 菜单句柄。 ### TbrButtonMenu 类 按钮下拉菜单项对象。 #### TbrButtonMenu 属性 #### Index ```vb Public Property Get Index() As Long ``` 菜单项索引。 #### Key ```vb Public Property Get Key() As String Public Property Let Key(ByVal Value As String) ``` 唯一标识键。 #### Tag ```vb Public Property Get Tag() As Variant Public Property Let Tag(ByVal Value As Variant) ``` 额外数据。 #### Text ```vb Public Property Get Text() As String Public Property Let Text(ByVal Value As String) ``` 菜单项文本。 #### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 #### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 #### Checked ```vb Public Property Get Checked() As Boolean Public Property Let Checked(ByVal Value As Boolean) ``` 是否选中。 #### Separator ```vb Public Property Get Separator() As Boolean Public Property Let Separator(ByVal Value As Boolean) ``` 是否为分隔符。 #### Picture ```vb Public Property Get Picture() As IPictureDisp Public Property Set Picture(ByVal Value As IPictureDisp) ``` 菜单项图标。 #### Parent ```vb Public Property Get Parent() As TbrButton ``` 所属按钮。 ### TbrButtonMenus 类 按钮下拉菜单项集合。 #### TbrButtonMenus 成员 #### NewEnum ```vb Public Function NewEnum() As IUnknown ``` 枚举器(隐藏)。 #### Add ```vb Public Function Add(Optional ByVal Index As Variant, Optional ByVal Key As Variant, Optional ByVal Text As Variant) As TbrButtonMenu ``` 添加菜单项。 #### Item ```vb Public Function Item(ByVal Index As Variant) As TbrButtonMenu ``` 获取菜单项(默认成员)。 #### Exists ```vb Public Function Exists(ByVal Index As Variant) As Boolean ``` 检查菜单项是否存在。 #### Count ```vb Public Property Get Count() As Long ``` 菜单项数量。 #### Clear ```vb Public Sub Clear() ``` 清除所有菜单项。 #### Remove ```vb Public Sub Remove(ByVal Index As Variant) ``` 移除菜单项。 ### TbrButtons 类 工具栏按钮集合。 #### TbrButtons 成员 #### NewEnum ```vb Public Function NewEnum() As IUnknown ``` 枚举器(隐藏)。 #### Add ```vb Public Function Add(Optional ByVal Index As Variant, Optional ByVal Key As Variant, Optional ByVal Caption As Variant, Optional ByVal Style As Variant, Optional ByVal Image As Variant) As TbrButton ``` 添加按钮。 #### Item ```vb Public Function Item(ByVal Index As Variant) As TbrButton ``` 获取按钮(默认成员)。 #### Exists ```vb Public Function Exists(ByVal Index As Variant) As Boolean ``` 检查按钮是否存在。 #### Count ```vb Public Property Get Count() As Long ``` 按钮数量。 #### Clear ```vb Public Sub Clear() ``` 清除所有按钮。 #### Remove ```vb Public Sub Remove(ByVal Index As Variant) ``` 移除按钮。 ### TbrButtonProperties 类 按钮内部属性对象(Friend访问)。 #### FInit ```vb Friend Property Get FInit() As Boolean Friend Property Let FInit(ByVal Value As Boolean) ``` 内部初始化标志。 #### ForeColor ```vb Public Property Get ForeColor() As OLE_COLOR Public Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 ## 代码示例 ### 基本用法 ```vb ' 创建工具栏并添加按钮 With ToolBar1.Buttons .Add , "New", "新建", tbrButtonDefault, 1 .Add , "Open", "打开", tbrButtonDefault, 2 .Add , , , tbrButtonSeparator .Add , "Bold", "加粗", tbrButtonCheck, 3 End With ' 为按钮添加下拉菜单 Dim btn As TbrButton Set btn = ToolBar1.Buttons.Add(, "Font", "字体", tbrButtonDropDown, 4) With btn.ButtonMenus .Add , "Arial", "Arial" .Add , "Courier", "Courier New" .Add , , , , , True ' 分隔符 .Add , "Tahoma", "Tahoma" End With ' 处理按钮点击 Private Sub ToolBar1_ButtonClick(ByVal Button As TbrButton) Select Case Button.Key Case "New": MsgBox "新建文件" Case "Open": MsgBox "打开文件" Case "Bold": MsgBox "加粗: " & Button.Value End Select End Sub ' 处理下拉菜单点击 Private Sub ToolBar1_ButtonMenuClick(ByVal ButtonMenu As TbrButtonMenu) MsgBox "选择字体: " & ButtonMenu.Text End Sub ``` --- --- url: /zh/official/IDE/Toolbox.md --- # 工具箱 工具箱列出了当前项目中可用于放置到窗体和设计器上的控件。可以通过 **+ 更多组件** 按钮添加额外的 COM 组件,这会打开项目设置的 COM 引用部分。 参见 [控件](/official/Reference/Controls) ![+ 更多组件](Images/Toolbox_MoreComponents.png "+ 更多组件") ![组件消息](/assets/Components_Message.BAa2XLqh.png "组件消息") "转到 COM 引用"按钮带你到**项目设置**并按 "project.references" 筛选。 ![库引用 - 项目设置](/assets/ProjectSettings_LibraryReferences.DnG_2vGd.png "库引用 - 项目设置") 点击 *可用 COM 引用* 选项卡。 ![可用 COM 引用 - 项目设置](/assets/ProjectSettings_AvailableCOMReferences.D1Lg66SW.png "可用 COM 引用 - 项目设置") 更多信息请参见[项目设置](/official/IDE/Project-Settings)。 --- --- url: /zh/official/Documentation/Tools.md --- # 工具与脚本 文档仓库中每个可执行文件的单行参考:`docs/` 下的Windows批处理包装器、`scripts/` 下的跨平台Node和Python脚本、`tbdocs` 编排器及其CLI标志,以及PDF渲染驱动器。如果你在寻找日常工作流而非速查表,[构建与部署](/official/Documentation/Building)页面更适合;如果你在修改构建管线本身,[tbdocs内部机制](/official/Documentation/Builder)页面更深入。 ## docs/下的批处理包装器 每个批处理文件使用 `@pushd "%~dp0"` 从仓库根目录运行,无论从何处调用。POSIX等效命令在各批处理条目下方列出。 ### build.bat ``` build.bat [extra tbdocs flags] ``` 渲染文档。包装 `node builder\tbdocs.mjs --src docs` 并通过 `%*` 转发额外参数。生成 `_site/`、`_site-offline/` 和 `_site-pdf/`,受 `--no-offline` / `--no-pdf` 标志和 `_config.yml` 中的 `also_build_offline` / `also_build_pdf` 键控制。当前源码树的构建时间端到端约3秒。 ### serve.bat ``` serve.bat ``` 启动长期开发进程。包装 `node builder\tbdocs.mjs --src docs --serve` 并通过 `%*` 转发额外参数。初始构建后,HTTP服务器绑定到端口4000(传 `--port ` 使用不同端口),递归源码树监视器在每次更改时触发防抖重建,连接到页面的浏览器通过SSE在每次成功重建后自动重载。离线和PDF传递在每次重建时跳过。Ctrl+C干净退出。**仅记录失败(4xx、5xx、服务器异常)**——成功请求无输出。 ### check.bat ``` check.bat ``` 以两个并行传递对渲染的 `_site/` 和 `_site-offline/` 树运行 `scripts/check_links.mjs`。离线传递还运行 `--forbid "https://docs.twinbasic.com"` 以标记离线重写遗漏的任何存活站点链接。两个传递都断言链接完整性、HTML良构性、重复 `id` 检测、锚点解析和无障碍提示;在线传递额外检查 `sitemap.xml` 和搜索索引。需要先运行 `build.bat`。 ### book.bat ``` book.bat ``` 从 `docs\_site-pdf\book.html` 渲染PDF书到 `docs\_pdf\twinBASIC Book.pdf`。调用 `node book\render-book.mjs`(见[下方](#bookrender-bookmjs))。需要 `build.bat` 已填充 `_site-pdf/` 和通过 `npx puppeteer browsers install chrome` 安装的Chromium。首次调用在缺少 `puppeteer` 时自动运行 `npm install`。输出文件名由此处的 `-o` 参数设置;要重命名PDF,需在 `book.bat` 和 `.github/workflows/jekyll-gh-pages.yml` 中更新。 ## CLI工具 ### tbdocs --- node builder/tbdocs.mjs 静态站点生成器入口。`build.bat` 调用 `node builder\tbdocs.mjs --src docs`;CI以相同方式调用。 完整调用: ``` node builder/tbdocs.mjs [--src ] [--dest ] [--baseurl ] [--url ] [--dry-run] [--no-offline] [--no-pdf] [--tolerate-missing-images] [--profile-offline] [--serve] [--port ] ``` | 标志 | 作用 | |---|---| | `--src ` | 源根目录。默认:相对于工作目录的 `docs`。 | | `--dest ` | 在线树目标。默认:`/_site`。离线树位于 `-offline`,PDF树位于 `-pdf`。 | | `--baseurl ` | 覆盖 `_config.yml` 的 `baseurl`。CI用于在fork部署时注入GitHub Pages基础路径。 | | `--url ` | 覆盖 `_config.yml` 的 `url`。CI用于使规范URL匹配实际部署源而非配置的生产主机。 | | `--dry-run` | 跳过所有文件系统写入。用于基准测试或验证发现/计算/渲染。 | | `--no-offline` | 跳过离线树传递。 | | `--no-pdf` | 跳过PDF树传递。 | | `--tolerate-missing-images` | 将阶段8的缺失图片错误降级为警告。当源码树正在编辑且可能临时引用尚不存在的图片时使用。 | | `--profile-offline` | 打印离线树传递的每子步骤计时。 | | `--serve` | 启动长期开发服务器(监视+重建+SSE实时重载)。每次重建跳过离线和PDF传递。 | | `--port ` | `--serve` 模式的HTTP端口。默认:4000。 | ### scripts/check\_links.mjs ``` node scripts/check_links.mjs [pass-args...] [/sep/ [pass-args...] ...] ``` 离线(仅文件系统)链接检查器加可选完整性检查。多个 `/sep/` 分隔的传递通过 `worker_threads` 并行运行。相关标志: | 标志 | 作用 | |---|---| | `--offline` | 必需。在线(网络)链接检查未实现。 | | `--root-dir ` | 解析根绝对URL所依据的文件系统根目录。 | | `--fallback-extensions ` | 当链接目标原样不存在时追加的扩展名逗号分隔列表。使用 `html` 镜像GitHub Pages的无扩展名URL行为。 | | `--index-files ` | 当URL解析到目录时尝试的文件名逗号分隔列表。使用 `'index.html,.'` 也接受目录本身作为有效目标。 | | `--base-path ` | 在解析前从根绝对URL中去除此前缀。CI中设置 `--baseurl` 时使用。 | | `--include-fragments` | 根据目标页面的ID解析 `#fragment` 锚点。 | | `--forbid ` | 可重复。如果任何提取的链接以 `prefix` 开头则运行失败。离线传递用于捕获离线重写遗漏的存活站点链接(裸前缀和 `prefix/` 豁免)。 | | `--check-html` | 断言HTML良构性。 | | `--check-a11y` | 显示无障碍提示(缺少 `alt` 等)。 | | `--check-ids` | 标记页面内重复的 `id` 属性。 | | `--check-sitemap` | 断言 `sitemap.xml` 覆盖每个页面。 | | `--check-search` | 断言搜索索引条目解析到现有页面。 | | `--check-canonical` | 断言每个页面的规范URL匹配其位置。 | | `--no-fail` | 将失败降级为信息输出(即使有断链也退出码0)。 | 退出码1表示断链;退出码2表示仅完整性失败(完整性检查与链接提取共享同一SAX解析传递)。脚本对 `(target, fragment)` 去重,因此每个唯一文件系统检查恰好触发一次,无论多少页面链接到同一目标——在当前源码树上(约733k链接出现,约12k唯一目标横跨1,127个HTML文件/124 MB)每个传递在开发机上约2.2秒运行。 ### scripts/crawl\_check.mjs ``` node scripts/crawl_check.mjs [--concurrency N] [--timeout MS] [--skip-external] ``` 已部署站点的在线链接爬虫。从 `` 开始,GET每个同源/同基础路径页面递归,提取链接,验证每个链接响应2xx(跨源HEAD,同源GET)。所有链接可达退出0,任何断链退出1。在手动 `workflow_dispatch` 部署后用于验证已发布站点——`check_links.mjs` 覆盖本地文件系统;`crawl_check.mjs` 覆盖实时部署的站点。 ### scripts/convert\_em\_dash\_separators.py ``` python scripts/convert_em_dash_separators.py ``` 将 `docs/` 下Markdown源中的字面短划线/长划线字符规范化为其kramdown智能引号ASCII源形式(`--` 表示短划线,`---` 表示长划线)。站点禁止源代码中出现字面 `–` / `—`——如果有混入,这是规范的修复工具。跳过围栏代码块和内联代码跨度。 ### book/render-book.mjs ``` node book/render-book.mjs -o [options] ``` `book.bat` 调用的PDF渲染器。它是一个通用HTML转PDF转换器:以预构建的 `_site-pdf/book.html` 作为唯一文档输入,不了解 `_data/book.yml`——所有章节结构、标题级别和大纲条目已由 `tbdocs` 阶段8嵌入HTML中。直接使用 `puppeteer` + `paged.js` + `pdf-lib`,因此控制了 `pdf-lib` 的 `parseSpeed`(默认值在加载时每100个对象之间让出事件循环,为100秒构建增加约32秒无意义开销——参见[perf/README.md](https://github.com/twinbasic/documentation/blob/main/perf/README.md)的诊断)。替代了早期的 `npx pagedjs-cli ...` 调用。 `book.bat` 使用的关键选项: | 标志 | 作用 | |---|---| | `-o ` | 输出PDF路径。 | | `--outline-tags h1,h2,h3,h4` | 包含在PDF大纲/书签中的标题级别。 | | `--additional-script ` | 在paged.js运行前注入的脚本路径。`book.bat` 传递 `perf\detach-pages.js`,它从Chromium的布局树中隐藏每个已定型的页面,并在 `page.pdf()` 运行前全部恢复,通过绕过paged.js的二次溢出遍历器将1,638页书籍的渲染时间从约104秒降至约51秒。 | ## 配置文件 构建管线还读取少量声明性文件。它们不可执行,但构建行为依赖于它们。 | 文件 | 作用 | |---|---| | `docs/_config.yml` | 站点配置。`tbdocs` 读取 `url`、`baseurl`、`title`、`logo`、`also_build_offline`、`also_build_pdf`、`offline_exclude`、`exclude`、页脚/辅助链接旋钮、GitHub编辑链接旋钮和离线下载链接旋钮。Jekyll专用键(`markdown`、`kramdown`、`theme`、`highlighter`、`defaults`块、`compress_html`块)被忽略。 | | `docs/_book.yml` | PDF书的章节清单。条目通过选择器模式(`page` / `pages` / `nav_page` / `nav_pages` / `no_descent`)解析为页面,并通过 `landing_page:`、`landing_is_target:`、`no_outline_entry:`、`no_heading_shift:` 和 `outline_closed:` 控制PDF大纲行为。完整模式记录在文件头部。阶段2解析章节数组;阶段8组装 `book.html`。 | | `builder/themes/Light.theme`、`Dark.theme`、`Classic.theme` | 从BETA安装程序供应商的twinBASIC IDE主题文件。`builder/highlight-theme.mjs` 将其解析为Symbol键控的调色板,驱动渲染器的scope到类映射和生成的 `tb-highlight.css`。当IDE添加新调色板条目时从安装程序刷新。 | | `builder/twinbasic.tmLanguage.json` | twinBASIC语言的TextMate语法。Shiki使用它对每个 ` ```vb ` 代码块进行分词。 | > AI生成 --- --- url: /zh/official/Features.md --- # 功能特性 本节记录了 twinBASIC 相比 VBx 及更早的 BASIC 方言所提供的全部功能增强和特性。 twinBASIC 在保持与 VBx 语法向后兼容的同时提供这些新功能。大多数增强都是可选的,允许你在项目中逐步采用。 如需了解每项功能的详细文档,请导航到下方列出的具体分类。 ## 分类 ### [特性](/official/Features/Attributes-Intro) 特性允许你为窗体、模块、类、类型、枚举、声明和过程添加编译器指令和元数据标注。现在这些内容可以直接在代码编辑器中看到。 ### [语言语法](/official/Features/Language/) twinBASIC 引入了大量语言增强功能,包括: * 新数据类型:**LongPtr**、**LongLong**、**Decimal** * 原生 **Interface** 和 **CoClass** 定义 * 通过 **Implements Via** 和 **Inherits** 实现的 OOP 功能 * 泛型和方法重载 * 增强的运算符和字面量 * 类型推断和指针功能 * 带有方法和事件的 UDT 增强 ### [项目配置](/official/Features/Project-Configuration/) twinBASIC 提供多种项目类型和配置选项: * 标准 DLL、控制台应用程序、服务和内核驱动 * 用于优化和安全的编译器选项 * 入口点覆盖和 IAT 放置 * ActiveX 项目的注册选项 ### [标准库](/official/Features/Standard-Library/) 标准库的增强包括: * 全面 Unicode 支持 * 支持多种编码的文件 I/O * 新的内置函数和 App 对象属性 * 直接的 COM 错误处理访问 * 数组解构赋值 ### [GUI 组件](/official/Features/GUI-Components/) 现代化的 GUI 组件,包括: * 支持透明和 Alpha 混合的增强窗体 * 控件锚定和停靠 * 有窗口和无窗口控件 * 64 位支持和 DPI 感知 * 新控件(QR Code、Multiframe、CheckMark) ### [包管理](/official/Features/Packages/) twinBASIC\[^1] 拥有一个名为 TWINSERV 的集中式包仓库。用户可以发布公开和私有包。包的浏览、下载和发布无缝集成到 IDE 中。 包是可被其他 twinBASIC 项目引用的组件集合。它们以 TWINPACK 文件形式分发,包含该包中组件所需的一切。 \[^1]: TWINBASIC LTD 向用户社区提供的服务。 ### [高级功能](/official/Features/Advanced/) 高级编程能力: * 通过直接 API 调用的多线程支持 * 使用 `Emit()` 直接插入汇编代码 * OBJ 和 LIB 文件的静态链接 * 增强的 API 声明(CDecl、可变参数、ByVal UDT) * 参数化构造函数和类导出 ### [编译器和 IDE 功能](/official/Features/Compiler-IDE/) 改进的开发体验: * 编译器警告和严格模式 * 调试跟踪记录器和过期指针检测 * 用于直接运行 Sub 的 CodeLens * 具有主题、代码折叠等功能的现代 IDE * 用于代码共享的包服务器 ### [Fusion](/official/Features/Fusion) Fusion 使 64 位应用程序能够托管 32 位 ActiveX 控件(反之亦然),通过一个外部进程宿主可执行文件透明地桥接它们,使用基于 IPC 的通信。 ### [64位编译](/official/Features/64bit) twinBASIC 除了编译 32 位外,还能编译原生 64 位可执行文件,使用 **LongPtr** 数据类型和 **PtrSafe** 关键字来标记 API 声明。 --- --- url: /zh/official/Tutorials/CEF/Building-a-browser-shell.md --- # 构建浏览器外壳 一个简短的工作教程:将[**CefBrowser**](/official/Reference/CEF/CefBrowser/)控件变成一个可工作的浏览器,带有地址栏、后退/前进/刷新按钮、缩放以及一些辅助工具(DevTools、PDF导出)。 完整项目以*示例1b——Chromium Embedded Framework示例*的形式在新项目对话框中提供(窗体*示例1*)。本教程描述其关键部分。 ## 窗体 将一个[**CefBrowser**](/official/Reference/CEF/CefBrowser/)控件放置到窗体上并重命名为 `WebView`。在其周围添加一个名为 `AddressBar` 的 `TextBox` 以及六个 `CommandButton`——`btnBack`、`btnForward`、`btnRefresh`、`btnZoomIn`、`btnZoomOut`、`btnPDF`、`btnDevTools`。 ## 导航 最基本的导航方法——[**Navigate**](/official/Reference/CEF/CefBrowser/#navigate)、[**GoBack**](/official/Reference/CEF/CefBrowser/#goback)、[**GoForward**](/official/Reference/CEF/CefBrowser/#goforward)、[**Reload**](/official/Reference/CEF/CefBrowser/#reload)——都是单行代码: ```vb Private Sub btnBack_Click() Handles btnBack.Click WebView.GoBack() End Sub Private Sub btnForward_Click() Handles btnForward.Click WebView.GoForward() End Sub Private Sub btnRefresh_Click() Handles btnRefresh.Click WebView.Reload() End Sub ``` 要使后退/前进按钮跟随实际的浏览历史状态,在每次导航后根据[**CanGoBack**](/official/Reference/CEF/CefBrowser/#cangoback)和[**CanGoForward**](/official/Reference/CEF/CefBrowser/#cangoforward)同步它们: ```vb Private Sub WebView_NavigationComplete( _ ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) _ Handles WebView.NavigationComplete btnBack.Enabled = WebView.CanGoBack btnForward.Enabled = WebView.CanGoForward End Sub ``` ::: info *IsSuccess*和*WebErrorStatus*是事件签名的一部分,但目前返回占位值(`True`和`0`)——使用[**DocumentURL**](/official/Reference/CEF/CefBrowser/#documenturl)确认浏览器实际到达的位置。 ::: ## 地址栏 在地址栏中按**Enter**触发导航。反向——保持可见URL与页面同步——是[**SourceChanged**](/official/Reference/CEF/CefBrowser/#sourcechanged)事件,每当[**DocumentURL**](/official/Reference/CEF/CefBrowser/#documenturl)更改时触发(包括同文档的 `history.pushState` 更新): ```vb Private Sub AddressBar_KeyDown(KeyCode As Integer, Shift As Integer) _ Handles AddressBar.KeyDown If KeyCode = vbKeyReturn Then WebView.Navigate AddressBar.Text End Sub Private Sub WebView_SourceChanged(ByVal IsNewDocument As Boolean) _ Handles WebView.SourceChanged AddressBar.Text = WebView.DocumentURL End Sub ``` [**Navigate**](/official/Reference/CEF/CefBrowser/#navigate)需要带方案的完整URI——`http://`、`https://`、`file://`、……与[**WebView2**](/official/Reference/WebView2/WebView2/#navigate)不同,方案缺失时不会自动添加 `https://` 前缀。 ## 缩放 [**ZoomFactor**](/official/Reference/CEF/CefBrowser/#zoomfactor)是一个**Double**——`1.0`为100%,`1.5`为150%。在浏览器达到[**Ready**](/official/Reference/CEF/CefBrowser/#ready)之前,该值读取为 `0`,因此乘以当前值的算术运算会悄悄从零开始,除非你先钳制: ```vb Private Sub btnZoomIn_Click() Handles btnZoomIn.Click If WebView.ZoomFactor = 0 Then WebView.ZoomFactor = 1 On Error Resume Next WebView.ZoomFactor *= 1.1 End Sub Private Sub btnZoomOut_Click() Handles btnZoomOut.Click If WebView.ZoomFactor = 0 Then WebView.ZoomFactor = 1 On Error Resume Next WebView.ZoomFactor /= 1.1 End Sub ``` `On Error Resume Next` 捕获在[**Ready**](/official/Reference/CEF/CefBrowser/#ready)触发前点击按钮时引发的"控件未就绪"错误。 ## PDF导出 [**PrintToPdf**](/official/Reference/CEF/CefBrowser/#printtopdf)异步将当前文档保存到磁盘——结果以[**PrintToPdfCompleted**](/official/Reference/CEF/CefBrowser/#printtopdfcompleted)或[**PrintToPdfFailed**](/official/Reference/CEF/CefBrowser/#printtopdffailed)事件到达: ```vb Private Sub btnPDF_Click() Handles btnPDF.Click Dim outputPath As String = _ Environ$("USERPROFILE") & "\Documents\page.pdf" WebView.PrintToPdf(outputPath) End Sub Private Sub WebView_PrintToPdfCompleted() Handles WebView.PrintToPdfCompleted MsgBox "PDF saved.", vbInformation End Sub ``` *outputPath*后面的可选参数——[**cefPrintOrientation**](/official/Reference/CEF/Enumerations/cefPrintOrientation)、以微米为单位的页面大小、边距、页眉/页脚切换——允许宿主覆盖Chromium的默认值。完整签名参见[**PrintToPdf**参考](/official/Reference/CEF/CefBrowser/#printtopdf)。 ## DevTools Chromium DevTools窗口在其自己的顶层窗口中打开: ```vb Private Sub btnDevTools_Click() Handles btnDevTools.Click WebView.OpenDevToolsWindow() End Sub ``` CEF包目前未暴露**WebView2**的**OpenTaskManagerWindow**等效功能——参见参考的[WebView2对等](/official/Reference/CEF/#webview2-parity)部分了解当前差距列表。 ## 窗体标题同步 要使宿主窗口的标题跟踪页面的 ``,监听[**DocumentTitleChanged**](/official/Reference/CEF/CefBrowser/#documenttitlechanged)并读取[**DocumentTitle**](/official/Reference/CEF/CefBrowser/#documenttitle): ```vb Private Sub WebView_DocumentTitleChanged() Handles WebView.DocumentTitleChanged Me.Caption = WebView.DocumentTitle End Sub ``` ## 下一步 * [托管本地Web资源](/official/Tutorials/CEF/Hosting-local-web-assets) —— 无需HTTP服务器即可从文件夹提供HTML/JS/CSS。 * [JavaScript互操作](/official/Tutorials/CEF/JavaScript-interop) —— 在BASIC和页面之间传递值和方法调用。 * [重入性](/official/Tutorials/CEF/Re-entrancy) —— 使用[**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun)前需要了解的一件事。 * [CefBrowser参考](/official/Reference/CEF/CefBrowser/) —— 每个属性、方法和事件。 --- --- url: /zh/official/Tutorials/WebView2/Building-a-browser-shell.md --- # 构建浏览器外壳 一个简短的工作教程:将[**WebView2**](/official/Reference/WebView2/WebView2/)控件变成一个可工作的浏览器,带有地址栏、后退/前进/刷新按钮、缩放以及一些辅助工具(DevTools、任务管理器、PDF导出)。 完整项目以*示例0——WebView2示例*的形式在新项目对话框中提供(窗体*示例1*)。本教程描述其关键部分。 ## 窗体 将一个[**WebView2**](/official/Reference/WebView2/WebView2/)控件放置到窗体上并重命名为 `WebView`。在其周围添加一个名为 `AddressBar` 的 `TextBox` 以及七个 `CommandButton`——`btnBack`、`btnForward`、`btnRefresh`、`btnZoomIn`、`btnZoomOut`、`btnPDF`、`btnDevTools`、`btnTaskMgr`。 ## 导航 最基本的导航方法——[**Navigate**](/official/Reference/WebView2/WebView2/#navigate)、[**GoBack**](/official/Reference/WebView2/WebView2/#goback)、[**GoForward**](/official/Reference/WebView2/WebView2/#goforward)、[**Reload**](/official/Reference/WebView2/WebView2/#reload)——都是单行代码: ```vb Private Sub btnBack_Click() Handles btnBack.Click WebView.GoBack() End Sub Private Sub btnForward_Click() Handles btnForward.Click WebView.GoForward() End Sub Private Sub btnRefresh_Click() Handles btnRefresh.Click WebView.Reload() End Sub ``` 要使后退/前进按钮跟随实际的浏览历史状态,在每次导航后根据[**CanGoBack**](/official/Reference/WebView2/WebView2/#cangoback)和[**CanGoForward**](/official/Reference/WebView2/WebView2/#cangoforward)同步它们: ```vb Private Sub WebView_NavigationComplete( _ ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) _ Handles WebView.NavigationComplete btnBack.Enabled = WebView.CanGoBack btnForward.Enabled = WebView.CanGoForward End Sub ``` ## 地址栏 在地址栏中按**Enter**触发导航。反向——保持可见URL与页面同步——是[**SourceChanged**](/official/Reference/WebView2/WebView2/#sourcechanged)事件,每当[**DocumentURL**](/official/Reference/WebView2/WebView2/#documenturl)更改时触发(包括同文档的 `history.pushState` 更新): ```vb Private Sub AddressBar_KeyDown(KeyCode As Integer, Shift As Integer) _ Handles AddressBar.KeyDown If KeyCode = vbKeyReturn Then WebView.Navigate AddressBar.Text End Sub Private Sub WebView_SourceChanged(ByVal IsNewDocument As Boolean) _ Handles WebView.SourceChanged AddressBar.Text = WebView.DocumentURL End Sub ``` [**Navigate**](/official/Reference/WebView2/WebView2/#navigate)接受任何URI字符串;如果缺少方案前缀,会自动添加 `https://`。 ## 缩放 [**ZoomFactor**](/official/Reference/WebView2/WebView2/#zoomfactor)是一个**Double**——`1.0`为100%,`1.5`为150%。设计时默认值为 `0`,表示"不覆盖Edge的默认值1.0"——因此从冷启动乘以 `1.1` 得到 `0`,而不是 `1.1`。缩放前先钳制到 `1`: ```vb Private Sub btnZoomIn_Click() Handles btnZoomIn.Click If WebView.ZoomFactor = 0 Then WebView.ZoomFactor = 1 WebView.ZoomFactor *= 1.1 End Sub Private Sub btnZoomOut_Click() Handles btnZoomOut.Click If WebView.ZoomFactor = 0 Then WebView.ZoomFactor = 1 WebView.ZoomFactor /= 1.1 End Sub ``` ## PDF导出 [**PrintToPdf**](/official/Reference/WebView2/WebView2/#printtopdf)异步将当前文档保存到磁盘——结果以[**PrintToPdfCompleted**](/official/Reference/WebView2/WebView2/#printtopdfcompleted)或[**PrintToPdfFailed**](/official/Reference/WebView2/WebView2/#printtopdffailed)事件到达: ```vb Private Sub btnPDF_Click() Handles btnPDF.Click Dim outputPath As String = _ Environ$("USERPROFILE") & "\Documents\page.pdf" WebView.PrintToPdf(outputPath) End Sub Private Sub WebView_PrintToPdfCompleted() Handles WebView.PrintToPdfCompleted MsgBox "PDF saved.", vbInformation End Sub ``` ## DevTools和任务管理器 两个窗口都是一次性调用——调用匹配方法,Edge在其自己的进程中打开窗口: ```vb Private Sub btnDevTools_Click() Handles btnDevTools.Click WebView.OpenDevToolsWindow() End Sub Private Sub btnTaskMgr_Click() Handles btnTaskMgr.Click WebView.OpenTaskManagerWindow() End Sub ``` [**OpenDevToolsWindow**](/official/Reference/WebView2/WebView2/#opendevtoolswindow)即使在[**AreDevToolsEnabled**](/official/Reference/WebView2/WebView2/#aredevtoolsenabled)为**False**时也能工作(该设置仅禁用用户发起的路径——键盘快捷键和上下文菜单)。 ## 窗体标题同步 要使宿主窗口的标题跟踪页面的 `<title>`,监听[**DocumentTitleChanged**](/official/Reference/WebView2/WebView2/#documenttitlechanged)并读取[**DocumentTitle**](/official/Reference/WebView2/WebView2/#documenttitle): ```vb Private Sub WebView_DocumentTitleChanged() Handles WebView.DocumentTitleChanged Me.Caption = WebView.DocumentTitle End Sub ``` ## 下一步 * [托管本地Web资源](/official/Tutorials/WebView2/Hosting-local-web-assets) —— 无需HTTP服务器即可从文件夹提供HTML/JS/CSS。 * [JavaScript互操作](/official/Tutorials/WebView2/JavaScript-interop) —— 在BASIC和页面之间传递值和方法调用。 * [WebView2参考](/official/Reference/WebView2/WebView2/) —— 每个属性、方法和事件。 --- --- url: /zh/official/Documentation/Building.md --- # 构建与部署 编辑文档的日常工作流程:需求、构建、本地服务、链接检查、Mermaid 图表、截图以及部署到 [docs.twinbasic.com](https://docs.twinbasic.com)。面向内容贡献者 --- 如果你正在修改构建管线本身,请参阅 [tbdocs 内部机制](/official/Documentation/Builder)。 ## 开发环境 文档由 `tbdocs` 渲染为 HTML,这是一个自定义的 Node.js 静态站点生成器,位于 [`builder/`](https://github.com/twinbasic/documentation/tree/main/builder) 下。下面的日常命令是封装该生成器的 Windows 批处理文件;其 POSIX 等效版本列在旁边。 1. 确保满足下面的[需求](#requirements)。 2. 如果你计划进行任何更改,请将 [https://github.com/twinbasic/documentation][docs-repo] 分叉到你自己的 GitHub 账户,或为了方便起见分叉。如果你只想在本地构建文档而不贡献更改,则跳过此步。 3. 克隆你的分叉或[文档仓库本身][docs-repo]。 ### 需求 * **Node.js 22+** 用于 `tbdocs` 本身。站点离线构建,无需 Ruby 工具链。 * **`npm ci`** 在仓库根目录安装所有内容:静态站点生成器的依赖、PDF 渲染器的依赖和 `puppeteer`(由 PDF 渲染器和 mermaid 的 `.mmd` → `.svg` 重新生成器共用)。仓库根目录的一个 `package.json` 承载整个依赖集。`build.bat` / `serve.bat` 封装脚本假定安装已经运行。 * **Chromium** 在需要重新生成 `.mmd` 图表和渲染 PDF 书籍时是必需的。通过 `npx puppeteer browsers install chrome --install-deps` 一次性下载。构建期间缺少 Chromium 会降级为警告并复用磁盘上的 `.svg`,因此跳过安装步骤的首次设置仍然可以构建(只是没有图表更新)。 ## 构建 将文档从 `.md` 文件渲染到 `_site/`(在线)、`_site-offline/`(离线镜像)和 `_site-pdf/`(稀疏 PDF 源)文件夹: ``` build.bat ``` 或直接运行: ``` node builder\tbdocs.mjs --src docs ``` 单次 `tbdocs` 运行生成全部三棵树。`_config.yml` 中的 `also_build_offline` 和 `also_build_pdf` 键切换同级输出;`--no-offline` 和 `--no-pdf` 标志在命令行上做同样的事情,如果你只需要 `_site/`。 `tbdocs` CLI 标志的完整集合 --- 每个标志、其作用、何时使用 --- 位于[工具与脚本](/official/Documentation/Tools#tbdocs)页面。 ## 构建与本地服务 最简单的本地预览是运行 `build.bat` 然后在任意浏览器中打开渲染的文件。要使用本地主机服务器: ``` serve.bat ``` 这运行 `tbdocs --serve`:初始构建后,HTTP 服务器绑定到端口 4000(传入 `--port <N>` 使用不同端口),递归源树监视器在每次文件更改时触发防抖重建,任何打开该页面的浏览器标签页在每次成功重建后通过 SSE 自动重新加载。只记录失败(4xx、5xx、服务器异常)--- 成功的请求是无声的。Ctrl+C 干净退出。 Serve 写入 `docs/_serve/`,与 `build.bat` 的 `_site/` 系列完全分离。这种分离意味着一次性 `build.bat` 调用(例如,为 `book.bat` 刷新 `_site-pdf/`,或重新检查 `_site-offline/` 的链接完整性)永远不会触及实时预览正在服务的树,预览始终显示 serve 上次重建的内容。 ## 检查链接完整性 在检查链接完整性之前,必须先构建文档: ``` check.bat ``` 这运行两轮 `scripts/check_links.mjs`:一轮针对 `_site/`(在线树),一轮针对 `_site-offline/`(`file://` 可浏览的镜像),使用 `--forbid 'https://docs.twinbasic.com'` 同时标记任何残留的在线站点链接 --- 离线镜像不应导航回在线文档站点。两项检查还断言 HTML 格式良好性、重复 `id` 检测、锚点解析、可访问性提示以及(对于在线树)站点地图和搜索索引完整性。相同的两项检查在 CI 中每个拉取请求和每次推送到 `staging` 时运行。 干净的 `check.bat` 运行是"准备好提交"的标准。 ## Mermaid 图表 Mermaid 图表以 `.mmd` 源文件形式存放在 `docs/assets/images/mmd/` 下,并在 markdown 中以 `.svg` 引用: ``` ![Diagram](/assets/images/mmd/<hash>.svg) ``` `tbdocs` 在 SVG 缺失或比其源文件更旧时,从 `.mmd` 同级文件重新生成每个 `.svg` --- 编辑 `.mmd` 一个字符后下次构建即重新生成 SVG。两个文件都属于 git;`.mmd` 是规范源,`.svg` 是浏览器实际加载的构建产物。 渲染器直接驱动 `puppeteer` + `mermaid` 包(两者都是仓库根 `package.json` 中的常规依赖)。一个无头 Chromium 覆盖整个批次 --- 以前项目通过 shell 调用 `@mermaid-js/mermaid-cli`,这会为每个图表分叉一个新的 node + Chrome 进程并附带自己捆绑的 puppeteer-core。直接路径使依赖树更小,消除了每文件进程启动开销,并使用与 `render-book.mjs` 相同的 Chromium 缓存。两种失败模式有不同的处理: * **设置失败**(无 puppeteer、无 Chrome、无 mermaid)发出一行警告,保留磁盘上现有的 SVG,并让构建以退出码 0 退出 --- 没有 `npm install` 的新签出或没有 Chromium 的沙箱不会中断无关工作。 * **内容失败**(损坏的 `.mmd` 语法、渲染异常)逐字发出解析器错误,保留该图表之前的 SVG,继续渲染批次的其余部分,并设置 `process.exitCode = 1` 以便 CI 捕获损坏的图表。 在 serve 模式下,监视器忽略对 `assets/images/mmd/*.svg` 的写入。`.mmd` 是事实来源;`.svg` 是 mermaid 回写到 `srcRoot` 下的构建产物。没有此过滤器,每次 `.mmd` 编辑会触发两次重建(一次在编辑时,一次在 SVG 写入时),浏览器为一次用户更改重载两次。 ## 部署到 docs.twinbasic.com 1. 将你的更改推送到你的 GitHub 分叉的[文档仓库][docs-repo]。 2. [在文档仓库中开一个新的拉取请求][docs-pr]。 3. 点击**跨分叉比较**。 4. 选择你的仓库和要合并的分支。 ![img](/assets/compare-changes.DFURGOIT.png) 5. 创建拉取请求。 ![img](/assets/create-pull-request.Cs58mWhB.png) 维护者会将拉取请求合并到文档仓库。你可能希望在 [#docs][hash-docs] 频道上提及待处理的请求,尽管 [#github-docs][hash-github-docs] 频道提供拉取请求的自动通知。通常,维护者会通过 Discord 收到新拉取请求的通知,并会合并它或评论要求修改。 **以下步骤由维护者完成。** 6. 审查,然后合并拉取请求或评论要求修改。 ![img](/assets/merge-pull-request.-xevR28n.png) ![img](/assets/confirm-merge.B-aESd2K.png) 7. 选择 **Build & deploy docs** 操作。 ![img](/assets/choose-workflow.kFwp_r80.png){width="75%"} 8. 如果需要发布快照,手动运行构建和部署工作流。(推送到 `staging` 会自动部署到 Pages;只有手动运行会额外创建一个 GitHub Release,附带离线可浏览站点副本的 zip 和 PDF 书籍附件。) ![img](/assets/run-workflow.BgsgOvro.png){width="50%"} ## 编辑截图 编辑截图的一种方式是使用集成矢量/像素程序,如 [Affinity][af]1。可能的工作流程: 1. PrtSc 截取屏幕截图。 2. 在 Affinity 中,Ctrl-Alt-Shift-N(文件,从剪贴板新建)将整个截图导入程序。 3. 使用矢量裁剪工具(来自 Vector 工作室)将截图裁剪到相关部分。 ![img](/assets/af-vector-studio.Ck0bWZQb.png) ![img](/assets/af-vector-crop-tool.DXF8qLLE.png) 4. 选择裁剪后的图像并用 Ctrl-C 复制到剪贴板。 5. 再次从剪贴板创建新文件,打开仅包含裁剪截图的文档 Ctrl-Alt-Shift-N(文件,从剪贴板新建)。 6. 关闭在第 2 步中打开的文件。 7. 根据需要添加箭头和标签。这些可以从本仓库中其他 `.af` 文件复制粘贴。 8. 通过 Ctrl-Alt-Shift-W(文件,导出,导出...)导出为 PNG。 ::: info 约定是将 `.af`("源")文件放在 `_Images` 文件夹中,导出的 `.png` 文件放在 `Images` 文件夹中。只有后者发布到网站。前者作为源保留,以便于编辑和更新。 ::: *** 1 Affinity 是一个免费套件,集成了矢量编辑器、位图编辑器和排版布局编辑器。需要 Canva 账户才能下载;账户是免费的。 [af]: https://www.affinity.studio/download [docs-pr]: https://github.com/twinbasic/documentation/compare [docs-repo]: https://github.com/twinbasic/documentation [hash-docs]: https://discord.com/channels/927638153546829845/1021635324809596988 [hash-github-docs]: https://discord.com/channels/927638153546829845/1111554338221989908 > AI生成 --- --- url: /zh/official/Tutorials/CustomControls/Notes-about-the-form-designer.md --- # 关于窗体设计器的说明 对于窗体设计器中控件的绘制,CustomControl实例会被实例化,然后在绘制完成后立即释放。设计模式标志暴露在框架的[`SerializeInfo.RuntimeUISrzIsDesignMode`](/official/Reference/CustomControls/Framework/SerializeInfo#runtimeuisrzisdesignmode)上——希望仅在设计器内渲染占位符的控件(如[`WaynesTimer`](/official/Reference/CustomControls/WaynesTimer)绘制其🕑字形的方式)在[`Initialize`](/official/Reference/CustomControls/Framework/ICustomControl#initialize)期间检查此标志。 ## 另见 * [CustomControls包参考](/official/Reference/CustomControls/) —— 框架和内置 `Waynes…` 控件的概述 --- --- url: /zh/official/Documentation/Pipeline-Stages.md --- # 管线阶段 `tbdocs`构建管线中每个阶段的完整接口参考。每节覆盖一个模块:其入口点签名、从前置阶段读取的数据、为后续阶段写入的数据,以及每个导出符号。 设计理念和叙述性描述见[tbdocs构建器](/official/Documentation/Builder)。要添加新阶段或markdown-it插件,请参阅[扩展构建器](/official/Documentation/Extending)。 ## 数据模型 管线通过每个阶段传递两个可变数据结构。 ### 页面对象(`pages[]`) `discover`为每个具有可解析YAML frontmatter的`.md`或`.html`源文件创建一个页面对象。后续阶段添加新字段;没有阶段会删除或重命名早期阶段设置的字段。后续阶段可以安全地假设早期阶段的所有字段都已存在。 | 字段 | 添加者 | 类型 | 描述 | |---|---|---|---| | `srcPath` | 阶段1 | `string` | 源文件的绝对文件系统路径。 | | `srcRel` | 阶段1 | `string` | 相对于`srcRoot`的POSIX风格路径,例如`Reference/Core/Dim.md`。 | | `ext` | 阶段1 | `string` | 小写文件扩展名:`.md`或`.html`。 | | `frontmatter` | 阶段1 | `object` | 已解析的YAML frontmatter。所有frontmatter键可在此访问(例如`frontmatter.title`、`frontmatter.parent`、`frontmatter.nav_order`)。 | | `rawContent` | 阶段1 | `string` | frontmatter块之后的正文文本。 | | `permalink` | 阶段1 | `string` | URL路径,取自`frontmatter.permalink`或从`srcRel`派生。 | | `destPath` | 阶段1 | `string` | 输出根目录中的文件系统路径,例如`Reference/Core/Dim.html`。 | | `layoutDefault` | 阶段1 | `boolean` | 当frontmatter没有显式`layout:`键时为`true`。 | | `imageScope` | 阶段1 | `boolean` | 当`srcRel`包含`Images/`段时为`true`。阶段3使用此字段验证图片路径。 | | `navPath` | 阶段2(nav) | `string` | 斜杠连接的导航链:`grand_parent / parent / title`。仅在有非空`title`的页面上设置。 | | `navLevels` | 阶段2(nav) | `object` | 侧边栏树中的位置索引。阶段4使用此字段生成每页激活CSS。 | | `breadcrumbs` | 阶段2(nav) | `Page[]` | 从根到当前页面的祖先链,最近者优先。 | | `children` | 阶段2(nav) | `Page[]` | 导航顺序中的直接子页面。 | | `seoTitle` | 阶段2(seo) | `string` | HTML剥离、空白折叠的页面标题,用于`<title>`和`og:title`。 | | `seoFullTitle` | 阶段2(seo) | `string` | 非首页为`"<seoTitle> -- <siteTitle>"`;首页等于`seoTitle`。 | | `seoCanonical` | 阶段2(seo) | `string` | 绝对规范URL(scheme + host + baseurl + permalink)。 | | `seoIsHome` | 阶段2(seo) | `boolean` | 当页面的permalink是已知主页URL时为`true`(例如`/`)。 | | `renderedContent` | 阶段3 | `string` | markdown-it生成的HTML正文。尚未包裹站点布局。 | | `html` | 阶段4 | `string` | 完整的HTML文档,可直接写入磁盘。`layout: book-combined`页面无此字段,由阶段8管理。 | ### 站点对象(`site`) 在阶段2末尾构建并原样传递给每个后续阶段。 | 字段 | 类型 | 描述 | |---|---|---| | `config` | `object` | 已解析的`_config.yml`,已应用CLI覆盖(`--baseurl`、`--url`)。 | | `navTree` | `object` | 由`nav.mjs`生成的顶级导航层次结构。 | | `seoSiteTitle` | `string` | 从`config.title`渲染的站点标题。 | | `seoLogoUrl` | `string` | 站点logo的绝对URL。 | | `buildInfo` | `object` | 来自git的`{ commit: string, commitDate: string }`。两者在git仓库之外均回退到`"unknown"`。 | | `bookData` | `object\|null` | 已解析的`_book.yml`,章节选择器已解析为`Page`引用。文件缺失时为`null`。参见[Book配置](/official/Documentation/Book-Configuration)。 | | `data` | `object` | `_book.yml`加载为`{ book: … }`,缺失时为`{}`。 | | `markdown` | `MarkdownIt` | 共享markdown-it实例,在阶段2设置期间构建一次,由阶段2的SEO处理和阶段3的渲染处理复用。 | ### 静态文件(`staticFiles[]`) 同样由阶段1生成。每个不是页面的文件——图片、字体、预构建的CSS/JS,以及任何没有frontmatter的`.md`/`.html`文件——都成为静态文件对象。此数组在阶段1之后不再增长。 | 字段 | 类型 | 描述 | |---|---|---| | `srcPath` | `string` | 绝对源路径。 | | `srcRel` | `string` | 相对于`srcRoot`的POSIX路径。 | | `destRel` | `string` | 输出根目录内的相对路径(当前与`srcRel`相同)。 | | `size` | `number` | 发现时的文件大小(字节)。 | *** ## 预阶段:`mermaid.mjs` 在阶段1之前运行,以便任何新生成的`.svg`文件出现在阶段1的静态文件清单中。 **入口点** ```js regenerateMermaid(srcRoot: string): Promise<{ processed: number, regenerated: number, failed: number, setupSkipped?: true, }> ``` 枚举`<srcRoot>/assets/images/mmd/*.mmd`,比较修改时间与同路径下的`.svg`兄弟文件,并直接驱动`puppeteer` + `mermaid`包将每个过期的`.mmd`渲染为`.svg`。一次浏览器启动覆盖整个批次。当没有`.mmd`文件过期时,调用为空操作。 渲染在页面内`page.evaluate`中运行,通过请求拦截源(`https://tbdocs-mermaid.invalid`)动态导入`mermaid.esm.mjs`。拦截将请求映射回`node_modules/mermaid/dist/`;需要源技巧是因为Chromium在`file://`上加载时阻止了`mermaid.esm.mjs`触发的`import()`链。IIFE包(`mermaid.min.js`)可以避开该约束,但会内联+压缩经过补丁的dagre块(参见[Mermaid Dagre补丁](/official/Documentation/Fixes-Dagre)),因此带拦截的ESM路径是保持补丁生效的唯一方式。 两种失败模式区分: * **设置失败**(`puppeteer` / `mermaid`未安装,Chrome运行时缺失)返回`{ ..., setupSkipped: true }`,警告一次,并保留磁盘上的SVG。编排器**不会**翻转退出码。 * **每图渲染失败**(损坏的`.mmd`,mermaid渲染抛出异常)不会中止批次——循环继续以便每个损坏的图在单次运行中暴露,每个失败图保留先前的SVG,编排器根据`failed`计数翻转`process.exitCode = 1`。 **读取:** `<srcRoot>/assets/images/mmd/*.mmd`及其`.svg`兄弟文件;`node_modules/mermaid/dist/**`(通过`import.meta.url`根的`createRequire`解析)。 **写入:** 过期`.mmd`源旁边的`.svg`文件。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `regenerateMermaid` | `(srcRoot) → Promise<{ processed, regenerated, failed, setupSkipped? }>` | 主入口点。 | *** ## 阶段1:`discover.mjs` 遍历源树并生成后续每个阶段消费的`pages`和`staticFiles`数组。 **入口点** ```js discover(srcRoot: string, ignore: string[]): Promise<{ pages: Page[], staticFiles: StaticFile[] }> ``` 对`srcRoot`运行单次`fast-glob`调用,使用从`_config.yml`读取并由编排器传入的`exclude:`列表。对于每个`.md`或`.html`文件,尝试解析YAML frontmatter。具有可解析frontmatter的文件成为页面对象;其他所有内容成为静态文件对象。页面按基本名排序(镜像Jekyll的读取器);静态文件按相对路径排序。 **读取:** `srcRoot`下的源文件。 **写入(页面字段):** `srcPath`、`srcRel`、`ext`、`frontmatter`、`rawContent`、`permalink`、`destPath`、`layoutDefault`、`imageScope`。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `discover` | `(srcRoot, ignore) → Promise<{ pages, staticFiles }>` | 主入口点。 | *** ## 阶段2:计算 阶段2按顺序运行多个模块(`captureBuildInfo`并行运行)。它们共同构建`site`对象并向每个页面添加导航、SEO和书籍章节数据。 ### `nav.mjs` 从每个页面的`title`、`parent`和`grand_parent` frontmatter键计算导航树。阶段2中唯一可能中止构建的子步骤——它在孤立或模糊的`parent:`声明上抛出异常。 **入口点** ```js computeNav(pages: Page[], config: object): { navTree: object } ``` 按顺序运行六个子步骤:导航路径、导航完整性检查、共享状态构建(`byTitle` / `byParentTitle`映射、`topLevel`列表、`orderedChildren`映射)、导航树、导航级别、面包屑、子页面。返回站点对象的导航树;直接在每个页面对象上写入导航相关字段。 **读取:** `frontmatter.title`、`frontmatter.parent`、`frontmatter.grand_parent`、`frontmatter.nav_order`、`frontmatter.nav_exclude`、`page.permalink`、`config.nav_sort`、`config.case_insensitive`。 **写入(页面字段):** `navPath`、`navLevels`、`breadcrumbs`、`children`。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `computeNav` | `(pages, config) → { navTree }` | 主入口点。 | *** ### `seo.mjs` 为每个页面和整个站点预计算SEO元数据。 **入口点** ```js precomputeSeo(pages: Page[], config: object, markdown: MarkdownIt): { seoSiteTitle: string, seoLogoUrl: string } ``` 对于每个页面,将标题通过`renderTitle`(markdown-it渲染 → 剥离HTML → 折叠空白 → 转义HTML实体)并写入四个SEO字段到页面对象。返回`seoSiteTitle`和`seoLogoUrl`给站点对象。要求共享的markdown-it实例已通过`createMarkdownIt`构建。 **读取:** `frontmatter.title`、`frontmatter.permalink`、`page.permalink`、`config.title`、`config.url`、`config.baseurl`、`config.logo`、`site.markdown`。 **写入(页面字段):** `seoTitle`、`seoFullTitle`、`seoCanonical`、`seoIsHome`。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `precomputeSeo` | `(pages, config, markdown) → { seoSiteTitle, seoLogoUrl }` | 主入口点。 | | `renderTitle` | `(text: string, markdown: MarkdownIt) → string` | 将一个标题字符串通过完整的markdown-it + 剥离HTML管线。 | | `stripHtml` | `(s: string) → string` | 从字符串中剥离所有HTML标签。为`search.mjs`重新导出。 | | `absoluteUrl` | `(input: string, config: object) → string` | 使用`config.url`和`config.baseurl`将根相对路径解析为绝对URL。为`sitemap.mjs`和`redirects.mjs`重新导出。 | | `relativeUrl` | `(input: string, config: object) → string` | 将`config.baseurl`前缀添加到根相对路径。 | *** ### `book.mjs` --- 阶段2部分 将`_book.yml`章节选择器解析为具体的`Page`数组,使阶段8无需再进行页面查找。 **阶段2入口点** ```js resolveBookChapters(bookData: object | null, pages: Page[]): void ``` 遍历`bookData.front_matter`和`bookData.parts`(及其`chapters`子数组)中的每个条目,将每个选择器解析为`Page[]`,并将结果存储为`entry._chapters`。预解析`landing_page`和`foreword_page` URL为其`Page`引用。就地操作;不返回任何值。选择器模式参见[Book配置](/official/Documentation/Book-Configuration)。 **读取:** `bookData`(由`data.mjs`加载)、`page.permalink`、`page.navPath`。 **写入:** 每个`bookData`条目上的`entry._chapters`(非页面字段)。在声明了`landing_page:` / `foreword_page:`的条目上设置`_landing`和`_foreword`引用。 阶段8的`assembleBook`位于同一模块中;参见下面的[阶段8](#phase-8-pdfmjs--bookmjs)。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `loadBookData` | `(srcRoot: string) → Promise<object\|null>` | 向后兼容包装器,直接加载`_book.yml`。优先使用`data.mjs`。 | | `resolveBookChapters` | `(bookData, pages) → void` | 阶段2入口点。 | | `sortByNavOrder` | `(input: Page[]) → Page[]` | 对页面数组排序:索引页(URL以`/`结尾)优先,然后按`nav_order`升序并以标题作为决胜,然后按标题字母顺序。 | | `chapterAnchorFromUrl` | `(url: string, fallbackTitle?: string) → string` | 将页面URL转换为用于书内交叉引用的`ch-…`锚点slug。 | | `bookChapterTransform` | `(body: string, baseurl: string, headingShiftN: number, chapterAnchor: string) → string` | 对渲染后的HTML字符串应用所有每章节正文转换:baseurl前缀剥离、`<details>` / `<summary>`解包、pagedjs分页的空白包裹、标题级别偏移和章节锚点前缀添加。 | | `assembleBook` | `(site: object, pages: Page[]) → string` | 阶段8入口点。返回已组装的`book.html`字符串。 | | `rewriteBookHrefs` | `(html: string, site: object, pages: Page[]) → string` | 将书内绝对`href="/X"`引用重写为页内`href="#ch-X"`片段锚点。 | *** ### `build-info.mjs` 为PDF标题页捕获git提交哈希和日期。 **入口点** ```js captureBuildInfo(): Promise<{ commit: string, commitDate: string }> ``` 发起两个并行的`git` shell调用(`rev-parse --short HEAD`和`log -1 --format=%cs`)。在任何失败时回退到`"unknown"`,使构建在git仓库之外永不中止。编排器在阶段1之后立即启动此promise,使shell调用与CPU密集的导航计算重叠。 **读取:** 本地git仓库状态。 **写入:** 不向页面写入(结果直接返回给编排器)。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `captureBuildInfo` | `() → Promise<{ commit, commitDate }>` | 主入口点。 | *** ### `data.mjs` 从`srcRoot`加载`_book.yml`。 **入口点** ```js loadData(srcRoot: string): Promise<object> ``` 返回`{ book: <parsed YAML> }`,文件不存在时返回`{}`。编排器将结果存储在`site.data`,并将`site.data.book`暴露为`site.bookData`。 **读取:** `<srcRoot>/_book.yml`。 **写入:** 不向页面写入(结果直接返回)。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `loadData` | `(srcRoot) → Promise<object>` | 主入口点。 | *** ### 阶段2设置 --- 共享markdown-it实例 在阶段2完成之前,编排器构建共享的markdown-it实例,阶段2的SEO处理和阶段3的渲染处理都复用此实例。按顺序调用`render.mjs`中的三个函数: ```js const highlighter = await initHighlighter(); const linkTables = buildLinkTables(pages); const markdown = createMarkdownIt({ highlighter, linkTables, baseurl, staticFiles }); ``` 这些函数的文档在下面的[阶段3](#phase-3-rendermjs)中,因为它们定义在`render.mjs`中。这里在阶段2期间调用它们仅为了让SEO处理能共享相同配置的管线。 *** ## 阶段3:`render.mjs` 通过markdown-it将每个页面的`rawContent`渲染为HTML。 **入口点** ```js renderPhase(pages: Page[], site: object, staticFiles?: StaticFile[]): Promise<void> ``` 使用共享的`site.markdown`实例将每个页面的`rawContent`渲染为`page.renderedContent`。跳过`layout: book-combined`的页面(阶段8管理这些)。 **读取:** `page.rawContent`、`page.frontmatter`、`page.imageScope`、`site.markdown`、`site.config.baseurl`、`staticFiles`(用于图片路径验证)。 **写入(页面字段):** `renderedContent`。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `renderPhase` | `(pages, site, staticFiles?) → Promise<void>` | 主入口点。 | | `createMarkdownIt` | `({ highlighter, linkTables, baseurl, staticFiles }) → MarkdownIt` | 配置并返回一个已应用所有插件和渲染规则覆盖的markdown-it实例。如何添加插件参见[扩展构建器](/official/Documentation/Extending)。 | | `initHighlighter` | `() → Promise<{ render, themeCss }>` | 使用捆绑的twinBASIC语法初始化Shiki(内部委托给`highlight.mjs`)。`render(code, lang)`返回高亮HTML;`themeCss`是生成的`tb-highlight.css`字符串,未加载主题时为`null`。 | | `buildLinkTables` | `(pages: Page[]) → { byPath, byUrl, byRedirect }` | 构建以`srcRel`、`permalink`和`redirect_from`条目为键的查找表。供相对链接插件在渲染时将源内`[X](Y.md)`链接解析为绝对URL使用。 | | `kramdownSlug` | `(text: string) → string` | 将标题文本转换为kramdown兼容的锚点slug:小写、剥离非单词字符、用`-1`、`-2`等去重。 | | `rewriteAdmonitions` | `(src: string) → string` | 预渲染文本遍:将GFM `> [!NOTE]` / `[!IMPORTANT]` / `[!WARNING]` / `[!TIP]` / `[!CAUTION]`块转换为`markdown-alert markdown-alert-<type>`类结构。 | *** ## 阶段4:`template.mjs`和`compress.mjs` 阶段4将每个页面的`renderedContent`包裹在完整站点布局中,然后压缩生成的HTML。 ### `template.mjs` **入口点** ```js templatePhase(pages: Page[], site: object): Promise<void> ``` 预计算每次构建的静态侧边栏HTML一次,然后通过直接JS模板字面量拼接(无模板引擎)将每个页面的`renderedContent`包裹在just-the-docs布局中。在存储结果之前对每个页面的输出调用`compressHtml`。跳过`layout: book-combined`页面。 **读取:** 阶段1--3设置的所有页面字段、所有`site`字段。 **写入(页面字段):** `html`。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `templatePhase` | `(pages, site) -> Promise<void>` | 主入口点。 | | `navActivationCss` | `(page: Page) → string` | 从`page.navLevels`生成每页的`<style id="jtd-nav-activation">`块。阶段12的开发服务器在修补SSE重载脚本时调用此函数。 | | `injectAnchorHeadings` | `(html: string) → string` | 在每个有`id`属性的标题旁添加`<a class="anchor-heading">`。 | *** ### `compress.mjs` `templatePhase`内部调用`compressHtml`。该函数也为独立使用而导出。 **入口点** ```js compressHtml(html: string): string ``` 按`<pre>…</pre>`块分割,在非`<pre>`段中折叠ASCII空白为单个空格并修剪。使用显式字符类`[ \t\n\r\f\v]+`而非`\s`以保留` `缩进中的不间断空格。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `compressHtml` | `(html) → string` | 压缩`<pre>`块外的空白。 | *** ## 阶段5:`write.mjs` 将内存中的页面集和静态文件实体化到磁盘。 **入口点** ```js writePhase( pages: Page[], staticFiles: StaticFile[], { destRoot: string, dryRun?: boolean, generatedAssets?: { rel: string, content: string }[], baseurl?: string } ): Promise<{ pages: { written, skipped }, theme: { copied }, staticFiles: { copied } }> ``` 清除然后重新创建`destRoot`,然后并行运行三个操作:将每个`page.html`写入其`destPath`;将vendor的just-the-docs JS从`builder/vendor/just-the-docs/assets/`复制到`<destRoot>/assets/`;复制每个`staticFiles[]`条目(包括现在位于`docs/assets/`下的项目自有主题文件)。CSS `url()` baseurl重写运行在两个复制路径和生成的CSS资产上,使根绝对`url("/path")`引用在非空baseurl下正确解析。并行批次之后,`writeGeneratedAssets`顺序写入`generatedAssets[]`(SCSS编译的CSS和高亮主题CSS),使它们在相对路径冲突时获胜。跳过`page.html`为`undefined`的页面。 **读取:** `page.html`、`page.destPath`、`staticFile.srcPath`、`staticFile.destRel`。 **写入:** `<destRoot>/**`(在线树)。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `writePhase` | `(pages, staticFiles, opts) → Promise<stats>` | 主入口点。 | | `WRITE_LIMIT` | `64` | `runLimited`的并发上限。阶段6、7和8将此值传递给自己的`runLimited`调用以实现一致的I/O节流。 | | `isUnderProject` | `(destRoot: string) → boolean` | 仅当`destRoot`是项目根目录的后代时返回`true`。阶段7和8用作防止破坏性`--dest`值的守卫。 | | `mkdirRec` | `(dir: string) → Promise<void>` | 带有进行中去重缓存的递归`mkdir`。由阶段6、7和8共享。 | | `runLimited` | `<T>(items: T[], limit: number, fn: (T) → Promise<any>) → Promise<void>` | 以最多`limit`个并发操作运行每个项上的`fn`。 | | `writeFileMkdirp` | `(filePath: string, content: string\|Buffer) → Promise<void>` | 将`content`写入`filePath`,按需创建父目录。 | | `safeWrite` | `(dest: string, fn: () → Promise<any>) → Promise<void>` | 包装写入回调,在回调抛出时在错误消息中包含`dest`重新抛出。 | *** ## 阶段6:辅助模块 阶段6并发运行三个写入器。都不写入页面对象;都写入`<destRoot>/`。 ### `redirects.mjs` **入口点** ```js writeRedirects(pages: Page[], site: object, destRoot: string): Promise<{ written: number }> ``` 对于每个有`redirect_from:` frontmatter条目的页面,为每个源URL写入一个HTML存根。每个存根使用`<script>location=…</script>`、`<meta http-equiv="refresh">`、`<link rel="canonical">`、`<meta name="robots" content="noindex">`和可见的`<a>`回退,以支持无脚本/无meta-refresh环境。 **读取:** `page.frontmatter.redirect_from`、`page.permalink`、`site.config`。 **写入:** `<destRoot>/`下的重定向存根HTML文件。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `writeRedirects` | `(pages, site, destRoot) → Promise<{ written }>` | 主入口点。 | | `deriveRedirectStubs` | `(pages, site) -> Array<{ from, to, destPath }>` | 存根列表的纯推导,不写入磁盘。导出以便`offline.mjs`可以在不重新运行推导的情况下读取列表。 | *** ### `sitemap.mjs` **入口点** ```js writeSitemap(pages: Page[], site: object, destRoot: string): Promise<{ entries: number }> ``` 按jekyll-sitemap规则过滤页面(删除`sitemap: false`和`/404.html`),按绝对URL字母顺序排序以实现字节相同的重复运行,并输出`sitemap.xml`。同时写入带`Sitemap:`引用的`robots.txt`。 **读取:** `page.permalink`、`page.frontmatter.sitemap`、`site.config`。 **写入:** `<destRoot>/sitemap.xml`、`<destRoot>/robots.txt`。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `writeSitemap` | `(pages, site, destRoot) → Promise<{ entries }>` | 主入口点。 | | `deriveSitemapUrls` | `(pages, site) -> string[]` | 返回将出现在站点地图中的已排序绝对URL列表,不写入磁盘。 | | `extractSitemapUrls` | `(xml: string) → string[]` | 解析现有`sitemap.xml`字符串并提取其`<loc>`值。用于比较两次构建。 | | `renderRobotsTxt` | `(config: object) → string` | 生成`robots.txt`内容字符串。 | *** ### `search.mjs` **入口点** ```js writeSearchData(pages: Page[], site: object, destRoot: string): Promise<{ entries: number }> ``` 将每个有标题且非`search_exclude`的页面按标题分割,为每个标题限定段发出一个搜索索引条目,并写入Lunr兼容的JSON索引。 **读取:** `page.renderedContent`、`page.frontmatter.title`、`page.frontmatter.search_exclude`、`page.permalink`、`page.seoTitle`、`site.config`。 **写入:** `<destRoot>/assets/js/search-data.json`。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `writeSearchData` | `(pages, site, destRoot) → Promise<{ entries }>` | 主入口点。 | | `deriveSearchEntries` | `(pages, site) -> object[]` | 返回搜索索引条目数组,不写入磁盘。 | *** ## 阶段7:`offline.mjs` 将`<destRoot>/`镜像到`<destRoot>-offline/`,将每个URL重写为页面相对路径,使树可在`file://`下打开。 **入口点** ```js writeOffline( pages: Page[], staticFiles: StaticFile[], site: object, destRoot: string, { auxStats?: object, profileOffline?: boolean } ): Promise<{ html, css, redirects, statics, assets, excluded, unresolved }> ``` 读取阶段5和6写入的每个文件,将绝对URL重写为相对路径,并写入`<destRoot>-offline/`。通过AST(acorn)修补`just-the-docs.js`,用离线兼容的实现替换`navLink`和`initSearch`。写入`search-data.js`,将搜索索引包装为`window.SEARCH_DATA`赋值,使离线搜索在`file://`下工作(浏览器在那里阻止`XMLHttpRequest`)。`offline_exclude`模式同等应用于页面、静态文件和主题资产;`search-data.json`列在`offline_exclude`中,在离线树中不存在——只有`.js`包装器存在。 **读取:** `<destRoot>`(在线树)下的所有文件、`auxStats.redirects`(来自阶段6的重定向存根列表)。 **写入:** 所有文件到`<destRoot>-offline/`。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `writeOffline` | `(pages, staticFiles, site, destRoot, opts) → Promise<stats>` | 主入口点。 | | `buildOfflineState` | `(pages, staticFiles, site, destRoot, { stubs? }) → Promise<OfflineState>` | 构造所有离线推导函数使用的状态对象(站点路径集、解析缓存、每目录导航缓存)。 | | `deriveOfflinePage` | `(page: Page, state: OfflineState) → string` | 为离线使用重写一个页面的HTML。 | | `deriveOfflineRedirect` | `(stub, state: OfflineState) → string` | 为离线使用重写一个重定向存根的HTML。 | | `deriveOfflineCss` | `(cssIn: string, themeRel: string, state: OfflineState) → string` | 将CSS文件中的`url()`引用重写为页面相对路径。 | | `deriveOfflineJtdJs` | `(src: string) → string` | 通过AST修补`just-the-docs.js`:用离线兼容的实现替换`navLink`和`initSearch`。构建时的解析失败是重新提取产生不可读源的信号。 | | `deriveOfflineSearchDataJs` | `(jsonBytes: Buffer) → string` | 将`search-data.json`包装为`window.SEARCH_DATA = …`并进行压缩。 | *** ## 阶段8:`pdf.mjs` + `book.mjs` 生成`render-book.mjs`渲染为PDF的稀疏`<destRoot>-pdf/`树。 **入口点** ```js writePdf( pages: Page[], staticFiles: StaticFile[], site: object, destRoot: string, { tolerateMissingImages?: boolean } ): Promise<{ bookBytes, css, images, missing }> ``` 调用`book.mjs`的`assembleBook(site, pages)`生成`book.html`,复制`print.css`和`tb-highlight.css`,并收集`book.html`中引用的每张图片。默认将缺失图片报告为构建错误;`--tolerate-missing-images`将其降级为警告。 **读取:** `site.bookData`(章节选择器已由阶段2的`resolveBookChapters`解析)、所有页面的`page.html`、`staticFiles`。 **写入:** `<destRoot>-pdf/book.html`、`<destRoot>-pdf/*.css`、`<destRoot>-pdf/`中的图片副本。 **`book.mjs`阶段8入口点** ```js assembleBook(site: object, pages: Page[]): string ``` 遍历`site.bookData`,发出标题页,然后按顺序遍历`front_matter`和`parts`。对于每个章节,调用`bookChapterTransform`应用五种正文转换。然后运行`rewriteBookHrefs`将书内绝对href转换为`#ch-…`片段锚点。返回完整的`book.html` HTML字符串。 **所有导出(`pdf.mjs`)** | 符号 | 签名 | 描述 | |---|---|---| | `writePdf` | `(pages, staticFiles, site, destRoot, opts) → Promise<stats>` | 主入口点。 | | `deriveBookOutputs` | `(pages, site) -> { bookHtml: string, images: string[] }` | 纯计算版本:返回已组装的HTML和图片路径列表,不写入磁盘。 | | `extractImagePaths` | `(html: string) → string[]` | 从HTML字符串中提取所有图片`src` / `href`路径。 | `book.mjs`的导出参见上面的[阶段2 `book.mjs`](#bookmjs--phase-2-half)。 *** ## 阶段12:`serve.mjs` 长期运行的开发服务器,通过`tbdocs --serve`激活。这是一次性构建的独立生命周期;跳过阶段7(离线)和阶段8(PDF)。 **入口点** ```js runServe(opts: BuildOpts): Promise<void> ``` 运行初始一次性在线构建(预阶段、阶段1--5),然后在`opts.port`(默认`4000`)上启动HTTP服务器,递归源树监视器和`/_tbdocs/reload`的SSE端点。300毫秒防抖在文件更改时触发重建。重建成功后,向每个连接的浏览器标签页发送重载事件。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `runServe` | `(opts: BuildOpts) → Promise<void>` | 主入口点。`BuildOpts`与`runBuild`接受的对象相同。 | *** ## 共享辅助模块 ### `paths.mjs` **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `permalinkToDestPath` | `(permalink: string) → string` | 将permalink URL转换为目标文件路径。`/` → `index.html`;`/foo/` → `foo/index.html`;带`.html`、`.htm`或`.xml`扩展名的路径保持不变;所有其他路径追加`.html`。由阶段1和阶段6使用。 | *** ### `highlight-theme.mjs` 由`highlight.mjs`中的`initHighlighter`内部调用;通常不被其他阶段直接调用。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `loadHighlightTheme` | `(themesDir?: string) → Promise<{ scopeToClass, css }>` | 读取`Light.theme`和`Dark.theme`,按其(light-props, dark-props)对将TextMate作用域分组,为每个唯一对分配一个CSS类,并返回作用域到类的查找和生成的`tb-highlight.css`内容。 | *** ## `tbdocs.mjs` --- 编排器 编排器排序所有阶段并组装`site`对象。它本身不是一个阶段。 **所有导出** | 符号 | 签名 | 描述 | |---|---|---| | `runBuild` | `(opts: BuildOpts) → Promise<{ pages, staticFiles, site, destRoot }>` | 运行完整管线(预阶段、阶段1--8)。返回最终状态以便外部线束可以链接额外工作。 | | `makeTimer` | `() → { lap(label: string): void, summary(): string }` | 轻量计时器。`lap(label)`记录自上次计时以来的毫秒数;`summary()`以`"label=Nms …"`字符串返回所有计时。 | `BuildOpts`字段: | 字段 | 默认值 | 描述 | |---|---|---| | `src` | `"docs"` | 源根目录,相对于`cwd`。 | | `dest` | `null` | 目标根目录。默认为`<src>/_site`。 | | `baseurl` | `null` | 覆盖`config.baseurl`。 | | `url` | `null` | 覆盖`config.url`。 | | `dryRun` | `false` | 跳过所有文件系统写入。 | | `skipOffline` | `null` | 跳过阶段7。`null`从`_config.yml`读取`also_build_offline`。 | | `skipPdf` | `null` | 跳过阶段8。`null`从`_config.yml`读取`also_build_pdf`。 | | `tolerateMissingImages` | `false` | 在阶段8中将缺失图片错误降级为警告。 | | `profileOffline` | `false` | 在控制台输出中发出阶段7的每子步骤计时。 | | `serve` | `false` | 启动阶段12而非一次性构建。 | | `port` | `4000` | 阶段12的HTTP端口。 | ## 另见 * [tbdocs构建器](/official/Documentation/Builder) --- 架构概述和叙述性设计理念。 * [Book配置](/official/Documentation/Book-Configuration) --- `_book.yml`键参考。 * [扩展构建器](/official/Documentation/Extending) --- 添加新管线阶段或markdown-it插件的教程。 > AI生成 --- --- url: /zh/official/Reference/Procedures-and-Functions.md --- # 过程和函数 ## A * [Abs](/official/Reference/VBA/Math/Abs) -- 返回数字的绝对值 * [AllocMem](/official/Reference/VBA/HiddenModule/AllocMem) -- 分配本机内存块并返回其地址 * [AppActivate](/official/Reference/VBA/Interaction/AppActivate) -- 激活应用程序窗口 * [Array](/official/Reference/VBA/Information/Array) -- 从逗号分隔的值列表创建**Variant**数组,或在赋值左侧使用时解构数组 * [Asc, AscB, AscW](/official/Reference/VBA/Strings/Asc) -- 返回字符串中第一个字母的字符代码 * [Atn](/official/Reference/VBA/Math/Atn) -- 返回数字的反正切值 ## B * [Beep](/official/Reference/VBA/Interaction/Beep) -- 通过计算机扬声器发出提示音 ## C * [Calendar](/official/Reference/VBA/DateTime/Calendar) -- 返回或设置日历类型(公历或回历) * [CallByDispId](/official/Reference/VBA/Interaction/CallByDispId) -- 通过IDispatch调度ID动态调用对象上的方法或属性 * [CallByName](/official/Reference/VBA/Interaction/CallByName) -- 通过名称动态调用对象上的方法或属性 * [CBool](/official/Reference/VBA/Conversion/CBool) -- 将表达式强制转换为**Boolean** * [CByte](/official/Reference/VBA/Conversion/CByte) -- 将表达式强制转换为**Byte** * [CCur](/official/Reference/VBA/Conversion/CCur) -- 将表达式强制转换为**Currency** * [CDate](/official/Reference/VBA/Conversion/CDate) -- 将表达式强制转换为**Date** * [CDbl](/official/Reference/VBA/Conversion/CDbl) -- 将表达式强制转换为**Double** * [CDec](/official/Reference/VBA/Conversion/CDec) -- 将表达式强制转换为**Decimal** * [ChDir](/official/Reference/Core/ChDir) -- 更改当前目录或文件夹 * [ChDrive](/official/Reference/Core/ChDrive) -- 更改当前驱动器 * [CurDir](/official/Reference/Core/CurDir) -- 返回当前路径 * [Choose](/official/Reference/VBA/Interaction/Choose) -- 从列表中返回一个值,由1为基的索引选择 * [Chr$, Chr, ChrB$, ChrB, ChrW$, ChrW](/official/Reference/VBA/Strings/Chr) -- 返回与给定字符代码关联的字符 * [CInt](/official/Reference/VBA/Conversion/CInt) -- 将表达式强制转换为**Integer** * [CLng](/official/Reference/VBA/Conversion/CLng) -- 将表达式强制转换为**Long** * [CLngLng](/official/Reference/VBA/Conversion/CLngLng) -- 将表达式强制转换为**LongLong** * [CLngPtr](/official/Reference/VBA/Conversion/CLngPtr) -- 将表达式强制转换为**LongPtr** * [Command$, Command](/official/Reference/VBA/Interaction/Command) -- 返回传递给程序的命令行参数 * [CompilerVersion](/official/Reference/VBA/Compilation/CompilerVersion) -- 返回twinBASIC编译器版本号 * [ConvertIconToBitmap](/official/Reference/VBA/HiddenModule/ConvertIconToBitmap) -- 将图标图片转换为位图图片 * [Cos](/official/Reference/VBA/Math/Cos) -- 返回角度的余弦值 * [CreateGUID](/official/Reference/VBA/HiddenModule/CreateGUID) -- 生成新的GUID并返回注册表格式的字符串 * [CreateObject](/official/Reference/VBA/Interaction/CreateObject) -- 创建COM/Automation对象的新实例 * [CreateStdPictureFromHandle](/official/Reference/VBA/HiddenModule/CreateStdPictureFromHandle) -- 将GDI位图或图标句柄包装为**stdole.StdPicture** * [CSng](/official/Reference/VBA/Conversion/CSng) -- 将表达式强制转换为**Single** * [CStr](/official/Reference/VBA/Conversion/CStr) -- 将表达式强制转换为**String** * [CType](/official/Reference/VBA/Conversion/CType) -- 泛型类型转换,支持\*\*CType(Of *type*)\*\*转换运算符 * [CurrentComponentCLSID](/official/Reference/VBA/Compilation/CurrentComponentCLSID) -- 返回当前类的类ID(CLSID) * [CurrentComponentName](/official/Reference/VBA/Compilation/CurrentComponentName) -- 返回当前组件(模块或类)的名称 * [CurrentProcedureName](/official/Reference/VBA/Compilation/CurrentProcedureName) -- 返回调用函数所在的过程名称 * [CurrentProjectName](/official/Reference/VBA/Compilation/CurrentProjectName) -- 返回当前项目的名称 * [CurrentSourceFile](/official/Reference/VBA/Compilation/CurrentSourceFile) -- 返回当前源文件的完整路径 * [CVar](/official/Reference/VBA/Conversion/CVar) -- 将表达式强制转换为**Variant** * [CVDate](/official/Reference/VBA/Conversion/CVDate) -- 将表达式强制转换为**Date**子类型的**Variant** * [CVErr](/official/Reference/VBA/Conversion/CVErr) -- 将数值表达式强制转换为**Error**子类型的**Variant** ## D * [Date](/official/Reference/Core/Date) -- 设置或返回当前系统日期 * [DateAdd](/official/Reference/VBA/DateTime/DateAdd) -- 向日期添加时间间隔 * [DateDiff](/official/Reference/VBA/DateTime/DateDiff) -- 返回两个日期之间的时间间隔数 * [DatePart](/official/Reference/VBA/DateTime/DatePart) -- 返回给定日期的指定部分 * [DateSerial](/official/Reference/VBA/DateTime/DateSerial) -- 返回指定年、月、日的日期 * [DateValue](/official/Reference/VBA/DateTime/DateValue) -- 将字符串转换为日期 * [Day](/official/Reference/VBA/DateTime/Day) -- 返回日期值中的月份日期 * [DDB](/official/Reference/VBA/Financial/DDB) -- 使用双倍余额递减法返回资产折旧值 * [DeleteSetting](/official/Reference/VBA/Interaction/DeleteSetting) -- 从Windows注册表中应用程序条目删除节或键设置 * [Dir](/official/Reference/Core/Dir) -- 返回与模式匹配的文件、目录、文件夹或卷标的名称 * [DoEvents](/official/Reference/VBA/Interaction/DoEvents) -- 让出控制权给消息循环,以便处理挂起的事件 ## E * [Emit](/official/Reference/VBA/HiddenModule/Emit) -- 向封闭过程的代码生成流中注入自定义**Byte**值 * [EmitAny](/official/Reference/VBA/HiddenModule/EmitAny) -- 向封闭过程的代码生成流中注入自定义类型值 * [Environ$, Environ](/official/Reference/VBA/Interaction/Environ) -- 返回进程环境变量的值 * [EOF](/official/Reference/VBA/FileSystem/EOF) -- 返回是否已到达文件末尾 * [Erl](/official/Reference/VBA/Information/Erl) -- 返回最近运行时错误发生的行号 * [Err](/official/Reference/VBA/Information/Err) -- 返回描述当前运行时错误状态的**ErrObject** * [Error$, Error](/official/Reference/VBA/Conversion/Error) -- 返回与给定错误号对应的错误消息 * [Eval](/official/Reference/VBA/HiddenModule/Eval) -- 编译并求值以字符串形式提供的twinBASIC表达式 * [Exp](/official/Reference/VBA/Math/Exp) -- 返回*e*(自然对数的底数)的指定次幂 ## F * [FileAttr](/official/Reference/VBA/FileSystem/FileAttr) -- 返回使用**Open**语句打开的文件的文件模式 * [FileCopy](/official/Reference/Core/FileCopy) -- 复制文件 * [FileDateTime](/official/Reference/VBA/FileSystem/FileDateTime) -- 返回文件创建或最后修改的日期和时间 * [FileLen](/official/Reference/VBA/FileSystem/FileLen) -- 返回文件的字节长度 * [Filter](/official/Reference/VBA/Strings/Filter) -- 根据条件将字符串数组筛选为子集 * [Fix](/official/Reference/VBA/Conversion/Fix) -- 返回数字的整数部分,向零截断 * [Format$, Format](/official/Reference/VBA/Strings/Format) -- 根据格式表达式中的指令格式化表达式 * [FormatCurrency](/official/Reference/VBA/Strings/FormatCurrency) -- 将表达式格式化为货币值 * [FormatDateTime](/official/Reference/VBA/Strings/FormatDateTime) -- 将表达式格式化为日期或时间 * [FormatNumber](/official/Reference/VBA/Strings/FormatNumber) -- 将表达式格式化为数字 * [FormatPercent](/official/Reference/VBA/Strings/FormatPercent) -- 将表达式格式化为百分比 * [FreeFile](/official/Reference/VBA/FileSystem/FreeFile) -- 返回**Open**语句可用的下一个文件号 * [FreeMem](/official/Reference/VBA/HiddenModule/FreeMem) -- 释放使用**AllocMem**分配的内存 * [FV](/official/Reference/VBA/Financial/FV) -- 基于定期固定付款和固定利率返回年金的终值 ## G * [GetAllSettings](/official/Reference/VBA/Interaction/GetAllSettings) -- 返回应用程序注册表项中某个节的所有键/值对 * [GetAttr](/official/Reference/VBA/FileSystem/GetAttr) -- 返回文件或目录的属性 * [GetMem1](/official/Reference/VBA/HiddenModule/GetMem1) -- 从内存地址读取一个字节到**Byte**变量 * [GetMem2](/official/Reference/VBA/HiddenModule/GetMem2) -- 从内存地址读取两个字节到**Integer**变量 * [GetMem4](/official/Reference/VBA/HiddenModule/GetMem4) -- 从内存地址读取四个字节到**Long**变量 * [GetMem8](/official/Reference/VBA/HiddenModule/GetMem8) -- 从内存地址读取八个字节到**Currency**变量 * [GetMemPtr](/official/Reference/VBA/HiddenModule/GetMemPtr) -- 从内存地址读取指针大小的值到**LongPtr**变量 * [GetObject](/official/Reference/VBA/Interaction/GetObject) -- 返回从文件加载或已在运行的Automation对象引用 * [GetSetting](/official/Reference/VBA/Interaction/GetSetting) -- 从Windows注册表中应用程序条目返回字符串键设置值 ## H * [Hex$, Hex](/official/Reference/VBA/Conversion/Hex) -- 返回表示数字十六进制值的字符串 * [Hour](/official/Reference/VBA/DateTime/Hour) -- 返回时间值中的小时 ## I * [If](/official/Reference/VBA/Interaction/If) -- 求值表达式并返回两个值之一,具有短路求值特性 * [IIf](/official/Reference/VBA/Interaction/IIf) -- 求值表达式并返回两个值之一;两个分支始终都被求值 * [IMEStatus](/official/Reference/VBA/Information/IMEStatus) -- 返回输入法编辑器的状态 * [Input, Input$](/official/Reference/VBA/FileSystem/Input) -- 从打开的顺序文件读取固定数量的字符 * [InputB, InputB$](/official/Reference/VBA/FileSystem/InputB) -- 从打开的顺序文件读取固定数量的字节 * [InputBox](/official/Reference/VBA/Interaction/InputBox) -- 提示用户输入一行文本并返回输入内容 * [InStr$, InStrB, InStr](/official/Reference/VBA/Strings/InStr) -- 返回一个字符串在另一个字符串中的位置 * [InStrRev](/official/Reference/VBA/Strings/InStrRev) -- 从末尾搜索,返回一个字符串在另一个字符串中的位置 * [Int](/official/Reference/VBA/Conversion/Int) -- 返回数字的整数部分,向负无穷舍入 * [IPmt](/official/Reference/VBA/Financial/IPmt) -- 返回年金给定期间的利息付款 * [IRR](/official/Reference/VBA/Financial/IRR) -- 返回一系列定期现金流的内部收益率 * [IsArray](/official/Reference/VBA/Information/IsArray) -- 返回变量是否为数组 * [IsArrayInitialized](/official/Reference/VBA/Information/IsArrayInitialized) -- 返回数组是否已分配维度 * [IsDate](/official/Reference/VBA/Information/IsDate) -- 返回表达式是否可求值为日期 * [IsEmpty](/official/Reference/VBA/Information/IsEmpty) -- 返回**Variant**是否未初始化 * [IsError](/official/Reference/VBA/Information/IsError) -- 返回表达式是否为错误子类型 * [IsMissing](/official/Reference/VBA/Information/IsMissing) -- 返回可选参数是否已提供 * [IsNull](/official/Reference/VBA/Information/IsNull) -- 返回变量是否包含**Null**值 * [IsNumeric](/official/Reference/VBA/Information/IsNumeric) -- 返回表达式是否可求值为数字 * [IsObject](/official/Reference/VBA/Information/IsObject) -- 返回变量是否引用对象 ## J * [Join](/official/Reference/VBA/Strings/Join) -- 使用给定分隔符连接字符串数组 ## K * [Kill](/official/Reference/Core/Kill) -- 从磁盘中删除文件 ## L * [LBound](/official/Reference/VBA/Information/LBound) -- 返回数组某维的最小有效下标 * [LCase$, LCase](/official/Reference/VBA/Strings/LCase) -- 返回转换为小写的字符串 * [Left$, Left, LeftB$, LeftB](/official/Reference/VBA/Strings/Left) -- 返回字符串最左边的字符 * [Len, LenB](/official/Reference/VBA/Strings/Len) -- 返回字符串的长度或变量的存储大小 * [Load](/official/Reference/Core/Load) -- 将对象(通常是窗体)加载到内存但不显示 * [Loc](/official/Reference/VBA/FileSystem/Loc) -- 返回打开文件中的当前读/写位置 * [LOF](/official/Reference/VBA/FileSystem/LOF) -- 返回打开文件的字节大小 * [Log](/official/Reference/VBA/Math/Log) -- 返回数字的自然对数(以*e*为底) * [LTrim$, LTrim](/official/Reference/VBA/Strings/LTrim) -- 删除字符串的前导空格 ## M * [MacID](/official/Reference/VBA/Conversion/MacID) -- 在Macintosh上,将4字符常量转换为**Dir**、**Kill**、**Shell**或**AppActivate**可用的值 * [Mid$, Mid, MidB$, MidB](/official/Reference/VBA/Strings/Mid) -- 返回字符串的子串 * [Minute](/official/Reference/VBA/DateTime/Minute) -- 返回时间值中的分钟 * [MIRR](/official/Reference/VBA/Financial/MIRR) -- 返回一系列定期现金流的修正内部收益率 * [MkDir](/official/Reference/Core/MkDir) -- 创建新目录或文件夹 * [Month](/official/Reference/VBA/DateTime/Month) -- 返回日期值中的月份 * [MonthName](/official/Reference/VBA/Strings/MonthName) -- 返回指定月份的名称 * [MsgBox](/official/Reference/VBA/Interaction/MsgBox) -- 显示模式消息对话框并返回用户单击的按钮 ## N * [Name](/official/Reference/Core/Name) -- 重命名磁盘文件、目录或文件夹 * [NPer](/official/Reference/VBA/Financial/NPer) -- 基于定期固定付款和固定利率返回年金的期数 * [NPV](/official/Reference/VBA/Financial/NPV) -- 基于一系列定期现金流和贴现率返回投资的净现值 * [Now](/official/Reference/Core/Now) -- 返回当前系统日期和时间 * [Nz](/official/Reference/VBA/Conversion/Nz) -- 用指定的替换值替换**Null**值 ## O * [ObjPtr](/official/Reference/VBA/Information/ObjPtr) -- 返回对象的COM标识地址 * [Oct$, Oct](/official/Reference/VBA/Conversion/Oct) -- 返回表示数字八进制值的字符串 ## P * [Partition](/official/Reference/VBA/Interaction/Partition) -- 返回标识数字所属范围的字符串 * [PictureToByteArray](/official/Reference/VBA/HiddenModule/PictureToByteArray) -- 将**IPicture**序列化为**Byte**数组 * [Pmt](/official/Reference/VBA/Financial/Pmt) -- 基于定期固定付款和固定利率返回年金的付款额 * [PPmt](/official/Reference/VBA/Financial/PPmt) -- 返回年金给定期间的本金付款 * [ProcessorArchitecture](/official/Reference/VBA/Compilation/ProcessorArchitecture) -- 返回运行应用程序的处理器架构 * [PutMem1](/official/Reference/VBA/HiddenModule/PutMem1) -- 向内存地址写入一个字节 * [PutMem2](/official/Reference/VBA/HiddenModule/PutMem2) -- 向内存地址写入两个字节 * [PutMem4](/official/Reference/VBA/HiddenModule/PutMem4) -- 向内存地址写入四个字节 * [PutMem8](/official/Reference/VBA/HiddenModule/PutMem8) -- 向内存地址写入八个字节 * [PutMemPtr](/official/Reference/VBA/HiddenModule/PutMemPtr) -- 向内存地址写入指针大小的值 * [PV](/official/Reference/VBA/Financial/PV) -- 基于定期固定付款和固定利率返回年金的现值 ## Q * [QBColor](/official/Reference/VBA/Information/QBColor) -- 返回QuickBASIC颜色索引的RGB颜色值 ## R * [RaiseEventByName](/official/Reference/VBA/Interaction/RaiseEventByName) -- 按名称在对象上引发事件,以**Variant**数组传递参数 * [RaiseEventByName2](/official/Reference/VBA/Interaction/RaiseEventByName2) -- 按名称在对象上引发事件,使用可变长度参数列表 * [Randomize](/official/Reference/VBA/Math/Randomize) -- 初始化随机数生成器 * [Rate](/official/Reference/VBA/Financial/Rate) -- 返回年金每期的利率 * [Replace](/official/Reference/VBA/Strings/Replace) -- 用另一个子串替换字符串中的子串 * [Reset](/official/Reference/VBA/FileSystem/Reset) -- 关闭使用**Open**语句打开的所有磁盘文件 * [RGB](/official/Reference/VBA/Information/RGB) -- 从红、绿、蓝分量构建RGB颜色值 * [RGBA](/official/Reference/VBA/Information/RGBA) -- 从红、绿、蓝和透明度分量构建RGBA颜色值 * [RGBA\_A](/official/Reference/VBA/Information/RGBA_A) -- 返回RGBA颜色值的透明度分量 * [RGB\_B](/official/Reference/VBA/Information/RGB_B) -- 返回RGB颜色值的蓝色分量 * [RGB\_G](/official/Reference/VBA/Information/RGB_G) -- 返回RGB颜色值的绿色分量 * [RGB\_R](/official/Reference/VBA/Information/RGB_R) -- 返回RGB颜色值的红色分量 * [Right$, Right, RightB$, RightB](/official/Reference/VBA/Strings/Right) -- 返回字符串最右边的字符 * [RmDir](/official/Reference/Core/RmDir) -- 删除现有目录或文件夹 * [Rnd](/official/Reference/VBA/Math/Rnd) -- 返回\[0.0, 1.0)范围内的伪随机数 * [Round](/official/Reference/VBA/Math/Round) -- 将数字舍入到指定小数位数 * [RTrim$, RTrim](/official/Reference/VBA/Strings/RTrim) -- 删除字符串的尾随空格 ## S * [SavePicture](/official/Reference/Core/SavePicture) -- 将**Picture**或**Image**中的图形保存到文件 * [SaveSetting](/official/Reference/VBA/Interaction/SaveSetting) -- 在Windows注册表中应用程序条目保存或创建应用程序条目 * [Second](/official/Reference/VBA/DateTime/Second) -- 返回时间值中的秒 * [Seek](/official/Reference/VBA/FileSystem/Seek) -- 返回或设置打开文件中的读/写位置 * [SendKeys](/official/Reference/VBA/Interaction/SendKeys) -- 向活动窗口发送按键 * [SetAttr](/official/Reference/VBA/FileSystem/SetAttr) -- 设置文件的属性信息 * [Sgn](/official/Reference/VBA/Math/Sgn) -- 返回指示数字符号的值 * [Shell](/official/Reference/VBA/Interaction/Shell) -- 异步运行另一个程序并返回其任务ID * [Sin](/official/Reference/VBA/Math/Sin) -- 返回角度的正弦值 * [SLN](/official/Reference/VBA/Financial/SLN) -- 返回资产单期的直线折旧值 * [Space$, Space](/official/Reference/VBA/Strings/Space) -- 返回由空格组成的字符串 * [Split](/official/Reference/VBA/Strings/Split) -- 将字符串拆分为字符串数组 * [Sqr](/official/Reference/VBA/Math/Sqr) -- 返回数字的平方根 * [Str$, Str](/official/Reference/VBA/Conversion/Str) -- 返回数字的字符串表示 * [StrComp](/official/Reference/VBA/Strings/StrComp) -- 比较两个字符串 * [StrConv](/official/Reference/VBA/Strings/StrConv) -- 将字符串转换为指定格式 * [String$, String](/official/Reference/VBA/Strings/String) -- 返回由重复字符组成的字符串 * [StrPtr](/official/Reference/VBA/Information/StrPtr) -- 返回**String**底层缓冲区的地址 * [StrReverse](/official/Reference/VBA/Strings/StrReverse) -- 反转字符串中的字符顺序 * [Switch](/official/Reference/VBA/Interaction/Switch) -- 返回(条件, 值)对列表中与第一个**True**条件配对的值 * [SYD](/official/Reference/VBA/Financial/SYD) -- 返回资产指定期间的年数总和折旧值 ## T * [Tan](/official/Reference/VBA/Math/Tan) -- 返回角度的正切值 * [Time](/official/Reference/Core/Time) -- 设置或返回当前系统时间 * [Timer](/official/Reference/VBA/DateTime/Timer) -- 返回自午夜以来经过的秒数 * [TimeSerial](/official/Reference/VBA/DateTime/TimeSerial) -- 返回指定小时、分钟和秒的时间 * [TimeValue](/official/Reference/VBA/DateTime/TimeValue) -- 将字符串转换为时间 * [TranslateColor](/official/Reference/VBA/Information/TranslateColor) -- 将OLE颜色值转换为纯RGB颜色值 * [Trim$, Trim](/official/Reference/VBA/Strings/Trim) -- 删除字符串的前导和尾随空格 * [TypeName](/official/Reference/VBA/Information/TypeName) -- 以**String**返回变量数据类型的名称 ## U * [UBound](/official/Reference/VBA/Information/UBound) -- 返回数组某维的最大有效下标 * [UCase$, UCase](/official/Reference/VBA/Strings/UCase) -- 返回转换为大写的字符串 * [Unload](/official/Reference/Core/Unload) -- 从内存中移除对象(通常是窗体) ## V * [Val](/official/Reference/VBA/Conversion/Val) -- 将字符串解析为**Double** * [ValDec](/official/Reference/VBA/Conversion/ValDec) -- 将字符串解析为**Decimal** * [VarPtr](/official/Reference/VBA/Information/VarPtr) -- 返回变量的地址 * [VarType](/official/Reference/VBA/Information/VarType) -- 返回标识变量子类型的**VbVarType**枚举值 * [vbaCastObj](/official/Reference/VBA/HiddenModule/vbaCastObj) -- 返回重新解释为另一个COM接口的对象 * [vbaCopyBytes](/official/Reference/VBA/HiddenModule/vbaCopyBytes) -- 从一个地址向另一个地址复制字节块 * [vbaCopyBytesZero](/official/Reference/VBA/HiddenModule/vbaCopyBytesZero) -- 从一个地址向另一个地址复制字节块,然后将源清零 * [vbaObjAddref](/official/Reference/VBA/HiddenModule/vbaObjAddref) -- 递增给定地址处对象的COM引用计数 * [vbaObjSet](/official/Reference/VBA/HiddenModule/vbaObjSet) -- 将对象指针赋给对象变量,释放先前的引用 * [vbaObjSetAddref](/official/Reference/VBA/HiddenModule/vbaObjSetAddref) -- 将对象指针赋给对象变量,添加引用并释放先前的引用 ## W * [Weekday](/official/Reference/VBA/DateTime/Weekday) -- 返回日期值中的星期几 * [WeekdayName](/official/Reference/VBA/Strings/WeekdayName) -- 返回指定星期几的名称 * [Width](/official/Reference/VBA/FileSystem/Width) -- 设置顺序输出文件的行宽 ## X ## Y * [Year](/official/Reference/VBA/DateTime/Year) -- 返回日期值中的年份 ## Z --- --- url: /zh/packages/vbccr/ranges/slider.md description: 滑块控件(Slider) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 滑块控件(Slider) 提供可自定义的滑块控件,支持水平/垂直方向、刻度样式、选择范围、自绘和OLE拖放。 ## 枚举 ### SldOrientationConstants 控件方向常量。 | 常量 | 值 | 说明 | |------|-----|------| | SldOrientationHorizontal | 0 | 水平方向 | | SldOrientationVertical | 1 | 垂直方向 | ### SldTipSideConstants 提示文本位置常量。 | 常量 | 值 | 说明 | |------|-----|------| | SldTipSideAboveLeft | 0 | 提示显示在上方/左侧 | | SldTipSideBelowRight | 1 | 提示显示在下方/右侧 | ### SldTickStyleConstants 刻度样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | SldTickStyleBottomRight | 0 | 底部/右侧刻度 | | SldTickStyleTopLeft | 1 | 顶部/左侧刻度 | | SldTickStyleBoth | 2 | 两侧刻度 | | SldTickStyleNone | 3 | 无刻度 | ### SldDrawModeConstants 绘制模式常量。 | 常量 | 值 | 说明 | |------|-----|------| | SldDrawModeNormal | 0 | 正常绘制 | | SldDrawModeOwnerDraw | 1 | 自绘模式 | ### SldOwnerDrawItemConstants 自绘项常量。 | 常量 | 值 | 说明 | |------|-----|------| | SldOwnerDrawItemTics | 1 | 刻度线 | | SldOwnerDrawItemThumb | 2 | 滑块 | | SldOwnerDrawItemChannel | 3 | 通道 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### Container ```vb Public Property Get Container() As Object Public Property Set Container(ByVal Value As Object) ``` 返回/设置对象的容器。 ### Left ```vb Public Property Get Left() As Single Public Property Let Left(ByVal Value As Single) ``` 返回/设置对象与其容器左边缘的距离。 ### Top ```vb Public Property Get Top() As Single Public Property Let Top(ByVal Value As Single) ``` 返回/设置对象与其容器顶边缘的距离。 ### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 返回/设置对象的宽度。 ### Height ```vb Public Property Get Height() As Single Public Property Let Height(ByVal Value As Single) ``` 返回/设置对象的高度。 ### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 返回/设置鼠标悬停时显示的提示文本。 ### HelpContextID ```vb Public Property Get HelpContextID() As Long Public Property Let HelpContextID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### WhatsThisHelpID ```vb Public Property Get WhatsThisHelpID() As Long Public Property Let WhatsThisHelpID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### DragIcon ```vb Public Property Get DragIcon() As IPictureDisp Public Property Let DragIcon(ByVal Value As IPictureDisp) Public Property Set DragIcon(ByVal Value As IPictureDisp) ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Public Property Get DragMode() As Integer Public Property Let DragMode(ByVal Value As Integer) ``` 返回/设置拖动模式。 ### hWnd ```vb Public Property Get hWnd() As LongPtr ``` 返回控件句柄。 ### hWndUserControl ```vb Public Property Get hWndUserControl() As LongPtr ``` 返回UserControl句柄。 ### VisualStyles ```vb Public Property Get VisualStyles() As Boolean Public Property Let VisualStyles(ByVal Value As Boolean) ``` 返回/设置是否启用视觉样式。需要comctl32.dll 6.0或更高版本。 ### BackColor ```vb Public Property Get BackColor() As OLE_COLOR Public Property Let BackColor(ByVal Value As OLE_COLOR) ``` 返回/设置背景色。 ### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 返回/设置对象是否能响应用户事件。 ### OLEDropMode ```vb Public Property Get OLEDropMode() As OLEDropModeConstants Public Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` 返回/设置对象是否可以作为OLE放置目标。 ### MousePointer ```vb Public Property Get MousePointer() As CCMousePointerConstants Public Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 返回/设置鼠标悬停时显示的指针类型。参见通用枚举。 ### MouseIcon ```vb Public Property Get MouseIcon() As IPictureDisp Public Property Let MouseIcon(ByVal Value As IPictureDisp) Public Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Public Property Get MouseTrack() As Boolean Public Property Let MouseTrack(ByVal Value As Boolean) ``` 返回/设置是否在鼠标进入或离开控件时触发事件。 ### RightToLeft ```vb Public Property Get RightToLeft() As Boolean Public Property Let RightToLeft(ByVal Value As Boolean) ``` 返回/设置从右到左显示方向。 ### RightToLeftLayout ```vb Public Property Get RightToLeftLayout() As Boolean Public Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 返回/设置从右到左布局。 ### RightToLeftMode ```vb Public Property Get RightToLeftMode() As CCRightToLeftModeConstants Public Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 返回/设置从右到左模式。参见通用枚举。 ### Min ```vb Public Property Get Min() As Long Public Property Let Min(ByVal Value As Long) ``` 返回/设置最小值。 ### Max ```vb Public Property Get Max() As Long Public Property Let Max(ByVal Value As Long) ``` 返回/设置最大值。 ### Value ```vb Public Property Get Value() As Long Public Property Let Value(ByVal NewValue As Long) ``` 返回/设置当前值。 ### TickFrequency ```vb Public Property Get TickFrequency() As Long Public Property Let TickFrequency(ByVal Value As Long) ``` 返回/设置刻度频率。 ### Orientation ```vb Public Property Get Orientation() As SldOrientationConstants Public Property Let Orientation(ByVal Value As SldOrientationConstants) ``` 返回/设置控件方向。 ### SmallChange ```vb Public Property Get SmallChange() As Long Public Property Let SmallChange(ByVal Value As Long) ``` 返回/设置按下箭头键时的变化量。 ### LargeChange ```vb Public Property Get LargeChange() As Long Public Property Let LargeChange(ByVal Value As Long) ``` 返回/设置按下PageUp/PageDown或点击通道时的变化量。 ### TickStyle ```vb Public Property Get TickStyle() As SldTickStyleConstants Public Property Let TickStyle(ByVal Value As SldTickStyleConstants) ``` 返回/设置刻度样式。 ### ShowTip ```vb Public Property Get ShowTip() As Boolean Public Property Let ShowTip(ByVal Value As Boolean) ``` 返回/设置是否显示值提示。 ### TipSide ```vb Public Property Get TipSide() As SldTipSideConstants Public Property Let TipSide(ByVal Value As SldTipSideConstants) ``` 返回/设置提示显示位置。 ### SelectRange ```vb Public Property Get SelectRange() As Boolean Public Property Let SelectRange(ByVal Value As Boolean) ``` 返回/设置是否启用选择范围。 ### SelStart ```vb Public Property Get SelStart() As Long Public Property Let SelStart(ByVal Value As Long) ``` 返回/设置选择范围的起始位置。 ### SelLength ```vb Public Property Get SelLength() As Long Public Property Let SelLength(ByVal Value As Long) ``` 返回/设置选择范围的长度。 ### Transparent ```vb Public Property Get Transparent() As Boolean Public Property Let Transparent(ByVal Value As Boolean) ``` 返回/设置控件背景是否透明。 ### HideThumb ```vb Public Property Get HideThumb() As Boolean Public Property Let HideThumb(ByVal Value As Boolean) ``` 返回/设置是否隐藏滑块。 ### Reversed ```vb Public Property Get Reversed() As Boolean Public Property Let Reversed(ByVal Value As Boolean) ``` 返回/设置是否反转滑块方向。 ### DrawMode ```vb Public Property Get DrawMode() As SldDrawModeConstants Public Property Let DrawMode(ByVal Value As SldDrawModeConstants) ``` 返回/设置绘制模式。 ### ThumbLeft ```vb Public Property Get ThumbLeft() As Single ``` 返回滑块左边距。 ### ThumbTop ```vb Public Property Get ThumbTop() As Single ``` 返回滑块顶边距。 ### ThumbWidth ```vb Public Property Get ThumbWidth() As Single ``` 返回滑块宽度。 ### ThumbHeight ```vb Public Property Get ThumbHeight() As Single ``` 返回滑块高度。 ### ChannelLeft ```vb Public Property Get ChannelLeft() As Single ``` 返回通道左边距。 ### ChannelTop ```vb Public Property Get ChannelTop() As Single ``` 返回通道顶边距。 ### ChannelWidth ```vb Public Property Get ChannelWidth() As Single ``` 返回通道宽度。 ### ChannelHeight ```vb Public Property Get ChannelHeight() As Single ``` 返回通道高度。 ## 方法 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘对象。 ### ClearSel ```vb Public Sub ClearSel() ``` 清除选择范围。 ### GetNumTicks ```vb Public Function GetNumTicks() As Long ``` 返回刻度数量。 ### GetTickPosition ```vb Public Function GetTickPosition(ByVal Index As Long) As Single ``` 返回指定刻度的位置。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动OLE拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移至控件。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置Z顺序。 ## 事件 ### Click ```vb Public Event Click() ``` 用户单击控件时触发。 ### Scroll ```vb Public Event Scroll() ``` 用户拖动滑块时触发。 ### Change ```vb Public Event Change() ``` 值改变后触发。 ### ContextMenu ```vb Public Event ContextMenu(ByVal X As Single, ByVal Y As Single) ``` 右键点击控件时触发。 ### ModifyTipText ```vb Public Event ModifyTipText(ByRef Text As String) ``` 提示文本即将显示时触发,可修改提示文本。 ### ItemDraw ```vb Public Event ItemDraw(ByVal Item As SldOwnerDrawItemConstants, ByRef Cancel As Boolean, ByVal ItemState As Long, ByVal hDC As Long, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` 自绘项时触发。Item为自绘项类型,Cancel可取消默认绘制,hDC为设备上下文。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键前预览。IsInputKey为True表示该键为输入键。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键释放前预览。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下键盘键时触发。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放键盘键时触发。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按下并释放ANSI键时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件区域时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件区域时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE拖放操作完成时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE拖放操作放置时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE拖放操作悬停时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE拖放操作给反馈时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE拖放操作设置数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE拖放操作开始时触发。 ## 代码示例 ### 基本用法 ```vb ' 设置滑块控件 With Slider1 .Min = 0 .Max = 100 .Value = 50 .TickFrequency = 10 .SmallChange = 1 .LargeChange = 10 .SelectRange = True .SelStart = 20 .SelLength = 60 End With ' 响应值变化 Private Sub Slider1_Change() Debug.Print "当前值: " & Slider1.Value End Sub ' 自定义提示文本 Private Sub Slider1_ModifyTipText(ByRef Text As String) Text = "进度: " & Slider1.Value & "%" End Sub ``` --- --- url: /zh/official.md --- # 欢迎使用twinBASIC twinBASIC是一种新的BASIC语言和开发环境,致力于与VB6和VBA100%向后兼容,同时添加现代语言特性——泛型、原生[**Interface**](/official/Reference/Core/Interface)和[**CoClass**](/official/Reference/Core/CoClass)声明、属性和包系统。编译器和IDE正在积极开发中,目前处于Beta阶段;[常见问题](/official/Miscellaneous/FAQs)涵盖了项目状态、作者信息以及当前已实现和未实现的功能,下载位于主GitHub仓库的[Releases](https://github.com/twinbasic/twinbasic/releases)页面。 ## twinBASIC新手? 从[常见问题](/official/Miscellaneous/FAQs)开始了解——什么是twinBASIC、当前进展、支持什么——然后阅读[特性概览](/official/Features/)了解twinBASIC在VBx基础上添加的所有内容。下方的[教程](#教程)部分提供分步指南;[Arrays](/official/Tutorials/Arrays)教程无需任何twinBASIC经验,是不错的入门读物。 ## 从VBA或VB6转来? 大多数现有VB6/VBA代码无需修改即可编译。VBx兼容性之外的关键新增:新数据类型([**LongLong**](/official/Features/Language/Data-Types#longlong)、[**LongPtr**](/official/Features/Language/Data-Types#longptr)、[**Decimal**](/official/Features/Language/Data-Types#decimal))、原生[**Interface**](/official/Reference/Core/Interface)和[**CoClass**](/official/Reference/Core/CoClass)声明、用于继承的[**Implements Via**](/official/Features/Language/Inheritance#implements-via-for-basic-inheritance)和[**Inherits**](/official/Features/Language/Inheritance#inherits-for-complete-oop)、泛型、方法重载、类型推断和属性语法。[特性概览](/official/Features/)是完整的目录。 ## 查找关键字、函数或运算符? 参考部分分为语言构造(编译器解析的内容)和运行时成员(内置包中提供的函数、属性、类型、类): * [**分类列表**](/official/Reference/Categories) —— 按用途分组的语句、过程和函数(编译器控制、声明、控制流、文件I/O……) * [**语句**](/official/Reference/Statements) —— 所有语言语句的字母索引 * [**过程和函数**](/official/Reference/Procedures-and-Functions) —— 所有可调用运行时成员的字母索引 * [**运算符**](/official/Reference/Operators) —— 算术、比较、逻辑、位运算及twinBASIC新增运算符 * [**编译器常量**](/official/Reference/Compiler-Constants) —— 编译器识别的 `#If` 符号 * [**属性**](/official/Reference/Attributes) —— `[Documentation(...)]`、`[COMCreatable(...)]` 及其余属性语法 * [**控件**](/official/Reference/Controls) —— 标准UI控件([**CheckBox**](/official/Reference/VB/CheckBox/)、[**TextBox**](/official/Reference/VB/TextBox/)、[**CommandButton**](/official/Reference/VB/CommandButton/)、……)按用途分组 * [**术语表**](/official/Reference/Glossary) —— 文档中使用的技术术语 ## 内置包 *包*将相关代码组织在一个命名空间下,作为单个依赖项被项目引用。[包页面](/official/Reference/Packages)列出了每个内置包及其简要描述;下面的标题按用途对它们进行分组。 **默认包** —— 自动在每个项目中引用: * [**VBA**](/official/Reference/VBA/) —— 标准运行时库(`MsgBox`、`CStr`、`Format`、`Mid`、……)以及[**Collection**](/official/Reference/VBA/Collection/)和[**Err**](/official/Reference/VBA/Information/Err)内置对象 * [**VBRUN**](/official/Reference/VBRUN/) —— 运行时类型([**PropertyBag**](/official/Reference/VBRUN/PropertyBag/)、环境属性、结构化错误上下文、拖放)以及经典VB6窗体和控件使用的枚举 * [**VB**](/official/Reference/VB/) —— 标准控件([**CheckBox**](/official/Reference/VB/CheckBox/)、[**TextBox**](/official/Reference/VB/TextBox/)、[**CommandButton**](/official/Reference/VB/CommandButton/)、……)和应用级单例([**App**](/official/Reference/VB/App/)、[**Screen**](/official/Reference/VB/Screen/)、[**Clipboard**](/official/Reference/VB/Clipboard/)、[**Printer**](/official/Reference/VB/Printer/)、……) **额外GUI** —— [**VB**](/official/Reference/VB/)包之外的控件: * [**CustomControls**](/official/Reference/CustomControls/) —— 自绘 `Waynes...` 控件及用于创作新控件的DESIGNER框架 * [**WinNativeCommonCtls**](/official/Reference/WinNativeCommonCtls/) —— `MSCOMCTL.OCX` 的VB6兼容替代([**DTPicker**](/official/Reference/WinNativeCommonCtls/DTPicker)、[**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/)、[**ListView**](/official/Reference/WinNativeCommonCtls/ListView/)、[**MonthView**](/official/Reference/WinNativeCommonCtls/MonthView)、[**ProgressBar**](/official/Reference/WinNativeCommonCtls/ProgressBar)、[**Slider**](/official/Reference/WinNativeCommonCtls/Slider)、[**TreeView**](/official/Reference/WinNativeCommonCtls/TreeView/)、[**UpDown**](/official/Reference/WinNativeCommonCtls/UpDown)) **Web嵌入** —— 在窗体中托管浏览器引擎: * [**WebView2**](/official/Reference/WebView2/) —— Microsoft Edge运行时 * [**CEF**](/official/Reference/CEF/) —— Chromium Embedded Framework(BETA),可选择三种Chromium运行时 **Windows集成** —— 操作系统功能的轻量封装: * [**WinServicesLib**](/official/Reference/WinServicesLib/) —— 将twinBASIC EXE作为一个或多个Windows服务运行 * [**WinEventLogLib**](/official/Reference/WinEventLogLib/) —— 写入Windows事件日志条目,支持编译时消息表生成 * [**WinNamedPipesLib**](/official/Reference/WinNamedPipesLib/) —— 基于IOCP的异步命名管道服务器和客户端 **工具链**: * [**Assert**](/official/Reference/Assert/) —— 单元测试断言函数,三个模块共享相同的十五成员API,但严格程度不同 * [**tbIDE**](/official/Reference/tbIDE/) —— twinBASIC IDE本身的加载项SDK ## 教程 * [**Arrays**](/official/Tutorials/Arrays) —— 固定数组和动态数组、`Dim`、`ReDim`、多维结构 * [**CustomControls**](/official/Tutorials/CustomControls/) —— 使用 `Waynes...` 框架构建自绘控件 * [**WebView2**](/official/Tutorials/WebView2/) —— 嵌入Edge运行时:托管本地资源、JavaScript互操作、驱动Monaco * [**CEF**](/official/Tutorials/CEF/) —— 嵌入Chromium:构建浏览器外壳、托管本地资源、JavaScript互操作、驱动Monaco ## twinBASIC IDE [**IDE部分**](/official/IDE/)记录了编辑器、项目资源管理器、调试面板(调用栈、监视、诊断、调试控制台)、[**tbForm**](/official/IDE/tbForm)和[**tbReport**](/official/IDE/tbReport)设计器以及各功能侧面板。要安装第三方加载项,参见[**Add Ins**](/official/IDE/AddIns/);要自行开发加载项,[**tbIDE包**](/official/Reference/tbIDE/)是加载项SDK。 ## 社区和外部资源 * GitHub上的[**twinBASIC wiki**](https://github.com/twinbasic/documentation/wiki)以社区贡献和对前沿特性的说明补充了本站文档。 * [**视频**](/official/Videos/) —— twinBASIC视频系列和[**Access DevCon**](/official/Videos/AccessDevCon)会议演讲。 * Mike Wolfe在[@nolongerset](https://nolongerset.com)的第三方指南: * [Create a Custom ActiveX Control with twinBASIC](https://nolongerset.com/create-activex-control-with-twinbasic/) * [Create a Tool Window in the VBIDE with twinBASIC](https://nolongerset.com/create-a-vbe-addin-with-twinbasic/) ## 贡献文档 本文档为开源项目。参见[**文档开发**](/official/Documentation/)了解构建和预览工作流以及贡献约定。 > AI生成 --- --- url: /zh/official/Tutorials/CustomControls/Painting-drawing-to-your-control.md --- # 绘制/绘图到你的控件 ### ICustomControl.Paint方法 这是CustomControl最重要的方法。它告诉窗体引擎你希望如何渲染你的控件。参见[`ICustomControl.Paint`](/official/Reference/CustomControls/Framework/ICustomControl#paint)参考了解宿主端契约。 ::: tip 强烈建议在尝试实现自己的CustomControl之前,先查看并实验twinBASIC提供的示例项目。 ::: ```vb Private Sub OnPaint(ByVal Canvas As CustomControls.Canvas) _ Implements ICustomControl.Paint ``` 你会收到一个[`Canvas`](/official/Reference/CustomControls/Framework/Canvas)对象,它提供以下方法: ```vb Canvas.Width As Long ' Property-Get Canvas.Height As Long ' Property-Get] Canvas.Dpi As Long ' Property-Get] Canvas.DpiScaleFactor As Double ' Property-Get Canvas.AddElement(Descriptor As ElementDescriptor) ``` ::: info 当前框架将这些成员拼写为[`RuntimeUICCGetWidth`](/official/Reference/CustomControls/Framework/Canvas#runtimeuiccgetwidth)、[`RuntimeUICCGetHeight`](/official/Reference/CustomControls/Framework/Canvas#runtimeuiccgetheight)、[`RuntimeUICCGetDpi`](/official/Reference/CustomControls/Framework/Canvas#runtimeuiccgetdpi)、[`RuntimeUICCGetDpiScaleFactor`](/official/Reference/CustomControls/Framework/Canvas#runtimeuiccgetdpiscalefactor)和[`RuntimeUICCCanvasAddElement`](/official/Reference/CustomControls/Framework/Canvas#runtimeuicccanvasaddelement)。上面显示的较短名称是API最初起草时的名称;底层行为是相同的。 ::: `Canvas.Width` 和 `Canvas.Height` 是你的控件正在绘制的绝对像素大小。与你控件未经DPI缩放的Width/Height属性不同,`Canvas.Width` 和 `Canvas.Height` 的值**已经过**DPI缩放。 `Canvas.Dpi` 属性表示Windows中的DPI设置。如果没有DPI缩放生效,此值为96。例如,如果你的显示器缩放设置为150%,则 `Canvas.Dpi` 属性将为144。 `Canvas.DpiScaleFactor` 属性给出表示DPI缩放百分比的浮点值。值为1表示无缩放。例如,如果你的显示器缩放设置为150%,则 `Canvas.DpiScaleFactor` 属性将为1.5。 `Canvas.AddElement` 方法用于向你的控件添加元素。*元素*被认为是窗体引擎将为你渲染的内容。例如,你可能有一个一次显示100个单元格的网格控件。每个单元格就是一个*元素*。元素可以相互重叠(允许不透明度/透明度)。窗体引擎按你调用AddElement的顺序绘制它们,这意味着最后添加的元素具有最高的z序。 *** ### AddElement(ElementDescriptor) AddElement方法接受一个参数;ElementDescriptor。ElementDescriptor是一个UDT,精确定义了元素的绘制方式以及它如何响应鼠标点击等事件。 ```vb Public Type ElementDescriptor OnClick As LongPtr ' event function callback pointer OnDblClick As LongPtr ' event function callback pointer OnMouseDown As LongPtr ' event function callback pointer OnMouseUp As LongPtr ' event function callback pointer OnMouseEnter As LongPtr ' event function callback pointer OnMouseLeave As LongPtr ' event function callback pointer OnMouseMove As LongPtr ' event function callback pointer OnScrollH As LongPtr ' event function callback pointer OnScrollV As LongPtr ' event function callback pointer Left As Long ' pixel offset (control relative, DPI scaled) Top As Long ' pixel offset (control relative, DPI scaled) Width As Long ' pixel width (DPI scaled) Height As Long ' pixel width (DPI scaled) Cursor As MousePointerConstants ' cursor/pointer icon TrackingIdX As LongLong ' for tracking this element, passed to events TrackingIdY As LongLong ' for tracking this element, passed to events Text As String ' the text to render TextRenderingOptions As TextRendering ' options to customize text rendering (object) BackgroundFill As Fill ' options to customize back fill rendering (object) Corners As Corners ' options to customize corner rendering (object) Borders As Borders ' options to customize border rendering (object) End Type ``` *** ### 提示 * 每次OnPaint方法被调用时,你从一块空白画布开始。 * Left/Top/Width/Height可以合法地位于画布区域之外。例如,负的Left/Top,或超过Canvas.Width/Canvas.Height的Width/Height不会有不良影响。窗体引擎会为你适当地裁剪所有内容,使得控件设计更加简单。 * 你应该考虑使Paint例程高效。尽量避免实例化COM对象,在绘制多个相似元素时,尝试通过在循环外设置公共属性来重用ElementDescriptor(参见WaynesGrid的示例) * 当控件内有多个元素时,TrackingIdX和TrackingIdY很重要。这两个值组合时应唯一表示该元素,并且在Paint例程再次被调用时必须保持不变。这是支持事件所需的。例如,在网格控件中,每个单元格都有一个与单元格X/Y坐标关联的TrackingIdX/TrackingIdY值。 * 目前仅提供鼠标事件,但焦点事件和键盘事件即将推出。 * 你可以通过简单地使用 `AddressOf MyEvent` 来使用基于类的事件处理程序,现在甚至可以在类成员上使用。你可以在示例中看到这种用法,如WaynesGrid。所有鼠标事件具有以下格式: ```vb Class MyCustomControl '... Private Sub MyClickEvent(ByRef EventInfo As MouseEvent) MsgBox "You clicked me!" End Sub Private Sub OnPaint(ByVal Canvas As CustomControls.Canvas) _ Implements ICustomControl.Paint Dim MyDescriptor As ElementDescriptor MyDescriptor.OnClick = AddressOf MyClickEvent End Sub ``` EventInfo(MouseEvent)提供鼠标信息,如鼠标的相对X/Y位置,以及前面讨论的TrackingX/Y值。 * 当你调用Canvas.AddElement时,你的元素进入渲染管线。它**不会**立即绘制到屏幕上。渲染管线会与你在上次OnPaint调用中提供的上一个渲染管线进行比较,tB窗体引擎只会重绘控件中已更改的区域。这使得控件绘制高效,同时无需关心如何进行局部重绘的细节。 *** ## 另见 * [`ICustomControl`](/official/Reference/CustomControls/Framework/ICustomControl) —— 每个自定义控件实现的接口 * [`Canvas`](/official/Reference/CustomControls/Framework/Canvas) —— 传递给**Paint**的绘图面 * `ElementDescriptor` 的 `BackgroundFill` / `Borders` / `Corners` / `TextRenderingOptions` 字段使用的样式辅助工具:[`Fill`](/official/Reference/CustomControls/Styles/Fill)、[`Borders`](/official/Reference/CustomControls/Styles/Borders)、[`Corners`](/official/Reference/CustomControls/Styles/Corners)、[`TextRendering`](/official/Reference/CustomControls/Styles/TextRendering) * [CustomControls包参考](/official/Reference/CustomControls/) —— 框架和内置 `Waynes…` 控件的概述(其中多个——`WaynesGrid`、`WaynesButton`、……——正是上面提到的工作示例) --- --- url: /zh/start/base.md --- # 基础入门 一些简单的入门知识点 ## 设置中文语言界面 默认是英文语言,可以在菜单设置为中文: ![设置中文语言界面](/images/base/language.png) ## 设置 暗黑/蓝白 主题 默认是暗黑主题,可以在菜单设置为蓝白经典主题: ![设置主题](/images/base/classTheme.png) ## 修改软件的图标 看图设置软件编译后的图标,删掉这个默认图片,替换为你自己的就行 ![设置中文语言界面](/images/base/icon.jpg) ## 编译程序 在按钮栏点击这个按钮即可编译,注意切换 win32/win64 ![设置中文语言界面](/images/base/build.png) 编译完毕后可以在控制台看到输出,点击可以运行或者打开目录 ![设置中文语言界面](/images/base/build2.png) --- --- url: /zh/official/Features/Language/Inheritance.md --- # 继承 twinBASIC 提供了几种继承机制以支持简单和完整的面向对象编程模式:**Implements**、**Implements Via** 和 **Inherits**。 ## **Implements** 的增强 twinBASIC 中的 `Implements` 有多项增强: ### 继承的接口 twinBASIC 中的 `Implements` 允许用于继承的接口——例如,如果你有 `Interface IFoo2 Extends IFoo`,然后在类中使用 `Implements IFoo2`,而在 VBx 中这是不允许的。你需要为所有继承的接口(除 `IDispatch` 和 `IUnknown` 外)提供方法。类将标记所有接口为可用——你不需要为 `IFoo` 写单独的语句,它会通过 `Set` 语句(及其底层的 `QueryInterface` 调用)自动传递。 ### 多重实现 如果你有一个被多个其他接口继承的接口,你可以编写多个实现,或为所有接口指定一个实现。例如: ```vb IOleWindow_GetWindow() As LongPtr _ Implements IOleWindow.GetWindow, IShellBrowser.GetWindow, IShellView2.GetWindow ``` ### 接口中的 'As Any' 参数 `Implements` 允许用于包含 'As Any' 参数的接口:在 VBx 中,如果你尝试使用任何包含 `As Any` 参数成员的接口会报错。在 twinBASIC 中,如果你用 `As LongPtr` 替代 `As Any`,这是允许的,例如: ```vb Interface IFoo Extends IUnknown Sub Bar(ppv As Any) End Interface Class MyClass Implements IFoo Private Sub IFoo_Bar(ppv As LongPtr) Implements IFoo.Bar End Sub ``` ## **Implements Via** 实现基本继承 tB 允许类之间的简单继承。例如,如果你有一个实现了 IVehicle(包含方法 Honk)的类 cVehicle,你可以创建子类如 cCar 或 cTruck,继承原始类的方法,这样你可以调用 cCar.Honk 而无需编写单独的实现。 ![image](/assets/b0724fe2-636d-47db-a8fc-531a585ddaf9.BDt0t_fJ.png) 你可以看到 Honk 方法只由父类实现,然后在你点击 CodeLens 按钮从 IDE 中就地运行 Sub 时从子类调用。 ## **Inherits** 实现完整 OOP 此选项支持完整的继承和 OOP:派生类可访问(但外部调用者不可)的 `Protected` 方法和变量、`Overridable` 和 `Overrides` 语法、多重继承以及显式基类构造函数。 ### 示例:Animal 类层次 从基类开始: ```vb Private Class Animal Protected _name As String Protected _dob As Date ' date of birth Public Event Spoke(ByVal sound As String) Public Sub New(name As String, dob As Date) _name = name _dob = dob End Sub Public Property Get Name() As String Name = _name End Property Public Property Get DOB() As Date DOB = _dob End Property ' Age in whole years based on DOB and today's date Public Function AgeYears() As Long Dim y As Long y = DateDiff("yyyy", _dob, Date) If DateSerial(Year(Date), Month(_dob), Day(_dob)) > Date Then y = y - 1 AgeYears = y End Function Public Sub Speak() Dim s As String s = GetSound() RaiseEvent Spoke(s) Debug.Print _name & " says: " & s End Sub ' --- Overridable hook for derived classes --- Protected Overridable Function GetSound() As String GetSound = "" End Function End Class ``` 其他类可以继承: ```vb ' ===== Derived: Dog ===== Private Class Dog Inherits Animal Protected _breed As String Public Sub New(name As String, dob As Date, breed As String) Animal.New(name, dob) ' we can explicitly call base constructors from within our constructor _breed = breed End Sub Public Property Get Breed() As String Breed = _breed End Property ' Override: Protected Overridable Function GetSound() As String Overrides Animal.GetSound GetSound = "woof" End Function End Class ' ===== Further derived: GuardDog (Dog → GuardDog) ===== Private Class GuardDog Inherits Dog Protected _onDuty As Boolean Public Sub New(name As String, dob As Date, breed As String) Dog.New(name, dob, breed) ' we can explicitly call base constructors from within our constructor _onDuty = True End Sub Public Property Get OnDuty() As Boolean OnDuty = _onDuty End Property Public Property Let OnDuty(ByVal v As Boolean) _onDuty = v End Property ' Multi-level override (overriding Dog's override): Protected Function GetSound() As String Overrides Dog.GetSound If _onDuty Then GetSound = "WOOF!" Else GetSound = "woof" End If End Function End Class ``` 这只是摘录,完整的示例 23 中有更多类、用法和关于 twinBASIC 中继承的说明。 --- --- url: /zh/official/IDE/Watches.md --- # 监视 未打开项目时此面板为空。 ![监视](Images/Watches.png "监视") 打开项目后会有其他按钮可用。 ![监视](Images/Watches_1.png "监视") 要添加新的监视,点击 ![添加](Images/Add.png "添加") 并输入要监视的"表达式"。 ![监视](/assets/Watches_2.BtwK8Y06.png "监视") 可以使用清除按钮 ![清除](Images/Clear.png "清除") 移除任意监视。 --- --- url: /zh/official/Tutorials.md --- # 教程 教程是针对特定主题的分步指南。关于语言构造的分类参考,请参见[参考部分](/official/Reference/);关于特性概览,请参见[特性](/official/Features/)。 **基础篇:** * [**Hello World**](/official/Tutorials/Hello-World) —— 创建一个标准EXE项目,在窗体上放置一个按钮,运行你的第一个twinBASIC应用程序。无需任何经验。 * [**窗体基础**](/official/Tutorials/Forms) —— 向窗体添加控件、命名约定、属性窗口、常见事件以及运行时与设计时属性更改。构建一个温度转换器。 * [**调用Windows API**](/official/Tutorials/Windows-API) —— 编写 `Declare` 语句、使用 `PtrSafe` 和 `LongPtr` 处理32/64位兼容性、读取错误信息。实时跟踪鼠标光标位置。 * [**使用Assert编写单元测试**](/official/Tutorials/Testing-with-Assert) —— **Assert**包的三个模块、测试Sub模式、从CodeLens条或F5运行、测试错误路径。 **参考主题:** * [**数组**](/official/Tutorials/Arrays) —— 固定数组和动态数组、`Dim` 和 `ReDim`、边界和多维结构。无需任何twinBASIC经验。 **控件与浏览器嵌入:** * [**CustomControls**](/official/Tutorials/CustomControls/) —— 使用 `Waynes…` 框架构建自绘控件:绘制、事件处理、属性表和DESIGNER设计面。 * [**WebView2**](/official/Tutorials/WebView2/) —— 在窗体中嵌入Microsoft Edge运行时:本地资源托管、JavaScript互操作、消息交换和Monaco编辑器案例。 * [**CEF**](/official/Tutorials/CEF/) —— 在窗体中嵌入Chromium:与WebView2相同的模式,但使用开发者控制的浏览器运行时,随应用程序一起发布。 --- --- url: /zh/official/Features/Language/Interfaces-CoClasses.md --- # 接口、CoClass 和别名 twinBASIC 将这些功能作为原生语言语法支持,而在 VBx 中它们只能通过类型库支持。 ## 定义接口 twinBASIC 支持使用 BASIC 语法定义 COM 接口,而不需要使用 IDL 和 C++ 的类型库。这些只在 .twin 文件中支持,不支持在遗留的 .bas 或 .cls 文件中。它们必须出现在 `Class` 或 `Module` 语句*之前*,并且始终具有项目范围的可见性。通用形式如下: ```vb [InterfaceId ("00000000-0000-0000-0000-000000000000")] '*<attributes>* Interface name Extends base_interface '*<attributes>* '<method 1> '*<attributes>* '<method 2> '... End Interface ``` 方法可以是以下任意一种:`Sub`、`Function`、`Property Get`、`Property Let` 或 `Property Set`,参数遵循标准语法,可使用标准特性。这些不能用 `Public/Private/Friend` 修饰。不使用 `End <method>`,因为这些只是原型定义。 ### 接口的可用特性 * `[Description("text")]` - 在信息弹窗中提供描述,并作为 `helpstring` 属性导出到类型库(如适用)。 * `[Hidden]` - 从某些 Intellisense 和其他列表中隐藏接口。 * `[Restricted]` - 限制接口方法在大多数上下文中被调用。 * `[OleAutomation(True/False)]` - 控制是否在类型库中应用此属性。默认为 **True**。 * `[ComImport]` - 指定接口是从外部 COM 库导入的,例如 Windows shell。 * `[ComExtensible(True/False)]` - 指定运行时添加的新成员是否可以通过实现 IDispatch 的接口按名称调用。默认为 **False**。 ### 方法的可用特性 * `[Description("text")]` - 提供描述 * `[PreserveSig]` - 对于 COM 接口,通常方法返回 HRESULT,语言会隐藏它。`[PreserveSig]` 属性覆盖此行为并完全按你提供的方式定义函数。如果你需要定义返回值不是 4 字节 `Long`,或者想自己处理结果(绕过返回值为负时引发的正常运行时错误),这是必要的(当负值表示预期的可接受失败而非真正的错误时很有用,如枚举接口没有更多项时)。 * `[DispId(number)]` - 定义与方法关联的调度 ID。 ### 示例 ```vb [InterfaceId("E7064791-0E4A-425B-8C8F-08802AAFEE61")] [Description("Defines the IFoo interface")] [OleAutomation(False)] Interface IFoo Extends IUnknown Sub MySub(Arg1 As Long) Function Clone() As IFoo [PreserveSig] Function MyFunc([TypeHint(MyEnum)] Arg1 As Variant) As Boolean End Interface ``` (其中 MyEnum 是标准的 `Enum ... End Enum` 块。) ## 定义 CoClass 除了接口外,twinBASIC 还允许定义 coclass——实现一个或多个已定义接口的可创建类。与接口一样,这些也必须在 .twin 文件中而非遗留的 .bas/.cls 文件中,且必须出现在 `Class` 或 `Module` 语句之前。通用形式为: ```vb [CoClassId("00000000-0000-0000-0000-000000000000")] '<attributes> CoClass name [Default] Interface interface_name [Default, Source] Interface event_interface_name 'additional Interface items> End CoClass ``` 每个 coclass 必须至少指定一个接口,但可以有多个。可以可选地将接口标记为默认或源。通常强烈建议将接口标记为 `[Default]` 属性,在有事件的情况下还应指定 `[Default, Source]` 以指示用于事件的默认接口。每个接口代表一个契约,类将提供该接口的实现。注意,目前 twinBASIC 尚不支持定义 `dispinterface` 接口(即仅调度的接口),这是事件源接口的常见形式。 ### CoClass 的特性 * `[Description("text")]` - 在信息弹窗和其他地方提供描述。 * `[ComCreatable(True/False)]` - 指示此 coclass 可以使用 `New` 关键字创建。默认为 *True*。 * `[AppObject]` - 指示类是全局命名空间的一部分。不应在不完全理解其含义的情况下包含此属性。 * `[Hidden]` - 隐藏 coclass 使其不出现在某些地方。 * `[CoClassCustomConstructor("factory method 的完全限定路径")]` - 允许自定义逻辑来创建和返回 coclass 实现的新实例。 ### 示例 ```vb [CoClassId("52112FA1-FBE4-11CA-B5DD-0020AFE7292D")] CoClass Foo [Default] Interface IFoo Interface IBar End CoClass ``` 其中 `IFoo` 和 `IBar` 是使用前面描述的 `Interface` 语法定义的接口。 ## 自定义构造函数示例 ```vb [InterfaceId("016BC30A-A8E0-4AAF-93AE-13BD838A149E")] Public Interface IFoo Sub Foo() End Interface [InterfaceId("2A20E655-30A4-4534-86BC-6A7E281C425D")] Public Interface IBar Sub Bar() End Interface [CoClassId("7980D953-10BF-478C-93BB-DD0093315D96")] [CoClassCustomConstructor("FooFactory.CreateFoo")] [COMCreatable(True)] Public CoClass Foo [Default] Interface IFoo Interface IBar End CoClass ' The implementation do not have to be exposed. The coclass is a sufficient description ' and we should implement the interfaces that the coclass exposes. Private Class FooImpl Implements IFoo Implements IBar Public Sub Foo() Implements IFoo.Foo Debug.Print "Foo ran" End Sub Public Sub Bar() Implements IBar.Bar Debug.Print "Bar ran" End Sub End Class Public Module FooFactory ' The signature must be "preserved", returning a HRESULT ' and the new instance via the "out" parameter. ' Note that we new up the FooImpl but return the Foo coclass. Public Function CreateFoo(ByRef RHS As Foo) As Long Set RHS = New FooImpl Return 0 ' S_OK End Function End Module Public Module Test Public Sub DoIt() Dim MyFoo As Foo ' create a new instance of coclass Foo ' this implicilty calls the custom constructor ' in the FooFactory. Set MyFoo = New Foo MyFoo.Foo End Sub End Module ``` --- --- url: /zh/packages/vbccr/ranges/progressbar.md description: 进度条控件(ProgressBar) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 进度条控件(ProgressBar) 封装 msctls\_progress32 系统进度条控件,用于显示操作进度,支持标准、平滑、跑马灯等滚动模式及任务栏进度显示。 ## 枚举 ### PrbOrientationConstants | 常量 | 值 | 说明 | |------|-----|------| | PrbOrientationHorizontal | 0 | 水平方向 | | PrbOrientationVertical | 1 | 垂直方向 | ### PrbScrollingConstants | 常量 | 值 | 说明 | |------|-----|------| | PrbScrollingStandard | 0 | 标准模式 | | PrbScrollingSmooth | 1 | 平滑滚动 | | PrbScrollingMarquee | 2 | 跑马灯模式 | ### PrbStateConstants | 常量 | 值 | 说明 | |------|-----|------| | PrbStateNormal | 1 | 正常状态 | | PrbStateError | 2 | 错误状态(红色) | | PrbStatePaused | 3 | 暂停状态(黄色) | ### CCMousePointerConstants 参见通用枚举。 ## 属性 ### Min ```vb Property Get Min() As Long Property Let Min(ByVal Value As Long) ``` 最小值。 ### Max ```vb Property Get Max() As Long Property Let Max(ByVal Value As Long) ``` 最大值。 ### Value ```vb Property Get Value() As Long Property Let Value(ByVal Value As Long) ``` 当前值。 ### Step ```vb Property Get Step() As Long Property Let Step(ByVal Value As Long) ``` 步进增量。 ### StepAutoReset ```vb Property Get StepAutoReset() As Boolean Property Let StepAutoReset(ByVal Value As Boolean) ``` StepIt 到达最大值时是否自动重置为最小值。 ### MarqueeAnimation ```vb Property Get MarqueeAnimation() As Boolean Property Let MarqueeAnimation(ByVal Value As Boolean) ``` 是否启用跑马灯动画。仅在 Scrolling 为 PrbScrollingMarquee 时有效。 ### MarqueeSpeed ```vb Property Get MarqueeSpeed() As Long Property Let MarqueeSpeed(ByVal Value As Long) ``` 跑马灯动画速度(毫秒)。仅在 Scrolling 为 PrbScrollingMarquee 时有效。 ### Orientation ```vb Property Get Orientation() As PrbOrientationConstants Property Let Orientation(ByVal Value As PrbOrientationConstants) ``` 进度条方向。 ### Scrolling ```vb Property Get Scrolling() As PrbScrollingConstants Property Let Scrolling(ByVal Value As PrbScrollingConstants) ``` 滚动模式。 ### SmoothReverse ```vb Property Get SmoothReverse() As Boolean Property Let SmoothReverse(ByVal Value As Boolean) ``` 是否启用平滑反转效果。需要 comctl32.dll 6.0 或更高版本。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景颜色。 ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景颜色。 ### State ```vb Property Get State() As PrbStateConstants Property Let State(ByVal Value As PrbStateConstants) ``` 进度条状态(正常/错误/暂停)。 ### ShowInTaskBar ```vb Property Get ShowInTaskBar() As Boolean Property Let ShowInTaskBar(ByVal Value As Boolean) ``` 是否在任务栏上显示进度。需要 Windows 7 或更高版本。 ### Text ```vb Property Get Text() As String Property Let Text(ByVal Value As String) ``` 覆盖在进度条上的文本,支持占位符:`{0}` 为当前值,`{1}` 为最小值,`{2}` 为最大值,`{3}` 为百分比值。 ### TextColor ```vb Property Get TextColor() As OLE_COLOR Property Let TextColor(ByVal Value As OLE_COLOR) ``` 覆盖文本的颜色。 ### BorderStyle ```vb Property Get BorderStyle() As Integer Property Let BorderStyle(ByVal Value As Integer) ``` 边框样式(vbBSNone 或 vbFixedSingle)。 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 进度条控件的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 用户控件的窗口句柄。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针样式。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 是否启用鼠标进入/离开跟踪。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` 帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "这是什么"帮助 ID。 ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` 拖拽图标。 ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` 拖拽模式。 ## 方法 ### StepIt ```vb Public Sub StepIt() ``` 按 Step 属性指定的增量推进当前位置。 ### Increment ```vb Public Sub Increment(ByVal Delta As Long) ``` 按指定增量推进当前位置。 ### Drag ```vb Public Sub Drag([ByRef Action As Variant]) ``` 开始、结束或取消拖放操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移至控件。 ### ZOrder ```vb Public Sub ZOrder([ByRef Position As Variant]) ``` 设置控件的 Z 顺序。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放操作。 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘控件。 ## 事件 ### Change ```vb Public Event Change() ``` Value 属性值发生改变时触发。 ### Click ```vb Public Event Click() ``` 单击控件时触发。 ### DblClick ```vb Public Event DblClick() ``` 双击控件时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件时触发。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下按键时触发。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放按键时触发。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按键字符输入时触发。 ## 代码示例 ```vb ' 标准进度条 ProgressBar1.Min = 0 ProgressBar1.Max = 100 ProgressBar1.Value = 0 ProgressBar1.Step = 10 ProgressBar1.StepIt ' 带文本覆盖的进度条 ProgressBar1.Min = 0 ProgressBar1.Max = 1000 ProgressBar1.Text = "正在处理 {3}%" ProgressBar1.TextColor = vbWhite ' 跑马灯模式(不确定进度) ProgressBar1.Scrolling = PrbScrollingMarquee ProgressBar1.MarqueeAnimation = True ProgressBar1.MarqueeSpeed = 30 ' 任务栏进度显示(Windows 7+) ProgressBar1.ShowInTaskBar = True ProgressBar1.State = PrbStateNormal ``` --- --- url: /zh/official/Features/Advanced/Static-Linking.md --- # OBJ 和 LIB 文件的静态链接 tB 允许你使用正确编译的 .lib 和 .obj 文件作为静态链接库,使用类似于 DLL 的声明,只需在项目的"杂项文件"文件夹中引用 lib/obj 文件。文件加入项目后,在声明外部使用以下语法进行配置。 ## 示例 来自 sqlite 示例的用法: ```vb #If Win64 Then Import Library "/Miscellaneous/sqlite3_64.obj" As SQLITE3 Link "stdlib", "kernel32" #Else Import Library "/Miscellaneous/sqlite3_32.obj" As SQLITE3 Link "stdlib", "kernel32" #End If ``` ### 通用语法 ```vb Import Libary "Relative resource path" As NAMESPACE Link "dependency1", "dependency2", '... ``` ## 使用导入的库 之后,你可以在类/模块声明中使用 NAMESPACE 代替 DLL 名称: ```vb ' Compiled sqlite-amalgamation-3440200 (v3.44.2) ' using cmdline (MSVC): cl /c /Gw /Gy /GS- /DSQLITE_OMIT_SEH sqlite3.c #If Win64 Then Import Library "/Miscellaneous/sqlite3_64.obj" As SQLITE3 Link "stdlib", "kernel32" #Else Import Library "/Miscellaneous/sqlite3_32.obj" As SQLITE3 Link "stdlib", "kernel32" #End If Module MainModule Declare PtrSafe Function sqlite3_open CDecl Lib SQLITE3 (ByVal filename As String, ByRef ppDb As LongPtr) As Long Declare PtrSafe Function sqlite3_exec CDecl Lib SQLITE3 (ByVal pDb As LongPtr, ByVal sql As String, ByVal exec_callback As LongPtr, ByVal udp As LongPtr, ByRef errmsg As LongPtr) As Long '... ``` ::: info StdCall 名称会使用参数大小进行修饰,例如 `int myfunc(int x, short y);` 会变成 `myfunc@6`。因此使用 `CDecl` 可能更好。 ::: --- --- url: /zh/official/Reference/Controls.md --- # 控件 twinBASIC附带的标准UI控件类位于**VB**内置包中 --- 参见[VB包](/official/Reference/VB/)的包主页。以下控件按用途分组;每个条目链接到对应类的参考页。 ## 窗体和宿主类 这些类是*容器*而非严格意义上的控件 --- 它们承载其他控件,并支撑IDE中的窗体/控件设计器。 * [Form](/official/Reference/VB/Form/) -- 承载控件、菜单和绘图表面的顶级窗口。 * [MDIForm](/official/Reference/VB/MDIForm/) -- 顶级MDI父窗口,在凹陷的客户区内承载MDI子[Form](/official/Reference/VB/Form/)实例。 * [UserControl](/official/Reference/VB/UserControl/) -- 用于在twinBASIC中设计可重用ActiveX控件的基类。 * [PropertyPage](/official/Reference/VB/PropertyPage/) -- 支撑COM属性页对话框单个标签页的容器(ActiveX控件属性浏览器上的\*\*(Custom)\*\*弹出页)。 * [Report](/official/Reference/VB/Report/) -- 专用于带状报表布局、打印预览和打印的顶级窗口。 ## 按钮和切换 * [CommandButton](/official/Reference/VB/CommandButton/) -- 用于触发操作的按钮。 * [CheckBox](/official/Reference/VB/CheckBox/) -- 两态或三态复选框,带可选文本标题。 * [CheckMark](/official/Reference/VB/CheckMark/) -- 无窗口复选标记,自动缩放填充其矩形区域;无标题,无焦点。 * [OptionButton](/official/Reference/VB/OptionButton/) -- 单选按钮;共享同一容器的单选按钮构成互斥组。 ## 文本和值输入 * [TextBox](/official/Reference/VB/TextBox/) -- 单行或多行编辑控件,可选密码掩码和仅数字输入。 * [ComboBox](/official/Reference/VB/ComboBox/) -- 编辑字段与下拉列表组合的控件。 * [ListBox](/official/Reference/VB/ListBox/) -- 垂直滚动的项目列表,可选多列和多选。 * [HScrollBar](/official/Reference/VB/HScrollBar/) -- 独立的水平滚动条。 * [VScrollBar](/official/Reference/VB/VScrollBar/) -- 独立的垂直滚动条。 ## 文件系统浏览 这三个控件通常连接在一起以构建完整的文件选择器。 * DriveListBox --- 驱动器选择器。*尚未文档化。* * [DirListBox](/official/Reference/VB/DirListBox/) -- 单路径目录树选择器。 * [FileListBox](/official/Reference/VB/FileListBox/) -- 单目录文件列表,可按通配符和文件属性开关进行筛选。 ## 容器 * [Frame](/official/Reference/VB/Frame/) -- 带标题的容器,用于分组相关控件并限定[OptionButton](/official/Reference/VB/OptionButton/)组的范围。 * [MultiFrame](/official/Reference/VB/MultiFrame/) -- 布局容器,将一组[Frame](/official/Reference/VB/Frame/)控件排列成水平或垂直条带。 * [PictureBox](/official/Reference/VB/PictureBox/) -- Win32原生控件,结合了图片显示、绘图表面和子控件容器功能。 ## 仅显示 * [Label](/official/Reference/VB/Label/) -- 无窗口轻量级只读文本显示,用于标题、状态文本和键盘助记符。 * [Image](/official/Reference/VB/Image/) -- 无窗口轻量级图片显示;是[PictureBox](/official/Reference/VB/PictureBox/)的小巧高效替代方案。 * [Line](/official/Reference/VB/Line/) -- 无窗口的两个端点之间的直线。 * [Shape](/official/Reference/VB/Shape/) -- 无窗口几何图元(矩形、椭圆、圆形、星形、箭头等),可配置边框、填充和旋转。 * [QRCode](/official/Reference/VB/QRCode/) -- 无窗口QR码渲染器,从文本或字节数组填充内容。 ## 菜单 * [Menu](/official/Reference/VB/Menu/) -- Win32原生菜单中的项 --- [Form](/official/Reference/VB/Form/)或[MDIForm](/official/Reference/VB/MDIForm/)菜单栏上的顶级条目、下拉条目或分隔符。 ## 数据和外部内容 * [Data](/official/Reference/VB/Data/) -- Win32原生控件,打开DAO记录集并为绑定控件提供记录导航按钮。 * [OLE](/official/Reference/VB/OLE/) -- 承载链接或嵌入的OLE Automation对象(Word文档、Excel工作表等)的OLE容器。 * [Timer](/official/Reference/VB/Timer/) -- 非可视化控件,按可编程间隔引发周期性事件。 --- --- url: /zh/official/Features/GUI-Components/Anchoring-Docking.md --- # 锚定 twinBASIC 窗体设计器中新增的功能之一是 'Anchors' 属性: ![image](/assets/b26da59b-4e98-40b7-b97b-bb3cef4ca1d0.BcGaGtE1.png) 点击左侧箭头展开后提供 4 个选项: ![image](/assets/d5dff8f5-c5fa-4620-ba11-430d06276b27.DcyU1nFU.png) 这些选项控制每个点相对于父窗体或控件容器的边框的位置在窗体大小改变时是否保持不变。默认行为是符合预期的;上边和左边保持不变,除非你通过代码手动处理(通常在 `Form_Resize` 事件中),否则控件不会随窗体调整大小或移动。锚定提供了自动处理大小和位置调整的替代方案。 如果控件在四个位置都锚定,它将在两个维度上随窗体调整大小: ![image](/assets/fddbffa9-2b71-47f5-b925-e67fc66b9e5c.CQlTnV3s.png) 如你所见,所有锚点都保持与边缘的恒定距离,结果控件被调整了大小。如果只锚定上、左和下,它将只在垂直方向调整大小,不在水平方向调整: ![image](/assets/3fa1cf2b-0af5-44ae-ae6a-3c0662f51f57.DUy7S04c.png) 右边未锚定到边缘,所以它没有随边缘移动。 如果你取消上边和左边的锚定(False)但保持右边和下边的锚定(True),控件将随下边和右边移动: ![image](/assets/0aeb25f6-d864-4ebb-a9f5-bbd7b5d242e8.Cy_MY7WO.png) 控件保持相同大小,因为右边和下边锚定到边缘,它们随窗体移动,结果整个控件被移动了。 ### 控件容器 以上示例说明了直接在窗体上的控件如何工作。但如果控件在 Frame 或其他控件容器中呢?锚点是相对于其父容器的,因此调整窗体大小不会调整或移动 Frame 内部的控件,除非 Frame 也以改变其大小/位置的方式锚定。 例如,如果一个 TextBox 在四个点都锚定,且位于一个在四个点都锚定的 Frame 中,那么它将随 Frame 调整大小: ![image](/assets/4829696d-788b-40ee-bebd-5afa44477460.BfumJ117.png) 如果我们移除 TextBox 的底部锚定但保留 Frame 的底部锚定,Frame 将沿底部调整大小,但 TextBox 不会: ![image](/assets/bc9f3756-a14b-4ee7-b819-6822497b640a.DIvlgSnZ.png) 使用这 4 个点,你可以自动维持相对大小、位置或两者兼有,而无需手动编写任何代码。 ::: tip 提醒一下,twinBASIC 还为窗体添加了 `MinWidth`、`MinHeight`、`MaxWidth` 和 `MaxHeight` 属性,因此可以与控件锚定结合使用来自动管理。你可能希望设置一个最小尺寸,以免控件消失。 ::: # 停靠 与锚定类似但略有不同,tB 还提供了 'Dock' 属性: ![image](/assets/4c8b881e-1216-4819-a558-d2ce20f47fcd.CdPMi0EK.png) 你可能已经熟悉 StatusBar 控件如何将自己锁定到窗体底部;这就是此属性控制的定位类型。控件可以停靠在任何一边,并保持该边的完整宽度或高度,随窗体或父容器的该边移动。例如,具有 `vbDockBottom` 的 CommandButton: ![image](/assets/599a66ad-31d5-449f-bbf5-00963fe9aa2a.DRatQz3A.png) 除了四个边之外,还有一个最终选项:`vbDockFill`。这将使控件填充其整个父区域。这在使用 PictureBox 或 Frame 等容器控件时最有用——当它作为子控件时,只填充该容器,而不是整个窗体。 `vbDockFill` 会排除其他停靠控件,因此例如你可以有一个 `vbDockRight` 的控件和另一个 `vbDockFill` 的控件,后者覆盖窗体或容器的其余部分,而第一个控件保持在右侧的位置。 ### 多个控件 正如上一节末尾所暗示的,可以将多个控件停靠到同一位置,例如将 CommandButton 和 TextBox 停靠到底部。以下示例还展示了具有 `vbDockRight` + `vbDockFill` 的 PictureBox 控件: ![image](/assets/80185a8d-2952-415f-bc02-ec3ddea89568.BG4-i5TH.png) ::: tip 停靠在同一位置的两个(或多个)控件的顺序由设置先后决定。目前不能拖动重新排列,但你可以将 Dock 属性设回 none,然后按所需顺序重新设置。 ::: --- --- url: /zh/official/Features/GUI-Components/Control-Properties.md --- # 控件属性增强 ## TextBox 增强 * `TextBox.NumbersOnly` 属性:通过在底层控件上设置 `ES_NUMBER` 样式,将输入限制为 0-9。 * `TextBox.TextHint` 属性:在空 TextBox 中设置浅灰色提示文本(`EM_SETCUEBANNER`)。 ## Label 增强 * `Label.VerticalAlignment` 属性:默认为 Top。 * `Label.LineSpacing` 属性(单位为 twip,默认为 0) * `Label.Angle` 属性(单位为度,旋转标签文本) * `Label.BorderCustom` 属性(有子选项可分别为每边设置边框的大小、内边距和颜色)。 ## Timer 增强 `Timer.Interval` 现在可以设置为任意正 `Long` 值,而不再局限于 65,535。 ## 示例 ```vb TextBox1.TextHint = "Enter your name" TextBox1.NumbersOnly = True Label1.Angle = 45 Label1.LineSpacing = 30 Timer1.Interval = 120000 ' 2 minutes; not limited to 65,535 ms ``` --- --- url: /zh/official/Features/GUI-Components/Modernization.md --- # 控件现代化 tB 最终将替换你习惯的所有内置控件,目前可用的有:基本集中的 CommandButton、TextBox、ComboBox、CheckBox、OptionButton、Label、Frame、PictureBox、Line、Shape、VScrollBar、HScrollBar、Timer、DriveListBox、DirListBox、FileListBox、Image 和 Data;以及通用控件中的 ListView、TreeView、ProgressBar、DTPicker、MonthView、Slider 和 UpDown。 ## 主要现代化特性 * **64 位支持**:每个控件都可以同时编译为 32 位和 64 位,无需任何更改。 * **DPI 感知**:当应用程序启用 DPI 感知时,它们会自动正确调整大小。 * **视觉样式**:控件逐个支持视觉样式。可通过 `.VisualStyles` 属性逐个控件地应用或不应用 Comctl6 样式。 ## 未实现控件的替代方案 最佳选择是 Krool 的 VBCCR 和 VBFlexGrid 项目。这些现在可以[从包服务器](/official/Features/Packages/Importing-a-package-from-TWINSERV)获取 x64 兼容版本,并且也是 DPI 感知的,支持视觉样式。 此外,Microsoft 提供的原始 OCX 控件也能正常工作;但它们大多仅支持 32 位。`MSComCtl.ocx` 的 x64 版本不随 Windows 附带,且在法律上不可再分发,但如果你安装了 64 位 Office,它在 tB 中可以使用。 --- --- url: /zh/official/Documentation/Fixes.md --- # 库补丁 若干第三方库包含树内修改。`book/lib/paged.browser.js` 是 paged.js v0.4.3(MIT)的补丁副本;该目录下的十三个 `fast-*.mjs` 文件是应用于 pdf-lib 运行时导出的副作用垫片,在每次 PDF 处理阶段之前生效;`builder/scripts/patch-dagre.mjs` 是一个 `postinstall` 钩子,重写 mermaid 内置的 dagre 适配器以修复每集群布局问题。本节记录了每一处修改:上游行为是什么、为何不适用于构建管线、以及做了哪些改动。 ## 子页面 * [Paged.js 补丁](/official/Documentation/Fixes-PagedJS) --- 对 `book/lib/paged.browser.js` 的修改:同步执行链、钩子分发快速路径、DOM 查找优化、布局正确性修复以及杂项无头浏览器专用变更。 * [pdf-lib 补丁](/official/Documentation/Fixes-PDFLib) --- 十三个 `fast-*.mjs` 垫片和 `parallel-deflate.mjs`,重新调整 pdf-lib 的解析器、对象模型和序列化器以优化处理阶段。 * [Mermaid Dagre 补丁](/official/Documentation/Fixes-Dagre) --- 对 `node_modules/mermaid/dist/chunks/mermaid.esm/dagre-ZXKKJJHT.mjs` 的五处补丁,使 `direction LR` 子图在有跨集群边或无内部边时能正确工作。 > AI生成 --- --- url: /zh/official/Documentation/Extending.md --- # 扩展构建器 如何向 `tbdocs` 添加新的管线阶段或自定义 markdown-it 插件。本指南假定你具备现代 JavaScript(async/await、ES 模块)的工作知识,但不需要了解构建管线内部机制。先阅读[管线阶段](/official/Documentation/Pipeline-Stages)了解每个阶段操作的数据契约。 ## 两个扩展点 **新管线阶段** --- 一个新的 `.mjs` 模块,从 `pages` 数组或 `site` 对象读取数据并向磁盘或页面字段写入输出。该模块导出一个异步函数。`tbdocs.mjs` 中的编排器在固定序列的正确位置调用它。不涉及插件注册表或钩子系统。 **新 markdown-it 插件** --- 一个配置共享 markdown-it 实例以添加额外解析或渲染规则的函数。在 `render.mjs` 内的 `createMarkdownIt` 中注册。阶段 2 的 SEO 标题提取和阶段 3 的正文渲染都使用同一个实例,因此插件在每个页面上运行。 ::: warning 阶段模块的更改不会热重载。编辑阶段模块后,停止并重启 `serve.bat`(Ctrl+C,然后重新运行)以加载更改。 ::: *** ## 添加管线阶段 ### 1. 编写模块 创建 `builder/my-stage.mjs`。导出一个异步函数。标准签名接收 `pages` 数组、`site` 对象和阶段需要的任何额外上下文(通常是 `destRoot`),并返回用于日志记录的统计对象: ```js import { writeFileMkdirp } from "./write.mjs"; import path from "node:path"; export async function myStage(pages, site, destRoot) { const manifest = pages.map((p) => ({ url: p.permalink, title: p.frontmatter.title ?? null, })); const dest = path.join(destRoot, "pages-manifest.json"); await writeFileMkdirp(dest, JSON.stringify(manifest, null, 2)); return { entries: manifest.length }; } ``` 使用 `write.mjs` 导出的 I/O 工具 --- `writeFileMkdirp`、`mkdirRec`、`runLimited`、`safeWrite` --- 而不是原始的 `fs.writeFile` 调用。它们处理目录创建并在错误消息中包含目标路径。 ::: warning 如果阶段写入磁盘,请检查 `opts.dryRun` 并在其为 `true` 时跳过所有文件系统写入。`dryRun` 标志通过编排器接收的同一个 `opts` 对象传递,必须传播到所有 I/O 操作。 ::: 如果阶段向页面对象写入新字段,请在 `runBuild` 中它们首次出现的位置添加,并在[管线阶段](/official/Documentation/Pipeline-Stages#page-objects-pages)的数据模型表中列出,以便其他开发者知道哪个阶段设置了每个字段。 ### 2. 在 `tbdocs.mjs` 中注册阶段 在 `builder/tbdocs.mjs` 顶部添加导入: ```js import { myStage } from "./my-stage.mjs"; ``` 然后在 `runBuild` 中的正确位置调用阶段。大多数辅助阶段属于阶段 5(写入)之后和阶段 7(离线)之前,这样在线树在它们运行时已完成: ```js const myStats = await myStage(pages, site, destRoot); t.lap("my-stage"); if (myStats) { console.log(` my-stage: ${myStats.entries} entries`); } ``` `t.lap("my-stage")` 记录该步骤的墙钟时间;标签出现在构建结束时的时间摘要行中。 ### 3. 处理 `dryRun` 标志 当 `dryRun` 为 `true` 时,阶段应记录它会做什么而不触及文件系统: ```js export async function myStage(pages, site, destRoot, { dryRun = false } = {}) { const manifest = pages.map((p) => ({ url: p.permalink, title: p.frontmatter.title ?? null, })); if (dryRun) { console.log(`[dry-run] my-stage: would write ${manifest.length} entries`); return { entries: manifest.length }; } const dest = path.join(destRoot, "pages-manifest.json"); await writeFileMkdirp(dest, JSON.stringify(manifest, null, 2)); return { entries: manifest.length }; } ``` ### 4. 验证 运行 `build.bat` 并在输出中查找时间标签。然后运行 `check.bat` 确认新输出不会破坏现有链接解析或页面数量守卫。 *** ## 添加 markdown-it 插件 ### 背景 `render.mjs` 中的 `createMarkdownIt` 构建整个管线使用的唯一 markdown-it 实例。它以固定顺序应用 `markdown-it-attrs`、`markdown-it-deflist`、`markdown-it-footnote` 和大约十个树内插件。新插件成为该顺序的一部分。 同一个实例用于阶段 2 的 SEO 标题提取(通过 `renderTitle`)和阶段 3 的正文渲染(通过 `renderPhase`)。更改内联内容渲染方式的插件会影响两个阶段。添加新 token 的块级插件通常只影响阶段 3,因为 `renderTitle` 会剥离所有 HTML。 ### 1. 编写插件 markdown-it 插件是一个接收 `md` 实例(和可选的选项对象)并通过添加规则、覆盖渲染器函数或调整选项来修改它的函数。 **渲染器覆盖示例** --- 将每个 `<table>` 包裹在可滚动容器中: ```js export function tableWrapPlugin(md) { const originalOpen = md.renderer.rules.table_open ?? ((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options)); const originalClose = md.renderer.rules.table_close ?? ((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options)); md.renderer.rules.table_open = (tokens, idx, options, env, self) => '<div class="table-wrapper">' + originalOpen(tokens, idx, options, env, self); md.renderer.rules.table_close = (tokens, idx, options, env, self) => originalClose(tokens, idx, options, env, self) + "</div>"; } ``` **块规则示例** --- 一个发出 `<div class="callout">` 的新围栏语法: ```js export function calloutPlugin(md) { md.block.ruler.before( "fence", "callout", (state, startLine, endLine, silent) => { const pos = state.bMarks[startLine] + state.tShift[startLine]; const max = state.eMarks[startLine]; if (state.src.slice(pos, pos + 3) !== ":::") return false; if (silent) return true; const label = state.src.slice(pos + 3, max).trim(); state .push("callout_open", "div", 1) .attrSet("class", `callout callout-${label}`); state.line = startLine + 1; while (state.line < endLine) { if ( state.src.slice( state.bMarks[state.line] + state.tShift[state.line], state.eMarks[state.line], ) === ":::" ) { state.line++; break; } state.line++; } state.push("callout_close", "div", -1); return true; }, ); } ``` 有关完整的 markdown-it 规则 API --- 块规则、内联规则、核心规则、渲染器规则覆盖 --- 请参阅 [markdown-it 文档](https://markdown-it.github.io/markdown-it/)和 `render.mjs` 中现有的树内插件作为示例。 ### 2. 在 `render.mjs` 中注册 打开 `builder/render.mjs`。在文件顶部(与其他树内插件导入一起)添加导入: ```js import { tableWrapPlugin } from "./table-wrap-plugin.mjs"; ``` 找到 `createMarkdownIt` 并在插件链中添加 `md.use(tableWrapPlugin)`。**顺序很重要** --- 将新插件放在它依赖的插件之后,放在可能与其 token 类型冲突的插件之前: ```js export function createMarkdownIt(ctx) { const md = new MarkdownIt({ ... }); // ... existing npm plugins ... // ... existing in-tree plugins ... md.use(tableWrapPlugin); // new plugin, appended after existing ones return md; } ``` ### 3. 验证 运行 `build.bat` 并在浏览器中打开受影响的页面(或使用 `serve.bat` 进行实时重载)。然后运行 `check.bat` 确认没有链接损坏且构建干净退出。注意控制台输出中阶段 3 的时间 --- 在每个页面上遍历完整 token 流的块规则可能为约 1-2 秒的热路径增加可测量的时间。 *** ## 测试两种扩展类型 对构建器的任何更改都适用相同的四步工作流程: 1. **`build.bat`** --- 运行完整管线;干净退出意味着无构建时错误。 2. **`serve.bat`** --- 实时重载服务器;在浏览器中导航到受影响的页面以发现视觉回归。 3. **`check.bat`** --- 离线链接和完整性检查;捕获更改引入的损坏链接和缺失页面。 4. **`book.bat`** --- 重新运行 PDF 构建;如果阶段或插件影响阶段 8 或 `book.html` 输出则需要。 干净运行全部四步是"准备好提交"的标准。 ::: info `check.bat` 需要先运行 `build.bat`;它从 `_site/` 和 `_site-offline/` 读取。 ::: *** ## 另见 * [管线阶段](/official/Documentation/Pipeline-Stages) -- 每个阶段的完整数据模型和导出引用。 * [tbdocs 构建器](/official/Documentation/Builder) -- 管线的叙述性设计理念。 * [构建与部署](/official/Documentation/Building) -- 内容贡献者的日常构建工作流程。 > AI生成 --- --- url: /zh/official/Features/Advanced/Classes-and-Modules.md --- # 类和模块增强 twinBASIC 为类和模块提供了多项增强。 ## 参数化类构造函数 类现在支持带有参数的 `New` Sub,在类构造时在 `Class_Initialize` 事件之前调用。 ### 示例 例如,一个类可以这样定义: ```vb [ComCreatable(False)] Class MyClass Private MyClassVar As Long Sub New(Value As Long) MyClassVar = Value End Sub End Class ``` 然后通过 `Dim mc As MyClass = New MyClass(123)` 创建,这会在创建时设置 `MyClassVar`。注意:使用此功能的类必须是私有的,具有 `[ComCreatable(False)]` 特性,或同时包含 `Class_Initialize()`。在编译的 OCX 的调用者中,`Class_Initialize()` 将替代 `New`。在项目内部,如果存在 `New` 则只会使用 `New`。 ## 模块和类的 Private/Public 修饰符 私有模块或类的成员不会在 ActiveX 项目中进入类型库。 ## ReadOnly 变量 在类中,模块级变量可以声明为 `ReadOnly`,例如 `Private ReadOnly mStartDate As Date`。这允许更复杂的常量赋值:你可以使用函数返回值来内联设置它,`Private ReadOnly mStartDate As Date = Now()`,或者在 `Class_Initialize` 或 `Sub New(...)` 中设置 `ReadOnly` 常量(参见上面的参数化类构造函数),但在其他所有地方,它们只能读取,不能修改。 ## 导出的函数和变量 可以从标准模块中导出函数或变量,包括使用 CDecl。 ### 示例 ```vb [DllExport] Public Const MyExportedSymbol As Long = &H00000001 [DllExport] Public Function MyExportedFunction(ByVal arg As Long) As Long [DllExport] Public Function MyCDeclExport CDecl(ByVal arg As Long) ``` 这主要用于创建标准 DLL(参见[项目类型](/official/Features/Project-Configuration/Project-Types)),但此功能在标准 EXE 和其他编译项目类型中也可用。 ## 创建不带 IDispatch 的类 默认情况下,编译器在所有 VBx/twinBASIC 类中创建 `IDispatch` 的默认实现。这允许后期绑定和其他功能。但有时你可能想要一个只实现 `IUnknown` 的更受限的类。这在 twinBASIC 中通过 `NotDispatchable` 关键字实现,用法如下: ```vb NotDispatchable Class MyClass '... End Class ``` 使用上述声明后,`MyClass` 将不会实现 `IDispatch`。这意味着它将不适用于后期绑定——即你不能将它用于声明为 `As Object` 的变量。如果你尝试将 `Object`(或 `IDispatch`)变量 `Set` 到此类,将引发 `E_NOINTERFACE` 错误。 --- --- url: /zh/official/Features/Language/Alias-Types.md --- # 类型别名 别名是用户定义类型、内置类型或接口的替代名称。这类似于 C/C++ 的 `typedef` 语句。这些可以用来替代原始类型,并被视为使用了原始类型(不会导致类型不匹配)。 `[Public|Private] Alias AltName As OrigName` ### 示例 对于内置类型,或者如果你有一个类型如: ```vb Public Type POINT x As Long y As Long End Type ``` 你可以创建别名: ```vb Public Alias POINTAPI As POINT Public Alias CBoolean As Byte Public Alias KAFFINITY As LongPtr ``` 与接口和 CoClass 一样,这些必须放在 .twin 文件中,在 `Module` 和 `Class` 块之外。你可以创建其他别名的别名。可选的 `Public` 和 `Private` 修饰符决定别名是否导出到 ActiveX DLL 或控件的类型库中。`Private` 别名将导致使用它时被替换为原始类型。 --- --- url: /zh/official/Features/Language/Type-Inference.md --- # 类型推断 变量现在可以声明为 `As Any`,其类型将被推断,类似于 C++ 的 `auto`。 ## 用法 `Dim x As Any = 5&` 将导致 x 为 `Long`。 ```vb Dim x As Any = 5& ' x is inferred as Long Dim s As Any = "hello" ' s is inferred as String Dim b As Any = True ' b is inferred as Boolean ``` ## 限制 这仅适用于 `Dim` 语句;参数不能为 `As Any`,API 声明除外。 --- --- url: /zh/packages/vbccr/bars/coolbar.md description: 冷却栏控件(CoolBar) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 冷却栏控件(CoolBar) 封装 ReBar 系统控件,实现可拖拽、可调整大小的带状容器栏。 ## 枚举 ### CbrOrientationConstants | 常量 | 值 | 说明 | |------|-----|------| | CbrOrientationHorizontal | 0 | 水平方向 | | CbrOrientationVertical | 1 | 垂直方向 | ### CbrBandStyleConstants | 常量 | 值 | 说明 | |------|-----|------| | CbrBandStyleNormal | 0 | 正常样式,可调整大小 | | CbrBandStyleFixedSize | 1 | 固定大小 | ### CbrBandGripperConstants | 常量 | 值 | 说明 | |------|-----|------| | CbrBandGripperNormal | 0 | 默认抓握条 | | CbrBandGripperAlways | 1 | 始终显示抓握条 | | CbrBandGripperNever | 2 | 不显示抓握条 | ### CbrHitResultConstants | 常量 | 值 | 说明 | |------|-----|------| | CbrHitResultNoWhere | 0 | 空白区域 | | CbrHitResultCaption | 1 | 标题区域 | | CbrHitResultClient | 2 | 客户区 | | CbrHitResultGrabber | 3 | 抓握条 | | CbrHitResultChevron | 4 | 折叠箭头 | | CbrHitResultSplitter | 5 | 分隔条 | ## 属性 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE 拖放模式。参见通用枚举。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示。 ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 从右到左镜像布局。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### ImageList ```vb Property Get ImageList() As Variant Property Let ImageList(ByVal Value As Variant) Property Set ImageList(ByVal Value As Variant) ``` 关联的 ImageList 控件。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景色。 ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 ### BorderStyle ```vb Property Get BorderStyle() As Integer Property Let BorderStyle(ByVal Value As Integer) ``` 边框样式(0-无边框,1-固定单线)。 ### Orientation ```vb Property Get Orientation() As CbrOrientationConstants Property Let Orientation(ByVal Value As CbrOrientationConstants) ``` 方向。 ### BandBorders ```vb Property Get BandBorders() As Boolean Property Let BandBorders(ByVal Value As Boolean) ``` 是否在带之间显示分隔线。 ### FixedOrder ```vb Property Get FixedOrder() As Boolean Property Let FixedOrder(ByVal Value As Boolean) ``` 是否禁止用户重新排列带。 ### VariantHeight ```vb Property Get VariantHeight() As Boolean Property Let VariantHeight(ByVal Value As Boolean) ``` 是否允许带具有不同高度。 ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` 背景图片。 ### DblClickToggle ```vb Property Get DblClickToggle() As Boolean Property Let DblClickToggle(ByVal Value As Boolean) ``` 双击是否切换最大化/最小化。 ### VerticalGripper ```vb Property Get VerticalGripper() As Boolean Property Let VerticalGripper(ByVal Value As Boolean) ``` 垂直方向时是否使用垂直抓握条。 ### ShowTips ```vb Property Get ShowTips() As Boolean Property Let ShowTips(ByVal Value As Boolean) ``` 是否显示工具提示。 ### DoubleBuffer ```vb Property Get DoubleBuffer() As Boolean Property Let DoubleBuffer(ByVal Value As Boolean) ``` 是否启用双缓冲减少闪烁。 ### Bands ```vb Property Get Bands() As CbrBands ``` 带的集合。 ### ContainedControls ```vb Property Get ContainedControls() As VBRUN.ContainedControls ``` 包含的控件集合。只读。 ### RowCount ```vb Property Get RowCount() As Long ``` 行数。只读。 ### hWnd / hWndUserControl / Font 参见公共属性。 ### Name / Tag / Parent / Container / Left / Top / Width / Height / Visible / ToolTipText / WhatsThisHelpID / Align / DragIcon / DragMode 参见标准扩展器属性。 ## 方法 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘。 ### HitTest ```vb Public Function HitTest(ByVal X As Single, ByVal Y As Single, Optional ByRef HitResult As CbrHitResultConstants) As CbrBand ``` 命中测试,返回指定坐标处的带对象。 ### OLEDrag ```vb Public Sub OLEDrag() ``` ### Drag / ZOrder 参见标准方法。 ## 事件 ### Click ```vb Public Event Click() ``` 单击。 ### DblClick ```vb Public Event DblClick() ``` 双击。 ### Resize ```vb Public Event Resize() ``` 大小改变。 ### HeightChanged ```vb Public Event HeightChanged(ByVal NewHeight As Single) ``` 高度改变。 ### LayoutChanged ```vb Public Event LayoutChanged() ``` 布局改变。 ### MinMax ```vb Public Event MinMax(ByRef Cancel As Boolean) ``` 带即将最大化或最小化,可取消。 ### BandBeforeDrag ```vb Public Event BandBeforeDrag(ByVal Band As CbrBand, ByRef Cancel As Boolean) ``` 带即将被拖动,可取消。 ### BandAfterDrag ```vb Public Event BandAfterDrag(ByVal Band As CbrBand, ByVal NewPosition As Long) ``` 带拖动完成。 ### BandChevronPushed ```vb Public Event BandChevronPushed(ByVal Band As CbrBand, ByVal Left As Single, ByVal Top As Single, ByVal Width As Single, ByVal Height As Single) ``` 折叠箭头被点击。 ### BandMouseEnter ```vb Public Event BandMouseEnter(ByVal Band As CbrBand) ``` 鼠标进入带。 ### BandMouseLeave ```vb Public Event BandMouseLeave(ByVal Band As CbrBand) ``` 鼠标离开带。 ### MouseDown / MouseMove / MouseUp / MouseEnter / MouseLeave ### OLECompleteDrag / OLEDragDrop / OLEDragOver / OLEGiveFeedback / OLESetData / OLEStartDrag ## CbrBand 对象 带的属性和方法。 ### 属性 #### Index ```vb Property Get Index() As Long ``` 带在集合中的索引。只读。 #### Key ```vb Property Get Key() As String Property Let Key(ByVal Value As String) ``` 带的关键字。 #### Tag ```vb Property Get Tag() As Variant Property Let Tag(ByVal Value As Variant) Property Set Tag(ByVal Value As Variant) ``` 自定义数据。 #### ID ```vb Property Get ID() As Long ``` 内部标识。只读。 #### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` 带标题。 #### Child ```vb Property Get Child() As Object Property Let Child(ByVal Value As Object) Property Set Child(ByVal Value As Object) ``` 带中包含的子控件。 #### Style ```vb Property Get Style() As CbrBandStyleConstants Property Let Style(ByVal Value As CbrBandStyleConstants) ``` 带样式。 #### Image ```vb Property Get Image() As Variant Property Let Image(ByVal Value As Variant) ``` ImageList 中图像的索引或关键字。 #### ImageIndex ```vb Property Get ImageIndex() As Long ``` 图像索引。只读。 #### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 带宽度。Style 为 FixedSize 时只读。 #### Height ```vb Property Get Height() As Single ``` 带高度。只读。 #### MinWidth ```vb Property Get MinWidth() As Single Property Let MinWidth(ByVal Value As Single) ``` 最小宽度。 #### MinHeight ```vb Property Get MinHeight() As Single Property Let MinHeight(ByVal Value As Single) ``` 最小高度。 #### IdealWidth ```vb Property Get IdealWidth() As Single Property Let IdealWidth(ByVal Value As Single) ``` 理想宽度。 #### Gripper ```vb Property Get Gripper() As CbrBandGripperConstants Property Let Gripper(ByVal Value As CbrBandGripperConstants) ``` 抓握条样式。 #### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。需要 ShowTips 为 True。 #### UseCoolBarPicture ```vb Property Get UseCoolBarPicture() As Boolean Property Let UseCoolBarPicture(ByVal Value As Boolean) ``` 是否使用 CoolBar 的背景图片。 #### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` 带的背景图片。 #### UseCoolBarColors ```vb Property Get UseCoolBarColors() As Boolean Property Let UseCoolBarColors(ByVal Value As Boolean) ``` 是否使用 CoolBar 的前景/背景色。 #### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 带背景色。 #### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 带前景色。 #### NewRow ```vb Property Get NewRow() As Boolean Property Let NewRow(ByVal Value As Boolean) ``` 是否在新行开始。 #### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 #### ChildEdge ```vb Property Get ChildEdge() As Boolean Property Let ChildEdge(ByVal Value As Boolean) ``` 是否在子控件上下显示边缘。 #### UseChevron ```vb Property Get UseChevron() As Boolean Property Let UseChevron(ByVal Value As Boolean) ``` 带宽小于理想宽度时是否显示折叠箭头。 #### HideCaption ```vb Property Get HideCaption() As Boolean Property Let HideCaption(ByVal Value As Boolean) ``` 是否隐藏标题。 #### FixedBackground ```vb Property Get FixedBackground() As Boolean Property Let FixedBackground(ByVal Value As Boolean) ``` 背景图片是否固定不动。 #### Position ```vb Property Get Position() As Long Property Let Position(ByVal Value As Long) ``` 带的位置。 ### 方法 #### Maximize ```vb Public Sub Maximize() ``` 最大化带。 #### Minimize ```vb Public Sub Minimize() ``` 最小化带。 #### PushChevron ```vb Public Sub PushChevron() ``` 程序化点击折叠箭头。 ## CbrBands 集合 带的集合对象。 ### 属性 #### Item ```vb Property Get Item(ByVal Index As Variant) As CbrBand ``` 按索引或关键字获取带。 #### ItemFromPosition ```vb Property Get ItemFromPosition(ByVal Position As Long) As CbrBand ``` 按位置获取带。 #### Count ```vb Property Get Count() As Long ``` 带数量。 ### 方法 #### Add ```vb Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Caption As String, Optional ByVal Image As Variant, Optional ByVal NewRow As Boolean, Optional ByVal Child As Variant, Optional ByVal Visible As Boolean = True) As CbrBand ``` 添加新带。 #### Remove ```vb Public Sub Remove(ByVal Index As Variant) ``` 移除带。 #### Clear ```vb Public Sub Clear() ``` 清空所有带。 #### Exists ```vb Public Function Exists(ByVal Index As Variant) As Boolean ``` 检查带是否存在。 ## CbrBandProperties 对象 带颜色属性的辅助对象。 ### 属性 #### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景色。 #### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 ## 代码示例 ### 基本用法 ```vb ' 添加带 With CoolBar1.Bands .Add Key:="Band1", Caption:="工具栏", NewRow:=True .Add Key:="Band2", Caption:="格式栏" End With ' 设置子控件 Set CoolBar1.Bands("Band1").Child = Toolbar1 ' 设置带属性 CoolBar1.Bands(1).UseChevron = True CoolBar1.Bands(1).IdealWidth = 500 ``` ### 命中测试 ```vb Private Sub CoolBar1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) Dim HitResult As CbrHitResultConstants Dim Band As CbrBand Set Band = CoolBar1.HitTest(X, Y, HitResult) If Not Band Is Nothing Then Debug.Print "点击了: " & Band.Caption End If End Sub ``` ### 折叠箭头事件 ```vb Private Sub CoolBar1_BandChevronPushed(ByVal Band As CbrBand, _ ByVal Left As Single, ByVal Top As Single, _ ByVal Width As Single, ByVal Height As Single) ' 在折叠箭头位置显示菜单 PopupMenu mnuToolbar, , Left, Top + Height End Sub ``` --- --- url: /zh/official/IDE/History.md --- # 历史记录 未打开项目时此面板为空。 ![历史记录](Images/History.png "历史记录") 打开项目后 ![历史记录](Images/History_1.png "历史记录") 将鼠标悬停在条目上会显示文件路径。 ![历史记录](/assets/History_2.CRqTgq_7.png "历史记录") 如果是代码文件(如 `.twin`),还会显示"行号: #"。 ![历史记录](/assets/History_3.B5Ldrdm9.png "历史记录") 点击条目即可打开对应文件。 --- --- url: /zh/official/Features/Packages/Linked-Packages.md --- # 链接包 除了本节到目前为止描述的标准用法外,包还可以被**链接**。当包被链接时,它不会嵌入在 .twinproj 文件中——而是存储在所有项目都可以访问的公共位置。这有多个好处。有些包非常大,不在每个 .twinproj 文件中存储副本使它们更容易共享。此外,它允许多个项目共享相同文件,至少以只读形式。虽然内置编译器包是链接的,但本文讨论的是第三方包。 ## 首次下载包 当你首次在当前机器上勾选某个包时,它默认是**Embedded**。你会在包名称旁边看到一列名为 Embedded: 取消勾选 Embedded 列,它将被转换为链接包。该包的 .twinpack 文件会创建在 `%APPDATA%\Roaming\twinBASIC\packages`,在那里它可以跨 tB IDE 更新保持可用。 ## 添加已链接的包 一旦你在一个项目中执行了上述步骤,链接包就可以被所有项目使用。你通过 Available Packages 以相同方式添加引用,只是现在你会被提示选择使用系统上已有的链接版本,还是从 TWINSERV 重新下载: 此提示提供了两个版本的版本号,允许在需要时更新包。如果你选择重新下载,你需要再次取消勾选 Embed 以保持为链接包。这样做时,你会被提示确认要用从包服务器新下载的版本覆盖本地链接副本: ## 打开缺少链接包的项目 有时你可能想打开一个引用了你当前没有副本的链接包的 .twinproj。如果发生这种情况,你会看到标准的缺少引用提示: 处理方式相同。**取消勾选引用**——"Fix" 目前尚未实现。然后,转到 Available Packages 选项卡并选择该包——如上所述,取消勾选 Embed 以转换为链接包。 ## 手动管理 你可以通过链接包文件夹手动管理包:`%APPDATA%\Roaming\twinBASIC\packages` 你可以使包可用、删除它们、备份它们等。如果你将 .twinpack 文件(或 .twinproj)复制到该位置,它将作为链接包可用,无需从包服务器下载。它不需要存在于服务器上,允许完全私有的本地链接包。 --- --- url: /zh/packages/vbccr/text/linklabel.md description: 链接标签控件(LinkLabel) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 链接标签控件(LinkLabel) 增强型链接标签控件,支持超链接显示和自定义链接集合。 ## 枚举 ### LlbLinkBehaviorConstants | 常量 | 值 | 说明 | |------|-----|------| | LlbLinkBehaviorSystemDefault | 0 | 系统默认 | | LlbLinkBehaviorAlwaysUnderline | 1 | 始终下划线 | | LlbLinkBehaviorHoverUnderline | 2 | 悬停下划线 | | LlbLinkBehaviorNeverUnderline | 3 | 从不下划线 | ### CCAppearanceConstants 参见通用枚举。 ### CCBorderStyleConstants 参见通用枚举。 ### CCBackStyleConstants 参见通用枚举。 ### CCMousePointerConstants 参见通用枚举。 ### CCVerticalAlignmentConstants 参见通用枚举。 ### CCRightToLeftModeConstants 参见通用枚举。 ## 属性 ### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` 显示文本。 ### ActiveLinkColor ```vb Property Get ActiveLinkColor() As OLE_COLOR Property Let ActiveLinkColor(ByVal Value As OLE_COLOR) ``` 活动链接颜色。 ### LinkColor ```vb Property Get LinkColor() As OLE_COLOR Property Let LinkColor(ByVal Value As OLE_COLOR) ``` 链接颜色。 ### VisitedLinkColor ```vb Property Get VisitedLinkColor() As OLE_COLOR Property Let VisitedLinkColor(ByVal Value As OLE_COLOR) ``` 已访问链接颜色。 ### DisabledLinkColor ```vb Property Get DisabledLinkColor() As OLE_COLOR Property Let DisabledLinkColor(ByVal Value As OLE_COLOR) ``` 禁用链接颜色。 ### LinkBehavior ```vb Property Get LinkBehavior() As LlbLinkBehaviorConstants Property Let LinkBehavior(ByVal Value As LlbLinkBehaviorConstants) ``` 链接行为样式。 ### Text ```vb Property Get Text() As String Property Let Text(ByVal Value As String) ``` 控件的完整文本内容,包含链接标记。 ### Links ```vb Property Get Links() As LlbLinks ``` 链接集合。 ### AutoSize ```vb Property Get AutoSize() As Boolean Property Let AutoSize(ByVal Value As Boolean) ``` 是否自动调整大小以适应内容。 ### BorderStyle ```vb Property Get BorderStyle() As CCBorderStyleConstants Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` 边框样式。参见通用枚举。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景颜色。 ### BackStyle ```vb Property Get BackStyle() As CCBackStyleConstants Property Let BackStyle(ByVal Value As CCBackStyleConstants) ``` 背景样式。参见通用枚举。 ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景颜色。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针样式。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 是否启用鼠标进入/离开跟踪。 ### WordWrap ```vb Property Get WordWrap() As Boolean Property Let WordWrap(ByVal Value As Boolean) ``` 是否自动换行。 ### UseMnemonic ```vb Property Get UseMnemonic() As Boolean Property Let UseMnemonic(ByVal Value As Boolean) ``` 是否将 & 字符解释为快捷键前缀。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示方向。 ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 从右到左镜像布局。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### Appearance ```vb Property Get Appearance() As CCAppearanceConstants Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` 外观样式。参见通用枚举。 ### VerticalAlignment ```vb Property Get VerticalAlignment() As CCVerticalAlignmentConstants Property Let VerticalAlignment(ByVal Value As CCVerticalAlignmentConstants) ``` 垂直对齐方式。参见通用枚举。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 窗口句柄。只读。 ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As Variant Property Let Tag(ByVal Value As Variant) Property Set Tag(ByVal Value As Variant) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 可见性。 ## 方法 ### Refresh ```vb Sub Refresh() ``` 强制重绘。 ### AboutBox ```vb Sub AboutBox() ``` 显示关于对话框。 ## 事件 ### LinkClick ```vb Event LinkClick(ByVal Link As LlbLink) ``` 链接被点击时触发。 ### Click ```vb Event Click() ``` 单击时触发。 ### DblClick ```vb Event DblClick() ``` 双击时触发。 ### MouseDown ```vb Event MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` 鼠标按下时触发。 ### MouseUp ```vb Event MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` 鼠标释放时触发。 ### MouseMove ```vb Event MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` 鼠标移动时触发。 ### MouseEnter ```vb Event MouseEnter() ``` 鼠标进入控件时触发。 ### MouseLeave ```vb Event MouseLeave() ``` 鼠标离开控件时触发。 ## 子对象 ### Link(LlbLink) 表示链接标签中的单个链接。 #### 属性 | 属性 | 类型 | 读写 | 说明 | |------|------|------|------| | Start As Long | Long | 读写 | 链接文本起始位置(从 0 开始) | | Length As Long | Long | 读写 | 链接文本长度 | | Visited As Boolean | Boolean | 读写 | 是否已访问 | | Key As String | String | 读写 | 链接关键字 | | Tag As Variant | Variant | 读写 | 自定义数据 | ### Links(LlbLinks) 链接集合对象。 #### 属性 | 属性 | 类型 | 读写 | 说明 | |------|------|------|------| | Item(ByVal Index As Variant) As LlbLink | LlbLink | 只读 | 按索引获取链接 | | Count As Long | Long | 只读 | 链接数量 | #### 方法 | 方法 | 说明 | |------|------| | Add(ByVal Start As Long, ByVal Length As Long, Optional ByVal Key As String) As LlbLink | 添加链接 | | Clear() | 清除所有链接 | | Remove(ByVal Index As Variant) | 移除指定链接 | ## 代码示例 ```vb ' 设置带链接的文本 With LinkLabel1 .Caption = "访问 VBCCR 项目主页获取更多信息" .LinkColor = vbBlue .VisitedLinkColor = vbPurple .LinkBehavior = LlbLinkBehaviorHoverUnderline ' 添加链接 .Links.Add 2, 7, "url_main" .Links.Add 15, 4, "url_more" End With ' 处理链接点击 Private Sub LinkLabel1_LinkClick(ByVal Link As LlbLink) Select Case Link.Key Case "url_main" ShellExecute 0, "open", "https://github.com/Kr00l/VBCCR", vbNullString, vbNullString, 1 Case "url_more" MsgBox "更多信息..." End Select Link.Visited = True End Sub ' 创建多链接文本 With LinkLabel2 .Caption = "请阅读 许可协议 和 隐私政策" .Links.Clear .Links.Add 3, 4, "license" .Links.Add 10, 4, "privacy" End With ``` --- --- url: /zh/packages/vbccr/lists/listboxw.md description: 列表框控件(ListBoxW) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 列表框控件(ListBoxW) 封装 Win32 原生列表框控件,支持复选框/单选样式、所有者绘制、插入标记和多列显示。 ## 枚举 ### LstStyleConstants | 常量 | 值 | 说明 | |------|-----|------| | LstStyleStandard | 0 | 标准列表框 | | LstStyleCheckbox | 1 | 复选框样式 | | LstStyleOption | 2 | 单选按钮样式 | ### LstDrawModeConstants | 常量 | 值 | 说明 | |------|-----|------| | LstDrawModeNormal | 0 | 系统绘制 | | LstDrawModeOwnerDrawFixed | 1 | 所有者绘制固定高度 | | LstDrawModeOwnerDrawVariable | 2 | 所有者绘制可变高度 | ### CCBorderStyleConstants 参见通用枚举。 ### CCMousePointerConstants 参见通用枚举。 ### CCRightToLeftModeConstants 参见通用枚举。 ## 属性 ### Text ```vb Property Get Text() As String Property Let Text(ByVal Value As String) ``` 当前选定项的文本。 ### List ```vb Property Get List(ByVal Index As Long) As String Property Let List(ByVal Index As Long, ByVal Value As String) ``` 按索引获取或设置列表项文本。 ### ItemData ```vb Property Get ItemData(ByVal Index As Long) As LongPtr Property Let ItemData(ByVal Index As Long, ByVal Value As LongPtr) ``` 按索引获取或设置列表项的关联数据。 ### ItemChecked ```vb Property Get ItemChecked(ByVal Index As Long) As Boolean Property Let ItemChecked(ByVal Index As Long, ByVal Value As Boolean) ``` 按索引获取或设置项的选中状态(Style 为 Checkbox 或 Option 时有效)。 ### ListCount ```vb Property Get ListCount() As Long ``` 列表项总数。只读。 ### ListIndex ```vb Property Get ListIndex() As Long Property Let ListIndex(ByVal Value As Long) ``` 当前选定项的索引。 ### NewIndex ```vb Property Get NewIndex() As Long ``` 最近添加项的索引。只读。 ### TopIndex ```vb Property Get TopIndex() As Long Property Let TopIndex(ByVal Value As Long) ``` 列表中第一个可见项的索引。 ### AnchorIndex ```vb Property Get AnchorIndex() As Long Property Let AnchorIndex(ByVal Value As Long) ``` 选择锚点的索引。 ### SelCount ```vb Property Get SelCount() As Long ``` 选定项数量。只读。 ### Selected ```vb Property Get Selected(ByVal Index As Long) As Boolean Property Let Selected(ByVal Index As Long, ByVal Value As Boolean) ``` 按索引获取或设置项的选定状态。 ### ItemHeight ```vb Property Get ItemHeight(Optional ByVal Index As Long) As Single Property Let ItemHeight(Optional ByVal Index As Long, ByVal Value As Single) ``` 项的高度。可变高度所有者绘制模式下可按索引设置。 ### InsertMark ```vb Property Get InsertMark(Optional ByRef After As Boolean) As Long Property Let InsertMark(Optional ByRef After As Boolean, ByVal Value As Long) ``` 插入标记的索引。 ### OptionIndex ```vb Property Get OptionIndex() As Long Property Let OptionIndex(ByVal Value As Long) ``` 单选按钮样式中选中项的索引。 ### OLEDraggedItem ```vb Property Get OLEDraggedItem() As Long ``` OLE 拖放操作中拖动项的索引。只读。 ### Style ```vb Property Get Style() As LstStyleConstants Property Let Style(ByVal Value As LstStyleConstants) ``` 列表框样式。设计时只读。 ### DrawMode ```vb Property Get DrawMode() As LstDrawModeConstants Property Let DrawMode(ByVal Value As LstDrawModeConstants) ``` 绘制模式。设计时只读。 ### MultiSelect ```vb Property Get MultiSelect() As VBRUN.MultiSelectConstants Property Let MultiSelect(ByVal Value As VBRUN.MultiSelectConstants) ``` 多选模式。 ### Sorted ```vb Property Get Sorted() As Boolean Property Let Sorted(ByVal Value As Boolean) ``` 是否自动排序。 ### MultiColumn ```vb Property Get MultiColumn() As Boolean Property Let MultiColumn(ByVal Value As Boolean) ``` 是否启用多列显示。 ### IntegralHeight ```vb Property Get IntegralHeight() As Boolean Property Let IntegralHeight(ByVal Value As Boolean) ``` 是否只显示完整项。设计时可设置。 ### AllowSelection ```vb Property Get AllowSelection() As Boolean Property Let AllowSelection(ByVal Value As Boolean) ``` 是否允许选择项。 ### UseTabStops ```vb Property Get UseTabStops() As Boolean Property Let UseTabStops(ByVal Value As Boolean) ``` 是否识别和展开制表符。 ### DisableNoScroll ```vb Property Get DisableNoScroll() As Boolean Property Let DisableNoScroll(ByVal Value As Boolean) ``` 无需滚动时是否禁用(而非隐藏)滚动条。 ### HorizontalExtent ```vb Property Get HorizontalExtent() As Single Property Let HorizontalExtent(ByVal Value As Single) ``` 水平滚动宽度。 ### InsertMarkColor ```vb Property Get InsertMarkColor() As OLE_COLOR Property Let InsertMarkColor(ByVal Value As OLE_COLOR) ``` 插入标记的颜色。 ### ScrollTrack ```vb Property Get ScrollTrack() As Boolean Property Let ScrollTrack(ByVal Value As Boolean) ``` 是否在拖动滚动条时实时滚动内容。 ### Redraw ```vb Property Get Redraw() As Boolean Property Let Redraw(ByVal Value As Boolean) ``` 是否在更改项时重绘列表框。禁用可加速批量添加。 ### BorderStyle ```vb Property Get BorderStyle() As CCBorderStyleConstants Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` 边框样式。参见通用枚举。 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景色。 ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### AllowDropFiles ```vb Property Get AllowDropFiles() As Boolean Property Let AllowDropFiles(ByVal Value As Boolean) ``` 是否允许拖放文件。 ### OLEDragMode ```vb Property Get OLEDragMode() As VBRUN.OLEDragConstants Property Let OLEDragMode(ByVal Value As VBRUN.OLEDragConstants) ``` OLE 拖动模式。 ### OLEDragDropScroll ```vb Property Get OLEDragDropScroll() As Boolean Property Let OLEDragDropScroll(ByVal Value As Boolean) ``` OLE 拖放时是否自动滚动。 ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE 放置模式。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针样式。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 是否启用鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示方向。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 列表框控件的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 用户控件的窗口句柄。 ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` 帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "这是什么"帮助 ID。 ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` 拖动图标。 ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` 拖动模式。 ## 方法 ### AddItem ```vb Public Sub AddItem(ByVal Item As String, Optional ByVal Index As Variant) ``` 添加列表项。 ### RemoveItem ```vb Public Sub RemoveItem(ByVal Index As Long) ``` 移除指定索引的列表项。 ### Clear ```vb Public Sub Clear() ``` 清除所有列表项。 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘控件。 ### SetSelRange ```vb Public Sub SetSelRange(ByVal StartIndex As Long, ByVal EndIndex As Long) ``` 设置选择范围(多选模式下)。 ### SetColumnWidth ```vb Public Sub SetColumnWidth(ByVal Value As Single) ``` 设置多列模式下列的宽度。 ### SelectItem ```vb Public Function SelectItem(ByVal Text As String, Optional ByVal Index As Long = -1) As Long ``` 选择匹配文本的项,返回选中项索引。 ### FindItem ```vb Public Function FindItem(ByVal Text As String, Optional ByVal Index As Long = -1, Optional ByVal Partial As Boolean) As Long ``` 查找匹配文本的项,返回索引。 ### HitTest ```vb Public Function HitTest(ByVal X As Single, ByVal Y As Single) As Long ``` 命中测试,返回指定坐标处的项索引。 ### HitTestInsertMark ```vb Public Function HitTestInsertMark(ByVal X As Single, ByVal Y As Single, Optional ByRef After As Boolean) As Long ``` 插入标记命中测试,返回插入位置索引。 ### ItemsPerColumn ```vb Public Function ItemsPerColumn() As Long ``` 获取每列项数。 ### SelectedIndices ```vb Public Function SelectedIndices() As Collection ``` 获取所有选定项索引的集合。 ### CheckedIndices ```vb Public Function CheckedIndices() As Collection ``` 获取所有选中项(复选框/单选)索引的集合。 ### GetIdealHorizontalExtent ```vb Public Function GetIdealHorizontalExtent() As Single ``` 获取理想的水平滚动宽度。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 获取焦点。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 调整 Z 顺序。 ### Move ```vb Public Sub Move(ByVal Left As Single, Optional ByVal Top As Variant, Optional ByVal Width As Variant, Optional ByVal Height As Variant) ``` 移动并调整控件位置和大小。 ## 事件 ### Click ```vb Public Event Click() ``` 单击。 ### DblClick ```vb Public Event DblClick() ``` 双击。 ### Scroll ```vb Public Event Scroll() ``` 滚动时触发。 ### ItemCheck ```vb Public Event ItemCheck(ByVal Item As Long) ``` 项被选中或取消选中时触发。 ### ItemBeforeCheck ```vb Public Event ItemBeforeCheck(ByVal Item As Long, ByRef Cancel As Boolean) ``` 项即将被选中或取消选中时触发,可取消。 ### ItemMeasure ```vb Public Event ItemMeasure(ByVal Item As Long, ByRef ItemHeight As Long) ``` 可变高度所有者绘制模式下测量项高度时触发。 ### ItemDraw ```vb Public Event ItemDraw(ByVal Item As Long, ByVal ItemAction As Long, ByVal ItemState As Long, ByVal hDC As Long, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` 所有者绘制模式下绘制项时触发。 ### DropFiles ```vb Public Event DropFiles(ByRef FileList As Variant, ByVal X As Single, ByVal Y As Single) ``` 拖放文件到控件时触发。 ### ContextMenu ```vb Public Event ContextMenu(ByVal X As Single, ByVal Y As Single) ``` 右键菜单请求时触发。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键前事件,在 KeyDown 之前触发。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键释放前事件,在 KeyUp 之前触发。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按键按下。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 按键释放。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按键字符。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 鼠标按下。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 鼠标移动。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 鼠标释放。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放完成。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE 拖放落下。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放悬停。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 给出反馈。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE 设置数据。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 开始拖动。 ## 代码示例 ### 基本用法 ```vb ' 添加列表项 ListBoxW1.AddItem "项目 1" ListBoxW1.AddItem "项目 2", 0 ' 设置当前选中项 ListBoxW1.ListIndex = 0 ' 获取选中项文本 Dim s As String s = ListBoxW1.Text ``` ### 复选框和单选样式 ```vb ' 复选框样式(设计时设置) ' ListBoxW1.Style = LstStyleCheckbox ' 获取选中项 Dim i As Long For i = 0 To ListBoxW1.ListCount - 1 If ListBoxW1.ItemChecked(i) Then Debug.Print ListBoxW1.List(i) End If Next i ``` ### 所有者绘制 ```vb ' 可变高度所有者绘制(设计时设置 DrawMode = LstDrawModeOwnerDrawVariable) Private Sub ListBoxW1_ItemMeasure(ByVal Item As Long, ByRef ItemHeight As Long) ItemHeight = 30 End Sub Private Sub ListBoxW1_ItemDraw(ByVal Item As Long, ByVal ItemAction As Long, _ ByVal ItemState As Long, ByVal hDC As Long, _ ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ' 自定义绘制逻辑 End Sub ``` ### 批量添加 ```vb ' 禁用重绘加速批量添加 ListBoxW1.Redraw = False Dim i As Long For i = 1 To 1000 ListBoxW1.AddItem "Item " & i Next i ListBoxW1.Redraw = True ``` --- --- url: /zh/packages/vbccr/views/listview.md description: 列表视图控件(ListView) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 列表视图控件(ListView) 封装 SysListView32 系统列表视图控件,支持大图标、小图标、列表、报表和平铺视图,以及分组、虚拟模式、列筛选等高级功能。 ## 枚举 ### LvwViewConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwViewIcon | 0 | 大图标视图 | | LvwViewSmallIcon | 1 | 小图标视图 | | LvwViewList | 2 | 列表视图 | | LvwViewReport | 3 | 报表视图 | | LvwViewTile | 4 | 平铺视图 | ### LvwArrangeConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwArrangeNone | 0 | 不排列 | | LvwArrangeAutoLeft | 1 | 自动靠左排列 | | LvwArrangeAutoTop | 2 | 自动靠顶排列 | | LvwArrangeLeft | 3 | 靠左排列 | | LvwArrangeTop | 4 | 靠顶排列 | ### LvwColumnHeaderAlignmentConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwColumnHeaderAlignmentLeft | 0 | 左对齐 | | LvwColumnHeaderAlignmentRight | 1 | 右对齐 | | LvwColumnHeaderAlignmentCenter | 2 | 居中 | ### LvwColumnHeaderSortArrowConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwColumnHeaderSortArrowNone | 0 | 无排序箭头 | | LvwColumnHeaderSortArrowDown | 1 | 向下箭头(升序) | | LvwColumnHeaderSortArrowUp | 2 | 向上箭头(降序) | ### LvwColumnHeaderAutoSizeConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwColumnHeaderAutoSizeToItems | 0 | 根据项自动调整 | | LvwColumnHeaderAutoSizeToHeader | 1 | 根据表头自动调整 | ### LvwColumnHeaderFilterTypeConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwColumnHeaderFilterTypeText | 0 | 文本筛选 | | LvwColumnHeaderFilterTypeNumber | 1 | 数值筛选 | ### LvwLabelEditConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwLabelEditAutomatic | 0 | 自动标签编辑 | | LvwLabelEditManual | 1 | 手动标签编辑 | | LvwLabelEditDisabled | 2 | 禁用标签编辑 | ### LvwSortOrderConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwSortOrderAscending | 0 | 升序 | | LvwSortOrderDescending | 1 | 降序 | ### LvwSortTypeConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwSortTypeBinary | 0 | 二进制排序 | | LvwSortTypeText | 1 | 文本排序 | | LvwSortTypeNumeric | 2 | 数值排序 | | LvwSortTypeCurrency | 3 | 货币排序 | | LvwSortTypeDate | 4 | 日期排序 | | LvwSortTypeLogical | 5 | 逻辑排序 | ### LvwPictureAlignmentConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwPictureAlignmentTopLeft | 0 | 左上 | | LvwPictureAlignmentTopRight | 1 | 右上 | | LvwPictureAlignmentBottomLeft | 2 | 左下 | | LvwPictureAlignmentBottomRight | 3 | 右下 | | LvwPictureAlignmentCenter | 4 | 居中 | | LvwPictureAlignmentTile | 5 | 平铺 | ### LvwGroupHeaderAlignmentConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwGroupHeaderAlignmentLeft | 0 | 左对齐 | | LvwGroupHeaderAlignmentRight | 1 | 右对齐 | | LvwGroupHeaderAlignmentCenter | 2 | 居中 | ### LvwGroupFooterAlignmentConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwGroupFooterAlignmentLeft | 0 | 左对齐 | | LvwGroupFooterAlignmentRight | 1 | 右对齐 | | LvwGroupFooterAlignmentCenter | 2 | 居中 | ### LvwVisualThemeConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwVisualThemeStandard | 0 | 标准主题 | | LvwVisualThemeExplorer | 1 | 资源管理器主题 | ### LvwVirtualPropertyConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwVirtualPropertyText | 1 | 文本属性 | | LvwVirtualPropertyIcon | 2 | 图标属性 | | LvwVirtualPropertyIndentation | 4 | 缩进属性 | | LvwVirtualPropertyToolTipText | 8 | 工具提示文本属性 | | LvwVirtualPropertyBold | 16 | 粗体属性 | | LvwVirtualPropertyForeColor | 32 | 前景色属性 | | LvwVirtualPropertyChecked | 64 | 选中属性 | ### LvwFindDirectionConstants | 常量 | 值 | 说明 | |------|-----|------| | LvwFindDirectionUndefined | 0 | 未定义 | | LvwFindDirectionPrior | vbKeyPageUp | 向上翻页方向 | | LvwFindDirectionNext | vbKeyPageDown | 向下翻页方向 | | LvwFindDirectionEnd | vbKeyEnd | End 方向 | | LvwFindDirectionHome | vbKeyHome | Home 方向 | | LvwFindDirectionLeft | vbKeyLeft | 左方向 | | LvwFindDirectionUp | vbKeyUp | 上方向 | | LvwFindDirectionRight | vbKeyRight | 右方向 | | LvwFindDirectionDown | vbKeyDown | 下方向 | ### CCBorderStyleConstants 参见通用枚举。 ### CCAppearanceConstants 参见通用枚举。 ### CCMousePointerConstants 参见通用枚举。 ### CCIMEModeConstants 参见通用枚举。 ### CCBackStyleConstants 参见通用枚举。 ### CCRightToLeftModeConstants 参见通用枚举。 ### CCScrollOrientationConstants 参见通用枚举。 ### OLEDropModeConstants 参见通用枚举。 ## 属性 ### View ```vb Property Get View() As LvwViewConstants Property Let View(ByVal Value As LvwViewConstants) ``` 视图模式。 ### Arrange ```vb Property Get Arrange() As LvwArrangeConstants Property Let Arrange(ByVal Value As LvwArrangeConstants) ``` 图标排列方式。 ### SortKey ```vb Property Get SortKey() As Integer Property Let SortKey(ByVal Value As Integer) ``` 排序关键列索引。 ### SortOrder ```vb Property Get SortOrder() As LvwSortOrderConstants Property Let SortOrder(ByVal Value As LvwSortOrderConstants) ``` 排序顺序。 ### SortType ```vb Property Get SortType() As LvwSortTypeConstants Property Let SortType(ByVal Value As LvwSortTypeConstants) ``` 排序类型。 ### Sorted ```vb Property Get Sorted() As Boolean Property Let Sorted(ByVal Value As Boolean) ``` 是否启用排序。 ### LabelEdit ```vb Property Get LabelEdit() As LvwLabelEditConstants Property Let LabelEdit(ByVal Value As LvwLabelEditConstants) ``` 标签编辑模式。 ### LabelWrap ```vb Property Get LabelWrap() As Boolean Property Let LabelWrap(ByVal Value As Boolean) ``` 是否允许标签换行。 ### MultiSelect ```vb Property Get MultiSelect() As Boolean Property Let MultiSelect(ByVal Value As Boolean) ``` 是否允许多选。 ### FullRowSelect ```vb Property Get FullRowSelect() As Boolean Property Let FullRowSelect(ByVal Value As Boolean) ``` 是否整行选中。 ### GridLines ```vb Property Get GridLines() As Boolean Property Let GridLines(ByVal Value As Boolean) ``` 是否显示网格线。 ### Checkboxes ```vb Property Get Checkboxes() As Boolean Property Let Checkboxes(ByVal Value As Boolean) ``` 是否显示复选框。 ### HideSelection ```vb Property Get HideSelection() As Boolean Property Let HideSelection(ByVal Value As Boolean) ``` 失去焦点时是否隐藏选中状态。 ### HideColumnHeaders ```vb Property Get HideColumnHeaders() As Boolean Property Let HideColumnHeaders(ByVal Value As Boolean) ``` 是否隐藏列标题。 ### AllowColumnReorder ```vb Property Get AllowColumnReorder() As Boolean Property Let AllowColumnReorder(ByVal Value As Boolean) ``` 是否允许拖动重排列。 ### AllowColumnCheckboxes ```vb Property Get AllowColumnCheckboxes() As Boolean Property Let AllowColumnCheckboxes(ByVal Value As Boolean) ``` 是否允许列复选框。 ### AllowDropFiles ```vb Property Get AllowDropFiles() As Boolean Property Let AllowDropFiles(ByVal Value As Boolean) ``` 是否允许拖放文件。 ### ShowInfoTips ```vb Property Get ShowInfoTips() As Boolean Property Let ShowInfoTips(ByVal Value As Boolean) ``` 是否显示信息提示。 ### ShowLabelTips ```vb Property Get ShowLabelTips() As Boolean Property Let ShowLabelTips(ByVal Value As Boolean) ``` 是否显示标签提示。 ### ShowColumnTips ```vb Property Get ShowColumnTips() As Boolean Property Let ShowColumnTips(ByVal Value As Boolean) ``` 是否显示列提示。 ### DoubleBuffer ```vb Property Get DoubleBuffer() As Boolean Property Let DoubleBuffer(ByVal Value As Boolean) ``` 是否启用双缓冲。 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。 ### VisualTheme ```vb Property Get VisualTheme() As LvwVisualThemeConstants Property Let VisualTheme(ByVal Value As LvwVisualThemeConstants) ``` 视觉主题。 ### HoverSelection ```vb Property Get HoverSelection() As Boolean Property Let HoverSelection(ByVal Value As Boolean) ``` 是否启用悬停选择。 ### HoverSelectionTime ```vb Property Get HoverSelectionTime() As Long Property Let HoverSelectionTime(ByVal Value As Long) ``` 悬停选择延迟时间(毫秒)。 ### HotTracking ```vb Property Get HotTracking() As Boolean Property Let HotTracking(ByVal Value As Boolean) ``` 是否启用热跟踪。 ### HighlightHot ```vb Property Get HighlightHot() As Boolean Property Let HighlightHot(ByVal Value As Boolean) ``` 是否高亮显示热项。 ### UnderlineHot ```vb Property Get UnderlineHot() As Boolean Property Let UnderlineHot(ByVal Value As Boolean) ``` 是否为热项添加下划线。 ### InsertMarkColor ```vb Property Get InsertMarkColor() As OLE_COLOR Property Let InsertMarkColor(ByVal Value As OLE_COLOR) ``` 插入标记的颜色。 ### TextBackground ```vb Property Get TextBackground() As CCBackStyleConstants Property Let TextBackground(ByVal Value As CCBackStyleConstants) ``` 文本背景样式。参见通用枚举。 ### ClickableColumnHeaders ```vb Property Get ClickableColumnHeaders() As Boolean Property Let ClickableColumnHeaders(ByVal Value As Boolean) ``` 列标题是否可点击。 ### HighlightColumnHeaders ```vb Property Get HighlightColumnHeaders() As Boolean Property Let HighlightColumnHeaders(ByVal Value As Boolean) ``` 是否高亮显示列标题。 ### TrackSizeColumnHeaders ```vb Property Get TrackSizeColumnHeaders() As Boolean Property Let TrackSizeColumnHeaders(ByVal Value As Boolean) ``` 是否跟踪列标题大小。 ### ResizableColumnHeaders ```vb Property Get ResizableColumnHeaders() As Boolean Property Let ResizableColumnHeaders(ByVal Value As Boolean) ``` 列标题是否可调整大小。 ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` 背景图片。 ### PictureAlignment ```vb Property Get PictureAlignment() As LvwPictureAlignmentConstants Property Let PictureAlignment(ByVal Value As LvwPictureAlignmentConstants) ``` 背景图片对齐方式。 ### PictureWatermark ```vb Property Get PictureWatermark() As Boolean Property Let PictureWatermark(ByVal Value As Boolean) ``` 是否将背景图片作为水印。 ### TileViewLines ```vb Property Get TileViewLines() As Long Property Let TileViewLines(ByVal Value As Long) ``` 平铺视图中的文本行数。 ### SnapToGrid ```vb Property Get SnapToGrid() As Boolean Property Let SnapToGrid(ByVal Value As Boolean) ``` 是否对齐到网格。 ### GroupView ```vb Property Get GroupView() As Boolean Property Let GroupView(ByVal Value As Boolean) ``` 是否启用分组视图。 ### GroupSubsetCount ```vb Property Get GroupSubsetCount() As Long Property Let GroupSubsetCount(ByVal Value As Long) ``` 分组子集显示数量。 ### UseColumnChevron ```vb Property Get UseColumnChevron() As Boolean Property Let UseColumnChevron(ByVal Value As Boolean) ``` 是否使用列折叠按钮。 ### UseColumnFilterBar ```vb Property Get UseColumnFilterBar() As Boolean Property Let UseColumnFilterBar(ByVal Value As Boolean) ``` 是否使用列筛选栏。 ### AutoSelectFirstItem ```vb Property Get AutoSelectFirstItem() As Boolean Property Let AutoSelectFirstItem(ByVal Value As Boolean) ``` 是否自动选择第一项。 ### IMEMode ```vb Property Get IMEMode() As CCIMEModeConstants Property Let IMEMode(ByVal Value As CCIMEModeConstants) ``` 输入法模式。参见通用枚举。 ### VirtualMode ```vb Property Get VirtualMode() As Boolean Property Let VirtualMode(ByVal Value As Boolean) ``` 是否启用虚拟模式。 ### VirtualItemCount ```vb Property Get VirtualItemCount() As Long Property Let VirtualItemCount(ByVal Value As Long) ``` 虚拟模式下的项总数。 ### VirtualDisabledInfos ```vb Property Get VirtualDisabledInfos() As LvwVirtualPropertyConstants Property Let VirtualDisabledInfos(ByVal Value As LvwVirtualPropertyConstants) ``` 虚拟模式下禁用的属性掩码。 ### ListItems ```vb Property Get ListItems() As LvwListItems ``` 列表项集合。只读。 ### VirtualListItems ```vb Property Get VirtualListItems() As LvwVirtualListItems ``` 虚拟列表项集合。只读。 ### ColumnHeaders ```vb Property Get ColumnHeaders() As LvwColumnHeaders ``` 列标题集合。只读。 ### Groups ```vb Property Get Groups() As LvwGroups ``` 分组集合。只读。 ### WorkAreas ```vb Property Get WorkAreas() As LvwWorkAreas ``` 工作区域集合。只读。 ### TopItem ```vb Property Get TopItem() As LvwListItem ``` 第一个可见项。只读。 ### SelectedItem ```vb Property Get SelectedItem() As LvwListItem Property Let SelectedItem(ByVal Value As LvwListItem) Property Set SelectedItem(ByVal Value As LvwListItem) ``` 当前选中项。 ### HotItem ```vb Property Get HotItem() As LvwListItem Property Let HotItem(ByVal Value As LvwListItem) Property Set HotItem(ByVal Value As LvwListItem) ``` 热项(鼠标悬停项)。 ### SelectionMark ```vb Property Get SelectionMark() As LvwListItem Property Let SelectionMark(ByVal Value As LvwListItem) Property Set SelectionMark(ByVal Value As LvwListItem) ``` 选择标记项。 ### DropHighlight ```vb Property Get DropHighlight() As LvwListItem Property Let DropHighlight(ByVal Value As LvwListItem) Property Set DropHighlight(ByVal Value As LvwListItem) ``` 拖放高亮项。 ### InsertMark ```vb Property Get InsertMark(Optional ByRef After As Boolean) As LvwListItem Property Let InsertMark(Optional ByRef After As Boolean, ByVal Value As LvwListItem) Property Set InsertMark(Optional ByRef After As Boolean, ByVal Value As LvwListItem) ``` 插入标记项。 ### OLEDraggedItem ```vb Property Get OLEDraggedItem() As LvwListItem ``` OLE 拖放操作中拖动的项。只读。 ### SelectedGroup ```vb Property Get SelectedGroup() As LvwGroup Property Let SelectedGroup(ByVal Value As LvwGroup) Property Set SelectedGroup(ByVal Value As LvwGroup) ``` 当前选中的分组。 ### SelectedColumn ```vb Property Get SelectedColumn() As LvwColumnHeader Property Let SelectedColumn(ByVal Value As LvwColumnHeader) Property Set SelectedColumn(ByVal Value As LvwColumnHeader) ``` 当前选中的列。 ### ColumnOrder ```vb Property Get ColumnOrder() As Variant Property Let ColumnOrder(ByVal ArgList As Variant) ``` 列顺序数组。 ### ColumnWidth ```vb Property Get ColumnWidth() As Single Property Let ColumnWidth(ByVal Value As Single) ``` 当前列宽。 ### ColumnFilterChangedTimeout ```vb Property Get ColumnFilterChangedTimeout() As Long Property Let ColumnFilterChangedTimeout(ByVal Value As Long) ``` 列筛选变更超时时间。 ### IconSpacingWidth ```vb Property Get IconSpacingWidth() As Single Property Let IconSpacingWidth(ByVal Value As Single) ``` 图标间距宽度。 ### IconSpacingHeight ```vb Property Get IconSpacingHeight() As Single Property Let IconSpacingHeight(ByVal Value As Single) ``` 图标间距高度。 ### IncrementalSearchString ```vb Property Get IncrementalSearchString() As String ``` 增量搜索字符串。只读。 ### Redraw ```vb Property Get Redraw() As Boolean Property Let Redraw(ByVal Value As Boolean) ``` 是否启用重绘。 ### BorderStyle ```vb Property Get BorderStyle() As CCBorderStyleConstants Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` 边框样式。参见通用枚举。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景色。 ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### Icons ```vb Property Get Icons() As Variant Property Set Icons(ByVal Value As Variant) Property Let Icons(ByVal Value As Variant) ``` 大图标图像列表。 ### SmallIcons ```vb Property Get SmallIcons() As Variant Property Set SmallIcons(ByVal Value As Variant) Property Let SmallIcons(ByVal Value As Variant) ``` 小图标图像列表。 ### ColumnHeaderIcons ```vb Property Get ColumnHeaderIcons() As Variant Property Set ColumnHeaderIcons(ByVal Value As Variant) Property Let ColumnHeaderIcons(ByVal Value As Variant) ``` 列标题图像列表。 ### GroupIcons ```vb Property Get GroupIcons() As Variant Property Set GroupIcons(ByVal Value As Variant) Property Let GroupIcons(ByVal Value As Variant) ``` 分组标题图像列表。 ### OLEDragMode ```vb Property Get OLEDragMode() As VBRUN.OLEDragConstants Property Let OLEDragMode(ByVal Value As VBRUN.OLEDragConstants) ``` OLE 拖动模式。 ### OLEDragDropScroll ```vb Property Get OLEDragDropScroll() As Boolean Property Let OLEDragDropScroll(ByVal Value As Boolean) ``` OLE 拖放时是否自动滚动。 ### OLEDragDropScrollOrientation ```vb Property Get OLEDragDropScrollOrientation() As CCScrollOrientationConstants Property Let OLEDragDropScrollOrientation(ByVal Value As CCScrollOrientationConstants) ``` OLE 拖放自动滚动方向。参见通用枚举。 ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE 放置模式。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针样式。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### HotMousePointer ```vb Property Get HotMousePointer() As CCMousePointerConstants Property Let HotMousePointer(ByVal Value As CCMousePointerConstants) ``` 热项鼠标指针样式。参见通用枚举。 ### HotMouseIcon ```vb Property Get HotMouseIcon() As IPictureDisp Property Let HotMouseIcon(ByVal Value As IPictureDisp) Property Set HotMouseIcon(ByVal Value As IPictureDisp) ``` 热项自定义鼠标图标。 ### HeaderMousePointer ```vb Property Get HeaderMousePointer() As CCMousePointerConstants Property Let HeaderMousePointer(ByVal Value As CCMousePointerConstants) ``` 列标题鼠标指针样式。参见通用枚举。 ### HeaderMouseIcon ```vb Property Get HeaderMouseIcon() As IPictureDisp Property Let HeaderMouseIcon(ByVal Value As IPictureDisp) Property Set HeaderMouseIcon(ByVal Value As IPictureDisp) ``` 列标题自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 是否启用鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示方向。 ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 从右到左镜像布局。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 列表视图控件的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 用户控件的窗口句柄。 ### hWndHeader ```vb Property Get hWndHeader() As LongPtr ``` 列标题控件的窗口句柄。 ### hWndLabelEdit ```vb Property Get hWndLabelEdit() As LongPtr ``` 标签编辑框的窗口句柄。 ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` 帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "这是什么"帮助 ID。 ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` 拖动图标。 ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` 拖动模式。 ## 方法 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘控件。 ### HitTest ```vb Public Function HitTest(ByVal X As Single, ByVal Y As Single, Optional ByRef SubItemIndex As Variant) As LvwListItem ``` 命中测试,返回指定坐标处的列表项。 ### HitTestInsertMark ```vb Public Function HitTestInsertMark(ByVal X As Single, ByVal Y As Single, Optional ByRef After As Boolean) As LvwListItem ``` 插入标记命中测试,返回插入位置的列表项。 ### FindItem ```vb Public Function FindItem(ByVal Text As String, Optional ByVal Index As Long, Optional ByVal Partial As Boolean, Optional ByVal Wrap As Boolean) As LvwListItem ``` 查找匹配文本的列表项。 ### FindNearestItem ```vb Public Function FindNearestItem(ByVal X As Single, ByVal Y As Single, Optional ByVal Direction As LvwFindDirectionConstants) As LvwListItem ``` 查找指定方向最近的列表项。 ### FindSubItem ```vb Public Function FindSubItem(ByVal Text As String, Optional ByVal Index As Long, Optional ByRef SubItemIndex As Long, Optional ByVal Partial As Boolean, Optional ByVal Wrap As Boolean) As LvwListItem ``` 查找匹配文本的子项。 ### GetVisibleCount ```vb Public Function GetVisibleCount() As Long ``` 获取可见项数量。 ### GetSelectedCount ```vb Public Function GetSelectedCount() As Long ``` 获取选中项数量。 ### GetHeaderHeight ```vb Public Function GetHeaderHeight() As Single ``` 获取列标题高度。 ### StartLabelEdit ```vb Public Sub StartLabelEdit() ``` 开始标签编辑。 ### EndLabelEdit ```vb Public Sub EndLabelEdit() ``` 结束标签编辑。 ### Scroll ```vb Public Sub Scroll(ByVal X As Single, ByVal Y As Single) ``` 滚动列表视图内容。 ### ResetEmptyMarkup ```vb Public Sub ResetEmptyMarkup() ``` 重置空标记文本。 ### ComputeControlSize ```vb Public Sub ComputeControlSize(ByVal VisibleCount As Long, ByRef Width As Single, ByRef Height As Single, Optional ByVal ProposedWidth As Single, Optional ByVal ProposedHeight As Single) ``` 计算显示指定数量项所需的控件尺寸。 ### TextWidth ```vb Public Function TextWidth(ByVal Text As String) As Single ``` 计算文本宽度。 ### ResetForeColors ```vb Public Sub ResetForeColors() ``` 重置所有列表项和子项的前景色。 ### SelectedIndices ```vb Public Function SelectedIndices() As Collection ``` 获取所有选中项索引的集合。 ### GhostedIndices ```vb Public Function GhostedIndices() As Collection ``` 获取所有幻影项索引的集合。 ### CheckedIndices ```vb Public Function CheckedIndices() As Collection ``` 获取所有选中(复选框)项索引的集合。 ### ResetIconSpacing ```vb Public Sub ResetIconSpacing() ``` 重置图标间距为默认值。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 获取焦点。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 调整 Z 顺序。 ### Move ```vb Public Sub Move(ByVal Left As Single, Optional ByVal Top As Variant, Optional ByVal Width As Variant, Optional ByVal Height As Variant) ``` 移动并调整控件位置和大小。 ## 事件 ### Click ```vb Public Event Click() ``` 单击。 ### DblClick ```vb Public Event DblClick() ``` 双击。 ### ItemClick ```vb Public Event ItemClick(ByVal Item As LvwListItem, ByVal Button As Integer) ``` 列表项被点击。 ### ItemDblClick ```vb Public Event ItemDblClick(ByVal Item As LvwListItem, ByVal Button As Integer) ``` 列表项被双击。 ### ItemFocus ```vb Public Event ItemFocus(ByVal Item As LvwListItem) ``` 列表项获得焦点。 ### ItemActivate ```vb Public Event ItemActivate(ByVal Item As LvwListItem, ByVal SubItemIndex As Long, ByVal Shift As Integer) ``` 列表项被激活。 ### ItemSelect ```vb Public Event ItemSelect(ByVal Item As LvwListItem, ByVal Selected As Boolean) ``` 列表项选中状态改变。 ### ItemCheck ```vb Public Event ItemCheck(ByVal Item As LvwListItem, ByVal Checked As Boolean) ``` 列表项复选框状态改变。 ### ItemDrag ```vb Public Event ItemDrag(ByVal Item As LvwListItem, ByVal Button As Integer) ``` 列表项启动拖放操作。 ### ItemBkColor ```vb Public Event ItemBkColor(ByVal Item As LvwListItem, ByRef RGBColor As Long) ``` 列表项背景色请求(报表视图),可提供替代背景色。 ### GetVirtualItem ```vb Public Event GetVirtualItem(ByVal ItemIndex As Long, ByVal SubItemIndex As Long, ByVal VirtualProperty As LvwVirtualPropertyConstants, ByRef Value As Variant) ``` 虚拟模式下请求项属性。 ### FindVirtualItem ```vb Public Event FindVirtualItem(ByVal StartIndex As Long, ByVal SearchText As String, ByVal Partial As Boolean, ByVal Wrap As Boolean, ByRef FoundIndex As Long) ``` 虚拟模式下查找项。 ### CacheVirtualItems ```vb Public Event CacheVirtualItems(ByVal FromIndex As Long, ByVal ToIndex As Long) ``` 虚拟模式下请求缓存项范围。 ### BeforeLabelEdit ```vb Public Event BeforeLabelEdit(ByRef Cancel As Boolean) ``` 标签编辑前触发,可取消。 ### AfterLabelEdit ```vb Public Event AfterLabelEdit(ByRef Cancel As Boolean, ByRef NewString As String) ``` 标签编辑后触发。 ### ColumnClick ```vb Public Event ColumnClick(ByVal ColumnHeader As LvwColumnHeader) ``` 列标题被点击。 ### ColumnDblClick ```vb Public Event ColumnDblClick(ByVal ColumnHeader As LvwColumnHeader) ``` 列标题被双击。 ### ColumnCheck ```vb Public Event ColumnCheck(ByVal ColumnHeader As LvwColumnHeader) ``` 列标题复选框状态改变。 ### ColumnBeforeResize ```vb Public Event ColumnBeforeResize(ByVal ColumnHeader As LvwColumnHeader, ByRef Cancel As Boolean) ``` 列宽即将调整,可取消。 ### ColumnAfterResize ```vb Public Event ColumnAfterResize(ByVal ColumnHeader As LvwColumnHeader, ByRef NewWidth As Single) ``` 列宽调整完成。 ### ColumnDividerDblClick ```vb Public Event ColumnDividerDblClick(ByVal ColumnHeader As LvwColumnHeader, ByRef Cancel As Boolean) ``` 列分隔线被双击。 ### ColumnBeforeDrag ```vb Public Event ColumnBeforeDrag(ByVal ColumnHeader As LvwColumnHeader) ``` 列标题开始拖动。 ### ColumnAfterDrag ```vb Public Event ColumnAfterDrag(ByVal ColumnHeader As LvwColumnHeader, ByVal NewPosition As Long, ByRef Cancel As Boolean) ``` 列标题拖动完成。 ### ColumnDropDown ```vb Public Event ColumnDropDown(ByVal ColumnHeader As LvwColumnHeader) ``` 列标题下拉按钮被点击。 ### ColumnChevronPushed ```vb Public Event ColumnChevronPushed(ByVal ColumnHeader As LvwColumnHeader) ``` 列折叠按钮被点击。 ### ColumnFilterChanged ```vb Public Event ColumnFilterChanged(ByVal ColumnHeader As LvwColumnHeader) ``` 列筛选条件变更。 ### ColumnFilterButtonClick ```vb Public Event ColumnFilterButtonClick(ByVal ColumnHeader As LvwColumnHeader, ByRef RaiseFilterChanged As Boolean, ByVal ButtonLeft As Long, ByVal ButtonTop As Long, ByVal ButtonRight As Long, ByVal ButtonBottom As Long) ``` 列筛选按钮被点击。 ### BeforeFilterEdit ```vb Public Event BeforeFilterEdit(ByVal ColumnHeader As LvwColumnHeader, ByVal hWndFilterEdit As LongPtr) ``` 列筛选编辑前触发。 ### AfterFilterEdit ```vb Public Event AfterFilterEdit(ByVal ColumnHeader As LvwColumnHeader) ``` 列筛选编辑后触发。 ### GetEmptyMarkup ```vb Public Event GetEmptyMarkup(ByRef Text As String, ByRef Center As Boolean) ``` 列表为空时请求标记文本。 ### GroupCollapsedChanged ```vb Public Event GroupCollapsedChanged(ByVal Group As LvwGroup) ``` 分组折叠状态变更。 ### GroupSelectedChanged ```vb Public Event GroupSelectedChanged(ByVal Group As LvwGroup) ``` 分组选中状态变更。 ### GroupLinkClick ```vb Public Event GroupLinkClick(ByVal Group As LvwGroup) ``` 分组链接被点击。 ### BeginMarqueeSelection ```vb Public Event BeginMarqueeSelection(ByRef Cancel As Boolean) ``` 框选开始,可取消。 ### BeforeScroll ```vb Public Event BeforeScroll(ByVal DeltaX As Single, ByVal DeltaY As Single) ``` 即将滚动前触发。 ### AfterScroll ```vb Public Event AfterScroll(ByVal DeltaX As Single, ByVal DeltaY As Single) ``` 滚动完成后触发。 ### DropFiles ```vb Public Event DropFiles(ByRef FileList As Variant, ByVal X As Single, ByVal Y As Single) ``` 拖放文件到控件时触发。 ### ContextMenu ```vb Public Event ContextMenu(ByVal X As Single, ByVal Y As Single) ``` 右键菜单请求时触发。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键前事件,在 KeyDown 之前触发。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键释放前事件,在 KeyUp 之前触发。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按键按下。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 按键释放。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按键字符。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 鼠标按下。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 鼠标移动。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 鼠标释放。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放完成。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE 拖放落下。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放悬停。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 给出反馈。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE 设置数据。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 开始拖动。 ## 子对象 ### LvwColumnHeader 列标题对象。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Index | `Property Get Index() As Long` | 索引。只读 | | Key | `Property Get Key() As String` / `Property Let Key(ByVal Value As String)` | 键值 | | Tag | `Property Get Tag() As Variant` / `Property Let Tag(ByVal Value As Variant)` / `Property Set Tag(ByVal Value As Variant)` | 自定义数据 | | Text | `Property Get Text() As String` / `Property Let Text(ByVal Value As String)` | 标题文本 | | Icon | `Property Get Icon() As Variant` / `Property Let Icon(ByVal Value As Variant)` | 图标 | | IconIndex | `Property Get IconIndex() As Long` | 图标索引。只读 | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | 列宽 | | Alignment | `Property Get Alignment() As LvwColumnHeaderAlignmentConstants` / `Property Let Alignment(ByVal Value As LvwColumnHeaderAlignmentConstants)` | 对齐方式 | | Position | `Property Get Position() As Long` / `Property Let Position(ByVal Value As Long)` | 位置 | | SortArrow | `Property Get SortArrow() As LvwColumnHeaderSortArrowConstants` / `Property Let SortArrow(ByVal Value As LvwColumnHeaderSortArrowConstants)` | 排序箭头 | | IconOnRight | `Property Get IconOnRight() As Boolean` / `Property Let IconOnRight(ByVal Value As Boolean)` | 图标在右侧 | | Resizable | `Property Get Resizable() As Boolean` / `Property Let Resizable(ByVal Value As Boolean)` | 是否可调整大小 | | SplitButton | `Property Get SplitButton() As Boolean` / `Property Let SplitButton(ByVal Value As Boolean)` | 是否显示分割按钮 | | CheckBox | `Property Get CheckBox() As Boolean` / `Property Let CheckBox(ByVal Value As Boolean)` | 是否显示复选框 | | Checked | `Property Get Checked() As Boolean` / `Property Let Checked(ByVal Value As Boolean)` | 复选框选中状态 | | Bold | `Property Get Bold() As Boolean` / `Property Let Bold(ByVal Value As Boolean)` | 是否粗体 | | ForeColor | `Property Get ForeColor() As OLE_COLOR` / `Property Let ForeColor(ByVal Value As OLE_COLOR)` | 前景色 | | ToolTipText | `Property Get ToolTipText() As String` / `Property Let ToolTipText(ByVal Value As String)` | 工具提示文本 | | ToolTipTextFilterBtn | `Property Get ToolTipTextFilterBtn() As String` / `Property Let ToolTipTextFilterBtn(ByVal Value As String)` | 筛选按钮工具提示 | | ToolTipTextDropDown | `Property Get ToolTipTextDropDown() As String` / `Property Let ToolTipTextDropDown(ByVal Value As String)` | 下拉按钮工具提示 | | FilterType | `Property Get FilterType() As LvwColumnHeaderFilterTypeConstants` / `Property Let FilterType(ByVal Value As LvwColumnHeaderFilterTypeConstants)` | 筛选类型 | | FilterValue | `Property Get FilterValue() As Variant` / `Property Let FilterValue(ByVal Value As Variant)` | 筛选值 | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | 左边距 | #### 方法 | 名称 | 签名 | 说明 | |------|------|------| | AutoSize | `Public Sub AutoSize(ByVal Value As LvwColumnHeaderAutoSizeConstants)` | 自动调整列宽 | | EditFilter | `Public Sub EditFilter()` | 编辑筛选条件 | | ClearFilter | `Public Sub ClearFilter()` | 清除筛选条件 | | SubItemIndex | `Public Function SubItemIndex() As Long` | 获取对应的子项索引 | ### LvwColumnHeaders 列标题集合。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Item | `Property Get Item(ByVal Index As Variant) As LvwColumnHeader` | 按索引获取列标题 | | ItemFromPosition | `Property Get ItemFromPosition(ByVal Position As Long) As LvwColumnHeader` | 按位置获取列标题 | | Count | `Property Get Count() As Long` | 列标题数量。只读 | #### 方法 | 名称 | 签名 | 说明 | |------|------|------| | Add | `Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Text As String, Optional ByVal Width As Variant, Optional ByVal Alignment As LvwColumnHeaderAlignmentConstants, Optional ByVal Icon As Variant) As LvwColumnHeader` | 添加列标题 | | Exists | `Public Function Exists(ByVal Index As Variant) As Boolean` | 检查列标题是否存在 | | Clear | `Public Sub Clear()` | 清除所有列标题 | | Remove | `Public Sub Remove(ByVal Index As Variant)` | 移除列标题 | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | 枚举器 | ### LvwListItem 列表项对象。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Index | `Property Get Index() As Long` | 索引。只读 | | Key | `Property Get Key() As String` / `Property Let Key(ByVal Value As String)` | 键值 | | Tag | `Property Get Tag() As Variant` / `Property Let Tag(ByVal Value As Variant)` / `Property Set Tag(ByVal Value As Variant)` | 自定义数据 | | Text | `Property Get Text() As String` / `Property Let Text(ByVal Value As String)` | 文本 | | Icon | `Property Get Icon() As Variant` / `Property Let Icon(ByVal Value As Variant)` | 大图标 | | IconIndex | `Property Get IconIndex() As Long` | 大图标索引。只读 | | SmallIcon | `Property Get SmallIcon() As Variant` / `Property Let SmallIcon(ByVal Value As Variant)` | 小图标 | | SmallIconIndex | `Property Get SmallIconIndex() As Long` | 小图标索引。只读 | | Indentation | `Property Get Indentation() As Long` / `Property Let Indentation(ByVal Value As Long)` | 缩进 | | Selected | `Property Get Selected() As Boolean` / `Property Let Selected(ByVal Value As Boolean)` | 是否选中 | | Checked | `Property Get Checked() As Boolean` / `Property Let Checked(ByVal Value As Boolean)` | 复选框状态 | | Ghosted | `Property Get Ghosted() As Boolean` / `Property Let Ghosted(ByVal Value As Boolean)` | 是否幻影显示 | | Hot | `Property Get Hot() As Boolean` / `Property Let Hot(ByVal Value As Boolean)` | 是否为热项 | | Bold | `Property Get Bold() As Boolean` / `Property Let Bold(ByVal Value As Boolean)` | 是否粗体 | | ForeColor | `Property Get ForeColor() As OLE_COLOR` / `Property Let ForeColor(ByVal Value As OLE_COLOR)` | 前景色 | | ToolTipText | `Property Get ToolTipText() As String` / `Property Let ToolTipText(ByVal Value As String)` | 工具提示文本 | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | 左边距 | | Top | `Property Get Top() As Single` / `Property Let Top(ByVal Value As Single)` | 顶边距 | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | 宽度 | | Height | `Property Get Height() As Single` / `Property Let Height(ByVal Value As Single)` | 高度 | | Visible | `Property Get Visible() As Boolean` | 是否可见。只读 | | TileViewIndices | `Property Get TileViewIndices() As Variant` / `Property Let TileViewIndices(ByVal ArgList As Variant)` | 平铺视图子项列索引 | | Group | `Property Get Group() As LvwGroup` / `Property Let Group(ByVal Value As LvwGroup)` / `Property Set Group(ByVal Value As LvwGroup)` | 所属分组 | | WorkArea | `Property Get WorkArea() As LvwWorkArea` | 所属工作区域。只读 | | ListSubItems | `Property Get ListSubItems() As LvwListSubItems` | 子项集合。只读 | | SubItems | `Property Get SubItems(ByVal Index As Integer) As String` / `Property Let SubItems(ByVal Index As Integer, ByVal Value As String)` | 按索引获取或设置子项文本 | #### 方法 | 名称 | 签名 | 说明 | |------|------|------| | EnsureVisible | `Public Sub EnsureVisible()` | 确保项可见 | | CreateDragImage | `Public Function CreateDragImage(Optional ByRef X As Single, Optional ByRef Y As Single) As LongPtr` | 创建拖动图像 | ### LvwListItems 列表项集合。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Item | `Property Get Item(ByVal Index As Variant) As LvwListItem` | 按索引获取列表项 | | Count | `Property Get Count() As Long` | 列表项数量。只读 | #### 方法 | 名称 | 签名 | 说明 | |------|------|------| | Add | `Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Text As String, Optional ByVal Icon As Variant, Optional ByVal SmallIcon As Variant) As LvwListItem` | 添加列表项 | | Exists | `Public Function Exists(ByVal Index As Variant) As Boolean` | 检查列表项是否存在 | | Clear | `Public Sub Clear()` | 清除所有列表项 | | Remove | `Public Sub Remove(ByVal Index As Variant)` | 移除列表项 | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | 枚举器 | ### LvwListSubItem 列表子项对象。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Index | `Property Get Index() As Long` | 索引。只读 | | Key | `Property Get Key() As String` | 键值。只读 | | Tag | `Property Get Tag() As Variant` / `Property Let Tag(ByVal Value As Variant)` / `Property Set Tag(ByVal Value As Variant)` | 自定义数据 | | Text | `Property Get Text() As String` / `Property Let Text(ByVal Value As String)` | 文本 | | ReportIcon | `Property Get ReportIcon() As Variant` / `Property Let ReportIcon(ByVal Value As Variant)` | 报表视图图标 | | ReportIconIndex | `Property Get ReportIconIndex() As Long` | 报表视图图标索引。只读 | | Bold | `Property Get Bold() As Boolean` / `Property Let Bold(ByVal Value As Boolean)` | 是否粗体 | | ForeColor | `Property Get ForeColor() As OLE_COLOR` / `Property Let ForeColor(ByVal Value As OLE_COLOR)` | 前景色 | | ToolTipText | `Property Get ToolTipText() As String` / `Property Let ToolTipText(ByVal Value As String)` | 工具提示文本 | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | 左边距 | | Top | `Property Get Top() As Single` / `Property Let Top(ByVal Value As Single)` | 顶边距 | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | 宽度 | | Height | `Property Get Height() As Single` / `Property Let Height(ByVal Value As Single)` | 高度 | ### LvwListSubItems 列表子项集合。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Item | `Property Get Item(ByVal Index As Variant) As LvwListSubItem` | 按索引获取子项 | | Count | `Property Get Count() As Long` | 子项数量。只读 | #### 方法 | 名称 | 签名 | 说明 | |------|------|------| | Add | `Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Text As String, Optional ByVal ReportIcon As Variant, Optional ByVal ToolTipText As String) As LvwListSubItem` | 添加子项 | | Exists | `Public Function Exists(ByVal Index As Variant) As Boolean` | 检查子项是否存在 | | Clear | `Public Sub Clear()` | 清除所有子项 | | Remove | `Public Sub Remove(ByVal Index As Variant)` | 移除子项 | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | 枚举器 | ### LvwGroup 分组对象。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Index | `Property Get Index() As Long` | 索引。只读 | | Key | `Property Get Key() As String` / `Property Let Key(ByVal Value As String)` | 键值 | | Tag | `Property Get Tag() As Variant` / `Property Let Tag(ByVal Value As Variant)` / `Property Set Tag(ByVal Value As Variant)` | 自定义数据 | | ID | `Property Get ID() As Long` | 分组 ID。只读 | | Header | `Property Get Header() As String` / `Property Let Header(ByVal Value As String)` | 分组标题 | | HeaderAlignment | `Property Get HeaderAlignment() As LvwGroupHeaderAlignmentConstants` / `Property Let HeaderAlignment(ByVal Value As LvwGroupHeaderAlignmentConstants)` | 标题对齐方式 | | Footer | `Property Get Footer() As String` / `Property Let Footer(ByVal Value As String)` | 分组页脚 | | FooterAlignment | `Property Get FooterAlignment() As LvwGroupFooterAlignmentConstants` / `Property Let FooterAlignment(ByVal Value As LvwGroupFooterAlignmentConstants)` | 页脚对齐方式 | | Hint | `Property Get Hint() As String` / `Property Let Hint(ByVal Value As String)` | 提示文本 | | Link | `Property Get Link() As String` / `Property Let Link(ByVal Value As String)` | 链接文本 | | SubsetLink | `Property Get SubsetLink() As String` / `Property Let SubsetLink(ByVal Value As String)` | 子集链接文本 | | Collapsible | `Property Get Collapsible() As Boolean` / `Property Let Collapsible(ByVal Value As Boolean)` | 是否可折叠 | | Collapsed | `Property Get Collapsed() As Boolean` / `Property Let Collapsed(ByVal Value As Boolean)` | 是否已折叠 | | ShowHeader | `Property Get ShowHeader() As Boolean` / `Property Let ShowHeader(ByVal Value As Boolean)` | 是否显示标题 | | Selected | `Property Get Selected() As Boolean` / `Property Let Selected(ByVal Value As Boolean)` | 是否选中 | | Subseted | `Property Get Subseted() As Boolean` / `Property Let Subseted(ByVal Value As Boolean)` | 是否为子集 | | SubsetLinkSelected | `Property Get SubsetLinkSelected() As Boolean` / `Property Let SubsetLinkSelected(ByVal Value As Boolean)` | 子集链接是否选中 | | Icon | `Property Get Icon() As Variant` / `Property Let Icon(ByVal Value As Variant)` | 图标 | | IconIndex | `Property Get IconIndex() As Long` | 图标索引。只读 | | Position | `Property Get Position() As Long` / `Property Let Position(ByVal Value As Long)` | 位置 | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | 左边距 | | Top | `Property Get Top() As Single` / `Property Let Top(ByVal Value As Single)` | 顶边距 | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | 宽度 | | Height | `Property Get Height() As Single` / `Property Let Height(ByVal Value As Single)` | 高度 | | ListItemCount | `Property Get ListItemCount() As Long` | 列表项数量。只读 | | ListItemIndices | `Property Get ListItemIndices() As Collection` | 列表项索引集合。只读 | ### LvwGroups 分组集合。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Item | `Property Get Item(ByVal Index As Variant) As LvwGroup` | 按索引获取分组 | | Count | `Property Get Count() As Long` | 分组数量。只读 | | Sorted | `Property Get Sorted() As Boolean` / `Property Let Sorted(ByVal Value As Boolean)` | 是否排序 | | SortOrder | `Property Get SortOrder() As LvwSortOrderConstants` / `Property Let SortOrder(ByVal Value As LvwSortOrderConstants)` | 排序顺序 | | SortType | `Property Get SortType() As LvwSortTypeConstants` / `Property Let SortType(ByVal Value As LvwSortTypeConstants)` | 排序类型 | #### 方法 | 名称 | 签名 | 说明 | |------|------|------| | Add | `Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Header As String, Optional ByVal HeaderAlignment As LvwGroupHeaderAlignmentConstants, Optional ByVal Footer As String, Optional ByVal FooterAlignment As LvwGroupFooterAlignmentConstants) As LvwGroup` | 添加分组 | | Exists | `Public Function Exists(ByVal Index As Variant) As Boolean` | 检查分组是否存在 | | Clear | `Public Sub Clear()` | 清除所有分组 | | Remove | `Public Sub Remove(ByVal Index As Variant)` | 移除分组 | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | 枚举器 | ### LvwVirtualListItem 虚拟列表项对象。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Index | `Property Get Index() As Long` | 索引。只读 | | Text | `Property Get Text() As String` | 文本。只读 | | Indentation | `Property Get Indentation() As Long` | 缩进。只读 | | Selected | `Property Get Selected() As Boolean` / `Property Let Selected(ByVal Value As Boolean)` | 是否选中 | | Checked | `Property Get Checked() As Boolean` | 复选框状态。只读 | | Hot | `Property Get Hot() As Boolean` / `Property Let Hot(ByVal Value As Boolean)` | 是否为热项 | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | 左边距 | | Top | `Property Get Top() As Single` / `Property Let Top(ByVal Value As Single)` | 顶边距 | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | 宽度 | | Height | `Property Get Height() As Single` / `Property Let Height(ByVal Value As Single)` | 高度 | | Visible | `Property Get Visible() As Boolean` | 是否可见。只读 | | SubItems | `Property Get SubItems(ByVal Index As Integer) As String` | 按索引获取子项文本。只读 | #### 方法 | 名称 | 签名 | 说明 | |------|------|------| | EnsureVisible | `Public Sub EnsureVisible()` | 确保项可见 | | CreateDragImage | `Public Function CreateDragImage(Optional ByRef X As Single, Optional ByRef Y As Single) As LongPtr` | 创建拖动图像 | ### LvwVirtualListItems 虚拟列表项集合。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Item | `Property Get Item(ByVal Index As Long) As LvwVirtualListItem` | 按索引获取虚拟列表项 | | Count | `Property Get Count() As Long` | 虚拟列表项数量。只读 | #### 方法 | 名称 | 签名 | 说明 | |------|------|------| | Exists | `Public Function Exists(ByVal Index As Long) As Boolean` | 检查虚拟列表项是否存在 | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | 枚举器 | ### LvwWorkArea 工作区域对象。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Index | `Property Get Index() As Long` | 索引。只读 | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | 左边距 | | Top | `Property Get Top() As Single` / `Property Let Top(ByVal Value As Single)` | 顶边距 | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | 宽度 | | Height | `Property Get Height() As Single` / `Property Let Height(ByVal Value As Single)` | 高度 | | ListItemIndices | `Property Get ListItemIndices() As Collection` | 工作区域中的列表项索引集合。只读 | ### LvwWorkAreas 工作区域集合。 #### 属性 | 名称 | 签名 | 说明 | |------|------|------| | Item | `Property Get Item(ByVal Index As Long) As LvwWorkArea` | 按索引获取工作区域 | | Count | `Property Get Count() As Long` | 工作区域数量。只读 | #### 方法 | 名称 | 签名 | 说明 | |------|------|------| | Add | `Public Function Add(ByVal Left As Single, ByVal Top As Single, ByVal Width As Single, ByVal Height As Single, Optional ByVal Index As Long) As LvwWorkArea` | 添加工作区域 | | Exists | `Public Function Exists(ByVal Index As Long) As Boolean` | 检查工作区域是否存在 | | Clear | `Public Sub Clear()` | 清除所有工作区域 | | Remove | `Public Sub Remove(ByVal Index As Long)` | 移除工作区域 | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | 枚举器 | ## 代码示例 ### 报表视图基本用法 ```vb ' 设置报表视图 ListView1.View = LvwViewReport ' 添加列标题 With ListView1.ColumnHeaders .Add , , "姓名", 120 .Add , , "年龄", 60, LvwColumnHeaderAlignmentCenter .Add , , "城市", 100 End With ' 添加列表项 Dim li As LvwListItem Set li = ListView1.ListItems.Add(, , "张三") li.SubItems(1) = "28" li.SubItems(2) = "北京" Set li = ListView1.ListItems.Add(, , "李四") li.SubItems(1) = "35" li.SubItems(2) = "上海" ``` ### 分组视图 ```vb ' 启用分组 ListView1.GroupView = True ListView1.View = LvwViewReport ' 添加分组 Dim grp1 As LvwGroup, grp2 As LvwGroup Set grp1 = ListView1.Groups.Add(, , "一组") Set grp2 = ListView1.Groups.Add(, , "二组") ' 将项分配到分组 Set ListView1.ListItems(1).Group = grp1 Set ListView1.ListItems(2).Group = grp2 ``` ### 虚拟模式 ```vb ' 启用虚拟模式 ListView1.VirtualMode = True ListView1.VirtualItemCount = 10000 ' 在 GetVirtualItem 事件中提供数据 Private Sub ListView1_GetVirtualItem(ByVal ItemIndex As Long, _ ByVal SubItemIndex As Long, _ ByVal VirtualProperty As LvwVirtualPropertyConstants, _ ByRef Value As Variant) If VirtualProperty = LvwVirtualPropertyText Then If SubItemIndex = 0 Then Value = "Item " & ItemIndex Else Value = "Sub " & SubItemIndex End If End If End Sub ``` ### 排序和筛选 ```vb ' 排序 ListView1.SortKey = 0 ListView1.SortOrder = LvwSortOrderAscending ListView1.SortType = LvwSortTypeText ListView1.Sorted = True ' 设置排序箭头 ListView1.ColumnHeaders(1).SortArrow = LvwColumnHeaderSortArrowDown ' 启用列筛选 ListView1.UseColumnFilterBar = True ``` --- --- url: /zh/official/Reference/CEF/Enumerations.md --- # 枚举 **CEF** 包暴露的两个面向用户的枚举。包中更大的一组内部 `cef_*_t` 枚举(镜像CEF C API)存在于 `Private Module` 包装器中,不属于公共API。 | 枚举 | 使用者 | |-------------|---------| | [CefLogSeverity](/official/Reference/CEF/Enumerations/CefLogSeverity) | [**EnvironmentOptions.LogSeverity**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#logseverity) | | [cefPrintOrientation](/official/Reference/CEF/Enumerations/cefPrintOrientation) | [**PrintToPdf**](/official/Reference/CEF/CefBrowser/#printtopdf) 上的 `Orientation` | --- --- url: /zh/official/Reference/CustomControls/Enumerations.md --- # 枚举 **CustomControls** 包的属性和样式对象使用的枚举。所有枚举定义在 **CustomControls DESIGNER** 库的 `Module Constants` 中,除 [**SliderDirection**](/official/Reference/CustomControls/WaynesSlider/#sliderdirection) 和 [**SliderDisplayValueFormat**](/official/Reference/CustomControls/WaynesSlider/#sliderdisplayvalueformat) 枚举嵌套在 **WaynesSlider** 控件内部。 | 枚举 | 使用者 | |------|--------| | [BorderStyle](/official/Reference/CustomControls/Enumerations/BorderStyle) | [**WindowsFormOptions.BorderStyle**](/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#borderstyle) | | [ColorRGBA](/official/Reference/CustomControls/Enumerations/ColorRGBA) | [**FillColorPoint.Color**](/official/Reference/CustomControls/Styles/Fill#color);ABGR 颜色的 `Long` 兼容类型别名 | | [CornerShape](/official/Reference/CustomControls/Enumerations/CornerShape) | [**Corner.Shape**](/official/Reference/CustomControls/Styles/Corners#shape) | | [Customtate](/official/Reference/CustomControls/Enumerations/Customtate) | 保留;[**WindowState**](/official/Reference/CustomControls/Enumerations/WindowState) 的副本 | | [DockMode](/official/Reference/CustomControls/Enumerations/DockMode) | 每个控件继承的 **Dock** 属性 | | [FillPattern](/official/Reference/CustomControls/Enumerations/FillPattern) | [**Fill.Pattern**](/official/Reference/CustomControls/Styles/Fill#pattern) | | [FontWeight](/official/Reference/CustomControls/Enumerations/FontWeight) | [**FontStyle.Weight**](/official/Reference/CustomControls/Styles/TextRendering#weight) | | [PixelCount](/official/Reference/CustomControls/Enumerations/PixelCount) | 大小、位置、内边距、笔触粗细、半径;`Long` 兼容类型别名 | | [PointSize](/official/Reference/CustomControls/Enumerations/PointSize) | [**FontStyle.Size**](/official/Reference/CustomControls/Styles/TextRendering#size);`Long` 兼容类型别名 | | [StartupPosition](/official/Reference/CustomControls/Enumerations/StartupPosition) | [**WindowsFormOptions.StartUpPosition**](/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#startupposition) | | [TextAlignment](/official/Reference/CustomControls/Enumerations/TextAlignment) | [**TextRendering.Alignment**](/official/Reference/CustomControls/Styles/TextRendering#alignment) | | [TextOverflowMode](/official/Reference/CustomControls/Enumerations/TextOverflowMode) | [**TextRendering.OverflowMode**](/official/Reference/CustomControls/Styles/TextRendering#overflowmode) | | [WindowState](/official/Reference/CustomControls/Enumerations/WindowState) | [**WindowsFormOptions.WindowState**](/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#windowstate) | --- --- url: /zh/official/Reference/Enumerations.md --- # 枚举 *枚举*定义一组命名的整数常量。传递枚举成员而非裸整数使调用点自文档化,并允许IDE补全有效值。每个内置包将其枚举分组在专用子文件夹下;本页索引所有枚举。 以下各节[按包](#按包分组)列出枚举,之后是[字母顺序索引](#字母顺序索引)。 *** ## 按包分组 ### VBA包 15个枚举,涵盖窗口样式、比较模式、消息框选项、变量类型、日期时间常量、文件属性等。 * [**VbAppWinStyle**](/official/Reference/VBA/Constants/VbAppWinStyle) -- [**Shell**](/official/Reference/VBA/Interaction/Shell)的*windowstyle*参数的窗口样式值 * [**VbArchitecture**](/official/Reference/VBA/Constants/VbArchitecture) -- [**ProcessorArchitecture**](/official/Reference/VBA/Compilation/ProcessorArchitecture)返回的处理器架构值 * [**VbCalendar**](/official/Reference/VBA/Constants/VbCalendar) -- [**Calendar**](/official/Reference/Core/Calendar)属性的日历类型值 * [**VbCallType**](/official/Reference/VBA/Constants/VbCallType) -- **CallByName**的过程调用类型标志 * [**VbCompareMethod**](/official/Reference/VBA/Constants/VbCompareMethod) -- [**InStr**](/official/Reference/VBA/Strings/InStr)、[**Replace**](/official/Reference/VBA/Strings/Replace)、[**Split**](/official/Reference/VBA/Strings/Split)等的文本比较模式 * [**VbDateTimeFormat**](/official/Reference/VBA/Constants/VbDateTimeFormat) -- [**FormatDateTime**](/official/Reference/VBA/Strings/FormatDateTime)的格式代码 * [**VbDayOfWeek**](/official/Reference/VBA/Constants/VbDayOfWeek) -- [**DateAdd**](/official/Reference/VBA/DateTime/DateAdd)、[**DateDiff**](/official/Reference/VBA/DateTime/DateDiff)、[**Weekday**](/official/Reference/VBA/DateTime/Weekday)等的星期常量 * [**VbFileAttribute**](/official/Reference/VBA/Constants/VbFileAttribute) -- [**Dir**](/official/Reference/VBA/FileSystem/Dir)、[**GetAttr**](/official/Reference/VBA/FileSystem/GetAttr)和[**SetAttr**](/official/Reference/VBA/FileSystem/SetAttr)的属性标志 * [**VbFirstWeekOfYear**](/official/Reference/VBA/Constants/VbFirstWeekOfYear) -- [**DateDiff**](/official/Reference/VBA/DateTime/DateDiff)、[**DatePart**](/official/Reference/VBA/DateTime/DatePart)和[**Weekday**](/official/Reference/VBA/DateTime/Weekday)的首周选择器 * [**VbIMEStatus**](/official/Reference/VBA/Constants/VbIMEStatus) -- 输入法编辑器模式常量 * [**VbMsgBoxResult**](/official/Reference/VBA/Constants/VbMsgBoxResult) -- 标识[**MsgBox**](/official/Reference/VBA/Interaction/MsgBox)对话框中单击的按钮 * [**VbMsgBoxStyle**](/official/Reference/VBA/Constants/VbMsgBoxStyle) -- [**MsgBox**](/official/Reference/VBA/Interaction/MsgBox)的按钮、图标、模态等标志 * [**VbStrConv**](/official/Reference/VBA/Constants/VbStrConv) -- [**StrConv**](/official/Reference/VBA/Strings/StrConv)的转换类型标志 * [**VbTriState**](/official/Reference/VBA/Constants/VbTriState) -- [**FormatNumber**](/official/Reference/VBA/Strings/FormatNumber)和[**FormatCurrency**](/official/Reference/VBA/Strings/FormatCurrency)等格式化函数的三态值 * [**VbVarType**](/official/Reference/VBA/Constants/VbVarType) -- [**VarType**](/official/Reference/VBA/Information/VarType)返回的Variant子类型代码 ### VBRUN包 86个枚举,涵盖经典VB6控件和窗体的各个方面 --- 对齐、边框样式、颜色、拖放、OLE容器选项、打印机设置、窗口状态等。 * [**AlignConstants**](/official/Reference/VBRUN/Constants/AlignConstants) -- 图片框、工具栏和数据控件的**Align**属性值 * [**AlignmentConstants**](/official/Reference/VBRUN/Constants/AlignmentConstants) -- 标签、文本框和选项按钮控件的文本对齐 * [**AlignmentConstantsNoCenter**](/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter) -- 不支持居中的左/右对齐值 * [**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants) -- **Appearance**属性的绘制样式 * [**ApplicationStartConstants**](/official/Reference/VBRUN/Constants/ApplicationStartConstants) -- 独立启动与Automation调用启动模式 * [**AspectTypeConstants**](/official/Reference/VBRUN/Constants/AspectTypeConstants) -- **DataObjectFormat**的OLE渲染方面标识符 * [**AsyncReadConstants**](/official/Reference/VBRUN/Constants/AsyncReadConstants) -- **UserControl.AsyncRead**的*AsyncReadOptions*参数标志 * [**AsyncStatusCodeConstants**](/official/Reference/VBRUN/Constants/AsyncStatusCodeConstants) -- **AsyncReadProgress**期间报告的状态代码 * [**AsyncTypeConstants**](/official/Reference/VBRUN/Constants/AsyncTypeConstants) -- **UserControl.AsyncRead**传递的数据类型 * [**BackFillStyleConstants**](/official/Reference/VBRUN/Constants/BackFillStyleConstants) -- 不透明与透明背景填充 * [**BorderStyleConstants**](/official/Reference/VBRUN/Constants/BorderStyleConstants) -- Shape和Line控件**BorderStyle**属性的线条样式 * [**ButtonConstants**](/official/Reference/VBRUN/Constants/ButtonConstants) -- 命令按钮样式,可选基于图片的外观 * [**CheckBoxConstants**](/official/Reference/VBRUN/Constants/CheckBoxConstants) -- 复选框**Value**属性的状态值 * [**ClipboardConstants**](/official/Reference/VBRUN/Constants/ClipboardConstants) -- **DataObject**和**Clipboard**的剪贴板格式标识符 * [**ColorConstants**](/official/Reference/VBRUN/Constants/ColorConstants) -- 常用命名RGB颜色 * [**ComboBoxConstants**](/official/Reference/VBRUN/Constants/ComboBoxConstants) -- 组合框**Style**属性的样式值 * [**ControlBorderStyleConstants**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants) -- 文本框、图片框和标签的边框样式 * [**ControlBorderStyleConstantsCustom**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstantsCustom) -- 包含自绘边框的扩展边框样式 * [**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants) -- 标准内部控件类型标识符 * [**DatabaseTypeConstants**](/official/Reference/VBRUN/Constants/DatabaseTypeConstants) -- Data控件**DefaultType**属性的数据库引擎 * [**DataBOFconstants**](/official/Reference/VBRUN/Constants/DataBOFconstants) -- 用户移动超过记录集起始处时的操作 * [**DataEOFConstants**](/official/Reference/VBRUN/Constants/DataEOFConstants) -- 用户移动超过记录集末尾处时的操作 * [**DataErrorConstants**](/official/Reference/VBRUN/Constants/DataErrorConstants) -- Data控件**Error**事件的响应值 * [**DataValidateConstants**](/official/Reference/VBRUN/Constants/DataValidateConstants) -- **Validate**事件中的操作代码 * [**DefaultCursorTypeConstants**](/official/Reference/VBRUN/Constants/DefaultCursorTypeConstants) -- Data控件连接的游标驱动程序 * [**DockModeConstants**](/official/Reference/VBRUN/Constants/DockModeConstants) -- 窗体和工具栏的停靠边缘值 * [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants) -- **Drag**方法的操作值 * [**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants) -- 控件的自动与手动拖动模式 * [**DragOverConstants**](/official/Reference/VBRUN/Constants/DragOverConstants) -- **DragOver**事件中的状态值 * [**DrawModeConstants**](/official/Reference/VBRUN/Constants/DrawModeConstants) -- **DrawMode**属性的GDI光栅操作值 * [**DrawStyleConstants**](/official/Reference/VBRUN/Constants/DrawStyleConstants) -- **DrawStyle**属性的线条样式 * [**FillStyleConstants**](/official/Reference/VBRUN/Constants/FillStyleConstants) -- **FillStyle**属性的填充图案 * [**FillStyleConstantsEx**](/official/Reference/VBRUN/Constants/FillStyleConstantsEx) -- 包含渐变填充的扩展填充图案 * [**FormArrangeConstants**](/official/Reference/VBRUN/Constants/FormArrangeConstants) -- MDI **Arrange**方法的排列模式 * [**FormBorderStyleConstants**](/official/Reference/VBRUN/Constants/FormBorderStyleConstants) -- 窗体**BorderStyle**属性的边框和框架样式 * [**FormShowConstants**](/official/Reference/VBRUN/Constants/FormShowConstants) -- **Show**的*Modal*参数的模态值 * [**FormWindowStateConstants**](/official/Reference/VBRUN/Constants/FormWindowStateConstants) -- 窗体**WindowState**属性的窗口状态值 * [**HitResultConstants**](/official/Reference/VBRUN/Constants/HitResultConstants) -- **UserControl**的**HitTest**事件返回值 * [**KeyCodeConstants**](/official/Reference/VBRUN/Constants/KeyCodeConstants) -- **KeyDown**和**KeyUp**事件的虚拟键代码 * [**LinkModeConstants**](/official/Reference/VBRUN/Constants/LinkModeConstants) -- **LinkMode**属性的DDE链接模式值 * [**ListBoxConstants**](/official/Reference/VBRUN/Constants/ListBoxConstants) -- 列表框**Style**属性的样式值 * [**LoadPictureColorConstants**](/official/Reference/VBRUN/Constants/LoadPictureColorConstants) -- **LoadPicture**的颜色深度 * [**LoadPictureSizeConstants**](/official/Reference/VBRUN/Constants/LoadPictureSizeConstants) -- **LoadPicture**的大小选择器 * [**LoadResConstants**](/official/Reference/VBRUN/Constants/LoadResConstants) -- **LoadResPicture**的资源类型值 * [**LogEventTypeConstants**](/official/Reference/VBRUN/Constants/LogEventTypeConstants) -- **LogEvent**的严重性值 * [**LogModeConstants**](/official/Reference/VBRUN/Constants/LogModeConstants) -- **App.StartLogging**的目标和行为标志 * [**MenuAccelConstants**](/official/Reference/VBRUN/Constants/MenuAccelConstants) -- 菜单项快捷键的键盘加速键代码 * [**MenuControlConstants**](/official/Reference/VBRUN/Constants/MenuControlConstants) -- **PopupMenu**的对齐和触发按钮标志 * [**MouseButtonConstants**](/official/Reference/VBRUN/Constants/MouseButtonConstants) -- 鼠标事件*Button*参数的位标志 * [**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants) -- **MousePointer**属性的光标形状值 * [**MultiSelectConstants**](/official/Reference/VBRUN/Constants/MultiSelectConstants) -- 列表框**MultiSelect**属性的多选模式 * [**NegotiatePositionConstants**](/official/Reference/VBRUN/Constants/NegotiatePositionConstants) -- OLE就地激活期间的菜单位置 * [**OldLinkModeConstants**](/official/Reference/VBRUN/Constants/OldLinkModeConstants) -- 为兼容性保留的旧版DDE链接模式值 * [**OLEContainerActivateConstants**](/official/Reference/VBRUN/Constants/OLEContainerActivateConstants) -- **AutoActivate**属性的激活触发器 * [**OLEContainerConstants**](/official/Reference/VBRUN/Constants/OLEContainerConstants) -- 所有OLE容器选项值的组合枚举 * [**OLEContainerDisplayTypeConstants**](/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants) -- OLE容器**DisplayType**属性的显示样式 * [**OLEContainerSizeModeConstants**](/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants) -- OLE容器**SizeMode**属性的大小调整规则 * [**OLEContainerTypesAllowedConstants**](/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants) -- **OLETypeAllowed**的对象类型筛选器 * [**OLEContainerUpdateOptionsConstants**](/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants) -- 链接OLE对象的更新模式 * [**OLEDragConstants**](/official/Reference/VBRUN/Constants/OLEDragConstants) -- **OLEDragMode**的OLE拖动模式值 * [**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants) -- **OLEDropMode**的OLE放置模式值 * [**OLEDropEffectConstants**](/official/Reference/VBRUN/Constants/OLEDropEffectConstants) -- OLE拖放事件*Effect*参数的位标志 * [**PaletteModeConstants**](/official/Reference/VBRUN/Constants/PaletteModeConstants) -- 窗体和UserControl的调色板来源值 * [**ParentControlsType**](/official/Reference/VBRUN/Constants/ParentControlsType) -- **ParentControls**集合的包装模式 * [**PictureTypeConstants**](/official/Reference/VBRUN/Constants/PictureTypeConstants) -- **stdole.IPictureDisp**的子类型值 * [**PrinterObjectConstants**](/official/Reference/VBRUN/Constants/PrinterObjectConstants) -- 所有**Printer**对象选项值的组合枚举 * [**PrinterObjectConstants\_ColorMode**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_ColorMode) -- **Printer.ColorMode**的颜色模式 * [**PrinterObjectConstants\_Duplex**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_Duplex) -- **Printer.Duplex**的双面模式 * [**PrinterObjectConstants\_Orientation**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_Orientation) -- **Printer.Orientation**的纸张方向 * [**PrinterObjectConstants\_PaperBin**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperBin) -- **Printer.PaperBin**的纸张来源 * [**PrinterObjectConstants\_PaperSize**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperSize) -- **Printer.PaperSize**的纸张大小 * [**PrinterObjectConstants\_PrintQuality**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_PrintQuality) -- **Printer.PrintQuality**的打印质量 * [**QueryUnloadConstants**](/official/Reference/VBRUN/Constants/QueryUnloadConstants) -- 窗体**QueryUnload**事件的原因代码 * [**RasterOpConstants**](/official/Reference/VBRUN/Constants/RasterOpConstants) -- **PaintPicture**的GDI光栅操作代码 * [**RecordsetTypeConstants**](/official/Reference/VBRUN/Constants/RecordsetTypeConstants) -- Data控件的记录集类型 * [**ScaleModeConstants**](/official/Reference/VBRUN/Constants/ScaleModeConstants) -- **ScaleMode**属性的度量单位 * [**ScrollBarConstants**](/official/Reference/VBRUN/Constants/ScrollBarConstants) -- 文本框等控件上显示的滚动条 * [**ShapeConstants**](/official/Reference/VBRUN/Constants/ShapeConstants) -- Shape控件**Shape**属性的几何形状值 * [**ShiftConstants**](/official/Reference/VBRUN/Constants/ShiftConstants) -- 鼠标和键盘事件的修饰键位标志 * [**ShortcutConstants**](/official/Reference/VBRUN/Constants/ShortcutConstants) -- 菜单项的快捷键标识符 * [**StartUpPositionConstants**](/official/Reference/VBRUN/Constants/StartUpPositionConstants) -- 窗体**StartUpPosition**属性的初始位置 * [**StorageTypeContants**](/official/Reference/VBRUN/Constants/StorageTypeContants) -- **DataObjectFormat**的OLE数据存储介质标识符 * [**SystemColorConstants**](/official/Reference/VBRUN/Constants/SystemColorConstants) -- 系统UI颜色引用(通过**TranslateColor**转换为纯RGB) * [**VariantTypeConstants**](/official/Reference/VBRUN/Constants/VariantTypeConstants) -- 为兼容性保留的旧版DAO字段类型标签 * [**VerticalAlignmentConstants**](/official/Reference/VBRUN/Constants/VerticalAlignmentConstants) -- 单元格样式控件的垂直文本对齐 * [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants) -- **ZOrder**方法的位置选择器 ### WebView2包 10个枚举,涵盖导航错误、权限、下载位置、脚本对话框、打印方向和资源请求过滤。 * [**wv2DefaultDownloadCornerAlign**](/official/Reference/WebView2/Enumerations/wv2DefaultDownloadCornerAlign) -- 将内置下载进度对话框锚定到控件的角落 * [**wv2ErrorStatus**](/official/Reference/WebView2/Enumerations/wv2ErrorStatus) -- 导航失败的原因(在**NavigationComplete**事件中传递) * [**wv2HostResourceAccessKind**](/official/Reference/WebView2/Enumerations/wv2HostResourceAccessKind) -- 虚拟主机名映射的跨域访问策略 * [**wv2KeyEventKind**](/official/Reference/WebView2/Enumerations/wv2KeyEventKind) -- **AcceleratorKeyPressed**事件中的键盘消息类型 * [**wv2PermissionKind**](/official/Reference/WebView2/Enumerations/wv2PermissionKind) -- 页面正在请求的设备或浏览器功能 * [**wv2PermissionState**](/official/Reference/WebView2/Enumerations/wv2PermissionState) -- 宿主对权限请求的决定 * [**wv2PrintOrientation**](/official/Reference/WebView2/Enumerations/wv2PrintOrientation) -- **PrintToPdf**的页面方向 * [**wv2ProcessFailedKind**](/official/Reference/WebView2/Enumerations/wv2ProcessFailedKind) -- 标识哪个WebView2进程失败 * [**wv2ScriptDialogKind**](/official/Reference/WebView2/Enumerations/wv2ScriptDialogKind) -- 页面试图打开的JavaScript对话框类型 * [**wv2WebResourceContext**](/official/Reference/WebView2/Enumerations/wv2WebResourceContext) -- Web资源过滤器匹配的请求类型 ### CustomControls包 13个枚举,控制`Waynes...`自定义控件的外观和行为。 * [**BorderStyle**](/official/Reference/CustomControls/Enumerations/BorderStyle) -- **WaynesForm**窗口的Win32框架样式 * [**ColorRGBA**](/official/Reference/CustomControls/Enumerations/ColorRGBA) -- 32位ABGR颜色值类型别名 * [**CornerShape**](/official/Reference/CustomControls/Enumerations/CornerShape) -- 控件单个角的形状(方形、圆角、切角) * [**Customtate**](/official/Reference/CustomControls/Enumerations/Customtate) -- 自定义状态绘制的控件状态标志 * [**DockMode**](/official/Reference/CustomControls/Enumerations/DockMode) -- 控件相对于其容器的停靠方式 * [**FillPattern**](/official/Reference/CustomControls/Enumerations/FillPattern) -- **Fill**中颜色停止点如何应用于绘制区域 * [**FontWeight**](/official/Reference/CustomControls/Enumerations/FontWeight) -- 标准100--900 OpenType刻度上的字重 * [**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount) -- 包中使用的像素度量类型别名 * [**PointSize**](/official/Reference/CustomControls/Enumerations/PointSize) -- 印刷点字体大小类型别名 * [**StartupPosition**](/official/Reference/CustomControls/Enumerations/StartupPosition) -- **WaynesForm**首次显示时的初始位置 * [**TextAlignment**](/official/Reference/CustomControls/Enumerations/TextAlignment) -- 控件内的水平和垂直文本对齐 * [**TextOverflowMode**](/official/Reference/CustomControls/Enumerations/TextOverflowMode) -- 不适合的文本如何截断 * [**WindowState**](/official/Reference/CustomControls/Enumerations/WindowState) -- **WaynesForm**的最小化、还原或最大化状态 ### CEF包 2个枚举,涵盖日志详细程度和打印方向。 * [**CefLogSeverity**](/official/Reference/CEF/Enumerations/CefLogSeverity) -- CEF运行时记录消息到调试日志的最低严重性 * [**cefPrintOrientation**](/official/Reference/CEF/Enumerations/cefPrintOrientation) -- **PrintToPdf**的页面方向 ### WinServicesLib包 4个枚举,涵盖服务类型、启动模式、控制代码和运行时状态。 * [**ServiceControlCodeConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants) -- SCM可向运行中的服务传递的控制代码 * [**ServiceStartConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceStartConstants) -- SCM何时以及如何启动服务 * [**ServiceStatusConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants) -- 服务向SCM报告的运行时状态值 * [**ServiceTypeConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceTypeConstants) -- Win32服务类型值(独立进程、共享宿主、内核驱动) ### WinNativeCommonCtls包 10个枚举,用于八种原生通用控件。 * [**DTPickerFormatConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants) -- **DTPicker**控件的显示格式 * [**ImlDrawConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) -- **ListImage.Draw**的渲染样式标志 * [**OrientationConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/OrientationConstants) -- **Slider**和**UpDown**的水平/垂直方向 * [**TreeBorderStyleConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeBorderStyleConstants) -- **TreeView**和**ListView**共享的边框样式 * [**TreeLabelEditConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeLabelEditConstants) -- **TreeView**上何时触发内联标签编辑 * [**TreeLineStyleConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeLineStyleConstants) -- **TreeView**是从根节点还是仅从子节点绘制连线 * [**TreeRelationshipConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeRelationshipConstants) -- 新节点相对于现有节点的插入位置 * [**TreeSortOrderConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortOrderConstants) -- **TreeView**和**Node**的升序或降序排序 * [**TreeSortTypeConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortTypeConstants) -- 区分大小写或不区分大小写的排序比较 * [**TreeStyleConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeStyleConstants) -- **TreeView**的复合视觉样式(按钮、连线、图标) *** ## 字母顺序索引 **A** * [**AlignConstants**](/official/Reference/VBRUN/Constants/AlignConstants) -- **Align**属性值(VBRUN) * [**AlignmentConstants**](/official/Reference/VBRUN/Constants/AlignmentConstants) -- 标签和文本框的文本对齐(VBRUN) * [**AlignmentConstantsNoCenter**](/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter) -- 不包含居中的左/右文本对齐(VBRUN) * [**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants) -- **Appearance**属性的绘制样式(VBRUN) * [**ApplicationStartConstants**](/official/Reference/VBRUN/Constants/ApplicationStartConstants) -- 独立与Automation启动模式(VBRUN) * [**AspectTypeConstants**](/official/Reference/VBRUN/Constants/AspectTypeConstants) -- OLE渲染方面标识符(VBRUN) * [**AsyncReadConstants**](/official/Reference/VBRUN/Constants/AsyncReadConstants) -- **UserControl.AsyncRead**选项标志(VBRUN) * [**AsyncStatusCodeConstants**](/official/Reference/VBRUN/Constants/AsyncStatusCodeConstants) -- **AsyncReadProgress**状态代码(VBRUN) * [**AsyncTypeConstants**](/official/Reference/VBRUN/Constants/AsyncTypeConstants) -- **UserControl.AsyncRead**的数据类型(VBRUN) **B** * [**BackFillStyleConstants**](/official/Reference/VBRUN/Constants/BackFillStyleConstants) -- 不透明与透明背景(VBRUN) * [**BorderStyle**](/official/Reference/CustomControls/Enumerations/BorderStyle) -- **WaynesForm**的Win32框架样式(CustomControls) * [**BorderStyleConstants**](/official/Reference/VBRUN/Constants/BorderStyleConstants) -- Shape和Line控件的线条样式(VBRUN) * [**ButtonConstants**](/official/Reference/VBRUN/Constants/ButtonConstants) -- 图形命令按钮的样式(VBRUN) **C** * [**CefLogSeverity**](/official/Reference/CEF/Enumerations/CefLogSeverity) -- CEF调试日志最低严重性(CEF) * [**cefPrintOrientation**](/official/Reference/CEF/Enumerations/cefPrintOrientation) -- **PrintToPdf**的页面方向(CEF) * [**CheckBoxConstants**](/official/Reference/VBRUN/Constants/CheckBoxConstants) -- 复选框**Value**属性状态(VBRUN) * [**ClipboardConstants**](/official/Reference/VBRUN/Constants/ClipboardConstants) -- 剪贴板格式标识符(VBRUN) * [**ColorConstants**](/official/Reference/VBRUN/Constants/ColorConstants) -- 命名RGB颜色(VBRUN) * [**ColorRGBA**](/official/Reference/CustomControls/Enumerations/ColorRGBA) -- 32位ABGR颜色类型别名(CustomControls) * [**ComboBoxConstants**](/official/Reference/VBRUN/Constants/ComboBoxConstants) -- 组合框**Style**属性值(VBRUN) * [**ControlBorderStyleConstants**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants) -- 内部控件的边框样式(VBRUN) * [**ControlBorderStyleConstantsCustom**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstantsCustom) -- 包含自绘的扩展边框样式(VBRUN) * [**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants) -- 标准内部控件类型标识符(VBRUN) * [**CornerShape**](/official/Reference/CustomControls/Enumerations/CornerShape) -- 角形状(方形、圆角、切角)(CustomControls) * [**Customtate**](/official/Reference/CustomControls/Enumerations/Customtate) -- 自定义绘制的控件状态标志(CustomControls) **D** * [**DatabaseTypeConstants**](/official/Reference/VBRUN/Constants/DatabaseTypeConstants) -- Data控件数据库引擎(VBRUN) * [**DataBOFconstants**](/official/Reference/VBRUN/Constants/DataBOFconstants) -- 记录集开始处的操作(VBRUN) * [**DataEOFConstants**](/official/Reference/VBRUN/Constants/DataEOFConstants) -- 记录集末尾处的操作(VBRUN) * [**DataErrorConstants**](/official/Reference/VBRUN/Constants/DataErrorConstants) -- Data控件**Error**事件响应值(VBRUN) * [**DataValidateConstants**](/official/Reference/VBRUN/Constants/DataValidateConstants) -- **Validate**事件中的操作代码(VBRUN) * [**DefaultCursorTypeConstants**](/official/Reference/VBRUN/Constants/DefaultCursorTypeConstants) -- Data控件连接的游标驱动程序(VBRUN) * [**DockMode**](/official/Reference/CustomControls/Enumerations/DockMode) -- CustomControl如何停靠(CustomControls) * [**DockModeConstants**](/official/Reference/VBRUN/Constants/DockModeConstants) -- 窗体和工具栏的停靠边缘值(VBRUN) * [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants) -- **Drag**方法操作值(VBRUN) * [**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants) -- 自动与手动拖动模式(VBRUN) * [**DragOverConstants**](/official/Reference/VBRUN/Constants/DragOverConstants) -- **DragOver**事件中的状态值(VBRUN) * [**DrawModeConstants**](/official/Reference/VBRUN/Constants/DrawModeConstants) -- **DrawMode**的GDI光栅操作(VBRUN) * [**DrawStyleConstants**](/official/Reference/VBRUN/Constants/DrawStyleConstants) -- **DrawStyle**属性的线条样式(VBRUN) * [**DTPickerFormatConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants) -- **DTPicker**显示格式(WinNativeCommonCtls) **F** * [**FillPattern**](/official/Reference/CustomControls/Enumerations/FillPattern) -- **Fill**中颜色停止点如何应用(CustomControls) * [**FillStyleConstants**](/official/Reference/VBRUN/Constants/FillStyleConstants) -- **FillStyle**属性的填充图案(VBRUN) * [**FillStyleConstantsEx**](/official/Reference/VBRUN/Constants/FillStyleConstantsEx) -- 包含渐变填充的扩展填充图案(VBRUN) * [**FontWeight**](/official/Reference/CustomControls/Enumerations/FontWeight) -- 100--900刻度上的字重(CustomControls) * [**FormArrangeConstants**](/official/Reference/VBRUN/Constants/FormArrangeConstants) -- MDI子窗口排列模式(VBRUN) * [**FormBorderStyleConstants**](/official/Reference/VBRUN/Constants/FormBorderStyleConstants) -- 窗体边框和框架样式(VBRUN) * [**FormShowConstants**](/official/Reference/VBRUN/Constants/FormShowConstants) -- **Show**的模态性(VBRUN) * [**FormWindowStateConstants**](/official/Reference/VBRUN/Constants/FormWindowStateConstants) -- 窗体窗口状态(VBRUN) **H** * [**HitResultConstants**](/official/Reference/VBRUN/Constants/HitResultConstants) -- **UserControl.HitTest**返回值(VBRUN) **I** * [**ImlDrawConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) -- **ListImage.Draw**渲染样式标志(WinNativeCommonCtls) **K** * [**KeyCodeConstants**](/official/Reference/VBRUN/Constants/KeyCodeConstants) -- 键盘事件的虚拟键代码(VBRUN) **L** * [**LinkModeConstants**](/official/Reference/VBRUN/Constants/LinkModeConstants) -- DDE链接模式值(VBRUN) * [**ListBoxConstants**](/official/Reference/VBRUN/Constants/ListBoxConstants) -- 列表框**Style**属性值(VBRUN) * [**LoadPictureColorConstants**](/official/Reference/VBRUN/Constants/LoadPictureColorConstants) -- **LoadPicture**颜色深度(VBRUN) * [**LoadPictureSizeConstants**](/official/Reference/VBRUN/Constants/LoadPictureSizeConstants) -- **LoadPicture**大小选择器(VBRUN) * [**LoadResConstants**](/official/Reference/VBRUN/Constants/LoadResConstants) -- **LoadResPicture**资源类型(VBRUN) * [**LogEventTypeConstants**](/official/Reference/VBRUN/Constants/LogEventTypeConstants) -- **LogEvent**严重性值(VBRUN) * [**LogModeConstants**](/official/Reference/VBRUN/Constants/LogModeConstants) -- **App.StartLogging**目标标志(VBRUN) **M** * [**MenuAccelConstants**](/official/Reference/VBRUN/Constants/MenuAccelConstants) -- 菜单项键盘加速键代码(VBRUN) * [**MenuControlConstants**](/official/Reference/VBRUN/Constants/MenuControlConstants) -- **PopupMenu**对齐和触发标志(VBRUN) * [**MouseButtonConstants**](/official/Reference/VBRUN/Constants/MouseButtonConstants) -- 鼠标事件*Button*参数位标志(VBRUN) * [**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants) -- **MousePointer**属性光标形状(VBRUN) * [**MultiSelectConstants**](/official/Reference/VBRUN/Constants/MultiSelectConstants) -- 列表框多选模式(VBRUN) **N** * [**NegotiatePositionConstants**](/official/Reference/VBRUN/Constants/NegotiatePositionConstants) -- OLE就地激活期间的菜单位置(VBRUN) **O** * [**OldLinkModeConstants**](/official/Reference/VBRUN/Constants/OldLinkModeConstants) -- 旧版DDE链接模式值(VBRUN) * [**OLEContainerActivateConstants**](/official/Reference/VBRUN/Constants/OLEContainerActivateConstants) -- OLE容器自动激活触发器(VBRUN) * [**OLEContainerConstants**](/official/Reference/VBRUN/Constants/OLEContainerConstants) -- 组合的OLE容器选项值(VBRUN) * [**OLEContainerDisplayTypeConstants**](/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants) -- OLE容器显示样式(VBRUN) * [**OLEContainerSizeModeConstants**](/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants) -- OLE容器大小调整规则(VBRUN) * [**OLEContainerTypesAllowedConstants**](/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants) -- OLE容器对象类型筛选器(VBRUN) * [**OLEContainerUpdateOptionsConstants**](/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants) -- OLE容器更新模式(VBRUN) * [**OLEDragConstants**](/official/Reference/VBRUN/Constants/OLEDragConstants) -- **OLEDragMode**属性值(VBRUN) * [**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants) -- **OLEDropMode**属性值(VBRUN) * [**OLEDropEffectConstants**](/official/Reference/VBRUN/Constants/OLEDropEffectConstants) -- OLE拖放*Effect*位标志(VBRUN) * [**OrientationConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/OrientationConstants) -- **Slider**和**UpDown**的水平/垂直(WinNativeCommonCtls) **P** * [**PaletteModeConstants**](/official/Reference/VBRUN/Constants/PaletteModeConstants) -- 窗体和UserControl的调色板来源(VBRUN) * [**ParentControlsType**](/official/Reference/VBRUN/Constants/ParentControlsType) -- **ParentControls**集合包装模式(VBRUN) * [**PictureTypeConstants**](/official/Reference/VBRUN/Constants/PictureTypeConstants) -- **IPictureDisp**子类型值(VBRUN) * [**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount) -- 像素度量类型别名(CustomControls) * [**PointSize**](/official/Reference/CustomControls/Enumerations/PointSize) -- 印刷点字体大小类型别名(CustomControls) * [**PrinterObjectConstants**](/official/Reference/VBRUN/Constants/PrinterObjectConstants) -- 组合的**Printer**对象选项值(VBRUN) * [**PrinterObjectConstants\_ColorMode**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_ColorMode) -- **Printer.ColorMode**值(VBRUN) * [**PrinterObjectConstants\_Duplex**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_Duplex) -- **Printer.Duplex**值(VBRUN) * [**PrinterObjectConstants\_Orientation**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_Orientation) -- **Printer.Orientation**值(VBRUN) * [**PrinterObjectConstants\_PaperBin**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperBin) -- **Printer.PaperBin**值(VBRUN) * [**PrinterObjectConstants\_PaperSize**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperSize) -- **Printer.PaperSize**值(VBRUN) * [**PrinterObjectConstants\_PrintQuality**](/official/Reference/VBRUN/Constants/PrinterObjectConstants_PrintQuality) -- **Printer.PrintQuality**值(VBRUN) **Q** * [**QueryUnloadConstants**](/official/Reference/VBRUN/Constants/QueryUnloadConstants) -- **QueryUnload**事件原因代码(VBRUN) **R** * [**RasterOpConstants**](/official/Reference/VBRUN/Constants/RasterOpConstants) -- **PaintPicture**的GDI光栅操作代码(VBRUN) * [**RecordsetTypeConstants**](/official/Reference/VBRUN/Constants/RecordsetTypeConstants) -- Data控件记录集类型(VBRUN) **S** * [**ScaleModeConstants**](/official/Reference/VBRUN/Constants/ScaleModeConstants) -- **ScaleMode**的度量单位(VBRUN) * [**ScrollBarConstants**](/official/Reference/VBRUN/Constants/ScrollBarConstants) -- 控件上显示的滚动条(VBRUN) * [**ServiceControlCodeConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants) -- 运行中服务的SCM控制代码(WinServicesLib) * [**ServiceStartConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceStartConstants) -- 服务启动模式(WinServicesLib) * [**ServiceStatusConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants) -- 服务运行时状态值(WinServicesLib) * [**ServiceTypeConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceTypeConstants) -- Win32服务类型(WinServicesLib) * [**ShapeConstants**](/official/Reference/VBRUN/Constants/ShapeConstants) -- Shape控件的几何形状(VBRUN) * [**ShiftConstants**](/official/Reference/VBRUN/Constants/ShiftConstants) -- 鼠标和键盘事件的修饰键位标志(VBRUN) * [**ShortcutConstants**](/official/Reference/VBRUN/Constants/ShortcutConstants) -- 菜单项键盘快捷键标识符(VBRUN) * [**StartupPosition**](/official/Reference/CustomControls/Enumerations/StartupPosition) -- **WaynesForm**的初始位置(CustomControls) * [**StartUpPositionConstants**](/official/Reference/VBRUN/Constants/StartUpPositionConstants) -- 窗体**StartUpPosition**属性值(VBRUN) * [**StorageTypeContants**](/official/Reference/VBRUN/Constants/StorageTypeContants) -- OLE数据存储介质标识符(VBRUN) * [**SystemColorConstants**](/official/Reference/VBRUN/Constants/SystemColorConstants) -- 系统UI颜色引用(VBRUN) **T** * [**TextAlignment**](/official/Reference/CustomControls/Enumerations/TextAlignment) -- 水平和垂直文本对齐(CustomControls) * [**TextOverflowMode**](/official/Reference/CustomControls/Enumerations/TextOverflowMode) -- 文本截断模式(CustomControls) * [**TreeBorderStyleConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeBorderStyleConstants) -- **TreeView**和**ListView**边框样式(WinNativeCommonCtls) * [**TreeLabelEditConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeLabelEditConstants) -- **TreeView**内联标签编辑触发器(WinNativeCommonCtls) * [**TreeLineStyleConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeLineStyleConstants) -- **TreeView**树线范围(WinNativeCommonCtls) * [**TreeRelationshipConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeRelationshipConstants) -- **Nodes.Add**插入位置(WinNativeCommonCtls) * [**TreeSortOrderConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortOrderConstants) -- **TreeView**/**Node**排序方向(WinNativeCommonCtls) * [**TreeSortTypeConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortTypeConstants) -- **TreeView**/**Node**排序比较模式(WinNativeCommonCtls) * [**TreeStyleConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeStyleConstants) -- **TreeView**复合视觉样式(WinNativeCommonCtls) **V** * [**VbAppWinStyle**](/official/Reference/VBA/Constants/VbAppWinStyle) -- **Shell**的窗口样式值(VBA) * [**VbArchitecture**](/official/Reference/VBA/Constants/VbArchitecture) -- 处理器架构值(VBA) * [**VbCalendar**](/official/Reference/VBA/Constants/VbCalendar) -- 日历类型值(VBA) * [**VbCallType**](/official/Reference/VBA/Constants/VbCallType) -- **CallByName**调用类型标志(VBA) * [**VbCompareMethod**](/official/Reference/VBA/Constants/VbCompareMethod) -- 字符串函数的文本比较模式(VBA) * [**VbDateTimeFormat**](/official/Reference/VBA/Constants/VbDateTimeFormat) -- **FormatDateTime**格式代码(VBA) * [**VbDayOfWeek**](/official/Reference/VBA/Constants/VbDayOfWeek) -- 日期函数的星期常量(VBA) * [**VbFileAttribute**](/official/Reference/VBA/Constants/VbFileAttribute) -- 文件属性标志(VBA) * [**VbFirstWeekOfYear**](/official/Reference/VBA/Constants/VbFirstWeekOfYear) -- 日期函数的首周选择器(VBA) * [**VbIMEStatus**](/official/Reference/VBA/Constants/VbIMEStatus) -- 输入法编辑器模式常量(VBA) * [**VbMsgBoxResult**](/official/Reference/VBA/Constants/VbMsgBoxResult) -- **MsgBox**按钮点击标识符(VBA) * [**VbMsgBoxStyle**](/official/Reference/VBA/Constants/VbMsgBoxStyle) -- **MsgBox**按钮、图标和模态标志(VBA) * [**VbStrConv**](/official/Reference/VBA/Constants/VbStrConv) -- **StrConv**转换类型标志(VBA) * [**VbTriState**](/official/Reference/VBA/Constants/VbTriState) -- 格式化函数的三态值(VBA) * [**VbVarType**](/official/Reference/VBA/Constants/VbVarType) -- **VarType** Variant子类型代码(VBA) * [**VariantTypeConstants**](/official/Reference/VBRUN/Constants/VariantTypeConstants) -- 旧版DAO字段类型标签(VBRUN) * [**VerticalAlignmentConstants**](/official/Reference/VBRUN/Constants/VerticalAlignmentConstants) -- 垂直文本对齐(VBRUN) **W** * [**WindowState**](/official/Reference/CustomControls/Enumerations/WindowState) -- **WaynesForm**窗口状态(CustomControls) * [**wv2DefaultDownloadCornerAlign**](/official/Reference/WebView2/Enumerations/wv2DefaultDownloadCornerAlign) -- 下载对话框角对齐(WebView2) * [**wv2ErrorStatus**](/official/Reference/WebView2/Enumerations/wv2ErrorStatus) -- 导航失败原因(WebView2) * [**wv2HostResourceAccessKind**](/official/Reference/WebView2/Enumerations/wv2HostResourceAccessKind) -- 虚拟主机名跨域访问策略(WebView2) * [**wv2KeyEventKind**](/official/Reference/WebView2/Enumerations/wv2KeyEventKind) -- 加速键事件类型(WebView2) * [**wv2PermissionKind**](/official/Reference/WebView2/Enumerations/wv2PermissionKind) -- 权限请求功能标识符(WebView2) * [**wv2PermissionState**](/official/Reference/WebView2/Enumerations/wv2PermissionState) -- 权限请求决定(WebView2) * [**wv2PrintOrientation**](/official/Reference/WebView2/Enumerations/wv2PrintOrientation) -- **PrintToPdf**页面方向(WebView2) * [**wv2ProcessFailedKind**](/official/Reference/WebView2/Enumerations/wv2ProcessFailedKind) -- 失败的WebView2进程标识符(WebView2) * [**wv2ScriptDialogKind**](/official/Reference/WebView2/Enumerations/wv2ScriptDialogKind) -- JavaScript对话框类型(WebView2) * [**wv2WebResourceContext**](/official/Reference/WebView2/Enumerations/wv2WebResourceContext) -- Web资源过滤器请求类型(WebView2) **Z** * [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants) -- **ZOrder**方法位置选择器(VBRUN) *** ### 另见 * [语句](/official/Reference/Statements) -- 语言语句的字母顺序索引 * [过程和函数](/official/Reference/Procedures-and-Functions) -- 可调用运行时成员的字母顺序索引 * [运算符](/official/Reference/Operators) -- 算术、比较、逻辑和位运算符 * [包](/official/Reference/Packages) -- 全部12个内置包 --- --- url: /zh/official/Reference/WinServicesLib/Enumerations.md --- # 枚举 **WinServicesLib** 包暴露的四个面向用户的枚举。这四个枚举均来自包源码中的公共 `ServicesConstantsPublic` 模块;源码中调用 `advapi32.dll` 时使用的更大一组内部 `SERVICE_*` 常量位于 `Private Module` 中,不属于公共 API。 | 枚举 | 使用者 | |------|--------| | [ServiceTypeConstants](/official/Reference/WinServicesLib/Enumerations/ServiceTypeConstants) | [**ServiceManager.Type**](/official/Reference/WinServicesLib/ServiceManager#type), [**ServiceState.Type**](/official/Reference/WinServicesLib/ServiceState#type) | | [ServiceStartConstants](/official/Reference/WinServicesLib/Enumerations/ServiceStartConstants) | [**ServiceManager.InstallStartMode**](/official/Reference/WinServicesLib/ServiceManager#installstartmode) | | [ServiceControlCodeConstants](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants) | [**Services.ControlService**](/official/Reference/WinServicesLib/Services#controlservice), [**ITbService.ChangeState**](/official/Reference/WinServicesLib/ITbService#changestate) 的 *dwControl* 参数 | | [ServiceStatusConstants](/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants) | [**ServiceManager.ReportStatus**](/official/Reference/WinServicesLib/ServiceManager#reportstatus) | 成员名称前缀继承自底层 Win32 SDK 常量——*配置*枚举([**ServiceTypeConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceTypeConstants)、[**ServiceStartConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceStartConstants))使用 `tb…`,*运行时*枚举([**ServiceControlCodeConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants)、[**ServiceStatusConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants))使用 `vb…`。这种分裂并非刻意设计;请将前缀视为成员名称的一部分,忽略这种不对称性。 --- --- url: /zh/packages/vbccr/buttons/commandbuttonw.md description: 命令按钮控件(CommandButtonW) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 命令按钮控件(CommandButtonW) 增强型命令按钮控件,支持视觉样式、分割按钮、自绘和图片标题共存。 ## 枚举 ### CmdImageListAlignmentConstants | 常量 | 值 | 说明 | |------|-----|------| | CmdImageListAlignmentLeft | 0 | 左对齐 | | CmdImageListAlignmentRight | 1 | 右对齐 | | CmdImageListAlignmentTop | 2 | 顶部对齐 | | CmdImageListAlignmentBottom | 3 | 底部对齐 | | CmdImageListAlignmentCenter | 4 | 居中对齐 | ### CmdDrawModeConstants | 常量 | 值 | 说明 | |------|-----|------| | CmdDrawModeNormal | 0 | 正常模式 | | CmdDrawModeOwnerDraw | 1 | 自绘模式 | ## 属性 ### Default ```vb Property Get Default() As Boolean Property Let Default(ByVal Value As Boolean) ``` 是否为默认按钮(Enter 键触发)。 ### Cancel ```vb Property Get Cancel() As Boolean Property Let Cancel(ByVal Value As Boolean) ``` 是否为取消按钮(Esc 键触发)。 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。 ### Appearance ```vb Property Get Appearance() As CCAppearanceConstants Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` 外观样式。参见通用枚举。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景色。 ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 ### ImageList ```vb Property Get ImageList() As Variant Property Let ImageList(ByVal Value As Variant) Property Set ImageList(ByVal Value As Variant) ``` 关联的 ImageList 控件。 ### ImageListAlignment ```vb Property Get ImageListAlignment() As CmdImageListAlignmentConstants Property Let ImageListAlignment(ByVal Value As CmdImageListAlignmentConstants) ``` ImageList 图标对齐方式。 ### ImageListMargin ```vb Property Get ImageListMargin() As Single Property Let ImageListMargin(ByVal Value As Single) ``` ImageList 图标边距。 ### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` 标题文本。 ### Alignment ```vb Property Get Alignment() As VBRUN.AlignmentConstants Property Let Alignment(ByVal Value As VBRUN.AlignmentConstants) ``` 文本水平对齐。 ### VerticalAlignment ```vb Property Get VerticalAlignment() As CCVerticalAlignmentConstants Property Let VerticalAlignment(ByVal Value As CCVerticalAlignmentConstants) ``` 文本垂直对齐。参见通用枚举。 ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` 图片。 ### PictureAndCaption ```vb Property Get PictureAndCaption() As Boolean Property Let PictureAndCaption(ByVal Value As Boolean) ``` 是否同时显示图片和标题。需要 comctl32.dll 6.1 或更高版本。 ### WordWrap ```vb Property Get WordWrap() As Boolean Property Let WordWrap(ByVal Value As Boolean) ``` 是否自动换行。 ### Transparent ```vb Property Get Transparent() As Boolean Property Let Transparent(ByVal Value As Boolean) ``` 是否透明背景(运行时有效)。 ### SplitButton ```vb Property Get SplitButton() As Boolean Property Let SplitButton(ByVal Value As Boolean) ``` 是否显示为分割按钮。需要 comctl32.dll 6.1 或更高版本。 ### SplitButtonAlignment ```vb Property Get SplitButtonAlignment() As CCLeftRightAlignmentConstants Property Let SplitButtonAlignment(ByVal Value As CCLeftRightAlignmentConstants) ``` 分割按钮对齐方式。参见通用枚举。 ### SplitButtonNoSplit ```vb Property Get SplitButtonNoSplit() As Boolean Property Let SplitButtonNoSplit(ByVal Value As Boolean) ``` 分割按钮不显示分割线。 ### SplitButtonGlyph ```vb Property Get SplitButtonGlyph() As IPictureDisp Property Let SplitButtonGlyph(ByVal Value As IPictureDisp) Property Set SplitButtonGlyph(ByVal Value As IPictureDisp) ``` 分割按钮的下拉箭头图标。 ### Style ```vb Property Get Style() As VBRUN.ButtonConstants Property Let Style(ByVal Value As VBRUN.ButtonConstants) ``` 按钮样式(标准或图形)。 ### DisabledPicture ```vb Property Get DisabledPicture() As IPictureDisp Property Let DisabledPicture(ByVal Value As IPictureDisp) Property Set DisabledPicture(ByVal Value As IPictureDisp) ``` 禁用状态图片。 ### DownPicture ```vb Property Get DownPicture() As IPictureDisp Property Let DownPicture(ByVal Value As IPictureDisp) Property Set DownPicture(ByVal Value As IPictureDisp) ``` 按下状态图片。 ### UseMaskColor ```vb Property Get UseMaskColor() As Boolean Property Let UseMaskColor(ByVal Value As Boolean) ``` 是否使用遮罩色。 ### MaskColor ```vb Property Get MaskColor() As OLE_COLOR Property Let MaskColor(ByVal Value As OLE_COLOR) ``` 遮罩色。 ### DrawMode ```vb Property Get DrawMode() As CmdDrawModeConstants Property Let DrawMode(ByVal Value As CmdDrawModeConstants) ``` 绘制模式。 ### Value ```vb Property Get Value() As Boolean Property Let Value(ByVal NewValue As Boolean) ``` 按钮值,设为 True 时触发 Click 事件。 ### Pushed ```vb Property Get Pushed() As Boolean Property Let Pushed(ByVal Value As Boolean) ``` 是否处于按下状态。 ### Hot ```vb Property Get Hot() As Boolean ``` 是否处于热状态。只读。 ### DroppedDown ```vb Property Get DroppedDown() As Boolean Property Let DroppedDown(ByVal Value As Boolean) ``` 分割按钮是否已下拉。 ### hWnd / hWndUserControl / Font / Enabled / OLEDropMode / MousePointer / MouseIcon / MouseTrack / RightToLeft / RightToLeftLayout / RightToLeftMode 参见公共属性。 ### Name / Tag / Parent / Container / Left / Top / Width / Height / Visible / ToolTipText / HelpContextID / WhatsThisHelpID / DragIcon / DragMode 参见标准扩展器属性。 ## 方法 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘。 ### PerformClick ```vb Public Sub PerformClick() ``` 模拟用户点击按钮。 ### SetShield ```vb Public Function SetShield(ByVal State As Boolean) As Long ``` 设置 UAC 提升图标。成功返回 1。需要 comctl32.dll 6.1 或更高版本。 ### GetIdealSize ```vb Public Sub GetIdealSize(ByRef Width As Single, ByRef Height As Single) ``` 获取按钮的理想尺寸。需要 comctl32.dll 6.0 或更高版本。 ### OLEDrag ```vb Public Sub OLEDrag() ``` ### Drag / ZOrder / SetFocus / Move 参见标准方法。 ## 事件 ### Click ```vb Public Event Click() ``` 单击。 ### DblClick ```vb Public Event DblClick() ``` 双击。 ### HotChanged ```vb Public Event HotChanged() ``` 热状态改变。 ### DropDown ```vb Public Event DropDown() ``` 分割按钮下拉时触发。 ### OwnerDraw ```vb Public Event OwnerDraw(ByVal DisplayAsDefault As Boolean, ByVal ItemAction As Long, ByVal ItemState As Long, ByVal hDC As LongPtr, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` 自绘事件。 ### KeyDown / KeyUp / KeyPress ### MouseDown / MouseMove / MouseUp / MouseEnter / MouseLeave ### OLECompleteDrag / OLEDragDrop / OLEDragOver / OLEGiveFeedback / OLESetData / OLEStartDrag ## 代码示例 ### 基本用法 ```vb ' 设置默认按钮 CommandButtonW1.Default = True CommandButtonW1.Caption = "确定" ' 图形按钮 CommandButtonW1.Style = vbButtonGraphical Set CommandButtonW1.Picture = LoadPicture("ok.bmp") ' 图片和标题共存 CommandButtonW1.PictureAndCaption = True ``` ### 分割按钮 ```vb CommandButtonW1.SplitButton = True Private Sub CommandButtonW1_DropDown() ' 显示上下文菜单 PopupMenu mnuOptions End Sub ``` ### UAC 提升图标 ```vb CommandButtonW1.SetShield True ``` ### 获取理想尺寸 ```vb Dim w As Single, h As Single CommandButtonW1.GetIdealSize w, h CommandButtonW1.Width = w CommandButtonW1.Height = h ``` --- --- url: /zh/packages/vbccr/buttons/commandlink.md description: 命令链接控件(CommandLink) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 命令链接控件(CommandLink) Windows 命令链接按钮控件,显示标题、提示文本和可选图标。 ## 枚举 无控件专用枚举。 ## 属性 ### Default ```vb Property Get Default() As Boolean Property Let Default(ByVal Value As Boolean) ``` 是否为默认按钮。 ### Cancel ```vb Property Get Cancel() As Boolean Property Let Cancel(ByVal Value As Boolean) ``` 是否为取消按钮。 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景色。 ### ImageList ```vb Property Get ImageList() As Variant Property Let ImageList(ByVal Value As Variant) Property Set ImageList(ByVal Value As Variant) ``` 关联的 ImageList 控件。 ### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` 标题文本。 ### Hint ```vb Property Get Hint() As String Property Let Hint(ByVal Value As String) ``` 提示文本(标题下方的说明文字)。 ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` 图标。 ### Transparent ```vb Property Get Transparent() As Boolean Property Let Transparent(ByVal Value As Boolean) ``` 透明背景(运行时有效)。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示。 ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 从右到左镜像布局。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### Value ```vb Property Get Value() As Boolean Property Let Value(ByVal NewValue As Boolean) ``` 按钮值,设为 True 时触发 Click 事件。 ### Pushed ```vb Property Get Pushed() As Boolean Property Let Pushed(ByVal Value As Boolean) ``` 是否处于按下状态。 ### Hot ```vb Property Get Hot() As Boolean ``` 是否处于热状态。只读。 ### hWnd / hWndUserControl / Font / Enabled / OLEDropMode / MousePointer / MouseIcon / MouseTrack 参见公共属性。 ### Name / Tag / Parent / Container / Left / Top / Width / Height / Visible / ToolTipText / HelpContextID / WhatsThisHelpID / DragIcon / DragMode 参见标准扩展器属性。 ## 方法 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘。 ### PerformClick ```vb Public Sub PerformClick() ``` 模拟用户点击。 ### SetShield ```vb Public Function SetShield(ByVal State As Boolean) As Long ``` 设置 UAC 提升图标。成功返回 1。 ### GetIdealHeight ```vb Public Function GetIdealHeight() As Single ``` 获取控件的理想高度。 ### OLEDrag ```vb Public Sub OLEDrag() ``` ### Drag / ZOrder / SetFocus / Move 参见标准方法。 ## 事件 ### Click ```vb Public Event Click() ``` 单击。 ### DblClick ```vb Public Event DblClick() ``` 双击。 ### HotChanged ```vb Public Event HotChanged() ``` 热状态改变。 ### KeyDown / KeyUp / KeyPress ### MouseDown / MouseMove / MouseUp / MouseEnter / MouseLeave ### OLECompleteDrag / OLEDragDrop / OLEDragOver / OLEGiveFeedback / OLESetData / OLEStartDrag ## 代码示例 ### 基本用法 ```vb ' 设置命令链接 CommandLink1.Caption = "保存文件" CommandLink1.Hint = "将当前文档保存到磁盘" CommandLink1.Default = True ' 设置 UAC 提升图标 CommandLink1.SetShield True ' 获取理想高度并调整 CommandLink1.Height = CommandLink1.GetIdealHeight ``` ### 响应点击 ```vb Private Sub CommandLink1_Click() MsgBox "您点击了: " & CommandLink1.Caption End Sub ``` --- --- url: /zh/official/Features/Language/Module-Organization.md --- # 模块级代码组织 现在可以在方法或属性之间插入模块级代码。以前所有 `Declare` 语句、`Enum`、`Type` 等都必须出现在第一个 `Sub/Function/Property` 之前,现在以下写法是有效的: ```vb Private Const foo = "foo" Sub SomeMethod() '... End Sub Private Const bar = "bar" Sub SomeOtherMethod() '... End Sub ``` ## 代码部件名称的预设方法 以下可用,它们代表的内容将自动作为 `String` 插入: * `CurrentComponentName`,例如 "Form1" * `CurrentProcedureName`,例如在 `Sub Foo()` 中为 "Foo" * `CurrentProjectName` * `CurrentSourceFile` * `CurrentComponentCLSID` ## 限制的移除 twinBASIC 对续行、过程大小、窗体上的控件数量、模块大小等不施加人为限制。 --- --- url: /zh/official/IDE/Memory.md --- # 内存 ![Memory](Images/Memory.png "Memory") 内存面板在暂停的调试会话中显示进程内存的原始内容,左列为地址,右列为字节值。它适用于在字节级别检查数据结构。 --- --- url: /zh/official/Features/Language/Inline-Initialization.md --- # 内联变量初始化 你现在可以为变量内联设置初始值,无需续行符。 ## 示例 ```vb Dim i As Long = 1 Dim foo As Boolean = bar() Dim arr As Variant = Array(1, 2, 3) Dim strArr(2) As String = Array("a", "b", "c") Dim cMC As cMyClass = New cMyClass(customConstructorArgs) ``` ## For 循环的内联变量声明 你现在不再需要为计数器变量单独写 `Dim` 语句: ```vb For i As Long = 0 To 10 '... Next ``` 现在是有效语法。你可以使用任何类型,不只是 `Long`。 --- --- url: /zh/official/IDE/Splash-Screen.md --- # 启动画面 ![Splash Screen](/assets/Splash_Screen.BScICLoJ.png "Splash Screen") 启动画面在每次 IDE 启动时出现,显示当前 twinBASIC 版本号、构建日期及社区资源链接。IDE 加载完成后自动关闭。 --- --- url: /zh/official/IDE/AddIns/GlobalSearch.md --- ## 全局搜索 此外接程序随 twinBASIC IDE 附带。 最新版本 : v1.0.0.0 开发者 : twinBASIC 全局搜索外接程序将包含一个[工具栏](/official/IDE/Toolbar)项。 ![全局搜索(工具栏)](Images/Toolbar_GlobalSearch.png "全局搜索(工具栏)") ![全局搜索](/assets/GlobalSearch.4t0aHh0h.png "全局搜索") 选项 * 在包中搜索 * 区分大小写 * 全字匹配 * 排除注释 在文本字段中输入搜索词(如 Button1),将返回匹配结果列表。 ![全局搜索](/assets/GlobalSearch_2.CqKvaBKL.png "全局搜索") ## 下载 此外接程序与 twinBASIC 捆绑在一起。可以从 [https://github.com/twinbasic/twinbasic/releases][tB] 下载。 [tB]: https://github.com/twinbasic/twinbasic/releases --- --- url: /zh/packages/vbccr/text/hotkey.md description: 热键控件(HotKey) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 热键控件(HotKey) 提供 Windows 标准热键输入控件,允许用户选择快捷键组合。 ## 枚举 ### HkeInvalidKeyCombinationConstants | 常量 | 值 | 说明 | |------|-----|------| | HkeInvalidKeyCombinationNone | 1 | 无效组合:无修饰键 | | HkeInvalidKeyCombinationShift | 2 | 无效组合:仅 Shift | | HkeInvalidKeyCombinationCtrl | 4 | 无效组合:仅 Ctrl | | HkeInvalidKeyCombinationAlt | 8 | 无效组合:仅 Alt | | HkeInvalidKeyCombinationShiftCtrl | 16 | 无效组合:Shift+Ctrl | | HkeInvalidKeyCombinationShiftAlt | 32 | 无效组合:Shift+Alt | | HkeInvalidKeyCombinationCtrlAlt | 64 | 无效组合:Ctrl+Alt | | HkeInvalidKeyCombinationShiftCtrlAlt | 128 | 无效组合:Shift+Ctrl+Alt | ## 属性 ### Name ```vb Property Get Name() As String ``` 返回控件的名称。 ### Tag ```vb Property Get/Let Tag() As String ``` 返回/设置控件的标记值。 ### Parent ```vb Property Get Parent() As Object ``` 返回控件的父对象。 ### Container ```vb Property Get/Set Container() As Object ``` 返回/设置控件的容器。 ### Left ```vb Property Get/Let Left() As Single ``` 返回/设置控件左边缘的位置。 ### Top ```vb Property Get/Let Top() As Single ``` 返回/设置控件上边缘的位置。 ### Width ```vb Property Get/Let Width() As Single ``` 返回/设置控件的宽度。 ### Height ```vb Property Get/Let Height() As Single ``` 返回/设置控件的高度。 ### Visible ```vb Property Get/Let Visible() As Boolean ``` 返回/设置控件是否可见。 ### ToolTipText ```vb Property Get/Let ToolTipText() As String ``` 返回/设置控件的工具提示文本。 ### HelpContextID ```vb Property Get/Let HelpContextID() As Long ``` 返回/设置控件的帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get/Let WhatsThisHelpID() As Long ``` 返回/设置控件的"这是什么"帮助 ID。 ### DragIcon ```vb Property Get/Let/Set DragIcon() As IPictureDisp ``` 返回/设置拖动操作时显示的图标。 ### DragMode ```vb Property Get/Let DragMode() As Integer ``` 返回/设置拖动模式(手动或自动)。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 返回热键控件的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 返回 UserControl 的窗口句柄。 ### Font ```vb Property Get/Let/Set Font() As StdFont ``` 返回/设置控件使用的字体。 ### VisualStyles ```vb Property Get/Let VisualStyles() As Boolean ``` 返回/设置是否启用视觉样式。 ### Enabled ```vb Property Get/Let Enabled() As Boolean ``` 返回/设置控件是否可用。 ### OLEDropMode ```vb Property Get/Let OLEDropMode() As OLEDropModeConstants ``` 返回/设置 OLE 放置模式。参见通用枚举。 ### MousePointer ```vb Property Get/Let MousePointer() As CCMousePointerConstants ``` 返回/设置鼠标指针类型。参见通用枚举。 ### MouseIcon ```vb Property Get/Let/Set MouseIcon() As IPictureDisp ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Property Get/Let MouseTrack() As Boolean ``` 返回/设置是否启用鼠标进入/离开跟踪。 ### BackColor ```vb Property Get/Let BackColor() As OLE_COLOR ``` 返回/设置控件的背景色。 ### BorderStyle ```vb Property Get/Let BorderStyle() As CCBorderStyleConstants ``` 返回/设置控件的边框样式。参见通用枚举。 ### Value ```vb Property Get/Let Value(Optional ByRef Modifiers As Integer) As VBRUN.KeyCodeConstants ``` 返回/设置热键的键码。Modifiers 参数接收修饰键标志(Shift=1, Ctrl=2, Alt=4)。 ### RawValue ```vb Property Get/Let RawValue() As Long ``` 返回/设置热键的原始数值(低字节为键码,高字节为修饰键标志)。 ### Text ```vb Property Get Text() As String ``` 返回热键的显示文本。只读。 ## 方法 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖动操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移到该控件。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置控件在其层级中的 Z 顺序位置。 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘控件。 ### SetRules ```vb Public Sub SetRules(ByVal InvalidKeyCombinations As HkeInvalidKeyCombinationConstants, Optional ByVal DefaultModifiers As VBRUN.ShiftConstants) ``` 设置无效键组合规则和默认修饰键。InvalidKeyCombinations 指定不允许的修饰键组合,DefaultModifiers 指定用户输入无效组合时替换为的默认修饰键。 ### SetApplicationHotKey ```vb Public Function SetApplicationHotKey(Optional ByVal hWnd As LongPtr) As Long ``` 将当前热键注册为窗口的应用程序热键。返回值为 WM\_SETHOTKEY 消息的返回值。 ## 事件 ### Click ```vb Public Event Click() ``` 单击控件时发生。 ### DblClick ```vb Public Event DblClick() ``` 双击控件时发生。 ### Change ```vb Public Event Change() ``` 热键值发生变化时发生。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyDown 事件之前发生,可设置 IsInputKey 标记按键是否为输入键。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyUp 事件之前发生。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下键盘键时发生。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放键盘键时发生。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按下并释放字符键时发生。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时发生。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时发生。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时发生。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件时发生。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件时发生。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放操作完成或取消后,在源控件上发生。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 数据通过 OLE 拖放操作放置到控件上时发生。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放操作期间鼠标移过控件时发生。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 拖放操作期间需要更改鼠标光标时,在源控件上发生。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` 放置目标请求数据时,在源控件上发生。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 拖放操作启动时发生。 ## 代码示例 ### 基本用法 ```vb Private Sub Form_Load() With HotKey1 .SetRules HkeInvalidKeyCombinationNone Or _ HkeInvalidKeyCombinationShift, vbCtrlMask .VisualStyles = True End With End Sub Private Sub HotKey1_Change() Dim Modifiers As Integer Dim KeyCode As VBRUN.KeyCodeConstants KeyCode = HotKey1.Value(Modifiers) Debug.Print "热键: " & HotKey1.Text Debug.Print "原始值: " & HotKey1.RawValue End Sub Private Sub cmdRegisterHotKey_Click() Dim Result As Long Result = HotKey1.SetApplicationHotKey(Me.hWnd) If Result = 1 Then Debug.Print "热键注册成功" Else Debug.Print "热键注册失败" End If End Sub ``` --- --- url: /zh/packages/vbccr/datetime/dtpicker.md description: 日期时间选择器控件(DTPicker) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 日期时间选择器控件(DTPicker) 基于 Windows 日期时间选择器通用控件,提供日期和时间的选取与自定义格式化功能。 ## 枚举 ### DtpFormatConstants | 常量 | 值 | 说明 | |------|-----|------| | DtpFormatLongDate | 0 | 长日期格式 | | DtpFormatShortDate | 1 | 短日期格式 | | DtpFormatTime | 2 | 时间格式 | | DtpFormatCustom | 3 | 自定义格式 | ## 属性 ### Name ```vb Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Property Get/Let Tag() As String ``` 存储程序所需的附加数据。 ### Parent ```vb Property Get Parent() As Object ``` 返回包含此对象的对象。 ### Container `Property Get Container() As Object` / `Property Set Container(ByVal Value As Object)` 返回/设置对象的容器。 ### Left ```vb Property Get/Let Left() As Single ``` 返回/设置对象左边缘与其容器左边缘的距离。 ### Top ```vb Property Get/Let Top() As Single ``` 返回/设置对象上边缘与其容器上边缘的距离。 ### Width ```vb Property Get/Let Width() As Single ``` 返回/设置对象的宽度。 ### Height ```vb Property Get/Let Height() As Single ``` 返回/设置对象的高度。 ### Visible ```vb Property Get/Let Visible() As Boolean ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Property Get/Let ToolTipText() As String ``` 返回/设置鼠标悬停时显示的提示文本。 ### HelpContextID ```vb Property Get/Let HelpContextID() As Long ``` 指定对象的默认帮助文件上下文 ID。 ### WhatsThisHelpID ```vb Property Get/Let WhatsThisHelpID() As Long ``` 返回/设置与对象关联的上下文编号。 ### DragIcon ```vb Property Get/Let/Set DragIcon() As IPictureDisp ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Property Get/Let DragMode() As Integer ``` 返回/设置拖动模式(手动或自动)。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 返回日期时间选择器控件的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 返回 UserControl 的窗口句柄。 ### hWndCalendar ```vb Property Get hWndCalendar() As LongPtr ``` 返回下拉日历控件的窗口句柄。 ### Font ```vb Property Get/Let/Set Font() As StdFont ``` 返回/设置控件字体。 ### CalendarFont ```vb Property Get/Let/Set CalendarFont() As StdFont ``` 返回/设置下拉日历字体。 ### VisualStyles ```vb Property Get/Let VisualStyles() As Boolean ``` 返回/设置是否启用视觉样式。 ### Enabled ```vb Property Get/Let Enabled() As Boolean ``` 返回/设置控件是否响应用户事件。 ### OLEDropMode ```vb Property Get/Let OLEDropMode() As OLEDropModeConstants ``` 返回/设置对象是否可作为 OLE 放置目标。参见通用枚举。 ### MousePointer ```vb Property Get/Let MousePointer() As CCMousePointerConstants ``` 返回/设置鼠标指针类型。参见通用枚举。 ### MouseIcon ```vb Property Get/Let/Set MouseIcon() As IPictureDisp ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Property Get/Let MouseTrack() As Boolean ``` 返回/设置是否触发 MouseEnter/MouseLeave 事件。 ### RightToLeft ```vb Property Get/Let RightToLeft() As Boolean ``` 决定双向系统上的文本显示方向和控件视觉外观。 ### RightToLeftLayout ```vb Property Get/Let RightToLeftLayout() As Boolean ``` 返回/设置是否启用从右到左镜像布局。 ### RightToLeftMode ```vb Property Get/Let RightToLeftMode() As CCRightToLeftModeConstants ``` 返回/设置从右到左模式。参见通用枚举。 ### CalendarBackColor ```vb Property Get/Let CalendarBackColor() As OLE_COLOR ``` 返回/设置日历月份区域的背景色。 ### CalendarForeColor ```vb Property Get/Let CalendarForeColor() As OLE_COLOR ``` 返回/设置日历月份区域的前景色。 ### CalendarTitleBackColor ```vb Property Get/Let CalendarTitleBackColor() As OLE_COLOR ``` 返回/设置日历标题的背景色。 ### CalendarTitleForeColor ```vb Property Get/Let CalendarTitleForeColor() As OLE_COLOR ``` 返回/设置日历标题的前景色。 ### CalendarTrailingForeColor ```vb Property Get/Let CalendarTrailingForeColor() As OLE_COLOR ``` 返回/设置日历末尾日期的前景色。 ### CalendarShowToday ```vb Property Get/Let CalendarShowToday() As Boolean ``` 返回/设置日历是否在底部显示"今天"日期。 ### CalendarShowTodayCircle ```vb Property Get/Let CalendarShowTodayCircle() As Boolean ``` 返回/设置是否在今天的日期上画圆圈。 ### CalendarShowWeekNumbers ```vb Property Get/Let CalendarShowWeekNumbers() As Boolean ``` 返回/设置日历是否显示周数。 ### CalendarShowTrailingDates ```vb Property Get/Let CalendarShowTrailingDates() As Boolean ``` 返回/设置日历是否显示上/下月的日期。 ### CalendarAlignment ```vb Property Get/Let CalendarAlignment() As CCLeftRightAlignmentConstants ``` 返回/设置日历的对齐方式。参见通用枚举。 ### CalendarDayState ```vb Property Get/Let CalendarDayState() As Boolean ``` 返回/设置日历是否支持 CalendarGetDayBold 事件中的粗体日期。 ### CalendarUseShortestDayNames ```vb Property Get/Let CalendarUseShortestDayNames() As Boolean ``` 返回/设置日历是否使用最短日期名称。 ### MinDate ```vb Property Get/Let MinDate() As Date ``` 返回/设置可选择的最小日期。 ### MaxDate ```vb Property Get/Let MaxDate() As Date ``` 返回/设置可选择的最大日期。 ### Value ```vb Property Get/Let Value() As Variant ``` 返回/设置当前日期时间值。 ### Year ```vb Property Get Year() As Integer ``` 返回当前日期的年份(只读)。 ### Month ```vb Property Get Month() As Integer ``` 返回当前日期的月份(只读)。 ### Week ```vb Property Get Week() As Integer ``` 返回当前日期的周数(只读)。 ### Day ```vb Property Get Day() As Integer ``` 返回当前日期的日(只读)。 ### Hour ```vb Property Get Hour() As Integer ``` 返回当前时间的小时(只读)。 ### Minute ```vb Property Get Minute() As Integer ``` 返回当前时间的分钟(只读)。 ### Second ```vb Property Get Second() As Integer ``` 返回当前时间的秒(只读)。 ### Format ```vb Property Get/Let Format() As DtpFormatConstants ``` 返回/设置日期时间的显示格式。 ### CustomFormat ```vb Property Get/Let CustomFormat() As String ``` 返回/设置自定义格式字符串。 ### UpDown ```vb Property Get/Let UpDown() As Boolean ``` 返回/设置是否使用上下按钮代替下拉日历。 ### CheckBox ```vb Property Get/Let CheckBox() As Boolean ``` 返回/设置是否在控件中显示复选框。 ### AllowUserInput ```vb Property Get/Let AllowUserInput() As Boolean ``` 返回/设置是否允许用户直接输入日期。 ### StartOfWeek ```vb Property Get/Let StartOfWeek() As Integer ``` 返回/设置一周的起始日(0=系统默认, 1=周一, ..., 7=周日)。 ### DroppedDown ```vb Property Get DroppedDown() As Boolean ``` 返回日历是否处于下拉状态(只读)。 ### Selected ```vb Property Get Selected() As Boolean ``` 返回复选框是否被选中(只读)。 ### DayCount ```vb Property Get DayCount() As Long ``` 返回当前可见的日期数(只读)。 ### DayOfWeek ```vb Property Get DayOfWeek() As Integer ``` 返回当前日期是星期几(只读)。 ### SystemStartOfWeek ```vb Property Get SystemStartOfWeek() As Integer ``` 返回系统一周起始日(只读)。 ## 方法 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移到控件上。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 将控件放置在 Z 轴顺序的前面或后面。 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘控件。 ### GetIdealSize ```vb Public Sub GetIdealSize(ByRef Width As Long, ByRef Height As Long) ``` 获取控件的理想尺寸。 ## 事件 ### Click ```vb Public Event Click() ``` 用户按下并释放鼠标按钮时发生。 ### DropDown ```vb Public Event DropDown() ``` 下拉日历即将展开时发生。 ### CloseUp ```vb Public Event CloseUp() ``` 用户关闭日历时发生。 ### Change ```vb Public Event Change() ``` 控件内容发生变化时发生。 ### ContextMenu ```vb Public Event ContextMenu(ByRef Handled As Boolean, ByVal X As Single, ByVal Y As Single) ``` 用户右键点击或按 Shift+F10 时发生。 ### CalendarGetDayBold ```vb Public Event CalendarGetDayBold(ByVal StartDate As Date, ByVal Count As Long, ByRef State() As Boolean) ``` 日历请求日期粗体信息时发生。需要 comctl32.dll 版本 6.1 或更高。 ### CalendarContextMenu ```vb Public Event CalendarContextMenu(ByRef Handled As Boolean, ByVal X As Single, ByVal Y As Single) ``` 日历区域右键点击时发生。 ### CallbackKeyDown ```vb Public Event CallbackKeyDown(ByVal KeyCode As Integer, ByVal Shift As Integer, ByVal CallbackField As String, ByRef CallbackDate As Date) ``` 用户在回调字段上按键时发生。 ### FormatString ```vb Public Event FormatString(ByVal CallbackField As String, ByRef FormattedString As String) ``` 控件请求回调字段的显示文本时发生。 ### FormatSize ```vb Public Event FormatSize(ByVal CallbackField As String, ByRef Size As Integer) ``` 控件需要知道回调字段的最大允许大小时发生。 ### BeforeUserInput ```vb Public Event BeforeUserInput(ByVal hWndEdit As LongPtr) ``` 用户尝试输入字符串时发生。 ### ParseUserInput ```vb Public Event ParseUserInput(ByVal Text As String, ByRef ParseDate As Variant) ``` 用户输入完成时发生,需要解析输入字符串。 ### AfterUserInput ```vb Public Event AfterUserInput() ``` 用户输入已完成或取消时发生。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyDown 事件之前发生。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyUp 事件之前发生。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 用户按下键时发生。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 用户释放键时发生。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 用户按下并释放字符键时发生。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 用户按下鼠标按钮时发生。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 用户移动鼠标时发生。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 用户释放鼠标按钮时发生。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件时发生。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件时发生。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放操作完成后发生。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 数据通过 OLE 拖放操作放置到控件上时发生。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` 鼠标在 OLE 拖放操作期间移过控件时发生。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` 需要更改鼠标光标时发生。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` 放置目标请求数据时发生。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 拖放操作启动时发生。 ## 代码示例 ### 基本用法 ```vb Private Sub Form_Load() With DTPicker1 .Format = DtpFormatShortDate .Value = Date .MinDate = #1/1/1900# .MaxDate = #12/31/9999# End With End Sub Private Sub DTPicker1_Change() MsgBox "选择的日期: " & DTPicker1.Value End Sub ``` ### 自定义格式与回调 ```vb Private Sub Form_Load() DTPicker1.Format = DtpFormatCustom DTPicker1.CustomFormat = "yyyy年MM月dd日 '第' w '周'" End Sub Private Sub DTPicker1_FormatString(ByVal CallbackField As String, ByRef FormattedString As String) Select Case CallbackField Case "w" FormattedString = CStr(DatePart("ww", DTPicker1.Value, vbMonday)) End Select End Sub ``` --- --- url: /zh/official/Tutorials/CEF/Getting-started.md --- # 入门 ## 包要求 要创建使用CEF包的项目,请向项目添加正确的编译器包引用。该包提供三种版本——每个支持的Chromium版本一种——你只需选择一种: | 引用 | Chromium基线 | 支持的操作系统 | |-----------------------------------------------------------------|-------------------|---------------| | **twinBASIC - Chromium Embedded Framework Package v49** | Chromium 49 | Windows XP+ | | **twinBASIC - Chromium Embedded Framework Package v109** | Chromium 109 | Windows 7+ | | **twinBASIC - Chromium Embedded Framework Package v145** | Chromium 145 | Windows 10+ | 除非你特别需要支持较旧的操作系统,否则请使用**v145**。包源代码针对所有三个版本编译——选择引用会设置 `CEF_VERSION` 编译器常量,该常量选择匹配的API。 通过**项目**→**引用**(Ctrl-T)→**TWINPACK PACKAGES**添加引用。勾选所需的CEF包,关闭对话框,并重启编译器。添加后,**CefBrowser**出现在窗体设计器工具箱中。 ::: warning 较旧的Chromium版本不应用于浏览来自公共Internet的不受信任内容——它们带有未修补的安全漏洞。v49和v109仅适用于浏览器仅加载受信任的本地或内部内容的严格受控环境;对于一般Web浏览,请使用v145。 ::: ## 下载运行时 与[**WebView2**](/official/Reference/WebView2/WebView2/)不同,CEF不依赖系统安装的运行时。Chromium二进制文件(`libcef.dll`及相关文件)作为单独下载提供,必须与应用程序一起安装——无论是在开发时还是部署时。 下载与CEF版本和应用程序位数匹配的运行时ZIP: | 版本 | Win32 | Win64 | | ------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | v49 | [cefRuntime49\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime49_win32.zip) | [cefRuntime49\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime49_win64.zip) | | v109 | [cefRuntime109\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime109_win32.zip) | [cefRuntime109\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime109_win64.zip) | | v145 | [cefRuntime145\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime145_win32.zip) | [cefRuntime145\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime145_win64.zip) | 完整版本列表和发行说明见[CEF运行时发布](https://github.com/twinbasic/cef-runtimes/releases/)。 将ZIP解压到 `%LocalAppData%\twinBASIC_CEF_Runtime\`。ZIP内的版本标记文件夹——例如 `145_0_7632_160_Win64`——必须直接放在该路径下,包含 `libcef.dll` 及其同级文件: ```text %LocalAppData%\twinBASIC_CEF_Runtime\145_0_7632_160_Win64\libcef.dll %LocalAppData%\twinBASIC_CEF_Runtime\145_0_7632_160_Win64\chrome_elf.dll %LocalAppData%\twinBASIC_CEF_Runtime\145_0_7632_160_Win64\… ``` 启动时,[**CefBrowser**](/official/Reference/CEF/CefBrowser/)会自动搜索此默认位置。如果找不到 `libcef.dll`,[**Error**](/official/Reference/CEF/CefBrowser/#error)事件会报告搜索的确切路径。 要指向不同的文件夹——例如随安装程序提供的便携并行部署——在[**Create**](/official/Reference/CEF/CefBrowser/#create)事件期间分配[**EnvironmentOptions.BrowserExecutableFolder**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#browserexecutablefolder): ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.BrowserExecutableFolder = _ App.Path & "\cef145_win64" End Sub ``` ## 位数必须匹配 运行时位数必须与应用程序位数匹配——32位twinBASIC构建需要Win32运行时,64位构建需要Win64运行时。混用会导致 `libcef.dll` 加载失败,通过[**Error**](/official/Reference/CEF/CefBrowser/#error)事件报告。 ## 在窗体上创建CefBrowser控件 包引用和运行时就位后,**CefBrowser**在窗体设计器工具箱中可用。像其他控件一样将其放到窗体上: ```vb Private Sub Form_Load() CefBrowser1.Navigate "https://www.twinbasic.com" End Sub ``` 控件异步启动——第一个用户可见事件是[**Ready**](/official/Reference/CEF/CefBrowser/#ready),在辅助浏览器进程启动且IPC连接后触发。在此之前,导航、脚本和大多数属性访问器会引发"CefBrowser控件未就绪"(运行时错误5)。 ## CefBrowser控件属性 切换**属性**面板查看设计时可见属性:[**DocumentURL**](/official/Reference/CEF/CefBrowser/#documenturl)(控件在**Ready**触发后自动导航到的初始URL)、[**ZoomFactor**](/official/Reference/CEF/CefBrowser/#zoomfactor)、[**UserAgent**](/official/Reference/CEF/CefBrowser/#useragent)以及标准的矩形可停靠属性(大小、**Anchors**、**Dock**)。 完整参考参见[**CefBrowser**类参考](/official/Reference/CEF/CefBrowser/);底层Chromium运行时支持的功能请查阅[Chromium Embedded Framework文档](https://bitbucket.org/chromiumembedded/cef/wiki/Home)。 ## 示例 如果你更喜欢从示例开始,**示例1b——Chromium Embedded Framework示例**可在新建项目对话框中找到。它几乎逐功能镜像**示例1a——WebView2示例**,在CEF包尚未暴露WebView2等效功能的地方会指出差异。 ## 下一步 * [自定义UserDataFolder](/official/Tutorials/CEF/Customize-the-UserDataFolder) —— 为Office加载项、信息亭或便携安装重新定位用户配置文件夹。 * [构建浏览器外壳](/official/Tutorials/CEF/Building-a-browser-shell) —— 后退/前进/刷新/缩放/PDF。 * [重入性](/official/Tutorials/CEF/Re-entrancy) —— 包保护你免受什么影响以及你仍需注意的一个地方。 --- --- url: /zh/official/Tutorials/WebView2/Getting-started.md --- # 入门 ## 包要求 要创建使用WebView2的项目,你的项目必须同时包含 `WinNativeForms` 包和 `WebView2` 包。 这两个包都可以通过 `项目` > `引用` 菜单选项添加,选择 `TWINPACK PACKAGES` 按钮。确保两个包都已勾选,然后关闭并保存设置文件并重启编译器。 ![Create Package](/assets/tbWebView2References.DoZJHOfO.png){style="width:45%; height:auto;"} 添加包引用后,你应该会发现WebView2控件现在在窗体设计器中可用: ![Create Package](/assets/tbWebView2Toolbox.DZ5RpmP2.png){style="width:15%; height:auto;"} ## 在窗体上创建WebView2控件 我们像使用任何普通控件一样使用WebView2控件: ![Create Package](/assets/tbWebView2InAForm.CQ8DE8sw.gif){style="width:60%; height:auto;"} ## WebView2控件属性 WebView2有很多属性和事件可供探索。 ![Create Package](/assets/tbWebView2Properties.BuB786ZA.png){style="width:45%; height:auto;"} 注意,切换任何属性都会在属性列表底部显示额外信息,提供更多细节。完整参考参见[WebView2控件类](/official/Reference/WebView2/WebView2/);对于底层浏览器功能,请搜索官方WebView2文档 ## 示例 如果你更喜欢从示例开始,请查看 `示例0. WebView2示例`,可在新建项目对话框中找到: ![Create Package](/assets/tbWebView2Sample0.CClG1yTB.png){style="width:45%; height:auto;"} --- --- url: /zh/packages/vbccr/ranges/updown.md description: 上下调整控件(UpDown) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 上下调整控件(UpDown) 提供数值递增/递减的旋转按钮,支持伙伴控件同步、循环和十六进制显示。 ## 枚举 ### UdnOrientationConstants 控件方向常量。 | 常量 | 值 | 说明 | |------|-----|------| | UdnOrientationVertical | 0 | 垂直方向 | | UdnOrientationHorizontal | 1 | 水平方向 | ### UdnNumberStyleConstants 数字显示样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | UdnNumberStyleDecimal | 0 | 十进制 | | UdnNumberStyleHexadecimal | 1 | 十六进制 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### Container ```vb Public Property Get Container() As Object Public Property Set Container(ByVal Value As Object) ``` 返回/设置对象的容器。 ### Left ```vb Public Property Get Left() As Single Public Property Let Left(ByVal Value As Single) ``` 返回/设置对象与其容器左边缘的距离。 ### Top ```vb Public Property Get Top() As Single Public Property Let Top(ByVal Value As Single) ``` 返回/设置对象与其容器顶边缘的距离。 ### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 返回/设置对象的宽度。 ### Height ```vb Public Property Get Height() As Single Public Property Let Height(ByVal Value As Single) ``` 返回/设置对象的高度。 ### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 返回/设置鼠标悬停时显示的提示文本。 ### WhatsThisHelpID ```vb Public Property Get WhatsThisHelpID() As Long Public Property Let WhatsThisHelpID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### DragIcon ```vb Public Property Get DragIcon() As IPictureDisp Public Property Let DragIcon(ByVal Value As IPictureDisp) Public Property Set DragIcon(ByVal Value As IPictureDisp) ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Public Property Get DragMode() As Integer Public Property Let DragMode(ByVal Value As Integer) ``` 返回/设置拖动模式。 ### hWnd ```vb Public Property Get hWnd() As LongPtr ``` 返回控件句柄。 ### hWndUserControl ```vb Public Property Get hWndUserControl() As LongPtr ``` 返回UserControl句柄。 ### VisualStyles ```vb Public Property Get VisualStyles() As Boolean Public Property Let VisualStyles(ByVal Value As Boolean) ``` 返回/设置是否启用视觉样式。需要comctl32.dll 6.0或更高版本。 ### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 返回/设置对象是否能响应用户事件。 ### OLEDropMode ```vb Public Property Get OLEDropMode() As OLEDropModeConstants Public Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` 返回/设置对象是否可以作为OLE放置目标。 ### MousePointer ```vb Public Property Get MousePointer() As CCMousePointerConstants Public Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 返回/设置鼠标悬停时显示的指针类型。参见通用枚举。 ### MouseIcon ```vb Public Property Get MouseIcon() As IPictureDisp Public Property Let MouseIcon(ByVal Value As IPictureDisp) Public Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Public Property Get MouseTrack() As Boolean Public Property Let MouseTrack(ByVal Value As Boolean) ``` 返回/设置是否在鼠标进入或离开控件时触发事件。 ### RightToLeft ```vb Public Property Get RightToLeft() As Boolean Public Property Let RightToLeft(ByVal Value As Boolean) ``` 返回/设置从右到左显示方向。 ### RightToLeftLayout ```vb Public Property Get RightToLeftLayout() As Boolean Public Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 返回/设置从右到左布局。 ### RightToLeftMode ```vb Public Property Get RightToLeftMode() As CCRightToLeftModeConstants Public Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 返回/设置从右到左模式。参见通用枚举。 ### BuddyControl ```vb Public Property Get BuddyControl() As Variant Public Property Let BuddyControl(ByVal Value As Variant) Public Property Set BuddyControl(ByVal Value As Variant) ``` 返回/设置关联的伙伴控件。 ### BuddyProperty ```vb Public Property Get BuddyProperty() As String Public Property Let BuddyProperty(ByVal Value As String) ``` 返回/设置伙伴控件的属性名,用于同步数据。 ### SyncBuddy ```vb Public Property Get SyncBuddy() As Boolean Public Property Let SyncBuddy(ByVal Value As Boolean) ``` 返回/设置是否与伙伴控件自动同步值。 ### Min ```vb Public Property Get Min() As Long Public Property Let Min(ByVal Value As Long) ``` 返回/设置最小值。 ### Max ```vb Public Property Get Max() As Long Public Property Let Max(ByVal Value As Long) ``` 返回/设置最大值。 ### Value ```vb Public Property Get Value() As Long Public Property Let Value(ByVal Value As Long) ``` 返回/设置当前值。 ### Increment ```vb Public Property Get Increment() As Long Public Property Let Increment(ByVal Value As Long) ``` 返回/设置每次点击的递增/递减量。 ### Wrap ```vb Public Property Get Wrap() As Boolean Public Property Let Wrap(ByVal Value As Boolean) ``` 返回/设置值是否循环。当为True时,超过最大值回到最小值,反之亦然。 ### HotTracking ```vb Public Property Get HotTracking() As Boolean Public Property Let HotTracking(ByVal Value As Boolean) ``` 返回/设置是否启用热点跟踪。 ### Orientation ```vb Public Property Get Orientation() As UdnOrientationConstants Public Property Let Orientation(ByVal Value As UdnOrientationConstants) ``` 返回/设置控件方向。 ### ThousandsSeparator ```vb Public Property Get ThousandsSeparator() As Boolean Public Property Let ThousandsSeparator(ByVal Value As Boolean) ``` 返回/设置是否显示千位分隔符。 ### NumberStyle ```vb Public Property Get NumberStyle() As UdnNumberStyleConstants Public Property Let NumberStyle(ByVal Value As UdnNumberStyleConstants) ``` 返回/设置数字显示样式。 ## 方法 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动OLE拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置Z顺序。 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘对象。 ### SyncFromBuddy ```vb Public Sub SyncFromBuddy() ``` 从伙伴控件同步值到UpDown控件。 ## 事件 ### DownClick ```vb Public Event DownClick() ``` 点击向下/向左按钮时触发。 ### UpClick ```vb Public Event UpClick() ``` 点击向上/向右按钮时触发。 ### BeforeChange ```vb Public Event BeforeChange(ByVal Value As Long, ByRef Delta As Long) ``` 值即将改变时触发。Value为当前值,Delta为预期变化量,可修改Delta控制实际变化。 ### Change ```vb Public Event Change() ``` 值改变后触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件区域时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件区域时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE拖放操作完成时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE拖放操作放置时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE拖放操作悬停时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE拖放操作给反馈时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE拖放操作设置数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE拖放操作开始时触发。 ## 代码示例 ### 基本用法 ```vb ' 设置UpDown控件 With UpDown1 .Min = 0 .Max = 100 .Value = 50 .Increment = 5 .Wrap = True Set .BuddyControl = Text1 .BuddyProperty = "Text" .SyncBuddy = True End With ' 限制值变化范围 Private Sub UpDown1_BeforeChange(ByVal Value As Long, ByRef Delta As Long) If Value + Delta > 100 Then Delta = 0 End Sub ' 响应值变化 Private Sub UpDown1_Change() Debug.Print "当前值: " & UpDown1.Value End Sub ``` --- --- url: /zh/official/IDE/AddIns/Community.md --- ::: warning 外接程序是编译后的可执行文件,因此应采取与对待任何非自行编写的应用程序相同的安全措施。 请务必采取必要的预防措施。 ::: 参见**示例 10. twinBASIC IDE Addin**以开始编写您自己的外接程序,完成后请将其添加回此处。 --- --- url: /zh/official/Tutorials/Testing-with-Assert.md --- # 使用Assert编写单元测试 本教程展示如何编写一个小函数、使用**Assert**包为其添加测试,并从IDE内部运行这些测试。 ## Assert包 [Assert包](/official/Reference/Assert/)提供三个模块——[**Exact**](/official/Reference/Assert/Exact)、[**Strict**](/official/Reference/Assert/Strict)和[**Permissive**](/official/Reference/Assert/Permissive)——它们共享相同的十五成员API: | 模块 | 字符串比较 | 数值数据类型必须匹配 | |--------|-------------------|-----------------------------| | **Exact** | 区分大小写 | 是——`5` 和 `5.0` 不相等 | | **Strict** | 区分大小写 | 否 | | **Permissive** | 不区分大小写 | 否 | 这三个模块在发布构建中会被编译掉:每个成员都标记了 `[DebugOnly(True)]`,因此断言调用在生产EXE中零运行时开销。测试与生产代码位于同一项目中,并在IDE中由完整调试器运行。 最常用的成员: * `Exact.AreEqual expected, actual` —— 如果两个值不同则失败 * `Exact.IsTrue condition` —— 如果条件为 `False` 则失败 * `Exact.IsFalse condition` —— 如果条件为 `True` 则失败 * `Exact.Fail message` —— 无条件记录失败 * `Exact.Succeed` —— 显式记录通过(在条件路径末尾很有用) 每个失败的断言记录源位置、期望值和实际值以及可选的消息字符串。结果显示在**调试控制台**面板中。 ## 添加包 打开**项目 → 引用**(Ctrl+T)→ **可用包**,勾选**Assert**。点击**确定**。三个模块(`Exact`、`Strict`、`Permissive`)现在在作用域中,无需任何 `Imports` 语句。 ## 被测试的函数 向项目添加一个标准**模块**(在项目资源管理器中右键点击项目,然后**添加 → 模块**)。命名为 `StringUtils`。添加以下函数: ```vb ' Pads s on the left with padChar until it reaches totalWidth characters. ' If s is already at or beyond totalWidth, it is returned unchanged. Public Function PadLeft(ByVal s As String, _ ByVal totalWidth As Long, _ Optional ByVal padChar As String = " ") As String If Len(s) >= totalWidth Then PadLeft = s Else PadLeft = String(totalWidth - Len(s), Left$(padChar, 1)) & s End If End Function ``` `PadLeft` 是一个很好的测试对象:它有明确的规格说明、带有默认值的可选参数,以及多个不同的边界情况。 ## 编写测试 添加第二个模块 `TestStringUtils`。每个测试是一个 `Public Sub`,测试函数的一个方面。保持每个Sub简短——理想情况下每个Sub一个逻辑场景,名称描述其检查内容。 ```vb Public Sub TestPadLeft_Normal() ' Three spaces prefix "hi" to reach width 5 Exact.AreEqual " hi", PadLeft("hi", 5) End Sub Public Sub TestPadLeft_CustomPadChar() ' Zero-pad to width 5 Exact.AreEqual "00042", PadLeft("42", 5, "0") End Sub Public Sub TestPadLeft_AtWidth() ' Already at width -- no change Exact.AreEqual "hello", PadLeft("hello", 5) End Sub Public Sub TestPadLeft_ExceedsWidth() ' Already longer than width -- not truncated Exact.AreEqual "toolong", PadLeft("toolong", 5) End Sub Public Sub TestPadLeft_EmptyString() ' Empty input -- result is all padding Exact.AreEqual " ", PadLeft("", 3) End Sub Public Sub TestPadLeft_SingleChar() ' Width of 1, input already 1 char -- no change Exact.AreEqual "x", PadLeft("x", 1) End Sub ``` 这些测试覆盖了:正常情况、自定义填充字符、边界情况、超出边界情况、空输入和最小输入。 ## 运行测试 有两种方式运行测试Sub: 1. **CodeLens** —— 将光标放在测试Sub内的任何位置。`Sub` 行上方的CodeLens条显示一个 `▶ Run` 按钮。点击它运行该Sub。结果立即显示在**调试控制台**中。 2. **从Sub内部按F5** —— 将光标放在Sub内并按**F5**。twinBASIC运行该过程,并在其返回或断言失败时停止。 要批量运行所有测试,添加一个运行器Sub按顺序调用每个测试: ```vb Public Sub RunAllTests() TestPadLeft_Normal TestPadLeft_CustomPadChar TestPadLeft_AtWidth TestPadLeft_ExceedsWidth TestPadLeft_EmptyString TestPadLeft_SingleChar Debug.Print "All PadLeft tests passed." End Sub ``` 将光标放在 `RunAllTests` 内并按**F5**(或点击CodeLens条中的\*\*▶ Run\*\*)。如果任何断言失败,执行在失败行停止,调试控制台显示哪个断言失败、其期望值和实际值以及源位置。 ## 测试错误路径 有时函数应该对错误输入引发错误。使用 `On Error Resume Next` 和 `Err.Number` 进行测试: ```vb Public Sub TestPadLeft_ZeroWidth() ' A width of 0 is technically valid -- the string is returned unchanged ' if it is already zero-length, and unchanged otherwise. Exact.AreEqual "hi", PadLeft("hi", 0) Exact.AreEqual "", PadLeft("", 0) End Sub ``` 如果你期望函数引发错误: ```vb Public Sub TestSomethingThatShouldRaise() On Error Resume Next SomeFunctionThatRaises 0 ' call that should fail If Err.Number = 0 Then Exact.Fail "expected an error, but none was raised" End If On Error GoTo 0 End Sub ``` ## 选择正确的模块 默认使用**Exact**——其最严格的比较语义防止测试因错误原因而通过。当被测试代码有意不区分大小写,或比较的值无论数值类型如何都应相等时,切换到**Strict**或**Permissive**: ```vb ' Exact would fail because "hello" ≠ "Hello" (case differs) Strict.AreEqual "HELLO", LCase$("HELLO") ' fails -- "hello" ≠ "HELLO" Permissive.AreEqual "HELLO", LCase$("HELLO") ' passes -- case-insensitive ``` 三个模块的完整文档见: * [Exact模块](/official/Reference/Assert/Exact) —— 最严格的语义 * [Strict模块](/official/Reference/Assert/Strict) —— 区分大小写字符串,类型宽松数值 * [Permissive模块](/official/Reference/Assert/Permissive) —— 不区分大小写字符串,类型宽松数值 ## 测试组织 随着项目增长,将测试保持在它们所测试的代码附近。一种常见约定: * 每个关注点一个生产模块:`StringUtils`、`DateUtils`、`FileHelpers`、…… * 每个生产模块一个测试模块:`TestStringUtils`、`TestDateUtils`、`TestFileHelpers`、…… * 在 `TestRunner` 模块中有一个顶层 `RunAll` Sub,调用每个模块的运行器 由于所有测试Sub在发布构建中会被编译掉(`[DebugOnly(True)]`),这种组织不会给发布可执行文件增加任何开销。 ## 下一步 * **Assert包参考** —— 所有十五个成员的详细说明:[Assert包](/official/Reference/Assert/) * **窗体基础** —— 构建窗体以可视化地承载小型测试工具:[窗体基础](/official/Tutorials/Forms) * **Windows API** —— 编写和测试封装Declare的函数:[调用Windows API](/official/Tutorials/Windows-API) --- --- url: /zh/official/Videos.md --- # 视频 记录twinBASIC开发和使用过程的视频。 * [**twinBASIC**](/official/Videos/twinBASIC) —— 官方twinBASIC视频系列:简介、编译器特性演示、调试演示、窗体设计器以及"twinBASIC for Applications"概念验证。 * [**Access DevCon**](/official/Videos/AccessDevCon) —— 年度Access DevCon大会上的twinBASIC主题演讲(2021--2025),由Microsoft Access MVP Mike Wolfe主讲。 > AI生成 --- --- url: /zh/official/IDE/Menu/View.md --- # 视图菜单 ![View Menu](/assets/Menu_View.D8SZ1Ya9.png "View Menu") * 代码编辑器 * 对象设计器 SHIFT + F7 *** * 定义 SHIFT + F2 / F12 * 上次位置 CTRL + SHIFT + F2 *** * 对象浏览器 * 放大 * 缩小 *** * 编辑器 * 项目资源管理器 * 打开的编辑器 * 历史记录 * 大纲 * 调用堆栈 CTRL + L * 变量 * 监视 * 调试控制台 CTRL + G * 诊断 * 包发布 * 工具栏 * 工具箱 * 属性 * 网页 * 查找/替换 * 内存 1 --- --- url: /zh/official/Documentation/Book-Configuration.md --- # 书籍配置 `docs/_book.yml` 定义 PDF 书籍的章节清单:哪些页面出现、以什么顺序、以及它们如何映射到命名的部分和章节。`book.mjs` 在阶段 2(解析页面选择器)和阶段 8(组装 `book.html`)期间读取此文件。参阅[管线阶段](/official/Documentation/Pipeline-Stages)了解相关的接口契约。 ## 文件位置与加载顺序 **文件:** `docs/_book.yml` `data.mjs` 在阶段 2 期间加载 `_book.yml` 并使其作为 `site.data.book` 可用。编排器然后将 `site.data.book` 暴露为 `site.bookData` 并传递给 `resolveBookChapters`。该调用遍历整个结构并将每个选择器解析为具体的 `Page[]`,存储为 `entry._chapters`,因此阶段 8 的 `assembleBook` 无需再做页面查找。 运行 `build.bat` 然后运行 `book.bat` 以查看更改的效果。`check.bat` 完整性检查也会运行 PDF 构建阶段。 ## 顶层结构 ```yaml front_matter: - <entry> # 零个或多个条目,在第一个 Part 之前发出 - ... parts: - <part> # 一个或多个编号 Part - ... ``` **`front_matter`** 条目在标题页和第一个编号 Part 之间发出。它们不生成分隔页和部分编号。 **`parts`** 条目每个生成一个编号分隔页。一个部分可以包含一组平面页面或有序的 `chapters` 列表,每个章节生成自己的子分隔页。 `front_matter` 条目和部分(及其章节)都共用下面描述的[选择器模式](#selector-schema)和[通用条目选项](#common-entry-options)。 ## 选择器模式 每个条目可以组合以下任何键来选择它贡献给书籍的页面。默认所有匹配都是 `contains` --- 页面的 URL 或导航路径必须包含前缀字符串。在条目上设置 `no_descent: true` 可将其所有匹配切换为精确相等。 | 键 | 类型 | 描述 | |---|---|---| | `page` | `string` | 单个 URL 前缀。单元素 `pages:` 列表的简写。 | | `pages` | `string[]` | URL 前缀列表。每个前缀与页面的 `permalink` 字段匹配。 | | `nav_page` | `string` | 单个导航路径前缀。单元素 `nav_pages:` 列表的简写。页面的导航路径是其斜杠连接的 `grand_parent / parent / title` 链,由 `nav.mjs` 填充。 | | `nav_pages` | `string[]` | 导航路径前缀列表,与每个页面的 `navPath` 字段匹配。 | | `no_descent` | `boolean` | 当为 `true` 时,将此条目上的每个匹配从 `contains` 切换为精确相等。当前缀如 `/Foo/` 应仅匹配索引页而非其子页面时使用,或当 `page: /` 否则会扫入站点上的每个页面时使用。 | 所有选择器键可以在一个条目中组合使用。同时有 `page` 和 `nav_page` 的条目收集两个选择的并集。章节条目上的选择器与包含部分的选择器独立 --- 章节收集自己的页面;部分不会自动继承它们。 ## 通用条目选项 front\_matter 条目、部分和章节都支持这些选项。部分和章节行为不同的地方,部分形式在前,章节形式在括号中注明。 ### `title` / `subtitle` ```yaml title: "VBA Package" subtitle: "Standard runtime modules --- Strings, Math, FileSystem, and the rest" ``` `title` 是分隔标题的文本 --- 部分用 H1,章节用 H2。`subtitle` 是在 `title` 下方渲染的可选副标题。两者都用作 PDF 书签标签。 当设置了 `landing_is_target:` 时,`title` 被注入登录页的文章中,而不是在独立的分隔页上渲染。 ### `landing_page` ```yaml landing_page: /tB/Packages/VBA ``` 单个绝对 URL。命名页在条目的内容列表中最先发出,在任何前缀扫入的页面之前。它被排除在前缀匹配之外,因此不会被发出两次。其源 H1 被重写器剥离,因此分隔标题仍然是条目的唯一 PDF 大纲条目。与 `foreword_page:` 不同,`landing_page` 以正常的连续页眉和常规文章样式渲染。 ### `landing_is_target` ```yaml landing_page: /tB/Packages/VBA landing_is_target: true ``` 需要 `landing_page:`。设置后,分隔页静默渲染,条目 `title` 作为 H1(部分)或 H2(章节)注入登录页文章的开头。PDF 书签导航到登录页而非空白分隔页。登录页的源 H1 仍被剥离。 与 `outline_closed:` 配对以使书签开始时折叠。 ### `no_outline_entry` ```yaml no_outline_entry: true ``` 将分隔 `title` 作为静默 `<p>` 而非 H1 或 H2 发出。PagedJS 在构建 PDF 大纲时跳过静默段落,因此条目没有自己的书签。条目页面中的第一个内容标题成为书签目标。 与 `landing_page:` 组合时,跳过登录页源 H1 的剥离 --- 登录页自己的第一个标题成为书签目标。 与 `no_heading_shift:` 配对以将该标题保持在正确的深度。 ### `no_heading_shift` ```yaml no_heading_shift: true ``` 控制标题组装器如何移动级别以防止组合的 `book.html` 中出现多个 H1。参阅下面的[标题移动机制](#heading-shift-mechanics)。 ### `outline_closed` ```yaml outline_closed: true ``` 使此条目的 PDF 书签开始时折叠(子项在 PDF 阅读器中展开前隐藏)。`data-pdf-bookmark-closed` 属性标记在: * 分隔 H1 / H2,对于有可见分隔标题的条目; * 第一个内容文章,对于 `no_outline_entry` 条目(PagedJS 通过 `closest()` 找到标题); * 注入的标题本身,对于 `landing_is_target` 条目。 ## 仅部分选项 ### `foreword_page` ```yaml foreword_page: /tB/Packages/ ``` 单个绝对 URL。命名页作为 `<article class="part-foreword">` 在部分分隔之后、任何章节分隔之前发出。无连续页眉(CSS 为前言文章抑制页面装饰)。前言的源 H1 不被剥离,也不成为 PDF 大纲条目。 与 `landing_page:` 在两个方面不同:源 H1 被保留,前言本身没有大纲贡献。 ### `chapters` ```yaml chapters: - title: VBA Package ... - title: VBRUN Package ... ``` 有序章节条目列表。每个章节生成自己的分隔页(H2)并使用相同的选择器模式和上述通用条目选项。除与部分共用的之外,不存在章节专有选项。 ## 标题移动机制 PDF 组装器移动标题级别以防止源 H1 与部分和章节分隔标题竞争: * **部分(无章节):** 部分中的每个页面接收 +1 移动 --- 源 H1 渲染为 H2,H2 渲染为 H3,以此类推。在部分条目上设置 `no_heading_shift: true` 以跳过此移动,保持源 H1 为 H1。 * **部分内的章节:** 每个页面总共接收 +2 移动(来自部分的基准 +1,加上章节级别的额外 +1)--- 源 H1 渲染为 H3。在章节条目上设置 `no_heading_shift: true` 以仅跳过额外的 +1,使源 H1 渲染为 H2 而非 H3。 典型模式:当单页部分或章节应使用登录页自己的 H1 作为 PDF 书签目标而不需要上方冗余的静默分隔时,将 `no_outline_entry: true` 与 `no_heading_shift: true` 配对。 ## 排序顺序 在每个条目内,选定的页面按 `sortByNavOrder` 排序: 1. **索引页优先** --- URL 以 `/` 结尾的任何页面。 2. **有 `nav_order` 的页面** --- 按 `nav_order` 值升序,以 `title` 作为平局决胜。 3. **无 `nav_order` 的页面** --- 按 `title` 字母顺序。 4. **按所属索引分组** --- 索引页面及其直接子页面保持相邻。 `landing_page:` URL 始终排在排序集之前的第一位,并被排除在排序集之外,因此不会被发出两次。 ## 实例说明 ### 带 `landing_is_target` 的章节 ```yaml - title: VBA Package subtitle: Standard runtime modules --- Strings, Math, FileSystem, and the rest landing_page: /tB/Packages/VBA page: /tB/Modules/ landing_is_target: true outline_closed: true ``` 这在 PDF 中生成: 1. 静默渲染的章节分隔(无可见的 H2 页面),因为 `landing_is_target: true`。 2. `/tB/Packages/VBA` 处的 VBA 登录页 --- 第一篇文章,`"VBA Package"` 作为 H2 注入其内容顶部。其原始源 H1 被剥离。 3. URL 包含 `/tB/Modules/` 的每个页面,按 `sortByNavOrder` 排序。 4. 此章节的 PDF 书签导航到 VBA 登录页并开始时折叠。 *** ### 带可见分隔和 `nav_page` 选择器的章节 ```yaml - title: Operators nav_page: Reference Section/Operators outline_closed: true ``` 这生成: 1. 可见的 H2 分隔页,标题为 "Operators"。 2. 所有 `navPath` 包含 `Reference Section/Operators` 的页面,按导航顺序。 3. PDF 书签导航到分隔页,开始时折叠。 *** ### 带 `no_outline_entry` 和 `no_descent` 的前言条目 ```yaml front_matter: - title: Introduction page: / no_outline_entry: true no_heading_shift: true no_descent: true outline_closed: true ``` 这生成: 1. 仅根页面(`/`)--- `no_descent: true` 阻止 `/` 扫入站点上的每个页面。 2. 分隔标题 "Introduction" 渲染为静默 `<p>`(无自身书签)。页面的源 H1 成为 PDF 书签目标。 3. 因为设置了 `no_heading_shift: true`,源 H1 渲染为 H1 而非 H2。 4. 书签开始时折叠。 *** ### 带前言和嵌套章节的部分 ```yaml - title: Packages subtitle: The runtime and library packages shipped with twinBASIC outline_closed: true foreword_page: /tB/Packages/ chapters: - title: VBA Package ... - title: VBRUN Package ... ``` 这生成: 1. 部分分隔页(H1),标题为 "Packages"。 2. `/tB/Packages/` 处的页面作为前言文章发出(无连续页眉,无大纲条目)。其 H1 被保留。 3. 每个章节的章节分隔页(H2),后跟该章节按导航顺序排列的页面。 ## 另见 * [管线阶段](/official/Documentation/Pipeline-Stages) -- `book.mjs` 接口契约。 * [tbdocs 构建器](/official/Documentation/Builder) -- `book.mjs` 的设计理念。 > AI生成 --- --- url: /zh/official/IDE/Properties.md --- # 属性 ![Properties](Images/Properties.png "Properties") 属性面板显示窗体设计器中当前选定的控件或对象的属性。属性名称显示在左列,当前值在右侧;点击值即可就地编辑。 --- --- url: /zh/official/Reference/Attributes.md --- # 属性 属性有两个主要功能: * 它们可以作为给编译器的指令来影响代码生成方式,或 * 用于标注窗体、模块、类、类型、枚举、Declares和[过程](/official/Reference/Glossary#procedure),即Sub/Function/Properties。 以前在VBx中,这些属性(如过程描述、隐藏、默认成员等)是通过IDE编辑器不显示的隐藏文本设置的,通过"过程属性"对话框或其他地方配置。在tB中,这些都在代码编辑器中可见。VBx的旧属性出于兼容性而受支持,但新属性使用以下语法: `[Attribute]`或`[Attribute(value)]` 在接受可选布尔参数的属性中,如果未提供值,则参数值取为**True**。这不意味着属性的默认值为True,只是如果属性在方括号内指定但没有值,其值将被设为True。不同的布尔值属性有不同的默认值。这些默认值在用户未显式提供属性时适用。 多个属性可以在同一方括号内指定,用逗号分隔: `[Attribute1, Attribute2(param), Attribute3]` *** ## 可用属性按字母顺序列出如下。并非每个属性都适用于每个语言元素。每个属性的适用范围在其语法下方给出。 ## AppObject (可选 Bool) 语法:**\[AppObject** \[ **( True** | **False )** ] **]** 适用于:[**CoClass**](/official/Reference/Core/CoClass) 旧版VB属性:*VB\_GlobalNameSpace* 指示该类属于全局命名空间。在未完全理解其含义的情况下,不应包含此属性。**Global**类是一个AppObject。 更多细节参见[此VBA文档页](https://learn.microsoft.com/en-us/openspecs/microsoft_general_purpose_programming_languages/ms-vbal/189fb41b-cc3a-4999-a6d2-ba89f72d2870)。 ## ArrayBoundsChecks (可选 Bool) 语法:**\[ArrayBoundsChecks** \[ **( True** | **False )** ] **]** 适用于:[**Class**](/official/Reference/Core/Class)、[**Module**](/official/Reference/Core/Module)、[过程](/official/Reference/Glossary#procedure) 在类、模块或单个过程/方法的范围内禁用或启用数组元素访问边界检查。用于性能关键的例程。 ## BindOnlyIfNoArguments (可选 Bool) 语法:**\[BindOnlyIfNoArguments** \[ **( True** | **False )** ] **]** 适用于:[过程](/official/Reference/Glossary#procedure) 仅在不存在参数时将此名称绑定到调用点。通常为False,但下面有一个例外。 此属性解决编译器对某些过程名称的特殊处理与不应被特殊处理的同名过程之间的冲突。目前这影响名为`Left`的过程。此类过程会被编译器隐式分配`[BindOnlyIfNoArguments(True)]`。如果用户希望拥有此名称的过程,应包含`[BindOnlyIfNoArguments(False)]`。 ## BindOnlyIfStringSuffix (可选 Bool) 语法:**\[BindOnlyIfStringSuffix** \[ **( True** | **False )** ] **]** 适用于:[过程](/official/Reference/Glossary#procedure) ## ClassId (String) 语法:**\[ClassId("** 00000000-0000-0000-0000-000000000000 **")]** 适用于:[**Class**](/official/Reference/Core/Class) 为类分配COM CLSID。详情参见[此COM文档页](https://learn.microsoft.com/en-us/windows/win32/com/com-class-objects-and-clsids)。 ## ClassInterface twinBASIC不直接支持此属性。它以不同名称支持其值。参见: * [DualInterface](#dualinterface) * [DispInterface](#dispinterface) ## CoClassCustomConstructor (String) 语法:**\[CoClassCustomConstructor("** 工厂方法的完全限定路径 **")]** 适用于:[**CoClass**](/official/Reference/Core/CoClass) 允许自定义逻辑来创建并返回coclass实现的新实例。 示例: ```vb [CoClassId("7980D953-10BF-478C-93BB-DD0093315D96")] [CoClassCustomConstructor("FooFactory.CreateFoo")] [COMCreatable(True)] Public CoClass Foo ' ... End CoClass ``` 关于tB中coclasses的概述,参见[定义coclasses](/official/Features/Language/Interfaces-CoClasses#defining-coclasses)。 ## CoClassId (String) 语法:**\[CoClassId("** 00000000-0000-0000-0000-000000000000 **")]** 适用于:[**CoClass**](/official/Reference/Core/CoClass) 除了接口,twinBASIC还允许定义coclasses --- 实现一个或多个已定义接口的可创建类。与接口一样,这些也必须在.twin文件中而非旧版.bas/.cls文件中,且必须出现在`Class`或`Module`语句之前。通用形式如下: ```vb [CoClassId("00000000-0000-0000-0000-000000000000")] *<attributes>* CoClass <name> [Default] Interface <interface name> *[Default, Source] Interface <event interface name>* *<additional Interface items>* End CoClass ``` 方法是[过程](/official/Reference/Glossary#procedure)。 关于tB中coclasses的概述,参见[定义coclasses](/official/Features/Language/Interfaces-CoClasses#defining-coclasses)。 ## COMControl (可选 Bool) 语法:**\[COMControl** \[ **( True** | **False )** ] **]** 适用于:[**Interface**](/official/Reference/Core/Interface) ## COMCreatable (可选 Bool) 语法:**\[COMCreatable** \[ **( True** | **False )** ] **]** 适用于:[**Class**](/official/Reference/Core/Class)、[**CoClass**](/official/Reference/Core/CoClass) 指示此coclass可以使用[**New**](/official/Reference/Core/New)关键字创建。 ## COMExtensible (可选 Bool) 语法:**\[COMExtensible** \[ **( True** | **False )** ] **]** 适用于:[**Interface**](/official/Reference/Core/Interface)、[接口中的过程](/official/Reference/Glossary#procedure) 指定运行时添加的新成员是否可以通过实现**IDispatch**的接口按名称调用。此属性默认为**False**。 ## ComImport (可选 Bool) 语法:**\[ComImport** \[ **( True** | **False )** ] **]** 适用于:[**Interface**](/official/Reference/Core/Interface) 指定接口是从外部COM库导入的,例如Windows Shell。 ## CompileIf (Bool) 语法:**\[CompileIf(** 条件 **)]** 适用于:[过程定义](/official/Reference/Glossary#procedure) 控制过程定义的条件编译。没有默认值。 ## CompilerOptions (String) 语法:**\[CompilerOptions( "** 选项 **" )]** 适用于:[过程定义](/official/Reference/Glossary#procedure) 典型用法是`[CompilerOptions("+llvm,+optimize,+optimizesize")]`以使用内置LLVM而非默认编译器编译过程,并选择优化。可用编译器选项: * **+llvm** - 使用LLVM编译此过程。此功能目前为实验性,不能用于编译带有"复杂"参数/变量类型(如对象、字符串和动态数组)的函数。LLVM编译器后端内置于twinBASIC。无需单独安装LLVM,twinBASIC会忽略任何此类安装。 * **+optimize** - 在编译此过程时启用优化 * **+optimizesize** - 优化此过程以获得更小的代码大小,可能以过程速度变慢为代价 * **+optimizespeed** - 优化此过程以获得更快的速度,可能以编译后更大的代码体积为代价 ## ConstantFoldable (可选 Bool) 语法:**\[ConstantFoldable** \[ **( True** | **False )** ] **]** 适用于:[**Function**](/official/Reference/Core/Function) 为使用非变量输入调用时将在编译时而非运行时计算的函数指定此属性。例如,将字符串字面量转换为ANSI的函数。结果永远不会改变,因此存储生成的ANSI字符串,而非每次运行重新计算。此类函数也称为*纯函数*,因为其输出仅取决于参数,而不取决于程序状态。 ## ConstantFoldableNumericsOnly (可选 Bool) 语法:**\[ConstantFoldableNumericsOnly** \[ **( True** | **False )** ] **]** 适用于:[**Function**](/official/Reference/Core/Function) [常量折叠属性](#constantfoldable)的有限情况,仅在函数使用数值参数调用时适用。 ## CustomControl (String) 语法:**\[Description("** 图片文件名 **")]** 适用于:[**Class**](/official/Reference/Core/Class) ## Debuggable (可选 Bool) 语法:**\[Debuggable** \[ **( True** | **False )** ] **]** 适用于:[**Module**](/official/Reference/Core/Module)、[**Class**或**Module**中的过程](/official/Reference/Glossary#procedure) 为False时,关闭方法或模块的断点和单步执行。默认值为**True**。 ## DebugOnly (可选 Bool) 语法:**\[DebugOnly** \[ **( True** | **False )** ] **]** 适用于:[过程定义](/official/Reference/Glossary#procedure) 将对此过程的调用从Build中排除。它们仅在从IDE运行(即调试)时可用。 ## DefaultMember (可选 Bool) 语法:**\[DefaultMember** \[ **(** **True** | **False** **)** ] **]** 适用于:[**Class**中的过程](/official/Reference/Glossary#procedure) 默认成员在对象实例本身下访问,无需指定其名称。例如,提供可索引元素的类可能有一个**Item**属性作为默认成员: ```vb Class MyCollection [DefaultMember] Property Get Item(ByVal index&) As String ' ... End Property [DefaultMember] Property Let Item(ByVal index&, ByVal value$) ' ... End Property End Class Sub Example() Dim coll As New MyCollection Debug.Print "Item #3: ", coll(3) ' Property Get Item is invoked coll(4) = "Item 4" ' Property Let Item is invoked End Sub ``` ## Description (String) 语法:**\[Description("** 任意文本 **")]** 适用于:[**Class**](/official/Reference/Core/Class)、[**CoClass**](/official/Reference/Core/CoClass)、[**Const**](/official/Reference/Core/Const)、[**Declare** (API声明)](/official/Reference/Core/Declare)、[**Interface**](/official/Reference/Core/Interface)、[**Module**](/official/Reference/Core/Module)、[**Type** (UDT)](/official/Reference/Core/Type) 在IDE信息弹出窗口中提供描述,并作为`helpstring`属性导出到类型库(如适用)。 ## DispId (Integer) 语法:**\[DispId(** 123 **)]** 适用于:[接口中的过程](/official/Reference/Glossary#procedure) 定义通过**IDispatch**公开时与过程关联的调度ID。 ## DispInterface 语法:**\[DispInterface]** 适用于:**Library**中的[**Interface**](/official/Reference/Core/Interface) ::: info 此属性在twinBASIC为项目中的COM引用生成的**Library**模块中生成。它不能手动创建。 ::: 指示接口通过**IDispatch**后期绑定公开方法。这是默认值。注意也可以指定[**DualInterface**](#dualinterface),与基于**IDispatch**的接口相比性能大幅提升。 ## DllExport (可选 Bool) 语法:**\[DllExport** \[ **( True** | **False )** ] **]** 适用于:模块中的[过程](/official/Reference/Glossary#procedure)和变量。 可以从标准模块导出函数或变量。示例: ```vb [DllExport] Public Const MyExportedSymbol As Long = &H00000001 ``` ## DLLStackCheck (可选 Bool) 语法:**\[DLLStackCheck** \[ **( True** | **False)** ] **]** 适用于:[**Declare** (API声明)](/official/Reference/Core/Declare) 在Intel平台上的32位API调用中略微减少代码生成大小。对其他平台无影响。 ## DualInterface 语法:**\[DualInterface]** 适用于:**Library**中的[**Interface**](/official/Reference/Core/Interface) ::: info 此属性在twinBASIC为项目中的COM引用生成的**Library**模块中生成。它不能手动创建。 ::: 指示接口通过OLE VTable绑定公开方法。后者与基于**IDispatch**的接口相比性能大幅提升。 ## EnforceErrors (可选 Bool) 语法:**\[EnforceErrors** \[ **( True** | **False )** ] **]** 适用于:[过程](/official/Reference/Glossary#procedure)。 ## EnforceWarnings (可选 Bool) 语法:**\[EnforceWarnings** \[ **( True** | **False )** ] **]** 适用于:[过程](/official/Reference/Glossary#procedure)。 ## EnumId (String) 语法:**\[EnumId("** 00000000-0000-0000-0000-000000000000 **")]** 适用于:[**Enum**](/official/Reference/Core/Enum) 指定要与类型库中的枚举关联的GUID。 ## EventInterfaceId (String) 语法:**\[EventInterfaceId("** 00000000-0000-0000-0000-000000000000 **")]** ## EventsUseDispInterface (可选 Bool) 语法:**\[EventsUseDispInterface** \[ **( True** | **False )** ] **]** ## Flags (可选 Bool) 语法:**\[Flags** \[ **( True** | **False )** ] **]** 适用于:[**Enum**](/official/Reference/Core/Enum) 将隐式枚举值作为标志集(2的幂)计算。 ::: info 为避免混淆,一旦使用显式值,其后所有剩余值也必须为显式值) ::: ![image](/assets/flags-attribute.IxK5Gpre.png) ## FloatingPointErrorChecks (可选 Bool) 语法:**\[FloatingPointErrorChecks** \[ **( True** | **False)** ] **]** 适用于:[**Class**](/official/Reference/Core/Class)、[**Module**](/official/Reference/Core/Module)、[过程](/official/Reference/Glossary#procedure) 禁用浮点错误检查。用于性能关键的例程。默认值为**True**。 ## FormDesignerId (String) 语法:**\[FormDesignerId("** 00000000-0000-0000-0000-000000000000 **")]** 适用于:[**Class**](/official/Reference/Core/Class) ## Hidden (可选 Bool) 语法:**\[Hidden** \[ **(** **True** | **False** **)** ] **]** 适用于:[**Class**](/official/Reference/Core/Class)、[**CoClass**](/official/Reference/Core/CoClass)、[**Interface**](/official/Reference/Core/Interface) 将接口或类从某些IntelliSense和其他列表中隐藏。 ## IdeButton (String) 语法:**\[IdeButton("** 标题 **")]** 适用于:模块中的[过程](/official/Reference/Glossary#procedure)定义。 ## IgnoreWarnings (String List) 语法:**\[IgnoreWarnings** **(** **TBnnnn** \[ **,** **TBmmmm** ]... **)** **]** 禁用某些警告。字符串列表应枚举要抑制的警告。 ## IntegerOverflowChecks (可选 Bool) 语法:**\[IntegerOverflowChecks** \[ **( True** | **False )** ] **]** 适用于:[**Class**](/official/Reference/Core/Class)、[**Module**](/official/Reference/Core/Module)、[过程](/official/Reference/Glossary#procedure) 禁用整数溢出检查。用于性能关键的例程。默认值为**True**。 ## InterfaceId (String) 语法:**\[InterfaceId( "**00000000-0000-0000-0000-000000000000**" )]** 适用于:[**Interface**](/official/Reference/Core/Interface) twinBASIC支持使用BASIC语法定义COM接口,而不需要带有IDL和C++的类型库。这些仅在.twin文件中受支持,不支持旧版.bas或.cls文件。它们必须出现在[**Class**](/official/Reference/Core/Class)或[**Module**](/official/Reference/Core/Module)语句*之前*,并始终具有项目范围的可见性。通用形式如下: ```vb [InterfaceId ("00000000-0000-0000-0000-000000000000")] *<attributes>* Interface <name> Extends <base-interface> *<attributes>* <method 1> *<attributes>* <method 2> ' ... End Interface ``` 方法是[过程](/official/Reference/Glossary#procedure)。 关于tB中接口的概述,参见[定义接口](/official/Features/Language/Interfaces-CoClasses#defining-interfaces)。 ## MustBeQualified (可选 Bool) 语法:**\[MustBeQualified** \[ **(True** | **False )** ] **]** 适用于:[过程](/official/Reference/Glossary#procedure) ## OleAutomation (可选 Bool) 语法:**\[OleAutomation** \[ **(True** | **False )** ] **]** 适用于:[**Interface**](/official/Reference/Core/Interface) 控制此属性是否在类型库中应用。此属性默认为**True**。 ## PackingAlignment (Integer) 语法:**\[PackingAlignment( 1** | **2** | **4** | **8** | **16** | **32** | **64 )]** 适用于:[**Type** (UDT)](/official/Reference/Core/Type) twinBASIC通常在UDT内自然对齐对象,例如8字节对象相对于UDT起始处在8字节边界对齐。这可能在UDT字段之间留下间隙。使用较小的**PackingAlignment**可以实现更紧凑的打包: ```vb [PackingAlignment(2)] Private Type MyUDT x As Integer y As Long z As Integer End Type Private t As MyUDT Debug.Assert Len(t) = 8 And LenB(t) = 8 ``` 你现在会发现`Len(t)`和`LenB(t)`都是8。 ::: info 对齐方式(而非打包对齐)不是以此方式设置的。指定16不会让`t`得到16字节结构。twinBASIC目前没有`__declspec_align(n)`的等效功能,但计划添加此功能。这在内核模式编程之外很少见。 ::: 关于此功能的介绍,参见[自定义UDT打包](/official/Features/Language/UDTs#custom-udt-packing)。 ## PopulateFrom (...) 语法:**\[PopulateFrom( "json", "**.json的内部路径\*\*", "\*\* 表字段 **", "** 名称字段 **", "** 值字段 **" )]** 适用于:[**Enum**](/official/Reference/Core/Enum) 从项目附带的json文件中用值填充**Enum**。 .json文件的路径和字段名是任意的。因此,json文件不必在项目内的Resources文件夹中。 将来,此属性可能会扩展以允许更多数据文件类型和除**Enum**之外的更多使用上下文。 例如,考虑.twin文件中的以下枚举声明: ```vb [PopulateFrom("json", "/Resources/MESSAGETABLE/Strings.json", "events", "name", "id")] Enum EVENTS End Enum ``` 那么,应有`/Resources/MESSAGETABLE/Strings.json`文件,结构如下: ```json { "events": [ { "id": -1073610751, "name": "service_started", "LCID_0000": "%1 service started" }, ], } ``` 结果等同于我们手写以下**Enum**定义: ```vb Enum EVENTS service_started = -1073610751 End Enum ``` ## PredeclaredID (可选 Bool) 语法:**\[PredeclaredId** \[ **( True** | **False )** ] **]** 适用于:[**Class**](/official/Reference/Core/Class) 设置后,应用程序启动时会创建该类的全局实例。 此属性等同于VBx .cls文件中的`VB_PredeclaredId`属性。 ## PreserveSig (可选 Bool) 语法:**\[PreserveSig** \[ **(** **True** | **False** **)** ] **]** 适用于:[接口](/official/Reference/Core/Interface)中的方法、[API声明](/official/Reference/Core/Declare)。 默认值:接口中为**False**,API Declare中为**True**。 在COM接口中,此属性的默认值为**False**,因为通常方法返回HRESULT,语言对你隐藏了它。**\[PreserveSig** \[ **(True)** ] **]**覆盖此行为,按照你提供的方式定义函数。如果你需要将其定义为返回4字节**Long**以外的类型,或者希望自己处理结果(绕过返回值为负数时引发的正常运行时错误),这是必要的(当负值表示预期的、可接受的失败而非真正的错误时有帮助,例如当枚举接口没有更多项时)。 在API中,此属性的默认值为`True`。因此,你可以指定`False`将最后一个参数重写为返回值。示例: ```vb Public Declare PtrSafe Function SHGetDesktopFolder Lib "shell32" (ppshf As IShellFolder) As Long ``` 可以重写为 ```vb [PreserveSig(False)] Public Declare PtrSafe Function SHGetDesktopFolder Lib "shell32" () As IShellFolder` ``` ## Restricted (可选 Bool) 语法:**\[Restricted** \[ **( True** | **False )** ] **]** 适用于:[**Interface**](/official/Reference/Core/Interface) 限制接口方法在大多数上下文中被调用。 此属性与[**restricted** MIDL属性][MIDL restricted]功能相同。 [MIDL restricted]: https://learn.microsoft.com/en-us/windows/win32/midl/restricted ## RunAfterBuild (可选 Bool) 语法:**\[RunAfterBuild** \[ **( True** | **False )** ] **]** 适用于:[**Function**](/official/Reference/Core/Function)、[**Sub**](/official/Reference/Core/Sub) 指定在exe构建完成后运行的函数。如果例如要对可执行文件签名,可使用`App.LastBuildPath`了解其位置。 ## Serialize (可选 Bool) 语法:**\[Serialize** \[ **( True** | **False )** ] **]** 适用于:[**Class**](/official/Reference/Core/Class)中的变量 ## SetDllDirectory (可选 Bool) 语法:**\[SetDllDirectory** \[ **( True** | **False )** ] **]** 适用于:[**Declare** (API声明)](/official/Reference/Core/Declare)、[**Module**](/official/Reference/Core/Module) 允许显式加载的DLL从其加载路径加载自己的依赖项。还具有允许在基本应用的declare语句中搜索DLL的应用路径的效果。可以按声明或在模块内使用。 ## SimplerByVals (可选 Bool) 语法:**\[SimplerByVals** \[ **( True** | **False )** ] **]** 适用于:[过程](/official/Reference/Glossary#procedure) ## SpecialCompilerBinding (可选 Bool) 语法:**\[SpecialCompilerBinding** \[ **( True** | **False )** ] **]** ## TestCase (可选 Bool) 语法:**\[TestCase** \[ **( True** | **False )** ] **]** 适用于:模块中的[过程](/official/Reference/Glossary#procedure)定义。 ## TestFixture (可选 Bool) 语法:\*\*\[TestFixture \*\*\[ **( True** | **False )** ] **]** 适用于:[**Module**](/official/Reference/Core/Module) ## TypeHint (EnumType) 语法:**\[TypeHint(** 枚举类型 **)]** 适用于:[过程](/official/Reference/Glossary#procedure)参数 允许为**Long**以外的类型填充IntelliSense枚举。 ## Unimplemented (可选 Bool) 语法:**\[Unimplemented** \[ **( True** | **False )** ] **]** 适用于:[过程](/official/Reference/Glossary#procedure)定义 使编译器在调用此过程时发出关于过程未实现的警告。你还可以将其升级为错误。 ## UseGetLastError (可选 Bool) 语法:**\[UseGetLastError** \[ **( True** | **False )** ] **]** 适用于:[**Declare** (API声明)](/official/Reference/Core/Declare) 如果声明的函数指示错误条件,编译器不会自动调用`GetLastError`检索错误代码。此属性的默认值为**True**,即假定Declare的函数在出错时设置`LastError`。 ## UserDefinedTypeIsAnAlias (可选 Bool) 语法:**\[UserDefinedTypeIsAnAlias** \[ **( True** | **False )** ] **]** 适用于:[**Type** (UDT)](/official/Reference/Core/Type) ## WindowsControl (可选 Bool) 语法:**\[WindowsControl** \[ **( True** | **False )** ] **]** --- --- url: >- /zh/official/Tutorials/CustomControls/Property-sheet-and-object-serialization.md --- # 属性表和对象序列化 窗体设计器属性表会自动拾取你通过CustomControl类暴露的任何**公共**自定义属性(字段)。例如,添加一个字段 `Public MyField As Long` 将自动显示在窗体设计器的控件属性表中: ![CustomControl MyField propertySheet](/assets/ccMyFieldPropertySheet1a.DZAhqDEZ.png) 然后这会作为属性持久化到你的项目中的窗体JSON结构内: ![CustomControl MyField JSON](Images/ccMyFieldJson1a.png) 实现这一功能的关键是你的序列化构造函数,可能类似这样: ```vb Public Sub New(Serializer As SerializationInfo) If Not Serializer.Deserialize(Me) Then InitializeDefaultValues ' you implement this End If End Sub ``` 如果 `Deserialize(Me)` 返回 `True`,则你的类属性已与通过窗体设计器设置的属性同步。如果返回 `False`,则控件刚刚被添加到窗体,这让你有机会为自定义公共属性设置适当的默认值。窗体设计器会注意到你在序列化构造函数中设置的默认值,从而使属性表保持同步。 *** ## 默认值 设置默认值的另一种方法是将其内联到类字段定义中: ![CustomControl MyField = 42](/assets/ccMyFieldPropertySheet1b.BvsaN66h.png) 当控件正在从持久化的属性表数据同步时,序列化构造函数内的 `Deserialize(Me)` 调用将覆盖属性值。 *** ## 枚举 你在twinBASIC项目中定义的枚举受支持。只需暴露一个枚举类型的类字段: ![CustomControl enumeration property sheet example](/assets/ccMyEnumFieldPropertySheet.DNENBnKG.png) 注意:枚举以字符串形式持久化到窗体JSON结构中,因此在修改/更新CustomControl时请记住这一点,以免通过重命名枚举值引入破坏性变更。 *** ## 对象 你在twinBASIC项目中定义的类对象受支持。你***必须***为任何暴露的对象提供ClassId属性,以便序列化可以识别它。 ![CustomControl class property sheet example](/assets/ccMyFieldClass.REoH1Cev.png) *** ## 数组 数组受支持。窗体设计器允许添加新元素、删除元素和重新排序元素(通过拖放)。 ![CustomControl array property sheet example](/assets/ccMyFieldArray.BaQJ1lKy.png) *** ## Property Get / Let 自定义属性过程受支持。如果你希望属性更改触发控件重绘,你会发现需要使用Property Get / Let过程。 ![CustomControl custom property example](/assets/ccMyFieldCustomProperty.B3189mqP.png) 注意,**私有**字段和属性不构成序列化的一部分,因此不会出现在属性表上。 *** ## 避免使用Variant 序列化不支持Variant或通用Object。始终使用强类型数据类型。 *** ## 事件 你在类中定义的事件将显示在事件属性表中: ![CustomControl attribute](/assets/ccEvents.DlWQLIlE.png) 目前,窗体设计器尚不支持代码隐藏窗体,因此此功能尚未完成。 ::: tip 如果你对CustomControl类进行了更改,如暴露新属性或更改控件的绘制方式,这些更改将立即反映到任何打开的窗体设计器中。当你返回窗体设计器时,它们会显示一个"resync"按钮,按下后更改即可可见。 ::: ::: tip 在IDE中运行时序列化通过JSON进行,而在编译的DLL/EXE中运行时通过二进制格式进行。传递给你的序列化构造函数的 `SerializationInfo` 对象在IDE中运行时是不同的实现,但作为CustomControl开发者,这对你应该是透明的。 ::: ::: tip 在修改或更新CustomControl时,始终考虑向后兼容性。例如,如果你重命名了一个暴露的属性,旧的通过属性表存储的属性值将不会被反序列化到你的新属性中。 ::: *** ## 另见 * [`SerializeInfo`](/official/Reference/CustomControls/Framework/SerializeInfo) —— 当前序列化器类型的参考(上面代码段中的 `SerializationInfo` 名称是较旧的草稿名称;当前类型是 `SerializeInfo`,`Deserialize()` 暴露为 `RuntimeUISrzDeserialize()`) * [CustomControls包参考](/official/Reference/CustomControls/) —— 框架和内置 `Waynes…` 控件的概述 --- --- url: /zh/official/Reference/Glossary.md --- ## 快捷键 用作选择对象快捷方式的单个字符。按下ALT键后按快捷键可将焦点赋予该对象,并引发与该对象关联的一个或多个事件。引发的特定事件因对象而异。如果事件关联了代码,则在引发事件时处理该代码。也称为*键盘快捷键*、*快捷键*、*键盘快捷方式*或*访问键*。 ## ActiveX控件 放置在窗体上以启用或增强用户与应用程序交互的对象。ActiveX控件具有事件,可以嵌入到其他控件中。这些控件的文件扩展名为`.ocx`。 ## ActiveX对象 通过自动化接口暴露给其他应用程序或编程工具的对象。也称为*Automation对象*。 ## 加载项 向twinBASIC开发环境添加功能的自定义工具。 ## ANSI字符集 美国国家标准学会(ANSI)8位字符集,用于表示最多256个字符(0–255)。前128个字符(0–127)对应标准美式键盘上的字母和符号。后128个字符(128–255)表示特殊字符,如国际字母表中的字母、重音符号、货币符号和分数。 ## 应用程序 作为一个程序协同工作的代码和可视元素的集合。开发人员在开发环境中构建和运行应用程序,而用户通常在开发环境之外以可执行文件形式运行应用程序。 ## 参数 传递给[过程](#procedure)的常量、[变量](#variable)或[表达式](#expression)。 ## 数组 具有相同内在[数据类型](#data-type)的顺序索引元素集合。数组的每个元素都有唯一的标识索引号。对数组某一元素的修改不会影响其他元素。 ## ASCII字符集 美国信息交换标准代码(ASCII)7位字符集,用于表示标准美式键盘上的字母和符号。ASCII字符集与[ANSI字符集](#ansi-character-set)的前128个字符(0–127)相同。 ## 属性(Attribute) (twinBASIC) 附加到[模块](#module)、过程、参数或其他声明的元数据,写在方括号中 --- 例如`[Documentation("...")]`。某些属性控制编译器行为(如[用户自定义类型](#user-defined-type)上的`[PackingAlignment]`或成员上的`[VB_UserMemId]`);其他属性为信息性属性。属性是twinBASIC新增功能;经典VBA仅通过`Attribute`指令暴露少量固定属性集。 ## Automation对象 参见[ActiveX对象](#activex-object)。 ## 背景色 空窗口或显示屏客户区的颜色,所有绘图和颜色显示都在此上进行。 ## 基类 可通过继承派生出其他类的原始类。 ## 位图 由像素表示并作为位集合存储的图像,其中每个位对应一个像素。在彩色系统上,每个像素对应多个位。位图通常具有`.bmp`文件扩展名。 ## 按位比较 对两个数值表达式中相同位置的位逐一进行比较。 ## Boolean数据类型 只有两个可能值**True**(`-1`)或**False**(`0`)的[数据类型](#data-type)。**Boolean**变量存储为16位(2字节)数字。 ## 布尔表达式 计算结果为**True**或**False**的[表达式](#expression)。 ## 绑定 描述内容与特定[数据源](#data-source)关联的控件。 ## 绑定控件 提供对数据源中特定字段的访问的数据感知控件。当数据源中的当前记录更改时,连接到该数据源的所有绑定控件会更新以显示当前记录中字段的数据。当用户在绑定控件中更改数据然后移动到另一条记录时,更改会自动保存。 ## 中断模式 开发环境中程序执行的临时暂停。在中断模式下,可以检查、调试、重置、单步执行或继续程序执行。进入中断模式的情况包括: * 在程序执行期间遇到[断点](#breakpoint)。 * 在程序执行期间按CTRL+BREAK。 * 在程序执行期间遇到[**Stop**](/official/Reference/Core/Stop)语句或未捕获的运行时错误。 * 添加*为真时中断*[监视表达式](#watch-expression);当监视值更改且计算为**True**时执行停止。 * 添加*更改时中断*监视表达式;当监视值更改时执行停止。 ## 断点 执行自动停止的选定程序行。断点不会与代码一起保存。 ## 按引用传递 将参数的地址而非值传递给过程的方式。这允许过程访问实际变量。因此,变量的实际值可以被接收它的过程更改。除非另有说明,参数按引用传递。使用**ByRef**关键字可以显式指定。 ## 按值传递 将参数的值而非地址传递给过程的方式。这允许过程访问变量的副本。因此,变量的实际值不能被接收它的过程更改。使用**ByVal**关键字按值传递参数。 ## Byte数据类型 用于保存0到255正整数的[数据类型](#data-type)。**Byte**变量存储为单个无符号8位(1字节)数字。 ## 字符代码 表示字符集中特定字符的数字,如[ANSI字符集](#ansi-character-set)或[Unicode](#unicode)。 ## 类 对象的正式定义。类充当运行时创建对象实例的模板。类定义对象的属性和控制对象行为的方法。 ## 类级别 描述类声明部分中的代码。过程外的任何代码称为类级别代码。声明必须列在最前面,后跟过程。 ## 类模块 包含一个或多个[类](#class)定义(包括其属性和方法定义)的[模块](#module)。 ## 清除 将设置更改为"关"或移除值。 ## 代码模块 参见[标准模块](#standard-module)。*代码模块*是某些文档中仍在使用的旧术语。 ## 集合 包含一组相关对象的对象。对象在集合中的位置可能随集合中发生更改而变化;因此,集合中任何特定对象的位置都可能变化。[**Collection**](/official/Reference/VBA/Collection/)类是标准示例;该类的实例即为集合。集合必须实现一个名为`NewEnum`的方法,该方法不接受参数,返回适当的**IUnknown**对象,并将其[`VB_UserMemId`](#attribute)属性设置为`-4`。 ## 命令行 用户为运行程序而提供的路径、文件名和参数信息。 ## 注释 添加到代码中用于解释代码工作原理的文本。在twinBASIC中,注释可以以撇号(`'`)或**Rem**关键字加空格开始,延伸到行尾。 ## 比较运算符 指示两个或多个值或表达式之间关系的符号或关键字。这些运算符包括小于(`<`)、小于等于(`<=`)、大于(`>`)、大于等于(`>=`)、不等于(`<>`)和等于(`=`)。其他比较运算符包括[**Is**](/official/Reference/Core/Is)、[**IsNot**](/official/Reference/Core/IsNot)和[**Like**](/official/Reference/Core/Like)。注意**Is**和**Like**不能在[**Select Case**](/official/Reference/Core/Select-Case)语句中用作比较运算符。参见[比较运算符](/official/Reference/Core/Comparison-Operators)。 ## 编译时 源代码被翻译为可执行代码的期间。 ## 编译器指令 用于改变编译器行为的命令 --- 例如[条件编译](#conditional-compiler-constant)指令`#If`、`#Else`、`#ElseIf`和`#End If`,或`#Const`指令。参见[预处理器指令](/official/Reference/Core/Topic-Preprocessor)。 ## 条件编译常量 使用`#Const`编译器指令定义(或在项目编译条件中设置)的twinBASIC标识符,被其他编译器指令用于确定何时或是否编译某些代码块。参见[预处理器指令](/official/Reference/Core/Topic-Preprocessor)。 ## 常量 在整个程序执行期间保持常量值的命名项。常量可以是字符串或数值字面量、另一个常量,或任何包含算术或逻辑运算符(不包括[**Is**](/official/Reference/Core/Is)和指数运算)的组合。每个宿主应用程序可以定义自己的常量集。用户可以使用[**Const**](/official/Reference/Core/Const)语句定义附加常量。可以在代码中的任何位置使用常量代替实际值。 ## 容器 可以包含其他对象的对象。 ## 上下文ID 与应用程序中特定对象对应的唯一数字或字符串。上下文ID用于创建应用程序与相应帮助主题之间的链接。 ## 控件 放置在窗体上具有自己一组可识别属性、方法和事件的对象。控件用于接收用户输入、显示输出和触发事件过程。大多数控件可以使用方法进行操作。某些控件是交互式的(响应用户操作),而其他控件是静态的(只能通过代码访问)。参见[VB包](/official/Reference/VB/)中的标准控件集。 ## 控件数组 共享相同名称、类型和事件过程的一组控件。数组中的每个控件都有唯一的索引号,可用于确定哪个控件识别事件。 ## Currency数据类型 范围为-922,337,203,685,477.5808到922,337,203,685,477.5807的[数据类型](#data-type)。此数据类型用于涉及货币的计算和精度特别重要的定点计算。at符号(`@`)[类型声明字符](#type-declaration-character)表示**Currency**。 ## 游标 向应用程序返回数据行的软件。结果集上的游标指示结果集中的当前位置。 ## 数据格式 数据单元的结构或外观,如文件、数据库记录、电子表格单元格或字处理文档中的文本。 ## 数据源 控件绑定的数据位置,例如工作表中的单元格或数据库行中的字段。数据源的当前值可以存储在控件的`Value`属性中。但是,控件不存储数据;它仅显示数据源中存储的信息。 ## 数据类型 确定变量可以保存何种数据的变量特征。内在数据类型包括[**Byte**](#byte-data-type)、[**Boolean**](#boolean-data-type)、[**Integer**](#integer-data-type)、[**Long**](#long-data-type)、[**LongLong**](#longlong-data-type)、[**LongPtr**](#longptr-data-type)、[**Currency**](#currency-data-type)、[**Decimal**](#decimal-data-type)、[**Single**](#single-data-type)、[**Double**](#double-data-type)、[**Date**](#date-data-type)、[**String**](#string-data-type)、[**Object**](#object-data-type)、[**Variant**](#variant-data-type)(默认),以及[用户自定义类型](#user-defined-type)和特定类型的对象。 ## Date数据类型 用于将日期和时间存储为实数的[数据类型](#data-type)。**Date**变量存储为64位(8字节)数字。小数点左边的值表示日期,小数点右边的值表示时间。 ::: info 在twinBASIC中,[`Date`](/official/Reference/VBA/DateTime/Date)和[`Time`](/official/Reference/VBA/DateTime/Time)(及其`$`变体)作为**属性**暴露,而非经典VBA中的语句/函数。 ::: ## 日期表达式 任何可以解释为日期的表达式,包括日期字面量、看起来像日期的数字、看起来像日期的字符串以及从函数返回的日期。日期表达式限于可以表示100年1月1日至9999年12月31日日期的数字或字符串的任意组合。 日期作为实数的一部分存储。小数点左边的值表示日期;小数点右边的值表示时间。负数表示1899年12月30日之前的日期。 ## 日期字面量 任何具有有效格式并被数字符号(`#`)包围的字符序列。有效格式包括代码区域设置指定的日期格式或[通用日期格式](#universal-date-format)。 例如,`#12/31/92#`是表示1992年12月31日的日期字面量,其中英语(美国)是应用程序的区域设置。使用日期字面量以最大化跨国家语言的可移植性。 ## 日期分隔符 格式化日期值时用于分隔日、月和年的字符。字符由系统设置或[**Format**](/official/Reference/VBA/Strings/Format)函数确定。 ## DBCS 使用1或2个字节表示字符的字符集,允许表示超过256个字符。 ## 声明 命名常量、[变量](#variable)或[过程](#procedure)并指定其特性(如数据类型)的非可执行代码。对于DLL过程,声明指定名称、库和参数。 ## Decimal数据类型 包含按10的幂缩放的小数的[数据类型](#data-type)。对于零缩放数(无小数部分的整数),范围为+/-79,228,162,514,264,337,593,543,950,335。对于具有28位小数的数,范围为+/-7.9228162514264337593543950335。可以表示为**Decimal**的最小非零值为`0.0000000000000000000000000001`。 ::: info 与经典VBA中**Decimal**仅可用作**CDec**产生的**Variant**子类型不同,twinBASIC支持**Decimal**作为一等声明类型。可以编写`Dim x As Decimal`。 ::: ## 设计器 twinBASIC开发环境中的可视化设计界面,用于可视化设计窗体、控件和其他类。 ## 设计时 通过添加控件、设置控件或窗体属性以及编写代码在开发环境中构建应用程序的时间。相比之下,在[运行时](#run-time),用户与应用程序进行交互。 ## 开发环境 应用程序中编写代码、创建控件、设置控件和窗体属性等的部分。这与运行应用程序形成对比。 ## 停靠窗口 附加到主窗口框架的窗口。 ## 文档 使用应用程序创建的任何独立作品,并被赋予唯一文件名。 ## 主导控件 *格式*菜单上*对齐*命令和*统一大小*命令的参照。对齐控件时,所选控件对齐到主导控件。调整控件大小时,所选控件被分配主导控件的尺寸。 ## Double数据类型 将双精度浮点数存储为64位数字的[数据类型](#data-type),负值范围为-1.79769313486231E308至-4.94065645841247E-324,正值范围为4.94065645841247E-324至1.79769313486232E308。数字符号(`#`)[类型声明字符](#type-declaration-character)表示**Double**。 ## 拖放源 在拖放操作中拖动的选定文本或对象。 ## 动态数据交换(DDE) 在Microsoft Windows下运行的应用程序之间通过活动链接交换数据的既定协议。 ## 动态链接库(DLL) 在运行时加载并链接到应用程序的例程库。DLL通常使用其他编程语言(如C)创建。外部DLL过程可通过[**Declare**](/official/Reference/Core/Declare)语句在twinBASIC中调用。 ## Empty 指示尚未为[**Variant**](#variant-data-type)变量赋初始值。**Empty**变量在数值上下文中表示为0,在字符串上下文中表示为零长度字符串(`""`)。 ## 枚举常量 值为使用[**Enum**](/official/Reference/Core/Enum)语句定义的枚举类型成员的命名常量。枚举数据项的附加信息通常可在使用该枚举的属性、方法或事件的描述中找到。 ## 错误号 0到65,535范围内的整数,对应[**Err**](/official/Reference/VBA/Information/Err)对象的`Number`属性设置。与**Err**对象的`Description`属性设置组合时,此数字代表特定的错误消息。 ## 事件源对象 作为响应操作而发生的事件之源的对象。事件源对象通常由属性返回。 ## 可执行文件 可以在开发环境之外运行的基于Windows的应用程序。可执行文件具有`.exe`文件扩展名。 ## 表达式 产生字符串、数字或对象的关键字、运算符、变量和常量的组合。表达式可用于执行计算、操作字符或测试数据。 ## 文件号 在[**Open**](/official/Reference/Core/Open)语句中用于打开文件的数字。使用1–255(含)范围内的文件号来处理其他应用程序不可访问的文件。使用256–511范围内的文件号来处理可从其他应用程序访问的文件。 ## 焦点 在任一时刻接收鼠标点击或键盘输入的能力。在Microsoft Windows环境中,同一时间只有一个窗口、窗体或控件可以具有此能力。"具有焦点"的对象通常通过高亮标题栏或标题来指示。焦点可由用户或应用程序设置。 ## 前景色 当前选定用于在屏幕上绘图或显示文本的颜色。在单色显示器中,前景色是位图或其他图形的颜色。 ## 窗体 窗口或对话框。窗体是[控件](#control)的容器。多文档界面(MDI)窗体还可以作为子窗体和某些控件的容器。 ## 窗体模块 twinBASIC项目中的文件,包含窗体的图形描述及其控件和属性设置、窗体级的常量、变量和外部过程声明,以及事件和通用过程。在twinBASIC源项目中,窗体模块存储为`.twin`文件。 ## Function过程 在程序中执行特定任务并返回值的[过程](#procedure)。**Function**过程以[**Function**](/official/Reference/Core/Function)语句开始,以**End Function**语句结束。 ## 通用过程 必须由另一过程显式调用的[过程](#procedure)。相比之下,事件过程在响应用户或系统操作时自动调用。 ## 图形方法 对**Form**、**PictureBox**或**Printer**等对象进行操作并执行运行时绘图操作(如动画或模拟)的方法。图形方法包括**Circle**、**Cls**、**Line**、**PaintPicture**、**Point**、**Print**和**PSet**。 ## 宿主应用程序 承载twinBASIC项目或组件的任何应用程序,例如加载已编译twinBASIC COM加载项的Office应用程序。 ## 图标 对象或概念的图形表示;通常用于在Microsoft Windows中表示最小化的应用程序。图标是最大尺寸为32 x 32像素的位图。图标具有`.ico`文件扩展名。 ## 标识符 表达式中引用常量、变量、过程或其他命名实体的元素。 ## 进程内 在与应用程序相同的地址空间中运行。 ## 继承属性 通过继承获取另一个类特征的属性。 ## 输入法编辑器(IME) 将键入内容转换为DBCS语言(如日语或中文)字符的应用程序。用户键入时,IME显示可能的等价项,用户选择最合适的条目。 ## 可插入对象 作为一种自定义控件类型的应用程序对象(如Microsoft Excel工作表),可以插入到宿主文档中。 ## Integer数据类型 将整数变量存储为2字节整数的[数据类型](#data-type),范围为-32,768到32,767。**Integer**数据类型也用于表示枚举值。百分号(`%`)[类型声明字符](#type-declaration-character)表示**Integer**。 ## 内在常量 由语言或引用库提供的常量。内在常量可在IDE的对象浏览器中查看。由于内在常量不能被禁用,因此不能创建同名的用户自定义常量。 ## 键盘状态 标识按下了哪些键以及是否按下了SHIFT、CTRL和ALT键盘修饰键的返回值。 ## 关键字 作为twinBASIC编程语言一部分被识别的单词或符号;例如语句、函数名或运算符。 ## 行续行符 源代码中用于将单个逻辑行代码扩展为两个或更多物理行的空格后跟下划线(`_`)的组合。行续行符不能用于在字符串表达式内续行。 ## 行标签 用于标识单行代码的标签。行标签可以是任何以字母开头以冒号(`:`)结尾的字符组合。行标签不区分大小写,必须从第一列开始。 ## 行号 用于标识单行代码的数字。行号可以是在使用它的模块内唯一的任何数字组合。行号必须从第一列开始。 ## 区域设置 与给定语言和国家/地区对应的信息集。代码区域设置影响关键字等术语的语言,并定义区域设置特定的设置,如小数和列表分隔符、日期格式和字符排序顺序。 系统区域设置影响识别区域设置功能的行为方式,例如显示数字或将字符串转换为日期时。使用操作系统提供的**控制面板**实用程序设置系统区域设置。 虽然代码区域设置和系统区域设置通常设置为相同设置,但在某些情况下可能不同。例如,在Visual Basic标准版和Visual Basic专业版中,代码不会从英语(美国)翻译。系统区域设置可以设置为用户的语言和国家/地区,但代码区域设置始终设置为英语(美国)且不能更改。在这种情况下,使用英语(美国)的分隔符、格式占位符和排序顺序。 ## 逻辑错误 可能导致代码产生错误结果或停止执行的编程错误。例如,逻辑错误可能由错误的变量名、错误的变量类型、无限循环、比较缺陷或数组问题引起。 ## Long数据类型 4字节整数,值范围为-2,147,483,648到2,147,483,647。和号(`&`)[类型声明字符](#type-declaration-character)表示**Long**。 ## LongLong数据类型 (twinBASIC) 8字节整数,值范围为-9,223,372,036,854,775,808到9,223,372,036,854,775,807。仅在64位平台上(或针对64位的DLL [**Declare**](/official/Reference/Core/Declare)签名中)可用作声明类型。脱字符(`^`)[类型声明字符](#type-declaration-character)表示**LongLong**。 ## LongPtr数据类型 (twinBASIC) 平台相关的整数,用于保存指针或句柄值。**LongPtr**在32位平台上为4字节,在64位平台上为8字节。声明保存指针或句柄的DLL参数时使用**LongPtr**而非**Long**或**LongLong**,以便同一源代码在两个平台上都能正确编译。 ## MDI子窗体 多文档界面(MDI)应用程序中包含在MDI窗体内的窗体。要创建子窗体,请将窗体的`MDIChild`属性设置为**True**。 ## MDI窗体 构成多文档界面(MDI)应用程序背景的窗口。MDI窗体是应用程序中任何MDI子窗体的容器。 ## 成员 集合、对象或用户自定义类型的元素。 ## 元文件 将图像存储为线条、圆形和多边形等图形对象而非像素的文件。有两种类型的元文件:标准和增强。标准元文件通常具有`.wmf`文件扩展名;增强元文件通常具有`.emf`文件扩展名。元文件在图像调整大小时比像素更准确地保留图像。 ## 方法 对对象进行操作的[过程](#procedure)。 ## 模块 一组声明后跟过程。 ## 模块级别 描述模块声明部分中的代码。过程外的任何代码称为模块级别代码。声明必须列在最前面,后跟过程。此术语也包括[类模块](#class-module)。 ## 模块变量 在[**Function**](/official/Reference/Core/Function)、[**Sub**](/official/Reference/Core/Sub)或[**Property**](/official/Reference/Core/Property)过程代码之外声明的变量。模块变量必须在模块中的任何过程之外声明。它们在模块加载期间存在,并且在模块的所有过程中可见。 ## 命名参数 在对象库中具有预定义名称的参数。命名参数可用于按任意顺序赋值,而不必按语法期望的指定顺序为每个参数提供值。例如,假设一个方法接受三个参数: > **DoSomething** *namedarg1, namedarg2, namedarg3* 通过为命名参数赋值,可以编写: ```vb DoSomething namedarg3 := 4, namedarg2 := 5, namedarg1 := 20 ``` 注意命名参数不必按正常位置顺序出现在语法中。 ## Null 指示变量不包含有效数据的值。**Null**是显式将**Null**赋值给变量或包含**Null**的表达式之间任何操作的结果。 ## 数值数据类型 任何内在数值[数据类型](#data-type)(**Byte**、**Boolean**、**Integer**、**Long**、**LongLong**、**LongPtr**、**Currency**、**Decimal**、**Single**、**Double**或**Date**)。 ## 数值表达式 任何可以计算为数值的[表达式](#expression)。表达式的元素可以包括产生数值的关键字、变量、常量和运算符的任意组合。 ## 对象 可以作为一个单元处理的代码和数据的组合,例如控件、窗体或应用程序组件。每个对象由类定义。 ## 对象浏览器 可以检查对象库内容以获取所提供对象信息的对话框。 ## Object数据类型 表示任何对象引用的[数据类型](#data-type)。**Object**变量存储为引用对象的指针大小地址(32位平台上4字节,64位平台上8字节)。 ## 对象表达式 指定特定对象并可以包含该对象任何容器的表达式。例如,应用程序可以有一个包含**Document**对象的**Application**对象,而**Document**对象又包含一个**Text**对象。 ## 对象库 包含所暴露对象、属性和方法的标准描述的文件。对象库文件通常具有`.olb`或`.tlb`扩展名。使用[对象浏览器](#object-browser)检查对象库内容以获取所提供对象的信息。 ## 对象模块 包含特定于对象的代码的模块,例如类模块或窗体模块。对象模块包含与其关联对象背后的代码。对象模块的规则与[标准模块](#standard-module)的规则不同。 ## 对象类型 应用程序通过自动化暴露的对象类型,例如**Application**、**File**、**Range**或**Sheet**。请参阅应用程序文档以获取可用对象的完整列表。 ## 对象变量 包含对象引用的变量。 ## 包 twinBASIC代码的分发和引用单元。包将模块、类、类型、枚举和其他声明捆绑在一起,可以作为单个依赖项从项目中引用。twinBASIC运行时库以此方式交付:[VBA](/official/Reference/VBA/)包镜像经典VBA的运行时,[VBRUN](/official/Reference/VBRUN/)包提供VB6的运行时对象,[VB](/official/Reference/VB/)包提供标准控件类。开发者可以编写和发布自己的包。 ## 参数 传递给过程的参数在过程内已知的变量名。此变量接收传入过程的参数。其作用域在过程结束时终止。 ## 路径 指定目录或文件夹位置的字符串表达式。位置可以包含驱动器规格。 ## 圆周率 约等于3.1415926535897932的数学常量。 ## 占位符 出于安全原因而遮掩或隐藏另一个字符的字符。例如,当用户输入密码时,屏幕上显示星号以替代每个键入的字符。 ## 磅 1/72英寸。字体大小通常以磅为单位测量。 ## 打印区 打印区每14列开始一个。每列的宽度是所选字体磅号下所有字符宽度的平均值。 ## Private 描述仅在声明它们的模块中可见的变量、过程或类型。参见[**Private**](/official/Reference/Core/Private)语句。 ## 过程 作为单元执行的命名语句序列。例如,[**Function**](/official/Reference/Core/Function)、[**Property**](/official/Reference/Core/Property)和[**Sub**](/official/Reference/Core/Sub)是过程的类型。过程名始终在模块级别定义。所有可执行代码必须包含在过程中。过程不能嵌套在其他过程中。 ## 过程调用 代码中告诉twinBASIC执行过程的语句。参见[**Call**](/official/Reference/Core/Call)。 ## 过程级别 描述位于[**Function**](/official/Reference/Core/Function)、[**Property**](/official/Reference/Core/Property)或[**Sub**](/official/Reference/Core/Sub)过程内的语句。声明通常列在最前面,后跟赋值和其他可执行代码。 注意模块级别代码位于过程块之外。 ## 项目 一组模块。 ## 属性(Property) 对象的命名属性。属性定义对象特征,如大小、颜色和屏幕位置,或对象的状态,如启用或禁用。 ## 属性页 作为属性表选项卡页呈现的属性分组。 ## Property过程 为类模块创建和操作属性的[过程](#procedure)。**Property**过程以[**Property Let**、**Property Get**或**Property Set**](/official/Reference/Core/Property)语句开始,以**End Property**语句结束。 ## Public 描述使用[**Public**](/official/Reference/Core/Public)语句声明的变量,除非[**Option Private Module**](/official/Reference/Core/Option#Private)生效,否则对所有应用程序中所有模块的所有过程可见。在该情况下,变量仅在其所在项目内为公共的。 ## 被引用项目 直接链接到当前项目的项目。由当前项目直接引用的项目所引用的项目称为*间接引用项目*。其**Public**变量不能供当前项目访问,除非通过其项目名称限定。项目之间的直接和间接引用的任何组合都是有效的,只要它们不会形成循环。 ## 引用项目 当前项目。直接被引用项目中的**Public**变量对直接引用项目可见,但直接引用项目中的**Public**变量对直接被引用项目不可见。 ## 注册表 Microsoft Windows中用于用户、应用程序和计算机特定信息的中央配置数据库。 ## 资源文件 twinBASIC项目中可包含位图、文本字符串或其他数据的文件。通过将此数据存储在单独文件中,可以在不编辑代码的情况下更改信息。 ## RGB 用于将颜色描述为红(R)、绿(G)和蓝(B)混合的颜色值系统。颜色定义为一组三个整数(R, G, B),其中每个整数范围为0–255。值0表示颜色分量完全不存在;值255表示颜色分量的最高强度。参见[**RGB**](/official/Reference/VBA/Information/RGB)和[**RGBA**](/official/Reference/VBA/Information/RGBA)。 ## 运行时 代码正在运行的时间。在运行时,不能编辑代码。 ## 运行时错误 代码运行时发生的错误。当语句尝试无效操作时产生运行时错误。 ## 作用域 定义变量、过程或对象的可见性。例如,声明为[**Public**](/official/Reference/Core/Public)的变量对直接引用项目中所有模块的所有过程可见,除非[**Option Private Module**](/official/Reference/Core/Option#Private)生效。**Option Private Module**生效时,模块本身为私有,因此对引用项目不可见。过程中声明的变量仅在该过程内可见,除非声明为[**Static**](/official/Reference/Core/Static),否则在调用之间不保留其值。 ## 种子 用于生成伪随机数的初始值。例如,[**Randomize**](/official/Reference/VBA/Math/Randomize)语句创建一个种子数,由[**Rnd**](/official/Reference/VBA/Math/Rnd)函数用于创建唯一的伪随机数序列。 ## Single数据类型 将单精度浮点变量存储为32位(4字节)浮点数的[数据类型](#data-type),负值范围为-3.402823E38至-1.401298E-45,正值范围为1.401298E-45至3.402823E38。感叹号(`!`)[类型声明字符](#type-declaration-character)表示**Single**。 ## 排序顺序 用于排序数据的排序原则,例如字母顺序、数字顺序、升序、降序等。 ## 栈 twinBASIC用于在过程调用期间保存局部变量和参数的固定内存量。 ## 标准模块 仅包含过程、类型和数据声明及定义的模块。标准模块中的模块级别声明和定义默认为**Public**。标准模块有时称为*代码模块*。 ## 语句 表达一种动作、声明或定义的语法完整单元。语句通常占据一行,但可以使用冒号(`:`)在一行中包含多个语句。也可以使用[行续行符](#line-continuation-character)(`_`)将单个逻辑行续到第二个物理行。 ## 字符串比较 两个字符序列的比较。使用[**Option Compare**](/official/Reference/Core/Option#Compare)指定二进制或文本比较。在英语(美国)中,二进制比较区分大小写;文本比较不区分大小写。 ## 字符串常量 使用[**Const**](/official/Reference/Core/Const)关键字定义的、由被解释为字符本身而非数值的连续字符序列组成的任何常量。 ## String数据类型 由表示字符本身而非其数值的连续字符序列组成的[数据类型](#data-type)。**String**可以包含字母、数字、空格和标点符号。**String**数据类型可存储长度0至约63K字符的定长字符串和长度0至约20亿字符的动态字符串。美元符号(`$`)[类型声明字符](#type-declaration-character)表示**String**。 ## 字符串表达式 计算结果为连续字符序列的任何[表达式](#expression)。字符串表达式的元素可以包括返回字符串的函数、字符串字面量、字符串常量、字符串变量、字符串[**Variant**](#variant-data-type)或返回字符串**Variant**的函数。 ## 字符串字面量 由被包围在引号中并按引号内字符字面解释的连续字符序列组成的任何表达式。 ## Sub过程 在程序中执行特定任务但不返回显式值的[过程](#procedure)。**Sub**过程以[**Sub**](/official/Reference/Core/Sub)语句开始,以**End Sub**语句结束。 ## 语法检查 检查代码语法正确性的功能。启用语法检查功能后,输入包含语法错误的代码时会显示消息,并高亮显示有问题的代码。 ## 语法错误 输入twinBASIC无法识别的代码行时发生的错误。 ## 系统颜色 由操作系统为特定类型显示器和视频适配器定义的颜色。在Windows中,每种颜色与用户界面的特定部分关联,如窗口标题或菜单。 ## Tab顺序 按TAB或SHIFT+TAB时焦点从一个字段移动到下一个字段的顺序。 ## 目标 在拖放操作中用户将拖动对象放到的对象。 ## 时间表达式 任何可以解释为时间的表达式。这包括时间字面量、看起来像时间的数字、看起来像时间的字符串以及从函数返回的时间的任意组合。 时间作为实数的一部分存储。小数点右边的值表示时间。例如,正午(12:00 PM)由0.5表示。 ## 透明 描述对象背景不可见的情况。替代背景,对象后面的一切可见 --- 例如应用程序中用作背景的图像或图片。使用`BackStyle`属性使背景透明。 ## 缇 等于1/20磅的屏幕测量单位。缇是屏幕无关单位,用于确保屏幕应用程序中屏幕元素的位置和比例在所有显示系统上相同。逻辑英寸约等于1440缇,逻辑厘米约等于567缇(打印时测量为一英寸或一厘米的屏幕项的长度)。 ## 类型声明字符 附加到变量名后指示变量数据类型的字符。默认情况下,变量为[**Variant**](#variant-data-type)类型,除非模块中存在相应的[**Def***type*](/official/Reference/Core/Deftype)语句。完整的类型声明字符集为: | 字符 | 类型 | |:----:|:----------------| | `%` | **Integer** | | `&` | **Long** | | `^` | **LongLong** | | `@` | **Currency** | | `!` | **Single** | | `#` | **Double** | | `$` | **String** | ## 类型库 包含可用于自动化的所暴露对象、属性和方法的标准描述的文件或另一文件中的组件。对象库文件(`.olb`、`.tlb`)包含类型库。 ## 非绑定 描述与[数据源](#data-source)无关的控件。相比之下,[绑定控件](#bound-control)提供对数据源的访问以进行显示或编辑。 ## Unicode 国际标准化组织(ISO)字符标准。Unicode使用16位(2字节)编码方案,允许65,536个不同字符空间。Unicode包含标点符号、数学符号和装饰符号的表示,并有充足的未来扩展空间。 ## 通用日期格式 通用日期格式为`#yyyy-mm-dd hh:mm:ss#`。日期部分(`#yyyy-mm-dd#`)和时间部分(`#hh:mm:ss#`)可以分别表示。 ## 用户自定义类型 使用[**Type**](/official/Reference/Core/Type)语句定义的任何数据类型。用户自定义数据类型可以包含一个或多个任何数据类型的元素。使用[**Dim**](/official/Reference/Core/Dim)语句创建用户自定义和其他数据类型的数组。任何类型的数组都可以包含在用户自定义类型中。参见[数据类型](#data-type)。 ## 变量 可以在程序执行期间修改的包含数据的命名存储位置。每个变量都有一个在其作用域内唯一标识它的名称。可以指定或不指定数据类型。 变量名必须以字母字符开头,在同一作用域内必须唯一,长度不能超过255个字符,不能包含嵌入的句点或类型声明字符。 ## Variant数据类型 可以包含数值、字符串或日期数据以及用户自定义类型和特殊值[**Empty**](#empty)和[**Null**](#null)的特殊[数据类型](#data-type)。**Variant**数据类型可以包含直到**Decimal**范围的数据,加上字符文本和字符串所需的平台特定存储。[**VarType**](/official/Reference/VBA/Information/VarType)函数定义**Variant**中数据的处理方式。所有变量如果不显式声明为其他数据类型,则成为**Variant**数据类型。 ## 变体表达式 可以计算为数值、字符串或日期数据,以及特殊值[**Empty**](#empty)和[**Null**](#null)的任何[表达式](#expression)。 ## 监视表达式 使用户能够观察变量或表达式行为的用户自定义表达式。监视表达式出现在开发环境的监视窗口中,在进入[中断模式](#break-mode)时自动更新。监视窗口在给定上下文中显示表达式的值。监视表达式不与代码一起保存。 ## Z顺序 窗体上控件沿窗体Z轴(深度)的视觉分层。Z顺序决定哪些控件在其他控件前面。 --- --- url: /zh/packages/vbccr/views/treeview.md description: 树视图控件(TreeView) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 树视图控件(TreeView) 提供层次化数据的树形展示,支持节点展开/折叠、复选框、多选、图像列表、标签编辑、排序和OLE拖放。 ## 枚举 ### TvwStyleConstants 树视图样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TvwStyleTextOnly | 0 | 仅文本 | | TvwStylePictureText | 1 | 图像和文本 | | TvwStylePlusMinusText | 2 | 加减号和文本 | | TvwStylePlusMinusPictureText | 3 | 加减号、图像和文本 | | TvwStyleTreeLinesText | 4 | 树线和文本 | | TvwStyleTreeLinesPictureText | 5 | 树线、图像和文本 | | TvwStyleTreeLinesPlusMinusText | 6 | 树线、加减号和文本 | | TvwStyleTreeLinesPlusMinusPictureText | 7 | 树线、加减号、图像和文本 | ### TvwLineStyleConstants 线条样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TvwLineStyleTreeLines | 0 | 显示树线 | | TvwLineStyleRootLines | 1 | 显示根线(根节点之间也显示连线) | ### TvwLabelEditConstants 标签编辑模式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TvwLabelEditAutomatic | 0 | 自动标签编辑(单击选中,再次单击编辑) | | TvwLabelEditManual | 1 | 手动标签编辑(需代码调用StartLabelEdit) | | TvwLabelEditDisabled | 2 | 禁用标签编辑 | ### TvwNodeRelationshipConstants 节点关系常量,用于Add方法和Move方法。 | 常量 | 值 | 说明 | |------|-----|------| | TvwNodeFirst | 0 | 第一个节点 | | TvwNodeLast | 1 | 最后一个节点 | | TvwNodeNext | 2 | 下一个节点(同级) | | TvwNodePrevious | 3 | 上一个节点(同级) | | TvwNodeChild | 4 | 子节点 | ### TvwSortOrderConstants 排序顺序常量。 | 常量 | 值 | 说明 | |------|-----|------| | TvwSortAscending | 0 | 升序排列 | | TvwSortDescending | 1 | 降序排列 | ### TvwSortTypeConstants 排序类型常量。 | 常量 | 值 | 说明 | |------|-----|------| | TvwSortBinary | 0 | 二进制排序(区分大小写) | | TvwSortText | 1 | 文本排序(不区分大小写) | ### TvwMultiSelectConstants 多选模式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TvwMultiSelectNone | 0 | 不允许多选 | | TvwMultiSelectAll | 1 | 允许选择所有节点 | | TvwMultiSelectVisibleOnly | 2 | 仅允许选择可见节点 | | TvwMultiSelectRestrictSiblings | 3 | 仅允许选择同级节点 | ### TvwVisualThemeConstants 视觉主题常量。 | 常量 | 值 | 说明 | |------|-----|------| | TvwVisualThemeStandard | 0 | 标准主题 | | TvwVisualThemeExplorer | 1 | 资源管理器主题 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### Container ```vb Public Property Get Container() As Object Public Property Set Container(ByVal Value As Object) ``` 返回/设置对象的容器。 ### Left ```vb Public Property Get Left() As Single Public Property Let Left(ByVal Value As Single) ``` 返回/设置对象与其容器左边缘的距离。 ### Top ```vb Public Property Get Top() As Single Public Property Let Top(ByVal Value As Single) ``` 返回/设置对象与其容器顶边缘的距离。 ### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 返回/设置对象的宽度。 ### Height ```vb Public Property Get Height() As Single Public Property Let Height(ByVal Value As Single) ``` 返回/设置对象的高度。 ### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 返回/设置鼠标悬停时显示的提示文本。 ### HelpContextID ```vb Public Property Get HelpContextID() As Long Public Property Let HelpContextID(ByVal Value As Long) ``` 返回/设置帮助上下文ID。 ### WhatsThisHelpID ```vb Public Property Get WhatsThisHelpID() As Long Public Property Let WhatsThisHelpID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### Align ```vb Public Property Get Align() As Integer Public Property Let Align(ByVal Value As Integer) ``` 返回/设置控件在其窗体上的对齐方式。 ### DragIcon ```vb Public Property Get DragIcon() As IPictureDisp Public Property Let DragIcon(ByVal Value As IPictureDisp) Public Property Set DragIcon(ByVal Value As IPictureDisp) ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Public Property Get DragMode() As Integer Public Property Let DragMode(ByVal Value As Integer) ``` 返回/设置拖动模式。 ### hWnd ```vb Public Property Get hWnd() As LongPtr ``` 返回控件句柄。 ### hWndUserControl ```vb Public Property Get hWndUserControl() As LongPtr ``` 返回UserControl句柄。 ### hWndLabelEdit ```vb Public Property Get hWndLabelEdit() As LongPtr ``` 返回标签编辑框句柄。 ### Font ```vb Public Property Get Font() As StdFont Public Property Let Font(ByVal NewFont As StdFont) Public Property Set Font(ByVal NewFont As StdFont) ``` 返回/设置字体。 ### VisualStyles ```vb Public Property Get VisualStyles() As Boolean Public Property Let VisualStyles(ByVal Value As Boolean) ``` 返回/设置是否启用视觉样式。需要comctl32.dll 6.0或更高版本。 ### VisualTheme ```vb Public Property Get VisualTheme() As TvwVisualThemeConstants Public Property Let VisualTheme(ByVal Value As TvwVisualThemeConstants) ``` 返回/设置视觉主题。 ### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 返回/设置对象是否能响应用户事件。 ### OLEDragMode ```vb Public Property Get OLEDragMode() As VBRUN.OLEDragConstants Public Property Let OLEDragMode(ByVal Value As VBRUN.OLEDragConstants) ``` 返回/设置OLE拖拽模式。 ### OLEDragDropScroll ```vb Public Property Get OLEDragDropScroll() As Boolean Public Property Let OLEDragDropScroll(ByVal Value As Boolean) ``` 返回/设置OLE拖放时是否自动滚动。 ### OLEDragExpandTime ```vb Public Property Get OLEDragExpandTime() As Long Public Property Let OLEDragExpandTime(ByVal Value As Long) ``` 返回/设置OLE拖放时悬停多久后展开节点(毫秒)。 ### OLEDropMode ```vb Public Property Get OLEDropMode() As OLEDropModeConstants Public Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` 返回/设置对象是否可以作为OLE放置目标。 ### MousePointer ```vb Public Property Get MousePointer() As CCMousePointerConstants Public Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 返回/设置鼠标悬停时显示的指针类型。参见通用枚举。 ### MouseIcon ```vb Public Property Get MouseIcon() As IPictureDisp Public Property Let MouseIcon(ByVal Value As IPictureDisp) Public Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Public Property Get MouseTrack() As Boolean Public Property Let MouseTrack(ByVal Value As Boolean) ``` 返回/设置是否在鼠标进入或离开控件时触发事件。 ### RightToLeft ```vb Public Property Get RightToLeft() As Boolean Public Property Let RightToLeft(ByVal Value As Boolean) ``` 返回/设置从右到左显示方向。 ### RightToLeftLayout ```vb Public Property Get RightToLeftLayout() As Boolean Public Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 返回/设置从右到左布局。 ### RightToLeftMode ```vb Public Property Get RightToLeftMode() As CCRightToLeftModeConstants Public Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 返回/设置从右到左模式。参见通用枚举。 ### ImageList ```vb Public Property Get ImageList() As Variant Public Property Let ImageList(ByVal Value As Variant) Public Property Set ImageList(ByVal Value As Variant) ``` 返回/设置关联的ImageList控件。可以是对象引用、字符串键名或LongPtr句柄。 ### BorderStyle ```vb Public Property Get BorderStyle() As CCBorderStyleConstants Public Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` 返回/设置边框样式。参见通用枚举。 ### BackColor ```vb Public Property Get BackColor() As OLE_COLOR Public Property Let BackColor(ByVal Value As OLE_COLOR) ``` 返回/设置背景色。 ### ForeColor ```vb Public Property Get ForeColor() As OLE_COLOR Public Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 返回/设置前景色。 ### Redraw ```vb Public Property Get Redraw() As Boolean Public Property Let Redraw(ByVal Value As Boolean) ``` 返回/设置是否重绘。禁用后可加速大量操作。 ### Style ```vb Public Property Get Style() As TvwStyleConstants Public Property Let Style(ByVal Value As TvwStyleConstants) ``` 返回/设置树视图样式。 ### LineStyle ```vb Public Property Get LineStyle() As TvwLineStyleConstants Public Property Let LineStyle(ByVal Value As TvwLineStyleConstants) ``` 返回/设置线条样式。 ### LineColor ```vb Public Property Get LineColor() As OLE_COLOR Public Property Let LineColor(ByVal Value As OLE_COLOR) ``` 返回/设置线条颜色。 ### LabelEdit ```vb Public Property Get LabelEdit() As TvwLabelEditConstants Public Property Let LabelEdit(ByVal Value As TvwLabelEditConstants) ``` 返回/设置标签编辑模式。 ### Checkboxes ```vb Public Property Get Checkboxes() As Boolean Public Property Let Checkboxes(ByVal Value As Boolean) ``` 返回/设置是否在节点旁显示复选框。 ### ShowTips ```vb Public Property Get ShowTips() As Boolean Public Property Let ShowTips(ByVal Value As Boolean) ``` 返回/设置是否显示工具提示。 ### HideSelection ```vb Public Property Get HideSelection() As Boolean Public Property Let HideSelection(ByVal Value As Boolean) ``` 返回/设置失去焦点时是否隐藏选中项高亮。 ### FullRowSelect ```vb Public Property Get FullRowSelect() As Boolean Public Property Let FullRowSelect(ByVal Value As Boolean) ``` 返回/设置是否整行选择。 ### HotTracking ```vb Public Property Get HotTracking() As Boolean Public Property Let HotTracking(ByVal Value As Boolean) ``` 返回/设置是否启用热点跟踪。 ### Indentation ```vb Public Property Get Indentation() As Single Public Property Let Indentation(ByVal Value As Single) ``` 返回/设置子节点缩进量。 ### PathSeparator ```vb Public Property Get PathSeparator() As String Public Property Let PathSeparator(ByVal Value As String) ``` 返回/设置FullPath属性使用的路径分隔符。 ### Scroll ```vb Public Property Get Scroll() As Boolean Public Property Let Scroll(ByVal Value As Boolean) ``` 返回/设置是否显示滚动条。 ### SingleSel ```vb Public Property Get SingleSel() As Boolean Public Property Let SingleSel(ByVal Value As Boolean) ``` 返回/设置单击节点是否展开并折叠其他节点。 ### Sorted ```vb Public Property Get Sorted() As Boolean Public Property Let Sorted(ByVal Value As Boolean) ``` 返回/设置是否对根节点排序。 ### SortOrder ```vb Public Property Get SortOrder() As TvwSortOrderConstants Public Property Let SortOrder(ByVal Value As TvwSortOrderConstants) ``` 返回/设置排序顺序。 ### SortType ```vb Public Property Get SortType() As TvwSortTypeConstants Public Property Let SortType(ByVal Value As TvwSortTypeConstants) ``` 返回/设置排序类型。 ### InsertMarkColor ```vb Public Property Get InsertMarkColor() As OLE_COLOR Public Property Let InsertMarkColor(ByVal Value As OLE_COLOR) ``` 返回/设置插入标记颜色。 ### DoubleBuffer ```vb Public Property Get DoubleBuffer() As Boolean Public Property Let DoubleBuffer(ByVal Value As Boolean) ``` 返回/设置是否启用双缓冲绘制。 ### IMEMode ```vb Public Property Get IMEMode() As CCIMEModeConstants Public Property Let IMEMode(ByVal Value As CCIMEModeConstants) ``` 返回/设置输入法模式。参见通用枚举。 ### MultiSelect ```vb Public Property Get MultiSelect() As TvwMultiSelectConstants Public Property Let MultiSelect(ByVal Value As TvwMultiSelectConstants) ``` 返回/设置多选模式。 ### Nodes ```vb Public Property Get Nodes() As TvwNodes ``` 返回节点集合。 ## 方法 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动OLE拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移到指定对象。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置Z顺序。 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘对象。 ## 事件 ### Click ```vb Public Event Click() ``` 用户单击控件时触发。 ### DblClick ```vb Public Event DblClick() ``` 用户双击控件时触发。 ### NodeClick ```vb Public Event NodeClick(ByVal Node As TvwNode, ByVal Button As Integer) ``` 用户单击节点时触发。Button指示鼠标按钮。 ### NodeDblClick ```vb Public Event NodeDblClick(ByVal Node As TvwNode, ByVal Button As Integer) ``` 用户双击节点时触发。 ### NodeBeforeCheck ```vb Public Event NodeBeforeCheck(ByVal Node As TvwNode, ByRef Cancel As Boolean) ``` 节点复选框即将改变时触发。设置Cancel为True可取消操作。 ### NodeCheck ```vb Public Event NodeCheck(ByVal Node As TvwNode) ``` 节点复选框状态改变后触发。 ### NodeDrag ```vb Public Event NodeDrag(ByVal Node As TvwNode, ByVal Button As Integer) ``` 用户拖动节点时触发。 ### NodeBeforeSelect ```vb Public Event NodeBeforeSelect(ByVal Node As TvwNode, ByRef Cancel As Boolean) ``` 节点即将被选中时触发。设置Cancel为True可取消选择。 ### NodeSelect ```vb Public Event NodeSelect(ByVal Node As TvwNode) ``` 节点被选中后触发。 ### NodeRangeSelect ```vb Public Event NodeRangeSelect(ByVal Node As TvwNode, ByRef Cancel As Boolean) ``` 范围选择时触发。设置Cancel为True可取消。 ### BeforeCollapse ```vb Public Event BeforeCollapse(ByVal Node As TvwNode, ByRef Cancel As Boolean) ``` 节点即将折叠时触发。设置Cancel为True可取消折叠。 ### Collapse ```vb Public Event Collapse(ByVal Node As TvwNode) ``` 节点折叠后触发。 ### BeforeExpand ```vb Public Event BeforeExpand(ByVal Node As TvwNode, ByRef Cancel As Boolean) ``` 节点即将展开时触发。设置Cancel为True可取消展开。 ### Expand ```vb Public Event Expand(ByVal Node As TvwNode) ``` 节点展开后触发。 ### BeforeLabelEdit ```vb Public Event BeforeLabelEdit(ByRef Cancel As Boolean) ``` 标签即将编辑时触发。设置Cancel为True可取消编辑。 ### AfterLabelEdit ```vb Public Event AfterLabelEdit(ByRef Cancel As Boolean, ByRef NewString As String) ``` 标签编辑完成后触发。设置Cancel为True可取消修改,NewString为编辑后的文本。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键预览事件。设置IsInputKey为True可将按键标记为输入键。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键释放预览事件。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下键盘键时触发。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放键盘键时触发。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按下并释放ANSI键时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件区域时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件区域时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE拖放操作完成时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE拖放操作放置时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE拖放操作悬停时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE拖放操作给反馈时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE拖放操作设置数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE拖放操作开始时触发。 ## 子对象 ### TvwNode 类 树视图节点对象。 #### TvwNode 属性 ##### Index ```vb Public Property Get Index() As Long ``` 节点在集合中的索引。 ##### Key ```vb Public Property Get Key() As String Public Property Let Key(ByVal Value As String) ``` 唯一标识键。 ##### Tag ```vb Public Property Get Tag() As Variant Public Property Let Tag(ByVal Value As Variant) ``` 额外数据。 ##### Handle ```vb Public Property Get Handle() As LongPtr ``` 节点句柄。 ##### Text ```vb Public Property Get Text() As String Public Property Let Text(ByVal Value As String) ``` 节点文本。 ##### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ##### BackColor ```vb Public Property Get BackColor() As OLE_COLOR Public Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景色。 ##### ForeColor ```vb Public Property Get ForeColor() As OLE_COLOR Public Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 ##### Image ```vb Public Property Get Image() As Variant Public Property Let Image(ByVal Value As Variant) ``` 节点图像。 ##### ImageIndex ```vb Public Property Get ImageIndex() As Long ``` 图像索引。 ##### SelectedImage ```vb Public Property Get SelectedImage() As Variant Public Property Let SelectedImage(ByVal Value As Variant) ``` 选中状态的图像。 ##### SelectedImageIndex ```vb Public Property Get SelectedImageIndex() As Long ``` 选中图像索引。 ##### ExpandedImage ```vb Public Property Get ExpandedImage() As Variant Public Property Let ExpandedImage(ByVal Value As Variant) ``` 展开状态的图像。 ##### ExpandedImageIndex ```vb Public Property Get ExpandedImageIndex() As Long ``` 展开图像索引。 ##### NoImages ```vb Public Property Get NoImages() As Boolean Public Property Let NoImages(ByVal Value As Boolean) ``` 是否不显示图像。 ##### Selected ```vb Public Property Get Selected() As Boolean Public Property Let Selected(ByVal Value As Boolean) ``` 是否选中。 ##### CheckBox ```vb Public Property Get CheckBox() As Boolean Public Property Let CheckBox(ByVal Value As Boolean) ``` 是否显示复选框。 ##### Checked ```vb Public Property Get Checked() As Boolean Public Property Let Checked(ByVal Value As Boolean) ``` 是否勾选。 ##### Bold ```vb Public Property Get Bold() As Boolean Public Property Let Bold(ByVal Value As Boolean) ``` 是否粗体。 ##### Ghosted ```vb Public Property Get Ghosted() As Boolean Public Property Let Ghosted(ByVal Value As Boolean) ``` 是否灰显。 ##### Expanded ```vb Public Property Get Expanded() As Boolean Public Property Let Expanded(ByVal Value As Boolean) ``` 是否展开。 ##### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ##### Sorted ```vb Public Property Get Sorted() As Boolean Public Property Let Sorted(ByVal Value As Boolean) ``` 是否对子节点排序。 ##### SortOrder ```vb Public Property Get SortOrder() As TvwSortOrderConstants Public Property Let SortOrder(ByVal Value As TvwSortOrderConstants) ``` 排序顺序。 ##### SortType ```vb Public Property Get SortType() As TvwSortTypeConstants Public Property Let SortType(ByVal Value As TvwSortTypeConstants) ``` 排序类型。 ##### Children ```vb Public Property Get Children() As Long ``` 子节点数量。 ##### Child ```vb Public Property Get Child() As TvwNode ``` 第一个子节点。 ##### Level ```vb Public Property Get Level() As Long ``` 节点层级(根节点为0)。 ##### Parent ```vb Public Property Get Parent() As TvwNode Public Property Set Parent(ByVal Value As TvwNode) ``` 父节点。 ##### Root ```vb Public Property Get Root() As TvwNode ``` 根节点。 ##### NextSibling ```vb Public Property Get NextSibling() As TvwNode ``` 下一个兄弟节点。 ##### PreviousSibling ```vb Public Property Get PreviousSibling() As TvwNode ``` 上一个兄弟节点。 ##### FirstSibling ```vb Public Property Get FirstSibling() As TvwNode ``` 第一个兄弟节点。 ##### LastSibling ```vb Public Property Get LastSibling() As TvwNode ``` 最后一个兄弟节点。 ##### FirstVisibleSibling ```vb Public Property Get FirstVisibleSibling() As TvwNode ``` 第一个可见兄弟节点。 ##### LastVisibleSibling ```vb Public Property Get LastVisibleSibling() As TvwNode ``` 最后一个可见兄弟节点。 ##### NextVisibleSibling ```vb Public Property Get NextVisibleSibling() As TvwNode ``` 下一个可见兄弟节点。 ##### PreviousVisibleSibling ```vb Public Property Get PreviousVisibleSibling() As TvwNode ``` 上一个可见兄弟节点。 ##### FullPath ```vb Public Property Get FullPath() As String ``` 从根到当前节点的完整路径。 ##### Visible ```vb Public Property Get Visible() As Boolean ``` 节点是否可见。 #### TvwNode 方法 ##### Move ```vb Public Sub Move(ByVal Relative As Variant, ByVal Relationship As TvwNodeRelationshipConstants) ``` 移动节点到新位置。 ##### EnsureVisible ```vb Public Sub EnsureVisible() ``` 确保节点可见(展开父节点并滚动到视图中)。 ##### CreateDragImage ```vb Public Function CreateDragImage() As LongPtr ``` 创建节点拖动图像,返回图像列表句柄。 ##### SelectedIndex ```vb Public Function SelectedIndex() As Long ``` 返回选中项索引。 ### TvwNodes 类 树视图节点集合。 #### TvwNodes 成员 ##### NewEnum ```vb Public Function NewEnum() As IUnknown ``` 枚举器(隐藏)。 ##### Add ```vb Public Function Add(Optional ByVal Relative As Variant, Optional ByVal Relationship As Variant, Optional ByVal Key As Variant, Optional ByVal Text As Variant, Optional ByVal Image As Variant, Optional ByVal SelectedImage As Variant) As TvwNode ``` 添加节点。 ##### Item ```vb Public Function Item(ByVal Index As Variant) As TvwNode ``` 获取节点(默认成员)。 ##### Exists ```vb Public Function Exists(ByVal Index As Variant) As Boolean ``` 检查节点是否存在。 ##### Count ```vb Public Property Get Count() As Long ``` 节点数量。 ##### Clear ```vb Public Sub Clear() ``` 清除所有节点。 ##### Remove ```vb Public Sub Remove(ByVal Index As Variant) ``` 移除节点。 ### TvwSelectedNodes 类 选中节点集合(多选模式)。 #### TvwSelectedNodes 成员 ##### NewEnum ```vb Public Function NewEnum() As IUnknown ``` 枚举器(隐藏)。 ##### Item ```vb Public Function Item(ByVal Index As Long) As TvwNode ``` 获取选中节点(默认成员)。 ##### Exists ```vb Public Function Exists(ByVal Index As Long) As Boolean ``` 检查选中节点是否存在。 ##### Count ```vb Public Property Get Count() As Long ``` 选中节点数量。 ## 代码示例 ### 基本用法 ```vb ' 添加树节点 Dim root As TvwNode Set root = TreeView1.Nodes.Add(, , "root", "根节点", 1) root.Expanded = True TreeView1.Nodes.Add "root", TvwNodeChild, "child1", "子节点1", 2 TreeView1.Nodes.Add "root", TvwNodeChild, "child2", "子节点2", 2 ' 处理节点点击 Private Sub TreeView1_NodeClick(ByVal Node As TvwNode, ByVal Button As Integer) MsgBox "点击: " & Node.Text End Sub ' 控制节点展开 Private Sub TreeView1_BeforeExpand(ByVal Node As TvwNode, ByRef Cancel As Boolean) If Node.Children = 0 Then Cancel = True End If End Sub ' 节点选中变化 Private Sub TreeView1_NodeSelect(ByVal Node As TvwNode) Debug.Print "选中: " & Node.FullPath End Sub ``` --- --- url: /zh/official/Features/Language/Data-Types.md --- # 新数据类型 twinBASIC 引入了多种新数据类型来增强编程能力。 ## LongPtr 主要用于处理指针,`LongPtr` 在 32 位模式下是 4 字节(32 位)有符号整数,在 64 位模式下是有符号的 8 字节(64 位)整数。 ## LongLong 有符号 8 字节(64 位)整数,范围从 -9,223,372,036,854,775,808 到 9,223,372,036,854,775,807。注意此类型在 32 位和 64 位模式下都可用(VBA 将其限制为 64 位模式)。 ## Decimal 在 twinBASIC 中,`Decimal` 作为完整的常规数据类型实现,除了在 `Variant` 中使用外也可以独立使用。这是一个 16 字节(128 位)类型,包含一个 12 字节(96 位)整数和可变的小数点缩放及符号位信息。值范围从 -79,228,162,514,264,337,593,543,950,335 到 79,228,162,514,264,337,593,543,950,335。 ## 类型支持 所有数据类型管理功能也适用于这些类型: * `DefDec`/`DefLngLng`/`DefLongPtr` - 默认类型声明 * `CDec`/`CLngLng`/`CLongPtr` - 类型转换函数 * `vbDecimal`/`vbLongLong`/`vbLongPtr` - 类型检查常量 --- --- url: /zh/official/Reference/Data-Types.md --- # 数据类型 twinBASIC支持十四种内置数据类型。它们分为四大类别:数值型(整数和浮点)、文本、日期/时间和引用/泛型。本页是存储大小、取值范围和类型声明后缀的权威参考。 关于twinBASIC对此集合的新增类型 --- **LongLong**、**LongPtr**和作为独立类型的**Decimal** --- 参见[功能 → 新数据类型](/official/Features/Language/Data-Types)。 *** ## 快速参考 | 类型 | 后缀 | 存储 | 范围 | |------|--------|---------|-------| | **Boolean** | (无) | 2字节 | `True`或`False` | | **Byte** | (无) | 1字节 | 0到255 | | **Integer** | `%` | 2字节 | -32,768到32,767 | | **Long** | `&` | 4字节 | -2,147,483,648到2,147,483,647 | | **LongLong** | `^` | 8字节 | -9,223,372,036,854,775,808到9,223,372,036,854,775,807 | | **LongPtr** | (无) | 4字节(32位)/8字节(64位) | 取决于目标,与**Long**或**LongLong**相同 | | **Single** | `!` | 4字节 | ±1.401298E-45到±3.402823E38 | | **Double** | `#` | 8字节 | ±4.94065645841246E-324到±1.79769313486232E308 | | **Currency** | `@` | 8字节 | -922,337,203,685,477.5808到922,337,203,685,477.5807 | | **Decimal** | (无) | 16字节 | ±79,228,162,514,264,337,593,543,950,335(最多28位小数) | | **Date** | (无) | 8字节 | 100年1月1日到9999年12月31日 | | **String** | `$` | 可变 | 最多约20亿个字符 | | **Variant** | (无) | 16字节(+ 堆数据) | 以上任意类型 | | **Object** | (无) | 4字节(32位)/8字节(64位) | COM接口引用 | 后缀列出了可选择性附加在字面量或标识符后以强制其类型的字符 --- 例如,`42&`是**Long**字面量,`3.14#`是**Double**,`Total!`在类型隐式上下文中声明**Single**变量。 *** ## 整数类型 **Boolean**存储`True`(-1)或`False`(0)。当期望**Boolean**时,运行时将任何非零值视为`True`;只有-1是规范的`True`。将任何非零整数赋值给**Boolean**会将其规范化为-1。 **Byte**是唯一的无符号整数类型。它保存0--255的值,使其成为二进制I/O和缓冲区操作中使用的字节数组的天然元素类型。 **Integer**保存小范围有符号整数。在大多数代码中,**Long**是更好的选择:它在32位硬件上并不更慢,且在值超过32,767时绝不会溢出。**Integer**在与声明16位字段的结构或API交互时有用。 **Long**是最常用的整数类型。它覆盖了Win32 `DWORD`和`int`值的完整范围,是索引变量和计数器的默认类型。 **LongLong**是在32位和64位构建中都可用8字节有符号整数。在VBA中它仅限于64位目标;twinBASIC解除了此限制,允许在32位项目中使用**LongLong**。当值可能超过2,147,483,647时使用它 --- 文件大小、滴答计数、GUID和64位Win32句柄。后缀`^`标记**LongLong**字面量:`9_000_000_000^`。 **LongPtr**根据编译目标改变宽度:32位构建4字节,64位构建8字节。它是Win32句柄、窗口句柄(**HWND**)和必须在两种模式下工作的`Declare`语句中指针的正确类型。它没有字面量后缀 --- 使用`Dim x As LongPtr`声明变量并赋值数值表达式。 整数溢出默认引发运行时错误(错误6)。溢出不会静默回绕。 *** ## 浮点类型 **Single**和**Double**分别遵循IEEE 754单精度和双精度浮点标准。两者都可以将`NaN`和`Infinity`表示为位模式,但VBA运行时在大多数会产生它们的操作上引发错误。 **Double**是包含小数点的无类型数字字面量的默认类型(`3.14`是**Double**)。精度约为15--16位有效十进制数字。选择它用于通用浮点运算。 **Single**精度约为6--7位有效十进制数字。它更小,在紧凑循环中可能更快,但精度降低使其不适合舍入误差敏感的金融或科学计算。 **Currency**是定点类型,内部存储为按10,000缩放的64位有符号整数。它避免了IEEE 754类型的二进制舍入误差,恰好携带四位小数。用于货币值和任何需要精确十进制舍入的计算。 *** ## Decimal **Decimal**是16字节类型,使用12字节(96位)整数加上可变小数点位置和符号位。它提供最多29位有效数字和最多28位小数,是可用精度最高的数值类型。 ::: info 在twinBASIC中,**Decimal**既可作为**Variant**子类型使用(如VBA中),也可作为独立声明类型使用 --- `Dim x As Decimal`可编译运行。转换函数[**CDec**](/official/Reference/VBA/Conversion/CDec)返回**Decimal**值。 ::: *** ## Date **Date**存储为IEEE 754双精度浮点数:整数部分计算从纪元(1899年12月30日)开始的天数,小数部分表示一天中的时间(午夜为0.0,正午为0.5)。可表示范围为100年1月1日到9999年12月31日。 [**Date**](/official/Reference/Core/Date)和[**Time**](/official/Reference/Core/Time)属性返回当前日期和时间。[**Now**](/official/Reference/VBA/DateTime/Now)返回两者组合。由于**Date**本质上是**Double**,**Date**值上的算术运算有效:加1前进一天,两个日期相减得到它们之间的天数。 *** ## String **String**保存Unicode字符序列,内部存储为COM `BSTR`(长度前缀宽字符字符串)。长度以字符为单位测量,而非字节;每个字符2字节宽(UTF-16 LE)。**String**最多可保存约20亿个字符,实际受可用内存限制。 **String**变量初始化为`vbNullString`(空`BSTR`指针),这与零长度字符串(`""`)不同。大多数字符串操作将两者视为空字符串,但在传递字符串给区分空指针和空缓冲区的API时,这个区别很重要。参见[**StrPtr**](/official/Reference/VBA/Information/StrPtr)获取底层缓冲区的地址。 定长字符串 --- `Dim s As String * 20` --- 恰好占用指定数量的字符,赋值时右侧补空格或截断。适用于固定宽度的二进制文件记录。 *** ## Variant **Variant**是标记联合,可以保存上表中的任何类型,加上`Null`、`Empty`和数组。其16字节头部存储类型标签([**VbVarType**](/official/Reference/VBA/Constants/VbVarType)),后跟类型特定数据。当值为**String**、**Object**或数组时,8字节数据槽保存指向堆分配存储的指针。 `Empty`是未初始化**Variant**的默认状态 --- 它与`0`、`""`、`False`和`Null`不同。使用[**IsEmpty**](/official/Reference/VBA/Information/IsEmpty)检测。`Null`会在算术和比较中传播;使用[**IsNull**](/official/Reference/VBA/Information/IsNull)检测。 **Variant**是后期绑定COM调用中参数和返回值的必需类型,也是运行时返回类型变化的任何函数的必需类型。与有类型变量相比,每次操作都有少量开销,因为运行时必须检查标签。在设计时类型已知的情况下,优先使用有类型变量。 *** ## Object **Object**保存COM接口引用 --- 指向vtable的指针。在32位构建中占用4字节;64位构建中8字节。运行时在赋值时调用`AddRef`,在变量超出作用域或设置为`Nothing`时调用`Release`。 `Nothing`是零值的**Object**引用。使用`If obj Is Nothing Then`检测。 **Object**变量可以保存任何兼容COM的对象;运行时通过`IDispatch`(后期绑定)解析成员调用。使用特定类或接口类型声明变量 --- `Dim fs As FileSystemObject` --- 可启用早期绑定,速度更快并产生编译时类型检查。 *** ### 另见 * [新数据类型](/official/Features/Language/Data-Types) -- **LongLong**、**LongPtr**和**Decimal**详解 * [枚举](/official/Reference/Enumerations) -- 所有包中全部枚举类型的索引 * [VbVarType](/official/Reference/VBA/Constants/VbVarType) -- **Variant**子类型标签常量 * [CDec](/official/Reference/VBA/Conversion/CDec)、[CLngLng](/official/Reference/VBA/Conversion/CLngLng)、[CLngPtr](/official/Reference/VBA/Conversion/CLngPtr) -- 三个扩展数值类型的转换函数 --- --- url: /zh/packages/vbccr/text/spinbox.md description: 数值调节控件(SpinBox) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 数值调节控件(SpinBox) 提供带编辑框的数值调节控件,支持十六进制显示、千位分隔符、加速递增和OLE拖放。 ## 枚举 ### SpbNumberStyleConstants 数字显示样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | SpbNumberStyleDecimal | 0 | 十进制 | | SpbNumberStyleHexadecimal | 1 | 十六进制 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### Container ```vb Public Property Get Container() As Object Public Property Set Container(ByVal Value As Object) ``` 返回/设置对象的容器。 ### Left ```vb Public Property Get Left() As Single Public Property Let Left(ByVal Value As Single) ``` 返回/设置对象与其容器左边缘的距离。 ### Top ```vb Public Property Get Top() As Single Public Property Let Top(ByVal Value As Single) ``` 返回/设置对象与其容器顶边缘的距离。 ### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 返回/设置对象的宽度。 ### Height ```vb Public Property Get Height() As Single Public Property Let Height(ByVal Value As Single) ``` 返回/设置对象的高度。 ### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 返回/设置鼠标悬停时显示的提示文本。 ### HelpContextID ```vb Public Property Get HelpContextID() As Long Public Property Let HelpContextID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### WhatsThisHelpID ```vb Public Property Get WhatsThisHelpID() As Long Public Property Let WhatsThisHelpID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### DragIcon ```vb Public Property Get DragIcon() As IPictureDisp Public Property Let DragIcon(ByVal Value As IPictureDisp) Public Property Set DragIcon(ByVal Value As IPictureDisp) ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Public Property Get DragMode() As Integer Public Property Let DragMode(ByVal Value As Integer) ``` 返回/设置拖动模式。 ### hWnd ```vb Public Property Get hWnd() As LongPtr ``` 返回控件句柄。 ### hWndUserControl ```vb Public Property Get hWndUserControl() As LongPtr ``` 返回UserControl句柄。 ### hWndEdit ```vb Public Property Get hWndEdit() As LongPtr ``` 返回内嵌编辑框句柄。 ### Font ```vb Public Property Get Font() As StdFont Public Property Let Font(ByVal NewFont As StdFont) Public Property Set Font(ByVal NewFont As StdFont) ``` 返回/设置字体。 ### VisualStyles ```vb Public Property Get VisualStyles() As Boolean Public Property Let VisualStyles(ByVal Value As Boolean) ``` 返回/设置是否启用视觉样式。需要comctl32.dll 6.0或更高版本。 ### BackColor ```vb Public Property Get BackColor() As OLE_COLOR Public Property Let BackColor(ByVal Value As OLE_COLOR) ``` 返回/设置背景色。 ### ForeColor ```vb Public Property Get ForeColor() As OLE_COLOR Public Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 返回/设置前景色。 ### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 返回/设置对象是否能响应用户事件。 ### OLEDropMode ```vb Public Property Get OLEDropMode() As OLEDropModeConstants Public Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` 返回/设置对象是否可以作为OLE放置目标。 ### MousePointer ```vb Public Property Get MousePointer() As CCMousePointerConstants Public Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 返回/设置鼠标悬停时显示的指针类型。参见通用枚举。 ### MouseIcon ```vb Public Property Get MouseIcon() As IPictureDisp Public Property Let MouseIcon(ByVal Value As IPictureDisp) Public Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Public Property Get MouseTrack() As Boolean Public Property Let MouseTrack(ByVal Value As Boolean) ``` 返回/设置是否在鼠标进入或离开控件时触发事件。 ### RightToLeft ```vb Public Property Get RightToLeft() As Boolean Public Property Let RightToLeft(ByVal Value As Boolean) ``` 返回/设置从右到左显示方向。 ### RightToLeftMode ```vb Public Property Get RightToLeftMode() As CCRightToLeftModeConstants Public Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 返回/设置从右到左模式。参见通用枚举。 ### Min ```vb Public Property Get Min() As Long Public Property Let Min(ByVal Value As Long) ``` 返回/设置最小值。 ### Max ```vb Public Property Get Max() As Long Public Property Let Max(ByVal Value As Long) ``` 返回/设置最大值。 ### Value ```vb Public Property Get Value() As Long Public Property Let Value(ByVal NewValue As Long) ``` 返回/设置当前值。 ### Increment ```vb Public Property Get Increment() As Long Public Property Let Increment(ByVal Value As Long) ``` 返回/设置每次点击的递增/递减量。 ### Wrap ```vb Public Property Get Wrap() As Boolean Public Property Let Wrap(ByVal Value As Boolean) ``` 返回/设置值是否循环。当为True时,超过最大值回到最小值,反之亦然。 ### HotTracking ```vb Public Property Get HotTracking() As Boolean Public Property Let HotTracking(ByVal Value As Boolean) ``` 返回/设置是否启用热点跟踪。 ### Alignment ```vb Public Property Get Alignment() As CCLeftRightAlignmentConstants Public Property Let Alignment(ByVal Value As CCLeftRightAlignmentConstants) ``` 返回/设置上下按钮的对齐方式。参见通用枚举。 ### ThousandsSeparator ```vb Public Property Get ThousandsSeparator() As Boolean Public Property Let ThousandsSeparator(ByVal Value As Boolean) ``` 返回/设置是否显示千位分隔符。 ### NumberStyle ```vb Public Property Get NumberStyle() As SpbNumberStyleConstants Public Property Let NumberStyle(ByVal Value As SpbNumberStyleConstants) ``` 返回/设置数字显示样式。 ### ArrowKeysChange ```vb Public Property Get ArrowKeysChange() As Boolean Public Property Let ArrowKeysChange(ByVal Value As Boolean) ``` 返回/设置是否允许方向键改变值。 ### AllowOnlyNumbers ```vb Public Property Get AllowOnlyNumbers() As Boolean Public Property Let AllowOnlyNumbers(ByVal Value As Boolean) ``` 返回/设置是否只允许输入数字。 ### TextAlignment ```vb Public Property Get TextAlignment() As VBRUN.AlignmentConstants Public Property Let TextAlignment(ByVal Value As VBRUN.AlignmentConstants) ``` 返回/设置文本对齐方式。 ### Locked ```vb Public Property Get Locked() As Boolean Public Property Let Locked(ByVal Value As Boolean) ``` 返回/设置是否锁定编辑框内容不可编辑。 ### HideSelection ```vb Public Property Get HideSelection() As Boolean Public Property Let HideSelection(ByVal Value As Boolean) ``` 返回/设置控件失去焦点时是否隐藏选定内容。 ### Text ```vb Public Property Get Text() As String Public Property Let Text(ByVal Value As String) ``` 返回/设置编辑框中的文本。 ### SelStart ```vb Public Property Get SelStart() As Long Public Property Let SelStart(ByVal Value As Long) ``` 返回/设置选定文本的起始位置。 ### SelLength ```vb Public Property Get SelLength() As Long Public Property Let SelLength(ByVal Value As Long) ``` 返回/设置选定文本的长度。 ### SelText ```vb Public Property Get SelText() As String Public Property Let SelText(ByVal Value As String) ``` 返回/设置选定文本。 ## 方法 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘对象。 ### SetAcceleration ```vb Public Sub SetAcceleration(ByVal Delays As Variant, ByVal Increments As Variant) ``` 设置加速递增参数。Delays和Increments为数组,指定延迟时间和递增量。 ### ValidateText ```vb Public Sub ValidateText() ``` 验证编辑框中的文本是否为有效数值。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动OLE拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移至控件。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置Z顺序。 ## 事件 ### DownClick ```vb Public Event DownClick() ``` 点击向下按钮时触发。 ### UpClick ```vb Public Event UpClick() ``` 点击向上按钮时触发。 ### BeforeChange ```vb Public Event BeforeChange(ByVal Value As Long, ByRef Delta As Long) ``` 值即将改变时触发。Value为当前值,Delta为预期变化量,可修改Delta控制实际变化。 ### Change ```vb Public Event Change() ``` 值改变后触发。 ### TextChange ```vb Public Event TextChange() ``` 编辑框文本改变后触发。 ### ContextMenu ```vb Public Event ContextMenu(ByRef Handled As Boolean, ByVal X As Single, ByVal Y As Single) ``` 右键点击控件时触发。Handled为True时阻止默认上下文菜单。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键前预览。IsInputKey为True表示该键为输入键。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键释放前预览。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下键盘键时触发。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放键盘键时触发。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按下并释放ANSI键时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件区域时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件区域时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE拖放操作完成时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE拖放操作放置时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE拖放操作悬停时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE拖放操作给反馈时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE拖放操作设置数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE拖放操作开始时触发。 ## 代码示例 ### 基本用法 ```vb ' 设置SpinBox控件 With SpinBox1 .Min = 0 .Max = 1000 .Value = 100 .Increment = 10 .Wrap = True .HotTracking = True .ThousandsSeparator = True End With ' 设置加速递增 Dim Delays(0 To 2) As Long, Increments(0 To 2) As Long Delays(0) = 500: Increments(0) = 10 Delays(1) = 300: Increments(1) = 50 Delays(2) = 100: Increments(2) = 100 SpinBox1.SetAcceleration Delays, Increments ' 限制值变化范围 Private Sub SpinBox1_BeforeChange(ByVal Value As Long, ByRef Delta As Long) If Value + Delta > 1000 Then Delta = 1000 - Value End Sub ``` --- --- url: /zh/official/Tutorials/Arrays.md --- # 数组 数组分为两种: 1. 固定大小数组,其大小规格为编译时常量。 `Dim MyInts(10) As Integer` `Dim MyLongs(10 To 19) As Long` 2. 动态数组,初始时不进行初始化,使用前必须(重新)定义维度。 `Dim MyLongs() As Long` 固定大小数组的内存和运行时开销低于动态数组。作为小型数组——不超过8个缓存行的大小,即不超过512字节——它们的性能更好。 在更大的数组中,创建(定义维度)时动态数组的开销变得可以忽略不计。然而,无论动态数组的大小如何,元素访问仍有轻微的运行时开销。 ## 数组声明语法 固定大小数组只能用于变量或类和UDT的字段。 动态数组可用于变量、字段、参数类型和返回类型。 固定大小数组可以作为接受动态数组的参数传递。 ::: info 固定大小数组不能直接作为返回类型使用。当包装在UDT中时可以返回。 ::: * 过程中变量声明的语法 **Dim** | **Static** name **()** \[ **As** type ] -- 动态数组 **Dim** | **Static** name **(** size \[ **,** size ... ] **)** \[ **As** type ] -- 固定数组 * 过程参数类型的语法;仅动态数组有效,以下两种语法等价 name **()** \[ **As** type ]\ name **As** type **()** * 过程返回类型的语法;仅动态数组有效 name **As** type **()** * 类中字段声明的语法 **Dim** | **Private** | **Protected** | **Public** name **()** \[ **As** type ] -- 动态数组 **Dim** | **Private** | **Protected** | **Public** name **(** size \[ **,** size ....] **)** \[ **As** type ] -- 静态数组 * 类型(UDT)中字段声明的语法 name **()** \[ **As** type ] -- 动态数组 name **(** size \[ **,** size ....] **)** \[ **As** type ] -- 静态数组 每个大小规格是一个范围,但下界是可选的,默认为当前有效的**Option Base**: * ubound,例如 `Dim A(10, 20)` * lbound **To** ubound -- 范围,包含两个边界,例如 `Dim A(1 To 10, 1 To 20)` 两种大小规格变体可以在一个声明中混合使用,例如 `Dim B(10, 1 To 20)` 以下是**Option Base**如何控制维度默认下界的方式: ```vb Option Base 0 Dim A(10, 20) ' is equivalent to... Dim A(0 To 10, 0 To 20) ' i.e. a 21 x 11 array Option Base 1 Dim A(10, 20) ' is equivalent to... Dim A(1 To 10, 1 To 20) ' i.e. a 20 x 10 array ``` 只有动态数组可以作为过程参数传递: ```vb Sub OkSub1(data() As Byte) ' Dynamic array parameter Sub OkSub2(data As Byte()) ' Alternate syntax Sub BadSub1(data(10) As Byte) ' Invalid, fixed array types are not allowed as parameters... Sub BadSub2(data As Byte(10)) ' ... in neither syntax ``` ## 定义动态数组维度 动态数组在声明后处于未初始化状态。除了定义维度外,不能以任何方式使用。维度定义通过**ReDim**语句执行: ```vb Dim array() Debug.Assert IsArrayInitialized(array) = False Debug.Print LBound(array) ' raises a runtime error since the array is uninitialized, ' and no operations are valid on it other than a ReDim ReDim array(1 to 10) ' now the array is initialized Debug.Assert IsArrayInitialized(array) = True Debug.Assert LBound(array) = 1 Debug.Assert UBound(array) = 10 ``` **ReDim**有两种操作模式:默认情况下,它丢弃数组中的现有数据。可选地,它可以在新维度允许的范围内保留现有数据。 语法: * **ReDim** \[ **Preserve** ] name **(** size \[ **,** size ...] **)** ::: warning 使用**ReDim Preserve**只能更改数组维度的上界。 非保留的**ReDim**允许任意更改。 ::: ```vb Dim a() As Long ReDim a(1 To 2) ' Initial dimensioning a(1) = 10 a(2) = 20 ReDim Preserve a(1 To 3) ' Change of an upper bound of 1st dimension Debug.Assert a(1) = 10 Debug.Assert a(2) = 20 Debug.Assert a(3) = 0 ReDim Preserve a(2 To 3) ' Causes a runtime error ReDim a(5 To 8) ' Change of both bounds of 1st dimension while losing data Debug.Assert a(5) = 0 ``` ## 确定数组维度边界 *已初始化*数组的每个维度都有关联的下界和上界。这些边界通过**LBound**和**UBound**函数访问。 ```vb Dim array(1 To 10, 3 To 20) Debug.Assert LBound(array) = 1 ' 1st dimension by default Debug.Assert LBound(array, 1) = 1 ' 1st dimension Debug.Assert LBound(array, 2) = 3 ' 2nd dimension Debug.Assert UBound(array, 2) = 20 ' 2nd dimension, upper bound' ``` ## 确定数组大小 对未初始化的数组使用**LBound**或**UBound**会导致运行时错误。因此,确定数组给定维度中元素数量的函数必须首先检查数组是否已初始化: ```vb Sub ArrayLen(Of T)(array() Of T, ByVal dimension% = 1) As Long ' zero is the default return value If IsArrayInitialized(array) Then Return 1 + UBound(array, dimension) - LBound(array, dimension) End If End Sub ``` 另见[一维数组的高效低级访问](#一维数组的高效低级访问)。 ## 数组元素访问 要访问数组元素,应在数组变量名后以括号列表形式提供所有维度的索引: ```vb Dim array(1 To 10) As Long array(1) = 42 Debug.Assert array(1) = 42 Dim array2(1 To 10, 1 To 2) As Long array(1, 2) = 42 Debug.Assert array(1, 2) = 42 ``` 数组元素初始化为零/null,与twinBASIC中所有其他类型一样: ```vb Dim intArray(1 To 10) As Integer Debug.Assert intArray(1) = 0 AndAlso intArray(10) = 0 Dim strArray(20 To 25) As String Debug.Assert strArray(20) = vbNullString ``` ## 返回数组 任何数组都可以作为动态数组返回: ```vb Function Fn1() As Long() Dim array1() As Long Dim array2(11) As Long Return array1 Return array2 End Function ``` 要返回固定大小数组,必须将其包装在UDT中: ```vb Type Wrapper array(11) As Long End Type Function Fn2() As Wrapper ' The procedure name is used to access the returned value Fn2.array(5) = 10 End Function Sub Test() Dim arr As Wrapper = Fn2() Debug.Assert arr.array(5) = 10 End Sub ``` ## 一维数组的高效低级访问 在twinBASIC中,数组类型实现为指向Windows API **SAFEARRAY**结构的指针的指针。 这可以用于高效访问: * 第一维度中的元素计数 * 指向数据的指针(指向数组中的第一个元素) * 数组的字节大小 ```vb Function ArrayLen(Of T)(array() As T) As Long Dim p As LongPtr GetMemPtr(VarPtr(array), p) If p <> 0 Then ' if the array is initialized #If win64 Then GetMem4(p + 24, Len) #Else GetMem4(p + 16, Len) #End If End If End Function Function ArrayPtr(Of T)(array() As T) As LongPtr Dim p As LongPtr GetMemPtr(VarPtr(array), p) If p <> 0 Then #If win64 Then GetMemPtr(p + 16, Ptr) #Else GetMemPtr(p + 12, Ptr) #End If End If End Function Function ArrayBytes(Of T)(array() As T) As Long Return ArrayLen(array) * LenB(Of T) End Function ``` 这些函数用于将数组和数组计数传递给外部的**Declare**声明的过程。例如: ```vb Declare Sub SaveData Lib "mylib" (ByVal ptr As LongPtr, ByVal count&) Declare Sub WriteData Lib "mylib" (ByVal ptr As LongPtr, ByVal numBytes&) Sub Save(array() As Long) Debug.Assert ArrayBytes(array) = ArrayLen(array) * 4 ' 4 = size of a Long SaveLongData(ArrayPtr(array), ArrayLen(array)) End Sub Sub Write(array() As Long) WriteData(ArrayPtr(array), ArrayBytes(array)) End Sub ``` 如果没有这些函数,这会更加繁琐: ```vb Sub Save(array() As Long) If IsArrayInitialized(array) Then SaveLongData( _ VarPtr(array(LBound(array))), _ 1 + UBound(array) - LBound(array)) Else SaveLongData(0, 0) ' ArrayLen, ArraySize, and ArrayPtr would ' return 0 for an uninitialized array End If End Sub ``` --- --- url: /zh/official/Features/Attributes-Intro.md --- # 特性 twinBASIC 支持直接在代码中定义特性,用于标注模块、类、类型、过程等。这些特性提供编译器指令和元数据。 特性有两个主要功能: * 可以作为编译器的指令来影响代码的生成方式,或 * 用于标注窗体、模块、类、类型、枚举、声明和[过程](/official/Reference/Glossary#procedure)(即 Sub/Function/Property)。 以前在 VBx 中,这些特性(如过程描述、隐藏、默认成员等)是通过 IDE 编辑器中不可见的隐藏文本设置的,通过"过程属性"对话框或其他地方进行配置。在 tB 中,这些内容都可在代码编辑器中直接看到。VBx 的遗留特性为兼容性而保留,但新特性使用以下语法: `[Attribute]` 或 `[Attribute(value)]` 许多新特性启用了 twinBASIC 提供的额外语言功能,因此以下某些条目的描述中包含了相关特性。 另请参阅[特性完整参考](/official/Reference/Attributes)。 --- --- url: /zh/official/Challenges.md --- # 挑战赛 来自Discord **#general**频道: 来自Discord上[Wayne的发言](https://discord.com/channels/927638153546829845/927638154192748606/1457062373465788671): > 在2026年开始之际,我们将推出twinBASIC月度挑战赛,让你有机会赢得£100账户额度,可用于未来的twinBASIC许可证。 另见Mike Wolfe的 [twinBASIC Update: January 6, 2026](https://nolongerset.com/twinbasic-update-january-6-2026/)。 > AI生成 --- --- url: /zh/packages/vbccr/system/commondialog.md description: 通用对话框控件(CommonDialog) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 通用对话框控件(CommonDialog) 提供 Windows 标准对话框(打开、保存、颜色、字体、打印、帮助、页面设置、文件夹浏览、查找、替换)的封装类。 ## 枚举 ### CdlErrorConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlCancel | 32755 | 用户选择了"取消" | | CdlBufferTooSmall | 20476 | 文件名缓冲区太小 | | CdlInvalidFileName | 20477 | 文件名无效 | | CdlSubclassFailure | 20478 | 子类化失败 | | CdlMaxLessThanMin | 24573 | 最小值大于最大值 | | CdlNoFonts | 24574 | 没有可用字体 | | CdlPrinterNotFound | 28660 | 未找到打印机 | | CdlCreateICFailure | 28661 | 创建信息上下文失败 | | CdlDndmMismatch | 28662 | DEVMODE 不匹配 | | CdlNoDefaultPrn | 28663 | 没有默认打印机 | | CdlNoDevices | 28664 | 没有打印设备 | | CdlInitFailure | 28665 | 打印对话框初始化失败 | | CdlGetDevModeFail | 28666 | 获取 DEVMODE 失败 | | CdlLoadDrvFailure | 28667 | 加载打印机驱动失败 | | CdlRetDefFailure | 28668 | 返回默认 DEVMODE 失败 | | CdlParseFailure | 28669 | 解析失败 | | CdlHelp | 32751 | 帮助请求 | | CdlBufferLengthZero | 36848 | 缓冲区长度为零 | ### CdlPRORConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlPRORPortrait | vbPRORPortrait | 纵向 | | CdlPRORLandscape | vbPRORLandscape | 横向 | ### CdlPRPSConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlPRPSLetter | vbPRPSLetter | Letter | | CdlPRPSLetterSmall | vbPRPSLetterSmall | Letter Small | | CdlPRPSTabloid | vbPRPSTabloid | Tabloid | | CdlPRPSLedger | vbPRPSLedger | Ledger | | CdlPRPSLegal | vbPRPSLegal | Legal | | CdlPRPSStatement | vbPRPSStatement | Statement | | CdlPRPSExecutive | vbPRPSExecutive | Executive | | CdlPRPSA3 | vbPRPSA3 | A3 | | CdlPRPSA4 | vbPRPSA4 | A4 | | CdlPRPSA4Small | vbPRPSA4Small | A4 Small | | CdlPRPSA5 | vbPRPSA5 | A5 | | CdlPRPSB4 | vbPRPSB4 | B4 | | CdlPRPSB5 | vbPRPSB5 | B5 | | CdlPRPSFolio | vbPRPSFolio | Folio | | CdlPRPSQuarto | vbPRPSQuarto | Quarto | | CdlPRPS10x14 | vbPRPS10x14 | 10x14 | | CdlPRPS11x17 | vbPRPS11x17 | 11x17 | | CdlPRPSNote | vbPRPSNote | Note | | CdlPRPSEnv9 | vbPRPSEnv9 | Envelope #9 | | CdlPRPSEnv10 | vbPRPSEnv10 | Envelope #10 | | CdlPRPSEnv11 | vbPRPSEnv11 | Envelope #11 | | CdlPRPSEnv12 | vbPRPSEnv12 | Envelope #12 | | CdlPRPSEnv14 | vbPRPSEnv14 | Envelope #14 | | CdlPRPSCSheet | vbPRPSCSheet | C Sheet | | CdlPRPSDSheet | vbPRPSDSheet | D Sheet | | CdlPRPSESheet | vbPRPSESheet | E Sheet | | CdlPRPSEnvDL | vbPRPSEnvDL | Envelope DL | | CdlPRPSEnvC5 | vbPRPSEnvC5 | Envelope C5 | | CdlPRPSEnvC3 | vbPRPSEnvC3 | Envelope C3 | | CdlPRPSEnvC4 | vbPRPSEnvC4 | Envelope C4 | | CdlPRPSEnvC6 | vbPRPSEnvC6 | Envelope C6 | | CdlPRPSEnvC65 | vbPRPSEnvC65 | Envelope C65 | | CdlPRPSEnvB4 | vbPRPSEnvB4 | Envelope B4 | | CdlPRPSEnvB5 | vbPRPSEnvB5 | Envelope B5 | | CdlPRPSEnvB6 | vbPRPSEnvB6 | Envelope B6 | | CdlPRPSEnvItaly | vbPRPSEnvItaly | Envelope Italy | | CdlPRPSEnvMonarch | vbPRPSEnvMonarch | Envelope Monarch | | CdlPRPSEnvPersonal | vbPRPSEnvPersonal | Envelope Personal | | CdlPRPSFanfoldUS | vbPRPSFanfoldUS | Fanfold US | | CdlPRPSFanfoldStdGerman | vbPRPSFanfoldStdGerman | Fanfold Std German | | CdlPRPSFanfoldLglGerman | vbPRPSFanfoldLglGerman | Fanfold Lgl German | | CdlPRPSUser | vbPRPSUser | 用户自定义 | ### CdlPRBNConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlPRBNUpper | vbPRBNUpper | 上层纸盒 | | CdlPRBNLower | vbPRBNLower | 下层纸盒 | | CdlPRBNMiddle | vbPRBNMiddle | 中层纸盒 | | CdlPRBNManual | vbPRBNManual | 手动送纸 | | CdlPRBNEnvelope | vbPRBNEnvelope | 信封纸盒 | | CdlPRBNEnvManual | vbPRBNEnvManual | 信封手动送纸 | | CdlPRBNAuto | vbPRBNAuto | 自动送纸 | | CdlPRBNTractor | vbPRBNTractor | 连续送纸 | | CdlPRBNSmallFmt | vbPRBNSmallFmt | 小格式纸盒 | | CdlPRBNLargeFmt | vbPRBNLargeFmt | 大格式纸盒 | | CdlPRBNLargeCapacity | vbPRBNLargeCapacity | 大容量纸盒 | | CdlPRBNCassette | vbPRBNCassette | 盒式纸盒 | ### CdlPRPQConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlPRPQHigh | vbPRPQHigh | 高质量 | | CdlPRPQMedium | vbPRPQMedium | 中等质量 | | CdlPRPQLow | vbPRPQLow | 低质量 | | CdlPRPQDraft | vbPRPQDraft | 草稿质量 | ### CdlPRCMConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlPRCMMonochrome | vbPRCMMonochrome | 单色打印 | | CdlPRCMColor | vbPRCMColor | 彩色打印 | ### CdlPRDPConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlPRDPSimplex | vbPRDPSimplex | 单面打印 | | CdlPRDPHorizontal | vbPRDPHorizontal | 双面水平翻转 | | CdlPRDPVertical | vbPRDPVertical | 双面垂直翻转 | ### CdlOFNConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlOFNReadOnly | \&H1 | 显示只读复选框 | | CdlOFNOverwritePrompt | \&H2 | 覆盖文件前提示 | | CdlOFNHideReadOnly | \&H4 | 隐藏只读复选框 | | CdlOFNNoChangeDir | \&H8 | 不改变当前目录 | | CdlOFNHelpButton | \&H10 | 显示帮助按钮 | | CdlOFNNoValidate | \&H100 | 不验证文件名 | | CdlOFNAllowMultiSelect | \&H200 | 允许多选 | | CdlOFNExtensionDifferent | \&H400 | 扩展名不同 | | CdlOFNPathMustExist | \&H800 | 路径必须存在 | | CdlOFNFileMustExist | \&H1000 | 文件必须存在 | | CdlOFNCreatePrompt | \&H2000 | 创建文件提示 | | CdlOFNShareAware | \&H4000 | 忽略共享错误 | | CdlOFNNoReadOnlyReturn | \&H8000& | 不返回只读文件 | | CdlOFNNoNetworkButton | \&H20000 | 隐藏网络按钮 | | CdlOFNExplorer | \&H80000 | 使用资源管理器风格 | | CdlOFNNoDereferenceLinks | \&H100000 | 不解除快捷方式 | | CdlOFNDontAddToRecent | \&H2000000 | 不添加到最近使用 | | CdlOFNForcesShowHidden | \&H10000000 | 显示隐藏文件 | ### CdlOFNShareViResultConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlOFNShareViResultWarn | \&H0 | 警告共享冲突 | | CdlOFNShareViResultNoWarn | \&H1 | 不警告共享冲突 | | CdlOFNShareViResultFallThrough | \&H2 | 忽略共享冲突 | ### CdlCCConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlCCRGBInit | \&H1 | 使用初始颜色 | | CdlCCFullOpen | \&H2 | 完全打开对话框 | | CdlCCPreventFullOpen | \&H4 | 禁止完全打开 | | CdlCCHelpButton | \&H8 | 显示帮助按钮 | | CdlCCSolidColor | \&H80 | 仅纯色 | | CdlCCAnyColor | \&H100 | 任意颜色 | ### CdlCFConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlCFScreenFonts | \&H1 | 屏幕字体 | | CdlCFPrinterFonts | \&H2 | 打印机字体 | | CdlCFHelpButton | \&H4 | 显示帮助按钮 | | CdlCFEffects | \&H100 | 启用效果选项 | | CdlCFApply | \&H200 | 启用应用按钮 | | CdlCFScriptsOnly | \&H400 | 仅脚本字体 | | CdlCFNoVectorFonts | \&H800 | 排除矢量字体 | | CdlCFLimitSize | \&H2000 | 限制字体大小 | | CdlCFFixedPitchOnly | \&H4000 | 仅等宽字体 | | CdlCFForceFontExist | \&H10000 | 字体必须存在 | | CdlCFScalableOnly | \&H20000 | 仅可缩放字体 | | CdlCFTTOnly | \&H40000 | 仅 TrueType 字体 | | CdlCFNoFaceSel | \&H80000 | 无字体名选择 | | CdlCFNoStyleSel | \&H100000 | 无样式选择 | | CdlCFNoSizeSel | \&H200000 | 无大小选择 | | CdlCFSelectScript | \&H400000 | 选择脚本 | | CdlCFNoScriptSel | \&H800000 | 无脚本选择 | | CdlCFNoVertFonts | \&H1000000 | 排除垂直字体 | ### CdlPDConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlPDAllPages | \&H0 | 全部页面 | | CdlPDSelection | \&H1 | 选定范围 | | CdlPDPageNums | \&H2 | 页码范围 | | CdlPDNoSelection | \&H4 | 禁用选定范围 | | CdlPDNoPageNums | \&H8 | 禁用页码范围 | | CdlPDCollate | \&H10 | 逐份打印 | | CdlPDPrintToFile | \&H20 | 打印到文件 | | CdlPDPrintSetup | \&H40 | 显示打印设置 | | CdlPDNoWarning | \&H80 | 无警告 | | CdlPDReturnDC | \&H100 | 返回设备上下文 | | CdlPDReturnIC | \&H200 | 返回信息上下文 | | CdlPDReturnDefault | \&H400 | 返回默认打印机 | | CdlPDHelpButton | \&H800 | 显示帮助按钮 | | CdlPDUseDevModeCopies | \&H40000 | 使用 DEVMODE 副本数 | | CdlPDUseDevModeCopiesAndCollate | \&H40000 | 使用 DEVMODE 副本和逐份 | | CdlPDDisablePrintToFile | \&H80000 | 禁用打印到文件 | | CdlPDCurrentPage | \&H400000 | 当前页 | | CdlPDHidePrintToFile | \&H100000 | 隐藏打印到文件 | | CdlPDNoNetworkButton | \&H200000 | 隐藏网络按钮 | | CdlPDNoCurrentPage | \&H800000 | 禁用当前页 | ### CdlPDResultConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlPDResultCancel | \&H0 | 用户取消 | | CdlPDResultPrint | \&H1 | 用户打印 | | CdlPDResultApply | \&H2 | 用户应用 | ### CdlHelpConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlHelpContext | \&H1 | 上下文帮助 | | CdlHelpQuit | \&H2 | 退出帮助 | | CdlHelpIndex | \&H3 | 帮助索引 | | CdlHelpContents | \&H3 | 帮助目录 | | CdlHelpHelpOnHelp | \&H4 | 关于帮助的帮助 | | CdlHelpSetIndex | \&H5 | 设置帮助索引 | | CdlHelpSetContents | \&H5 | 设置帮助目录 | | CdlHelpContextPopup | \&H8 | 弹出上下文帮助 | | CdlHelpForceFile | \&H9 | 强制帮助文件 | | CdlHelpKey | \&H101 | 关键字帮助 | | CdlHelpCommandHelp | \&H102 | 命令帮助 | | CdlHelpPartialKey | \&H105 | 部分关键字帮助 | ### CdlPSDConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlPSDDefaultMinMargins | \&H0 | 默认最小边距 | | CdlPSDMinMargins | \&H1 | 允许设置最小边距 | | CdlPSDMargins | \&H2 | 允许设置边距 | | CdlPSDInThousandthsOfInches | \&H4 | 以千分之一英寸为单位 | | CdlPSDInHundredthsOfMillimeters | \&H8 | 以百分之一毫米为单位 | | CdlPSDDisableMargins | \&H10 | 禁用边距 | | CdlPSDDisablePrinter | \&H20 | 禁用打印机按钮 | | CdlPSDNoWarning | \&H80 | 无警告 | | CdlPSDDisableOrientation | \&H100 | 禁用方向 | | CdlPSDDisablePaper | \&H200 | 禁用纸张 | | CdlPSDReturnDefault | \&H400 | 返回默认设置 | | CdlPSDHelpButton | \&H800 | 显示帮助按钮 | | CdlPSDDisablePagePainting | \&H80000 | 禁用页面绘制 | | CdlPSDNoNetworkButton | \&H200000 | 隐藏网络按钮 | ### CdlBIFConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlBIFReturnOnlyFSDirs | \&H1 | 仅返回文件系统目录 | | CdlBIFDontGoBelowDomain | \&H2 | 不浏览域以下 | | CdlBIFStatusText | \&H4 | 包含状态文本 | | CdlBIFReturnFSAncestors | \&H8 | 返回文件系统祖先 | | CdlBIFEditBox | \&H10 | 包含编辑框 | | CdlBIFValidate | \&H20 | 验证输入 | | CdlBIFNewDialogStyle | \&H40 | 新对话框样式 | | CdlBIFBrowseIncludeURLs | \&H80 | 包含 URL | | CdlBIFUseNewUI | \&H50 | 使用新 UI | | CdlBIFUAHint | \&H100 | 用户提示 | | CdlBIFNoNewFolderButton | \&H200 | 隐藏新建文件夹按钮 | | CdlBIFNoTranslateTargets | \&H400 | 不翻译目标 | | CdlBIFBrowseForComputer | \&H1000 | 仅浏览计算机 | | CdlBIFBrowseForPrinter | \&H2000 | 仅浏览打印机 | | CdlBIFBrowseIncludeFiles | \&H4000 | 包含文件 | | CdlBIFShareable | \&H8000& | 可共享 | | CdlBIFBrowseFileJunctions | \&H10000 | 浏览文件联结点 | ### CdlFRConstants | 常量 | 值 | 说明 | |------|-----|------| | CdlFRDown | \&H1 | 向下搜索 | | CdlFRWholeWord | \&H2 | 全字匹配 | | CdlFRMatchCase | \&H4 | 区分大小写 | | CdlFRFindNext | \&H8 | 查找下一个 | | CdlFRReplace | \&H10 | 替换 | | CdlFRReplaceAll | \&H20 | 全部替换 | | CdlFRHelpButton | \&H80 | 显示帮助按钮 | | CdlFRNoUpDown | \&H400 | 禁用方向选择 | | CdlFRNoMatchCase | \&H800 | 禁用大小写选择 | | CdlFRNoWholeWord | \&H1000 | 禁用全字选择 | | CdlFRHideUpDown | \&H4000 | 隐藏方向选择 | | CdlFRHideMatchCase | \&H8000& | 隐藏大小写选择 | | CdlFRHideWholeWord | \&H10000 | 隐藏全字选择 | ## 属性 ### Object ```vb Property Get Object() As Object ``` 返回对象自身的实例。 ### CancelError ```vb Property Get/Let CancelError() As Boolean ``` 指示用户选择"取消"时是否产生错误。 ### HookEvents ```vb Property Get/Let HookEvents() As Boolean ``` 指示对话框是否可以引发需要钩子回调的事件。 ### Tag ```vb Property Get/Let Tag() As String ``` 存储程序所需的附加数据。 ### hDC ```vb Property Get hDC() As LongPtr ``` 返回设备上下文句柄(只读)。 ### Flags ```vb Property Get/Let Flags() As Long ``` 返回/设置对话框选项标志。 ### DialogTitle ```vb Property Get/Let DialogTitle() As String ``` 设置对话框标题栏显示的字符串。 ### MaxFileSize ```vb Property Get/Let MaxFileSize() As Long ``` 返回/设置打开文件名的最大大小。 ### FileName ```vb Property Get/Let FileName() As String ``` 返回/设置所选文件的路径和文件名。 ### FileTitle ```vb Property Get FileTitle() As String ``` 返回所选文件的文件名(不含路径,只读)。 ### FileOffset ```vb Property Get FileOffset() As Integer ``` 返回从路径开头到文件名的零偏移量(只读)。 ### Filter ```vb Property Get/Let Filter() As String ``` 返回/设置对话框类型列表框中显示的过滤器。 ### FilterIndex ```vb Property Get/Let FilterIndex() As Long ``` 返回/设置默认过滤器索引。 ### InitDir ```vb Property Get/Let InitDir() As String ``` 返回/设置初始文件目录。 ### DefaultExt ```vb Property Get/Let DefaultExt() As String ``` 返回/设置默认文件扩展名。 ### Color ```vb Property Get/Let Color() As Long ``` 返回/设置所选颜色。 ### CustomColors ```vb Property Get/Let CustomColors() As Variant ``` 返回/设置用户可选择的自定义颜色。 ### FontName ```vb Property Get/Let FontName() As String ``` 返回/设置字体名称。 ### FontSize ```vb Property Get/Let FontSize() As Single ``` 返回/设置字体大小(磅值)。 ### FontBold ```vb Property Get/Let FontBold() As Boolean ``` 返回/设置粗体字体样式。 ### FontItalic ```vb Property Get/Let FontItalic() As Boolean ``` 返回/设置斜体字体样式。 ### FontStrikethru ```vb Property Get/Let FontStrikethru() As Boolean ``` 返回/设置删除线字体样式。 ### FontUnderline ```vb Property Get/Let FontUnderline() As Boolean ``` 返回/设置下划线字体样式。 ### FontCharset ```vb Property Get/Let FontCharset() As Integer ``` 返回/设置字体字符集。 ### FontWeight ```vb Property Get/Let FontWeight() As Integer ``` 返回/设置字体粗细(0=Don'tCare, 100=Thin, 200=ExtraLight, 300=Light, 400=Normal, 500=Medium, 600=SemiBold, 700=Bold, 800=ExtraBold, 900=Heavy)。 ### Min ```vb Property Get/Let Min() As Long ``` 返回/设置最小字体大小(字体对话框)或最小打印页范围(打印对话框)。 ### Max ```vb Property Get/Let Max() As Long ``` 返回/设置最大字体大小(字体对话框)或最大打印页范围(打印对话框)。 ### FromPage ```vb Property Get/Let FromPage() As Long ``` 返回/设置打印起始页。 ### ToPage ```vb Property Get/Let ToPage() As Long ``` 返回/设置打印终止页。 ### Orientation ```vb Property Get/Let Orientation() As CdlPRORConstants ``` 返回/设置打印方向。 ### PaperSize ```vb Property Get/Let PaperSize() As CdlPRPSConstants ``` 返回/设置打印纸张大小。 ### Copies ```vb Property Get/Let Copies() As Integer ``` 返回/设置打印份数。 ### PaperBin ```vb Property Get/Let PaperBin() As CdlPRBNConstants ``` 返回/设置默认送纸器。 ### PrintQuality ```vb Property Get/Let PrintQuality() As CdlPRPQConstants ``` 返回/设置打印分辨率。 ### ColorMode ```vb Property Get/Let ColorMode() As CdlPRCMConstants ``` 返回/设置打印机颜色模式。 ### Duplex ```vb Property Get/Let Duplex() As CdlPRDPConstants ``` 返回/设置双面打印模式。 ### PrinterDefault ```vb Property Get/Let PrinterDefault() As Boolean ``` 返回/设置用户选择是否更改默认打印机。 ### PrinterDefaultInit ```vb Property Get/Let PrinterDefaultInit() As Boolean ``` 返回/设置是否始终初始化默认打印机。 ### PrinterDriver ```vb Property Get/Let PrinterDriver() As String ``` 返回/设置非默认打印机驱动名称。 ### PrinterName ```vb Property Get/Let PrinterName() As String ``` 返回/设置非默认打印机设备名称。 ### PrinterPort ```vb Property Get/Let PrinterPort() As String ``` 返回/设置非默认打印机端口名称。 ### HelpFile ```vb Property Get/Let HelpFile() As String ``` 返回/设置与项目关联的帮助文件名。 ### HelpCommand ```vb Property Get/Let HelpCommand() As CdlHelpConstants ``` 返回/设置联机帮助类型。 ### HelpContext ```vb Property Get/Let HelpContext() As LongPtr ``` 返回/设置帮助主题的上下文 ID。 ### HelpKey ```vb Property Get/Let HelpKey() As String ``` 返回/设置标识帮助主题的关键字。 ### PageLeftMargin ```vb Property Get/Let PageLeftMargin() As Long ``` 返回/设置纸张左边距(设备单位)。 ### PageTopMargin ```vb Property Get/Let PageTopMargin() As Long ``` 返回/设置纸张上边距(设备单位)。 ### PageRightMargin ```vb Property Get/Let PageRightMargin() As Long ``` 返回/设置纸张右边距(设备单位)。 ### PageBottomMargin ```vb Property Get/Let PageBottomMargin() As Long ``` 返回/设置纸张下边距(设备单位)。 ### PageLeftMinMargin ```vb Property Get/Let PageLeftMinMargin() As Long ``` 返回/设置纸张最小左边距(设备单位)。 ### PageTopMinMargin ```vb Property Get/Let PageTopMinMargin() As Long ``` 返回/设置纸张最小上边距(设备单位)。 ### PageRightMinMargin ```vb Property Get/Let PageRightMinMargin() As Long ``` 返回/设置纸张最小右边距(设备单位)。 ### PageBottomMinMargin ```vb Property Get/Let PageBottomMinMargin() As Long ``` 返回/设置纸张最小下边距(设备单位)。 ### RootFolder ```vb Property Get/Let RootFolder() As Variant ``` 返回/设置文件夹浏览对话框的根文件夹。 ### FindWhat ```vb Property Get/Let FindWhat() As String ``` 返回/设置查找对话框的搜索字符串。 ### ReplaceWith ```vb Property Get/Let ReplaceWith() As String ``` 返回/设置替换对话框的替换字符串。 ### Action ```vb Property Let Action() As Integer ``` 设置要显示的对话框类型(只写,1=打开, 2=保存, 3=颜色, 4=字体, 5=打印, 6=帮助, 7=页面设置, 8=文件夹浏览, 9=查找, 10=替换)。 ## 方法 ### ShowOpen ```vb Public Function ShowOpen() As Boolean ``` 显示"打开"对话框。成功返回 True。 ### ShowSave ```vb Public Function ShowSave() As Boolean ``` 显示"保存"对话框。成功返回 True。 ### ShowColor ```vb Public Function ShowColor() As Boolean ``` 显示"颜色"对话框。成功返回 True。 ### ShowFont ```vb Public Function ShowFont() As Boolean ``` 显示"字体"对话框。成功返回 True。 ### ShowPrinter ```vb Public Function ShowPrinter() As Boolean ``` 显示"打印"对话框。成功返回 True。 ### ShowPrinterEx ```vb Public Function ShowPrinterEx() As Boolean ``` 显示"打印"扩展对话框(PrintDlgEx)。成功返回 True。 ### ShowHelp ```vb Public Sub ShowHelp() ``` 显示帮助。 ### ShowPageSetup ```vb Public Function ShowPageSetup() As Boolean ``` 显示"页面设置"对话框。成功返回 True。 ### ShowFolderBrowser ```vb Public Function ShowFolderBrowser() As Boolean ``` 显示"文件夹浏览"对话框。成功返回 True。 ### ShowFind ```vb Public Function ShowFind() As Boolean ``` 显示"查找"对话框。成功返回 True。 ### ShowReplace ```vb Public Function ShowReplace() As Boolean ``` 显示"替换"对话框。成功返回 True。 ## 事件 ### InitDialog ```vb Public Event InitDialog(ByVal Action As Integer, ByVal hDlg As Long) ``` 对话框完成初始化时发生。 ### Help ```vb Public Event Help(ByRef Handled As Boolean, ByVal Action As Integer, ByVal hDlg As Long) ``` 用户在对话框中点击帮助按钮时发生。 ### FileShareViolation ```vb Public Event FileShareViolation(ByVal FileName As String, ByRef Result As CdlOFNShareViResultConstants, ByVal hDlg As Long) ``` 在打开或保存对话框中用户点击确定且发生网络共享冲突时发生。 ### FileValidate ```vb Public Event FileValidate(ByVal FileName As String, ByVal FileTitle As String, ByVal FileOffset As Integer, ByRef Cancel As Boolean, ByVal hDlg As Long) ``` 在打开或保存对话框中用户点击确定时发生。 ### ColorValidate ```vb Public Event ColorValidate(ByRef RGBColor As Long, ByRef Cancel As Boolean, ByVal hDlg As Long) ``` 在颜色对话框中用户点击确定时发生。 ### FontApply ```vb Public Event FontApply(ByVal Flags As Long, ByVal FontName As String, ByVal FontSize As Single, ByVal FontBold As Boolean, ByVal FontItalic As Boolean, ByVal FontStrikethru As Boolean, ByVal FontUnderline As Boolean, ByVal FontCharset As Integer, ByVal RGBColor As Long, ByVal hDlg As Long) ``` 在字体对话框中用户点击"应用"按钮时发生。 ### FolderBrowserValidateFailed ```vb Public Event FolderBrowserValidateFailed(ByVal Text As String, ByRef Cancel As Boolean, ByVal hDlg As Long) ``` 在文件夹浏览对话框中用户输入无效名称时发生。 ### FindNext ```vb Public Event FindNext() ``` 在查找或替换对话框中用户点击"查找下一个"按钮时发生。 ### Replace ```vb Public Event Replace() ``` 在替换对话框中用户点击"替换"按钮时发生。 ### ReplaceAll ```vb Public Event ReplaceAll() ``` 在替换对话框中用户点击"全部替换"按钮时发生。 ## 代码示例 ### 基本用法 ```vb Private Sub cmdOpen_Click() Dim dlg As CommonDialog Set dlg = New CommonDialog dlg.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*" dlg.FilterIndex = 1 dlg.CancelError = True On Error GoTo Cancelled If dlg.ShowOpen() Then MsgBox "已选择: " & dlg.FileName End If Exit Sub Cancelled: If Err.Number = CdlCancel Then Exit Sub MsgBox "错误: " & Err.Description End Sub ``` ### 使用事件钩子 ```vb Private WithEvents dlg As CommonDialog Private Sub cmdFont_Click() Set dlg = New CommonDialog dlg.HookEvents = True dlg.Flags = CdlCFScreenFonts Or CdlCFEffects Or CdlCFLimitSize dlg.Min = 8 dlg.Max = 72 dlg.ShowFont End Sub Private Sub dlg_FontApply(ByVal Flags As Long, ByVal FontName As String, _ ByVal FontSize As Single, ByVal FontBold As Boolean, ByVal FontItalic As Boolean, _ ByVal FontStrikethru As Boolean, ByVal FontUnderline As Boolean, _ ByVal FontCharset As Integer, ByVal RGBColor As Long, ByVal hDlg As Long) Me.Font.Name = FontName Me.Font.Size = FontSize Me.Font.Bold = FontBold Me.Font.Italic = FontItalic End Sub ``` --- --- url: /zh/packages/vbccr/author.md description: 通用控件替代包【官方文档】 - VBCCR 开发手册,基于源码的完整 API 参考 --- # 通用控件替代包【官方文档】 本页文档翻译自官方作者写的文档,使用ai把原始的word文档转为md,然后ai翻译为中文。 翻译:(邓伟) ## 工具说明 注意:本文件适用于 StdEXE 工具 3.3 版。工具的更新日志见本文档末尾的表格。3.3 版增加了对 VBCCRxx.OCX(最高至 1.7 版)和 VBFLXGRDxx.OCX(最新为 1.6 版)的支持。 自 2012 年 11 月以来,VBForums 用户 Krool 一直在开发一套用于替换 Windows 通用控件的控件包。虽然很多人讨论过替换这些控件,但直到现在都没有人真正成功实现。Krool 主要凭借个人力量,在论坛中不断调试和收集反馈。2017 年中,Krool 又着手开发 MSFlexGrid 控件的替代品,虽然与其他替代控件类似,但他选择在论坛的独立主题中进行开发。 本包希望为您提供一些设置和使用这些控件的技巧,并指导您减少或消除对除自身代码以外的任何文件的依赖。 Krool 的控件会像下图一样出现在 VB6 的工具箱中。它们的使用方式与 VB6 内置控件完全一致,只需拖放到窗体或其他控件上即可。下方展示了可添加的控件。 这些新控件能为您和您的程序带来什么? * 支持 Unicode。网上虽然能找到一些支持 Unicode 的控件,但 Krool 的两个包可以让您一次性获得 34 个 Windows 通用控件的 Unicode 支持。 * 功能增强,超越了 VB6 和 VBA 程序员多年来使用的常规控件。 * 支持主题(视觉样式),让您的程序拥有现代化外观,不再像 Windows 95 时代的风格。相关配置在本包中有简化说明。 * 控件可以嵌入到您的代码中,最终生成的 EXE 文件无任何依赖,仅需一个可执行文件,无需注册或安装(例如可直接从 U 盘运行)。也可以使用传统的 .OCX 控件文件,并通过“并排”方式让 .OCX 文件无需在用户电脑上注册,只需与程序放在同一文件夹即可。这两种方式都能让您的程序真正实现便携分发。 * Krool 的代码日益稳定,作者和用户社区也会持续提供问题解答和新功能建议。 * 本包包含了一份用户指南(即本文档),介绍控件包的整体用法,而非每个控件的详细用法。 * 附带了一个名为 OCX2StdEXE 的工具,帮助您及时获取最新控件,并支持在开发阶段使用 OCX 版本,最终编译时自动切换为 StdEXE 版本,实现无依赖的可执行文件。 * 生成的 EXE 文件完全自包含,无任何外部依赖。无需在用户电脑上安装,也无需随程序分发和注册 .OCX 控件文件。 * 在 IDE 中使用 Krool 的 StdEXE 控件(即非传统 .OCX 控件文件)并非完全安全,尽管 Krool 已尽力减少 IDE 崩溃风险。开发时建议使用 .OCX 版本,既安全又高效,最终编译时再用本工具切换为 StdEXE 版本,将所有控件嵌入程序,无需任何依赖。 * 在 IDE 中使用 StdEXE 控件不仅有稳定性风险,还会导致每次编译都要重新编译控件代码(以我电脑为例,使用 .OCX 版本编译典型程序只需 3 秒,而 StdEXE 版本需 25 秒)。开发阶段频繁编译会非常耗时。借助 OCX2StdEXE 工具,您可以在开发时用 .OCX 版本(速度快、稳定),最终编译时用 StdEXE 版本,兼得体积小和无依赖的优点。 ## 用户指南 Krool有一个包含大量功能的程序包,但程序员需要理解很多内容才能充分利用这些包。涉及的内容包括: * 安装 * 两种不同的方法:已编译的.OCX控件和嵌入程序中每次编译的控件。如何选择使用哪个版本以及为什么?您能否或应该同时使用两者? * 设置 * 如何设置频繁更新,以最小化错误修复和功能添加带来的频繁更新的麻烦。 * 必需的类型库。 * 您还需要什么来使用这些控件包? * 什么是视觉主题,我应该使用它们吗?如何使用? * "并排"是什么意思?我应该使用它吗,如何使用它? * 清单文件是什么,我应该使用它们吗,应该如何使用它们? ## 简介 VB6控件有两个版本。最简单的是控件的源代码在您的程序中,当您的代码编译时,控件的代码与之一起编译。控件的已编译代码成为您程序的一部分。您的程序是独立的,除了Windows中包含的文件外,不依赖于任何外部文件来运行,也不需要将任何文件复制到用户的PC上或在用户的PC上注册。这种方法的缺点是,当您在开发程序时,每次编译代码时都必须编译控件的代码。此外,大多数编写控件的公司不希望放弃他们的代码,所以他们不会分发每个控件的源代码。因此,这种制作控件的方法并不常见。 另一种方式是将一个或多个控件编译到扩展名为OCX的文件中(代表OLE控件扩展或ActiveX控件)。使用OCX文件的程序员永远不会看到源代码,而且代码不需要一遍又一遍地编译。这种类型的控件包的一个缺点是,控件不是程序的一部分,必须发送给每个最终用户,而且由于超出本文档范围的原因,OCX文件必须在每个用户的计算机上注册(我们稍后会讲到并排)。 Krool在2012年底发布了通用控件替代品的第一个版本。这些是源代码的未编译版本,您会将其包含在代码中。他称这个版本为StdEXE,这可能意味着这些控件的标准版本被编译到您的EXE文件中。大约5年后(2017年1月),他开始提供相同的控件,但是采用预编译的OCX版本。所以现在我们程序员可以两种形式使用相同的控件。 没有关于如何使用每个控件的用户指南,但由于每个控件都是其他通用控件的增强替代品,可以说这种手把手的指导对于大多数非常资深的VB6程序员来说并不需要。然而,这些控件集的其他几个方面如果没有一些支持,会使它们比必要的更难完全使用。希望本文档能解决其中的一些问题。 在Krool开发了他的通用控件包之后,他决定添加另一个在他的包中遗漏的控件,即MSFlexGrid控件的替代品。他决定,尽管它与第一个包有很多共同点,但它是一个单独的包,可以与原始包一起使用,但可能会令人困惑。 当使用任一组控件的StdEXE版本时,您需要在IDE中使用一个类型库,"OLEGuids和接口定义"。此外,当使用FlexGrid控件的StdEXE版本时,还需要另一个类型库。OCX版本不需要类型库,因为它们实际上包含在OCX文件中。 Krool控件的一个主要优势是它们设计时就考虑到了使用"视觉样式"的能力,这样您的程序就不会看起来像来自Windows 95。但是,为了使用这些样式,您需要知道如何打开这个功能,对我们许多人来说这并不直观。不过,一旦打开,它确实令人印象深刻。 如果您使用控件的OCX版本,您必须将OCX文件与您的程序一起分发给用户。在VB6出现之前,Windows的设计是这样的:这些预编译的控件、动态链接库、设备驱动程序等都会在每个用户的系统上注册,每个版本(据说是最新的)只会在每个用户的系统上存在一个,这样一旦安装和注册,许多程序就可以使用相同的注册代码。这样设计是为了节省硬盘空间、减少内存使用等,但它造成的问题比解决的问题还多。到VB6出来的时候,一个新的系统已经设计出来并正在实施,它使程序能够使用集中注册的文件,或者让程序拥有自己的支持文件,这些文件不会复制到中央存储库(Windows系统文件夹)并注册,而是与程序"并排"放在一起。如果您使用StdEXE版本的控件,则不需要这个(至少对于这些控件来说),因为所有代码都编译到您的代码中,但如果您使用OCX版本,这个并排解决方案可能是可取的,因为它使您能够分发不需要安装且没有必须安装和注册的组件的程序。 如果您使用StdEXE版本的控件,没有"版本"之说,当Krool发布更新时,您只需将新文件复制到旧文件上即可继续。但是,OCX版本确实有版本(就像所有预编译代码一样,请参见上面的长段落),修改每个程序以使用较新版本并不是一件小事。我的工具可以为您处理这个问题。 由于Krool同时提供了控件的OCX和StdEXE版本,因此可以通过使您能够在开发过程中使用OCX版本(更易于使用且编译时间更短)来改善您的编程体验,但随后使用StdEXE版本进行最终编译,以将所有控件代码包含在程序中,这样就不需要将OCX文件包含在程序中,您也不必处理并排的复杂性。我的工具也可以为您处理这个问题。 ## 概述 每组控件都有两个版本;一个是具有OCX扩展名的单个文件,其中包含控件的预编译版本。这需要在您(程序员)的计算机上注册。它可以在VBForums上[这里](https://www.vbforums.com/showthread.php?698563-CommonControls-\(Replacement-of-the-MS-common-controls\))找到。 您在程序中引用它,然后就可以访问所有控件。从程序员的角度来看这很简单,但是当您分发完成的EXE或DLL文件时,您必须包含OCX文件。此外,此文件需要是"并排"解决方案的一部分,或者需要复制到用户的PC上并注册。 另一种方法Krool称之为StdEXE版本。在这个版本中,所有代码都在一个大型文件组中(当前在38个文件夹中有162个),这些都是未编译的,必须作为模块添加到您的程序中。此包的最新版本可以在VBForums上[这里](https://www.vbforums.com/showthread.php?698563-CommonControls-\(Replacement-of-the-MS-common-controls\))找到。 每次编译程序时,所有这些控件也会被编译。即使知道哪些文件要包含在程序中以用于哪些控件也是一个大麻烦,子程序、函数和变量的某些名称可能与您使用的名称冲突,并且每次编译所有这些控件代码都需要很长时间。我的电脑相当快,但仅仅编译Krool提供的ComCtlsDemo程序就需要超过25秒。在VB6中编码时我经常编译,部分原因是只是为了检查语法和逻辑错误,而25+秒的编译时间是非常令人恼火的,特别是当我知道我可以在OCX版本中在3秒内编译相同的代码时。我喜欢最终可执行文件中没有外部依赖项的事实,但我讨厌编译时间。要是有办法可以在开发过程中使用OCX版本及其快速的编译时间,但在最终编译时使用内部控件,这样就不需要有单独的OCX文件与程序一起分发就好了。我的工具就是这样做的。 此外,这些控件有许多更新。未编译文件(StdEXE版本)实际上没有版本号,只要您将最新文件复制到相同位置的早期文件上,就不会有任何问题。然而,OCX版本并非如此。我将我的放在C:\Windows\SysWOW64中,只要我们有相同的版本,我们就可以将新的OCX文件复制到旧的文件上。但随着时间的推移,已经添加了新功能,所以我们有了1.1、1.2、1.3、1.4、1.5、1.6和现在的1.7版本。如果您使用1.6版本的控件开发了一个程序,那么使用1.7版本的控件时会遇到问题,因为需要对使用Krool控件的每个项目文件、每个控件文件以及清单文件(如果您使用的话)进行更改。我的工具可以处理这些问题,允许您从任何OCX版本切换到安装在PC上的CommonControls的任何其他OCX版本(包括独立的FlexGrid控件)。 ## 包含的控件 以下是Krool包中的控件列表。除了VBFlexGrid(在VBFlexGrid Control包中)外,所有控件都在Common Controls替代包中。 | | | | | | --- | --- | --- | --- | | Animation(动画) | FrameW(框架) | MCIWnd(多媒体) | SysInfo(系统信息) | | CheckBoxW(复选框) | HotKey(热键) | MonthView(月历) | TabStrip(标签条) | | ComboBoxW(组合框) | ImageCombo(图像组合框) | OptionButtonW(选项按钮) | TextBoxW(文本框) | | CommandButtonW(命令按钮) | ImageList(图像列表) | Pager(分页器) | ToolBar(工具栏) | | CommandLink(命令链接) | IPAddress(IP地址) | ProgressBar(进度条) | TreeView(树形视图) | | CommonDialog(通用对话框) | LabelW(标签) | RichTextBox(富文本框) | UpDown(上下调节器) | | CoolBar(冷工具栏) | LinkLabel(链接标签) | Slider(滑块) | VirtualBoxCombo(虚拟组合框) | | DTPicker(日期时间选择器) | ListBoxW(列表框) | SpinBox(数值调节器) | VListBox(虚拟列表框) | | FontCombo(字体组合框) | ListView(列表视图) | StatusBar(状态栏) | VBFlexGrid(灵活网格) | 如果您有任何编程经验,您无疑已经看到并使用过这些控件中的许多。一旦安装好Krool的系统,使用起来相当容易,因为控件的行为与现有控件非常相似。我们主要讨论如何安装和设置每个系统以供使用。 ## 术语 Krool的控件很棒,但在他的包内部和周围使用的许多术语可能会令人非常困惑(至少对我来说是这样)。以下是我对一些术语的解释。 **ActiveX** - 维基百科[文章](https://en.wikipedia.org/wiki/ActiveX)。这是Microsoft在1996年使用早期OLE和COM技术制定的软件框架。对于本文档,我们将把ActiveX视为我们控件的基础。 **Control(控件)** - 在工具箱中由图标表示的组件,可以放置在窗体上。大多数是可见的,但有些(如计时器)是不可见的。VB6中最简单的控件包含在已安装的VB6程序包中。其他的,如Krool的控件和来自Microsoft和其他供应商的许多控件,必须添加。有关制作自己的控件的更多信息,请参见[这个](https://pages.cpsc.ucalgary.ca/~saul/vb_examples/index.html)网页,特别是教程#10。 **OCX** - 通常,我们都使用已预编译到扩展名为.OCX的文件中的控件(代表OLE控件扩展或ActiveX控件)。这些文件必须在开发人员的PC上注册,并且必须分发给开发人员程序的每个用户并在其PC上注册。一个.OCX文件可以包含多个控件。程序员(您)需要在其系统上安装并注册OCX,但用户也需要在其系统上拥有OCX文件,通常是注册的,但有时是与正在运行的已编译程序"并排"使用该OCX控件。 **StdEXE** - Krool使用这个术语来指定在程序中包含ActiveX控件的另一种方法。有许多源代码文件,包括标准模块和类模块、属性页文件等,它们被编译成OCX控件。另外,所有这些都可以由作者分发并作为源代码放入我们每个程序中。通常,控件包的作者出于各种原因不想分发其控件的源代码,但Krool选择对他的包这样做。这样做的好处是您的程序中包含了所有编译在其中的控件代码,因此不需要分发或注册文件就可以使它工作。所有内容都包含在您编译的代码中。从程序员的角度来看,这样做的一个缺点是,在开发程序并一遍又一遍地编译时,所有控件代码都必须重新编译。 **VBCCRxx** - VBCCR代表Visual Basic Common Controls Replacement(Visual Basic通用控件替代品),而"xx"指的是OCX版本,目前可以是1.1(xx=11)、1.2、1.3、1.4、1.5或1.6(xx=16)。随着以编译形式分发的代码随时间的推移被修改和扩展,作者(Krool)必须发布不同的版本,每个版本都必须在用户的PC(和程序员的PC)上存在。例如,假设您编写了一个使用VBCCR16.ocx的程序,并将其发送给一个安装了VBCCR13.ocx但没有VBCCR16.ocx的同事。它将无法运行,因为它在启动时会寻找其他ocx文件。这就是OCX文件的缺点。如果您使用StdEXE版本,代码会直接编译到您的代码中,您不必分发、安装或注册任何外部文件即可使用控件。OCX版本相对于StdExE版本的主要优点是a)程序的编译时间几乎快10倍,因为每次不需要重新编译窗体代码,b)构成每个控件的各种.BAS、.CTL、.PAG文件不会使程序员的文件列表变得混乱。 **ComCtlsDemo** - 这是一个展示Krool每个控件的示例程序。这个文件会定期更新,总是可以在VBForums上[这个](http://www.vbforums.com/showthread.php?698563-CommonControls-\(Replacement-of-the-MS-common-controls\))主题的第一个帖子底部找到。这个包使用StdEXE概念,将所有控件的代码编译到可执行文件中。 这不仅仅是一个示例文件。这个文件中的源代码就是他的包的全部内容,当您制作自己的使用他的控件的程序时,您将使用它(或其中的大部分)。 它不像OCX版本那样需要版本号,因为没有文件需要在开发人员或用户的PC上注册(它是每次编译程序时都要嵌入的源代码)。我下载了大多数更新,为了避免混淆,我将每个.zip文件重命名为我硬盘上带有文件日期的文件名。由于VBForum的大小限制,他发布的文件带有.docx扩展名,但它实际上是一个.zip文件,所以当您下载它时,您要执行另存为并删除文件名中的.docx。在撰写本文时,Krool发布的最新版本是2018年11月11日(看看帖子底部下载链接下方的小斜体行),要下载的文件名为ComCtlsDemo.zip.docx,所以当我下载该文件时,我在我的硬盘上将其重命名为ComCtlsDemo 2018-11-11.zip。 **VBCCR OCX版本** - 在只有StdEXE版本大约4年之后,Krool发布了一个名为VBCCRxx.OCX的预编译版本,其中xx是版本号。最早的版本是1.1,所以第一个文件是VBCCR11.ocx。截至本文撰写时,最新版本是1.6.13,所以文件是VBCCR16.ocx。最新版本总是在VBForums上[这个](http://www.vbforums.com/showthread.php?841929-VB6-ActiveX-CommonControls-%28Replacement-of-the-MS-common-controls%29\&p=5129155#post5129155)主题的第1个帖子底部。在线.zip文件包含.ocx文件以及一些资源文件(下面讨论),这些文件与程序员的EXE文件的"并排"执行以及使您的程序主题化(这样您在屏幕上显示的内容看起来不像来自Windows 95)有关。我保存.zip文件时将其重命名以包含版本号。例如,最新的一个叫做'VBCCR16.OCX.rar.docx'被复制到我的硬盘上,名为'VBCCR.OCX v1.6.13.rar'(请参见上面关于为什么文件带有.docx扩展名的说明)。除了包含.ocx文件外,.zip文件还包含所有代码,以防您想要制作自己的.ocx文件(不推荐)或只是从Krool所做的工作中学习。 将.ocx文件复制到Windows系统文件夹中。如果运行32位Windows,这通常是C:\Windows\System32,但如果运行64位Windows,那么所有64位DLL、类型库和控件都进入system32文件夹(?),因此Microsoft将所有32位文件放入名为'SysWOW64'(**W**indows 32-bit **O**n **W**indows **64**-bit)的文件夹中。(如果您将Windows放在C:\Windows以外的位置,那么请使用该路径)。由于您要复制到系统文件夹,因此需要提升权限。如果xx相同(在我的示例中xx是16,所以我可以覆盖1.6.12或1.6.11版本),那么可以覆盖以前的版本,如果xx是新的(如1.6.0版本),那么没有覆盖,但您应该使用regsvr32向系统注册此控件。 在VB6 IDE中使用Ctrl-T(或Project|Components)并选择适当的控件,将此OCX文件加载到您的项目中。对于1.6版本,您需要通过单击旁边的复选标记来选择'VB Common Controls Replacement 1.6 Library'。 通过引用此OCX,所有控件都将显示在工具箱中,供您像使用可以放在窗体上的任何其他控件一样使用。因为控件的.OCX版本是预编译的,所以控件不会像使用StdEXE版本那样在每次编译程序时编译,在StdEXE版本中,控件会嵌入到您的代码中。另一方面,缺点是.OCX文件必须随EXE或DLL文件一起分发,因为它没有编译到其中。 **Type Library(类型库)** - 要在StdEXE版本(不是OCX版本)中使用Krool的VBCCR和VBFlexGrid控件,您需要使用他提供的名为'OLEGuids.tlb'的类型库,该库在他随每个控件包分发的'OLDGuids'文件夹中。我将oleguids.tlb复制到我的系统目录中,然后可以使用Project|References通过单击'OLE Guid and interface definitions'旁边的复选框来指定它。他目前分发的文件带有2017年6月9日的日期戳,所以它已经有一段时间没有改变了。此文件仅在使用StdEXE版本进行代码开发时才需要。它不需要与最终编译的程序一起分发。(注意-如果您在VBA中使用Krool的控件,则***不***需要此文件,因为您必须使用已经将此类型库编译到其中的OCX版本。) **Visual Styles(视觉样式)(主题)** - 这从XP就开始了,但直到Vista及以后才真正得到广泛使用。使用视觉样式,您可以获得更现代的窗体外观,但由于这些样式是在VB6推出之后才流行起来的,所以在VB6程序中使用它们并没有简单的方法。Krool的代码设置为使用这些视觉样式,但如果没有几个有趣的步骤,您将无法获得它们。无论如何,他的代码与原始控件相比提供了Unicode和一些增强功能,但要获得视觉样式,您必须在清单中指定这一点,然后将清单嵌入到程序引用的资源文件中。这听起来比实际操作要难,我稍后会介绍如何做到这一点。(注意- VBA不支持样式) **Side-by-Side Assemblies(并排程序集)** - 如果您的程序需要DLL或OCX文件才能运行,它可以使用已经存在于用户系统上、已注册且版本正确的文件。从VB6发布时起,就有一个运动要摆脱这个系统,以避免许多人称之为"DLL地狱"的情况(谷歌一下这个词会很有趣)。长话短说,Windows允许程序在不必注册支持文件的情况下运行,只要支持文件位于EXE或DLL文件旁边(或其子文件夹中)即可。许多企业用户通过阻止注册这些支持文件来设置他们的PC不允许安装任何新程序,这是一种解决方法。为了指定支持文件是并排的,您必须在清单中指定这一点(见下文)。以前,将清单放在可执行文件的同一文件夹中或嵌入到文件中是可以的,但后来的Windows版本强烈建议将清单文件包含在资源文件中。这一切听起来很疯狂,但Krool为所有的复杂性提供了一些支持,而我的工具(希望)可以消除其余部分的痛苦。 **Manifest File(清单文件)** - 清单文件基于XML,可以为Windows指定许多要执行的事情来控制程序。一个例子是,您可以在清单中指定程序需要以提升的权限运行。但是,对于我们的情况,清单文件有两个用途:1)我们可以告诉Windows我们想要使用Microsoft的CommonControls dll文件的6.0版本,这是使用Krool代码给我们视觉样式的版本,2)我们可以给出信息,使OCX文件(如果您使用它而不是StdEXE版本)与您将制作的可执行文件并排。这本身就够糟糕的,但Windows现在希望这个清单文件包含在程序的资源文件中。 **Resource File(资源文件)** - 您可以将许多内容放入VB6资源文件(扩展名.RES)中,包括图标、图形图像、国际化字符串等。您还可以放入清单文件,而且您会这样做以获得视觉样式和/或并排功能。Krool在OCX版本中提供了两个资源文件,一个仅用于并排,一个用于并排加视觉样式。在StdEXE包中,Resources文件夹中有一个提供视觉样式的资源文件(如果不使用.OCX版本,则不需要并排)。一个名叫LaVolpe的用户在VBForums上有一个工具([这里](http://www.vbforums.com/showthread.php?845909-VB6-Manifest-Creator-II)),使您能够从资源文件中提取清单信息,编辑它,然后把它放回去。希望您不必使用该工具(我在我的工具中使用了LaVolpe代码的一部分,稍后会讨论)。在这里定义它的要点是确保程序员知道并排和视觉样式需要指定资源文件,而资源文件需要在内部指定这些。 **Windows System Folder(Windows系统文件夹)** - Windows系统文件夹包含许多系统相关文件,包括DLL、类型库、注册控件等。对于32位VB6和32位VBA,此文件夹可以是两个中的一个。如果您使用32位操作系统,此文件夹将是'C:\Windows\System32'。不幸的是,如果您使用64位Windows操作系统,所有64位DLL、类型库和控件都进入system32文件夹(?),因此Microsoft将所有32位文件放入名为'SysWOW64'(**W**indows 32-bit **O**n **W**indows **64**-bit)的文件夹中。所有32位文件都进入'C:\Windows\SysWOW64'。 如果您在64位VBA中使用所有这些,您只会处理64位Windows文件夹,该文件夹始终是'C:\Windows\System32'。 **VBFlexGrid** - Krool的原始控件包括35个控件,但不包括MSFlexGrid控件的替代品(Microsoft提供了一个MSFLXGRD.OCX文件,Krool的包对其进行了升级和替换)。他采取的方法与他对其他控件所做的非常相似。有独立版本,就像VBCCR ComCtlsDemo包一样,这个叫做VBFlexGridDemo,可以在[这里](http://www.vbforums.com/showthread.php?848839-VBFlexGrid-Control-\(Replacement-of-the-MSFlexGrid-control\))找到,以及它对应的OCX版本,VBFLXGRD12.OCX,可以在[这里](http://www.vbforums.com/showthread.php?855931-VB6-ActiveX-VBFlexGrid-%28Replacement-of-the-MSFlexGrid-control%29\&p=5236525#post5236525)找到。这两个版本都独立于VBCCRxx控件。我的工具将这些和VBCCR控件视为同一个包的一部分来处理。 ## 程序员用户指南 下面是每个版本的使用说明。之后是我推荐的使用方法的讨论,这是每个选项的简单混合,它(希望)利用了每个选项的最佳功能,然后还有一些其他功能。 VBCCR - 这组33个控件(除了最后一个之外的表中的所有控件)存在两个版本。到目前为止,程序员必须决定是使用StdEXE还是OCX版本;没有办法同时使用这两个版本。在介绍两个版本的用户指南之后,我将向您展示另一种希望更好的使用这些控件的方法,这样您就可以利用OCX版本更简单和更快的开发优势,同时用StdEXE版本生产最终的可执行文件,使控件成为您控制代码的一部分。 ### VBCCR - StdEXE版本 这是将所有控件代码编译到程序中的版本。您将在程序中包含适当的源代码,当您编译时,控件成为程序的一部分。 获取最新版本 - 您可能会认为有一个可下载的包,其中包含所有控件、用户指南等,但事实并非如此。Krool在VBForums网站上有一个演示项目,从中您可以访问他的所有控件(有趣的方法,但它确实有效)。Krool的演示项目和所有控件从2012年11月10日起就在[这里](http://www.vbforums.com/showthread.php?698563-CommonControls-\(Replacement-of-the-MS-common-controls\))。该主题中有超过78页的评论和讨论。大多数涉及各种错误、用户问题和功能添加请求,因为Krool在过去9年中一直在处理这个包。 重要的是,在第一个帖子的底部有一个名为'**ComCtlsDemo.zip.docx**'的可下载文件,这始终是要下载的最新版本。它具有.DOCX扩展名,因为VBForums对.ZIP文件的大小限制比.DOCX文件低,而此文件超过了.ZIP文件的大小限制。它实际上是一个.ZIP文件,所以当您下载它时(或之后),通过去掉名称的.DOCX部分来重命名它,留下文件ComCtlsDemo.zip。 这个文件在网站上的名称始终相同。我建议您查看第一个帖子的最后一行并注意日期,然后将日期放在文件名中。例如,我正在查看第一个帖子,在底部它说Krool在2018年11月11日最后编辑,所以当我右键单击链接时,我告诉它将其保存到一组我保存所有下载存档文件的文件夹中,我用名称'**ComCtlsDemo 2018-11-11.zip**'保存它,这样我就可以将其与之前下载的副本区分开。 现在有一个重要的观察。ComCtlsDemo包含所有控件文件,这些文件不应该被更改,所以您可以将这些文件放在所有程序都可以访问的中心位置(一个库)。这个位置不需要改变,您总是可以删除现有文件并将最新版本的文件放在相同的文件夹中。此外,您的所有程序都可以在它们所在的位置访问所有这些文件,因此您不需要将所有这些文件复制到您的个人项目文件夹中。这大大简化了使用和更新较新版本的过程。 解压时将下载的文件放在哪里 - 我有一个库文件夹,我将各种可在程序中使用的文件放在其中。我不会在这里放置会更改的文件。这包含我可以在所有程序中使用的文件,而不需要修改。在我的Library文件夹中,我有一个用于Controls & Forms的子文件夹。在其中,我有一个名为VBCCR的文件夹,用于Krool的控件,在其中我创建了一个名为'Current'的子文件夹。每当我从Krool下载最新更新时,我首先删除Current中的所有文件和文件夹,然后将新文件解压到Current中。这很重要,因为已经使用这些控件的程序将继续在相同的位置找到这些控件,甚至不知道它们是新版本。幸运的是,Krool在调试和添加控件功能时保持他的文件和文件夹名称相同。 所以现在我们在PC上的一个位置有了文件,我们可以将它们用于所有程序,我们就可以开始使用它们了。对吗?嗯,差不多。为了使用他的控件,还需要采取一些额外的步骤。请按照以下步骤操作,以创建或修改任何程序。 类型库 - 您需要能够访问一个名为'OLEGuids.tlb'的类型库,该库包含在Krool的示例程序中。这个文件在Current的一个名为'OLEGuids'的子文件夹中。在编辑和编译期间您需要这个文件,但您编译的程序不需要它,您也不用将它与可执行文件一起分发。我将我的放入Windows系统文件夹中,这样我总是知道它在哪里,我在Windows 10中用regsvr32注册它。幸运的是,这个类型库文件不经常更改,所以您不必经常执行此步骤。OLEGuids.tlb的日期是2017年6月9日,所以18个月来它没有改变。 在VB6中,您将使用Project | References命令来选择这个类型库。如果您已经使用regsvr32注册了这个文件,那么您可以在Available References列表中找到名为'OLE Guid and interface definitions'的文件,但如果您还没有注册它,您可以单击'Browse'并找到它。 视觉样式 - 为了在程序中使用视觉样式(主题),使它们看起来不像旧的Windows程序,您必须指定使用Windows Common Controls库版本6.0,因为它支持视觉样式。实现这一点的方法是在清单文件中包含这个规范。过去,您制作一个包含可执行文件名称且扩展名为'.Manifest'的文件,当分发程序时,您将此文件包含在与可执行文件相同的文件夹中。后来的Windows版本不鼓励这样做,而是建议将清单作为嵌入资源文件的一部分包含在EXE文件中。VB6可以使用资源文件来保存许多不同的内容,如国际化字符串、图标等,除了清单之外。 所以我们必须将视觉样式规范放入清单中,然后将清单文件放入VB6资源文件中。在Krool的包中,查看Current\Resources中名为'Resources.res'的文件,这是Krool制作的包含启用视觉样式(或主题)指令的资源文件。如果您没有将资源文件用于其他任何内容,您可以简单地将这个Resources.res文件复制到项目文件(.VBP)所在的位置。稍后我会向您展示如何将其嵌入到您的项目中。但现在让我们考虑一下如果您已经有一个资源文件,我们想要将我们的清单信息添加到该资源文件中(无论它是否已经包含清单信息)该怎么办。 请注意,VB6 IDE并不是为了使用视觉样式而设计的。[这里](http://www.vbforums.com/showthread.php?693111-VB6-IDE-solving-UAC-and-Visual-Style-issues\&highlight=)是Krool在VBForums上的一个帖子,展示了如何获取带有嵌入清单的资源文件,该文件将以提升的UAC运行VB6,同时合并视觉样式。您不需要这个来使用Krool的控件,但如果您想看到"更漂亮的"窗体,那么这对您可能有价值。请注意,它涉及使用另一个名为ResourceHacker的工具将资源文件放入VB6.EXE文件中。 一个更简单的方法是从[这里](http://www.vbaccelerator.com/home/VB/Code/Libraries/XP_Visual_Styles/Using_XP_Visual_Styles_in_VB/article.asp)获取vb6.exe.manifest文件,并将其放入与vb6相同的文件夹中(通常是C:\Program Files (x86)\Microsoft Visual Studio\VB98)。 关于在程序中使用视觉样式,我觉得很奇怪的是使用视觉样式的说明是清单文件的一部分,我们必须将其嵌入到资源文件中,然后将其嵌入到我们的可执行文件中。Krool在Current下的Resources文件夹中提供了一个带有视觉样式的资源文件,您可以将其复制到您的项目中并嵌入。 高级资源/清单/视觉样式注意事项 - 您可能希望在资源文件中添加视觉样式设置之外的其他内容。处理这些文件并不是一件小事。清单部分是XML,它包含在非XML资源文件中。我在VBForums上发现了另一个由名为LaVolpe的用户提供的工具([这里](http://www.vbforums.com/showthread.php?845909-VB6-Manifest-Creator-II)),让我们可以从头开始或从清单文件中创建或编辑清单,或从资源文件中提取,这样我们就可以编辑它,然后我们可以指定将其放入资源文件中。下面是LaVolpe的工具运行时加载Resources.res的屏幕截图。我突出显示了指定使用Windows Common Controls版本6.0.0.0的部分。这就是指定视觉样式的内容。通常对于新程序,您应该能够只将Resources.res复制到您的项目文件夹并使用它,而无需编辑它。顺便说一句,您不*需要*这个文件,但如果没有它,您的程序中将不会获得任何现代外观的控件。 所以现在您有了一个指定使用视觉样式的资源文件。我们如何将它放入我们的项目中?在VB6中,转到AddIns | AddIn Manager,您将看到类似以下内容。 选择'VB6 Resource Editor',并确保'Loaded/Unloaded'和'Load On Startup'都被选中。然后,回到您的主项目,转到Project | Add New Resource File,然后从弹出的对话框中选择您的.res文件。现在您的资源文件应该在导航窗格中的Related Documents下显示出来。 Side-by-Side(并排) - 使用StdEXE版本的一个原因是,除非您使用其他专门的控件或其他文件,否则您的可执行文件没有依赖项,因此无需担心并排。我将在OCX版本的用户指南中详细讨论它。 要包含在您的项目中的文件 - 每个控件都有一些特定于该控件的文件,需要如下所示插入到您的项目中。 | **控件** | **Current文件夹中的文件** | | --- | --- | | Animation(动画) | Builds\Animation\Animation.ctl | | | Builds\Animation\PPAnimationGeneral.pag | | CheckBoxW(复选框) | Builds\CheckBoxW\CheckBoxW.ctl | | ComboBoxW(组合框) | Builds\ComboBoxW\ComboBoxW.ctl | | CommandButtonW(命令按钮) | Builds\CommandButtonW\CommandButtonW.ctl | | CommandLink(命令链接) | Builds\CommandLink\CommandLink.ctl | | | Builds\CommandLink\PPCommandLinkGeneral.pag | | CoolBar(冷工具栏) | Builds\CoolBar\CbrBand.cls | | | Builds\CoolBar\CbrBandProperties.cls | | | Builds\CoolBar\CbrBands.cls | | | Builds\CoolBar\CoolBar.ctl | | | Builds\CoolBar\PPCoolBarBands.pag | | | Builds\CoolBar\PPCoolBarGeneral.pag | | DTPicker(日期时间选择器) | Builds\DTPicker\DTPicker.ctl | | | Builds\DTPicker\PPDTPickerGeneral.pag | | FontCombo(字体组合框) | Builds\FontCombo\FontCombo.ctl | | FrameW(框架) | Builds\FrameW\FrameW.ctl | | HotKey(热键) | Builds\HotKey\HotKey.ctl | | ImageCombo(图像组合框) | Builds\ImageCombo\ImageCombo.ctl | | | Builds\ImageCombo\ImcComboItem.cls | | | Builds\ImageCombo\ImcComboItems.cls | | | Builds\ImageCombo\PPImageComboGeneral.pag | | ImageList(图像列表) | Builds\ImageList\ImageList.ctl | | | Builds\ImageList\ImlListImage.cls | | | Builds\ImageList\ImlListImages.cls | | | Builds\ImageList\PPImageListGeneral.pag | | | Builds\ImageList\PPImageListImages.pag | | IPAddress(IP地址) | Builds\IPAddress\IPAddress.ctl | | LabelW(标签) | Builds\LabelW\LabelW.ctl | | LinkLabel(链接标签) | Builds\LinkLabel\LinkLabel.ctl | | | Builds\LinkLabel\LlbLink.cls | | | Builds\LinkLabel\LlbLinks.cls | | | Builds\LinkLabel\PPLinkLabelGeneral.pag | | ListBoxW(列表框) | Builds\ListBoxW\ListBoxW.ctl | | ListView(列表视图) | Builds\ListView\ListView.ctl | | | Builds\ListView\LvwColumnHeader.cls | | | Builds\ListView\LvwColumnHeaders.cls | | | Builds\ListView\LvwGroup.cls | | | Builds\ListView\LvwGroups.cls | | | Builds\ListView\LvwListItem.cls | | | Builds\ListView\LvwListItems.cls | | | Builds\ListView\LvwListSubItem.cls | | | Builds\ListView\LvwListSubItems.cls | | | Builds\ListView\LvwVirtualListItem.cls | | | Builds\ListView\LvwVirtualListItems.cls | | | Builds\ListView\PPListViewGeneral.pag | | | Builds\ListView\PPListViewImageLists.pag | | | Builds\ListView\PPListViewSorting.pag | | MCIWnd(多媒体窗口) | Builds\MCIWnd\MCIWnd.ctl | | MonthView(月历) | Builds\MonthView\MonthView.ctl | | | Builds\MonthView\PPMonthViewGeneral.pag | | OptionButtonW(选项按钮) | Builds\OptionButtonW\OptionButtonW.ctl | | Pager(分页器) | Builds\Pager\Pager.ctl | | | Builds\Pager\PPPagerGeneral.pag | | ProgressBar(进度条) | Builds\ProgressBar\PPProgressBarGeneral.pag | | | Builds\ProgressBar\ProgressBar.ctl | | RichTextBox(富文本框) | Builds\RichTextBox\PPRichTextBoxGeneral.pag | | | Builds\RichTextBox\RichTextBox.ctl | | | Builds\RichTextBox\RichTextBoxBase.bas | | Slider(滑块) | Builds\Slider\PPSliderAppearance.pag | | | Builds\Slider\PPSliderGeneral.pag | | | Builds\Slider\Slider.ctl | | SpinBox(数值调节器) | Builds\SpinBox\PPSpinBoxGeneral.pag | | | Builds\SpinBox\SpinBox.ctl | | StatusBar(状态栏) | Builds\StatusBar\PPStatusBarGeneral.pag | | | Builds\StatusBar\PPStatusBarPanels.pag | | | Builds\StatusBar\SbrPanel.cls | | | Builds\StatusBar\SbrPanelProperties.cls | | | Builds\StatusBar\SbrPanels.cls | | | Builds\StatusBar\StatusBar.ctl | | SysInfo(系统信息) | Builds\SysInfo\SysInfo.ctl | | TabStrip(标签条) | Builds\TabStrip\PPTabStripGeneral.pag | | | Builds\TabStrip\PPTabStripTabs.pag | | | Builds\TabStrip\TabStrip.ctl | | | Builds\TabStrip\TbsTab.cls | | | Builds\TabStrip\TbsTabs.cls | | TextBoxW(文本框) | Builds\TextBoxW\PPTextBoxWText.pag | | | Builds\TextBoxW\TextBoxW.ctl | | ToolBar(工具栏) | Builds\ToolBar\PPToolBarButtons.pag | | | Builds\ToolBar\PPToolBarGeneral.pag | | | Builds\ToolBar\TbrButton.cls | | | Builds\ToolBar\TbrButtonMenu.cls | | | Builds\ToolBar\TbrButtonMenus.cls | | | Builds\ToolBar\TbrButtonProperties.cls | | | Builds\ToolBar\TbrButtons.cls | | | Builds\ToolBar\ToolBar.ctl | | TreeView(树形视图) | Builds\TreeView\PPTreeViewGeneral.pag | | | Builds\TreeView\TreeView.ctl | | | Builds\TreeView\TvwNode.cls | | | Builds\TreeView\TvwNodes.cls | | UpDown(上下调节器) | Builds\UpDown\PPUpDownGeneral.pag | | | Builds\UpDown\UpDown.ctl | | VirtualCombo(虚拟组合框) (2020年8月15日或之后) | Builds\VirtualCombo.ctl Builds\VirtualCombo.ctx Builds\VirtualComboBase.bas | | VListBox(虚拟列表框) (2020年8月15日或之后) | Builds\VListBox\VListBox.ctl Buids\VListBox\VListBox.ctx | 如果您希望任何单个控件在项目中可用,在IDE中按Ctrl-D,然后导航到适当的文件夹并突出显示要导入的文件夹中的所有文件,然后按Enter。 一个挑战是Krool的包包含所有控件,而您不太可能需要所有控件。演示程序利用了所有控件,由此产生的EXE文件大小为4.2 MB,因此如果您在程序中包含所有控件,将增加大约4 MB的文件大小。在这些多千兆字节RAM和硬盘的日子里,这可能不像以前那样重要。 还有一些文件,无论您使用一个控件还是所有控件都必须存在。这些是: | | | --- | | Builds\ComCtlsBase.bas | | Builds\VTableHandle.bas | | Builds\VTableSubclass.cls (仅限2020年1月5日之前) | | Builds\ISubclass.cls | | Common\Common.bas | | Common\VisualStyles.bas | 最后,如果您使用MCIWnd.ctl控件或CoolBar、Imagelist、RichTextBox或StatusBar的属性页,您还必须在项目中包含文件'Builds\CommonDialog.cls'。 您可能会倾向于不包含您不使用的控件的代码。您确实可以在最终可执行文件中节省一些大小,但要知道,如果不包含上述控件的代码,这些控件甚至不会出现在工具箱中供可能使用。如果您确定不会使用给定的控件,可以将其排除。每个控件都独立于其他控件。 Krool的ComCtlsDemo包中还有一个文件,Common\Startup.bas,这实际上是用于演示程序的。您不需要这个文件,但该文件中的一些概念需要成为您程序的一部分。 Sub Main - Krool的控件依赖于一些Microsoft代码,这些代码需要在加载或显示任何窗体之前运行。要使用新控件,您必须将启动对象指定为Sub Main而不是任何Form,并且必须在引用任何控件之前在Sub main中有正确的启动代码。这在General选项卡的Project | Properties中设置。如果您没有名为Main的Sub中的启动例程,则需要在程序中放入一个。 您需要调用Krool的一个例程,为他的程序中内置的回调等提供保护,这样您就不会在IDE中崩溃。此外,您的程序需要一些启动代码才能使用通过使用Microsoft的Common Controls 6.0启用的视觉样式。因此,Sub Main中的前两行应该是: ```vb Call ComCtlsInitIDEStopProtection ' 在Builds\ComCtlsBase.bas中 ' 以上仅在使用2020年8月13日之前的Krool包时需要) Call InitVisualStyles ' 在Common\VisualStyles.bas中 ``` 现在您可以放入其余的代码来显示窗体、进行计算等。除非您使用其他.OCX控件文件,否则您的最终可执行文件将包含所有代码,包括控件,因此可执行文件是独立的,除了Microsoft随Windows提供的标准VB6支持文件外,不需要任何其他内容。 您可能会遇到子例程和变量的名称与您使用的名称相同的问题。如果您使用控件的.OCX版本,大多数这些都是隐藏的,不是问题。然而,当您在程序中包含所有各种控件文件以在程序中编译时,您现在有153个新文件,并且可能有一些命名冲突。如果您决定保留您的名称并更改Krool的名称,只需知道每次下载和使用更新时,您都必须编辑他的文件来重命名这些(不仅仅是子例程的名称,还有调用它的每个其他例程)。我不情愿地决定更改我代码中的一些冲突名称,这样我就不必不断更新他的文件。我不喜欢这样,但这是使用这些控件的一个小代价。 注意 - 我不使用上述方法,因为我不喜欢长时间的编译,尽管我确实喜欢完全独立的可执行文件。这就是我编写后面要讨论的工具的部分原因。它允许您使用.OCX版本进行开发(编译速度快得多),然后通过我的工具使用StdEXE版本进行最终编译,这样您就有了独立的可执行文件。 ### VBCCR OCX 版本指南 Krool 提供了 VBCCR 控件的预编译 OCX 版本,等价于 StdEXE 包,但更符合传统 ActiveX 控件的使用方式。你可以在 [这里](http://www.vbforums.com/showthread.php?841929-VB6-ActiveX-CommonControls-%28Replacement-of-the-MS-common-controls%29\&p=5129155#post5129155) 下载。与 StdEXE 版本相比,OCX 版本的优点有:1)只需一个 .OCX 文件而不是 153 个单独文件,使用更简单;2)编译速度更快,因为 OCX 已经预编译好;3)大多数程序员都熟悉 OCX 控件的用法。缺点是:1)OCX 文件需要和可执行文件一起分发给用户;2)OCX 文件必须在用户电脑上注册,或者采用更复杂的并排(side-by-side)方案。 获取最新版——从上述链接进入,下载首帖底部的文件。目前控件的 OCX 版本为 1.6,下载文件名通常为“VBCCR16.OCX.rar.docx”。由于 VBForums 限制,文件扩展名为 .docx,实际上是 RAR 压缩包。建议下载时将文件重命名为如“VBCCR16.OCX v1.6.13.rar”,方便管理不同版本。解压后可获得 .OCX 文件和包含源代码的 zip 文件(不建议自行编译 OCX,否则会与 Krool 官方包分离,内容与 StdEXE 版本类似)。 在程序中使用——在新建程序中,按 Ctrl-T 或通过 Project | Components,选择“VB Common Controls Replacement 1.6 Library”(即 vbccr16.ocx 文件)。在 VBA 项目中,可通过“工具 | 其他控件”添加。 最后,你需要设置包含清单(manifest)的资源文件,以启用视觉样式和可选的并排功能(仅 VB6,VBA 不适用)。VBForums 首帖还提供了两个资源文件:“VBCCR16SideBySide.res”和“VBCCR16SideBySideAndVisualStyles.res”,分别用于并排和并排+视觉样式。这些文件无需解压,直接保存使用即可。后文会介绍如何使用这些资源文件。 项目设置——与 StdEXE 版本一样,程序启动不能直接用窗体,必须先用 Sub Main 作为入口,以便在调用第一个窗体前运行必要的初始化代码。最简单的做法是从 StdEXE 包中包含 VisualStyles.bas 模块,然后在 Project | Properties 的 General 选项卡中设置启动对象为 Sub Main,并在 Sub Main 中,在加载、引用或显示任何窗体前加入如下代码: ```vb InitVisualStyles ``` 这样就可以正常使用所有控件,控件会出现在工具箱中,供窗体使用。 注意:StdEXE 版本中 Krool 提供了 IDE 崩溃保护代码,OCX 版本同样需要这些保护,但已编译进 OCX 文件,无需手动调用。 编译代码——只需确保 Sub Main 中有上述初始化过程即可。Krool 声称其代码 IDE 安全,实际使用中也确实如此。 你可以选择使用清单文件来指定两个常用功能:一是启用主题/视觉样式(Krool 的控件已内置支持,配置简单);二是指定“并排程序集”。通常,ActiveX 控件和 DLL 需要注册到系统目录,但有些组织不允许注册外部依赖。自 VB6 时代起,Windows 支持通过清单文件让 OCX/DLL 与程序放在同一目录,无需注册即可使用。虽然不如 StdEXE 版本将代码直接嵌入程序那样彻底无依赖,但已是次优选择。 清单文件还可以包含其他内容,但本用户指南只关注对 Krool 控件包有影响的两项。过去,您可以将清单文件与 EXE 文件放在一起分发给用户,但新版 Windows 更推荐将清单嵌入到程序内部。实际上,清单是通过资源文件(resource file)嵌入的,这也是 VB6 等多种编程语言的常用做法。 清单文件是 XML 格式,并且文件大小必须正好是 4 的倍数。幸运的是,Krool 已经提供了两个资源文件(前文已介绍),可以直接包含到您的程序中。一个用于并排(side-by-side),另一个用于启用视觉样式和并排。例如,假设您从 Krool 网站下载了 `VBCCR16SideBySideAndVisualStyles.res` 文件并希望使用它。显然,这个文件同时支持视觉样式和并排。您无需编辑此文件,只需在项目中引用即可。 注意:资源文件可以放在公共位置,作为多个程序共享的库文件。但如果您修改了该文件,所有引用它的程序都会受到影响。如果担心这一点,可以将资源文件复制到项目文件夹(即 .vbp 文件所在的文件夹)并单独引用。 那么,如何将资源文件添加到项目中?在 VB6 中,依次点击菜单 AddIns | AddIn Manager,您会看到如下界面: 选择“VB6 Resource Editor”,确保“Loaded/Unloaded”和“Load On Startup”都已勾选。然后回到主项目,点击 Project | Add New Resource File,从弹出的对话框中选择您的 .res 文件。此时,资源文件会显示在导航窗格的 Related Documents 下方。 现在,您就可以编译并使用您的程序了。 关于 EXE 或 DLL 的分发:由于清单已嵌入资源文件,无需再单独分发清单文件。 您需要将 VBCCRxx.OCX 文件与程序一起分发。如果采用并排方式,只需将 OCX 文件放在 EXE 文件同一目录或其子目录下。请注意,采用并排时,Windows 会优先在可执行文件所在目录查找 OCX 文件,即使您已将其复制到系统目录并注册(实际测试如此)。因此建议不要将 OCX 文件从系统目录移走,而是在 EXE 所在目录再复制一份。建议在采用并排前先参考我的工具。我的方案是:开发阶段使用 OCX 版本控件,最终用工具命令行编译为 StdEXE 版本,这样无需任何并排方案,所有代码都嵌入到可执行文件中(仅限 Krool 控件;如果用到其他人的 OCX 控件,仍可采用并排方式)。 如果不采用并排,开发机上已注册 OCX 文件无需额外操作,但分发时需让安装程序将 OCX 文件复制到用户系统目录并注册。 ### VBFlexGrid 用户指南 Krool 的 MSFlexGrid 替代控件包与前述 33 个 Common Controls 替代控件几乎完全一致。由于该控件发布较晚,Krool 将其单独分离。未来可能会合并,但目前请将 VBFLXGRD 理解为和 VBCCR 类似,只是它只有一个控件。 StdEXE 版本可在 VBForums [这里](http://www.vbforums.com/showthread.php?848839-VBFlexGrid-Control-\(Replacement-of-the-MSFlexGrid-control\)) 下载,OCX 版本在 [这里](http://www.vbforums.com/showthread.php?855931-VB6-ActiveX-VBFlexGrid-%28Replacement-of-the-MSFlexGrid-control%29\&p=5236525#post5236525)。所有与 VBCCR 相关的问题在 FlexGrid 控件上同样适用。 我的工具可以帮助您无缝管理这两类控件。 ### VBA 使用说明 VBCCR 和 VBFLXGRD 控件的 StdEXE 版本无法在 VBA 中使用,因为 VBA 不允许将控件直接嵌入代码。VBA 只能使用 ActiveX 控件(即 OCX 版本)。 OCX 版本可以在 VBA 中正常使用。类型库无需单独引用,因为已编译进 OCX 文件。每位用户都需在其电脑上注册 OCX 文件,并在 VBA 项目中引用。 另外,VBA 不支持视觉样式,因此该功能不可用。如果您的 VBA 窗体外观较旧,这些控件无法改善。 这些控件可为 VBA 用户带来 Unicode 支持(尽管近年来很多 VBA 控件本身已支持 Unicode 显示,但设计时属性仍不支持 Unicode)。注意,这不会让 VBA 的代码编辑器支持 Unicode,编辑器始终是 ANSI。最后,Krool 的控件功能通常比微软自带控件更强大,这对 VBA 用户是个优势。 ## OCX2StdExe 工具 我在实际使用中总结了如何高效管理这些控件,避免混乱并提升开发效率。常见痛点包括: * StdEXE 版本可生成无依赖的独立可执行文件,但编译速度很慢。 * OCX 版本编译速度快,但每个可执行文件都要分发和注册 OCX。 * OCX 包更新频繁,带来大量 bug 修复和新功能,但每次升级都很麻烦。每个项目都要手动查找和替换 .vbp、窗体、资源文件中的 OCX 名称和 GUID,非常繁琐。 * Krool 的 OCX 包没有示例文件,如何让 OCX 版本支持视觉样式并不直观,即使清单/资源文件已引用,仍需初始化代码(OCX 包未包含,可从 StdEXE 版本提取)。 * 我有很多自定义初始化代码,不希望与 Krool 的代码混在一起。 为此,我写了一个 VB6 工具来统一管理这些问题: * 开发阶段使用 OCX 版本,因其简单(1 个文件而非 153 个),编译速度快。 * 可同时支持 VBCCRxx.OCX 和 VBFLXGRDxx.OCX。我的工具将两者视为同一类控件包(预计未来 Krool 也会合并)。 * 每当有新版本发布,只需下载、复制到系统目录并注册。如果覆盖同名旧文件(如 VBCCR17.OCX),无需额外操作;如果是跨版本升级(如 1.6 升级到 1.7),可用本工具自动升级项目引用,自动修改 .vbp、窗体、资源文件中的所有相关内容。所有原始文件会备份,便于回退(不推荐)。工具也支持降级到旧版本(如 1.7 降到 1.1)。 * 项目开发和维护流程与普通 OCX 控件项目一致。需要生成无依赖单文件时,可用工具切换为 StdEXE 版本命令行编译,生成独立可执行文件,且不会修改原始文件。只需一次慢编译即可。 * 使用 StdEXE 命令行编译时,最终 EXE 只包含实际用到的控件,体积更小。原始文件不变,工具会生成临时文件,引用 StdEXE 控件(153 个文件),而不是单一 OCX。可选择保留这些临时文件(文件名与 OCX 版本不同),便于后续重新编译。属性页文件可选不包含,进一步减小 EXE 体积(命令行编译不需要属性页,IDE 才需要)。 * 工具还可自动在项目目录下创建 StdExe 子文件夹,便于管理和编译。 这个工具(希望)易于使用。本文档涵盖了为VB6编写的工具版本;如果您愿意,还有一个几乎相同的Excel版本。Excel版本与VB6版本一起包含在包中。以下是VB6版本的屏幕截图。在窗体顶部是要更新或编译的VB6项目文件。您可以在文本框中输入路径,或单击左侧的按钮搜索它。项目文件需要是使用Krool控件的OCX版本(任一版本或两者)的项目。OCX版本有版本号,从一个版本更改到较新版本并不简单,因为要使用的OCX文件的引用嵌入在使用控件的窗体代码、资源文件(如果有嵌入的清单)和项目文件本身中。如果您指定的项目文件是不使用Krool控件或使用StdEXE版本的项目,那么您将无法执行OCX升级或命令行编译。 **更新OCX引用** 我们的窗体会告诉您在项目中使用的VBCCRxx.OCX和/或VBFLXGRD.OCX的当前版本。上面的示例显示指定的项目正在使用VBCCR15.OCX和VBFLXGRD12.OCX。它还显示您在运行此工具的PC上安装的每个版本,默认为最新版本。在上面的示例中,显示的是VBCCR17.OCX和VBFLXGRD14.OCX,这是本文档编写时的最新可用版本。虽然从图片中看不到,但下拉列表也包含一些早期版本。 升级后您可以选择保留或删除旧版本文件。通常您不需要保留旧文件,但如果选择保留,可以在与新文件相同的文件夹中找到它们,但扩展名添加的是旧OCX版本号而不是文件名。例如,如果您在'myForm.frm'上使用了Krool的控件,当它从版本15转换到16时,可以保留旧文件,如果保留,它将被命名为'myForm.frm.ocxCCR15ocxFlex12',这样您可以清楚地将其识别为升级后留下的旧文件。我建议一旦您对此工具有了信任,确信它不会删除不应该删除的文件,就没有理由保存旧版本,因此您可以选择删除旧文件。 如果较旧的OCX文件已在PC上注册,您实际上可以转到控件的较早版本。通常,较新版本有更多功能,但更重要的是它们也有错误修复,所以我不建议回到较早版本。另外要考虑的是,VBCCR16添加了一个新控件(ComboFont),VBCCR17添加了在较早版本中不存在的VirtualCombo和VListBox,因此如果您指定从1.6或更高版本转到1.5或更早版本,对这些控件的引用必须被删除,这可能不是您想要的(假设您已经使用了它)。 一旦您选择了要转到的版本以及是否保存旧文件,只需单击'Update .OCX References'即可更改您的项目。所有控件的设置将与升级到新版本之前相同。 **注意** - 此工具不使用任何Krool的控件,因此a)它只是ANSI的,b)您在PC上安装的OCX版本无关紧要。 **不带OCX文件编译** 主菜单中的这个选项允许您将程序与StdEXE文件一起编译到程序中,这样编译后就不再需要OCX文件。它不会更改您一直在使用OCX版本控件进行开发的任何文件。 此选项应该在您让程序使用OCX版本编译和运行*之后*使用。使用OCX版本开发程序要容易得多,效率也更高,然后使用StdEXE版本制作可以分发的可执行文件。请注意,所有这些都假设您已下载并注册了VBCCR和VBFlexGrid的OCX版本,并且还下载并解压了StdEXE版本的等效版本。 如果您单击主窗体上的Options按钮,将看到以下内容: 窗体顶部是选项,用于选择要包含的Krool支持文件(不是每个控件的一部分)。其中一些是许多单独控件使用的通用文件,有些只是通用支持文件。例如,Common.bas是一个通用模块,其例程被许多控件使用。我总是选中这个,因为它对所有功能都很核心。另一方面,VisualStyles.bas包含的代码我已经合并到我的核心模块中,所以我不在上面的选项中使用它。 类模块CommonDialog.cls很有趣。只有一个控件使用它(MCIWnd.ctl),IDE中使用的4个.pag文件也使用它(CoolBar、ImageList、RichTextBox和StatusBar)。我有代码来查看是否使用了这些,如果没有,它会自动被排除,所以我的建议是,除非您专门在代码中包含CommonDialog.cls用于其他用途,否则只需在上面选中它即可。 请注意,有一个名为VTableSubClass.bas的模块选项,但如果您使用2020年1月5日或之后的ComCtrlsDemo版本,则不需要此选项,也不会显示。 窗体中间是编译文件位置的选择。工具不会影响您现有的项目文件,但需要修改它们以将引用从.OCX控件更改为StdEXE控件。您有两种选择:1)复制所有受影响的文件,并在新复制文件的名称前面加上XXX,或2)将所有项目文件复制到单独的文件夹,在那里您可以进行适当的更改来编译。我建议复制到单独文件夹的选项,因为您不会在整个编程系统中留下散乱的XXX文件。 **将所有文件复制到StdEXE子文件夹然后编译** - 如果您选择此选项,与您项目相关的所有文件都会被复制到项目文件所在文件夹的名为StdEXE的子文件夹中。项目文件的副本会放入此子文件夹,所有引用都会调整到现在此子文件夹中的文件。编译后,EXE文件将位于此文件夹中。这个项目与父项目的不同之处在于OCX引用不见了,被替换为对StdEXE控件文件的引用。但是,除了将项目提供给命令行VB6编译器外,它也可以像普通项目一样在VB6 IDE中打开。如果您想要删除此项目,只需删除子文件夹的内容即可。注意- Krool的控件文件被视为库,因此在编译时不会以任何方式更改,所以它们不会被复制到StdEXE文件夹中。它们是从您放置它们的位置引用的。 **在编译前用XXX前缀重命名所有支持文件然后'** - 当您选择此选项时,您会在其下方得到3个子选项。为了保护原始项目,我们通过在名称前面加上'XXX\_'来复制所有更改的文件,包括从命令行编译器生成的EXE。您可以告诉程序在编译后删除这些支持文件;您可以保存这些XXX\_文件,以便以后可以重新编译新项目文件(其名称也以XXX\_为前缀);或者您可以选择保留Krool所有控件的所有支持文件,即使是那些在项目中未使用的。(注意 - 如果您使用此工具的Excel版本,前缀是YYY\_而不是XXX\_。) 注意 - 如果您选择保存支持文件以便可以在VB6 IDE中打开StdEXE版本,我必须进行一些对您来说透明但重要的修改,这样您就不会感到意外。例如,我不包含任何控件属性页文件(.pag扩展名),因为这些只在IDE中使用,而我们在命令行编译时跳过IDE。但是,如果您想保存支持文件以便以后可以在IDE中打开,那么我们需要确保调整您的项目文件以引用适当的.PAG文件,这样您就可以在IDE中打开它。因此,在命令行编译之后,.PAG文件的引用被放入.VBP项目文件中。 直到2020年8月初,Krool在StdEXE文件集中内置了一个机制,试图确保在IDE中使用这些控件的安全性。在2020年8月13日之后,他删除了这些保护措施。如果您仍在使用之前的StdEXE版本(强烈不建议),那么我们有一些代码可以帮助您在编译后将这个尝试的保护措施放入代码中,在.OCX版本中不需要它,但在早期的StdEXE版本中需要。 **包含哪些控件** 当您进行命令行编译时,只有您实际使用的控件才会包含在编译的代码中。这使得生成的.EXE文件尽可能小,因为您不包含对未使用控件的引用。但是,如果您想稍后编辑此StdEXE版本,可能您希望有选项将更多或所有当前未使用的控件添加到项目中。在Options窗体上有一个选项,可以指定将所有控件包含到新项目中,或者您可以单击'Special'并包含特定的控件。一般来说,我不建议这样做,因为继续使用引用.OCX文件的原始项目(您可以使用所有控件)更容易,然后只需在想要生成包含在.EXE中的控件的.EXE文件时重新运行此工具即可。 有一个特殊情况必须使用'Special'按钮。如果您在运行时定义控件,并且控件名称在变量中,我的工具无法看到它,追踪字符串的所有可能赋值会变得非常复杂。由于您编写编程代码,您应该知道在运行时添加哪些控件,因此您可以指定要包含的其他控件(如果有)。如果您的程序中已经使用了特定控件,则甚至不需要这样做,因为该使用已经使该控件包含在编译中。 **基本文件位置** 在Compile Options窗体底部是'Base File Locations'部分。为了进行命令行编译,我们需要知道VB6的位置以及Krool的控件文件的位置。 如果您要通过将OCX版本替换为临时StdEXE版本来编译项目,那么您需要知道VB6.EXE的位置,因为当您在主窗体中单击'Compile w/o .OCX's'时,此工具将稍后执行它。当您单击'VB6.EXE'按钮时,我们将尝试自动为您定位VB6。如果找不到,您可以导航到它或手动输入它。 窗体底部有两个位置,用于指定Krool的StdEXE版本(ComCtlsDemo和VBFlexGridDemo)的位置。您不需要这些来指定OCX版本的更新,但如果您希望使用StdExE控件而不是OCX版本的控件进行命令行编译,则需要指定这些。这些文件永远不会被修改,所以我把它们放在我的库中,我总是把最新版本保存在名为'Current'的文件夹中。您不需要将文件夹命名为那个名字,但您确实需要某个地方来放置为VBCCRxx和/或VBFLXGRDxx下载的新文件。 在您对此编译选项窗体做出任何想要的更改后,如果您单击'Accept changes & return',您的所有输入都将保存在INI文件中,以供下次运行StdEXE工具时重用。INI文件保存在保存StdEXE工具的同一文件夹中。我假设作为程序员,您不会将其安装到'Program Files'中,因此将您的设置与程序一起保存更方便,因为您不必担心尝试保存到'Program Files'需要UAC提升。 **编译** 当您在主窗体上单击'Compile w/o .OCX's'按钮时,工具将查看您的项目文件、所有控件、模块和清单/资源文件中对OCX控件的引用,并将它们更改为StdEXE控件,StdEXE控件的引用被放入.vbp文件中,然后使用VB6.EXE程序从命令行编译(我们切换到提升的命令提示符)。 您的原始项目文件不会被修改。 **注意** - 请知道,在最初几次使用此工具进行命令行编译时,您可能会遇到一些命名冲突。所有控件、页面属性、类文件等的名称(基本上是Builds文件夹中的所有内容)在OCX中都是"隐藏"的,但当您的程序编译时包含所有这些控件时,所有文件名和所有公共变量、类型、过程枚举等都是可见的。在这一点上,您可以决定是重命名您的代码还是Krool的代码。我本想保留我的并重命名Krool的(我有2个冲突),但我没有这样做,因为我不想追踪他每次使用的内容,也不想每次下载和更新时都要经历重命名的麻烦。但无论哪种方式都可以。 下面是两个屏幕截图,一个是成功编译的,一个是失败的。 ### 使用命令行选项运行OCX2StdEXE 现在有一个工具的命令行版本,可以执行OCX版本升级或使用StdEXE版本进行OCX编译,就像上面描述的那样,但没有输入窗体。请注意,在这两种情况下,如果项目的完整路径中有任何空格,那么完整路径必须用引号括起来。 **通过命令行编译** OCX2StdExe ProjectPathAndName \[/s\[1]\[2]\[3]] \[/A\[-]\[+]] 这意味着使用StdEXE版本编译使用OCX版本的项目,将代码嵌入到可执行文件中。如果指定/S,则编译后除了可执行文件外不保存任何文件(假设编译成功)。如果指定/S1,则保存使用的控件的支持文件,如果指定/S2,则保存所有控件的所有支持文件,无论项目中是否使用这些控件。指定/S3表示在StdEXE子文件夹中制作整个项目的副本,然后编译该副本。如果不指定/S开关,则重用上次使用对话框时保存的值。 您还可以指定在命令行编译中是否使用所有StdEXE控件(这与编译后是否保存任何文件不同)。指定/A或/A+表示使用所有控件,/A-表示不使用所有控件。如果不指定/A开关,则使用上次运行时当前保存的/A值。 开关大小写无关。/S与/s相同。 程序的编译版本(如果编译成功)将在2个地方之一找到。如果指定/S3,则StdEXE子文件夹不仅包含所有项目文件的副本,还包含编译的.EXE文件。另一方面,使用任何其他SaveControls选项将使编译的EXE与原始项目文件位于同一文件夹中,并且可执行文件名称前面将附加'XXX\_'。 **更新项目中的.OCX版本** OCX2StdExe ProjectPathAndName /u \[/CCRxx] \[/FLEXxx] \[/d] 这将使指定项目的OCX控件更改为/CCRxx或/FLExxx开关中指定的值。'xx'指定要使用的版本(必须首先在此PC上注册)。如果未指定'xx',则使用运行工具的PC上注册的最新版本。与常规版本的OCX2STDExe一样,旧文件使用新扩展名保存。指定/d或/D将导致删除所有包含旧OCX引用的那些旧文件。 ## 我如何管理Krool的系统 正如您可能已经发现的那样,我在开发期间使用Krool的OCX版本控件,然后使用我的工具切换到使用Krool的StdEXE版本进行编译,这样我就有了一个可以分发的独立可执行文件。我学到了一些技巧,希望能使整个过程变得非常简单。 * OCX版本的控件 * 我总是使用[这里](http://www.vbforums.com/showthread.php?841929-VB6-ActiveX-CommonControls-%28Replacement-of-the-MS-common-controls%29\&p=5129155#post5129155)的VBCCRxx和[这里](http://www.vbforums.com/showthread.php?855931-VB6-ActiveX-VBFlexGrid-%28Replacement-of-the-MSFlexGrid-control%29\&p=5236525#post5236525)的VBFLXGRDxx的最新OCX文件版本。最新版本在第1个帖子的末尾。保存VBCCRxx文件时注意使用"另存为"并删除.docx扩展名,因为这是Krool用来避免VBForums对zip文件大小限制的技巧。我建议将文件保存到硬盘时在文件名中包含当前版本。当前VBCCRxx文件是1.7.0版本,所以我将文件'VBCCR17.OCX.rar.docx'保存为'VBCCR16.OCX v1.7.0.rar'。最新的VBFLXGRDxx版本是1.4.27,目前文件大小足够小,仍然使用.zip扩展名。我会将'VBFLXGRD14.OCX.zip'这个文件保存为'VBFLXGRD12.OCX v1.4.27.zip'。在网页上获取OCX文件时,您还应该获取.RES文件(资源文件),因为稍后会用到这些文件。 * 现在您需要将.RAR和.ZIP文件中的OCX文件放入系统文件夹以使用它们。如果使用32位Windows版本,您需要将OCX文件放入C:\Windows\System32,如果使用64位Windows版本,则放入C:\Windows\SysWOW64。请注意,OCX文件名中没有次要版本。例如,最近的两个VBCCRxx.OCX版本是1.7.12和1.7.13,但每个都是名为VBCCR17.OCX的文件。如果系统文件夹中已经有旧版本,您可以直接覆盖它。请注意,对于XP之后的任何操作系统,您都需要使用提升的CMD提示符或像Directory Opus(我最喜欢的)这样的文件管理器来处理提升。您不必将OCX文件放在系统文件夹中,但我总是这样做,如果不是别的原因,至少我知道它在哪里。 * 如果您从未使用过Krool的OCX控件,或者您有更新的版本(比如1.7而不是1.5),那么您需要使用提升的命令提示符中的regsver32注册OCX文件(如果您只是覆盖了同名的旧文件则不需要)。 * 如果您有更新的OCX版本(例如从1.5到1.7),那么您需要为使用早期版本的每个项目运行我的工具,并更新到最新的OCX版本。 * StdEXE版本的控件 * StdEXE版本控件的一个令人困惑的方面是,它们没有像OCX版本控件那样的版本号。当Krool更新他的StdEXE控件时,我下载该包并在下载文件名中放入发布日期。然后我将文件提取到之前使用的相同文件夹结构中,这样我总是可以使用最新版本的控件。Krool警告不要使用这些控件进行开发,因为它们不是IDE安全的,但通过使用这个编译工具,您可以使用稳定的.OCX版本进行开发,然后使用stdEXE版本进行命令行编译,将您使用的控件包含到EXE文件中,这样您就不需要.OCX文件与.EXE程序一起分发。 * 您需要查看VBCCRxx或VBFLXGRDxx的OLEGuids文件夹,并将类型库OLEGuids.tlb复制到系统文件夹并注册它。幸运的是,这个文件不经常更改(当前版本日期为2020年4月15日),但值得时不时检查一下,以确保您不使用过时的类型库。请注意,OCX版本不需要此类型库,因为它实际上已编译到OCX文件中,但StdEXE版本需要它。 * 在您的程序中,您必须通过Project | References在IDE中引用类型库,并在'OLE Guid and interface definitions'旁边打勾。再次说明,这只是StdEXE版本需要的。当您使用此工具并修改使用OCX版本的项目副本以改用StdEXE版本时,我会为您处理这个问题。 * 通过Project | Components(或Ctrl-T)在IDE中启用控件,然后选择适当的控件文件。对于VBCCR 1.7版本,您需要在'VB Common Controls Replacement 1.7 Library'旁边打勾。对于VBFLXGRD 1.4版本,您需要在'VB FlexGrid Control 1.4'旁边打勾。所有控件现在应该出现在IDE的工具箱中。 * VB6程序的默认启动操作是加载和显示窗体。您不能用这些控件这样做,因为在引用、加载或显示任何窗体之前需要运行一些初始化代码。首先,您需要在项目中的标准模块中有一个Sub Main。然后您需要在Project | Properties的General选项卡中更改设置,使Startup Object成为调用Sub Main而不是任何窗体。然后在Sub Main中,您需要一些初始化代码,这样在调用第一个窗体时就不会崩溃。有两种方法可以做到这一点。 * 第一种是直接使用Krool的代码,尽管方式有点奇怪。OCX控件包不包含任何关于如何使用它的指南或代码(它在后来的版本中确实有一些代码,可以让您从源代码制作自己的OCX文件,但这与使用指南不同)。如果您下载StdEXE版本,您会找到一个名为'Common'的文件夹,其中有文件'Common.bas'和'VisualStyles.bas'。VisualStyles.bas中有一个名为'InitVisualStyles'的子程序,这是您在调用窗体之前需要运行的,但如果您只是将VisualStyles.bas包含在程序中,您会发现它需要Common.bas中的一些例程,所以您也必须加载它。因此,如果您在项目中包含这两个文件,您的Sub Main中的第一行应该是调用InitVisualStyles,然后您就可以调用您的窗体了。 * 我使用的方法(正如您在我的工具源代码中看到的那样),我在库中有一个名为mVB6Core.bas的通用标准模块,其中我放入了足够的来自Common.bas和VisualStyles.bas的代码,这样我就可以运行InitVisualStyles子程序,并且可以做很多我经常做的其他事情(检查我们是否在IDE中还是运行编译代码、当前Windows版本等)。以下是我在名为UCCoreInit的通用初始化例程中的代码(第1971行): ```vb If OSVer >= Vista Then Dim ICC As InitCC If App.LogMode <> 0 Then Call InitReleaseVisualStyles(AddressOf ReleaseVisualStyles) ICC.dwSize = LenB(ICC) ICC.dwICC = &H4000& InitCommonControlsEx ICC Else InitCommonControls End If ``` * 您可能认为可以开始了。还不行。当加载每个窗体上的每个控件时,我们必须设置视觉样式。在每个窗体的初始化代码中的某个地方,您需要调用SetupVisualStyles并将窗体传递给子程序。这段代码在VisualStyles.bas中,也是我的mVB6Core.bas库的一部分。这个SetupVisualStyles子程序确保窗体上的所有控件都可以使用视觉样式。所以您可以在使用的每个窗体的Form\_Load子程序中放置这个调用。我的方法与此接近。我总是让我的窗体使用我的类库clResizer.cls,即使我关闭窗体的调整大小功能,我仍然在窗体的初始化代码中有对这个类模块的调用,该模块反过来调用SetupVisualStyles子程序。这样我就不必让该调用成为每个新窗体代码的一部分,因为我的类库处理它。但两种方式都可以。 * 关于清单(manifest)和资源文件。Krool 的控件本身与资源文件没有直接关系,资源文件只是用来容纳清单文件。如果你不需要视觉样式、并排(side-by-side)或高 DPI 显示器,则不必使用清单或资源文件。但如果你想让程序支持视觉样式、并排或高 DPI,则必须使用清单,并将其嵌入到资源文件中,再将该资源文件加载到可执行文件中。如果你打算一直使用 OCX 版本而不是最终用 StdEXE 版本编译控件,通常会希望启用并排选项。但我个人***不***这样做。在开发机上指定并排没有任何好处,反而会带来麻烦——因为如果你在开发机上用 OCX 版本生成 EXE,并且指定了并排,那么运行 EXE 时必须把 OCX 文件和 EXE 放在同一目录下,即使该 OCX 已经注册在系统目录中。 我为所有新项目都使用一个名为 OCX2StdEXE.res 的资源文件(随我的工具提供),它只指定了视觉样式和高 DPI 支持,并未指定并排。如果你有其他文件需要并排,可以把它们写进资源文件,但 Krool 的 OCX 控件没必要这样做。 注意:即使你指定了并排,后来又用我的工具进行最终编译,也不会有任何问题。我的工具会自动从资源文件中移除并排相关的内容,因为当所有控件代码都已编译进可执行文件时,并排就没有意义了。和往常一样,你用于开发的原始文件不会被修改。 * 下面要为后续做一些准备。如果你用的是 2020 年 8 月 13 日之后的 Krool ComCtrlDemo 项目 StdEXE 控件版本,可以跳过以下内容,因为 Krool 的新代码已经不再需要这些处理。如果你还在用旧版本,建议尽快升级,因为 Krool 的控件是免费的,没理由继续用旧版。 * 开发阶段我们用 OCX 版本控件,不用担心 IDE 崩溃,因为 Krool 的 OCX 已经处理了相关问题。命令行编译时我也做了处理。唯一需要注意的是:如果你用命令行编译并选择“保留支持文件以便后续在 IDE 打开”,这时就涉及 IDE Stop 保护代码。Krool 通过条件编译常量 `ImplementIDEStopProtection` 控制 IDE 保护。在 StdEXE 演示项目的 ComCtlsBase 文件第 3 行有这个常量,设为 True 时会编译 IDE 保护代码。命令行编译时我们不希望启用它,所以我会用一份注释掉该常量的 ComCtlsBase.bas 副本。命令行编译后,如果你选择保留支持文件,新的项目文件会自动加上 `ImplementIDEStopProtection = -1`(True),并且需要调用 `ComCtlsInitIDEStopProtection` 子程序来启用 IDE 保护。我的工具自带的 mVB6Core.bas 标准模块会自动处理这些。如果你查看第 1980 行,会看到如下代码: ```vb #If ImplementIDEStopProtection = True Then ' 如果你用 Krool 的控件,OCX 版本不需要 IDE 保护, ' 但 StdEXE 版本需要。如果你用 OCX 版本开发, ' 然后用本工具命令行切换为 StdEXE 并选择保留支持文件, ' 需要执行如下子程序。命令行编译结束后, ' 我会在新的 .vbp 项目文件(引用单独控件而非 OCX)中 ' 添加 ImplementIDEStopProtection = True 编译常量。 ' 下面的子程序在 ComCtlsBase.bas 中。 ComCtlsInitIDEStopProtection ' 命令行编译时常量为 False #End If ``` 通常情况下,这个条件编译常量为 0(OCX 版本下不可见),所以不会调用 ComCtlsInitIDEStopProtection。但如果你用工具保留了支持文件,保存的项目文件会加上 ImplementIDEStopProtection = -1(True)。只有在命令行编译后保留支持文件、并用 IDE 打开时才需要这个过程。一般情况下你不会用到这些支持文件,也不需要关心。如果你有自己的初始化代码,想让命令行编译后的支持文件能在 IDE 打开,也需要类似的处理。实际上,这不是必须的——如果你的程序能用 OCX 版本编译通过,那么用 StdEXE 版本命令行编译也极大概率能成功,通常不会用到这些支持文件。 * 现在你可以正常开发程序了,使用 OCX 版本控件(VBCCRxx.OCX 和/或 VBFLXGRDxx.OCX)。 * 如果有新版本 OCX 发布([VBCCRxx 下载地址](http://www.vbforums.com/showthread.php?841929-VB6-ActiveX-CommonControls-%28Replacement-of-the-MS-common-controls%29\&p=5129155#post5129155),[VBFLXGRDxx 下载地址](http://www.vbforums.com/showthread.php?855931-VB6-ActiveX-VBFlexGrid-%28Replacement-of-the-MSFlexGrid-control%29\&p=5236525#post5236525)),主版本号不变(如 1.7.10 升级到 1.7.13),直接覆盖 OCX 文件即可。如果主版本号升级(如 1.7 升到 1.8),复制新 OCX 到系统目录并用 regsvr32 注册,然后用本工具批量升级所有项目的引用。 * 同时关注 Krool ComCtlsDemo(StdEXE 版)和 VBFlexGridDemo 的更新([ComCtlsDemo 下载](http://www.vbforums.com/showthread.php?698563-CommonControls-\(Replacement-of-the-MS-common-controls\)),[VBFlexGridDemo 下载](http://www.vbforums.com/showthread.php?848839-VBFlexGrid-Control-\(Replacement-of-the-MSFlexGrid-control\)))。虽然没有严格的版本号,但网站上的最新版本通常和 OCX 版本保持同步。过去 OCX 版本有时会落后于 StdEXE 版,但最近几年 Krool 已经做到了同步更新。 * 每当你要发布可执行文件时,运行本工具,选择“无 OCX 编译”选项即可。 * 命令行编译时,每个控件都需要相应的文件。工具会自动判断并包含所需文件。Common 和 Builds 文件夹下有一些通用文件是否包含,由你在工具的 Options 窗体中设置。你可以自由选择是否包含这些文件。相关代码在 zVBandVBA 模块的 DoCompile 函数(第 191 行起)。我的默认设置如下所示。 ```vb Public IncludeStartupbas As Boolean Public IncludeCommonbas As Boolean Public IncludeVisualStylesbas As Boolean Public IncludeISubclasscls As Boolean Public IncludeVTableHandlebas As Boolean Public IncludeVTableSubclasscls As Boolean Public IncludeCommonDialogcls As Boolean ``` 我在自己的程序中不包含 Startup.bas,因为它是特定于 Krool 的演示程序的,尽管我在自己的程序中使用了他的部分例程。 我不包含 VisualStyles.bas,因为我已将该代码集成到 OCX 和 StdEXE 版本的初始化例程中。VisualStyles 需要 Common.bas 中的一些函数和子程序,但我只采用了其中的一部分,并将它们与 VisualStyles 一起设为私有,这样在命令行编译时我就可以引入整个 Common.bas。最后,指定可以包含 CommonDialog.bas。请注意,它不会自动包含。只有在使用 MCIWnd.ctl 控件或使用 CoolBar、ImageList、RichtextBox 或 StatusBar 的一个或多个属性页时才会包含它。属性页不用于命令行编译选项,但如果您选择保存支持文件以供以后重新编译,则会包含属性页文件。 ## 版本历史 | **版本** | **日期** | **说明** | | --- | --- | --- | | 0.9.0 | 2017年7月2日 | \* VB6 和 Excel 初始版本发布用于测试。 | | 0.9.1 | 2017年7月4日 | \* 可以在没有控件但有一个或多个 CommonDialog 引用的情况下工作 \* .vbp 文件中的比较使用大写 \* 如果 .vbp 文件已有 stdol2.tlb 引用,则不包含该引用。 | | 0.9.2 | 2017年7月9日 | \* 正确处理没有使用控件但在窗体中调用 CommonDialog 的情况(之前只在类和标准模块中检查)。 | | 0.9.3 | 2017年7月31日 | \* 修复新 .vbp 文件中窗体的路径错误 | | 0.9.4 | 2017年8月23日 | \* 重新处理一些相对路径问题 | | 0.9.6 | 2018年7月11日 | \* 调整以适应 mUCCore 中函数名称从 myQuickOpen 改为 FileCreateOrOpen 的变化。 | | 0.9.7 | 2018年10月1日 | \* 添加 VBCCR16 支持 \* 将 VB6 核心代码拆分到独立的 mVB6Core.bas 中,与 VBA 的 mUCCore 并行 | | 0.9.8 | 2018年11月24日 | \* 大量更改 | | 0.9.9 | 2018年12月1日 | \* 添加对 VBFLXGRD.OCX 和 VBFlexGridDemo.vbp (StdEXE) 的支持 \* VB6 版本中将所有输入合并到一个窗体 \* 为编译后支持文件保存数量添加三个选项按钮(无、使用的控件、所有控件) \* 修改逻辑以在编译中包含或排除 Common 和 Builds 中的各种模块 \* 修改围绕条件编译常量 ImplementIDEStopProtection 的逻辑,特别是针对编译后重用 \* 编译和/或编译后支持文件保存中包含或排除 CommonDialog.cls 的新逻辑 \* 使用枚举来帮助管理特定项目中是否使用 VBCCRxx 和/或 VBFLXGRDxx 的代码 \* 添加升级或编译的命令行选项。 | | 0.9.10 | 2018年12月11日 | \* 修复如果未安装/注册 VBCCRxx 或 VBFLXGRDxx 时 DoCompile 中的错误 \* 修复当资源文件没有嵌入清单时 DoCompile 从资源文件提取清单的错误 | | 0.9.11 | 2018年12月12日 | \* 在 DoCompile 中查找类和标准模块中对 VBCCRxx 和/或 VBFLXGRDxx 的引用(之前只处理窗体和资源文件,但未处理 .bas 和 .cls 文件) \* 在 fmInput 上,当对话框中已有当前文件时,cbutProjFile 默认为该文件的文件夹,而不是程序的路径。 | | 0.9.12 | 2018年12月13日 | \* fmInput 上的 DoCompile 新增复选框,强制在编译中使用所有 StdEXE 控件,这通常不需要,但如果有人在基于 OCX 的项目中引用了控件的属性,我们可以看到它是 VBCCRxx 的一部分,但如果不遍历每个控件的每个属性,我们就不知道它与哪个控件相连。我认为这种情况不常见,所以我把它放在那里以防有人在基于 OCX 的代码中这样做。 | | 0.9.13 | 2018年12月19日 | \* 代码清理 \* 将所有编译选项移至第二个窗体 | | 2.0.0 | 2020年7月1日 | \* 支持 VBFlexGrid OCX 版本 1.4。 \* Krool 的控件已被标准 VB6 控件替代。这听起来似乎适得其反,但更新工具不应该依赖于控件的特定版本。变化的一小部分是清单和并行编译已被移除。 \* 似乎 Krool 即将发布 VBCCR.OCX 1.7 版和 VBFlexGrid 1.5 版的重大更新,此工具现已设置为可快速添加更新到这些新版本的功能。 \* 该工具使用新的类模块 clINI.cls,在 INI 文件中保存和恢复工具多次运行之间的设置。上一版本将设置保存到注册表。这仍然是一个选项,但出于各种原因,我已完全不使用注册表,因此需要一些代码修改。目前,该工具会将 INI 文件保存到程序文件复制到的同一文件夹中。 \* 集成了 VBForums 上 The Trick 的工具提示模块。 | | 2.1.0 | 2020年7月2日 | \* 各种错误修复。 | | 2.1.1 | 2020年7月3日 | \* 上传的版本没有工具提示模块的本地版本。 | | 2.2.0 | 2020年8月20日 | \* clResize.cls 中包含了新的工具提示方法,并从 VB6Core.bas 中移除旧的 \* 支持 VBCCR17.OCX \* 改进了几处注册表读取。 | | 2.3.0 | 2020年8月28日 | \* 现在包含一个选项,可以首先将项目文件(及其所有模块等)复制到项目的 StdEXE 子文件夹中,以供以后使用。 \* 大量小错误修复。 | | 2.3.1 | 2020年8月31日 | \* 错误修复 - 如果您在项目中有自己的 UserControl 和/或 PropertyPage(不是 Krool 的控件,而是您自己的),这些不会被复制到用于独立项目编译的 StdExe 文件夹中。现已修复。 | | 3.0.0 | 2021年3月27日 | \* 您可以指定在使用 StdExe 编译时要包含的单个控件。添加此功能是因为帖子 #34 中的示例,他想在标准模块中添加一个控件,控件名称在变量中。我不想在您的代码中追踪变量赋值,所以现在有一个功能来处理这个问题(您应该知道您添加了哪些这样的控件,这样您就可以打开这些控件以包含在 EXE 文件中)。以前这是一个全有或全无的选择。 \* StdExe 编译选项包括在所有项目文件(包括 .BAS 文件)中查找对 Krool 控件的引用。 \* 修复了 StdExe 编译部分的错误 \* 实际上忽略了 VirtualCombo 和 VirtualListbox。 \* 即使指定要包含,CommonDialog.cls 也被遗漏。 \* 有时会遗漏用户项目文件中的条件编译常量。 \* 在"复制到子文件夹"选项中,最终的 .VBP 文件中没有引用 .PAG 文件。 \* 改进了 MS 编译器/链接器的命令行编译输出处理。 \* 在从命令行使用 StdExe 选项编译之前,现在需要基本文件位置。如果您尚未输入这些文件位置值,系统会在您继续之前提示您输入。 | | 3.1.0 | 2021年11月17日 | \* 处理 VBCCR17.OCX 版本 1.1(之前只处理 1.0) \* Set\_xx\_CCR 和 Set\_xx\_Flex 现在只调用一次 \* 数组 GUIDxxCCR() 和 GUIDccFlex() 现在是公共的(之前嵌入在 Set\_xx\_CCR 和 Set\_xx\_Flex 中) | | 3.2.0 | 2021年12月20日 | \* 处理 VBCCRxx.OCX 直至 1.7 版。处理所有 VBFLXGRDxx.OCX 版本,包括刚发布的 v1.5。 | | 3.3.0 | 2023年6月24日 | \* 现在支持 VBFleGrd16 \* 每个 OCX 版本都是独立的。VBCCR16.OCX 与 VBCCR17.OCX 等完全分开。这些版本很少有多个版本,所以有 1.0、1.2 版,现在是 1.2。这个版本号出现在 VBP 文件和所有 .FRM 文件中。我之前假设每个 .OCX 的版本号都是 1.0,因为它们都只有 1.0,但现在 VBCCR17.OCX 有 1.0、1.1 和 1.2。未能识别大于 1.0 的版本导致了一些问题。现在已修复。\* 琐事 - VBCCR11.OCX 有一个 1.1 版本,但那是在 2015 年,我很确定没有人再使用它了。 | --- --- url: /zh/packages/vbccr/system/imagelist.md description: 图像列表控件(ImageList) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 图像列表控件(ImageList) 封装 ImageList 控件,用于存储和管理图像集合,供其他控件引用。 ## 枚举 ### ImlImageSizeConstants | 常量 | 值 | 说明 | |------|-----|------| | imlSmall | 0 | 小图标(16×16) | | imlLarge | 1 | 大图标(32×32) | | imlCustom | 2 | 自定义大小 | ### CCBackStyleConstants 参见通用枚举。 ## 属性 ### ImageWidth ```vb Property Get ImageWidth() As Long Property Let ImageWidth(ByVal Value As Long) ``` 图像宽度(像素)。 ### ImageHeight ```vb Property Get ImageHeight() As Long Property Let ImageHeight(ByVal Value As Long) ``` 图像高度(像素)。 ### ImageSize ```vb Property Get ImageSize() As ImlImageSizeConstants Property Let ImageSize(ByVal Value As ImlImageSizeConstants) ``` 预设图像尺寸。设置此属性将自动调整 ImageWidth 和 ImageHeight。 ### ColorDepth ```vb Property Get ColorDepth() As Long Property Let ColorDepth(ByVal Value As Long) ``` 色深。支持 4、8、16、24、32 位。需要 comctl32.dll 6.0 或更高版本。 ### MaskColor ```vb Property Get MaskColor() As OLE_COLOR Property Let MaskColor(ByVal Value As OLE_COLOR) ``` 掩码颜色。 ### UseMaskColor ```vb Property Get UseMaskColor() As Boolean Property Let UseMaskColor(ByVal Value As Boolean) ``` 是否使用掩码颜色。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景颜色。 ### hImageList ```vb Property Get hImageList() As LongPtr ``` 图像列表句柄。只读。 ### ListImages ```vb Property Get ListImages() As ImlListImages ``` 图像集合。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As Variant Property Let Tag(ByVal Value As Variant) Property Set Tag(ByVal Value As Variant) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度(设计时使用)。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度(设计时使用)。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 可见性(设计时使用)。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 窗口句柄。只读。 ## 方法 ### Refresh ```vb Sub Refresh() ``` 强制重绘。 ### CreateIcon ```vb Function CreateIcon(ByVal ImageIndex As Long) As IPictureDisp ``` 从指定图像创建图标。 ### CreateBitmap ```vb Function CreateBitmap(ByVal ImageIndex As Long) As IPictureDisp ``` 从指定图像创建位图。需要 comctl32.dll 6.0 或更高版本。 ### Overlay ```vb Function Overlay(ByVal ImageIndex1 As Long, ByVal ImageIndex2 As Long) As IPictureDisp ``` 将两个图像叠加,返回叠加后的图像。 ### AboutBox ```vb Sub AboutBox() ``` 显示关于对话框。 ## 子对象 ### ListImage(ImlListImage) 表示图像列表中的单个图像。 #### 属性 | 属性 | 类型 | 读写 | 说明 | |------|------|------|------| | Index | Long | 只读 | 集合中的索引 | | Key | String | 读写 | 集合中的键 | | Tag | Variant | 读写 | 自定义数据 | | Picture | IPictureDisp | 读写 | 图像 | | MaskPicture | IPictureDisp | 读写 | 掩码图像 | | Overlay | Boolean | 读写 | 是否为叠加图像 | | OverlaySourceIndex | Long | 读写 | 叠加源索引 | | ExtractIcon | IPictureDisp | 只读 | 提取图标 | | ExtractBitmap | IPictureDisp | 只读 | 提取位图 | ### ListImages(ImlListImages) 图像集合对象。 #### 属性 | 属性 | 类型 | 读写 | 说明 | |------|------|------|------| | Item(ByVal Index As Variant) | ImlListImage | 只读 | 按索引或键获取图像 | | Count | Long | 只读 | 图像数量 | #### 方法 | 方法 | 说明 | |------|------| | Add(\[Index], \[Key], \[Picture], \[MaskPicture]) As ImlListImage | 添加图像 | | Exists(ByVal Index As Variant) As Boolean | 判断图像是否存在 | | Clear | 清除所有图像 | | Remove(ByVal Index As Variant) | 移除指定图像 | ## 代码示例 ```vb ' 设置图像大小并添加图像 With ImageList1 .ImageSize = imlSmall .ListImages.Add , "open", LoadPicture("open.ico") .ListImages.Add , "save", LoadPicture("save.ico") .ListImages.Add , "exit", LoadPicture("exit.ico") End With ' 按键引用图像 Set cmdOpen.Picture = ImageList1.ListImages("open").ExtractIcon ' 创建叠加图像 ImageList1.ListImages.Add , "overlay1", LoadPicture("ov1.ico") ImageList1.ListImages("overlay1").Overlay = True ImageList1.ListImages("overlay1").OverlaySourceIndex = 1 ' 使用 Overlay 方法叠加两个图像 Set imgOverlay = ImageList1.Overlay(1, 2) ' 遍历所有图像 Dim img As ImlListImage For Each img In ImageList1.ListImages Debug.Print img.Index; img.Key Next img ``` --- --- url: /zh/packages/vbccr/lists/imagecombo.md description: 图像组合框控件(ImageCombo) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 图像组合框控件(ImageCombo) 提供支持图标显示的增强型组合框控件,每个项目可关联图像列表中的图标。 ## 枚举 ### ImcStyleConstants | 常量 | 值 | 说明 | |------|-----|------| | ImcStyleDropDownCombo | 0 | 下拉组合框(可输入) | | ImcStyleSimpleCombo | 1 | 简单组合框(列表始终可见) | | ImcStyleDropDownList | 2 | 下拉列表(仅选择) | ### ImcEndEditReasonConstants | 常量 | 值 | 说明 | |------|-----|------| | ImcEndEditReasonLostFocus | 1 | 编辑结束原因:失去焦点 | | ImcEndEditReasonReturn | 2 | 编辑结束原因:按回车键 | | ImcEndEditReasonEscape | 3 | 编辑结束原因:按 Escape 键 | | ImcEndEditReasonDropDown | 4 | 编辑结束原因:下拉选择 | ### ImcEllipsisFormatConstants | 常量 | 值 | 说明 | |------|-----|------| | ImcEllipsisFormatNone | 0 | 不使用省略号 | | ImcEllipsisFormatEnd | 1 | 文本末尾使用省略号 | ## ImcComboItem 对象 表示图像组合框中的一个项目。 ### ImcComboItem 属性 #### Index ```vb Property Get Index() As Long ``` 返回项目在集合中的索引。只读。 #### Key ```vb Property Get/Let Key() As String ``` 返回/设置项目的键值。 #### Tag ```vb Property Get/Let/Set Tag() As Variant ``` 返回/设置项目的附加数据。 #### Text ```vb Property Get/Let Text() As String ``` 返回/设置项目的文本。 #### Image ```vb Property Get/Let Image() As Variant ``` 返回/设置项目关联的图像索引或键。 #### ImageIndex ```vb Property Get ImageIndex() As Long ``` 返回项目关联的图像索引。只读。 #### SelImage ```vb Property Get/Let SelImage() As Variant ``` 返回/设置项目选中时关联的图像索引或键。 #### SelImageIndex ```vb Property Get SelImageIndex() As Long ``` 返回项目选中时关联的图像索引。只读。 #### Indentation ```vb Property Get/Let Indentation() As Long ``` 返回/设置项目的缩进级别(以图标宽度为单位)。 #### Selected ```vb Property Get/Let Selected() As Boolean ``` 返回/设置项目是否被选中。 #### Data ```vb Property Get/Let Data() As LongPtr ``` 返回/设置项目的附加数值数据。 ## ImcComboItems 集合 表示图像组合框中所有项目的集合。 ### ImcComboItems 属性和方法 #### NewEnum ```vb Public Function NewEnum() As IEnumVARIANT ``` 返回枚举器,支持 For Each 语法。 #### Add ```vb Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Text As String, Optional ByVal Image As Variant, Optional ByVal SelImage As Variant, Optional ByVal Indentation As Variant) As ImcComboItem ``` 添加一个项目到集合中,返回新创建的 ImcComboItem 对象。 #### Item ```vb Public Property Get Item(ByVal Index As Variant) As ImcComboItem ``` 按索引或键返回项目。 #### Exists ```vb Public Function Exists(ByVal Index As Variant) As Boolean ``` 检查指定索引或键的项目是否存在。 #### Count ```vb Public Property Get Count() As Long ``` 返回集合中的项目数量。 #### Clear ```vb Public Sub Clear() ``` 移除集合中的所有项目。 #### Remove ```vb Public Sub Remove(ByVal Index As Variant) ``` 按索引或键移除一个项目。 ## 属性 ### ControlsEnum ```vb Property Get ControlsEnum() As VBRUN.ParentControls ``` 返回父控件枚举器。 ### Name ```vb Property Get Name() As String ``` 返回控件的名称。 ### Tag ```vb Property Get/Let Tag() As String ``` 返回/设置控件的标记值。 ### Parent ```vb Property Get Parent() As Object ``` 返回控件的父对象。 ### Container ```vb Property Get/Set Container() As Object ``` 返回/设置控件的容器。 ### Left ```vb Property Get/Let Left() As Single ``` 返回/设置控件左边缘的位置。 ### Top ```vb Property Get/Let Top() As Single ``` 返回/设置控件上边缘的位置。 ### Width ```vb Property Get/Let Width() As Single ``` 返回/设置控件的宽度。 ### Height ```vb Property Get/Let Height() As Single ``` 返回/设置控件的高度。 ### Visible ```vb Property Get/Let Visible() As Boolean ``` 返回/设置控件是否可见。 ### ToolTipText ```vb Property Get/Let ToolTipText() As String ``` 返回/设置控件的工具提示文本。 ### HelpContextID ```vb Property Get/Let HelpContextID() As Long ``` 返回/设置控件的帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get/Let WhatsThisHelpID() As Long ``` 返回/设置控件的"这是什么"帮助 ID。 ### DragIcon ```vb Property Get/Let/Set DragIcon() As IPictureDisp ``` 返回/设置拖动操作时显示的图标。 ### DragMode ```vb Property Get/Let DragMode() As Integer ``` 返回/设置拖动模式(手动或自动)。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 返回图像组合框的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 返回 UserControl 的窗口句柄。 ### hWndCombo ```vb Property Get hWndCombo() As LongPtr ``` 返回 ComboBoxEx 控件的窗口句柄。 ### hWndEdit ```vb Property Get hWndEdit() As LongPtr ``` 返回编辑框部分的窗口句柄。 ### hWndList ```vb Property Get hWndList() As LongPtr ``` 返回列表部分的窗口句柄。 ### Font ```vb Property Get/Let/Set Font() As StdFont ``` 返回/设置控件使用的字体。 ### VisualStyles ```vb Property Get/Let VisualStyles() As Boolean ``` 返回/设置是否启用视觉样式。 ### Enabled ```vb Property Get/Let Enabled() As Boolean ``` 返回/设置控件是否可用。 ### OLEDragMode ```vb Property Get/Let OLEDragMode() As VBRUN.OLEDragConstants ``` 返回/设置 OLE 拖动模式。 ### OLEDropMode ```vb Property Get/Let OLEDropMode() As OLEDropModeConstants ``` 返回/设置 OLE 放置模式。参见通用枚举。 ### MousePointer ```vb Property Get/Let MousePointer() As CCMousePointerConstants ``` 返回/设置鼠标指针类型。参见通用枚举。 ### MouseIcon ```vb Property Get/Let/Set MouseIcon() As IPictureDisp ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Property Get/Let MouseTrack() As Boolean ``` 返回/设置是否启用鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get/Let RightToLeft() As Boolean ``` 返回/设置是否启用从右到左布局。 ### RightToLeftLayout ```vb Property Get/Let RightToLeftLayout() As Boolean ``` 返回/设置是否启用从右到左布局镜像。 ### RightToLeftMode ```vb Property Get/Let RightToLeftMode() As CCRightToLeftModeConstants ``` 返回/设置从右到左模式。参见通用枚举。 ### ImageList ```vb Property Get/Set/Let ImageList() As Variant ``` 返回/设置关联的 ImageList 控件,用于提供项目图标。 ### Style ```vb Property Get/Let Style() As ImcStyleConstants ``` 返回/设置组合框的样式。 ### Locked ```vb Property Get/Let Locked() As Boolean ``` 返回/设置控件是否锁定(禁止编辑和选择)。 ### Text ```vb Property Get/Let Text() As String ``` 返回/设置编辑框中的文本。 ### Default ```vb Property Get/Let Default() As String ``` 返回/设置默认值。 ### Indentation ```vb Property Get/Let Indentation() As Long ``` 返回/设置新项目的默认缩进级别。 ### ExtendedUI ```vb Property Get/Let ExtendedUI() As Boolean ``` 返回/设置是否使用扩展用户界面。 ### MaxDropDownItems ```vb Property Get/Let MaxDropDownItems() As Integer ``` 返回/设置下拉列表中可见的最大项目数。 ### ShowImages ```vb Property Get/Let ShowImages() As Boolean ``` 返回/设置是否显示项目图标。 ### MaxLength ```vb Property Get/Let MaxLength() As Long ``` 返回/设置编辑框中可输入的最大字符数。 ### IMEMode ```vb Property Get/Let IMEMode() As CCIMEModeConstants ``` 返回/设置输入法编辑器模式。参见通用枚举。 ### EllipsisFormat ```vb Property Get/Let EllipsisFormat() As ImcEllipsisFormatConstants ``` 返回/设置文本超出宽度时的省略号格式。 ### ScrollTrack ```vb Property Get/Let ScrollTrack() As Boolean ``` 返回/设置滚动条是否实时跟踪。 ### ComboItems ```vb Property Get ComboItems() As ImcComboItems ``` 返回组合框项目集合。只读。 ### SelStart ```vb Property Get/Let SelStart() As Long ``` 返回/设置选中文本的起始位置。 ### SelLength ```vb Property Get/Let SelLength() As Long ``` 返回/设置选中文本的长度。 ### SelText ```vb Property Get/Let SelText() As String ``` 返回/设置当前选中的文本。 ### TopItem ```vb Property Get/Set TopItem() As ImcComboItem ``` 返回/设置列表顶部可见的项目。 ### SelectedItem ```vb Property Get/Set SelectedItem() As ImcComboItem ``` 返回/设置当前选中的项目。 ### DroppedDown ```vb Property Get/Let DroppedDown() As Boolean ``` 返回/设置下拉列表是否展开。 ### DropDownWidth ```vb Property Get/Let DropDownWidth() As Single ``` 返回/设置下拉列表的宽度。简单样式下不支持。 ### OLEDraggedItem ```vb Property Get OLEDraggedItem() As ImcComboItem ``` 返回 OLE 拖放操作中当前被拖动的项目。只读。 ## 方法 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖动操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移到该控件。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置控件在其层级中的 Z 顺序位置。 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘控件。 ### GetItemHeight ```vb Public Function GetItemHeight() As Single ``` 返回列表项目的高度(考虑图标高度)。 ### FindItem ```vb Public Function FindItem(ByVal Text As String, Optional ByVal Index As Long, Optional ByVal Partial As Boolean, Optional ByVal Wrap As Boolean) As ImcComboItem ``` 在列表中查找项目并返回该项目的引用。Partial 为 True 时进行部分匹配,Wrap 为 True 时从开头继续搜索。 ## 事件 ### Click ```vb Public Event Click() ``` 单击控件时发生。 ### DblClick ```vb Public Event DblClick() ``` 双击控件时发生。 ### Scroll ```vb Public Event Scroll() ``` 滚动列表时发生。 ### Change ```vb Public Event Change() ``` 控件内容发生变化时发生。 ### DropDown ```vb Public Event DropDown() ``` 下拉列表即将展开时发生。 ### CloseUp ```vb Public Event CloseUp() ``` 下拉列表关闭时发生。 ### ItemDrag ```vb Public Event ItemDrag(ByVal Item As ImcComboItem, ByVal Button As Integer) ``` 项目发起拖放操作时发生。 ### BeginEdit ```vb Public Event BeginEdit() ``` 用户激活下拉列表或点击编辑框时发生。 ### EndEdit ```vb Public Event EndEdit(ByVal Changed As Boolean, ByVal NewIndex As Long, ByVal NewText As String, ByVal Reason As ImcEndEditReasonConstants) ``` 编辑操作结束时发生。Changed 指示文本是否改变,NewIndex 为新选中项索引,NewText 为新文本,Reason 为结束原因。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyDown 事件之前发生,可设置 IsInputKey 标记按键是否为输入键。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyUp 事件之前发生。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下键盘键时发生。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放键盘键时发生。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按下并释放字符键时发生。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时发生。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时发生。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时发生。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件时发生。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件时发生。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放操作完成或取消后,在源控件上发生。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 数据通过 OLE 拖放操作放置到控件上时发生。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放操作期间鼠标移过控件时发生。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 拖放操作期间需要更改鼠标光标时,在源控件上发生。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` 放置目标请求数据时,在源控件上发生。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 拖放操作启动时发生。 ## 代码示例 ### 基本用法 ```vb Private Sub Form_Load() Set ImageCombo1.ImageList = ImageList1 With ImageCombo1 .Style = ImcStyleDropDownCombo .ShowImages = True .MaxDropDownItems = 10 End With Dim Item As ImcComboItem Set Item = ImageCombo1.ComboItems.Add(, "k1", "项目一", 1, 2) Set Item = ImageCombo1.ComboItems.Add(, "k2", "项目二", 1, 2) Set Item = ImageCombo1.ComboItems.Add(, "k3", "子项目", 3, 4) Item.Indentation = 1 End Sub Private Sub ImageCombo1_Click() If Not ImageCombo1.SelectedItem Is Nothing Then Debug.Print "选中: " & ImageCombo1.SelectedItem.Text End If End Sub Private Sub ImageCombo1_EndEdit(ByVal Changed As Boolean, ByVal NewIndex As Long, ByVal NewText As String, ByVal Reason As ImcEndEditReasonConstants) If Changed Then Debug.Print "编辑完成: " & NewText End If End Sub ``` --- --- url: /zh/official/Tutorials/CEF/Hosting-local-web-assets.md --- # 托管本地Web资源 [**CefBrowser**](/official/Reference/CEF/CefBrowser/)控件可以直接从磁盘上的文件夹提供HTML、JavaScript、CSS和任何其他资源——无需嵌入式HTTP服务器。Chromium的[**SetVirtualHostNameToFolderMapping**](/official/Reference/CEF/CefBrowser/#setvirtualhostnametofoldermapping)将虚拟 `https://` 主机名路由到本地文件夹,使资源表现如同来自真实源:同源 `fetch`、内容安全策略、Service Workers等都能正常工作。 本教程演示*示例1b——Chromium Embedded Framework示例*(窗体*示例2*、*示例3*、*示例4*)中使用的模式。 ## 三步模式 1. **选择文件夹。** 它必须存在于磁盘上并包含 `index.html`(加上页面需要的任何资源——脚本、样式、图片)。 2. **注册虚拟主机**映射到该文件夹。 3. **导航**到虚拟主机名下的URL。 挂接[**Ready**](/official/Reference/CEF/CefBrowser/#ready)事件,以便在安装映射之前控件已完全初始化: ```vb Private Sub WebView_Ready() Handles WebView.Ready Dim folderPath As String = _ Environ$("USERPROFILE") & "\Documents\MyApp" WebView.SetVirtualHostNameToFolderMapping _ "myapp.example", folderPath & "\" WebView.Navigate "https://myapp.example/index.html" End Sub ``` 映射完成后,对 `https://myapp.example/<path>` 的每个请求都从 `folderPath\<path>` 提供。页面上的 `<script src="/script.js">` 解析为 `folderPath\script.js`,就像真正的Web服务器位于 `myapp.example` 上一样。 文件夹路径上的尾部反斜杠是必需的——运行时将传入的URL路径逐字连接到文件夹字符串上,因此缺少分隔符会将 `folderPath` + `/index.html` 变成无意义的路径。 ## 选择主机名 安全的约定是选择一个永远不会在公共Internet上解析的TLD下的主机名: | 推荐 | 避免 | |---------------------|-----------------------------| | `myapp.example` | `myapp.com`, `app.local` | | `editor.invalid` | `editor.dev` | | `assets.test` | `assets.io` | `.example`、`.invalid` 和 `.test` TLD由IANA正式保留,永远不会分配给真实域名,因此可以安全无限期使用。 ## 在项目Resources文件夹中捆绑资源 大多数应用程序希望将HTML/JS/CSS打包在可执行文件*内部*,并在首次运行时释放到磁盘上。twinBASIC的 `Resources` 文件夹是存放它们的正确位置。 1. 在IDE的项目资源管理器中,展开**Resources**并添加子文件夹(右键→*添加新子文件夹*)。给它一个容易记住的名称,如 `WEB_APP`。 2. 将资源放入其中——`index.html`、`script.js`、`styles.css`,以及你需要的任何子目录。 在运行时,下面的辅助过程将 `Resources` 子文件夹的内容复制到本地路径。将其放入项目中的 `.twin` 模块: ```vb Module Files Private Sub CreateFile(ByVal Path As String, ByRef Data() As Byte) On Error Resume Next : Kill Path : On Error GoTo 0 Dim fileNum As Integer = FreeFile Open Path For Binary As fileNum Put fileNum, 1, Data Close fileNum End Sub Private Sub CreateLocalFileFromResource( _ ByVal OutputLocalFolderPath As String, _ ByVal InputResourceSubFolderName As String, _ ByVal ResourceName As String) Dim splitPath As Variant = Split(ResourceName, "~") On Error Resume Next : MkDir OutputLocalFolderPath : On Error GoTo 0 Dim i As Long For i = 0 To UBound(splitPath) - 1 OutputLocalFolderPath &= "\" & splitPath(i) On Error Resume Next : MkDir OutputLocalFolderPath : On Error GoTo 0 Next Dim Data() As Byte Data = LoadResData(ResourceName, InputResourceSubFolderName) CreateFile(OutputLocalFolderPath & "\" & splitPath(i), Data) End Sub [Description("Copy every file from a Resources subfolder onto disk. " & _ "'~' characters in resource names represent subfolders.")] Public Sub CopyResourcesFolderContentsToLocalPath( _ ByVal InputResourceSubFolderName As String, _ ByVal OutputLocalFolderPath As String) Dim resourceId As Variant For Each resourceId In LoadResIdList(InputResourceSubFolderName) CreateLocalFileFromResource _ OutputLocalFolderPath, InputResourceSubFolderName, resourceId Next End Sub End Module ``` [**LoadResIdList**](/official/Reference/VB/Global/#loadresidlist)返回指定子文件夹下的每个资源ID;[**LoadResData**](/official/Reference/VB/Global/#loadresdata)返回字节数据。辅助过程将每个资源名称按 `~` 分割,在磁盘上重建原始子目录树——当资源被编译时,twinBASIC IDE通过用 `~` 连接名称来展平嵌套文件夹。 ## 完整组合 完整的部署于`Ready`的模式如下: ```vb Private Sub WebView_Ready() Handles WebView.Ready ' Resources/WEB_APP/* is copied here on every launch. Dim folderPath As String = _ Environ$("USERPROFILE") & "\Documents\MyApp" CopyResourcesFolderContentsToLocalPath "WEB_APP", folderPath WebView.SetVirtualHostNameToFolderMapping _ "myapp.example", folderPath & "\" WebView.Navigate "https://myapp.example/index.html" End Sub ``` 部署完成后,应用程序可以启动DevTools([**OpenDevToolsWindow**](/official/Reference/CEF/CefBrowser/#opendevtoolswindow))检查已加载的文件,用户可以直接编辑磁盘上的 `index.html` 并点击**刷新**——这在开发过程中的快速迭代中很有用。 ## 移除映射 [**ClearVirtualHostNameToFolderMapping**](/official/Reference/CEF/CefBrowser/#clearvirtualhostnametofoldermapping)移除先前通过[**SetVirtualHostNameToFolderMapping**](/official/Reference/CEF/CefBrowser/#setvirtualhostnametofoldermapping)安装的映射: ```vb WebView.ClearVirtualHostNameToFolderMapping "myapp.example" ``` 浏览器会保留缓存资源直到硬刷新,因此命中刚移除主机名的导航可能在短时间内仍然成功。 ## 下一步 * [JavaScript互操作](/official/Tutorials/CEF/JavaScript-interop) —— 托管页面如何与BASIC应用交换值和方法调用。 * [从twinBASIC驱动Monaco](/official/Tutorials/CEF/Driving-Monaco) —— 基于此模式的完整案例研究。 * [SetVirtualHostNameToFolderMapping](/official/Reference/CEF/CefBrowser/#setvirtualhostnametofoldermapping) —— 完整参考。 --- --- url: /zh/official/Tutorials/WebView2/Hosting-local-web-assets.md --- # 托管本地Web资源 [**WebView2**](/official/Reference/WebView2/WebView2/)控件可以直接从磁盘上的文件夹提供HTML、JavaScript、CSS和任何其他资源——无需嵌入式HTTP服务器。Edge的[**SetVirtualHostNameToFolderMapping**](/official/Reference/WebView2/WebView2/#setvirtualhostnametofoldermapping)将虚拟 `https://` 主机名路由到本地文件夹,使资源表现如同来自真实源:同源 `fetch`、内容安全策略、Service Workers等都能正常工作。 本教程演示*示例0——WebView2示例*(窗体*示例2*、*示例3*、*示例4*)中使用的模式。 ## 三步模式 1. **选择文件夹。** 它必须存在于磁盘上并包含 `index.html`(加上页面需要的任何资源——脚本、样式、图片)。 2. **注册虚拟主机**映射到该文件夹。 3. **导航**到虚拟主机名下的URL。 挂接[**Ready**](/official/Reference/WebView2/WebView2/#ready)事件,以便在安装映射之前控件已完全初始化: ```vb Private Sub WebView_Ready() Handles WebView.Ready Dim folderPath As String = _ Environ$("USERPROFILE") & "\Documents\MyApp" WebView.SetVirtualHostNameToFolderMapping _ "myapp.example", folderPath & "\", wv2ResourceAllow WebView.Navigate "https://myapp.example/index.html" End Sub ``` 映射完成后,对 `https://myapp.example/<path>` 的每个请求都从 `folderPath\<path>` 提供。页面上的 `<script src="/script.js">` 解析为 `folderPath\script.js`,就像真正的Web服务器位于 `myapp.example` 上一样。 ## 选择主机名 Edge运行时在应用本地覆盖之前通过DNS解析虚拟主机名。碰巧可以在公共Internet上解析的主机名会在每个请求上引入短暂的(约2秒)停顿——参见[WebView2Feedback#2381](https://github.com/MicrosoftEdge/WebView2Feedback/issues/2381)。 安全的约定是选择一个永远不会解析的TLD下的名称,如 `.example`、`.invalid` 或 `.test`: | 推荐 | 避免 | |---------------------|-----------------------------| | `myapp.example` | `myapp.com`, `app.local` | | `editor.invalid` | `editor.dev` | | `assets.test` | `assets.io` | ## 在项目Resources文件夹中捆绑资源 大多数应用程序希望将HTML/JS/CSS打包在可执行文件*内部*,并在首次运行时释放到磁盘上。twinBASIC的 `Resources` 文件夹是存放它们的正确位置。 1. 在IDE的项目资源管理器中,展开**Resources**并添加子文件夹(右键→*添加新子文件夹*)。给它一个容易记住的名称,如 `WEB_APP`。 2. 将资源放入其中——`index.html`、`script.js`、`styles.css`,以及你需要的任何子目录。 在运行时,下面的辅助过程将 `Resources` 子文件夹的内容复制到本地路径。将其放入项目中的 `.twin` 模块: ```vb Module Files Private Sub CreateFile(ByVal Path As String, ByRef Data() As Byte) On Error Resume Next : Kill Path : On Error GoTo 0 Dim fileNum As Integer = FreeFile Open Path For Binary As fileNum Put fileNum, 1, Data Close fileNum End Sub Private Sub CreateLocalFileFromResource( _ ByVal OutputLocalFolderPath As String, _ ByVal InputResourceSubFolderName As String, _ ByVal ResourceName As String) Dim splitPath As Variant = Split(ResourceName, "~") On Error Resume Next : MkDir OutputLocalFolderPath : On Error GoTo 0 Dim i As Long For i = 0 To UBound(splitPath) - 1 OutputLocalFolderPath &= "\" & splitPath(i) On Error Resume Next : MkDir OutputLocalFolderPath : On Error GoTo 0 Next Dim Data() As Byte Data = LoadResData(ResourceName, InputResourceSubFolderName) CreateFile(OutputLocalFolderPath & "\" & splitPath(i), Data) End Sub [Description("Copy every file from a Resources subfolder onto disk. " & _ "'~' characters in resource names represent subfolders.")] Public Sub CopyResourcesFolderContentsToLocalPath( _ ByVal InputResourceSubFolderName As String, _ ByVal OutputLocalFolderPath As String) Dim resourceId As Variant For Each resourceId In LoadResIdList(InputResourceSubFolderName) CreateLocalFileFromResource _ OutputLocalFolderPath, InputResourceSubFolderName, resourceId Next End Sub End Module ``` [**LoadResIdList**](/official/Reference/VB/Global/#loadresidlist)返回指定子文件夹下的每个资源ID;[**LoadResData**](/official/Reference/VB/Global/#loadresdata)返回字节数据。辅助过程将每个资源名称按 `~` 分割,在磁盘上重建原始子目录树——当资源被编译时,twinBASIC IDE通过用 `~` 连接名称来展平嵌套文件夹。 ## 完整组合 完整的部署于`Ready`的模式如下: ```vb Private Sub WebView_Ready() Handles WebView.Ready ' Resources/WEB_APP/* is copied here on every launch. Dim folderPath As String = _ Environ$("USERPROFILE") & "\Documents\MyApp" CopyResourcesFolderContentsToLocalPath "WEB_APP", folderPath WebView.SetVirtualHostNameToFolderMapping _ "myapp.example", folderPath & "\", wv2ResourceAllow WebView.Navigate "https://myapp.example/index.html" End Sub ``` 部署完成后,应用程序可以启动DevTools([**OpenDevToolsWindow**](/official/Reference/WebView2/WebView2/#opendevtoolswindow))检查已加载的文件,用户可以直接编辑磁盘上的 `index.html` 并点击**刷新**——这在开发过程中的快速迭代中很有用。 ## 下一步 * [JavaScript互操作](/official/Tutorials/WebView2/JavaScript-interop) —— 托管页面如何与BASIC应用交换值和方法调用。 * [从twinBASIC驱动Monaco](/official/Tutorials/WebView2/Driving-Monaco) —— 基于此模式的完整案例研究。 * [SetVirtualHostNameToFolderMapping](/official/Reference/WebView2/WebView2/#setvirtualhostnametofoldermapping) —— 完整参考。 --- --- url: /zh/official/IDE/AddIns.md --- # 外接程序 外接程序是一个标准 DLL,导出 `tbCreateCompilerAddin` 并返回实现 [**AddIn**](/official/Reference/tbIDE/AddIn) 接口的对象。通过 IDE 启动时传递的 [**Host**](/official/Reference/tbIDE/Host) 对象,外接程序可以访问工具栏、工具窗口、调试控制台、当前项目、键盘快捷键和主题。[**tbIDE 包**](/official/Reference/tbIDE/) 文档提供了完整的 API 说明。 新建项目对话框包含外接程序模板(示例 10 至 16),涵盖从简单工具栏按钮到 HTML DOM 支持的工具窗口等多种模式。社区外接程序列在[**社区**](/official/IDE/AddIns/Community/)页面。 twinBASIC 支持两个外接程序安装位置。IDE 安装目录对所有用户账户可用,但 IDE 更新后可能需要重新安装。每用户应用数据文件夹在 IDE 升级后持久保留,无需管理员权限。 要通过 IDE 安装目录安装外接程序,解压并将每种架构的 DLL 复制到对应文件夹: `\twinBASIC_IDE_BETA_xxx\addins\win32\` `\twinBASIC_IDE_BETA_xxx\addins\win64\` --- --- url: /zh/official/IDE/Menu/Add-Ins.md --- # 外接程序菜单 ![外接程序菜单](Images/Menu_Add-Ins.png "外接程序菜单") {无外接程序加载} 打开项目后: ![全局搜索 - 外接程序菜单](Images/Menu_Add-Ins_GlobalSearch.png "全局搜索 - 外接程序菜单") 点击此菜单选项将显示 > 🛈 抱歉,此菜单选项尚未实现 ![全局搜索 - 弹窗](Images/GlobalSearch-Popup.png "全局搜索 - 弹窗") --- --- url: /zh/official/IDE/Webpage.md --- # 网页 ![Webpage](/assets/Webpage.D-3VPVCS.png "Webpage") 网页面板在 IDE 中内嵌一个浏览器视图,用于显示在线内容——如文档或发行说明——无需打开外部浏览器。 --- --- url: /zh/official/Features/Language/Delegates.md --- # 用于间接调用的委托类型 twinBASIC 原生支持通过指针调用函数,使用 `Delegate` 语法。twinBASIC 中的委托是与 LongPtr 兼容的函数指针类型。`AddressOf` 返回委托类型,也与 `LongPtr` 向后兼容。 ## 基本用法 语法如下: ```vb Private Delegate Function Delegate1 (ByVal A As Long, ByVal B As Long) As Long Private Sub Command1_Click() Dim myDelegate As Delegate1 = AddressOf Addition MsgBox "Answer: " & myDelegate(5, 6) End Sub Public Function Addition(ByVal A As Long, ByVal B As Long) As Long Return A + B End Function ``` ## 高级用法 委托类型也可以在接口/API 声明中以及作为用户定义类型的成员使用。例如 `ChooseColor` API: ```vb Public Delegate Function CCHookProc (ByVal hwnd As LongPtr, ByVal uMsg As Long, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As LongPtr Public Type CHOOSECOLOR lStructSize As Long hwndOwner As LongPtr hInstance As LongPtr rgbResult As Long lpCustColors As LongPtr Flags As ChooseColorFlags lCustData As LongPtr lpfnHook As CCHookProc 'Delegate function pointer type instead of LongPtr lpTemplateName As LongPtr End Type ``` 如果你已有代码将 `Long`/`LongPtr` 赋值给 `lpfnHook` 成员,它将继续正常工作,但现在你还可以获得类型安全的好处,将其设置为匹配委托的方法: ```vb Dim tCC As CHOOSECOLOR tCC.lpfnHook = AddressOf ChooseColorHookProc '... Public Function ChooseColorHookProc(ByVal hwnd As LongPtr, ByVal uMsg As Long, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As LongPtr End Function ``` --- --- url: /zh/packages/vbccr/text/textboxw.md description: 文本框控件(TextBoxW) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 文本框控件(TextBoxW) 提供增强的文本框,支持Unicode、密码字符、气球提示、网络地址验证、拖放文件和OLE拖放。 ## 枚举 ### TxtCharacterCasingConstants 字符大小写常量。 | 常量 | 值 | 说明 | |------|-----|------| | TxtCharacterCasingNormal | 0 | 正常(不转换大小写) | | TxtCharacterCasingUpper | 1 | 转换为大写 | | TxtCharacterCasingLower | 2 | 转换为小写 | ### TxtIconConstants 气球提示图标常量。 | 常量 | 值 | 说明 | |------|-----|------| | TxtIconNone | 0 | 无图标 | | TxtIconInfo | 1 | 信息图标 | | TxtIconWarning | 2 | 警告图标 | | TxtIconError | 3 | 错误图标 | ### TxtNetAddressFormatConstants 网络地址格式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TxtNetAddressFormatString | 0 | 字符串格式 | | TxtNetAddressFormatHostName | 1 | 主机名格式 | | TxtNetAddressFormatIPv4 | 2 | IPv4格式 | | TxtNetAddressFormatIPv6 | 3 | IPv6格式 | ### TxtNetAddressTypeConstants 网络地址类型常量。 | 常量 | 值 | 说明 | |------|-----|------| | TxtNetAddressTypeNone | 0 | 无 | | TxtNetAddressTypeIPv4 | 1 | IPv4地址 | | TxtNetAddressTypeIPv6 | 2 | IPv6地址 | | TxtNetAddressTypeIPv6WithScope | 3 | 带作用域的IPv6地址 | | TxtNetAddressTypeDNS | 4 | DNS名称 | | TxtNetAddressTypeNetBIOS | 5 | NetBIOS名称 | | TxtNetAddressTypeUnspecified | 6 | 未指定类型 | | TxtNetAddressTypeNamedPipe | 7 | 命名管道 | | TxtNetAddressTypeEmailAddress | 8 | 电子邮件地址 | | TxtNetAddressTypeURL | 9 | URL地址 | | TxtNetAddressTypeURLKnownSuffix | 10 | 已知后缀的URL | | TxtNetAddressTypeFriendlyDNS | 11 | 友好DNS名称 | | TxtNetAddressTypeDNSSimpleLabel | 12 | 单标签DNS名称 | | TxtNetAddressTypeAddressMask | 13 | 地址掩码 | | TxtNetAddressTypeFileName | 14 | 文件名 | | TxtNetAddressTypeAny | 15 | 任意地址 | | TxtNetAddressTypeAnyLocal | 16 | 任意本地地址 | | TxtNetAddressTypeIPv4MappedIPv6 | 17 | IPv4映射的IPv6地址 | | TxtNetAddressTypeIPv4TranslatedIPv6 | 18 | IPv4转换的IPv6地址 | | TxtNetAddressTypeIPv4TeredoIPv6 | 19 | Teredo IPv6地址 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### Container ```vb Public Property Get Container() As Object Public Property Set Container(ByVal Value As Object) ``` 返回/设置对象的容器。 ### Left ```vb Public Property Get Left() As Single Public Property Let Left(ByVal Value As Single) ``` 返回/设置对象与其容器左边缘的距离。 ### Top ```vb Public Property Get Top() As Single Public Property Let Top(ByVal Value As Single) ``` 返回/设置对象与其容器顶边缘的距离。 ### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 返回/设置对象的宽度。 ### Height ```vb Public Property Get Height() As Single Public Property Let Height(ByVal Value As Single) ``` 返回/设置对象的高度。 ### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 返回/设置鼠标悬停时显示的提示文本。 ### WhatsThisHelpID ```vb Public Property Get WhatsThisHelpID() As Long Public Property Let WhatsThisHelpID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### DragIcon ```vb Public Property Get DragIcon() As IPictureDisp Public Property Let DragIcon(ByVal Value As IPictureDisp) Public Property Set DragIcon(ByVal Value As IPictureDisp) ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Public Property Get DragMode() As Integer Public Property Let DragMode(ByVal Value As Integer) ``` 返回/设置拖动模式(手动或自动)。 ### hWnd ```vb Public Property Get hWnd() As LongPtr ``` 返回控件句柄。 ### hWndUserControl ```vb Public Property Get hWndUserControl() As LongPtr ``` 返回UserControl句柄。 ### Font ```vb Public Property Get Font() As StdFont Public Property Let Font(ByVal NewFont As StdFont) Public Property Set Font(ByVal NewFont As StdFont) ``` 返回/设置字体。 ### VisualStyles ```vb Public Property Get VisualStyles() As Boolean Public Property Let VisualStyles(ByVal Value As Boolean) ``` 返回/设置是否启用视觉样式。需要comctl32.dll 6.0或更高版本。 ### BackColor ```vb Public Property Get BackColor() As OLE_COLOR Public Property Let BackColor(ByVal Value As OLE_COLOR) ``` 返回/设置背景色。 ### ForeColor ```vb Public Property Get ForeColor() As OLE_COLOR Public Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 返回/设置前景色。 ### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 返回/设置对象是否能响应用户事件。 ### AllowDropFiles ```vb Public Property Get AllowDropFiles() As Boolean Public Property Let AllowDropFiles(ByVal Value As Boolean) ``` 返回/设置是否允许拖放文件。 ### OLEDragMode ```vb Public Property Get OLEDragMode() As Integer Public Property Let OLEDragMode(ByVal Value As Integer) ``` 返回/设置OLE拖动模式。 ### OLEDragDropScroll ```vb Public Property Get OLEDragDropScroll() As Boolean Public Property Let OLEDragDropScroll(ByVal Value As Boolean) ``` 返回/设置OLE拖放时是否自动滚动。 ### OLEDropMode ```vb Public Property Get OLEDropMode() As OLEDropModeConstants Public Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` 返回/设置对象是否可以作为OLE放置目标。 ### MousePointer ```vb Public Property Get MousePointer() As CCMousePointerConstants Public Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 返回/设置鼠标悬停时显示的指针类型。参见通用枚举。 ### MouseIcon ```vb Public Property Get MouseIcon() As IPictureDisp Public Property Let MouseIcon(ByVal Value As IPictureDisp) Public Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Public Property Get MouseTrack() As Boolean Public Property Let MouseTrack(ByVal Value As Boolean) ``` 返回/设置是否在鼠标进入或离开控件时触发事件。 ### RightToLeft ```vb Public Property Get RightToLeft() As Boolean Public Property Let RightToLeft(ByVal Value As Boolean) ``` 返回/设置从右到左显示方向。 ### RightToLeftMode ```vb Public Property Get RightToLeftMode() As CCRightToLeftModeConstants Public Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 返回/设置从右到左模式。参见通用枚举。 ### BorderStyle ```vb Public Property Get BorderStyle() As Integer Public Property Let BorderStyle(ByVal Value As Integer) ``` 返回/设置边框样式。 ### Text ```vb Public Property Get Text() As String Public Property Let Text(ByVal Value As String) ``` 返回/设置文本内容。 ### Default ```vb Public Property Get Default() As Boolean Public Property Let Default(ByVal Value As Boolean) ``` 返回/设置是否为默认按钮(按Enter键触发)。 ### Alignment ```vb Public Property Get Alignment() As AlignmentConstants Public Property Let Alignment(ByVal Value As AlignmentConstants) ``` 返回/设置文本对齐方式。 ### AllowOnlyNumbers ```vb Public Property Get AllowOnlyNumbers() As Boolean Public Property Let AllowOnlyNumbers(ByVal Value As Boolean) ``` 返回/设置是否只允许输入数字。 ### Locked ```vb Public Property Get Locked() As Boolean Public Property Let Locked(ByVal Value As Boolean) ``` 返回/设置是否锁定编辑(仍可滚动和选择)。 ### HideSelection ```vb Public Property Get HideSelection() As Boolean Public Property Let HideSelection(ByVal Value As Boolean) ``` 返回/设置控件失去焦点时是否隐藏选中内容的突出显示。 ### PasswordChar ```vb Public Property Get PasswordChar() As String Public Property Let PasswordChar(ByVal Value As String) ``` 返回/设置密码掩码字符。 ### UseSystemPasswordChar ```vb Public Property Get UseSystemPasswordChar() As Boolean Public Property Let UseSystemPasswordChar(ByVal Value As Boolean) ``` 返回/设置是否使用系统默认密码字符。 ### MultiLine ```vb Public Property Get MultiLine() As Boolean Public Property Let MultiLine(ByVal Value As Boolean) ``` 返回/设置是否接受多行文本输入。 ### MaxLength ```vb Public Property Get MaxLength() As Long Public Property Let MaxLength(ByVal Value As Long) ``` 返回/设置最大字符数。0表示不限制。 ### ScrollBars ```vb Public Property Get ScrollBars() As Integer Public Property Let ScrollBars(ByVal Value As Integer) ``` 返回/设置滚动条样式。 ### CueBanner ```vb Public Property Get CueBanner() As String Public Property Let CueBanner(ByVal Value As String) ``` 返回/设置提示横幅文本(控件为空时显示)。 ### CueBannerAlways ```vb Public Property Get CueBannerAlways() As Boolean Public Property Let CueBannerAlways(ByVal Value As Boolean) ``` 返回/设置提示横幅是否始终显示(即使控件有焦点)。 ### CharacterCasing ```vb Public Property Get CharacterCasing() As TxtCharacterCasingConstants Public Property Let CharacterCasing(ByVal Value As TxtCharacterCasingConstants) ``` 返回/设置字符大小写转换方式。 ### WantReturn ```vb Public Property Get WantReturn() As Boolean Public Property Let WantReturn(ByVal Value As Boolean) ``` 返回/设置多行文本框中按Enter键是否插入换行符。 ### IMEMode ```vb Public Property Get IMEMode() As CCIMEModeConstants Public Property Let IMEMode(ByVal Value As CCIMEModeConstants) ``` 返回/设置输入法编辑器模式。参见通用枚举。 ### NetAddressValidator ```vb Public Property Get NetAddressValidator() As Boolean Public Property Let NetAddressValidator(ByVal Value As Boolean) ``` 返回/设置是否启用网络地址验证。 ### NetAddressType ```vb Public Property Get NetAddressType() As TxtNetAddressTypeConstants Public Property Let NetAddressType(ByVal Value As TxtNetAddressTypeConstants) ``` 返回/设置网络地址验证的类型。 ### AllowOverType ```vb Public Property Get AllowOverType() As Boolean Public Property Let AllowOverType(ByVal Value As Boolean) ``` 返回/设置是否允许改写模式。 ### OverTypeMode ```vb Public Property Get OverTypeMode() As Boolean Public Property Let OverTypeMode(ByVal Value As Boolean) ``` 返回/设置是否处于改写模式。 ### Modified ```vb Public Property Get Modified() As Boolean Public Property Let Modified(ByVal Value As Boolean) ``` 返回/设置文本是否已被修改。 ### TextLength ```vb Public Property Get TextLength() As Long ``` 返回文本长度。 ### SelStart ```vb Public Property Get SelStart() As Long Public Property Let SelStart(ByVal Value As Long) ``` 返回/设置选中内容的起始位置。 ### SelLength ```vb Public Property Get SelLength() As Long Public Property Let SelLength(ByVal Value As Long) ``` 返回/设置选中内容的长度。 ### SelText ```vb Public Property Get SelText() As String Public Property Let SelText(ByVal Value As String) ``` 返回/设置选中内容的文本。 ### LeftMargin ```vb Public Property Get LeftMargin() As Long Public Property Let LeftMargin(ByVal Value As Long) ``` 返回/设置左边距。 ### RightMargin ```vb Public Property Get RightMargin() As Long Public Property Let RightMargin(ByVal Value As Long) ``` 返回/设置右边距。 ## 方法 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘对象。 ### Copy ```vb Public Sub Copy() ``` 将选中内容复制到剪贴板。 ### Cut ```vb Public Sub Cut() ``` 将选中内容剪切到剪贴板。 ### Paste ```vb Public Sub Paste() ``` 将剪贴板内容粘贴到控件。 ### Clear ```vb Public Sub Clear() ``` 清除所有文本。 ### Undo ```vb Public Sub Undo() ``` 撤销上一次操作。 ### CanUndo ```vb Public Function CanUndo() As Boolean ``` 返回是否可以撤销。 ### ResetUndoQueue ```vb Public Sub ResetUndoQueue() ``` 重置撤销队列。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动OLE拖放操作。 ### GetLine ```vb Public Function GetLine(ByVal LineIndex As Long) As String ``` 获取指定行的文本内容。 ### GetLineCount ```vb Public Function GetLineCount() As Long ``` 获取文本行数。 ### ScrollToLine ```vb Public Sub ScrollToLine(ByVal LineIndex As Long) ``` 滚动到指定行。 ### ScrollToCaret ```vb Public Sub ScrollToCaret() ``` 滚动到光标位置。 ### CharFromPos ```vb Public Function CharFromPos(ByVal X As Long, ByVal Y As Long) As Long ``` 根据坐标获取字符索引。 ### GetLineFromChar ```vb Public Function GetLineFromChar(ByVal CharIndex As Long) As Long ``` 根据字符索引获取行号。 ### ShowBalloonTip ```vb Public Sub ShowBalloonTip(ByVal Title As String, ByVal Text As String, ByVal Icon As TxtIconConstants) ``` 显示气球提示。 ### HideBalloonTip ```vb Public Sub HideBalloonTip() ``` 隐藏气球提示。 ### ValidateNetAddress ```vb Public Function ValidateNetAddress() As Long ``` 验证网络地址,返回0表示有效。 ### ShowNetAddressErrorTip ```vb Public Sub ShowNetAddressErrorTip() ``` 根据验证结果显示网络地址错误提示。 ### NetAddressFormat ```vb Public Property Get NetAddressFormat() As TxtNetAddressFormatConstants ``` 返回网络地址格式。 ### NetAddressString ```vb Public Property Get NetAddressString() As String ``` 返回网络地址字符串。 ### NetAddressPortNumber ```vb Public Property Get NetAddressPortNumber() As Long ``` 返回网络地址端口号。 ### NetAddressPrefixLength ```vb Public Property Get NetAddressPrefixLength() As Long ``` 返回网络地址前缀长度。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移至控件。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置Z顺序。 ## 事件 ### Click ```vb Public Event Click() ``` 用户单击控件时触发。 ### DblClick ```vb Public Event DblClick() ``` 用户双击控件时触发。 ### Change ```vb Public Event Change() ``` 文本内容改变时触发。 ### MaxText ```vb Public Event MaxText() ``` 输入文本超过MaxLength限制时触发。 ### DropFiles ```vb Public Event DropFiles(ByVal Files As Variant) ``` 拖放文件到控件时触发。Files为文件路径数组。 ### Scroll ```vb Public Event Scroll() ``` 文本滚动时触发。 ### ContextMenu ```vb Public Event ContextMenu(ByVal X As Single, ByVal Y As Single, ByRef Handled As Boolean) ``` 请求上下文菜单时触发。Handled为True时取消默认菜单。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(KeyCode As Integer, Shift As Integer) ``` 在KeyDown事件之前触发,用于预处理键盘输入。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(KeyCode As Integer, Shift As Integer) ``` 在KeyUp事件之前触发。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下键盘按键时触发。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放键盘按键时触发。 ### KeyPress ```vb Public Event KeyPress(KeyAscii As Integer) ``` 按下并释放ANSI键时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件区域时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件区域时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE拖放操作完成时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE拖放操作放置时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE拖放操作悬停时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE拖放操作给反馈时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE拖放操作设置数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE拖放操作开始时触发。 ## 代码示例 ### 基本用法 ```vb ' 设置多行文本框 With TextBoxW1 .MultiLine = True .ScrollBars = 3 .MaxLength = 5000 .WantReturn = True .CueBanner = "请输入内容..." End With ' 使用密码框 With TextBoxW1 .PasswordChar = "*" .UseSystemPasswordChar = True .MaxLength = 20 End With ' 网络地址验证 TextBoxW1.NetAddressValidator = True TextBoxW1.NetAddressType = TxtNetAddressTypeURL Private Sub Command1_Click() If TextBoxW1.ValidateNetAddress() = 0 Then MsgBox "地址有效: " & TextBoxW1.NetAddressString Else TextBoxW1.ShowNetAddressErrorTip End If End Sub ' 气球提示 TextBoxW1.ShowBalloonTip "输入错误", "请输入有效的邮箱地址", TxtIconError ' 拖放文件 Private Sub TextBoxW1_DropFiles(ByVal Files As Variant) Dim i As Long For i = LBound(Files) To UBound(Files) Debug.Print "文件: " & Files(i) Next i End Sub ``` --- --- url: /zh/official/Documentation.md --- # 文档开发 本节涵盖与twinBASIC文档相关的一切:编译器和IDE依赖的URL契约、内容贡献者的构建/预览/部署工作流、仓库中的每个脚本和批处理文件,以及生成站点的 `tbdocs` 静态站点生成器的内部机制。 ## 工具链概览 三个命令处理整个构建和验证工作流。`build.bat` 从Markdown源生成三个输出树;`check.bat` 验证两个HTML树的链接完整性;`book.bat` 从第三个渲染PDF。 ![Toolchain overview](/assets/images/mmd/toolchain-overview.svg) `build.bat` 必须在另外两个之前运行——`check.bat` 从 `_site/` 和 `_site-offline/` 读取,而 `book.bat` 从 `_site-pdf/` 读取。干净的 `build.bat && check.bat` 是"可以提交"的标准。 ## 构建管线 单次 `build.bat` 运行驱动 `tbdocs` 经过八个阶段加一个Mermaid预阶段。 ![Build pipeline, eight phases plus the Mermaid pre-phase](/assets/images/mmd/build-phases.svg) 阶段1--6生成在线树(`_site/`)。阶段7将其镜像为 `file://` 可浏览的离线副本。阶段8组装稀疏PDF源树,`book.bat` 稍后将其渲染为最终PDF。[管线阶段](/official/Documentation/Pipeline-Stages)页面记录了每个阶段的接口契约;[tbdocs构建器](/official/Documentation/Builder)页面涵盖了设计原理。 ## 子页面 * [永久链接](/official/Documentation/Permanent-Links) —— IDE帮助系统、源代码中 `[Documentation(...)]` 属性链接和外部引用解析所依赖的稳定 `/tB/` URL契约。 * [构建与部署](/official/Documentation/Building) —— 编辑内容的日常工作流:要求、构建、本地服务、链接检查、Mermaid图、截图和GitHub Pages部署。 * [工具与脚本](/official/Documentation/Tools) —— 文档工具链中每个脚本、批处理文件和CLI标志的单行参考(目标读者:文档贡献者)。 * [tbdocs构建器](/official/Documentation/Builder) —— 位于[`builder/`](https://github.com/twinbasic/documentation/tree/main/builder)下的 `tbdocs` 静态站点生成器的详细技术文档。修改构建管线本身时阅读此页。子页面: * [管线阶段](/official/Documentation/Pipeline-Stages) —— 按阶段的接口参考:函数签名、读/写和每个导出符号。 * [书籍配置](/official/Documentation/Book-Configuration) —— PDF章节清单的 `_book.yml` 键参考。 * [扩展构建器](/official/Documentation/Extending) —— 添加新管线阶段或markdown-it插件的教程。 * [PDF生成](/official/Documentation/PDF-Generation) —— PDF渲染器的内部机制:`render-book.mjs`、paged.browser.js和pdf-lib垫片。 * [库补丁](/official/Documentation/Fixes) —— 对 `paged.browser.js` 和 `fast-*.mjs` pdf-lib垫片的每项修改:上游问题、应用的修复和机制。 > AI生成 --- --- url: /zh/official/IDE/Menu/File.md --- # 文件菜单 ![File (Menu)](/assets/Menu_File.44veW5jh.png "File (Menu)") * 新建项目... CTRL + N * 打开项目... CTRL + O * 打开最近... * 关闭项目 *** * 保存项目 CTRL + S * 项目另存为... *** * 导出项目... * 保存当前文档 *** * 构建 * 清理 *** * 退出 ALT + F4 --- --- url: /zh/official/Features/Standard-Library/File-IO.md --- # 文件 I/O 的编码选项 `Open` 语句通过新的 `Encoding` 关键字和变量支持 Unicode,允许你指定多种编码选项,除了标准的 Unicode 选项外。 ## 用法示例 ```vb Open "C:\MyFile.txt" For Input Encoding utf_8 As #1 ``` ## 支持的编码 参见 **Open** 语句参考页面上的[文本编码表](/official/Reference/Core/Open#text-encodings)。 --- --- url: /zh/official/Features/GUI-Components/Windowless.md --- # 无窗口控件与普通(有窗口)控件 | 特性 | **无窗口控件** | **普通控件** | | --- | --- | --- | | **窗口句柄 (hWnd)** | 无 hWnd;直接绘制在容器的设备上下文 (DC) 上 | 每个都有自己的 hWnd | | **性能** | 开销更低,渲染更快\[^3] | 由于窗口管理,开销更高 | | **透明和形状** | 支持透明背景和非矩形区域 | 限于不透明的矩形区域 | | **Z 序行为** | 始终渲染在有窗口控件下方\[^4] | 可以浮在其他控件上方 | | **输入处理** | 需要通过容器手动路由输入(键盘、鼠标) | 操作系统原生处理输入 | | **无障碍** | 需要通过 `IAccessibleWindowlessSite` 等接口显式支持\[^1] | 内置无障碍支持 | | **已知问题** | 可能需要自定义处理来解决 twinBASIC 中的已知问题(例如,事件不触发)\[^2] | 更完整和稳定 | | **适用场景** | 适合轻量级、静态 UI 元素(例如标签、图像) | 适合交互式或可聚焦控件(例如文本框、按钮) | *** ### 无窗口控件的优势 * **性能提升**:无 hWnd 意味着更少的 GDI 开销——适合包含大量静态元素的窗体。3 * **视觉灵活性**:支持透明或自定义形状的 UI 元素(例如圆角按钮、覆盖层)。 * **资源效率**:有助于避免在控件密集的 UI 中达到系统句柄限制。 *** ### 缺点 * **复杂的输入处理**:你必须从容器手动转发焦点、鼠标和键盘事件。 * **Z 序限制**:不能出现在有窗口控件上方——对于覆盖层或工具提示有问题。4 * **怪癖**:twinBASIC 在无窗口控件事件和其他功能方面存在一些已知问题。2 * **无障碍开销**:需要额外工作来暴露无障碍接口。1 *** \[^1]: [IAccessibleWindowlessSite 接口 - Microsoft Learn](https://learn.microsoft.com/en-us/windows/win32/api/oleacc/nn-oleacc-iaccessiblewindowlesssite) \[^2]: 最初报告于 [twinBASIC GitHub Issue #1310 -- 无窗口锚定调整大小 Bug](https://github.com/twinbasic/twinbasic/issues/1310)。已在 BETA 162 中修复。 \[^3]: Windows UI 架构中 [GDI 对象句柄](https://learn.microsoft.com/en-us/windows/win32/sysinfo/gdi-objects)和 [hWnd 用户对象句柄](https://learn.microsoft.com/en-us/windows/win32/sysinfo/user-objects)概述:[MSDN -- 窗口资源](https://learn.microsoft.com/en-us/windows/win32/winmsg/about-windows) \[^4]: Z 序渲染和 Windows 控件分层背景:[Windows 控件 - Z 序](https://learn.microsoft.com/en-us/windows/win32/winmsg/window-features#z-order) *** ## 使用场景示例 ### 何时选择无窗口控件 * **静态 UI 元素**:适合标签、装饰图像或非交互式覆盖层,此时性能和视觉灵活性是关键。 * **透明或自定义形状元素**:适合圆角按钮、自定义形状覆盖层或透明背景。 * **控件密集的窗体**:在可能超过系统句柄限制的场景中很有用,如包含数百个静态元素的仪表板。 ### 何时选择普通(有窗口)控件 * **交互式元素**:适合文本框、按钮、下拉菜单或任何需要用户输入或焦点的控件。 * **分层 UI 组件**:适合工具提示、模态对话框或任何需要浮在其他控件上方的元素。 * **无障碍要求**:适合内置无障碍支持至关重要的应用程序。 ### 混合布局 * **结合两种类型**:使用无窗口控件用于静态元素,使用普通控件用于交互式元素,以平衡性能和功能。 * **示例场景**:一个仪表板,静态标签和图表(无窗口)旁边是交互式筛选器和按钮(有窗口)。 *** ## 实际示例 ### 无窗口控件示例 * **[SweetIceLolly/VB6-MemoryDC](https://github.com/SweetIceLolly/VB6-MemoryDC)** — 一个使用内存设备上下文进行离屏渲染的 VB6 项目。非常适合说明自定义绘制的无窗口 UI 元素。 * **[fafalone/WinDevLib](https://github.com/fafalone/WinDevLib)** — 一个具有底层 Win32 API 封装的 twinBASIC 库。包括绕过 hWnd 的自定义渲染和控件逻辑示例。 * **[fafalone/EventTrace](https://github.com/fafalone/EventTrace)** — ETW 文件活动监视器的 twinBASIC 移植。使用轻量级的非窗口 UI 元素以提升性能。 ### 有窗口控件示例 * **[fafalone/UIRibbonDemos](https://github.com/fafalone/UIRibbonDemos)** — Windows Ribbon UI 框架的 twinBASIC 演示。展示具有完整无障碍支持和 Z 序行为的交互式 hWnd 支持的控件。 * **[SweetIceLolly/DragControlsIDE](https://github.com/SweetIceLolly/DragControlsIDE)** — 基于 VB6 的类 IDE 接口,具有可拖动的有窗口控件。用于演示布局和锚定行为。 * **[SweetIceLolly/DragControlsIDE-v2](https://github.com/SweetIceLolly/DragControlsIDE-v2)** — 上述项目的更新版本。 * **[bclothier/TwinBasicSevenZip](https://github.com/bclothier/TwinBasicSevenZip)** — 7-Zip COM 集成的 twinBASIC 封装。包含使用标准有窗口控件的文件选择和进度 UI。 *** ### 在 VBx/twinBASIC 中打印混合控件窗体 #### 开箱即用的功能 * **有窗口控件**(例如 `TextBox`、`CommandButton`)通常可以在 VB6 中使用 `Form.DrawToDC` 或 `PrintForm` 捕获,或在 twinBASIC 中通过渲染窗体的 `hDC` 来捕获。 * **无窗口控件**没有自己的 `hWnd` 或设备上下文,因此除非你显式绘制它们,否则它们不会出现。 *** #### 推荐策略 1. **将整个窗体渲染到位图** * 在 VB6 中:使用 `BitBlt` 或 `PaintPicture` 复制窗体的可见区域。 * 在 TwinBASIC 中:使用窗体的 [`Canvas`](/official/Reference/CustomControls/Framework/Canvas) 或 [`ICustomControl.Paint`](/official/Reference/CustomControls/Framework/ICustomControl#paint) 逻辑手动将无窗口元素渲染到位图。参见 [CustomControls 包参考](/official/Reference/CustomControls/) 获取完整框架 API。 2. **确保无窗口控件被绘制** * 对于使用 [`ICustomControl.Paint`](/official/Reference/CustomControls/Framework/ICustomControl#paint) 的[自定义控件](/official/Reference/CustomControls/),手动调用其绘制例程到同一个位图或 `DC`。 * 如果使用 [`Canvas.RuntimeUICCCanvasAddElement`](/official/Reference/CustomControls/Framework/Canvas#runtimeuicccanvasaddelement),使用与运行时相同的布局逻辑模拟一次绘制。 3. **将位图发送到打印机** * 在 VB6 中使用 `Printer.PaintPicture` 或在 twinBASIC 中使用 `Printer.Canvas.DrawImage`(如果可用)。 * 或者,使用 `GDI` 或 `GDI+` API 将位图发送到打印机的 `DC`。 *** #### 精度提示 * **Z 序很重要**:由于无窗口控件在有窗口控件后面渲染,应先绘制它们。 * **DPI 感知**:将打印机的 DPI 与窗体的布局比例匹配以避免模糊输出。 * **离屏渲染**:考虑在打印前先渲染到内存 `DC` 或 `StdPicture` 对象以避免闪烁或部分绘制。 *** #### twinBASIC 代码片段 ```vb ' Example: Printing a Mixed-Control Form in twinBASIC Dim bmp As StdPicture Set bmp = CreateCompatibleBitmap(Me.Width, Me.Height) ' Render windowless controls For Each ctrl In Me.Controls If TypeOf ctrl Is ICustomControl Then ctrl.Paint bmp.Canvas End If Next ' Render windowed controls Me.DrawToDC bmp.Canvas ' Send to printer Printer.Canvas.DrawImage bmp, 0, 0 Printer.EndDoc ``` *** 对于 DPI 感知的多显示器布局工作,无窗口控件很有用——尤其是用于静态或装饰元素——但在涉及交互性或分层时需要更多手动处理。如果你正在构建混合布局,结合两种类型可能给你两全其美的效果。 --- --- url: /zh/packages/vbccr/system/sysinfo.md description: 系统信息控件(SysInfo) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 系统信息控件(SysInfo) 提供系统事件监测,包括设备变更、电源状态、显示设置更改和主题变更等通知。运行时不可见。 ## 枚举 ### SysDeviceTypeConstants 设备类型常量。 | 常量 | 值 | 说明 | |------|-----|------| | SysDeviceTypeOEM | DBT\_DEVTYP\_OEM | OEM设备 | | SysDeviceTypeDevNode | DBT\_DEVTYP\_DEVNODE | 设备节点 | | SysDeviceTypeVolume | DBT\_DEVTYP\_VOLUME | 卷设备 | | SysDeviceTypePort | DBT\_DEVTYP\_PORT | 端口设备 | | SysDeviceTypeDevInterface | DBT\_DEVTYP\_DEVICEINTERFACE | 设备接口 | ### SysACStatusConstants 交流电源状态常量。 | 常量 | 值 | 说明 | |------|-----|------| | SysACStatusOffline | 0 | 离线(使用电池) | | SysACStatusOnline | 1 | 在线(使用交流电) | | SysACStatusUnknown | 255 | 未知 | ### SysBatteryStatusConstants 电池状态常量。 | 常量 | 值 | 说明 | |------|-----|------| | SysBatteryStatusHigh | 1 | 电量高 | | SysBatteryStatusLow | 2 | 电量低 | | SysBatteryStatusCritical | 4 | 电量严重不足 | | SysBatteryStatusCharging | 8 | 正在充电 | | SysBatteryStatusNone | 128 | 无电池 | | SysBatteryStatusUnknown | 255 | 未知 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### hMain ```vb Public Property Get hMain() As LongPtr ``` 返回主窗口句柄。 ### ACStatus ```vb Public Property Get ACStatus() As SysACStatusConstants ``` 返回交流电源状态。 ### BatteryFullTime ```vb Public Property Get BatteryFullTime() As Long ``` 返回电池完全充满所需的时间(秒)。 ### BatteryLifePercent ```vb Public Property Get BatteryLifePercent() As Integer ``` 返回电池剩余电量百分比。 ### BatteryLifeTime ```vb Public Property Get BatteryLifeTime() As Long ``` 返回电池剩余使用时间(秒)。 ### BatteryStatus ```vb Public Property Get BatteryStatus() As SysBatteryStatusConstants ``` 返回电池状态。 ### WorkAreaLeft ```vb Public Property Get WorkAreaLeft() As Single ``` 返回工作区左边距。 ### WorkAreaTop ```vb Public Property Get WorkAreaTop() As Single ``` 返回工作区顶边距。 ### WorkAreaWidth ```vb Public Property Get WorkAreaWidth() As Single ``` 返回工作区宽度。 ### WorkAreaHeight ```vb Public Property Get WorkAreaHeight() As Single ``` 返回工作区高度。 ### ScrollBarSize ```vb Public Property Get ScrollBarSize() As Single ``` 返回滚动条尺寸。 ## 事件 ### SysColorsChanged ```vb Public Event SysColorsChanged() ``` 系统颜色改变时触发。 ### SettingChanged ```vb Public Event SettingChanged(ByVal Item As Long, ByVal Section As String) ``` 系统设置改变时触发。Item为设置项,Section为设置节。 ### DevModeChanged ```vb Public Event DevModeChanged() ``` 设备模式改变时触发。 ### TimeChanged ```vb Public Event TimeChanged() ``` 系统时间改变时触发。 ### FontChanged ```vb Public Event FontChanged() ``` 系统字体改变时触发。 ### DisplayChanged ```vb Public Event DisplayChanged(ByVal NewColorDepth As Long, ByVal NewWidth As Single, ByVal NewHeight As Single) ``` 显示设置改变时触发。NewColorDepth为新颜色深度,NewWidth/NewHeight为新分辨率。 ### DeviceArrival ```vb Public Event DeviceArrival(ByVal DeviceType As SysDeviceTypeConstants, ByVal DeviceID As Long, ByVal DeviceName As String, ByVal DeviceData As Long) ``` 设备插入时触发。 ### DeviceQueryRemove ```vb Public Event DeviceQueryRemove(ByVal DeviceType As SysDeviceTypeConstants, ByVal DeviceID As Long, ByVal DeviceName As String, ByVal DeviceData As Long, ByRef Cancel As Boolean) ``` 设备即将移除时触发。Cancel为True时阻止移除。 ### DeviceQueryRemoveFailed ```vb Public Event DeviceQueryRemoveFailed(ByVal DeviceType As SysDeviceTypeConstants, ByVal DeviceID As Long, ByVal DeviceName As String, ByVal DeviceData As Long) ``` 设备移除查询失败时触发。 ### DeviceRemoveComplete ```vb Public Event DeviceRemoveComplete(ByVal DeviceType As SysDeviceTypeConstants, ByVal DeviceID As Long, ByVal DeviceName As String, ByVal DeviceData As Long) ``` 设备移除完成时触发。 ### DeviceRemovePending ```vb Public Event DeviceRemovePending(ByVal DeviceType As SysDeviceTypeConstants, ByVal DeviceID As Long, ByVal DeviceName As String, ByVal DeviceData As Long) ``` 设备即将被移除时触发。 ### DevNodesChanged ```vb Public Event DevNodesChanged() ``` 设备节点改变时触发。 ### QueryChangeConfig ```vb Public Event QueryChangeConfig(ByRef Cancel As Boolean) ``` 配置即将改变时触发。Cancel为True时阻止改变。 ### ConfigChangeCancelled ```vb Public Event ConfigChangeCancelled() ``` 配置改变被取消时触发。 ### ConfigChanged ```vb Public Event ConfigChanged() ``` 配置改变完成时触发。 ### PowerQuerySuspend ```vb Public Event PowerQuerySuspend(ByRef Cancel As Boolean) ``` 系统即将挂起时触发。Cancel为True时阻止挂起。 ### PowerQuerySuspendFailed ```vb Public Event PowerQuerySuspendFailed() ``` 系统挂起请求失败时触发。 ### PowerResume ```vb Public Event PowerResume() ``` 系统从挂起恢复时触发。 ### PowerStatusChanged ```vb Public Event PowerStatusChanged() ``` 电源状态改变时触发。 ### PowerSuspend ```vb Public Event PowerSuspend() ``` 系统即将挂起时触发。 ### ThemeChanged ```vb Public Event ThemeChanged() ``` 系统主题改变时触发。 ## 代码示例 ### 基本用法 ```vb ' 监测电源状态 Private Sub SysInfo1_PowerStatusChanged() Select Case SysInfo1.ACStatus Case SysACStatusOnline Debug.Print "使用交流电源" Case SysACStatusOffline Debug.Print "使用电池, 剩余: " & SysInfo1.BatteryLifePercent & "%" End Select End Sub ' 监测设备变更 Private Sub SysInfo1_DeviceArrival(ByVal DeviceType As SysDeviceTypeConstants, _ ByVal DeviceID As Long, ByVal DeviceName As String, ByVal DeviceData As Long) Debug.Print "设备插入: " & DeviceName End Sub ' 监测显示设置变更 Private Sub SysInfo1_DisplayChanged(ByVal NewColorDepth As Long, _ ByVal NewWidth As Single, ByVal NewHeight As Single) Debug.Print "分辨率: " & NewWidth & "x" & NewHeight & " 色深: " & NewColorDepth End Sub ``` --- --- url: /zh/official/Features/Compiler-IDE/IDE-Features.md --- # 现代 IDE 功能 虽然 twinBASIC IDE 仍有许多计划中的工作,但它已经包含许多在其他现代 IDE 中能找到而古老 VBx IDE 中没有的便利功能。 ## 主题系统 完全支持主题自定义,内置暗色(默认)、亮色和经典(亮色)主题,并提供基于继承的简便系统,可通过 CSS 文件添加自定义主题。 ## 代码导航和结构 * **代码折叠**,支持通过 `#Region "name" ... #End Region` 块定义可折叠的自定义区域。 * **粘性滚动**,在顶部保持上下文行,显示模块、区域、方法、`With` 块等主要代码段落。 * **缩进参考线**,沿常见缩进位置绘制线条帮助对齐。 * **代码缩略图**,在滚动条旁边显示代码结构的图形概览,辅助滚动定位。 ## 编辑功能 * **完全可自定义的键盘快捷键**,涵盖所有命令,可保存和切换不同方案。 * **粘贴时自动缩进**。 * **粘贴为注释**。 * **内联代码提示**,在块末尾提供注释标注该块的类型(见图)。 * **括号和方括号颜色匹配**。 ## 高级功能 * **完整 Unicode 支持**,在 .twin 文件中,你可以在注释和字符串中使用字体的完整 Unicode 范围。 * **高级信息弹窗**,显示 UDT 成员的偏移量、通过 `Len()` 和 `LenB()` 的总大小及其对齐方式;以及接口和类的 v-table 条目偏移量及其继承链。 * **类型库查看器**,用于控件和 TLB 文件,以 twinBASIC 风格的语法显示完整内容,而非 ODL。 ## 面板和窗口 * **历史面板**,包含最近修改方法的列表。 * **大纲面板**,带有可选类别。 * **问题面板**,提供当前所有错误和警告的列表(可以筛选只显示其中一种)。 ## 窗体设计器增强 在窗体设计器上,`Visible = False` 的控件会显示为半透明以直观指示。此外,按住 Control 键会显示每个 Tab Stop 的 Tab 键索引。 ![image](/assets/014a1d28-30af-4a4d-8b9b-83ab6084f00a.Dq9Q2C3y.png) [完整大图](../Images/fafaloneIDEscreenshot1.png) ### 新的基于代码的项目资源管理器 新的基于代码结构的项目资源管理器: ![image](/assets/9a5c50d5-a9f8-44a7-96f7-ae84548bd7ef.YtjenBmj.png) 经典的基于文件的视图仍然是默认使用的,你可以通过切换按钮激活新视图: ![image](/assets/b000d3aa-3689-4d94-88e3-bca44f8b7de6.DdxYXKUA.png) ## 以 JSON 格式查看窗体和包 项目窗体和包以 JSON 格式数据存储,你可以在项目资源管理器中右键点击并选择"View as JSON"来查看。这对于包特别有用,因为它以更易解析的格式暴露了整个代码。 ![image](/assets/22660f54-ff5d-4b21-93d3-39715f1f35ed.DPbNvO4N.png) ![image](/assets/a6525b1d-ac22-4303-ae27-7984c20eba0c.B8dWFGYA.png) --- --- url: /zh/official/IDE/Menu/Project.md --- # 项目菜单 ![项目菜单](/assets/Menu_Project.B4GSOMrQ.png "项目菜单") * 添加 *** * 引用 * 项目设置 *** * 打开项目文件夹... * 打开生成输出文件夹... ## 添加 **添加**与在[项目资源管理器](/official/IDE/Project-Explorer)中右键添加的功能相同。 ![右键 - 添加](/assets/RightClick-Add.BC9Rjdot.png "右键 - 添加") ## 引用 参见按"project.references"筛选的[项目设置](/official/IDE/Project-Settings)。 ![库引用 - 项目设置](/assets/ProjectSettings_LibraryReferences.DnG_2vGd.png "库引用 - 项目设置") ## 项目设置 参见[项目设置](/official/IDE/Project-Settings)。 --- --- url: /zh/official/IDE/New-Project.md --- # 新建项目 ![新建/打开项目](/assets/New_Project.ClFan8Zq.png "新建/打开项目") ![文件(菜单)](/assets/Menu_File.44veW5jh.png "文件(菜单)") 快捷键:CTRL + N ## 选项 * 标准 Exe * ActiveX 控件 * ActiveX DLL * 标准 DLL * 标准 EXE(控制台应用) * 标准 EXE(附带 VBCCR v1.8) * 从 VBP 导入... * 从文件夹导入... 浏览 | 打开 | 取消 # 示例 ![示例](/assets/New_Project_Samples.CGB-fdBo.png "示例") 0. 报表(实验性) 1. WebView2 示例 2. GetIPAddress 3. MyCodeLibrary 4. MyVBEAddin(含 ToolWindow) 5. MyCOMAddin 6. CustomControls 7. Package 8. FilePropertyViewer(CustomControls) 9. ActiveX 控件 WebView2 + Monaco 10. twinBASIC IDE Addin 11. twinBASIC IDE Addin(图表) 12. twinBASIC IDE Addin(Monaco) 13. twinBASIC IDE Addin(ListView) 14. twinBASIC IDE Addin(VirutalListView) 15. twinBASIC IDE Addin(全局搜索) 16. twinBASIC IDE Addin(TODO 组件演示) 17. 静态库示例(SQLITE3) 18. 静态库示例(libdeflate) 19. MDI 窗体 20. TreeView + ListView + ImageList 21. Windows 服务简单示例 22. Windows 服务复杂示例(含事件日志和 IPC) 23. OOP 继承示例(Animals) # 最近 如果从未打开过项目,或已移除所有项目,此选项卡将为空白。 ![最近](/assets/New_Project_Recent_1.C9Rkot1S.png "最近") 将显示最近项目的列表,列表会根据项目数量自动调整大小。 ![最近](/assets/New_Project_Recent_2.DzUJhhC7.png "最近") *移除路径* 点击 X 可从列表中移除。 --- --- url: /zh/official/Features/Project-Configuration/Project-Types.md --- # 项目类型 twinBASIC 为传统 EXE 和 ActiveX DLL/Control 之外的多种项目类型提供内置支持。 ## 标准 DLL 虽然以前可以通过变通方法实现,但 tB 将其作为内置项目类型提供。你可以在启动时选择此项目类型,然后只需在需要导出时用 `[DllExport]` 标记函数。名称将原样使用,不会被修饰。`CDecl` 调用约定使用正常语法支持,例如 `Public Function foo CDecl(bar As Long) As Long`。 twinBASIC 中的标准 DLL 仍然可以指定启动点;每个导出将检查此代码是否已运行,如果没有则运行它。 ```vb [DllExport] Public Function Add(ByVal a As Long, ByVal b As Long) As Long Add = a + b End Function [DllExport] Public Function Multiply CDecl(ByVal a As Long, ByVal b As Long) As Long Multiply = a * b End Function ``` ## 控制台应用程序 此项目类型允许创建真正的控制台项目而非 GUI 项目。它还会添加一个默认的 `Console` 类用于读写控制台 IO 和提供的调试控制台。 ## Windows 服务 tB 有一个服务包(WinServicesLib),使创建功能完整的真正服务变得轻松。它简化了 MESSAGETABLE 资源的使用、每个 exe 中的多个服务、用于 IPC 的命名管道等。参见示例 21-22。 ## 内核模式驱动 内核模式驱动只能访问非常有限的 API 子集,不能像运行时那样调用用户模式 DLL。因此在以前的 BASIC 产品中,这通常需要复杂的变通方法,并大幅限制你能做的事情(如果可能的话)。当然,内核模式没有 WOW64 层,所以 tB 是第一个支持为 64 位 Windows 创建驱动的 BASIC 产品。这通过"Project: Native subsystem"选项以及以下两个功能控制: ### 覆盖入口点 BASIC 应用程序通常有一个隐藏的入口点,它在 `Sub Main` 或启动窗体的 `Form_Load` 之前最先运行。它设置应用程序的功能,如初始化 COM。twinBASIC 支持覆盖此入口点,将你自己的过程设置为真正的入口点。这主要用于内核模式项目,它们必须有特定类型的入口点,且不能在默认情况下调用正常的 API。但还有其他可能使用此选项的原因,不过请注意:如果不自己执行初始化过程或不精确了解你不能使用什么,许多东西在普通应用程序中会出错。 ### 将 API 声明放入 IAT tB 可以选择将所有 API 声明放入导入地址表,而不是像 VBx 那样在运行时通过 `LoadLibrary/GetProcAddress` 调用(VBx 将 TLB 声明的 API 放入导入表;tB 也复制了这一点,但进一步为项目内声明提供了选项)。 这在性能上有小幅优势,因为它在启动时加载和绑定,而非首次调用时。但主要用途是内核模式,它不能调用 `LoadLibrary` 和其他用户模式 API 来使用后期绑定。 --- --- url: /zh/official/Features/Project-Configuration.md --- # 项目配置 twinBASIC 提供各种项目配置选项和新项目类型以满足不同开发需求。 ## 主题 * [项目类型](/official/Features/Project-Configuration/Project-Types) - 标准 DLL、控制台、服务和内核驱动 * [编译器选项](/official/Features/Project-Configuration/Compiler-Options) - 入口点、IAT 放置等 * [ActiveX 注册选项](/official/Features/Project-Configuration/ActiveX-Registration) - ActiveX 项目的注册设置 --- --- url: /zh/official/IDE/Project-Settings.md --- # 项目设置 以下列出了项目设置,顺序与项目设置对话框中显示的相同。各设置说明将在后续补充。目前请参考项目设置对话框中内置的描述: !\[项目设置对话框片段,指示设置的描述信息]\(Images/project settings description text.png) ## 项目名称 ## 项目描述 ## 应用程序标题 ## 应用程序帮助文件 ## 启动对象 ## 图标窗体 ## 库引用 ![库引用 - 项目设置](/assets/ProjectSettings_LibraryReferences.DnG_2vGd.png "库引用 - 项目设置") ![可用 COM 引用 - 项目设置](/assets/ProjectSettings_AvailableCOMReferences.D1Lg66SW.png "可用 COM 引用 - 项目设置") 参见[包](/official/Features/Packages/) ![432410211-d9f1e4d9-1805-47e5-93aa-251151b4e914](../Features/Packages/Images/e749e10f-e361-4f15-a977-d756fcb3b5dd.png) ## 编译器警告 ## 项目 ID ## 使用项目 ID 作为类型库 ID ## 生成输出路径 ## 生成类型 ## 许可证类型 ## 包可见性 ## VERSION 资源 ### 主版本/次版本/内部版本 ### 产品名称 ### 公司名称 ### 文件描述 ### 版权 ### 商标 ### 备注 ### 自动递增 ## 类型库版本 ### 主版本/次版本 ### 自动递增 ## 将 DLL 注册到 HKLM ## COM 初始化 ## 控制台应用程序 ## 原生子系统 ## 覆盖入口点 ## DLL 声明的运行时绑定 ## 条件编译参数 ## Option Explicit On ## 自动格式化源代码 ## CodeLens - 显示运行过程 ## 运行时 Windows 代码页 ## 使用 Unicode 标准库 ## Unicode 控件通知 ## 在生成的可执行文件中包含过程名称符号 ## 跟踪标志 ## 跟踪输出 ## 禁用溢出检查 ## 禁用数组边界检查 ## 禁用 FPU 错误检查 ## 布尔值净化 ## 常量函数折叠 ## 大地址感知 (LAA) ## 终端服务器感知 ## 数据执行保护感知 (DEP) ## 导出 ### 导出路径 ### 保存后导出 ### 详细导出 ## 启动时强制 DPI 感知 ## 运行时命令行参数 ## 即时内存失效 ## 遇到所有错误时中断 ## 构建堆栈保留大小 ## 目标操作系统版本 ## 代码生成模型 ## 去除 PE 文件重定位符号 ## 启用地址空间布局随机化 (ASLR) ## PE 文件映像基址 (Win32) ## PE 文件映像基址 (Win64) ## 可调试 ## 功能标志 --- --- url: /zh/official/IDE/Project-Explorer.md --- # 项目资源管理器 ![项目资源管理器](Images/ProjectExplorer.png "项目资源管理器") ![项目资源管理器示例](/assets/ProjectExplorer_Sample.DLy6CPkZ.png "项目资源管理器示例") ![文件夹](Images/Folder.png "文件夹") 导入的类型库 ![文件夹](Images/Folder.png "文件夹") 杂项 ![文件夹](Images/Folder.png "文件夹") 包 ![文件夹](Images/Folder.png "文件夹") 引用 ![文件夹](Images/Folder.png "文件夹") 资源 ![文件夹](Images/Folder.png "文件夹") 源文件 项目打开时会出现上下文图标。 ![项目资源管理器标题栏](Images/ProjectExplorer_Header.png "项目资源管理器标题栏") ## ![](Images/Settings.png) 项目设置 * [信息](/official/IDE/Project-Settings) ## ![](Images/Toggle.png) 切换文件视图 (CTRL + R) ## ![](Images/Add.png) 添加... 与右键相同 ## 右键 - 添加 ![右键 - 添加](/assets/RightClick-Add.BC9Rjdot.png "右键 - 添加") * ![文件夹](Images/Folder.png "文件夹") 添加文件夹 * ![](Images/tB-Green.png) 添加 Windows 窗体 * ![](Images/tB-Green.png) 添加 Windows MDI 窗体 * ![](Images/tB-Green.png) 添加 Windows UserControl * ![](Images/tB-Green.png) 添加 Windows 属性页 * ![](Images/tB-Green.png) 添加 Windows 报表 *** * ![](Images/tB-Green.png) 添加 CustomControls 窗体 *** * ![模块](Images/tB-Red.png "模块") 添加模块 (.TWIN 支持 Unicode) * ![类](Images/tB-Red.png "类") 添加类 (.TWIN 支持 Unicode) *** * ![模块](Images/tB-Blue.png "模块 (BAS)") 添加模块 (.BAS) * ![类](Images/tB-Orange.png "类 (CLS)") 添加类 (.CLS) *** * ![文件](Images/File-Green.png "文件") 添加其他文件 *** * ![文件](Images/File-Green.png "文件") 导入 *** * 添加资源:视觉样式清单 * 添加资源:字符串表 * 添加资源:MESSAGETABLE ## ![](Images/Folder.png) 文件夹 ## ![](Images/tB-Green.png) Windows 窗体 [tbForm](/official/IDE/tbForm) ## ![](Images/tB-Green.png) Windows MDI 窗体 ## ![](Images/UserControl.png) Windows UserControl ## ![](Images/tB-Green.png) Windows 属性页 ## ![](Images/tB-Green.png) Windows 报表 [tbReport](/official/IDE/tbReport) ## ![](Images/tB-Green.png) CustomControls 窗体 ![添加 CustomControls 窗体弹窗](/assets/RightClick-Add-CustomControlsForm-Popup.B0pK9qpz.png "添加 CustomControls 窗体弹窗") ## ![](Images/tB-Red.png) 模块 ## ![](Images/tB-Red.png) 类 ## ![](Images/File-Green.png) 其他文件 ## ![](Images/File-Green.png) 导入 ## 资源:视觉样式清单 参见 ![文件夹](Images/Folder.png "文件夹") `/.../Resources/MANIFEST/#1.xml` ```xml <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity type="win32" processorArchitecture="*" name="My_twinBASIC_Application" version="1.0.0.0" /> <description>Application description here</description> <dependency> <dependentAssembly> <assemblyIdentity type="win32" processorArchitecture="*" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" publicKeyToken="6595b64144ccf1df" language="*" /> </dependentAssembly> </dependency> </assembly> ``` ## 资源:字符串表 参见 ![文件夹](Images/Folder.png "文件夹") `/.../Resources/STRING/Strings.json` ```json [ { "id": 101, "name": "MyLocalizedString1", "LCID_0000": "This is my NEUTRAL text for MyLocalizedString1", "LCID_0409": "This is my USA text for MyLocalizedString1", "LCID_0407": "This is my GERMAN text for MyLocalizedString1", "LCID_0809": "This is my UK text for MyLocalizedString1" }, { "id": 102, "name": "MyLocalizedString2", "LCID_0000": "This is my NEUTRAL text for MyLocalizedString2", "LCID_0409": "This is my USA text for MyLocalizedString2", "LCID_0407": "This is my GERMAN text for MyLocalizedString2", "LCID_0809": "This is my UK text for MyLocalizedString2" } ] ``` ## 资源:MESSAGETABLE 参见 ![文件夹](Images/Folder.png "文件夹") `/.../Resources/MESSAGETABLE/Strings.json` ```json { "events": [ { "id": -1073610751, "name": "service_started", "LCID_0000": "%1 service started" }, { "id": -1073610750, "name": "service_startup_failed", "LCID_0000": "%1 service startup failed" }, { "id": -1073610749, "name": "service_ended", "LCID_0000": "%1 service ended" }, { "id": -1073610748, "name": "service_stopping", "LCID_0000": "%1 service stopping" } ], "categories": [ { "id": 1, "name": "status_changed", "LCID_0000": "Status Changed" } ] } ``` --- --- url: /zh/official/Features/Standard-Library/New-Functions.md --- # 新内置函数 除了前面描述的与数据类型相关和组件名称的函数外,标准内置 `VBA` 库现在包含许多新功能。 ## 新函数 * `IsArrayInitialized(variable)` - 判断数组是否已初始化。注意:用 `Array()` 声明为空数组的 `Variant` 将返回 `True`。 * `RGBA(r, g, b, a)` - 类似 `RBG()` 函数,但包含 alpha 通道。 * `RBG_R(rgba)`、`RGB_B(rgba)`、`RBG_G(rgba)` 和 `RGBA_A(rgba)` - 获取各通道的值。 * `TranslateColor(ColorValue, Optional Palette)` - 将 OLE 颜色值转换为 RGB 颜色。 * `ProcessorArchitecture()` - 根据应用程序位数返回 `vbArchWin32` 或 `vbArchWin64`。 * `CallByDispId(Object, DispId, CallType, Arguments)` - 类似 `CallByName()`,但使用调度 ID 而非方法名。 * `RaiseEventByName(Object, Name, Args)` - 在类上触发事件,使用包含数组的单个 `Variant` 参数。 * `RaiseEventByName2(Object, Name, Arg1, Arg2, ...)` - 在类上触发事件,使用 ParamArray 参数。 * `PictureToByteArray(StdPicture)` - 将图片转换为字节数组;Global.LoadPicture 支持从字节数组加载。 * `CreateGUID()` - 返回一个新生成的 GUID 字符串。 * `AllocMem(size)` 和 `FreeMem` - 从进程堆分配和释放内存。 * `Int3Breakpoint` - 插入真正的断点,有助于已附加的外部调试器。 * `GetDeclaredTypeProgId(Of T)` / `GetDeclaredTypeClsid(Of T)` 泛型,用于获取 ProgID/CLSID 字符串。 * `GetDeclaredMinEnumValue(Of T)` / `GetDeclaredMaxEnumValue(Of T)` 泛型。 * 一些 `Interlocked*` 函数 ## 来自 msvbvm60.dll 的运行时函数 tB 内置了对一些最常用运行时函数的支持,以兼容性。这些都同时支持 32 位和 64 位。除非另有说明,所有这些函数以两种方式工作:首先,始终存在的内置原生版本(除非你移除了基本编译器包),具有最常见的参数排列。这些不需要 `Declare` 语句。如果你*确实*提供了 `Declare` 版本,tB 将允许你指定的任何参数排列(例如用 `As Any` 代替 `As LongPtr`),并在提供别名时映射到别名。 ### 内存函数 * `GetMem1`、`GetMem2`、`GetMem4`、`GetMem8`、`PutMem1`、`PutMem2`、`PutMem4`、`PutMem8` * 新增 `GetMemPtr` 和 `PutMemPtr`,对应当前指针大小 ### 对象操作 * `vbaObjSet`、`vbaObjSetAddref`、`vbaCastObj` 和 `vbaObjAddref`,用于通过指针操作对象赋值。 ### 数组操作 * `vbaCopyBytes` 和 `vbaCopyBytesZero` * `vbaAryMove` 和 `vbaRefVarAry`(目前仅支持通过 `Declare` 语句)。 * tB 也有内置的 `VarPtr`,但仍会通过 declare 语句重定向调用,例如用于数组的别名(不过 tB 的 `VarPtr` 原生支持数组)。 ## 新的 App 对象属性 * `App.IsInIDE` - 从 IDE 运行时为 `True`。 * `App.IsElevated` - 返回程序当前是否以管理员权限运行。 * `App.LastBuildPath` - 返回上次构建的完整路径。不在编译器/IDE 重启之间持久保存。 * `App.Build` - 用于额外的版本号字段。 * `App.ModulePath` - 返回当前执行模块的完整路径。例如,如果放在 DLL 中并从 EXE 调用,将返回 DLL 的路径。此外,从 IDE 运行且方法在应用本身中时,返回的是 twinBASIC 调试器 DLL。 ## COM 错误处理 ### 直接访问 COM 错误 你可以通过 `Err.LastHResult` 检索最后一次 COM 接口调用的 `HRESULT`;这些通常被隐藏并映射为内部错误——COM 接口中正常称为 `Sub` 的所有内容实际上是返回 `HRESULT` 的函数。 ### 设置返回 HRESULT 更重要的是,你现在可以在接口实现中使用 `Err.ReturnHResult` **设置** `HRESULT`。这是一个关键缺失的功能,以前有时 `Err.Raise` 可以工作,但大多数程序员诉诸于复杂的 v-table 交换代码来重定向到标准模块函数。例如,你现在可以在需要时用 `Err.ReturnHResult = S_FALSE` 返回 `S_FALSE`。 ## 解构赋值 此功能允许你将数组内容在单行中赋值给多个变量: ```vb Dim a As Long, b As Long, c As Long Dim d(2) As Long d(0) = 1 d(1) = 2 d(2) = 3 Array(a, b, c) = d Debug.Print a, b, c ``` 这将打印 `1 2 3`。你也可以这样一次赋值多个变量并得到相同结果: ```vb Dim a As Long, b As Long, c As Long Array(a, b, c) = Array(1, 2, 3) Debug.Print a, b, c ``` 你现在还可以这样做: ```vb Dim a As Long = 9 Dim b As Long = 7 Dim c() As Long = Array(a, b) Debug.Print c(1), UBound(c) ``` 打印 `7 1`。 --- --- url: /zh/official/Features/GUI-Components/New.md --- # 新控件 twinBASIC 引入了几种新控件来增强你的应用程序。 ## QR Code 控件 ![image](/assets/54ed49d8-b434-45e3-9e63-a1fe75cdf814.CsGo_QgA.png) 使用原生控件轻松显示自定义 QR 码。 ## Multiframe 控件 ![image](/assets/4ad9c774-b31d-47d3-9963-6d99ac4f37bb.fM2RmIbS.png) 此控件允许你创建多个帧,其大小以百分比指定,这样当控件调整大小时,帧内的内容按比例扩展。有关详细信息和视频演示,Mike Wolfe 的 twinBASIC 周更新在[发布时做了介绍](https://nolongerset.com/twinbasic-update-april-29-2025/#experimental-multi-frame-control)。 结合锚定和停靠,这允许设计高度功能化和复杂的布局,无需编写任何处理大小调整的代码。 ## CheckMark 控件 ![image](/assets/5fc60b7b-4f54-445c-8504-451019b7ec55.kSlH4oTD.png) 主要面向报表但在窗体和 UserControl 中也可用,CheckMark 控件提供了可缩放的勾选组件,而普通 CheckBox 控件中此组件固定为单一尺寸。 --- --- url: /zh/packages/vbccr/lists/vlistbox.md description: 虚拟列表框控件(VListBox) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 虚拟列表框控件(VListBox) 提供虚拟数据列表框,使用LBS\_NODATA样式实现大数据量展示,按需提供数据,支持多选、自绘、插入标记和OLE拖放。 ## 枚举 ### VlbDrawModeConstants 绘制模式常量。 | 常量 | 值 | 说明 | |------|-----|------| | VlbDrawModeNormal | 0 | 标准绘制模式 | | VlbDrawModeOwnerDrawFixed | 1 | 固定高度自绘模式 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### Container ```vb Public Property Get Container() As Object Public Property Set Container(ByVal Value As Object) ``` 返回/设置对象的容器。 ### Left ```vb Public Property Get Left() As Single Public Property Let Left(ByVal Value As Single) ``` 返回/设置对象与其容器左边缘的距离。 ### Top ```vb Public Property Get Top() As Single Public Property Let Top(ByVal Value As Single) ``` 返回/设置对象与其容器顶边缘的距离。 ### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 返回/设置对象的宽度。 ### Height ```vb Public Property Get Height() As Single Public Property Let Height(ByVal Value As Single) ``` 返回/设置对象的高度。 ### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 返回/设置鼠标悬停时显示的提示文本。 ### HelpContextID ```vb Public Property Get HelpContextID() As Long Public Property Let HelpContextID(ByVal Value As Long) ``` 返回/设置帮助上下文ID。 ### WhatsThisHelpID ```vb Public Property Get WhatsThisHelpID() As Long Public Property Let WhatsThisHelpID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### DragIcon ```vb Public Property Get DragIcon() As IPictureDisp Public Property Let DragIcon(ByVal Value As IPictureDisp) Public Property Set DragIcon(ByVal Value As IPictureDisp) ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Public Property Get DragMode() As Integer Public Property Let DragMode(ByVal Value As Integer) ``` 返回/设置拖动模式。 ### hWnd ```vb Public Property Get hWnd() As LongPtr ``` 返回控件句柄。 ### hWndUserControl ```vb Public Property Get hWndUserControl() As LongPtr ``` 返回UserControl句柄。 ### Font ```vb Public Property Get Font() As StdFont Public Property Let Font(ByVal NewFont As StdFont) Public Property Set Font(ByVal NewFont As StdFont) ``` 返回/设置字体。 ### VisualStyles ```vb Public Property Get VisualStyles() As Boolean Public Property Let VisualStyles(ByVal Value As Boolean) ``` 返回/设置是否启用视觉样式。需要comctl32.dll 6.0或更高版本。 ### BackColor ```vb Public Property Get BackColor() As OLE_COLOR Public Property Let BackColor(ByVal Value As OLE_COLOR) ``` 返回/设置背景色。 ### ForeColor ```vb Public Property Get ForeColor() As OLE_COLOR Public Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 返回/设置前景色。 ### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 返回/设置对象是否能响应用户事件。 ### OLEDragMode ```vb Public Property Get OLEDragMode() As VBRUN.OLEDragConstants Public Property Let OLEDragMode(ByVal Value As VBRUN.OLEDragConstants) ``` 返回/设置OLE拖拽模式。 ### OLEDragDropScroll ```vb Public Property Get OLEDragDropScroll() As Boolean Public Property Let OLEDragDropScroll(ByVal Value As Boolean) ``` 返回/设置OLE拖放时是否自动滚动。 ### OLEDropMode ```vb Public Property Get OLEDropMode() As OLEDropModeConstants Public Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` 返回/设置对象是否可以作为OLE放置目标。 ### MousePointer ```vb Public Property Get MousePointer() As CCMousePointerConstants Public Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 返回/设置鼠标悬停时显示的指针类型。参见通用枚举。 ### MouseIcon ```vb Public Property Get MouseIcon() As IPictureDisp Public Property Let MouseIcon(ByVal Value As IPictureDisp) Public Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Public Property Get MouseTrack() As Boolean Public Property Let MouseTrack(ByVal Value As Boolean) ``` 返回/设置是否在鼠标进入或离开控件时触发事件。 ### RightToLeft ```vb Public Property Get RightToLeft() As Boolean Public Property Let RightToLeft(ByVal Value As Boolean) ``` 返回/设置从右到左显示方向。 ### RightToLeftMode ```vb Public Property Get RightToLeftMode() As CCRightToLeftModeConstants Public Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 返回/设置从右到左模式。参见通用枚举。 ### Redraw ```vb Public Property Get Redraw() As Boolean Public Property Let Redraw(ByVal Value As Boolean) ``` 返回/设置是否重绘。禁用后可加速大量操作。 ### BorderStyle ```vb Public Property Get BorderStyle() As CCBorderStyleConstants Public Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` 返回/设置边框样式。参见通用枚举。 ### MultiColumn ```vb Public Property Get MultiColumn() As Boolean Public Property Let MultiColumn(ByVal Value As Boolean) ``` 返回/设置是否多列显示。 ### IntegralHeight ```vb Public Property Get IntegralHeight() As Boolean Public Property Let IntegralHeight(ByVal Value As Boolean) ``` 返回/设置是否调整高度为完整项。仅设计时可设置。 ### AllowSelection ```vb Public Property Get AllowSelection() As Boolean Public Property Let AllowSelection(ByVal Value As Boolean) ``` 返回/设置是否允许选择项。 ### MultiSelect ```vb Public Property Get MultiSelect() As VBRUN.MultiSelectConstants Public Property Let MultiSelect(ByVal Value As VBRUN.MultiSelectConstants) ``` 返回/设置多选模式。使用VBRUN.MultiSelectConstants常量(vbMultiSelectNone=0, vbMultiSelectSimple=1, vbMultiSelectExtended=2)。 ### HorizontalExtent ```vb Public Property Get HorizontalExtent() As Single Public Property Let HorizontalExtent(ByVal Value As Single) ``` 返回/设置水平滚动范围。仅在MultiColumn为False时有效。 ### UseTabStops ```vb Public Property Get UseTabStops() As Boolean Public Property Let UseTabStops(ByVal Value As Boolean) ``` 返回/设置是否识别和展开制表符。 ### DisableNoScroll ```vb Public Property Get DisableNoScroll() As Boolean Public Property Let DisableNoScroll(ByVal Value As Boolean) ``` 返回/设置不需要滚动条时是否禁用而非隐藏。 ### DrawMode ```vb Public Property Get DrawMode() As VlbDrawModeConstants Public Property Let DrawMode(ByVal Value As VlbDrawModeConstants) ``` 返回/设置绘制模式。仅设计时可设置。 ### InsertMarkColor ```vb Public Property Get InsertMarkColor() As OLE_COLOR Public Property Let InsertMarkColor(ByVal Value As OLE_COLOR) ``` 返回/设置插入标记颜色。 ### ScrollTrack ```vb Public Property Get ScrollTrack() As Boolean Public Property Let ScrollTrack(ByVal Value As Boolean) ``` 返回/设置是否启用滚动跟踪(拖动滑块时实时滚动)。 ### ListCount ```vb Public Property Get ListCount() As Long Public Property Let ListCount(ByVal Value As Long) ``` 返回/设置列表项数量。虚拟列表中为数据项总数。 ### List ```vb Public Property Get List(ByVal Index As Long) As String ``` 获取指定索引的列表项文本。通过GetVirtualItem事件获取数据。 ### ListIndex ```vb Public Property Get ListIndex() As Long Public Property Let ListIndex(ByVal Value As Long) ``` 返回/设置当前选中项索引。 ### Text ```vb Public Property Get Text() As String Public Property Let Text(ByVal Value As String) ``` 返回/设置当前选中项文本。设置时触发FindVirtualItem查找匹配项。 ### SelCount ```vb Public Property Get SelCount() As Long ``` 返回选中项数量。 ### Selected ```vb Public Property Get Selected(ByVal Index As Long) As Boolean Public Property Let Selected(ByVal Index As Long, ByVal Value As Boolean) ``` 返回/设置指定索引项的选中状态。 ### ItemHeight ```vb Public Property Get ItemHeight() As Single Public Property Let ItemHeight(ByVal Value As Single) ``` 返回/设置项高度。 ### TopIndex ```vb Public Property Get TopIndex() As Long Public Property Let TopIndex(ByVal Value As Long) ``` 返回/设置列表顶部可见项索引。 ### AnchorIndex ```vb Public Property Get AnchorIndex() As Long Public Property Let AnchorIndex(ByVal Value As Long) ``` 返回/设置锚点项索引(多项选择的起始项)。 ### InsertMark ```vb Public Property Get InsertMark(Optional ByRef After As Boolean) As Long Public Property Let InsertMark(Optional ByRef After As Boolean, ByVal Value As Long) ``` 返回/设置插入标记位置。After参数指示插入标记在项目的上方(False)还是下方(True)。设为-1取消插入标记。 ### OLEDraggedItem ```vb Public Property Get OLEDraggedItem() As Long ``` 返回当前OLE拖拽项的索引。 ## 方法 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动OLE拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移到指定对象。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置Z顺序。 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘对象。 ### SetSelRange ```vb Public Sub SetSelRange(ByVal StartIndex As Long, ByVal EndIndex As Long) ``` 设置选择范围(多选模式下)。 ### SetColumnWidth ```vb Public Sub SetColumnWidth(ByVal Value As Single) ``` 设置多列列表的列宽。 ### ItemsPerColumn ```vb Public Function ItemsPerColumn() As Long ``` 获取每列项数。 ### SelectedIndices ```vb Public Function SelectedIndices() As Collection ``` 返回所有选中项索引的集合。 ### HitTest ```vb Public Function HitTest(ByVal X As Single, ByVal Y As Single) As Long ``` 命中测试,返回指定坐标处的项索引。不在任何项上返回-1。 ### HitTestInsertMark ```vb Public Function HitTestInsertMark(ByVal X As Single, ByVal Y As Single, Optional ByRef After As Boolean) As Long ``` 插入标记命中测试,同时获取插入标记应出现在项目上方还是下方。 ### FindItem ```vb Public Function FindItem(ByVal Text As String, Optional ByVal Index As Long = -1, Optional ByVal Partial As Boolean) As Long ``` 查找列表项。返回匹配项索引,未找到返回-1。 ### GetIdealHorizontalExtent ```vb Public Function GetIdealHorizontalExtent() As Single ``` 获取理想的水平滚动范围。 ### SelectItem ```vb Public Function SelectItem(ByVal Text As String, Optional ByVal Index As Long = -1) As Long ``` 搜索并选择匹配的列表项。返回选中项索引。 ## 事件 ### Click ```vb Public Event Click() ``` 用户单击控件时触发。 ### DblClick ```vb Public Event DblClick() ``` 用户双击控件时触发。 ### Scroll ```vb Public Event Scroll() ``` 列表滚动时触发。 ### ContextMenu ```vb Public Event ContextMenu(ByVal X As Single, ByVal Y As Single) ``` 右键上下文菜单事件。X和Y为-1时表示键盘触发(Shift+F10)。 ### GetVirtualItem ```vb Public Event GetVirtualItem(ByVal Item As Long, ByRef Text As String) ``` 请求虚拟项数据时触发。需设置Text参数返回项文本。 ### FindVirtualItem ```vb Public Event FindVirtualItem(ByVal StartIndex As Long, ByVal SearchText As String, ByVal Partial As Boolean, ByRef FoundIndex As Long) ``` 搜索虚拟项时触发。需设置FoundIndex返回匹配项索引,未找到设为-1。 ### IncrementalSearch ```vb Public Event IncrementalSearch(ByVal SearchString As String, ByVal StartIndex As Long, ByRef FoundIndex As Long) ``` 增量搜索时触发。需设置FoundIndex返回匹配项索引。 ### ItemDraw ```vb Public Event ItemDraw(ByVal Item As Long, ByVal ItemAction As Long, ByVal ItemState As Long, ByVal hDC As Long, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` 自绘项时触发(DrawMode为OwnerDrawFixed时)。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键预览事件。设置IsInputKey为True可将按键标记为输入键。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键释放预览事件。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下键盘键时触发。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放键盘键时触发。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按下并释放ANSI键时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件区域时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件区域时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE拖放操作完成时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE拖放操作放置时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE拖放操作悬停时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE拖放操作给反馈时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE拖放操作设置数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE拖放操作开始时触发。 ## 代码示例 ### 基本用法 ```vb ' 设置虚拟列表框 With VListBox1 .ListCount = 10000 .MultiSelect = vbMultiSelectExtended .InsertMarkColor = vbBlue .ScrollTrack = True End With ' 提供虚拟项数据 Private Sub VListBox1_GetVirtualItem(ByVal Item As Long, ByRef Text As String) Text = "第 " & CStr(Item + 1) & " 项" End Sub ' 查找虚拟项 Private Sub VListBox1_FindVirtualItem(ByVal StartIndex As Long, _ ByVal SearchText As String, ByVal Partial As Boolean, ByRef FoundIndex As Long) FoundIndex = -1 End Sub ' 自绘项示例 Private Sub VListBox1_ItemDraw(ByVal Item As Long, ByVal ItemAction As Long, _ ByVal ItemState As Long, ByVal hDC As Long, ByVal Left As Long, _ ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ' 自定义绘制代码 End Sub ``` --- --- url: /zh/packages/vbccr/lists/virtualcombo.md description: 虚拟组合框控件(VirtualCombo) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 虚拟组合框控件(VirtualCombo) 提供虚拟数据组合框,使用LBS\_NODATA样式实现大数据量展示,按需提供数据,支持自绘、增量搜索和OLE拖放。 ## 枚举 ### VcbStyleConstants 组合框样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | VcbStyleDropDownCombo | 0 | 下拉组合框(可编辑) | | VcbStyleSimpleCombo | 1 | 简单组合框 | | VcbStyleDropDownList | 2 | 下拉列表框(不可编辑) | ### VcbDrawModeConstants 绘制模式常量。 | 常量 | 值 | 说明 | |------|-----|------| | VcbDrawModeNormal | 0 | 标准绘制模式 | | VcbDrawModeOwnerDrawFixed | 1 | 固定高度自绘模式 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### Container ```vb Public Property Get Container() As Object Public Property Set Container(ByVal Value As Object) ``` 返回/设置对象的容器。 ### Left ```vb Public Property Get Left() As Single Public Property Let Left(ByVal Value As Single) ``` 返回/设置对象与其容器左边缘的距离。 ### Top ```vb Public Property Get Top() As Single Public Property Let Top(ByVal Value As Single) ``` 返回/设置对象与其容器顶边缘的距离。 ### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 返回/设置对象的宽度。 ### Height ```vb Public Property Get Height() As Single Public Property Let Height(ByVal Value As Single) ``` 返回/设置对象的高度。 ### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 返回/设置鼠标悬停时显示的提示文本。 ### HelpContextID ```vb Public Property Get HelpContextID() As Long Public Property Let HelpContextID(ByVal Value As Long) ``` 返回/设置帮助上下文ID。 ### WhatsThisHelpID ```vb Public Property Get WhatsThisHelpID() As Long Public Property Let WhatsThisHelpID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### DragIcon ```vb Public Property Get DragIcon() As IPictureDisp Public Property Let DragIcon(ByVal Value As IPictureDisp) Public Property Set DragIcon(ByVal Value As IPictureDisp) ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Public Property Get DragMode() As Integer Public Property Let DragMode(ByVal Value As Integer) ``` 返回/设置拖动模式。 ### hWnd ```vb Public Property Get hWnd() As LongPtr ``` 返回控件句柄。 ### hWndUserControl ```vb Public Property Get hWndUserControl() As LongPtr ``` 返回UserControl句柄。 ### hWndEdit ```vb Public Property Get hWndEdit() As LongPtr ``` 返回编辑框句柄。 ### hWndList ```vb Public Property Get hWndList() As LongPtr ``` 返回下拉列表框句柄。 ### Font ```vb Public Property Get Font() As StdFont Public Property Let Font(ByVal NewFont As StdFont) Public Property Set Font(ByVal NewFont As StdFont) ``` 返回/设置字体。 ### VisualStyles ```vb Public Property Get VisualStyles() As Boolean Public Property Let VisualStyles(ByVal Value As Boolean) ``` 返回/设置是否启用视觉样式。需要comctl32.dll 6.0或更高版本。 ### BackColor ```vb Public Property Get BackColor() As OLE_COLOR Public Property Let BackColor(ByVal Value As OLE_COLOR) ``` 返回/设置背景色。 ### ForeColor ```vb Public Property Get ForeColor() As OLE_COLOR Public Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 返回/设置前景色。 ### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 返回/设置对象是否能响应用户事件。 ### OLEDragMode ```vb Public Property Get OLEDragMode() As VBRUN.OLEDragConstants Public Property Let OLEDragMode(ByVal Value As VBRUN.OLEDragConstants) ``` 返回/设置OLE拖拽模式。 ### OLEDropMode ```vb Public Property Get OLEDropMode() As OLEDropModeConstants Public Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` 返回/设置对象是否可以作为OLE放置目标。 ### MousePointer ```vb Public Property Get MousePointer() As CCMousePointerConstants Public Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 返回/设置鼠标悬停时显示的指针类型。参见通用枚举。 ### MouseIcon ```vb Public Property Get MouseIcon() As IPictureDisp Public Property Let MouseIcon(ByVal Value As IPictureDisp) Public Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Public Property Get MouseTrack() As Boolean Public Property Let MouseTrack(ByVal Value As Boolean) ``` 返回/设置是否在鼠标进入或离开控件时触发事件。 ### RightToLeft ```vb Public Property Get RightToLeft() As Boolean Public Property Let RightToLeft(ByVal Value As Boolean) ``` 返回/设置从右到左显示方向。 ### RightToLeftMode ```vb Public Property Get RightToLeftMode() As CCRightToLeftModeConstants Public Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 返回/设置从右到左模式。参见通用枚举。 ### Style ```vb Public Property Get Style() As VcbStyleConstants Public Property Let Style(ByVal Value As VcbStyleConstants) ``` 返回/设置组合框样式。仅设计时可设置。 ### Locked ```vb Public Property Get Locked() As Boolean Public Property Let Locked(ByVal Value As Boolean) ``` 返回/设置是否锁定(禁止编辑和选择)。 ### Text ```vb Public Property Get Text() As String Public Property Let Text(ByVal Value As String) ``` 返回/设置编辑框文本。 ### Default ```vb Public Property Get Default() As String Public Property Let Default(ByVal Value As String) ``` 返回/设置默认文本。 ### ExtendedUI ```vb Public Property Get ExtendedUI() As Boolean Public Property Let ExtendedUI(ByVal Value As Boolean) ``` 返回/设置是否使用扩展用户界面(F4键打开下拉列表,ESC键关闭)。 ### MaxDropDownItems ```vb Public Property Get MaxDropDownItems() As Integer Public Property Let MaxDropDownItems(ByVal Value As Integer) ``` 返回/设置下拉列表最大显示项数。 ### IntegralHeight ```vb Public Property Get IntegralHeight() As Boolean Public Property Let IntegralHeight(ByVal Value As Boolean) ``` 返回/设置是否调整高度为完整项。仅设计时可设置。 ### MaxLength ```vb Public Property Get MaxLength() As Long Public Property Let MaxLength(ByVal Value As Long) ``` 返回/设置编辑框最大文本长度。 ### UseListBackColor ```vb Public Property Get UseListBackColor() As Boolean Public Property Let UseListBackColor(ByVal Value As Boolean) ``` 返回/设置是否使用列表背景色。 ### UseListForeColor ```vb Public Property Get UseListForeColor() As Boolean Public Property Let UseListForeColor(ByVal Value As Boolean) ``` 返回/设置是否使用列表前景色。 ### ListBackColor ```vb Public Property Get ListBackColor() As OLE_COLOR Public Property Let ListBackColor(ByVal Value As OLE_COLOR) ``` 返回/设置下拉列表背景色。 ### ListForeColor ```vb Public Property Get ListForeColor() As OLE_COLOR Public Property Let ListForeColor(ByVal Value As OLE_COLOR) ``` 返回/设置下拉列表前景色。 ### HorizontalExtent ```vb Public Property Get HorizontalExtent() As Single Public Property Let HorizontalExtent(ByVal Value As Single) ``` 返回/设置下拉列表水平滚动范围。 ### DrawMode ```vb Public Property Get DrawMode() As VcbDrawModeConstants Public Property Let DrawMode(ByVal Value As VcbDrawModeConstants) ``` 返回/设置绘制模式。仅设计时可设置。 ### IMEMode ```vb Public Property Get IMEMode() As CCIMEModeConstants Public Property Let IMEMode(ByVal Value As CCIMEModeConstants) ``` 返回/设置输入法模式。参见通用枚举。 ### ScrollTrack ```vb Public Property Get ScrollTrack() As Boolean Public Property Let ScrollTrack(ByVal Value As Boolean) ``` 返回/设置是否启用滚动跟踪(拖动滑块时实时滚动)。 ### AutoSelect ```vb Public Property Get AutoSelect() As Boolean Public Property Let AutoSelect(ByVal Value As Boolean) ``` 返回/设置是否自动选择匹配项。 ### AlwaysFindExact ```vb Public Property Get AlwaysFindExact() As Boolean Public Property Let AlwaysFindExact(ByVal Value As Boolean) ``` 返回/设置是否始终进行精确查找。 ### ListCount ```vb Public Property Get ListCount() As Long ``` 返回列表项数量。 ### List ```vb Public Property Get List(ByVal Index As Long) As String ``` 获取指定索引的列表项文本。通过GetVirtualItem事件获取数据。 ### ListIndex ```vb Public Property Get ListIndex() As Long Public Property Let ListIndex(ByVal Value As Long) ``` 返回/设置当前选中项索引。 ### SelStart ```vb Public Property Get SelStart() As Long Public Property Let SelStart(ByVal Value As Long) ``` 返回/设置选择起始位置。 ### SelLength ```vb Public Property Get SelLength() As Long Public Property Let SelLength(ByVal Value As Long) ``` 返回/设置选择长度。 ### SelText ```vb Public Property Get SelText() As String Public Property Let SelText(ByVal Value As String) ``` 返回/设置选择的文本。 ### ItemHeight ```vb Public Property Get ItemHeight() As Single Public Property Let ItemHeight(ByVal Value As Single) ``` 返回/设置项高度。 ### FieldHeight ```vb Public Property Get FieldHeight() As Single ``` 返回编辑框高度。 ### DroppedDown ```vb Public Property Get DroppedDown() As Boolean Public Property Let DroppedDown(ByVal Value As Boolean) ``` 返回/设置是否处于下拉状态。 ### DropDownWidth ```vb Public Property Get DropDownWidth() As Single Public Property Let DropDownWidth(ByVal Value As Single) ``` 返回/设置下拉列表宽度。 ### DropDownHeight ```vb Public Property Get DropDownHeight() As Single Public Property Let DropDownHeight(ByVal Value As Single) ``` 返回/设置下拉列表高度。 ### TopIndex ```vb Public Property Get TopIndex() As Long Public Property Let TopIndex(ByVal Value As Long) ``` 返回/设置下拉列表顶部可见项索引。 ## 方法 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动OLE拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移到指定对象。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置Z顺序。 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘对象。 ### FindItem ```vb Public Function FindItem(ByVal Text As String, Optional ByVal Index As Long = -1, Optional ByVal Partial As Boolean) As Long ``` 查找列表项。返回匹配项索引,未找到返回-1。 ### GetIdealHorizontalExtent ```vb Public Function GetIdealHorizontalExtent() As Single ``` 获取理想的水平滚动范围。 ### SelectItem ```vb Public Function SelectItem(ByVal Text As String, Optional ByVal Index As Long = -1) As Long ``` 搜索并选择匹配的列表项。返回选中项索引。 ## 事件 ### Click ```vb Public Event Click() ``` 用户单击控件时触发。 ### DblClick ```vb Public Event DblClick() ``` 用户双击控件时触发。 ### Scroll ```vb Public Event Scroll() ``` 下拉列表滚动时触发。 ### Change ```vb Public Event Change() ``` 文本内容改变时触发。 ### ContextMenu ```vb Public Event ContextMenu(ByRef Handled As Boolean, ByVal X As Single, ByVal Y As Single) ``` 右键上下文菜单事件。设置Handled为True可禁止默认菜单。 ### GetVirtualItem ```vb Public Event GetVirtualItem(ByVal Item As Long, ByRef Text As String) ``` 请求虚拟项数据时触发。需设置Text参数返回项文本。 ### FindVirtualItem ```vb Public Event FindVirtualItem(ByVal StartIndex As Long, ByVal SearchText As String, ByVal Partial As Boolean, ByRef FoundIndex As Long) ``` 搜索虚拟项时触发。需设置FoundIndex返回匹配项索引,未找到设为-1。 ### IncrementalSearch ```vb Public Event IncrementalSearch(ByVal SearchString As String, ByVal StartIndex As Long, ByRef FoundIndex As Long) ``` 增量搜索时触发。需设置FoundIndex返回匹配项索引。 ### DropDown ```vb Public Event DropDown() ``` 下拉列表展开时触发。 ### CloseUp ```vb Public Event CloseUp() ``` 下拉列表关闭时触发。 ### ItemDraw ```vb Public Event ItemDraw(ByVal Item As Long, ByVal ItemAction As Long, ByVal ItemState As Long, ByVal hDC As Long, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` 自绘项时触发(DrawMode为OwnerDrawFixed时)。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键预览事件。设置IsInputKey为True可将按键标记为输入键。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 按键释放预览事件。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下键盘键时触发。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放键盘键时触发。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按下并释放ANSI键时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件区域时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件区域时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE拖放操作完成时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE拖放操作放置时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE拖放操作悬停时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE拖放操作给反馈时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE拖放操作设置数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE拖放操作开始时触发。 ## 辅助模块 ### VirtualComboBase.bas 自定义窗口类辅助模块,注册/释放"VComboBoxWndClass"窗口类,为ComboLBox添加LBS\_NODATA样式。 #### VcbWndRegisterClass ```vb Public Sub VcbWndRegisterClass() ``` 注册自定义窗口类。 #### VcbWndReleaseClass ```vb Public Sub VcbWndReleaseClass() ``` 释放自定义窗口类。 ## 代码示例 ### 基本用法 ```vb ' 设置虚拟组合框 With VirtualCombo1 .Style = VcbStyleDropDownList .ListCount = 1000 .MaxDropDownItems = 15 End With ' 提供虚拟项数据 Private Sub VirtualCombo1_GetVirtualItem(ByVal Item As Long, ByRef Text As String) Text = "项目 " & CStr(Item) End Sub ' 查找虚拟项 Private Sub VirtualCombo1_FindVirtualItem(ByVal StartIndex As Long, _ ByVal SearchText As String, ByVal Partial As Boolean, ByRef FoundIndex As Long) FoundIndex = -1 End Sub ' 监听下拉事件 Private Sub VirtualCombo1_DropDown() Debug.Print "下拉列表已打开" End Sub Private Sub VirtualCombo1_Change() Debug.Print "当前文本: " & VirtualCombo1.Text End Sub ``` --- --- url: /zh/packages/vbccr/buttons/optionbuttonw.md description: 选项按钮控件(OptionButtonW) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 选项按钮控件(OptionButtonW) 封装 Windows 系统按钮控件(Button),以单选按钮样式运行,支持图形样式、所有者绘制、图像列表及视觉样式。 ## 枚举 ### OptImageListAlignmentConstants | 常量 | 值 | 说明 | |------|-----|------| | OptImageListAlignmentLeft | 0 | 左对齐 | | OptImageListAlignmentRight | 1 | 右对齐 | | OptImageListAlignmentTop | 2 | 顶部对齐 | | OptImageListAlignmentBottom | 3 | 底部对齐 | | OptImageListAlignmentCenter | 4 | 居中对齐 | ### OptDrawModeConstants | 常量 | 值 | 说明 | |------|-----|------| | OptDrawModeNormal | 0 | 标准模式,由系统绘制 | | OptDrawModeOwnerDraw | 1 | 所有者绘制模式,由代码处理绘制 | ### CCAppearanceConstants 参见通用枚举。 ### CCLeftRightAlignmentConstants 参见通用枚举。 ### CCVerticalAlignmentConstants 参见通用枚举。 ### CCMousePointerConstants 参见通用枚举。 ### CCRightToLeftModeConstants 参见通用枚举。 ### OLEDropModeConstants 参见通用枚举。 ## 属性 ### Value ```vb Property Get Value() As OLE_OPTEXCLUSIVE Property Let Value(ByVal NewValue As OLE_OPTEXCLUSIVE) ``` 选项按钮的选中状态。True 表示选中。 ### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` 显示在控件上的文本标题。 ### Alignment ```vb Property Get Alignment() As CCLeftRightAlignmentConstants Property Let Alignment(ByVal Value As CCLeftRightAlignmentConstants) ``` 选项按钮标题的对齐方式(左侧或右侧)。参见通用枚举。 ### TextAlignment ```vb Property Get TextAlignment() As VBRUN.AlignmentConstants Property Let TextAlignment(ByVal Value As VBRUN.AlignmentConstants) ``` 标题文本的对齐方式(左对齐、居中或右对齐)。 ### PushLike ```vb Property Get PushLike() As Boolean Property Let PushLike(ByVal Value As Boolean) ``` 是否使控件外观和行为类似下压按钮。 ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` 显示在控件上的图片。 ### WordWrap ```vb Property Get WordWrap() As Boolean Property Let WordWrap(ByVal Value As Boolean) ``` 是否允许标题文本换行以防止溢出。 ### Transparent ```vb Property Get Transparent() As Boolean Property Let Transparent(ByVal Value As Boolean) ``` 是否以底层背景的副本模拟透明背景。设计时忽略此属性。 ### VerticalAlignment ```vb Property Get VerticalAlignment() As CCVerticalAlignmentConstants Property Let VerticalAlignment(ByVal Value As CCVerticalAlignmentConstants) ``` 垂直对齐方式。参见通用枚举。 ### Style ```vb Property Get Style() As VBRUN.ButtonConstants Property Let Style(ByVal Value As VBRUN.ButtonConstants) ``` 控件外观样式,标准或图形。当 DrawMode 不为 Normal 时,Style 必须为 Standard。 ### DisabledPicture ```vb Property Get DisabledPicture() As IPictureDisp Property Let DisabledPicture(ByVal Value As IPictureDisp) Property Set DisabledPicture(ByVal Value As IPictureDisp) ``` 按钮禁用时显示的图片。仅当 Style 为图形样式时适用。 ### DownPicture ```vb Property Get DownPicture() As IPictureDisp Property Let DownPicture(ByVal Value As IPictureDisp) Property Set DownPicture(ByVal Value As IPictureDisp) ``` 按钮按下时显示的图片。仅当 Style 为图形样式时适用。 ### UseMaskColor ```vb Property Get UseMaskColor() As Boolean Property Let UseMaskColor(ByVal Value As Boolean) ``` 是否使用 MaskColor 属性作为透明色。仅当 Style 为图形样式时适用。 ### MaskColor ```vb Property Get MaskColor() As OLE_COLOR Property Let MaskColor(ByVal Value As OLE_COLOR) ``` 图片中作为透明色(遮罩)的颜色。仅当 Style 为图形样式时适用。 ### DrawMode ```vb Property Get DrawMode() As OptDrawModeConstants Property Let DrawMode(ByVal Value As OptDrawModeConstants) ``` 绘制模式,标准或所有者绘制。 ### ImageList ```vb Property Get ImageList() As Variant Property Let ImageList(ByVal Value As Variant) Property Set ImageList(ByVal Value As Variant) ``` 关联的图像列表控件。图像列表应包含单个图片(用于所有状态)或每种状态的独立图片。需要 comctl32.dll 6.0 或更高版本。 ### ImageListAlignment ```vb Property Get ImageListAlignment() As OptImageListAlignmentConstants Property Let ImageListAlignment(ByVal Value As OptImageListAlignmentConstants) ``` 图像列表中图像的对齐方式。需要 comctl32.dll 6.0 或更高版本。 ### ImageListMargin ```vb Property Get ImageListMargin() As Single Property Let ImageListMargin(ByVal Value As Single) ``` 图像列表中图像的边距。需要 comctl32.dll 6.0 或更高版本。 ### Pushed ```vb Property Get Pushed() As Boolean Property Let Pushed(ByVal Value As Boolean) ``` 选项按钮是否处于按下状态。 ### Hot ```vb Property Get Hot() As Boolean Property Let Hot(ByVal Value As Boolean) ``` 选项按钮是否处于热态(鼠标悬停)。只读,写入时引发错误 383。需要 comctl32.dll 6.0 或更高版本。 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。需要 comctl32.dll 6.0 或更高版本。 ### Appearance ```vb Property Get Appearance() As CCAppearanceConstants Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` 控件外观,平面或三维效果。参见通用枚举。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景颜色。 ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景颜色。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE 拖放目标模式。参见通用枚举。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针样式。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 是否启用鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示方向。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 选项按钮控件的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 用户控件的窗口句柄。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` 帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "这是什么"帮助 ID。 ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` 拖拽图标。 ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` 拖拽模式。 ## 方法 ### Drag ```vb Public Sub Drag([ByRef Action As Variant]) ``` 开始、结束或取消拖放操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移至控件。 ### ZOrder ```vb Public Sub ZOrder([ByRef Position As Variant]) ``` 设置控件的 Z 顺序。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放操作。 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘控件。 ## 事件 ### Click ```vb Public Event Click() ``` 在控件上按下并释放鼠标按钮时触发。 ### DblClick ```vb Public Event DblClick() ``` 在控件上双击鼠标时触发。 ### HotChanged ```vb Public Event HotChanged() ``` 选项按钮的热态状态发生变化时触发。需要 comctl32.dll 6.0 或更高版本。 ### OwnerDraw ```vb Public Event OwnerDraw(ByVal Action As Long, ByVal State As Long, ByVal hDC As Long, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` 所有者绘制按钮的某个视觉方面发生变化时触发。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyDown 事件之前触发。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyUp 事件之前触发。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下按键时触发。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放按键时触发。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按键字符输入时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放操作完成或取消后触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 数据通过 OLE 拖放操作放到控件上时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放操作期间鼠标移过控件时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 拖放操作中需要更改鼠标光标时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` 放置目标请求 OLEDragStart 期间未提供的数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 拖放操作启动时触发。 ## 代码示例 ```vb ' 基本选项按钮 OptionButtonW1.Caption = "选项 A" OptionButtonW1.Value = True ' 图形样式 OptionButtonW1.Style = vbButtonGraphical Set OptionButtonW1.Picture = LoadPicture("C:\icon.bmp") Set OptionButtonW1.DownPicture = LoadPicture("C:\icon_down.bmp") ' 按下式选项按钮 OptionButtonW1.PushLike = True ' 使用图像列表 Set OptionButtonW1.ImageList = ImageList1 OptionButtonW1.ImageListAlignment = OptImageListAlignmentLeft OptionButtonW1.ImageListMargin = 4 ' 所有者绘制 OptionButtonW1.DrawMode = OptDrawModeOwnerDraw ``` --- --- url: /zh/packages/vbccr/views/tabstrip.md description: 选项卡控件(TabStrip) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 选项卡控件(TabStrip) 提供可自定义的选项卡容器,支持多种放置位置、多行标签、分隔符、自绘和OLE拖放。 ## 枚举 ### TbsPlacementConstants 选项卡放置位置常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbsPlacementTop | 0 | 顶部放置 | | TbsPlacementBottom | 1 | 底部放置 | | TbsPlacementLeft | 2 | 左侧放置 | | TbsPlacementRight | 3 | 右侧放置 | ### TbsStyleConstants 选项卡控件样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbsStyleTab | 0 | 标准选项卡样式 | | TbsStyleButton | 1 | 按钮样式 | | TbsStyleFlatButton | 2 | 扁平按钮样式 | ### TbsTabStyleConstants 选项卡标签样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbsTabStyleTab | 0 | 标准标签样式 | | TbsTabStyleButton | 1 | 按钮标签样式 | ### TbsTabWidthStyleConstants 选项卡宽度样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbsTabWidthStyleJustified | 0 | 根据标签宽度自动调整 | | TbsTabWidthStyleFixed | 1 | 固定宽度 | | TbsTabWidthStyleVariable | 2 | 可变宽度 | ### TbsTabAlignmentConstants 选项卡标签对齐方式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbsTabAlignmentNear | 0 | 靠近起始边对齐 | | TbsTabAlignmentCenter | 1 | 居中对齐 | | TbsTabAlignmentFar | 2 | 靠近结束边对齐 | ### TbsHitResultConstants 命中测试结果常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbsHitNowhere | 0 | 未命中任何选项卡 | | TbsHitTab | 1 | 命中选项卡 | | TbsHitDivider | 2 | 命中分隔符 | | TbsHitDisplay | 3 | 命中显示区域 | ### TbsDrawModeConstants 自绘模式常量。 | 常量 | 值 | 说明 | |------|-----|------| | TbsDrawModeNormal | 0 | 正常绘制 | | TbsDrawModeOwnerDraw | 1 | 自绘模式 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### Container ```vb Public Property Get Container() As Object Public Property Set Container(ByVal Value As Object) ``` 返回/设置对象的容器。 ### Left ```vb Public Property Get Left() As Single Public Property Let Left(ByVal Value As Single) ``` 返回/设置对象与其容器左边缘的距离。 ### Top ```vb Public Property Get Top() As Single Public Property Let Top(ByVal Value As Single) ``` 返回/设置对象与其容器顶边缘的距离。 ### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 返回/设置对象的宽度。 ### Height ```vb Public Property Get Height() As Single Public Property Let Height(ByVal Value As Single) ``` 返回/设置对象的高度。 ### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 返回/设置鼠标悬停时显示的提示文本。 ### WhatsThisHelpID ```vb Public Property Get WhatsThisHelpID() As Long Public Property Let WhatsThisHelpID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### DragIcon ```vb Public Property Get DragIcon() As IPictureDisp Public Property Let DragIcon(ByVal Value As IPictureDisp) Public Property Set DragIcon(ByVal Value As IPictureDisp) ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Public Property Get DragMode() As Integer Public Property Let DragMode(ByVal Value As Integer) ``` 返回/设置拖动模式(手动或自动)。 ### hWnd ```vb Public Property Get hWnd() As LongPtr ``` 返回控件句柄。 ### hWndUserControl ```vb Public Property Get hWndUserControl() As LongPtr ``` 返回UserControl句柄。 ### Font ```vb Public Property Get Font() As StdFont Public Property Let Font(ByVal NewFont As StdFont) Public Property Set Font(ByVal NewFont As StdFont) ``` 返回/设置字体。 ### VisualStyles ```vb Public Property Get VisualStyles() As Boolean Public Property Let VisualStyles(ByVal Value As Boolean) ``` 返回/设置是否启用视觉样式。需要comctl32.dll 6.0或更高版本。 ### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 返回/设置对象是否能响应用户事件。 ### OLEDropMode ```vb Public Property Get OLEDropMode() As OLEDropModeConstants Public Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` 返回/设置对象是否可以作为OLE放置目标。 ### MousePointer ```vb Public Property Get MousePointer() As CCMousePointerConstants Public Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 返回/设置鼠标悬停时显示的指针类型。参见通用枚举。 ### MouseIcon ```vb Public Property Get MouseIcon() As IPictureDisp Public Property Let MouseIcon(ByVal Value As IPictureDisp) Public Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Public Property Get MouseTrack() As Boolean Public Property Let MouseTrack(ByVal Value As Boolean) ``` 返回/设置是否在鼠标进入或离开控件时触发事件。 ### RightToLeft ```vb Public Property Get RightToLeft() As Boolean Public Property Let RightToLeft(ByVal Value As Boolean) ``` 返回/设置从右到左显示方向。 ### RightToLeftLayout ```vb Public Property Get RightToLeftLayout() As Boolean Public Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 返回/设置从右到左布局。 ### RightToLeftMode ```vb Public Property Get RightToLeftMode() As CCRightToLeftModeConstants Public Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 返回/设置从右到左模式。参见通用枚举。 ### BackColor ```vb Public Property Get BackColor() As OLE_COLOR Public Property Let BackColor(ByVal Value As OLE_COLOR) ``` 返回/设置背景色。 ### ImageList ```vb Public Property Get ImageList() As Variant Public Property Let ImageList(ByVal Value As Variant) Public Property Set ImageList(ByVal Value As Variant) ``` 返回/设置关联的ImageList控件。可以是对象引用、字符串键名或LongPtr句柄。 ### Placement ```vb Public Property Get Placement() As TbsPlacementConstants Public Property Let Placement(ByVal Value As TbsPlacementConstants) ``` 返回/设置选项卡的放置位置。 ### MultiRow ```vb Public Property Get MultiRow() As Boolean Public Property Let MultiRow(ByVal Value As Boolean) ``` 返回/设置选项卡是否允许多行显示。 ### MultiSelect ```vb Public Property Get MultiSelect() As Boolean Public Property Let MultiSelect(ByVal Value As Boolean) ``` 返回/设置是否允许选择多个选项卡。 ### HotTracking ```vb Public Property Get HotTracking() As Boolean Public Property Let HotTracking(ByVal Value As Boolean) ``` 返回/设置是否启用热点跟踪。 ### Style ```vb Public Property Get Style() As TbsStyleConstants Public Property Let Style(ByVal Value As TbsStyleConstants) ``` 返回/设置选项卡控件样式。 ### TabStyle ```vb Public Property Get TabStyle() As TbsTabStyleConstants Public Property Let TabStyle(ByVal Value As TbsTabStyleConstants) ``` 返回/设置选项卡标签样式。 ### TabWidthStyle ```vb Public Property Get TabWidthStyle() As TbsTabWidthStyleConstants Public Property Let TabWidthStyle(ByVal Value As TbsTabWidthStyleConstants) ``` 返回/设置选项卡宽度样式。 ### TabFixedWidth ```vb Public Property Get TabFixedWidth() As Single Public Property Let TabFixedWidth(ByVal Value As Single) ``` 返回/设置固定宽度样式下选项卡的宽度。 ### TabFixedHeight ```vb Public Property Get TabFixedHeight() As Single Public Property Let TabFixedHeight(ByVal Value As Single) ``` 返回/设置固定高度样式下选项卡的高度。 ### TabMinWidth ```vb Public Property Get TabMinWidth() As Single Public Property Let TabMinWidth(ByVal Value As Single) ``` 返回/设置选项卡的最小宽度。 ### TabAlignment ```vb Public Property Get TabAlignment() As TbsTabAlignmentConstants Public Property Let TabAlignment(ByVal Value As TbsTabAlignmentConstants) ``` 返回/设置选项卡标签的对齐方式。 ### Separators ```vb Public Property Get Separators() As Boolean Public Property Let Separators(ByVal Value As Boolean) ``` 返回/设置是否在选项卡之间显示分隔符。 ### ShowTips ```vb Public Property Get ShowTips() As Boolean Public Property Let ShowTips(ByVal Value As Boolean) ``` 返回/设置是否显示工具提示。 ### DrawMode ```vb Public Property Get DrawMode() As TbsDrawModeConstants Public Property Let DrawMode(ByVal Value As TbsDrawModeConstants) ``` 返回/设置绘制模式。 ### TabScrollWheel ```vb Public Property Get TabScrollWheel() As Boolean Public Property Let TabScrollWheel(ByVal Value As Boolean) ``` 返回/设置是否允许使用鼠标滚轮切换选项卡。 ### DoubleBuffer ```vb Public Property Get DoubleBuffer() As Boolean Public Property Let DoubleBuffer(ByVal Value As Boolean) ``` 返回/设置是否启用双缓冲绘制。 ### Transparent ```vb Public Property Get Transparent() As Boolean Public Property Let Transparent(ByVal Value As Boolean) ``` 返回/设置选项卡控件是否透明。 ### Tabs ```vb Public Property Get Tabs() As TbsTabs ``` 返回选项卡集合。 ### ClientLeft ```vb Public Property Get ClientLeft() As Single ``` 返回客户区域的左边距。 ### ClientTop ```vb Public Property Get ClientTop() As Single ``` 返回客户区域的顶边距。 ### ClientWidth ```vb Public Property Get ClientWidth() As Single ``` 返回客户区域的宽度。 ### ClientHeight ```vb Public Property Get ClientHeight() As Single ``` 返回客户区域的高度。 ### SelectedItem ```vb Public Property Get SelectedItem() As TbsTab Public Property Let SelectedItem(ByVal Value As TbsTab) ``` 返回/设置当前选中的选项卡。 ### RowCount ```vb Public Property Get RowCount() As Long ``` 返回选项卡行数。 ## 方法 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘对象。 ### DeselectAll ```vb Public Sub DeselectAll() ``` 取消所有选项卡的选中状态。 ### HitTest ```vb Public Function HitTest(ByVal X As Single, ByVal Y As Single) As TbsHitResultConstants ``` 对指定坐标进行命中测试,返回命中结果。 ### DrawBackground ```vb Public Sub DrawBackground(ByVal hdc As LongPtr, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` 在指定设备上下文中绘制选项卡控件背景。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动OLE拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移至控件。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置Z顺序。 ## 事件 ### TabBeforeClick ```vb Public Event TabBeforeClick(ByVal Tab As TbsTab, ByRef Cancel As Boolean) ``` 选项卡即将被点击时触发。Cancel为True时取消切换。 ### TabClick ```vb Public Event TabClick(ByVal Tab As TbsTab) ``` 选项卡被点击时触发。 ### ItemDraw ```vb Public Event ItemDraw(ByVal Index As Long, ByVal ItemData As Long, ByVal hdc As LongPtr, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` 自绘模式下绘制选项卡时触发。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(KeyCode As Integer, Shift As Integer) ``` 在KeyDown事件之前触发,用于预处理键盘输入。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(KeyCode As Integer, Shift As Integer) ``` 在KeyUp事件之前触发。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下键盘按键时触发。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放键盘按键时触发。 ### KeyPress ```vb Public Event KeyPress(KeyAscii As Integer) ``` 按下并释放ANSI键时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件区域时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件区域时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE拖放操作完成时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE拖放操作放置时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE拖放操作悬停时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE拖放操作给反馈时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE拖放操作设置数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE拖放操作开始时触发。 ## 子对象 ### TbsTab 类 选项卡标签对象。 #### TbsTab 属性 #### Index ```vb Public Property Get Index() As Long ``` 选项卡在集合中的索引。 #### Key ```vb Public Property Get Key() As String Public Property Let Key(ByVal Value As String) ``` 选项卡的唯一标识键。 #### Tag ```vb Public Property Get Tag() As Variant Public Property Let Tag(ByVal Value As Variant) ``` 额外数据。 #### Caption ```vb Public Property Get Caption() As String Public Property Let Caption(ByVal Value As String) ``` 选项卡标题。 #### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 #### Image ```vb Public Property Get Image() As Variant Public Property Let Image(ByVal Value As Variant) ``` 选项卡图像。 #### ImageIndex ```vb Public Property Get ImageIndex() As Long ``` 图像索引。 #### Selected ```vb Public Property Get Selected() As Boolean Public Property Let Selected(ByVal Value As Boolean) ``` 是否选中。 #### Pressed ```vb Public Property Get Pressed() As Boolean Public Property Let Pressed(ByVal Value As Boolean) ``` 是否按下。 #### HighLighted ```vb Public Property Get HighLighted() As Boolean Public Property Let HighLighted(ByVal Value As Boolean) ``` 是否高亮显示。 #### Left ```vb Public Property Get Left() As Single ``` 选项卡左边距。 #### Top ```vb Public Property Get Top() As Single ``` 选项卡顶边距。 #### Width ```vb Public Property Get Width() As Single ``` 选项卡宽度。 #### Height ```vb Public Property Get Height() As Single ``` 选项卡高度。 ### TbsTabs 类 选项卡集合。 #### TbsTabs 成员 #### NewEnum ```vb Public Function NewEnum() As IUnknown ``` 枚举器(隐藏)。 #### Add ```vb Public Function Add(Optional ByVal Index As Variant, Optional ByVal Key As Variant, Optional ByVal Caption As Variant, Optional ByVal Image As Variant) As TbsTab ``` 添加选项卡。 #### Item ```vb Public Function Item(ByVal Index As Variant) As TbsTab ``` 获取选项卡(默认成员)。 #### Exists ```vb Public Function Exists(ByVal Index As Variant) As Boolean ``` 检查选项卡是否存在。 #### Count ```vb Public Property Get Count() As Long ``` 选项卡数量。 #### Clear ```vb Public Sub Clear() ``` 清除所有选项卡。 #### Remove ```vb Public Sub Remove(ByVal Index As Variant) ``` 移除选项卡。 ## 代码示例 ### 基本用法 ```vb ' 创建选项卡 With TabStrip1.Tabs .Add , "Tab1", "常规" .Add , "Tab2", "高级" .Add , "Tab3", "关于" End With ' 设置选项卡样式 TabStrip1.Placement = TbsPlacementTop TabStrip1.Style = TbsStyleTab TabStrip1.TabWidthStyle = TbsTabWidthStyleFixed TabStrip1.TabFixedWidth = 80 TabStrip1.MultiRow = False TabStrip1.HotTracking = True ' 处理选项卡切换 Private Sub TabStrip1_TabBeforeClick(ByVal Tab As TbsTab, ByRef Cancel As Boolean) If Tab.Key = "Tab3" Then Cancel = True MsgBox "此选项卡已禁用" End If End Sub Private Sub TabStrip1_TabClick(ByVal Tab As TbsTab) MsgBox "选中的选项卡: " & Tab.Caption End Sub ' 使用客户区域定位子控件 Private Sub TabStrip1_TabClick(ByVal Tab As TbsTab) Dim l As Single, t As Single l = TabStrip1.ClientLeft t = TabStrip1.ClientTop Frame1.Move l, t, TabStrip1.ClientWidth, TabStrip1.ClientHeight End Sub ``` --- --- url: /zh/official/Features/Language/Loop-Control.md --- # 循环控制 以下新语句可用于控制循环的执行流程: * `Continue For` - 进入 `For` 循环的下一次迭代(或结束)。 * `Continue While` - 进入 `While` 循环的下一次迭代(或结束)。 * `Continue Do` - 进入 `Do` 循环的下一次迭代。 * `Exit While` - 立即退出 `While` 循环。 ## 示例 ```vb Dim i As Long For i = 1 To 10 If i Mod 2 = 0 Then Continue For ' skip even numbers If i > 7 Then Exit For ' stop before reaching 8 Debug.Print i Next ' prints: 1, 3, 5, 7 ``` --- --- url: /zh/official/Documentation/Permanent-Links.md --- # 永久链接 文档树中稳定的、可通过机器访问的部分以 `/tB/` 前缀为根。带有此前缀的URL——以及指向它们的内部链接,例如 [`docs.twinbasic.com/tB/Modules/Math/Round`](/official/Reference/VBA/Math/Round)——保证不会移动。这是IDE帮助系统、`[Documentation(...)]` 属性引用和外部链接所依赖的契约;以下记录的任何内容都应被视为必不可少的。 ## /tB/Core/`<Statement>` * [AppActivate](/official/Reference/Core/AppActivate) * [Beep](/official/Reference/Core/Beep) * [Call](/official/Reference/Core/Call), [ChDir](/official/Reference/Core/ChDir), [ChDrive](/official/Reference/Core/ChDrive), [Class](/official/Reference/Core/Class), [Close](/official/Reference/Core/Close), [CoClass](/official/Reference/Core/CoClass), [Const](/official/Reference/Core/Const), [Continue](/official/Reference/Core/Continue) * [Date](/official/Reference/Core/Date), [Declare](/official/Reference/Core/Declare), [Deftype](/official/Reference/Core/Deftype), [DeleteSetting](/official/Reference/Core/DeleteSetting), [Dim](/official/Reference/Core/Dim), [Do-Loop](/official/Reference/Core/Do-Loop) * [End](/official/Reference/Core/End), [Enum](/official/Reference/Core/Enum), [Erase](/official/Reference/Core/Erase), [Error](/official/Reference/Core/Error), [Event](/official/Reference/Core/Event), [Exit](/official/Reference/Core/Exit) * [FileCopy](/official/Reference/Core/FileCopy), [For-Next](/official/Reference/Core/For-Next), [For-Each-Next](/official/Reference/Core/For-Each-Next), [Function](/official/Reference/Core/Function) * [Get](/official/Reference/Core/Get), [GetSetting](/official/Reference/Core/GetSetting), [GoSub-Return](/official/Reference/Core/GoSub-Return), [GoTo](/official/Reference/Core/GoTo) * [If-Then-Else](/official/Reference/Core/If-Then-Else), [Implements](/official/Reference/Core/Implements), [Input](/official/Reference/Core/Input), [Interface](/official/Reference/Core/Interface), [Is](/official/Reference/Core/Is) * [Kill](/official/Reference/Core/Kill) * [LBound](/official/Reference/Core/LBound), [Let](/official/Reference/Core/Let), [Line-Input](/official/Reference/Core/Line-Input), [Load](/official/Reference/Core/Load), [Lock](/official/Reference/Core/Lock), [LSet](/official/Reference/Core/LSet) * [Mid-equals](/official/Reference/Core/Mid-equals) 用于 `Mid(...) = ...`,[MidB-equals](/official/Reference/Core/MidB-equals) 用于 `MidB(...) = ...`,[MkDir](/official/Reference/Core/MkDir),[Module](/official/Reference/Core/Module) * [Name](/official/Reference/Core/Name), [New](/official/Reference/Core/New) * [Option](/official/Reference/Core/Option), [On-Error](/official/Reference/Core/On-Error), [On-GoSub](/official/Reference/Core/On-GoSub), [On-GoTo](/official/Reference/Core/On-GoTo), [Open](/official/Reference/Core/Open) * [ParamArray](/official/Reference/Core/ParamArray), [Print](/official/Reference/Core/Print), [Private](/official/Reference/Core/Private), [Property](/official/Reference/Core/Property), [Protected](/official/Reference/Core/Protected), [Public](/official/Reference/Core/Public), [Put](/official/Reference/Core/Put) * [RaiseEvent](/official/Reference/Core/RaiseEvent), [ReDim](/official/Reference/Core/ReDim), [Reset](/official/Reference/Core/Reset), [Resume](/official/Reference/Core/Resume), [RmDir](/official/Reference/Core/RmDir), [RSet](/official/Reference/Core/RSet) * [SavePicture](/official/Reference/Core/SavePicture), [SaveSetting](/official/Reference/Core/SaveSetting), [Seek](/official/Reference/Core/Seek), [Select-Case](/official/Reference/Core/Select-Case), [SendKeys](/official/Reference/Core/SendKeys), [Set](/official/Reference/Core/Set), [SetAttr](/official/Reference/Core/SetAttr), [Static](/official/Reference/Core/Static), [Sub](/official/Reference/Core/Sub), [Stop](/official/Reference/Core/Stop) * [Time](/official/Reference/Core/Time), [Type](/official/Reference/Core/Type) * [Unload](/official/Reference/Core/Unload), [Unlock](/official/Reference/Core/Unlock) * [While-Wend](/official/Reference/Core/While-Wend), [Width](/official/Reference/Core/Width), [With](/official/Reference/Core/With), [Write](/official/Reference/Core/Write) ## /tB/Modules/`<ModuleName>`/`<Symbol>` 在每个VBA模块中,每个过程、属性或语句都有自己独立的页面,例如 [**LenB**: /tB/Modules/Strings/Len](/official/Reference/VBA/Strings/Len)。带 `$` 后缀和 `B`/`W` 变体的符号记录在与基础符号相同的页面上(因此 `LenB`、`Len$` 等都共享 [`Len`](/official/Reference/VBA/Strings/Len) 页面)。 * [Collection](/official/Reference/VBA/Collection/) * [Compilation](/official/Reference/VBA/Compilation/) * [Constants](/official/Reference/VBA/Constants/) * [Conversion](/official/Reference/VBA/Conversion/) * [DateTime](/official/Reference/VBA/DateTime/) * [ErrObject](/official/Reference/VBA/ErrObject/) * [TbExpressionService](/official/Reference/VBA/TbExpressionService/) * [FileSystem](/official/Reference/VBA/FileSystem/) * [Financial](/official/Reference/VBA/Financial/) * [Information](/official/Reference/VBA/Information/) * [Interaction](/official/Reference/VBA/Interaction/) * [Math](/official/Reference/VBA/Math/) * [Strings](/official/Reference/VBA/Strings/) * 内部 [\_HiddenModule](/official/Reference/VBA/HiddenModule/) ## /tB/Packages/`<Package>`/... 每个包位于 `/tB/Packages/<Package>/` 下。子结构取决于包:模块、类、枚举和子对象各有自己的页面。 ### VBRUN -- /tB/Packages/VBRUN/`<Module>`/ * [AmbientProperties](/official/Reference/VBRUN/AmbientProperties/) * [AsyncProperty](/official/Reference/VBRUN/AsyncProperty/) * [Constants](/official/Reference/VBRUN/Constants/) * [ContainedControls](/official/Reference/VBRUN/ContainedControls/) * [DataMembers](/official/Reference/VBRUN/DataMembers/) * [DataObject](/official/Reference/VBRUN/DataObject/) * [ErrorCallstack](/official/Reference/VBRUN/ErrorCallstack/) * [ErrorContext](/official/Reference/VBRUN/ErrorContext/) * [ErrorStackFrame](/official/Reference/VBRUN/ErrorStackFrame/) * [Hyperlink](/official/Reference/VBRUN/Hyperlink/) * [ParentControls](/official/Reference/VBRUN/ParentControls/) * [PropertyBag](/official/Reference/VBRUN/PropertyBag/) ### VB -- /tB/Packages/VB/`<Class>`/ * [App](/official/Reference/VB/App/), [CheckBox](/official/Reference/VB/CheckBox/), [CheckMark](/official/Reference/VB/CheckMark/), [Clipboard](/official/Reference/VB/Clipboard/), [ComboBox](/official/Reference/VB/ComboBox/), [CommandButton](/official/Reference/VB/CommandButton/) * [Data](/official/Reference/VB/Data/), [DirListBox](/official/Reference/VB/DirListBox/), [DriveListBox](/official/Reference/VB/DriveListBox/) * [FileListBox](/official/Reference/VB/FileListBox/), [Form](/official/Reference/VB/Form/), [Frame](/official/Reference/VB/Frame/), [Global](/official/Reference/VB/Global/) * [HScrollBar](/official/Reference/VB/HScrollBar/), [Image](/official/Reference/VB/Image/) * [Label](/official/Reference/VB/Label/), [Line](/official/Reference/VB/Line/), [ListBox](/official/Reference/VB/ListBox/) * [MDIForm](/official/Reference/VB/MDIForm/), [Menu](/official/Reference/VB/Menu/), [MultiFrame](/official/Reference/VB/MultiFrame/) * [OLE](/official/Reference/VB/OLE/), [OptionButton](/official/Reference/VB/OptionButton/) * [PictureBox](/official/Reference/VB/PictureBox/), [Printer](/official/Reference/VB/Printer/), [Printers](/official/Reference/VB/Printers/), [PropertyPage](/official/Reference/VB/PropertyPage/) * [QRCode](/official/Reference/VB/QRCode/), [Report](/official/Reference/VB/Report/) * [Screen](/official/Reference/VB/Screen/), [Shape](/official/Reference/VB/Shape/) * [TextBox](/official/Reference/VB/TextBox/), [Timer](/official/Reference/VB/Timer/) * [UserControl](/official/Reference/VB/UserControl/), [VScrollBar](/official/Reference/VB/VScrollBar/) ### WebView2 -- /tB/Packages/WebView2/... * [WebView2](/official/Reference/WebView2/WebView2/)(控件类,含 [EnvironmentOptions](/official/Reference/WebView2/WebView2/EnvironmentOptions) 子页面) * [WebView2Header](/official/Reference/WebView2/WebView2Header), [WebView2HeadersCollection](/official/Reference/WebView2/WebView2HeadersCollection), [WebView2Request](/official/Reference/WebView2/WebView2Request), [WebView2RequestHeaders](/official/Reference/WebView2/WebView2RequestHeaders), [WebView2Response](/official/Reference/WebView2/WebView2Response), [WebView2ResponseHeaders](/official/Reference/WebView2/WebView2ResponseHeaders) * 枚举:[wv2DefaultDownloadCornerAlign](/official/Reference/WebView2/Enumerations/wv2DefaultDownloadCornerAlign), [wv2ErrorStatus](/official/Reference/WebView2/Enumerations/wv2ErrorStatus), [wv2HostResourceAccessKind](/official/Reference/WebView2/Enumerations/wv2HostResourceAccessKind), [wv2KeyEventKind](/official/Reference/WebView2/Enumerations/wv2KeyEventKind), [wv2PermissionKind](/official/Reference/WebView2/Enumerations/wv2PermissionKind), [wv2PermissionState](/official/Reference/WebView2/Enumerations/wv2PermissionState), [wv2PrintOrientation](/official/Reference/WebView2/Enumerations/wv2PrintOrientation), [wv2ProcessFailedKind](/official/Reference/WebView2/Enumerations/wv2ProcessFailedKind), [wv2ScriptDialogKind](/official/Reference/WebView2/Enumerations/wv2ScriptDialogKind), [wv2WebResourceContext](/official/Reference/WebView2/Enumerations/wv2WebResourceContext) * 类型:[COREWEBVIEW2\_PHYSICAL\_KEY\_STATUS](/official/Reference/WebView2/Types/COREWEBVIEW2_PHYSICAL_KEY_STATUS) ### Assert -- /tB/Packages/Assert/`<Module>` * [Exact](/official/Reference/Assert/Exact), [Strict](/official/Reference/Assert/Strict), [Permissive](/official/Reference/Assert/Permissive) ### CustomControls -- /tB/Packages/CustomControls/... * 控件:[WaynesButton](/official/Reference/CustomControls/WaynesButton/)(含 [WaynesButtonState](/official/Reference/CustomControls/WaynesButton/WaynesButtonState)),[WaynesForm](/official/Reference/CustomControls/WaynesForm/)(含 [WindowsFormOptions](/official/Reference/CustomControls/WaynesForm/WindowsFormOptions)),[WaynesFrame](/official/Reference/CustomControls/WaynesFrame),[WaynesGrid](/official/Reference/CustomControls/WaynesGrid/)(含 [CellRenderingOptions](/official/Reference/CustomControls/WaynesGrid/CellRenderingOptions), [Column](/official/Reference/CustomControls/WaynesGrid/Column)),[WaynesLabel](/official/Reference/CustomControls/WaynesLabel),[WaynesSlider](/official/Reference/CustomControls/WaynesSlider/)(含 [WaynesSliderState](/official/Reference/CustomControls/WaynesSlider/WaynesSliderState)),[WaynesTextBox](/official/Reference/CustomControls/WaynesTextBox/)(含 [WaynesTextBoxState](/official/Reference/CustomControls/WaynesTextBox/WaynesTextBoxState)),[WaynesTimer](/official/Reference/CustomControls/WaynesTimer) * 样式:[Anchors](/official/Reference/CustomControls/Styles/Anchors), [Borders](/official/Reference/CustomControls/Styles/Borders), [Corners](/official/Reference/CustomControls/Styles/Corners), [Fill](/official/Reference/CustomControls/Styles/Fill), [Line](/official/Reference/CustomControls/Styles/Line), [Padding](/official/Reference/CustomControls/Styles/Padding), [TextRendering](/official/Reference/CustomControls/Styles/TextRendering) * 框架:[Canvas](/official/Reference/CustomControls/Framework/Canvas), [CustomControlContext](/official/Reference/CustomControls/Framework/CustomControlContext), [CustomControlsCollection](/official/Reference/CustomControls/Framework/CustomControlsCollection), [CustomControlTimer](/official/Reference/CustomControls/Framework/CustomControlTimer), [CustomFormContext](/official/Reference/CustomControls/Framework/CustomFormContext), [ICustomControl](/official/Reference/CustomControls/Framework/ICustomControl), [ICustomForm](/official/Reference/CustomControls/Framework/ICustomForm), [SerializeInfo](/official/Reference/CustomControls/Framework/SerializeInfo) * 枚举:[BorderStyle](/official/Reference/CustomControls/Enumerations/BorderStyle), [ColorRGBA](/official/Reference/CustomControls/Enumerations/ColorRGBA), [CornerShape](/official/Reference/CustomControls/Enumerations/CornerShape), [Customtate](/official/Reference/CustomControls/Enumerations/Customtate), [DockMode](/official/Reference/CustomControls/Enumerations/DockMode), [FillPattern](/official/Reference/CustomControls/Enumerations/FillPattern), [FontWeight](/official/Reference/CustomControls/Enumerations/FontWeight), [PixelCount](/official/Reference/CustomControls/Enumerations/PixelCount), [PointSize](/official/Reference/CustomControls/Enumerations/PointSize), [StartupPosition](/official/Reference/CustomControls/Enumerations/StartupPosition), [TextAlignment](/official/Reference/CustomControls/Enumerations/TextAlignment), [TextOverflowMode](/official/Reference/CustomControls/Enumerations/TextOverflowMode), [WindowState](/official/Reference/CustomControls/Enumerations/WindowState) ### CEF -- /tB/Packages/CEF/... * [CefBrowser](/official/Reference/CEF/CefBrowser/)(控件类,含 [EnvironmentOptions](/official/Reference/CEF/CefBrowser/EnvironmentOptions) 子页面) * 枚举:[CefLogSeverity](/official/Reference/CEF/Enumerations/CefLogSeverity), [cefPrintOrientation](/official/Reference/CEF/Enumerations/cefPrintOrientation) ### WinEventLogLib -- /tB/Packages/WinEventLogLib/`<Class>` * [EventLog](/official/Reference/WinEventLogLib/EventLog), [EventLogHelperPublic](/official/Reference/WinEventLogLib/EventLogHelperPublic) ### WinNamedPipesLib -- /tB/Packages/WinNamedPipesLib/`<Class>` * [NamedPipeClientConnection](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection), [NamedPipeClientManager](/official/Reference/WinNamedPipesLib/NamedPipeClientManager), [NamedPipeServer](/official/Reference/WinNamedPipesLib/NamedPipeServer), [NamedPipeServerConnection](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection) ### WinServicesLib -- /tB/Packages/WinServicesLib/... * [ITbService](/official/Reference/WinServicesLib/ITbService), [ServiceCreator](/official/Reference/WinServicesLib/ServiceCreator), [ServiceManager](/official/Reference/WinServicesLib/ServiceManager), [Services](/official/Reference/WinServicesLib/Services), [ServiceState](/official/Reference/WinServicesLib/ServiceState) * 枚举:[ServiceControlCodeConstants](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants), [ServiceStartConstants](/official/Reference/WinServicesLib/Enumerations/ServiceStartConstants), [ServiceStatusConstants](/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants), [ServiceTypeConstants](/official/Reference/WinServicesLib/Enumerations/ServiceTypeConstants) ### tbIDE -- /tB/Packages/tbIDE/`<Class>` * [AddIn](/official/Reference/tbIDE/AddIn), [AddinTimer](/official/Reference/tbIDE/AddinTimer), [Button](/official/Reference/tbIDE/Button), [CodeEditor](/official/Reference/tbIDE/CodeEditor), [DebugConsole](/official/Reference/tbIDE/DebugConsole), [Editor](/official/Reference/tbIDE/Editor), [Editors](/official/Reference/tbIDE/Editors) * [File](/official/Reference/tbIDE/File), [FileSystem](/official/Reference/tbIDE/FileSystem), [FileSystemItem](/official/Reference/tbIDE/FileSystemItem), [Folder](/official/Reference/tbIDE/Folder) * [Host](/official/Reference/tbIDE/Host), [HtmlElement](/official/Reference/tbIDE/HtmlElement), [HtmlElementProperties](/official/Reference/tbIDE/HtmlElementProperties), [HtmlElementProperty](/official/Reference/tbIDE/HtmlElementProperty), [HtmlElements](/official/Reference/tbIDE/HtmlElements), [HtmlEventProperties](/official/Reference/tbIDE/HtmlEventProperties), [HtmlEventProperty](/official/Reference/tbIDE/HtmlEventProperty) * [KeyboardShortcuts](/official/Reference/tbIDE/KeyboardShortcuts), [Project](/official/Reference/tbIDE/Project), [Themes](/official/Reference/tbIDE/Themes), [Toolbar](/official/Reference/tbIDE/Toolbar), [Toolbars](/official/Reference/tbIDE/Toolbars), [ToolWindow](/official/Reference/tbIDE/ToolWindow), [ToolWindows](/official/Reference/tbIDE/ToolWindows) ### WinNativeCommonCtls -- /tB/Packages/WinNativeCommonCtls/... * 控件:[DTPicker](/official/Reference/WinNativeCommonCtls/DTPicker), [ImageList](/official/Reference/WinNativeCommonCtls/ImageList/), [ListView](/official/Reference/WinNativeCommonCtls/ListView/), [MonthView](/official/Reference/WinNativeCommonCtls/MonthView), [ProgressBar](/official/Reference/WinNativeCommonCtls/ProgressBar), [Slider](/official/Reference/WinNativeCommonCtls/Slider), [TreeView](/official/Reference/WinNativeCommonCtls/TreeView/), [UpDown](/official/Reference/WinNativeCommonCtls/UpDown) * 子对象:[ListImages](/official/Reference/WinNativeCommonCtls/ImageList/ListImages), [ListImage](/official/Reference/WinNativeCommonCtls/ImageList/ListImage), [ListItems](/official/Reference/WinNativeCommonCtls/ListView/ListItems), [ListItem](/official/Reference/WinNativeCommonCtls/ListView/ListItem), [ColumnHeaders](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders), [ColumnHeader](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader), [Nodes](/official/Reference/WinNativeCommonCtls/TreeView/Nodes), [Node](/official/Reference/WinNativeCommonCtls/TreeView/Node) * 枚举:[DTPickerFormatConstants](/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants), [ImlDrawConstants](/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants), [OrientationConstants](/official/Reference/WinNativeCommonCtls/Enumerations/OrientationConstants), [TreeBorderStyleConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeBorderStyleConstants), [TreeLabelEditConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeLabelEditConstants), [TreeLineStyleConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeLineStyleConstants), [TreeRelationshipConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeRelationshipConstants), [TreeSortOrderConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortOrderConstants), [TreeSortTypeConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortTypeConstants), [TreeStyleConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeStyleConstants) ## /tB/Core/Attributes#`<attribute>` ::: info 链接中会移除所有非字母字符以及参数。属性名称在链接中均为小写。例如 `ArrayBoundsChecks(Bool)` 引用为 `/tB/Core/Attributes#arrayboundschecks`。 ::: * [AppObject](/official/Reference/Attributes#appobject), [ArrayBoundsChecks](/official/Reference/Attributes#arrayboundschecks) * [BindOnlyIfNoArguments](/official/Reference/Attributes#bindonlyifnoarguments), [BindOnlyIfStringSuffix](/official/Reference/Attributes#bindonlyifstringsuffix) * [ClassId](/official/Reference/Attributes#classid), [ClassInterface](/official/Reference/Attributes#classinterface), [CoClassCustomConstructor](/official/Reference/Attributes#coclasscustomconstructor), [CoClassId](/official/Reference/Attributes#coclassid), [COMControl](/official/Reference/Attributes#comcontrol), [COMCreatable](/official/Reference/Attributes#comcreatable), [COMExtensible](/official/Reference/Attributes#comextensible), [ComImport](/official/Reference/Attributes#comimport), [CompileIf](/official/Reference/Attributes#compileif), [CompilerOptions](/official/Reference/Attributes#compileroptions), [ConstantFoldable](/official/Reference/Attributes#constantfoldable), [ConstantFoldableNumericsOnly](/official/Reference/Attributes#constantfoldablenumericsonly) * [Debuggable](/official/Reference/Attributes#debuggable), [DebugOnly](/official/Reference/Attributes#debugonly), [DefaultMember](/official/Reference/Attributes#defaultmember), [Description](/official/Reference/Attributes#description), [DispId](/official/Reference/Attributes#dispid), [DispInterface](/official/Reference/Attributes#dispinterface), [DllExport](/official/Reference/Attributes#dllexport), [DLLStackCheck](/official/Reference/Attributes#dllstackcheck), [DualInterface](/official/Reference/Attributes#dualinterface) * [EnforceErrors](/official/Reference/Attributes#enforceerrors), [EnforceWarnings](/official/Reference/Attributes#enforcewarnings), [EnumId](/official/Reference/Attributes#enumid), [EventInterfaceId](/official/Reference/Attributes#eventinterfaceid), [EventsUseDispInterface](/official/Reference/Attributes#eventsusedispinterface) * [Flags](/official/Reference/Attributes#flags), [FloatingPointErrorChecks](/official/Reference/Attributes#floatingpointerrorchecks), [FormDesignerId](/official/Reference/Attributes#formdesignerid), [Hidden](/official/Reference/Attributes#hidden) * [IdeButton](/official/Reference/Attributes#idebutton), [IgnoreWarnings](/official/Reference/Attributes#ignorewarnings), [IntegerOverflowChecks](/official/Reference/Attributes#integeroverflowchecks), [InterfaceId](/official/Reference/Attributes#interfaceid) * [MustBeQualified](/official/Reference/Attributes#mustbequalified) * [OleAutomation](/official/Reference/Attributes#oleautomation) * [PackingAlignment](/official/Reference/Attributes#packingalignment), [PopulateFrom](/official/Reference/Attributes#populatefrom), [PredeclaredID](/official/Reference/Attributes#predeclaredid), [PreserveSig](/official/Reference/Attributes#preservesig) * [Restricted](/official/Reference/Attributes#restricted), [RunAfterBuild](/official/Reference/Attributes#runafterbuild) * [Serialize](/official/Reference/Attributes#serialize), [SetDllDirectory](/official/Reference/Attributes#setdlldirectory), [SimplerByVals](/official/Reference/Attributes#simplerbyvals) * [TestCase](/official/Reference/Attributes#testcase), [TestFixture](/official/Reference/Attributes#testfixture), [TypeHint](/official/Reference/Attributes#typehint) * [Unimplemented](/official/Reference/Attributes#unimplemented), [UseGetLastError](/official/Reference/Attributes#usegetlasterror), [UserDefinedTypeIsAnAlias](/official/Reference/Attributes#userdefinedtypeisanalias) * [WindowsControl](/official/Reference/Attributes#windowscontrol) --- --- url: /zh/official/Reference/Statements.md --- # 语句 这些语句内置于语言本身。它们由编译器理解,不在可见的运行时库中显式声明或定义。 ## 字母顺序列表 * [Alias](/official/Reference/Core/Alias) -- (twinBASIC) 为内部类型、用户定义类型或接口声明替代名称 * [Call](/official/Reference/Core/Call) -- 将控制权转移给过程 * [Class](/official/Reference/Core/Class) -- 定义类 * [CoClass](/official/Reference/Core/CoClass) -- (twinBASIC) 定义可创建COM类,作为一个或多个**Interface**块的契约 * [Close](/official/Reference/Core/Close) -- 终止使用**Open**语句打开的文件的输入/输出(I/O) * [Const](/official/Reference/Core/Const) -- 声明常量以替代字面值 * [Continue](/official/Reference/Core/Continue) -- 立即开始封闭循环的下一次迭代 * [Declare](/official/Reference/Core/Declare) -- 声明对动态链接库(DLL)中外部过程的引用 * [Delegate](/official/Reference/Core/Delegate) -- (twinBASIC) 声明函数指针类型 --- 用于间接调用的命名签名 * [Dim](/official/Reference/Core/Dim) -- 声明变量并分配存储空间 * [Do ... Loop](/official/Reference/Core/Do-Loop) -- 在条件为**True**时或直到条件变为**True**时重复语句块 * [End](/official/Reference/Core/End) -- 结束过程或块 * [Enum](/official/Reference/Core/Enum) -- 声明枚举类型 * [Erase](/official/Reference/Core/Erase) -- 重新初始化固定大小数组的元素,或释放动态数组存储空间 * [Error](/official/Reference/Core/Error) -- 模拟错误的发生 * [Event](/official/Reference/Core/Event) -- 声明用户定义事件 * [Exit](/official/Reference/Core/Exit) -- 退出**Do…Loop**、**For…Next**、**Function**、**Sub**或**Property**代码块 * [For ... Next](/official/Reference/Core/For-Next) -- 在循环计数器趋近终值时重复一组语句 * [For Each...Next](/official/Reference/Core/For-Each-Next) -- 对数组或集合中的每个元素重复一组语句 * [Function](/official/Reference/Core/Function) -- 声明**Function**过程的名称、参数和代码体 * [Get](/official/Reference/Core/Get) -- 从打开的磁盘文件读取数据到变量 * [GoSub ... Return](/official/Reference/Core/GoSub-Return) -- 在过程中分支到子程序并返回 * [GoTo](/official/Reference/Core/GoTo) -- 无条件分支到过程中的指定行 * [Handles](/official/Reference/Core/Handles) -- (twinBASIC) 将过程绑定为命名事件的事件处理程序 * [If ... Then ... Else](/official/Reference/Core/If-Then-Else) -- 根据表达式值有条件地执行一组语句 * [Input #](/official/Reference/Core/Input) -- 从打开的顺序文件读取数据并赋值给变量 * [Implements](/official/Reference/Core/Implements) -- 指定将在出现它的类中实现的接口或类 * [Interface](/official/Reference/Core/Interface) -- (twinBASIC) 使用twinBASIC语法定义COM接口 * [Kill](/official/Reference/Core/Kill) -- 从磁盘中删除文件 * [Let](/official/Reference/Core/Let) -- 将表达式的值赋给变量或属性 * [Line Input #](/official/Reference/Core/Line-Input) -- 从打开的顺序文件读取一行到字符串变量 * [Load](/official/Reference/Core/Load) -- 将对象(通常是窗体)加载到内存但不显示 * [Lock](/official/Reference/Core/Lock)、[Unlock](/official/Reference/Core/Unlock) -- 控制其他进程对打开文件的全部或部分的访问 * [LSet](/official/Reference/Core/LSet) -- 在字符串变量中左对齐字符串,或将一个用户定义类型变量复制到另一个 * [Mid =](/official/Reference/Core/Mid-equals) -- 替换字符串变量中指定数量的字符 * [MidB =](/official/Reference/Core/MidB-equals) -- \*\*Mid =\*\*的字节定位形式 * [Module](/official/Reference/Core/Module) -- 定义模块:不可实例化的过程、常量、类型和模块级变量容器 * [Name](/official/Reference/Core/Name) -- 重命名磁盘文件、目录或文件夹 * [New](/official/Reference/Core/New) -- 创建类的新实例 * [On Error](/official/Reference/Core/On-Error) -- 启用错误处理例程并指定其位置,或禁用错误处理 * [On ... GoTo](/official/Reference/Core/On-GoTo)、[On ... GoSub](/official/Reference/Core/On-GoSub) -- 根据表达式的值分支到多个行之一 * [Open](/official/Reference/Core/Open) -- 启用对文件的输入/输出(I/O) * [Option](/official/Reference/Core/Option) -- 配置编译器选项 * [ParamArray](/official/Reference/Core/ParamArray) -- 将过程的最后一个参数声明为可变参数列表 * [Print #](/official/Reference/Core/Print) -- 向顺序文件写入显示格式的数据 * [Private](/official/Reference/Core/Private) -- 声明仅在声明模块内可访问的模块级变量 * [Property](/official/Reference/Core/Property) -- 声明构成属性体的**Get**、**Let**或**Set**过程 * [Protected](/official/Reference/Core/Protected) -- (twinBASIC) 声明在类及其派生类中可访问的类成员 * [Public](/official/Reference/Core/Public) -- 声明所有模块中所有过程都可访问的模块级变量 * [Put](/official/Reference/Core/Put) -- 将变量中的数据写入磁盘文件 * [RaiseEvent](/official/Reference/Core/RaiseEvent) -- 触发在类、窗体或文档的模块级声明的事件 * [Randomize](/official/Reference/VBA/Math/Randomize) -- 初始化随机数生成器 * [ReDim](/official/Reference/Core/ReDim) -- 重新分配动态数组的存储空间 * [Resume](/official/Reference/Core/Resume) -- 在错误处理例程完成后恢复执行 * [Return](/official/Reference/Core/Return) -- 从**GoSub**子程序返回,或(twinBASIC)带可选值退出过程 * [RSet](/official/Reference/Core/RSet) -- 在字符串变量中右对齐字符串 * [SavePicture](/official/Reference/Core/SavePicture) -- 将**Picture**或**Image**中的图形保存到文件 * [Seek](/official/Reference/Core/Seek) -- 设置使用**Open**语句打开的文件中的读/写位置 * [Select Case](/official/Reference/Core/Select-Case) -- 根据表达式的值执行多组语句中的一组 * [Set](/official/Reference/Core/Set) -- 将对象引用赋给变量或属性 * [Static](/official/Reference/Core/Static) -- 声明在调用之间保留值的过程局部变量 * [Stop](/official/Reference/Core/Stop) -- 暂停执行 * [Sub](/official/Reference/Core/Sub) -- 声明**Sub**过程的名称、参数和代码体 * [Type](/official/Reference/Core/Type) -- 定义包含一个或多个元素的用户定义数据类型 * [Unload](/official/Reference/Core/Unload) -- 从内存中移除对象(通常是窗体) * [While ... Wend](/official/Reference/Core/While-Wend) -- 在给定条件为**True**时执行一系列语句 * [With](/official/Reference/Core/With) -- 在单个对象或用户定义类型上执行一系列语句 * [Write #](/official/Reference/Core/Write) -- 向顺序文件写入原始的、带分隔符的数据(与[**Input #**](/official/Reference/Core/Input)配对使用) * [#If ... Then ... Else](/official/Reference/Core/Topic-Preprocessor)、[#Const](/official/Reference/Core/Topic-Preprocessor) -- 在编译时条件性地包含代码块的编译器指令 *** ## 已弃用 * [DefBool到DefVar](/official/Reference/Core/Deftype) -- 为名称以给定字母开头的变量设置默认数据类型;已被显式**As** *type*声明取代 --- --- url: /zh/official/Features/Language.md --- # 语言语法 twinBASIC 为 VBx 语言语法引入了大量增强,包括新数据类型、改进的类型系统和现代编程构造。 ## 主题 * [类型别名](/official/Features/Language/Alias-Types) - 类型别名,类似于 C 的 **typedef** 和 C++ 的 **using** * [数据类型](/official/Features/Language/Data-Types) - 新数据类型(**LongPtr**、**LongLong**、**Decimal**) * [接口和 CoClass](/official/Features/Language/Interfaces-CoClasses) - 原生接口和 CoClass 定义 * [继承](/official/Features/Language/Inheritance) - **Implements Via** 和 **Inherits** 关键字 * [委托](/official/Features/Language/Delegates) - 函数指针,也称为委托 * [泛型](/official/Features/Language/Generics) - 泛型类型支持 * [重载](/official/Features/Language/Overloading) - 方法重载能力 * [运算符](/official/Features/Language/Operators) - 新运算符和语法 * [字面量](/official/Features/Language/Literals) - 二进制字面量和数字分组 * [类型推断](/official/Features/Language/Type-Inference) - **As Any** 类型推断 * [指针](/official/Features/Language/Pointers) - 增强的指针功能 * [UDT 增强](/official/Features/Language/UDTs) - 用户定义类型改进 * [循环控制](/official/Features/Language/Loop-Control) - **Continue ...** 和 **Exit While** * [Return 语法](/official/Features/Language/Return) - 现代 **Return** 语句 * [内联初始化](/official/Features/Language/Inline-Initialization) - 变量初始化 * [Handler 方法](/official/Features/Language/Handlers) - **Handles** 和 **Implements** 语法 * [模块组织](/official/Features/Language/Module-Organization) - 代码放置灵活性 * [注释](/official/Features/Language/Comments) - 新的代码注释语法 --- --- url: /zh/packages/vbccr/datetime/monthview.md description: 月历视图控件(MonthView) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 月历视图控件(MonthView) 封装 SysMonthCal32 系统月历控件,用于日期选择和日历显示,支持多日期选择、多月份视图等高级功能。 ## 枚举 ### MvwViewConstants | 常量 | 值 | 说明 | |------|-----|------| | MvwViewMonth | 0 | 月视图 | | MvwViewYear | 1 | 年视图 | | MvwViewDecade | 2 | 十年视图 | | MvwViewCentury | 3 | 百年视图 | ### MvwHitResultConstants | 常量 | 值 | 说明 | |------|-----|------| | MvwHitResultNowhere | 0 | 无命中 | | MvwHitResultTitleBg | 1 | 标题背景 | | MvwHitResultTitleMonth | 2 | 标题月份 | | MvwHitResultTitleYear | 3 | 标题年份 | | MvwHitResultTitlePrevMonth | 4 | 上一个月按钮 | | MvwHitResultTitleNextMonth | 5 | 下一个月按钮 | | MvwHitResultCalendarBg | 6 | 日历背景 | | MvwHitResultCalendarDate | 7 | 日历日期 | | MvwHitResultCalendarDateMin | 8 | 日历最小日期 | | MvwHitResultCalendarDateMax | 9 | 日历最大日期 | | MvwHitResultCalendarWeekNumber | 10 | 周数 | | MvwHitResultCalendarPrevMonth | 11 | 上个月的日期 | | MvwHitResultCalendarNextMonth | 12 | 下个月的日期 | | MvwHitResultTodayLink | 13 | "今天"链接 | ### CCMousePointerConstants 参见通用枚举。 ## 属性 ### Value ```vb Property Get Value() As Date Property Let Value(ByVal Value As Date) ``` 当前选中的日期。 ### MinDate ```vb Property Get MinDate() As Date Property Let MinDate(ByVal Value As Date) ``` 最小可选日期。 ### MaxDate ```vb Property Get MaxDate() As Date Property Let MaxDate(ByVal Value As Date) ``` 最大可选日期。 ### Year ```vb Property Get Year() As Integer Property Let Year(ByVal Value As Integer) ``` 当前年份。 ### Month ```vb Property Get Month() As Integer Property Let Month(ByVal Value As Integer) ``` 当前月份(1-12)。 ### Week ```vb Property Get Week() As Integer Property Let Week(ByVal Value As Integer) ``` 当前周数。 ### Day ```vb Property Get Day() As Integer Property Let Day(ByVal Value As Integer) ``` 当前日(1-31)。 ### DayCount ```vb Property Get DayCount() As Long ``` 当前可见月份中包含的天数。只读。 ### CalendarCount ```vb Property Get CalendarCount() As Long ``` 当前显示的月份数量。只读。 ### ShowToday ```vb Property Get ShowToday() As Boolean Property Let ShowToday(ByVal Value As Boolean) ``` 是否显示"今天"日期。 ### ShowTodayCircle ```vb Property Get ShowTodayCircle() As Boolean Property Let ShowTodayCircle(ByVal Value As Boolean) ``` 是否用圆圈标记今天。 ### ShowWeekNumbers ```vb Property Get ShowWeekNumbers() As Boolean Property Let ShowWeekNumbers(ByVal Value As Boolean) ``` 是否显示周数。 ### ShowTrailingDates ```vb Property Get ShowTrailingDates() As Boolean Property Let ShowTrailingDates(ByVal Value As Boolean) ``` 是否显示上/下个月的拖尾日期。 ### ScrollRate ```vb Property Get ScrollRate() As Long Property Let ScrollRate(ByVal Value As Long) ``` 滚动速率。 ### StartOfWeek ```vb Property Get StartOfWeek() As Integer Property Let StartOfWeek(ByVal Value As Integer) ``` 一周的开始日(0=周日,1=周一...6=周六)。 ### MultiSelect ```vb Property Get MultiSelect() As Boolean Property Let MultiSelect(ByVal Value As Boolean) ``` 是否允许多日期选择。 ### DayState ```vb Property Get DayState() As String Property Let DayState(ByVal Value As String) ``` 日期状态位图字符串,控制日期的粗体显示。 ### MaxSelCount ```vb Property Get MaxSelCount() As Long Property Let MaxSelCount(ByVal Value As Long) ``` 多选时的最大可选天数。 ### MonthColumns ```vb Property Get MonthColumns() As Long Property Let MonthColumns(ByVal Value As Long) ``` 水平显示的月份数。 ### MonthRows ```vb Property Get MonthRows() As Long Property Let MonthRows(ByVal Value As Long) ``` 垂直显示的月份数。 ### View ```vb Property Get View() As MvwViewConstants Property Let View(ByVal Value As MvwViewConstants) ``` 日历视图模式。 ### UseShortestDayNames ```vb Property Get UseShortestDayNames() As Boolean Property Let UseShortestDayNames(ByVal Value As Boolean) ``` 是否使用最短的星期名称。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景颜色。 ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景颜色。 ### TitleBackColor ```vb Property Get TitleBackColor() As OLE_COLOR Property Let TitleBackColor(ByVal Value As OLE_COLOR) ``` 标题背景颜色。 ### TitleForeColor ```vb Property Get TitleForeColor() As OLE_COLOR Property Let TitleForeColor(ByVal Value As OLE_COLOR) ``` 标题前景颜色。 ### TrailingForeColor ```vb Property Get TrailingForeColor() As OLE_COLOR Property Let TrailingForeColor(ByVal Value As OLE_COLOR) ``` 拖尾日期的前景颜色。 ### SelStart ```vb Property Get SelStart() As Date Property Let SelStart(ByVal Value As Date) ``` 选择范围的起始日期。 ### SelEnd ```vb Property Get SelEnd() As Date Property Let SelEnd(ByVal Value As Date) ``` 选择范围的结束日期。 ### Today ```vb Property Get Today() As Date ``` 返回今天的日期。只读。 ### SystemStartOfWeek ```vb Property Get SystemStartOfWeek() As Integer ``` 返回系统设置的一周开始日。只读。 ### DayOfWeek ```vb Property Get DayOfWeek() As Integer ``` 返回 Value 对应的星期几。只读。 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 月历视图控件的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 用户控件的窗口句柄。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针样式。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 是否启用鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示方向。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` 帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "这是什么"帮助 ID。 ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` 拖拽图标。 ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` 拖拽模式。 ## 方法 ### SetSelRange ```vb Public Sub SetSelRange(ByVal StartDate As Date, ByVal EndDate As Date) ``` 设置日期选择范围。 ### ComputeControlSize ```vb Public Sub ComputeControlSize() ``` 根据当前设置重新计算控件大小。 ### GetMonthRange ```vb Public Function GetMonthRange() As String ``` 获取当前显示的月份范围。 ### HitTest ```vb Public Function HitTest(ByVal X As Single, ByVal Y As Single) As MvwHitResultConstants ``` 测试指定坐标处的命中区域。 ### Drag ```vb Public Sub Drag([ByRef Action As Variant]) ``` 开始、结束或取消拖放操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移至控件。 ### ZOrder ```vb Public Sub ZOrder([ByRef Position As Variant]) ``` 设置控件的 Z 顺序。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放操作。 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘控件。 ## 事件 ### GetDayBold ```vb Public Event GetDayBold(ByRef DayState As String) ``` 需要获取日期粗体状态时触发。 ### SelChange ```vb Public Event SelChange(ByVal StartDate As Date, ByVal EndDate As Date) ``` 选择范围发生改变时触发。 ### DateClick ```vb Public Event DateClick(ByVal DateClicked As Date) ``` 单击某个日期时触发。 ### ViewChange ```vb Public Event ViewChange() ``` 视图模式发生改变时触发。 ### ContextMenu ```vb Public Event ContextMenu(ByRef Handled As Boolean, ByVal X As Single, ByVal Y As Single) ``` 右键单击或按 Shift+F10 时触发。 ### Click ```vb Public Event Click() ``` 单击控件时触发。 ### DblClick ```vb Public Event DblClick() ``` 双击控件时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件时触发。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下按键时触发。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放按键时触发。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按键字符输入时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE 拖放完成时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放经过控件时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 拖放需要更改光标时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 拖放开始时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放完成时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE 放置目标请求数据时触发。 ## 代码示例 ```vb ' 基本日期选择 MonthView1.Value = Date ' 限制可选日期范围 MonthView1.MinDate = #1/1/2025# MonthView1.MaxDate = #12/31/2025# ' 多日期选择 MonthView1.MultiSelect = True MonthView1.MaxSelCount = 7 Call MonthView1.SetSelRange(#1/1/2025#, #1/7/2025#) ' 多月份显示 MonthView1.MonthColumns = 2 MonthView1.MonthRows = 1 ``` --- --- url: /zh/official/Features/Language/Operators.md --- # 新运算符 twinBASIC 引入了几个新运算符来增强语言能力。每个运算符的参考页面位于 [参考 → 运算符](/official/Reference/Operators)。 ## 位移运算符 [`<<`](/official/Reference/Core/LeftShift) 和 [`>>`](/official/Reference/Core/RightShift) 对数值变量执行左移和右移操作。注意超出可用大小的位移结果为 0,而不是回绕。 ## 短路条件运算符 ### OrElse 和 AndAlso 使用常规的 [`Or`](/official/Reference/Core/Or) 和 [`And`](/official/Reference/Core/And) 语句时,两边都会被计算,即使并非必要。使用短路运算符时,如果条件已由第一边确定,另一边不会被计算。因此如果你有 `If Condition1 `[`OrElse`](/official/Reference/Core/OrElse)` Condition2 Then`,如果 `Condition1` 为 `True`,则 `Condition2` 不会被计算,由它调用的任何代码也不会运行。配套的合取运算符是 [`AndAlso`](/official/Reference/Core/AndAlso)。 ### If() 运算符 短路 [`If()`](/official/Reference/Core/If) 运算符,语法与传统 [`IIf`](/official/Reference/Core/IIf) 相同。这还有一个额外好处:如果变量是相同类型,不会将它们转换为 `Variant`;即 `If(condition, Long, Long)` 中的 `Long` 变量永远不会变成 `Variant`。 ## 赋值运算符 `+= -= /= \= *= ^= &= <<= >>=` 这些等价于 `var = var (operand) (var2)`。因此 `i += 1` 等价于 `i = i + 1`。参见 [参考 → 运算符 → 复合赋值](/official/Reference/Operators#compound-assignment) 获取每个运算符的详细信息。 ## IsNot 运算符 用于测试对象等价性的 [`Is`](/official/Reference/Core/Is) 运算符的逻辑反义。例如,你不再需要写 `If (object Is Nothing) = False`,现在可以写 `If object `[`IsNot`](/official/Reference/Core/IsNot)` Nothing Then`。 ## 示例 ```vb Dim n As Long = &HFF Dim shifted As Long = n << 4 ' result: &HFF0 n += 1 ' compound assignment: n = &H100 n <<= 2 ' left-shift assignment: n = &H400 Dim obj As Object = Nothing If obj IsNot Nothing Then Debug.Print obj Dim x As Long = -5 Debug.Print If(x >= 0, x, -x) ' short-circuit If(): prints 5 ``` --- --- url: /zh/official/Reference/Operators.md --- # 运算符 twinBASIC语言内置的运算符。它们由编译器理解,不在运行时库中声明或定义。 ## 算术 * [+](/official/Reference/Core/Plus) -- 加法;**String**操作数时为连接 * [-](/official/Reference/Core/Minus) -- 减法;作为一元运算符时为取负 * [\*](/official/Reference/Core/Multiply) -- 乘法 * [/](/official/Reference/Core/Divide) -- 浮点除法 * [\\](/official/Reference/Core/IntegerDivide) -- 整数除法(截断) * [Mod](/official/Reference/Core/Mod) -- 两数相除仅返回余数 * [ ^](/official/Reference/Core/Exponent) -- 指数运算 ## 连接 * [&](/official/Reference/Core/Concat) -- 强制字符串连接,无论操作数类型如何 ## 比较 * [比较运算符](/official/Reference/Core/Comparison-Operators)(`=`、`<>`、`<`、`<=`、`>`、`>=`)-- 数值或字符串比较 * [Like](/official/Reference/Core/Like) -- 通配符/模式匹配比较 * [Is](/official/Reference/Core/Is) -- 比较两个对象引用是否相同 * [IsNot](/official/Reference/Core/IsNot) -- (twinBASIC) **Is**的逻辑反 ## 位运算 两个操作数始终被求值。布尔值被视为整数:True = -1,False = 0。 * [And](/official/Reference/Core/And) -- 按位与 * [Or](/official/Reference/Core/Or) -- 按位或 * [Not](/official/Reference/Core/Not) -- 按位取反 * [Xor](/official/Reference/Core/Xor) -- 按位异或 * [Eqv](/official/Reference/Core/Eqv) -- 按位等价 * [Imp](/official/Reference/Core/Imp) -- 按位蕴含 ## 逻辑短路 右操作数仅当左操作数不能确定结果时才被求值。 * [AndAlso](/official/Reference/Core/AndAlso) -- (twinBASIC) 短路与;仅当左操作数为**True**时才求值右操作数 * [OrElse](/official/Reference/Core/OrElse) -- (twinBASIC) 短路或;仅当左操作数为**False**时才求值右操作数 ## 位移 *(twinBASIC)* 移位为*逻辑移位* --- 空出位用零填充,超出操作数宽度的移位产生`0`而非循环。 * [<<](/official/Reference/Core/LeftShift) -- (twinBASIC) 将数值左移指定位数 * [>>](/official/Reference/Core/RightShift) -- (twinBASIC) 将数值右移指定位数 ## 对象同一性 * [Is](/official/Reference/Core/Is) -- 比较两个对象引用是否相同 * [IsNot](/official/Reference/Core/IsNot) -- (twinBASIC) **Is**的逻辑反 ## 复合赋值 *(twinBASIC)* 对于大多数算术、连接和位移运算符,twinBASIC提供了`op=`复合形式,将运算与赋值结合。`x op= y`等同于`x = x op y`,但左侧只求值一次,且是语句而非表达式。 | 运算符 | 复合形式 | 等同于 | | :----------------------------- | :------------ | :------------ | | [+](/official/Reference/Core/Plus) | **+=** | `x = x + y` | | [-](/official/Reference/Core/Minus) | **-=** | `x = x - y` | | [\*](/official/Reference/Core/Multiply) | **\*=** | `x = x * y` | | [/](/official/Reference/Core/Divide) | **/=** | `x = x / y` | | [\\](/official/Reference/Core/IntegerDivide) | **\\=** | `x = x \ y` | | [ ^](/official/Reference/Core/Exponent) | **^=** | `x = x ^ y` | | [&](/official/Reference/Core/Concat) | **&=** | `x = x & y` | | [<<](/official/Reference/Core/LeftShift) | **<<=** | `x = x << y` | | [>>](/official/Reference/Core/RightShift) | **>>=** | `x = x >> y` | [**Mod**](/official/Reference/Core/Mod)以及任何逻辑/比较运算符没有复合形式。 ## 函数指针 * [AddressOf](/official/Reference/Core/AddressOf) -- 生成指向过程的有类型函数指针 ## 运算符优先级 当表达式中出现多个运算时,各部分按固定顺序求值。算术运算符最先求值,比较运算符其次,逻辑运算符最后。括号可覆盖默认顺序。 各类别内从最高到最低优先级的顺序为: | 算术 | 比较 | 逻辑 | |:-----------------------------------------------------|:--------------------------------------|:-----------| | 指数(`^`) | 等于(`=`) | **Not** | | 一元取负(`-`) | 不等于(`<>`) | **And**、**AndAlso** | | 乘法和除法(`*`、`/`) | 小于(`<`) | **Or**、**OrElse** | | 整数除法(`\`) | 大于(`>`) | **Xor** | | 取模(`Mod`) | 小于等于(`<=`) | **Eqv** | | 加法和减法(`+`、`-`) | 大于等于(`>=`) | **Imp** | | 字符串连接(`&`) | **Like**、**Is**、**IsNot** | | | 位移(`<<`、`>>`) | | | 比较运算符具有相同的优先级,从左到右求值。乘法和除法同时出现时也从左到右求值,加法和减法同理。`&`运算符严格来说不是算术运算符,但在优先级上它排在所有算术运算符之后、所有比较运算符之前。 复合赋值运算符(`+=`、`-=`、`*=`、`/=`、`^=`、`&=`、`<<=`、`>>=`)仅出现在语句级别 --- 它们不属于任何表达式,因此不参与优先级排序。 --- --- url: /zh/official/IDE/Menu/Run.md --- # 运行菜单 ![Run Menu](Images/Menu_Run.png "Run Menu") * 启动 F5 * 中断 CTRL + BREAK * 结束 --- --- url: /zh/official/Features/Advanced/API-Declarations.md --- # API 和方法声明的增强 twinBASIC 为 API 和方法声明提供了多项增强,使与外部库的交互更加便捷。 ## DeclareWide `DeclareWide` 关键字替代 `Declare`,用于禁用 API 调用的 ANSI<->Unicode 转换。这同时适用于参数本身和 UDT 内部的 String 参数。例如,以下两种声明在功能上是等效的: ```vb Public Declare PtrSafe Sub FooW Lib "some.dll" (ByVal bar As LongPtr) Public DeclareWide PtrSafe Sub Foo Lib "some.dll" Alias "FooW" (ByVal bar As String) ``` 两者都表示完全的 Unicode 操作,但后者允许直接使用 `String` 数据类型,而无需使用 `StrPtr` 来阻止转换。 ::: warning 这**不会**改变底层数据类型——`String` 类型是 `BSTR`,不是 `LPWSTR`,因此如果 API 返回预先分配的 `LPWSTR`(而不是填充你创建的缓冲区),它将不会提供有效的 `String` 类型。这种情况出现在 API 参数为 `[out] LPWSTR *arg` 时。 ::: ## CDecl 支持 cdecl 调用约定同时支持 API 声明和代码中的方法。这包括标准 DLL 中的 DLL 导出。 ### 示例 ```vb Private DeclareWide PtrSafe Function _wtoi64 CDecl Lib "msvcrt" (ByVal psz As String) As LongLong` ``` ```vb [ DllExport ] Public Function MyExportedFunction CDecl(foo As Long, Bar As Long) As Long ``` ### CDecl 回调 也支持使用 `CDecl` 的回调。你需要传递一个在原型定义中包含 `CDecl` 的委托。以下是一个使用 [`qsort` 函数](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-wsprintfw)执行快速排序的示例代码: ```vb Private Delegate Function LongComparator CDecl ( _ ByRef a As Long, _ ByRef b As Long _ ) As Long Private Declare PtrSafe Sub qsort CDecl _ Lib "msvcrt" ( _ ByRef pFirst As Any, _ ByVal lNumber As Long, _ ByVal lSize As Long, _ ByVal pfnComparator As LongComparator _ ) Public Sub CallMe() Dim z() As Long Dim i As Long Dim s As String ReDim z(10) As Long For i = 0 To UBound(z) z(i) = Int(Rnd * 1000) Next i qsort z(0), UBound(z) + 1, LenB(z(0)), AddressOf Comparator For i = 0 To UBound(z) s = s & CStr(z(i)) & vbNewLine Next i MsgBox s End Sub Private Function Comparator CDecl( _ ByRef a As Long, _ ByRef b As Long _ ) As Long Comparator = a - b End Function ``` ## 支持按值传递用户定义类型 简单 UDT 现在可以在 API、接口和任何其他方法中按值传递。在 VBx 中,以前需要使用变通方法,如分别传递每个参数。 ```vb Public Declare PtrSafe Function LBItemFromPt Lib "comctl32" (ByVal hLB As LongPtr, ByVal PXY As POINT, ByVal bAutoScroll As BOOL) As Long Interface IDropTarget Extends stdole.IUnknown Sub DragEnter(ByVal pDataObject As IDataObject, ByVal grfKeyState As KeyStateMouse, ByVal pt As POINT, pdwEffect As DROPEFFECTS) ``` 等等。对于此功能,"简单"UDT 是指没有引用计数或在后台管理的成员的 UDT,因此不能包含 interface、String 或 Variant 类型。它们可以包含其他 UDT。 ## 可变参数支持 随着 `cdecl` 调用约定的完全支持,twinBASIC 也能处理可变参数函数。在 C/C++ 中,这些函数的参数中包含省略号 `...`。这在 tB 中表示为 `{ByRef | ByVal} ParamArray ... As Any()`。注意 `ByRef` 或 `ByVal` 必须显式标记;不允许隐式 `ByRef`。 ### 使用 wsprintfW 的示例 使用[给定的 C/C++ 原型](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-wsprintfw): ```c int WINAPIV wsprintfW( /* [out] */ LPWSTR unnamedParam1, /* [in] */ LPCWSTR unnamedParam2, /* ... */ ); ``` twinBASIC 声明和使用它的函数可以这样编写: ```vb Private DeclareWide PtrSafe Function wsprintfW CDecl _ Lib "user32" ( _ ByVal buf As String, _ ByVal format As String, _ ByVal ParamArray args As Any() _ ) As Long Private Sub Test() Dim buf As String = Space(1024) wsprintfW(buf, "%d %d %d", 1, 2, 3) MsgBox buf End Sub ``` ### va\_list 参数 对于参数中包含 `va_list` 类型的函数,ParamArray 声明必须为 `ByRef`。 ## PreserveSig `[PreserveSig]` 属性前面已针对 COM 方法描述过,但它也可以用于 API 声明。对于 API,默认值为 `True`。因此,你可以指定 `False` 来将最后一个参数重写为返回值。 ### 示例 ```vb Public Declare PtrSafe Function SHGetDesktopFolder Lib "shell32" (ppshf As IShellFolder) As Long ``` 可以重写为: ```vb [PreserveSig(False)] Public Declare PtrSafe Function SHGetDesktopFolder Lib "shell32" () As IShellFolder` ``` --- --- url: /zh/official/Features/Language/Pointers.md --- # 增强的指针功能 twinBASIC 为指针操作提供了多项增强。 ## ByVal Nothing 虽然不是严格意义上的新语法,twinBASIC 还添加了对 `ByVal Nothing` 的支持,用于覆盖 `ByRef <interface>` 参数并传递空指针。 ## ByVal vbNullPtr 允许向 API/接口的 UDT 成员传递空指针。VBx 中的等价行为是将它们声明为 `As Any` 然后在调用点传递 `ByVal 0`。 ### 示例 ```vb Type Foo bar As Long End Type Public Declare PtrSafe Function MyFunc Lib "MyDLL" (pFoo As Foo) As Long Private Sub CallMyFunc() Dim ret As Long = MyFunc(ByVal vbNullPtr) End Sub ``` ## 用指针替代 UDT 更一般地,在 API 和本地方法中,任何接受用户定义类型的参数都可以改为传递 `ByVal LongPtr`,并使用新的特殊常量 `vbNullPtr` 表示空指针: ```vb Public Declare PtrSafe Function CreateFileW Lib "kernel32" (ByVal lpFileName As LongPtr, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, lpSecurityAttributes As SECURITY_ATTRIBUTES, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As LongPtr) As LongPtr hFile = CreateFileW(StrPtr("name"), 0, 0, ByVal vbNullPtr, '...') '---or--- Dim pSec As SECURITY_ATTRIBUTES Dim lPtr As LongPtr = VarPtr(pSec) hFile = CreateFileW(StrPtr("name"), 0, 0, ByVal lPtr, '...) ``` ## CType(Of `<type>`) `CType(Of <type>)` 运算符指定将一个类型显式转换为另一个类型的意图。这可以用于将 `LongPtr`(或 32 位上的 `Long`/64 位上的 `LongLong`)转换为自定义用户定义类型,是否制作副本取决于用法。这不仅允许直接转换而无需 `CopyMemory` 调用,还可以设置仅由指针表示的 UDT 的成员,无需来回复制内存。 ### 示例 考虑以下 UDT: ```vb Private Type foo a As Long b As Long pfizz As LongPtr 'A pointer to a variable of type fizz End Type Private Type bar pfoo As LongPtr 'A pointer to a variable of type foo End Type Private Type fizz c As Long End Type ``` 以下代码示例用于操作指针: ```vb Sub call1() Dim f As foo test1 VarPtr(f) Debug.Print f.a, f.b End Sub Sub test1(ByVal ptr As LongPtr) With CType(Of foo)(ptr) .a = 1 .b = 2 End With End Sub ``` 这将打印 `1 2`。 ```vb Sub call2() Dim f As foo, b As bar b.pfoo = VarPtr(f) test2 b Debug.Print f.a, f.b End Sub Sub test2(b As bar) With CType(Of foo)(b.pfoo) .a = 3 .b = 4 End With End Sub ``` 这将打印 `3 4`。 ```vb Sub call3() Dim f As foo, b As bar, z As fizz f.pfizz = VarPtr(z) b.pfoo = VarPtr(f) test3 b Debug.Print z.c End Sub Sub test3(b As bar) CType(Of fizz)(CType(Of foo)(b.pfoo).pfizz).c = 4 End Sub ``` 这将打印 `4`。也允许独立使用和嵌套。虽然这里的示例仅使用本地代码,但这对 API 特别有用,因为你被迫大量使用指针。 ## Len/LenB(Of `<type>`) 支持 经典的 `Len` 和 `LenB` 函数现在可以直接获取类型(包括内置类型和用户定义类型)的长度/大小,无需声明该类型的变量。例如,要知道指针大小,可以使用 `LenB(Of LongPtr)`。 ## AddressOf 的改进 `AddressOf` 现在可以用于类/窗体/UserControl 的成员,包括通过指定实例从类外部使用。也不需要 `FARPROC` 类型的函数,你可以像 `Ptr = AddressOf Func` 这样使用。因此如果你有类 `CFoo` 和成员函数 `bar`,以下写法是有效的: ```vb Dim foo1 As New CFoo Dim lpfn As LongPtr = AddressOf foo1.bar ``` --- --- url: /zh/packages/vbccr/system/framew.md description: 增强框架控件(FrameW) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 增强框架控件(FrameW) 提供支持视觉样式、透明背景和图片显示的容器框架控件,可作为其他控件的容器。 ## 枚举 无专有公共枚举。使用以下通用枚举:CCAppearanceConstants、CCLeftRightAlignmentConstants、CCMousePointerConstants、CCRightToLeftModeConstants、OLEDropModeConstants。 ## 属性 ### Name ```vb Property Get Name() As String ``` 返回控件的名称。 ### Tag ```vb Property Get/Let Tag() As String ``` 返回/设置控件的标记值。 ### Parent ```vb Property Get Parent() As Object ``` 返回控件的父对象。 ### Container ```vb Property Get/Set Container() As Object ``` 返回/设置控件的容器。 ### Left ```vb Property Get/Let Left() As Single ``` 返回/设置控件左边缘的位置。 ### Top ```vb Property Get/Let Top() As Single ``` 返回/设置控件上边缘的位置。 ### Width ```vb Property Get/Let Width() As Single ``` 返回/设置控件的宽度。 ### Height ```vb Property Get/Let Height() As Single ``` 返回/设置控件的高度。 ### Visible ```vb Property Get/Let Visible() As Boolean ``` 返回/设置控件是否可见。 ### ToolTipText ```vb Property Get/Let ToolTipText() As String ``` 返回/设置控件的工具提示文本。 ### WhatsThisHelpID ```vb Property Get/Let WhatsThisHelpID() As Long ``` 返回/设置控件的"这是什么"帮助 ID。 ### DragIcon ```vb Property Get/Let/Set DragIcon() As IPictureDisp ``` 返回/设置拖动操作时显示的图标。 ### DragMode ```vb Property Get/Let DragMode() As Integer ``` 返回/设置拖动模式(手动或自动)。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 返回控件的窗口句柄。 ### Font ```vb Property Get/Let/Set Font() As StdFont ``` 返回/设置控件使用的字体。 ### VisualStyles ```vb Property Get/Let VisualStyles() As Boolean ``` 返回/设置是否启用视觉样式。 ### Appearance ```vb Property Get/Let Appearance() As CCAppearanceConstants ``` 返回/设置控件的视觉外观。参见通用枚举。 ### BackColor ```vb Property Get/Let BackColor() As OLE_COLOR ``` 返回/设置控件的背景色。 ### ForeColor ```vb Property Get/Let ForeColor() As OLE_COLOR ``` 返回/设置控件的前景色(标题文字颜色)。 ### Enabled ```vb Property Get/Let Enabled() As Boolean ``` 返回/设置控件是否可用。 ### OLEDropMode ```vb Property Get/Let OLEDropMode() As OLEDropModeConstants ``` 返回/设置 OLE 放置模式。参见通用枚举。 ### MousePointer ```vb Property Get/Let MousePointer() As CCMousePointerConstants ``` 返回/设置鼠标指针类型。参见通用枚举。 ### MouseIcon 无此属性。框架控件不支持自定义鼠标图标。 ### MouseTrack ```vb Property Get/Let MouseTrack() As Boolean ``` 返回/设置是否启用鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get/Let RightToLeft() As Boolean ``` 返回/设置是否启用从右到左布局。 ### RightToLeftMode ```vb Property Get/Let RightToLeftMode() As CCRightToLeftModeConstants ``` 返回/设置从右到左模式。参见通用枚举。 ### BorderStyle ```vb Property Get/Let BorderStyle() As Integer ``` 返回/设置控件的边框样式。值:0 (vbBSNone) 无边框,1 (vbFixedSingle) 固定单线边框。 ### Caption ```vb Property Get/Let Caption() As String ``` 返回/设置框架标题文本。 ### UseMnemonic ```vb Property Get/Let UseMnemonic() As Boolean ``` 返回/设置标题中的 & 符号是否作为访问键。 ### Alignment ```vb Property Get/Let Alignment() As VBRUN.AlignmentConstants ``` 返回/设置标题的对齐方式。 ### Transparent ```vb Property Get/Let Transparent() As Boolean ``` 返回/设置控件是否透明。 ### Picture ```vb Property Get/Let/Set Picture() As IPictureDisp ``` 返回/设置框架中显示的图片。 ### PictureAlignment ```vb Property Get/Let PictureAlignment() As CCLeftRightAlignmentConstants ``` 返回/设置图片的对齐方式。参见通用枚举。 ### ContainedControls ```vb Property Get ContainedControls() As VBRUN.ContainedControls ``` 返回框架包含的控件集合。只读。 ## 方法 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖动操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置控件在其层级中的 Z 顺序位置。 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘控件。 ## 事件 ### Click ```vb Public Event Click() ``` 单击控件时发生。 ### DblClick ```vb Public Event DblClick() ``` 双击控件时发生。 ### Resize ```vb Public Event Resize() ``` 控件大小改变时发生。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时发生。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时发生。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时发生。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件时发生。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件时发生。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放操作完成或取消后,在源控件上发生。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 数据通过 OLE 拖放操作放置到控件上时发生。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放操作期间鼠标移过控件时发生。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 拖放操作期间需要更改鼠标光标时,在源控件上发生。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` 放置目标请求数据时,在源控件上发生。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 拖放操作启动时发生。 ## 代码示例 ### 基本用法 ```vb Private Sub Form_Load() With FrameW1 .Caption = "选项设置" .BorderStyle = vbFixedSingle .UseMnemonic = True .Alignment = vbLeftJustify .VisualStyles = True End With End Sub Private Sub FrameW1_Resize() Debug.Print "框架尺寸: " & FrameW1.Width & " x " & FrameW1.Height End Sub ``` --- --- url: /zh/official/IDE/Diagnostics.md --- # 诊断 ![诊断](/assets/Diagnostics.D_TiNJxY.png) ![诊断开关](/assets/Diagnostics_Toggles.DBEs0SQw.png) ![诊断汇总](/assets/Diagnostics_Totals.D0b1V0ny.png) ## 分类 * 🟥 错误 * 🟨 警告 * 🟩 提示 * 🟦 信息 --- --- url: /zh/official/Features/Advanced/Assembly.md --- # Emit() 和 Naked 函数 可以使用 tB 的 `Emit()` 函数将原始字节码插入二进制文件中。为支持此功能,函数可以标记为 `Naked` 以移除隐藏的 tB 代码。 ## 示例 例如,以下是 InterlockedIncrement 编译器内联函数的实现,它替代了 Microsoft C/C++ 中的 API(将 `Addend` 加一并返回结果,作为原子操作,这是普通代码无法保证的): ```vb Public Function InlineInterlockedIncrement CDecl Naked(Addend As Long) As Long #If Win64 Then Emit(&Hb8, &H01, &H00, &H00, &H00) ' mov eax,0x1 Emit(&Hf0, &H0f, &Hc1, &H41, &H00) ' lock xadd DWORD PTR [rcx+0x4],eax Emit(&Hff, &Hc0) ' inc eax Emit(&Hc3) ' ret #Else Emit(&H8b, &H4c, &H24, &H04) ' mov ecx, DWORD PTR _Addend$[esp-4] Emit(&Hb8, &H01, &H00, &H00, &H00) ' mov eax, 1 Emit(&Hf0, &H0f, &Hc1, &H01) ' lock xadd DWORD PTR [ecx], eax Emit(&H40) ' inc eax Emit(&Hc3) ' ret 0 #End If End Function ``` (注意:`CDecl` 调用约定是可选的;你可以使用 `_stdcall` 编写 x86 汇编,只需省略该标记即可。) --- --- url: /zh.md --- *** # 中文开发文档 ::: info 特别说明 本站不是Twinbasic的官方网站,只是因为官方网站无法访问而创立的分享网站。 如果需要访问源站,请点击 <https://twinbasic.com> Here is for the convenience of Chinese developers only. English users, please go to the official documentation site.<https://docs.twinbasic.com> ::: ## 核心特性 ✨ ### 完美的兼容性 🤝 * 与现有的 VB6/VBA 代码库 100% 向后兼容 * 完全基于 COM 技术,与经典版本的 Visual Basic 保持一致 * 模拟了所有已知的 VB6 特性和行为 ### 现代化的开发环境 💻 * 轻量级、现代化的专用 IDE * 基于 Monaco 的代码编辑器 * 支持深色和浅色主题 * 代码折叠功能 * 实时代码提示 * 语法高亮 * 实时项目错误诊断 ### 强大的编译器特性 🔧 * 支持 32 位和 64 位原生编译 * 完整的 Unicode 支持 * 生成无需运行时库的独立可执行文件 * 多线程编译过程,性能优异 * 计划支持 Mac、Linux 和 Android 平台 ### 增强的语言特性 🌟 * 支持位移运算符 * 类实例 AddressOf * 继承支持 * 内联汇编 * 过程重载 * 多线程语法(即将推出) * 泛型支持(类似 VB.NET 但更灵活) * 新的数据类型:LongLong、LongPtr、Decimal * 新的运算符:AndAlso、OrElse、<<、>> * 新的赋值运算符:+=、-=、\*=等 ### 内置调试器 🔍 * 支持多线程调试 * 调用堆栈窗口 * 变量窗口 * 监视窗口 * 调试控制台 ### 新的内置控件 🎮 * FlexGrid 支持 * QRCode 生成器 * 更多自定义控件支持 ## 包管理功能 📦 * 内置包服务器 * 支持 TWINPACK 包格式 * 便捷的包导入和更新机制 ## 为什么选择 twinBasic? 🤔 * 无缝升级现有 VB6/VBA 项目 * 现代化的开发体验 * 活跃的社区支持 * 持续更新和改进 * 无需运行时依赖 * 专业的技术支持 ## 参与社区 👥 * 加入 Discord 社区交流 <https://discord.gg/UaW9GgKKuE> * 关注官方更新 * 参与 GitHub 问题追踪 * 成为 VIP Gold 会员获取更多支持 * 点击链接加入群聊【TwinBasic开发交流】:[788160802](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027\&k=c9Pkw_KrA0V0VYNhHq1bQ3ury6s85ZmM\&authKey=QJ4ZvpFfXPivXHgvfpcnbPg%2F99jOQOqvHArXoPz5VIvFX%2Bn%2BV0CBf8uQf%2F14aLrn\&noverify=0\&group_code=788160802) > 注意:twinBasic 仍在积极开发中,每日更新是常态。建议关注官方渠道获取最新动态。 --- --- url: /zh/official/Tutorials/CEF/Re-entrancy.md --- # 重入性 Chromium Embedded Framework在*独立进程*中运行浏览器和渲染器,BASIC和页面之间跨进程IPC。该模型与进程内API根本不同,它对宿主代码施加了特定的规则:当BASIC线程上正在执行CEF回调时,浏览器/渲染器进程正在等待其返回——在该等待期间回调到[**CefBrowser**](/official/Reference/CEF/CefBrowser/)控件可能导致死锁。 在大多数情况下你不需要考虑这些。控件通过投递消息将每个事件提升到BASIC消息循环,因此在响应CEF回调而运行的处理程序在你代码运行之前已经将控制权返回给浏览器进程。规则仍然适用的唯一地方是[**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun)——*同步*JavaScript桥。 ## 控件如何保护你 当浏览器或渲染器进程引发需要出现在BASIC中的CEF回调时,控件: 1. 将回调的参数捕获到 `Type` 实例中。 2. 调用 `PostMessageW` 将自定义消息推送到主线程的消息队列。 3. 立即返回——浏览器进程解除阻塞。 4. 稍后,当窗体的消息循环接收到投递的消息时,控件在BASIC端引发事件。 处理程序在原始CEF回调*之外*运行。到它执行时,浏览器进程已继续进行;处理程序可以自由调用任何[**CefBrowser**](/official/Reference/CEF/CefBrowser/)方法或属性——[**Navigate**](/official/Reference/CEF/CefBrowser/#navigate)、[**ExecuteScript**](/official/Reference/CEF/CefBrowser/#executescript)、[**JsRunAsync**](/official/Reference/CEF/CefBrowser/#jsrunasync),甚至另一个[**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun)——不会有任何重入问题。 这涵盖了控件当前引发的所有事件: * [**Create**](/official/Reference/CEF/CefBrowser/#create)、[**Ready**](/official/Reference/CEF/CefBrowser/#ready)、[**Error**](/official/Reference/CEF/CefBrowser/#error) * [**NavigationComplete**](/official/Reference/CEF/CefBrowser/#navigationcomplete)、[**SourceChanged**](/official/Reference/CEF/CefBrowser/#sourcechanged)、[**DocumentTitleChanged**](/official/Reference/CEF/CefBrowser/#documenttitlechanged)、[**DOMContentLoaded**](/official/Reference/CEF/CefBrowser/#domcontentloaded) * [**PrintToPdfCompleted**](/official/Reference/CEF/CefBrowser/#printtopdfcompleted)、[**PrintToPdfFailed**](/official/Reference/CEF/CefBrowser/#printtopdffailed) * [**JsAsyncResult**](/official/Reference/CEF/CefBrowser/#jsasyncresult)、[**JsMessage**](/official/Reference/CEF/CefBrowser/#jsmessage) ## NavigationStarting例外 [**NavigationStarting**](/official/Reference/CEF/CefBrowser/#navigationstarting)是*无法*完全延迟的唯一事件——其 `Cancel` 参数是**ByRef**的,因此BASIC处理程序必须在浏览器进程决定是否继续导航之前设置它。控件仍使用 `SendMessageW`(同步)而非 `PostMessageW` 来传递此事件,这意味着处理程序在浏览器进程阻塞等待回答时运行。 控件为一种特定情况添加了额外的安全网:如果渲染器IPC通道恰好在**NavigationStarting**触发时正忙于连接(这在较旧CEF版本的早期页面加载期间可能发生),直接的 `SendMessageW` 会死锁——BASIC在等待渲染器;渲染器在等待BASIC。控件检测到这种情况并使用中断式机制在UI线程上分发*仅* **NavigationStarting**处理程序,而无需等待渲染器IPC。 实际后果:**NavigationStarting**处理程序应保持工作最小——读取[**Uri**](/official/Reference/CEF/CefBrowser/#navigationstarting),做出决定,设置或保留[**Cancel**](/official/Reference/CEF/CefBrowser/#navigationstarting),返回。避免从处理程序内部进行任何类型的同步往返——包括[**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun)、[**MsgBox**](/official/Reference/VBA/Interaction/MsgBox)和文件对话框。 ## JsRun——明确警告 [**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun)是同步JavaScript桥: ```vb Dim product As Long = CefBrowser1.JsRun("multiplyTheseNumbers", 5, 6) ``` 调用会阻塞BASIC线程,直到渲染器进程回复结果。在该阻塞期间,渲染器正在运行JavaScript;如果该JavaScript回调到BASIC——通过 `window.chrome.webview.postMessage(...)`,或通过到达BASIC线程的任何宿主对象调用——则没有可用线程来*接收*该调用。渲染器等待BASIC;BASIC等待渲染器。死锁。 控件的源代码在方法上直接包含此警告: > **!!!WARNING!!!** 使用此同步函数时注意不要引入重入,否则可能导致UI冻结。 安全经验法则: * 使用[**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun)处理**纯**JavaScript函数——接受输入、计算并返回值的函数。没有 `postMessage`,没有宿主对象调用,没有 `await` 任何涉及宿主的内容。 * 其他情况使用[**JsRunAsync**](/official/Reference/CEF/CefBrowser/#jsrunasync)——JavaScript端可能在调用期间需要与BASIC通信的任何地方。 ```vb ' Safe — pure JavaScript: takes two numbers, returns one number. Dim html As String = CefBrowser1.JsRun("renderMarkdownToHtml", source) ' Prefer JsRunAsync when the JS could call back into BASIC. CefBrowser1.JsRunAsync "uploadAndReturnUrl", filePath ' ... result arrives later via JsAsyncResult event. ``` ## 为什么此模型比WebView2的更简单 [**WebView2**](/official/Reference/WebView2/WebView2/)支持 `AddObject`——发布JavaScript可以直接调用的BASIC COM对象。该功能有自己的重入问题([**UseDeferredInvoke**](/official/Reference/WebView2/WebView2/#addobject)),因为页面发起的宿主对象调用必须到达某个地方。 CEF的宿主对象等效功能尚未暴露——参见参考的[WebView2对等](/official/Reference/CEF/#webview2-parity)部分。CEF目前提供的唯一同步BASIC↔JavaScript边界是**JsRun**,因此整个重入问题简化为"不要从**JsRun**目标内部向BASIC发回消息"。 ## 另见 * [JavaScript互操作](/official/Tutorials/CEF/JavaScript-interop) —— 在[**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun)、[**JsRunAsync**](/official/Reference/CEF/CefBrowser/#jsrunasync)和消息桥之间选择的实用模式。 * [CefBrowser参考](/official/Reference/CEF/CefBrowser/) —— 每个属性、方法和事件。 * [WebView2重入性教程](/official/Tutorials/WebView2/Re-entrancy) —— [**WebView2**](/official/Reference/WebView2/WebView2/)控件的并行情况,包括CEF尚未具有的**AddObject**权衡。 --- --- url: /zh/official/Tutorials/WebView2/Re-entrancy.md --- # 重入性 WebView2 API对不允许从其事件中重入非常严格(参见WebView2应用的线程模型)。这意味着当我们处理 `NavigationCompleted` 等事件时,通常禁止在从该事件返回之前对WebView2对象模型执行任何操作。例如,你不能在 `NavigationCompleted` 事件本身内导航到新的URL。 为了解决这些限制,我们的WebView2实现通过窗体消息循环重新触发事件来延迟所有事件处理。这允许事件被处理后立即将执行控制权返回WebView2,然后我们的延迟事件在WebView2返回主消息循环时被触发。 由于我们实现的设计,在大多数情况下你可以忽略WebView2 API施加的重入限制。但是,如果你使用WebView2的 `AddObject` 功能(允许你将twinBASIC类实例暴露给JavaScript),则需要注意 `AddObject` 功能有两种可用模式。 ## AddObject(ObjectInstance As Object, UseDeferredInvoke As Boolean) 如果你向 `AddObject` 调用的 `UseDeferredInvoke` 参数传递 `True`,则从JavaScript进入你的类实例的调用将被视为**异步**的,因此你不能向JavaScript返回值。这非常适合事件通知。 如果你向 `AddObject` 调用的 `UseDeferredInvoke` 参数传递 `False`,则从JavaScript进入你的类实例的调用将被视为**同步**的,因此你可以返回供JavaScript使用的值,但你必须确保不会导致重入,因此绝不能回调到WebView2控件的方法和属性中。警告:如果你在不使用 `UseDeferredInvoke` 时确实回调了WebView2控件,你将导致死锁,使应用程序变得不稳定,有时关闭后仍停留在任务管理器中。 ::: info 添加两个单独的对象是完全可以接受的:一个用于异步事件处理(使用 `UseDeferredInvoke:=True`),另一个用于同步属性(使用 `UseDeferredInvoke:=False`)。 ::: --- --- url: /zh/official/Features/Language/Overloading.md --- # 重载 twinBASIC 支持两种方式的重载: ## 按参数类型重载 以下 Sub 可以同时存在于模块/类等中: ```vb Sub foo(bar As Integer) '... End Sub Sub foo(bar As Long) '... End Sub Sub foo(bar As Double) '... End Sub ``` 编译器会根据数据类型自动选择调用哪一个。 ## 按参数数量重载 除了上述方式外,你还可以添加以下内容: ```vb Sub Foo(bar1 As Integer) '... End Sub Sub Foo(bar1 As Integer, bar2 As Integer) '... End Sub ``` 编译器会根据参数的数量和/或类型自动选择调用哪一个。 --- --- url: /zh/official/Features/Language/Comments.md --- # 新注释语法 ## 块注释和行内注释 你现在可以使用 `/* */` 语法。例如,`Sub Foo(bar As Long /* out */)` 或: ```c /* Everything here is a comment until: */ ``` ### 示例 ```vb ' Single-line comment using the apostrophe Sub Greet(ByVal name As String /* in */) Debug.Print "Hello, " & name ' inline comment /* This block comment spans multiple lines. */ End Sub ``` --- --- url: /zh/official/IDE/Status-Bar.md --- # 状态栏 ![状态栏](/assets/StatusBar.DaBaZ7if.png "状态栏") 状态栏位于 IDE 窗口底部,显示后端服务健康状态、活跃许可证层级和社区资源快速访问链接的一目了然的信息。 ## 服务 ![服务不可用](Images/Services_Unavailable.png "服务不可用") ![服务不可用提示](Images/Services_Unavailable_Tooltip.png "服务不可用提示") ![服务受限](Images/Services_Limited.png "服务受限") ![服务正常](Images/Services_Operational.png "服务正常") ![服务正常提示](Images/Services_Operational_Tooltip.png "服务正常提示") 编译器:已断开/运行中 FS:已断开/运行中 LSP:已断开/运行中 * [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) 调试器:已断开/运行中 ## 许可证 * [预购](https://twinbasic.com/preorder.html) ![许可证 - 社区版](Images/Licence_CommunityEdition.png "许可证 - 社区版") * 社区版 * 专业版 * 终极版 ## 链接 ![链接](Images/Links.png "链接") * https://ko-fi.com/twinbasic * https://discord.com/invite/UaW9GgKKuE * http://x.com/waynephillipsea * https://github.com/twinbasic/twinbasic ## 状态 --- --- url: /zh/packages/vbccr/bars/statusbar.md description: 状态栏控件(StatusBar) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 状态栏控件(StatusBar) 提供可自定义的状态栏,支持面板集合、简单/正常模式、大小调整手柄和OLE拖放。不可获得焦点。 ## 枚举 ### SbrStyleConstants 状态栏样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | SbrStyleNormal | 0 | 正常模式(显示面板) | | SbrStyleSimple | 1 | 简单模式(仅显示SimpleText) | ### SbrPanelStyleConstants 面板样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | SbrPanelStyleText | 0 | 文本面板 | | SbrPanelStyleCaps | 1 | Caps Lock状态 | | SbrPanelStyleNum | 2 | Num Lock状态 | | SbrPanelStyleIns | 3 | Insert状态 | | SbrPanelStyleScrl | 4 | Scroll Lock状态 | | SbrPanelStyleTime | 5 | 时间 | | SbrPanelStyleDate | 6 | 日期 | | SbrPanelStyleKana | 7 | Kana状态 | | SbrPanelStyleHangul | 8 | Hangul状态 | | SbrPanelStyleJunja | 9 | Junja状态 | | SbrPanelStyleFinal | 10 | Final状态 | | SbrPanelStyleKanji | 11 | Kanji状态 | | SbrPanelStyleHanja | 12 | Hanja状态 | ### SbrPanelBevelConstants 面板斜面样式常量。 | 常量 | 值 | 说明 | |------|-----|------| | SbrPanelBevelFlat | 0 | 平面 | | SbrPanelBevelInset | 1 | 内凹 | | SbrPanelBevelRaised | 2 | 凸起 | ### SbrPanelAutoSizeConstants 面板自动调整大小常量。 | 常量 | 值 | 说明 | |------|-----|------| | SbrPanelAutoSizeNone | 0 | 不自动调整 | | SbrPanelAutoSizeSpring | 1 | 弹性调整(填充剩余空间) | | SbrPanelAutoSizeContent | 2 | 根据内容调整 | ### SbrPanelAlignmentConstants 面板对齐方式常量。 | 常量 | 值 | 说明 | |------|-----|------| | SbrPanelAlignmentLeft | 0 | 左对齐 | | SbrPanelAlignmentCenter | 1 | 居中对齐 | | SbrPanelAlignmentRight | 2 | 右对齐 | | SbrPanelAlignmentLeftRight | 3 | 从左到右对齐(RTL支持) | ### SbrPanelDTFormatConstants 面板日期时间格式常量。 | 常量 | 值 | 说明 | |------|-----|------| | SbrPanelDTFormatShort | 0 | 短格式 | | SbrPanelDTFormatLong | 1 | 长格式 | ## 属性 ### Name ```vb Public Property Get Name() As String ``` 返回在代码中标识对象的名称。 ### Tag ```vb Public Property Get Tag() As String Public Property Let Tag(ByVal Value As String) ``` 存储程序所需的额外数据。 ### Parent ```vb Public Property Get Parent() As Object ``` 返回对象所在的对象。 ### Container ```vb Public Property Get Container() As Object Public Property Set Container(ByVal Value As Object) ``` 返回/设置对象的容器。 ### Left ```vb Public Property Get Left() As Single Public Property Let Left(ByVal Value As Single) ``` 返回/设置对象与其容器左边缘的距离。 ### Top ```vb Public Property Get Top() As Single Public Property Let Top(ByVal Value As Single) ``` 返回/设置对象与其容器顶边缘的距离。 ### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 返回/设置对象的宽度。 ### Height ```vb Public Property Get Height() As Single Public Property Let Height(ByVal Value As Single) ``` 返回/设置对象的高度。 ### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 返回/设置对象是否可见。 ### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 返回/设置鼠标悬停时显示的提示文本。 ### WhatsThisHelpID ```vb Public Property Get WhatsThisHelpID() As Long Public Property Let WhatsThisHelpID(ByVal Value As Long) ``` 返回/设置关联的上下文帮助ID。 ### Align ```vb Public Property Get Align() As Integer Public Property Let Align(ByVal Value As Integer) ``` 返回/设置控件在其窗体上的对齐方式。 ### DragIcon ```vb Public Property Get DragIcon() As IPictureDisp Public Property Let DragIcon(ByVal Value As IPictureDisp) Public Property Set DragIcon(ByVal Value As IPictureDisp) ``` 返回/设置拖放操作中显示的图标。 ### DragMode ```vb Public Property Get DragMode() As Integer Public Property Let DragMode(ByVal Value As Integer) ``` 返回/设置拖动模式。 ### hWnd ```vb Public Property Get hWnd() As LongPtr ``` 返回控件句柄。 ### hWndUserControl ```vb Public Property Get hWndUserControl() As LongPtr ``` 返回UserControl句柄。 ### Font ```vb Public Property Get Font() As StdFont Public Property Let Font(ByVal NewFont As StdFont) Public Property Set Font(ByVal NewFont As StdFont) ``` 返回/设置字体。 ### VisualStyles ```vb Public Property Get VisualStyles() As Boolean Public Property Let VisualStyles(ByVal Value As Boolean) ``` 返回/设置是否启用视觉样式。需要comctl32.dll 6.0或更高版本。 ### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 返回/设置对象是否能响应用户事件。 ### OLEDropMode ```vb Public Property Get OLEDropMode() As OLEDropModeConstants Public Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` 返回/设置对象是否可以作为OLE放置目标。 ### MousePointer ```vb Public Property Get MousePointer() As CCMousePointerConstants Public Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 返回/设置鼠标悬停时显示的指针类型。参见通用枚举。 ### MouseIcon ```vb Public Property Get MouseIcon() As IPictureDisp Public Property Let MouseIcon(ByVal Value As IPictureDisp) Public Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Public Property Get MouseTrack() As Boolean Public Property Let MouseTrack(ByVal Value As Boolean) ``` 返回/设置是否在鼠标进入或离开控件时触发事件。 ### RightToLeft ```vb Public Property Get RightToLeft() As Boolean Public Property Let RightToLeft(ByVal Value As Boolean) ``` 返回/设置从右到左显示方向。 ### RightToLeftLayout ```vb Public Property Get RightToLeftLayout() As Boolean Public Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 返回/设置从右到左布局。 ### RightToLeftMode ```vb Public Property Get RightToLeftMode() As CCRightToLeftModeConstants Public Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 返回/设置从右到左模式。参见通用枚举。 ### Style ```vb Public Property Get Style() As SbrStyleConstants Public Property Let Style(ByVal Value As SbrStyleConstants) ``` 返回/设置状态栏样式。 ### SimpleText ```vb Public Property Get SimpleText() As String Public Property Let SimpleText(ByVal Value As String) ``` 返回/设置简单模式下显示的文本。 ### AllowSizeGrip ```vb Public Property Get AllowSizeGrip() As Boolean Public Property Let AllowSizeGrip(ByVal Value As Boolean) ``` 返回/设置是否显示大小调整手柄。 ### ShowTips ```vb Public Property Get ShowTips() As Boolean Public Property Let ShowTips(ByVal Value As Boolean) ``` 返回/设置是否显示工具提示。 ### BackColor ```vb Public Property Get BackColor() As OLE_COLOR Public Property Let BackColor(ByVal Value As OLE_COLOR) ``` 返回/设置背景色。 ### DoubleBuffer ```vb Public Property Get DoubleBuffer() As Boolean Public Property Let DoubleBuffer(ByVal Value As Boolean) ``` 返回/设置是否启用双缓冲绘制。 ### Panels ```vb Public Property Get Panels() As SbrPanels ``` 返回面板集合。 ## 方法 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘对象。 ### IncludesSizeGrip ```vb Public Function IncludesSizeGrip() As Boolean ``` 判断状态栏是否包含大小调整手柄。 ### HitTest ```vb Public Function HitTest(ByVal X As Single, ByVal Y As Single) As SbrPanel ``` 返回指定坐标处的面板。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动OLE拖放操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置Z顺序。 ## 事件 ### Click ```vb Public Event Click() ``` 用户单击控件时触发。 ### DblClick ```vb Public Event DblClick() ``` 用户双击控件时触发。 ### StyleChange ```vb Public Event StyleChange() ``` 状态栏样式改变时触发。 ### PanelClick ```vb Public Event PanelClick(ByVal Panel As SbrPanel, ByVal Button As Integer) ``` 用户单击面板时触发。 ### PanelDblClick ```vb Public Event PanelDblClick(ByVal Panel As SbrPanel, ByVal Button As Integer) ``` 用户双击面板时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件区域时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件区域时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE拖放操作完成时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE拖放操作放置时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE拖放操作悬停时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE拖放操作给反馈时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE拖放操作设置数据时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE拖放操作开始时触发。 ## 子对象 ### SbrPanel 类 状态栏面板对象。 #### SbrPanel 属性 #### Index ```vb Public Property Get Index() As Long ``` 面板在集合中的索引。 #### Key ```vb Public Property Get Key() As String Public Property Let Key(ByVal Value As String) ``` 面板的唯一标识键。 #### Tag ```vb Public Property Get Tag() As Variant Public Property Let Tag(ByVal Value As Variant) Public Property Set Tag(ByVal Value As Variant) ``` 额外数据。 #### Text ```vb Public Property Get Text() As String Public Property Let Text(ByVal Value As String) ``` 面板文本。 #### ToolTipText ```vb Public Property Get ToolTipText() As String Public Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 #### Style ```vb Public Property Get Style() As SbrPanelStyleConstants Public Property Let Style(ByVal Value As SbrPanelStyleConstants) ``` 面板样式。 #### Bevel ```vb Public Property Get Bevel() As SbrPanelBevelConstants Public Property Let Bevel(ByVal Value As SbrPanelBevelConstants) ``` 面板斜面样式。 #### AutoSize ```vb Public Property Get AutoSize() As SbrPanelAutoSizeConstants Public Property Let AutoSize(ByVal Value As SbrPanelAutoSizeConstants) ``` 面板自动调整大小方式。 #### Alignment ```vb Public Property Get Alignment() As SbrPanelAlignmentConstants Public Property Let Alignment(ByVal Value As SbrPanelAlignmentConstants) ``` 面板对齐方式。 #### DTFormat ```vb Public Property Get DTFormat() As SbrPanelDTFormatConstants Public Property Let DTFormat(ByVal Value As SbrPanelDTFormatConstants) ``` 面板日期时间格式。 #### ForeColor ```vb Public Property Get ForeColor() As OLE_COLOR Public Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 #### MinWidth ```vb Public Property Get MinWidth() As Single Public Property Let MinWidth(ByVal Value As Single) ``` 最小宽度。 #### Picture ```vb Public Property Get Picture() As IPictureDisp Public Property Let Picture(ByVal Value As IPictureDisp) Public Property Set Picture(ByVal Value As IPictureDisp) ``` 面板图片。 #### Enabled ```vb Public Property Get Enabled() As Boolean Public Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 #### Visible ```vb Public Property Get Visible() As Boolean Public Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 #### Bold ```vb Public Property Get Bold() As Boolean Public Property Let Bold(ByVal Value As Boolean) ``` 是否以粗体显示文本。 #### PictureOnRight ```vb Public Property Get PictureOnRight() As Boolean Public Property Let PictureOnRight(ByVal Value As Boolean) ``` 图片是否显示在右侧。 #### Left ```vb Public Property Get Left() As Single ``` 面板左边距(只读)。 #### Width ```vb Public Property Get Width() As Single Public Property Let Width(ByVal Value As Single) ``` 面板宽度。 ### SbrPanels 类 状态栏面板集合。 #### SbrPanels 成员 #### NewEnum ```vb Public Function NewEnum() As IEnumVARIANT ``` 枚举器(隐藏)。 #### Add ```vb Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Text As String, Optional ByVal Style As SbrPanelStyleConstants) As SbrPanel ``` 添加面板。 #### Item ```vb Public Property Get Item(ByVal Index As Variant) As SbrPanel ``` 获取面板(默认成员)。 #### Exists ```vb Public Function Exists(ByVal Index As Variant) As Boolean ``` 检查面板是否存在。 #### Count ```vb Public Property Get Count() As Long ``` 面板数量。 #### Clear ```vb Public Sub Clear() ``` 清除所有面板。 #### Remove ```vb Public Sub Remove(ByVal Index As Variant) ``` 移除面板。 ### SbrPanelProperties 类 面板内部属性对象。 #### SbrPanelProperties 属性 #### ForeColor ```vb Public Property Get ForeColor() As OLE_COLOR Public Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 ## 代码示例 ### 基本用法 ```vb ' 添加状态栏面板 With StatusBar1.Panels .Add , "Status", "就绪", sbrText .Add , "Caps", , sbrCaps .Add , "Time", , sbrTime End With ' 自定义面板样式 With StatusBar1.Panels(1) .AutoSize = sbrSpring .Bevel = sbrInset End With ' 切换到简单模式 StatusBar1.Style = sbrSimple StatusBar1.SimpleText = "正在加载数据..." ' 处理面板点击 Private Sub StatusBar1_PanelClick(ByVal Panel As SbrPanel, ByVal Button As Integer) Debug.Print "点击面板: " & Panel.Key End Sub ``` --- --- url: /zh/res/pic.md --- # 资源文件:图片使用 这里介绍如何在 twinbasic 中使用资源文件来存储图片,并直接从内存中加载为图片类型数据。 > 支持PNG图片直接使用 ## 资源文件的存储 在twinbasic 中,资源文件可以使用 `LoadResData` 函数得到原始二进制数据,如图 ![原始二进制](/images/res/bin.jpg) 【群主】 2025/9/7 10:37:50 这样 【群主】 2025/9/7 10:37:56 可以得到任何文件 ## 把二进制内容转为图片对象 ```vb Dim b() As Byte b = LoadResData("car3.png", "PICTURE") Set Picture1.Picture = Global.LoadPicture(b) Picture1.Refresh() ``` 或者,一句话使用 ```vb Set Picture1.Picture = Global.LoadPicture(LoadResData("car1.bmp", "ICON")) ``` 效果 ![效果](/images/res/pic.jpg) 【群主】 2025/9/7 10:51:30 你可以存储任意图片了 【潜水】群友 2025/9/7 10:51:44 编译的时候,直接跟EXE结合到一起,对吧,不用再带着图片到处跑了 【群主】 2025/9/7 10:51:52 是的 【群主】 2025/9/7 10:51:58 资源文件会自动内置的 【潜水】群友 2025/9/7 10:52:10 不错,不错,光是这个功能,就能吊打VB6 【群主】 2025/9/7 10:54:08 嗯, vb6 一样的,,可以使用 res 资源文件,也是内置的 【群主】 2025/9/7 10:54:19 只不过 vb6 不能直接支持 png ,tb 可以 【群主】 2025/9/7 10:56:46 而且 tb 的资源管理可以非常好的用 目录分类,,vb 的虽然也可以分类,但是每次都要自己重写 目录名称 --- --- url: /zh/official/Features/Language/Literals.md --- # 新字面量表示法 twinBASIC 为编写数字字面量提供了新选项。 ## 二进制字面量 除了 `&H` 十六进制字面量和 `&O` 八进制表示法外,twinBASIC 还提供了 `&B` 二进制表示法。例如,`Dim b As Long = &B010110` 是有效语法,b = 22。 ## 数字分组 `&H`、`&O` 和 `&B` 字面量都可以使用下划线进行分组,例如按二进制字节分组一个 `Long`:`&B10110101_10100011_10000011_01101110`,或将 `LongLong` 分为两个 `Long` 组:`&H01234567_89ABCDEF`。 ## 示例 ```vb Dim flags As Long = &B1010 ' 10 in decimal Dim perms As Long = &O17 ' 15 in decimal Dim colour As Long = &HFF ' 255 in decimal Dim mask As Long = &B10110101_10100011 ' grouped binary bytes Dim wide As LongLong = &H01234567_89ABCDEF ' grouped hex halves ``` --- --- url: /zh/packages/vbccr/lists/fontcombo.md description: 字体组合框控件(FontCombo) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 字体组合框控件(FontCombo) 提供带最近使用列表的字体选择组合框控件,可枚举系统字体并按类型和间距过滤。 ## 枚举 ### FtcStyleConstants | 常量 | 值 | 说明 | |------|-----|------| | FtcStyleDropDownCombo | 0 | 下拉组合框(可输入) | | FtcStyleSimpleCombo | 1 | 简单组合框(列表始终可见) | | FtcStyleDropDownList | 2 | 下拉列表(仅选择) | ### FtcFontTypeConstants | 常量 | 值 | 说明 | |------|-----|------| | FtcFontTypeTrueType | 0 | 仅 TrueType 字体 | | FtcFontTypeBitmap | 1 | 仅位图字体 | | FtcFontTypeBitmapTrueType | 2 | 位图和 TrueType 字体 | ### FtcFontPitchConstants | 常量 | 值 | 说明 | |------|-----|------| | FtcFontPitchAll | 0 | 所有间距 | | FtcFontPitchFixed | 1 | 固定间距 | | FtcFontPitchVariable | 2 | 可变间距 | ## 属性 ### Name ```vb Property Get Name() As String ``` 返回控件的名称。 ### Tag ```vb Property Get/Let Tag() As String ``` 返回/设置控件的标记值。 ### Parent ```vb Property Get Parent() As Object ``` 返回控件的父对象。 ### Container ```vb Property Get/Set Container() As Object ``` 返回/设置控件的容器。 ### Left ```vb Property Get/Let Left() As Single ``` 返回/设置控件左边缘的位置。 ### Top ```vb Property Get/Let Top() As Single ``` 返回/设置控件上边缘的位置。 ### Width ```vb Property Get/Let Width() As Single ``` 返回/设置控件的宽度。 ### Height ```vb Property Get/Let Height() As Single ``` 返回/设置控件的高度。 ### Visible ```vb Property Get/Let Visible() As Boolean ``` 返回/设置控件是否可见。 ### ToolTipText ```vb Property Get/Let ToolTipText() As String ``` 返回/设置控件的工具提示文本。 ### HelpContextID ```vb Property Get/Let HelpContextID() As Long ``` 返回/设置控件的帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get/Let WhatsThisHelpID() As Long ``` 返回/设置控件的"这是什么"帮助 ID。 ### DragIcon ```vb Property Get/Let/Set DragIcon() As IPictureDisp ``` 返回/设置拖动操作时显示的图标。 ### DragMode ```vb Property Get/Let DragMode() As Integer ``` 返回/设置拖动模式(手动或自动)。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` 返回组合框的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 返回 UserControl 的窗口句柄。 ### hWndEdit ```vb Property Get hWndEdit() As LongPtr ``` 返回编辑框部分的窗口句柄。 ### hWndList ```vb Property Get hWndList() As LongPtr ``` 返回列表部分的窗口句柄。 ### Font ```vb Property Get/Let/Set Font() As StdFont ``` 返回/设置控件使用的字体。 ### VisualStyles ```vb Property Get/Let VisualStyles() As Boolean ``` 返回/设置是否启用视觉样式。 ### BackColor ```vb Property Get/Let BackColor() As OLE_COLOR ``` 返回/设置控件的背景色。 ### ForeColor ```vb Property Get/Let ForeColor() As OLE_COLOR ``` 返回/设置控件的前景色。 ### Enabled ```vb Property Get/Let Enabled() As Boolean ``` 返回/设置控件是否可用。 ### OLEDragMode ```vb Property Get/Let OLEDragMode() As VBRUN.OLEDragConstants ``` 返回/设置 OLE 拖动模式。 ### OLEDropMode ```vb Property Get/Let OLEDropMode() As OLEDropModeConstants ``` 返回/设置 OLE 放置模式。参见通用枚举。 ### MousePointer ```vb Property Get/Let MousePointer() As CCMousePointerConstants ``` 返回/设置鼠标指针类型。参见通用枚举。 ### MouseIcon ```vb Property Get/Let/Set MouseIcon() As IPictureDisp ``` 返回/设置自定义鼠标图标。 ### MouseTrack ```vb Property Get/Let MouseTrack() As Boolean ``` 返回/设置是否启用鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get/Let RightToLeft() As Boolean ``` 返回/设置是否启用从右到左布局。 ### RightToLeftMode ```vb Property Get/Let RightToLeftMode() As CCRightToLeftModeConstants ``` 返回/设置从右到左模式。参见通用枚举。 ### BuddyControl ```vb Property Get/Set/Let BuddyControl() As Variant ``` 返回/设置关联的伙伴控件,当选择字体时通知伙伴控件更新。 ### Style ```vb Property Get/Let Style() As FtcStyleConstants ``` 返回/设置组合框的样式。 ### FontType ```vb Property Get/Let FontType() As FtcFontTypeConstants ``` 返回/设置显示的字体类型过滤。 ### FontPitch ```vb Property Get/Let FontPitch() As FtcFontPitchConstants ``` 返回/设置显示的字体间距过滤。 ### Locked ```vb Property Get/Let Locked() As Boolean ``` 返回/设置控件是否锁定(禁止编辑和选择)。 ### Text ```vb Property Get/Let Text() As String ``` 返回/设置编辑框中的文本。 ### Default ```vb Property Get/Let Default() As String ``` 返回/设置默认字体名称。 ### ExtendedUI ```vb Property Get/Let ExtendedUI() As Boolean ``` 返回/设置是否使用扩展用户界面。 ### MaxDropDownItems ```vb Property Get/Let MaxDropDownItems() As Integer ``` 返回/设置下拉列表中可见的最大项目数。 ### IntegralHeight ```vb Property Get/Let IntegralHeight() As Boolean ``` 返回/设置是否只显示完整项目(不截断部分项目)。 ### MaxLength ```vb Property Get/Let MaxLength() As Long ``` 返回/设置编辑框中可输入的最大字符数。 ### HorizontalExtent ```vb Property Get/Let HorizontalExtent() As Single ``` 返回/设置列表的水平滚动宽度。 ### IMEMode ```vb Property Get/Let IMEMode() As CCIMEModeConstants ``` 返回/设置输入法编辑器模式。参见通用枚举。 ### ScrollTrack ```vb Property Get/Let ScrollTrack() As Boolean ``` 返回/设置滚动条是否实时跟踪。 ### AutoSelect ```vb Property Get/Let AutoSelect() As Boolean ``` 返回/设置获得焦点时是否自动选中编辑框文本。 ### AlwaysFindExact ```vb Property Get/Let AlwaysFindExact() As Boolean ``` 返回/设置是否始终精确查找匹配项。 ### RecentMax ```vb Property Get/Let RecentMax() As Integer ``` 返回/设置最近使用列表的最大项目数(0-9),0 表示不显示最近列表。 ### RecentBackColor ```vb Property Get/Let RecentBackColor() As OLE_COLOR ``` 返回/设置最近使用列表的背景色。 ### RecentForeColor ```vb Property Get/Let RecentForeColor() As OLE_COLOR ``` 返回/设置最近使用列表的前景色。 ### RecentCount ```vb Property Get RecentCount() As Long ``` 返回最近使用列表中的项目数。只读。 ### ListCount ```vb Property Get ListCount() As Long ``` 返回列表中的项目总数。只读。 ### List ```vb Property Get List(ByVal Index As Long) As String ``` 返回指定索引处的列表项文本。只读。 ### ListIndex ```vb Property Get/Let ListIndex() As Long ``` 返回/设置当前选中项的索引。 ### ItemData ```vb Property Get/Let ItemData(ByVal Index As Long) As LongPtr ``` 返回/设置指定索引项的附加数据。 ### SelStart ```vb Property Get/Let SelStart() As Long ``` 返回/设置选中文本的起始位置。 ### SelLength ```vb Property Get/Let SelLength() As Long ``` 返回/设置选中文本的长度。 ### SelText ```vb Property Get/Let SelText() As String ``` 返回/设置当前选中的文本。 ### ItemHeight ```vb Property Get ItemHeight() As Single ``` 返回列表项目的高度。只读。 ### FieldHeight ```vb Property Get FieldHeight() As Single ``` 返回编辑框(或静态文本)部分的高度。只读。 ### DroppedDown ```vb Property Get/Let DroppedDown() As Boolean ``` 返回/设置下拉列表是否展开。 ### DropDownWidth ```vb Property Get/Let DropDownWidth() As Single ``` 返回/设置下拉列表的宽度。简单样式下不支持。 ### TopIndex ```vb Property Get/Let TopIndex() As Long ``` 返回/设置列表中顶部可见项的索引。 ## 方法 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖动操作。 ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` 开始、结束或取消拖动操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移到该控件。 ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` 设置控件在其层级中的 Z 顺序位置。 ### Refresh ```vb Public Sub Refresh() ``` 强制完全重绘控件。 ### FindItem ```vb Public Function FindItem(ByVal Text As String, Optional ByVal Index As Long = -1, Optional ByVal Partial As Boolean) As Long ``` 在字体组合框中查找项目并返回其索引。Partial 为 True 时进行部分匹配。 ### GetIdealHorizontalExtent ```vb Public Function GetIdealHorizontalExtent() As Single ``` 获取水平滚动宽度的理想值。 ### SelectItem ```vb Public Function SelectItem(ByVal Text As String, Optional ByVal Index As Long = -1) As Long ``` 搜索以指定字符串开头的项目并选中它。不区分大小写。 ### SaveRecent ```vb Public Function SaveRecent() As Variant ``` 保存最近使用列表,返回字符串数组。 ### RestoreRecent ```vb Public Sub RestoreRecent(ByVal ArgList As Variant) ``` 从之前保存的状态恢复最近使用列表。 ### ClearRecent ```vb Public Sub ClearRecent() ``` 清除最近使用列表的内容。 ## 事件 ### Click ```vb Public Event Click() ``` 单击控件时发生。 ### DblClick ```vb Public Event DblClick() ``` 双击控件时发生。 ### Scroll ```vb Public Event Scroll() ``` 滚动列表时发生。 ### Change ```vb Public Event Change() ``` 控件内容发生变化时发生。 ### ContextMenu ```vb Public Event ContextMenu(ByRef Handled As Boolean, ByVal X As Single, ByVal Y As Single) ``` 右键单击或按 Shift+F10 时发生。设置 Handled 为 True 可阻止默认上下文菜单。 ### DropDown ```vb Public Event DropDown() ``` 下拉列表即将展开时发生。 ### CloseUp ```vb Public Event CloseUp() ``` 下拉列表关闭时发生。 ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyDown 事件之前发生,可设置 IsInputKey 标记按键是否为输入键。 ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` 在 KeyUp 事件之前发生。 ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按下键盘键时发生。 ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 释放键盘键时发生。 ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` 按下并释放字符键时发生。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时发生。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时发生。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时发生。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件时发生。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件时发生。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放操作完成或取消后,在源控件上发生。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 数据通过 OLE 拖放操作放置到控件上时发生。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放操作期间鼠标移过控件时发生。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 拖放操作期间需要更改鼠标光标时,在源控件上发生。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` 放置目标请求数据时,在源控件上发生。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 拖放操作启动时发生。 ## 代码示例 ### 基本用法 ```vb Private Sub Form_Load() With FontCombo1 .Style = FtcStyleDropDownCombo .FontType = FtcFontTypeTrueType .FontPitch = FtcFontPitchAll .RecentMax = 5 End With End Sub Private Sub FontCombo1_Click() Me.Font.Name = FontCombo1.Text Debug.Print "选中字体: " & FontCombo1.Text End Sub Private Sub Form_Unload(Cancel As Integer) Dim v As Variant v = FontCombo1.SaveRecent SaveSetting App.Title, "FontCombo", "Recent", Join(v, vbTab) End Sub ``` --- --- url: /zh/official/Challenges/self-contained_diagnostic_tool.md --- # twinBASIC 月度挑战 #1 ## 自包含诊断工具 使用 **twinBASIC** 构建一个**自包含的Windows诊断工具**。 你的工具应报告**运行所在系统的有用信息**。 **没有唯一正确的输出**——期待不同的方法和解读。 ## 奖品 * £100 twinBASIC账户额度 * (不可转让,无现金替代,仅可用于未来的twinBASIC许可证) ## 要求 * 使用 **twinBASIC** 构建 * 提交必须是**单个** `.twinproj` 文件 * 生成**单个Windows EXE** * 在 **Windows 10 及更高版本**上运行 * 无需管理员权限(提权时可提供增强输出) * **无外部依赖** (仅限内置twinBASIC包和内置OS/WinAPI功能) * 输出可以是**控制台或GUI** ## 诊断内容 报告**至少三个不同类别**的信息。 示例: * 操作系统版本/构建号 * CPU信息 * 内存使用 * 磁盘信息 * 进程信息 * 环境变量 * 系统运行时间 * 区域设置/代码页 * 网络配置 * 已安装的运行时(如.NET) ## 评审 参赛作品将在多个类别中评审,包括: * 报告信息的实用性 * 性能 * 最小EXE体积 * 文档完善或自文档化代码 * 有趣或巧妙的API使用 * 派生或推断的系统指标 * 整体优雅度和完成度 额外加分项: * 使用较新的twinBASIC特性(如委托、泛型) * 特别整洁或有洞察力的设计 获奖者由**twinBASIC团队全权决定**。 ## 截止日期 2026年1月31日(星期六) 截止日期后提交将锁定。 🔗: https://discord.com/channels/927638153546829845/1457060903332614357/1457060903332614357 > AI生成 --- --- url: /zh/official/Tutorials/CEF/Customize-the-UserDataFolder.md --- # 自定义UserDataFolder 在运行时,CEF需要一个工作文件夹用于用户配置——缓存、Cookie、历史记录、本地存储、密码管理器以及防止两个浏览器进程共享同一配置的每实例锁文件。默认情况下,运行时在 `%LocalAppData%\twinBASIC_CEF\<ProjectName>\instance-<N>\` 下选择一个文件夹,但该默认值并非总是合适的。 以下是默认值出错的几种情况: * **Office加载项**,其中宿主进程是 `MSACCESS.EXE` 或 `EXCEL.EXE`——默认的每进程布局会与宿主自身的配置冲突。 * **信息亭安装**,应用程序在低权限账户下运行,无法写入 `%LocalAppData%`。 * **便携部署**,所有状态必须存在于可执行文件旁边的USB闪存或网络共享上。 * **多用户/托管场景**,每个终端用户需要隔离的配置。 在所有这些情况下,通过在控件的[**Create**](/official/Reference/CEF/CefBrowser/#create)事件期间分配[**EnvironmentOptions.UserDataFolder**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#userdatafolder)来覆盖默认值: ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.UserDataFolder = _ Environ$("APPDATA") & "\MyApp\CEF\" End Sub ``` 如果文件夹不存在会自动创建。路径必须可由当前用户写入——只读路径在辅助浏览器进程尝试启动时会引发[**Error**](/official/Reference/CEF/CefBrowser/#error)事件。 ## 为什么在Create事件中 CEF在辅助浏览器进程启动时*一次性*读取环境选项。[**Create**](/official/Reference/CEF/CefBrowser/#create)事件在该启动之前立即触发,这使它成为覆盖默认值的正确位置。在此之后分配[**UserDataFolder**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#userdatafolder)(例如在[**Ready**](/official/Reference/CEF/CefBrowser/#ready)中)对运行中的浏览器没有影响。 ## 跨实例共享文件夹 单个用户数据文件夹不能同时被两个CEF进程打开——运行时在浏览器进程的整个生命周期内对其持有独占锁。同一应用程序中的两个**CefBrowser**控件共享辅助进程,因此也共享同一个锁,它们可以正常协作;指向同一文件夹的两个*独立*应用程序则会冲突。 当检测到冲突且[**UserDataFolder**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#userdatafolder)保留默认值时,控件会自动使用下一个 `instance-N` 子文件夹重试。当宿主已明确设置路径时,锁失败反而作为CEF初始化错误出现("CEF cache path already locked by another process")——在[**Error**](/official/Reference/CEF/CefBrowser/#error)事件中处理它: ```vb Private Sub CefBrowser1_Error(ByVal code As Long, ByVal msg As String) If InStr(msg, "already locked") > 0 Then MsgBox "Another copy of this application is already running. " & _ "Close it before opening another window.", _ vbExclamation End If End Sub ``` ## 记录运行时输出 [**EnvironmentOptions**](/official/Reference/CEF/CefBrowser/EnvironmentOptions)上的两个相关字段配置CEF调试日志,在调查运行时问题时很有用: ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.UserDataFolder = _ Environ$("APPDATA") & "\MyApp\CEF\" CefBrowser1.EnvironmentOptions.LogFilePath = _ Environ$("APPDATA") & "\MyApp\CEF\debug.log" CefBrowser1.EnvironmentOptions.LogSeverity = CefLogWarning End Sub ``` [**LogFilePath**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#logfilepath)跨运行追加——如果需要限制大小,请从你自己的代码中轮换或删除它。[**LogSeverity**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#logseverity)控制阈值;**CefLogDisable**(默认值)无论路径如何都不写入任何内容。 ## 另见 * [CefEnvironmentOptions](/official/Reference/CEF/CefBrowser/EnvironmentOptions) —— 预创建选项的完整参考。 * [自定义UserDataFolder(WebView2)](/official/Tutorials/WebView2/Customize-the-UserDataFolder) —— 应用于[**WebView2**](/official/Reference/WebView2/WebView2/)控件的相同思路。 --- --- url: /zh/official/Tutorials/WebView2/Customize-the-UserDataFolder.md --- # 自定义UserDataFolder 在运行时,WebView2需要一个工作文件夹来存储会话期间使用的数据。 默认情况下,将在可执行文件同目录下创建一个名为 `<FileName>.WebView2` 的文件夹(例如 `MyApp.Exe.WebView2`)。 如果此文件夹无法创建,WebView2控件将无法工作(你可以在运行时捕获控件的Error事件来确定此情况)。 这种默认行为并非总是合适的。 例如,如果你正在为Microsoft Access创建加载项,那么你几乎肯定不被允许在系统的Program Files文件夹的Office子文件夹中创建名为 `MSACCESS.EXE.WebView2` 的文件夹。 强烈建议你覆盖默认行为,改为提供一个被认为可以安全存储此类数据的路径。要在运行时覆盖UserDataFolder路径,请处理WebView2控件的Create事件。 参见此处的 `示例9. ActiveX Control WebView2 + Monaco` 中的示例,我们使用 `%APPDATA%\Local` 系统路径: ![Create Package](/assets/tbWebView2CreateEvent.DEpSZmxB.png){style="width:80%; height:auto;"} 将 `EnvironmentOptions.UserDataFolder` 属性设置为包含要使用的输出路径的字符串(文件夹将在必要时创建)。 --- --- url: /zh/packages/vbccr/lists/comboboxw.md description: 组合框控件(ComboBoxW) - VBCCR 开发手册,基于源码的完整 API 参考 --- # 组合框控件(ComboBoxW) 增强型组合框控件,支持视觉样式、自绘、大小写控制和提示文本。 ## 枚举 ### CboStyleConstants | 常量 | 值 | 说明 | |------|-----|------| | CboStyleDropDownCombo | 0 | 下拉组合框 | | CboStyleSimpleCombo | 1 | 简单组合框 | | CboStyleDropDownList | 2 | 下拉列表 | ### CboCharacterCasingConstants | 常量 | 值 | 说明 | |------|-----|------| | CboCharacterCasingNormal | 0 | 正常大小写 | | CboCharacterCasingUpper | 1 | 大写 | | CboCharacterCasingLower | 2 | 小写 | ### CboDrawModeConstants | 常量 | 值 | 说明 | |------|-----|------| | CboDrawModeNormal | 0 | 正常模式 | | CboDrawModeOwnerDrawFixed | 1 | 固定高度自绘 | | CboDrawModeOwnerDrawVariable | 2 | 可变高度自绘 | ## 属性 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景色。 ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景色。 ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE 拖放模式。参见通用枚举。 ### Redraw ```vb Property Get Redraw() As Boolean Property Let Redraw(ByVal Value As Boolean) ``` 是否允许重绘。 ### Style ```vb Property Get Style() As CboStyleConstants Property Let Style(ByVal Value As CboStyleConstants) ``` 组合框样式。 ### Locked ```vb Property Get Locked() As Boolean Property Let Locked(ByVal Value As Boolean) ``` 是否锁定(不可编辑)。 ### Text ```vb Property Get Text() As String Property Let Text(ByVal Value As String) ``` 编辑框文本。 ### ExtendedUI ```vb Property Get ExtendedUI() As Boolean Property Let ExtendedUI(ByVal Value As Boolean) ``` 扩展用户界面模式。 ### MaxDropDownItems ```vb Property Get MaxDropDownItems() As Long Property Let MaxDropDownItems(ByVal Value As Long) ``` 下拉列表最大显示项数。 ### IntegralHeight ```vb Property Get IntegralHeight() As Boolean Property Let IntegralHeight(ByVal Value As Boolean) ``` 是否按整项高度调整列表大小。 ### MaxLength ```vb Property Get MaxLength() As Long Property Let MaxLength(ByVal Value As Long) ``` 编辑框最大字符数。 ### CueBanner ```vb Property Get CueBanner() As String Property Let CueBanner(ByVal Value As String) ``` 提示文本(编辑框为空时显示)。 ### UseListBackColor ```vb Property Get UseListBackColor() As Boolean Property Let UseListBackColor(ByVal Value As Boolean) ``` 是否使用自定义列表背景色。 ### ListBackColor ```vb Property Get ListBackColor() As OLE_COLOR Property Let ListBackColor(ByVal Value As OLE_COLOR) ``` 下拉列表背景色。 ### UseListForeColor ```vb Property Get UseListForeColor() As Boolean Property Let UseListForeColor(ByVal Value As Boolean) ``` 是否使用自定义列表前景色。 ### ListForeColor ```vb Property Get ListForeColor() As OLE_COLOR Property Let ListForeColor(ByVal Value As OLE_COLOR) ``` 下拉列表前景色。 ### Sorted ```vb Property Get Sorted() As Boolean Property Let Sorted(ByVal Value As Boolean) ``` 是否自动排序。 ### HorizontalExtent ```vb Property Get HorizontalExtent() As Long Property Let HorizontalExtent(ByVal Value As Long) ``` 下拉列表水平滚动范围。 ### DisableNoScroll ```vb Property Get DisableNoScroll() As Boolean Property Let DisableNoScroll(ByVal Value As Boolean) ``` 当项目不足以填满时是否禁用滚动条而非隐藏。 ### CharacterCasing ```vb Property Get CharacterCasing() As CboCharacterCasingConstants Property Let CharacterCasing(ByVal Value As CboCharacterCasingConstants) ``` 字符大小写模式。 ### DrawMode ```vb Property Get DrawMode() As CboDrawModeConstants Property Let DrawMode(ByVal Value As CboDrawModeConstants) ``` 绘制模式。 ### IMEMode ```vb Property Get IMEMode() As CCIMEModeConstants Property Let IMEMode(ByVal Value As CCIMEModeConstants) ``` 输入法模式。参见通用枚举。 ### ScrollTrack ```vb Property Get ScrollTrack() As Boolean Property Let ScrollTrack(ByVal Value As Boolean) ``` 是否启用滚动跟踪。 ### AutoSelect ```vb Property Get AutoSelect() As Boolean Property Let AutoSelect(ByVal Value As Boolean) ``` 是否自动选择匹配项。 ### AlwaysFindExact ```vb Property Get AlwaysFindExact() As Boolean Property Let AlwaysFindExact(ByVal Value As Boolean) ``` 是否始终精确查找。 ### ListCount ```vb Property Get ListCount() As Long ``` 列表项数。只读。 ### List ```vb Property Get List(ByVal Index As Long) As String Property Let List(ByVal Index As Long, ByVal Value As String) ``` 按索引存取列表项。 ### ListIndex ```vb Property Get ListIndex() As Long Property Let ListIndex(ByVal Value As Long) ``` 当前选中项索引。 ### ItemData ```vb Property Get ItemData(ByVal Index As Long) As Long Property Let ItemData(ByVal Index As Long, ByVal Value As Long) ``` 列表项关联数据。 ### NewIndex ```vb Property Get NewIndex() As Long ``` 最近添加项的索引。只读。 ### TopIndex ```vb Property Get TopIndex() As Long Property Let TopIndex(ByVal Value As Long) ``` 列表顶部可见项索引。 ### SelStart ```vb Property Get SelStart() As Long Property Let SelStart(ByVal Value As Long) ``` 选中文本起始位置。 ### SelLength ```vb Property Get SelLength() As Long Property Let SelLength(ByVal Value As Long) ``` 选中文本长度。 ### SelText ```vb Property Get SelText() As String Property Let SelText(ByVal Value As String) ``` 选中文本。 ### ItemHeight ```vb Property Get ItemHeight() As Single Property Let ItemHeight(ByVal Value As Single) ``` 列表项高度。 ### FieldHeight ```vb Property Get FieldHeight() As Single ``` 编辑框高度。只读。 ### DroppedDown ```vb Property Get DroppedDown() As Boolean Property Let DroppedDown(ByVal Value As Boolean) ``` 下拉列表是否展开。 ### DropDownWidth ```vb Property Get DropDownWidth() As Long Property Let DropDownWidth(ByVal Value As Long) ``` 下拉列表宽度。 ### DropDownHeight ```vb Property Get DropDownHeight() As Long Property Let DropDownHeight(ByVal Value As Long) ``` 下拉列表高度。 ### hWndEdit ```vb Property Get hWndEdit() As LongPtr ``` 编辑框窗口句柄。只读。 ### hWndList ```vb Property Get hWndList() As LongPtr ``` 列表框窗口句柄。只读。 ### hWnd / hWndUserControl / Font / Enabled / MousePointer / MouseIcon / MouseTrack 参见公共属性。 ### Name / Tag / Parent / Container / Left / Top / Width / Height / Visible / ToolTipText / HelpContextID / WhatsThisHelpID / DragIcon / DragMode 参见标准扩展器属性。 ## 方法 ### AddItem ```vb Public Sub AddItem(ByVal Item As String, Optional ByVal Index As Variant) ``` 添加列表项。 ### RemoveItem ```vb Public Sub RemoveItem(ByVal Index As Long) ``` 移除列表项。 ### Clear ```vb Public Sub Clear() ``` 清空所有列表项。 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘。 ### FindItem ```vb Public Function FindItem(ByVal SearchString As String, Optional ByVal StartIndex As Long, Optional ByVal FindMode As Long) As Long ``` 查找列表项,返回索引。 ### GetIdealHorizontalExtent ```vb Public Function GetIdealHorizontalExtent() As Long ``` 获取理想的水平滚动范围。 ### SelectItem ```vb Public Sub SelectItem(ByVal SearchString As String) ``` 选择匹配的列表项。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放。 ### Drag / ZOrder / SetFocus / Move 参见标准方法。 ## 事件 ### Click ```vb Public Event Click() ``` ### DblClick ```vb Public Event DblClick() ``` ### Scroll ```vb Public Event Scroll() ``` 列表滚动时触发。 ### Change ```vb Public Event Change() ``` 文本内容改变时触发。 ### ContextMenu ```vb Public Event ContextMenu() ``` 右键菜单。 ### DropDown ```vb Public Event DropDown() ``` 下拉列表展开。 ### CloseUp ```vb Public Event CloseUp() ``` 下拉列表关闭。 ### ItemMeasure ```vb Public Event ItemMeasure(ByVal Index As Long, ByVal ItemWidth As Long, ByVal ItemHeight As Long) ``` 自绘测量事件。 ### ItemDraw ```vb Public Event ItemDraw(ByVal Index As Long, ByVal ItemState As Long, ByVal hDC As LongPtr, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` 自绘绘制事件。 ### KeyDown / KeyUp / KeyPress ### MouseDown / MouseMove / MouseUp / MouseEnter / MouseLeave ### OLECompleteDrag / OLEDragDrop / OLEDragOver / OLEGiveFeedback / OLESetData / OLEStartDrag ## 代码示例 ### 基本用法 ```vb ' 添加项目 ComboBoxW1.AddItem "苹果" ComboBoxW1.AddItem "香蕉" ComboBoxW1.ListIndex = 0 ' 设置提示文本 ComboBoxW1.CueBanner = "请选择水果..." ' 大写模式 ComboBoxW1.CharacterCasing = CboCharacterCasingUpper ' 自绘模式 ComboBoxW1.DrawMode = CboDrawModeOwnerDrawFixed ``` ### 自绘示例 ```vb Private Sub ComboBoxW1_ItemDraw(ByVal Index As Long, ByVal ItemState As Long, _ ByVal hDC As LongPtr, ByVal Left As Long, ByVal Top As Long, _ ByVal Right As Long, ByVal Bottom As Long) ' 绘制自定义列表项 End Sub ``` --- --- url: /en/official/Reference/VBA/Math/Abs.md --- # Abs Returns a value of the same type that is passed to it specifying the absolute value of a number. Syntax: **Abs(** *number* **)** *number* : *required* Any valid numeric expression. If *number* contains **Null**, **Null** is returned; if it is an uninitialized variable, zero is returned. The absolute value of a number is its unsigned magnitude. For example, `Abs(-1)` and `Abs(1)` both return `1`. ### Example This example uses the **Abs** function to compute the absolute value of a number. ```vb Dim MyNumber MyNumber = Abs(50.3) ' Returns 50.3. MyNumber = Abs(-50.3) ' Returns 50.3. ``` ### See Also * [Sgn](/en/official/Reference/VBA/Math/Sgn) function --- --- url: /zh/official/Reference/VBA/Math/Abs.md --- # Abs 返回与传入类型相同的值,指定数字的绝对值。 语法:**Abs(** *number* **)** *number* : *必需* 任何有效的数值表达式。如果 *number* 包含 **Null**,则返回 **Null**;如果是未初始化的变量,则返回零。 数字的绝对值是其无符号大小。例如,`Abs(-1)` 和 `Abs(1)` 都返回 `1`。 ### 示例 此示例使用 **Abs** 函数计算数字的绝对值。 ```vb Dim MyNumber MyNumber = Abs(50.3) ' Returns 50.3. MyNumber = Abs(-50.3) ' Returns 50.3. ``` ### 另请参阅 * [Sgn](/official/Reference/VBA/Math/Sgn) 函数 --- --- url: /zh/official/Videos/AccessDevCon.md --- # Access DevCon - 视频 了解更多关于本会议的信息:[https://www.donkarl.com/devcon][2]。 ### Access DevCon 2025 - twinBASIC 更新 2025年4月26日 Access MVP Mike Wolfe介绍twinBASIC项目更新。 * 幻灯片和更多信息见:[https://nolongerset.com/devcon-2025][1]。 [1]: https://nolongerset.com/devcon-2025 [2]: https://www.donkarl.com/devcon *** ### Access DevCon 2024 - twinBASIC 使用twinBASIC创建加载项 2024年4月29日 Mike Wolfe介绍twinBASIC项目更新以及如何使用twinBASIC为Access创建加载项。 * 更多信息见:[https://nolongerset.com/tag/twinbasic-weekly-update/][3]。 [3]: https://nolongerset.com/tag/twinbasic-weekly-update/ *** ### Access DevCon 2023 - twinBASIC 更新 2023年5月8日 Mike Wolfe介绍twinBASIC专题,涵盖项目概述、进展、路线图、演示和Access集成计划。 * 更多信息见[https://nolongerset.com/tag/twinbasic][5]。 [5]: https://nolongerset.com/tag/twinbasic *** ### Access DevCon 2022 - twinBASIC 更新 2022年5月12日 Mike Wolfe介绍twinBASIC的当前状态,重点介绍对Access开发者的实际用途和实用性。 * 更多信息见[https://nolongerset.com/tag/twinbasic][5] *** ### Access DevCon 2021 - twinBasic 2021年5月12日 Mike Wolfe展示:twinBasic的全球首发——一种全新风格的VB(A)。 > AI生成 --- --- url: /en/official/Videos/AccessDevCon.md --- # Access DevCon - Videos To learn more about the conference: [https://www.donkarl.com/devcon][2]. ### Access DevCon 2025 - twinBASIC Update 26 Apr 2025 Access MVP Mike Wolfe presents a twinBASIC project update. * For the slide deck and more information see: [https://nolongerset.com/devcon-2025][1]. [1]: https://nolongerset.com/devcon-2025 [2]: https://www.donkarl.com/devcon *** ### Access DevCon 2024 - twinBASIC Add-In creation with twinBASIC 29 Apr 2024 Mike Wolfe presents a twinBASIC project update and how to create add-ins for Access with twinBASIC. * For more information see: [https://nolongerset.com/tag/twinbasic-weekly-update/][3]. [3]: https://nolongerset.com/tag/twinbasic-weekly-update/ *** ### Access DevCon 2023 - twinBASIC Update 8 May 2023 Mike Wolfe presents a session on twinBASIC covering a brief project overview, progress, roadmap, demos and Access integration plans. * For more information see [https://nolongerset.com/tag/twinbasic][5]. [5]: https://nolongerset.com/tag/twinbasic *** ### Access DevCon 2022 - twinBASIC Update 12 May 2022 Mike Wolfe presents the current state of twinBASIC focussing on the practical use and usefulness for Access developers. * For more information, see [https://nolongerset.com/tag/twinbasic][5] *** ### Access DevCon 2021 - twinBasic 12 May 2021 Mike Wolfe presents: The world premier of twinBasic, a new flavour of VB(A). --- --- url: /zh/official/Features/Project-Configuration/ActiveX-Registration.md --- # ActiveX 注册选项 ## 注册位置 将 ActiveX 构建注册到 `HKEY_LOCAL_MACHINE` 或 `HKEY_CURRENT_USER` 的选项。虽然现代应用程序使用 `HKEY_CURRENT_USER`,但为了 VBx 兼容性,组件必须注册到 `HKEY_LOCAL_MACHINE`。注意这需要在注册时以管理员身份运行。 ## 构建时注册 构建时注册是可选的。tB 提供了"Project: Register DLL after build"选项,因此你可以禁用自动注册,例如你想先移动文件时。 --- --- url: /en/official/Features/Project-Configuration/ActiveX-Registration.md --- # ActiveX Registration Options ## Registration Location Register ActiveX builds to `HKEY_LOCAL_MACHINE` or `HKEY_CURRENT_USER` option. While modern applications use `HKEY_CURRENT_USER`, for VBx compatibility components must be registered to `HKEY_LOCAL_MACHINE`. Note that this requires running as admin when registering. ## Build-Time Registration Registration at build time is optional. tB provides the Project: Register DLL after build option so you can disable automatic registration, if for example you wanted to move the file first. --- --- url: /en/official/Reference/VBA/Collection/Add.md --- # Add Adds a member to a **Collection** object. Syntax: *object*.**Add** *item* \[ **,** *key* ] \[ **,** *before* ] \[ **,** *after* ] *object* : *required* An object expression that evaluates to a **Collection** object. *item* : *required* An expression of any type that specifies the member to add to the collection. *key* : *optional* A unique string expression that specifies a key string that can be used, instead of a positional index, to access a member of the collection. *before* : *optional* An expression that specifies a relative position in the collection. The member to be added is placed in the collection before the member identified by the *before* argument. If a numeric expression, *before* must be a number from 1 to the value of the collection's [**Count**](/en/official/Reference/VBA/Collection/Count) property. If a string expression, *before* must correspond to the *key* specified when the member being referred to was added to the collection. Specify a *before* position or an *after* position, but not both. *after* : *optional* An expression that specifies a relative position in the collection. The member to be added is placed in the collection after the member identified by the *after* argument. The same numeric and string-key constraints as *before* apply. Specify a *before* position or an *after* position, but not both. If neither *before* nor *after* is specified, the new item is added at the end of the collection. Whether *before* or *after* is a string expression or a numeric expression, it must refer to an existing member of the collection, or an error occurs. An error also occurs if a specified *key* duplicates the *key* for an existing member of the collection. Key comparison is governed by the [**KeyCompareMode**](/en/official/Reference/VBA/Collection/KeyCompareMode) property. ### Example This example uses the **Add** method to add `Inst` objects (instances of a class called `Class1` containing a **Public** variable `InstanceName`) to a collection called `MyClasses`. To run this code, insert a class module and declare a public variable called `InstanceName` at module level of `Class1` (type `Public InstanceName`) to hold the names of each instance. Leave the default name as `Class1`. ```vb Dim MyClasses As New Collection ' Create a Collection object. Dim Num As Integer ' Counter for individualizing keys. Dim Msg As String Dim TheName As Variant ' Holder for names user enters. Do Dim Inst As New Class1 ' Create a new instance of Class1. Num = Num + 1 ' Increment Num, then get a name. Msg = "Please enter a name for this object." & vbNewLine _ & "Press Cancel to see names in collection." TheName = InputBox(Msg, "Name the Collection Items") Inst.InstanceName = TheName ' Put name in object instance. ' If user entered name, add it to the collection. If Inst.InstanceName <> "" Then ' Add the named object to the collection. MyClasses.Add Item := Inst, Key := CStr(Num) End If ' Clear the current reference in preparation for next one. Set Inst = Nothing Loop Until TheName = "" Dim x As Variant For Each x In MyClasses MsgBox x.InstanceName, , "Instance Name" Next ``` ### See Also * [Count](/en/official/Reference/VBA/Collection/Count) property * [Item](/en/official/Reference/VBA/Collection/Item) method * [Remove](/en/official/Reference/VBA/Collection/Remove) method * [Exists](/en/official/Reference/VBA/Collection/Exists) method --- --- url: /zh/official/Reference/VBA/Collection/Add.md --- # Add 向 **Collection** 对象添加一个成员。 语法:*object*.**Add** *item* \[ **,** *key* ] \[ **,** *before* ] \[ **,** *after* ] *object* : *必需* 一个计算结果为 **Collection** 对象的对象表达式。 *item* : *必需* 任意类型的表达式,指定要添加到集合中的成员。 *key* : *可选* 一个唯一的字符串表达式,指定一个键字符串,可用于代替位置索引来访问集合中的成员。 *before* : *可选* 一个指定集合中相对位置的表达式。要添加的成员将放置在由 *before* 参数标识的成员之前。如果是数值表达式,*before* 必须是从 1 到集合的 [**Count**](/official/Reference/VBA/Collection/Count) 属性值之间的数字。如果是字符串表达式,*before* 必须与被引用成员添加到集合时指定的 *key* 相对应。指定 *before* 位置或 *after* 位置,但不能同时指定两者。 *after* : *可选* 一个指定集合中相对位置的表达式。要添加的成员将放置在由 *after* 参数标识的成员之后。与 *before* 相同的数值和字符串键约束适用。指定 *before* 位置或 *after* 位置,但不能同时指定两者。 如果既未指定 *before* 也未指定 *after*,则新项添加到集合末尾。 无论 *before* 还是 *after* 是字符串表达式还是数值表达式,它都必须引用集合中现有的成员,否则将发生错误。 如果指定的 *key* 与集合中现有成员的 *key* 重复,也会发生错误。键比较由 [**KeyCompareMode**](/official/Reference/VBA/Collection/KeyCompareMode) 属性控制。 ### 示例 此示例使用 **Add** 方法将 `Inst` 对象(名为 `Class1` 的类的实例,该类包含一个 **Public** 变量 `InstanceName`)添加到名为 `MyClasses` 的集合中。要运行此代码,请插入一个类模块,并在 `Class1` 的模块级别声明一个名为 `InstanceName` 的公共变量(类型为 `Public InstanceName`),以保存每个实例的名称。保留默认名称为 `Class1`。 ```vb Dim MyClasses As New Collection ' Create a Collection object. Dim Num As Integer ' Counter for individualizing keys. Dim Msg As String Dim TheName As Variant ' Holder for names user enters. Do Dim Inst As New Class1 ' Create a new instance of Class1. Num = Num + 1 ' Increment Num, then get a name. Msg = "Please enter a name for this object." & vbNewLine _ & "Press Cancel to see names in collection." TheName = InputBox(Msg, "Name the Collection Items") Inst.InstanceName = TheName ' Put name in object instance. ' If user entered name, add it to the collection. If Inst.InstanceName <> "" Then ' Add the named object to the collection. MyClasses.Add Item := Inst, Key := CStr(Num) End If ' Clear the current reference in preparation for next one. Set Inst = Nothing Loop Until TheName = "" Dim x As Variant For Each x In MyClasses MsgBox x.InstanceName, , "Instance Name" Next ``` ### 另请参阅 * [Count](/official/Reference/VBA/Collection/Count) 属性 * [Item](/official/Reference/VBA/Collection/Item) 方法 * [Remove](/official/Reference/VBA/Collection/Remove) 方法 * [Exists](/official/Reference/VBA/Collection/Exists) 方法 --- --- url: /en/official/IDE/AddIns.md --- # Add Ins An addin is a Standard DLL that exports `tbCreateCompilerAddin` and returns an object implementing the [**AddIn**](/en/official/Reference/tbIDE/AddIn) interface. Through the [**Host**](/en/official/Reference/tbIDE/Host) object the IDE passes at startup, an addin can reach the toolbar, tool windows, debug console, current project, keyboard shortcuts, and themes. The [**tbIDE package**](/en/official/Reference/tbIDE/) documents the full API. The New Project dialog includes addin templates (samples 10 through 16), covering patterns from simple toolbar buttons to HTML DOM-backed tool windows. Community addins are listed on the [**Community**](/en/official/IDE/AddIns/Community/) page. twinBASIC supports two addin install locations. The IDE install directory is available to all user accounts on the machine but may require reinstallation after an IDE update. A per-user application data folder persists across IDE upgrades and requires no administrator rights. To install an addin via the IDE install directory, unzip and copy each architecture DLL to the matching folder: `\twinBASIC_IDE_BETA_xxx\addins\win32\` `\twinBASIC_IDE_BETA_xxx\addins\win64\` --- --- url: /en/official/IDE/Menu/Add-Ins.md --- # Add-Ins Menu ![Add-Ins Menu](Images/Menu_Add-Ins.png "Add-Ins Menu") {no addins loaded} Once you open a project: ![Global Search - Add-Ins Menu](Images/Menu_Add-Ins_GlobalSearch.png "Global Search - Add-Ins Menu") Clicking on this menu option shows > 🛈 Sorry, this menu option has not been implemented yet ![Global Search - Popup](Images/GlobalSearch-Popup.png "Global Search - Popup") --- --- url: /en/official/Reference/VBA/TbExpressionService/AddCustomBinder.md --- # AddCustomBinder Registers a user-supplied binder that resolves symbols dynamically at compile time. Syntax: *service*.**AddCustomBinder** *customBinder* *service* : *required* An object expression that evaluates to a **TbExpressionService** object. *customBinder* : *required* An object that implements [**ITbCustomBinder**](./#itbcustombinder-interface). Use **AddCustomBinder** when [**AddCustomBinderObject**](/en/official/Reference/VBA/TbExpressionService/AddCustomBinderObject) doesn't fit --- for example, when the names available to the expression are not statically known, when a name should resolve to something other than a member access on a fixed object, or when the implementer needs to inspect the argument count at the call site as part of resolution. The engine calls [**Bind**](/en/official/Reference/VBA/TbExpressionService/Bind) on each registered custom binder during compilation, once per unresolved symbol. The first binder that returns a non-**Nothing** result wins. Multiple custom binders can be registered with one service, and they are consulted in registration order. ### Example This example registers a class instance as both a property source (via [**AddCustomBinderObject**](/en/official/Reference/VBA/TbExpressionService/AddCustomBinderObject) with [**IsAppObject**](./#IsAppObject)) and a custom binder. Bare symbols in the expression are first looked up as members of `Me` via the property source; whatever isn't matched there falls through to `Me.Bind`, which can resolve it dynamically --- for example, against a live recordset. ```vb ' Inside a class that does: Implements ITbCustomBinder Dim Service As TbExpressionService = New TbExpressionService Service.AddStdLibraryBinder() Service.AddCustomBinderObject "Report", Me, IsAppObject Service.AddCustomBinder Me Dim Expr As ITbExpression = Service.Compile("UCase(FieldName) & "" — "" & Title") ``` ### See Also * [Bind](/en/official/Reference/VBA/TbExpressionService/Bind) method * [Compile](/en/official/Reference/VBA/TbExpressionService/Compile) method * [AddStdLibraryBinder](/en/official/Reference/VBA/TbExpressionService/AddStdLibraryBinder) method * [AddCustomBinderObject](/en/official/Reference/VBA/TbExpressionService/AddCustomBinderObject) method --- --- url: /zh/official/Reference/VBA/TbExpressionService/AddCustomBinder.md --- # AddCustomBinder 注册用户提供的绑定器,在编译时动态解析符号。 语法:*service*.**AddCustomBinder** *customBinder* *service* : *必需* 计算结果为 **TbExpressionService** 对象的对象表达式。 *customBinder* : *必需* 实现 [**ITbCustomBinder**](./#itbcustombinder-interface) 的对象。 当 [**AddCustomBinderObject**](/official/Reference/VBA/TbExpressionService/AddCustomBinderObject) 不适用时使用 **AddCustomBinder**——例如,当表达式可用的名称不是静态已知的,当名称应解析为固定对象上的成员访问之外的其他内容,或当实现者需要在解析过程中检查调用点的参数数量时。 引擎在编译期间对每个已注册的自定义绑定器调用 [**Bind**](/official/Reference/VBA/TbExpressionService/Bind),每个未解析符号调用一次。第一个返回非 **Nothing** 结果的绑定器胜出。一个服务可以注册多个自定义绑定器,按注册顺序查询。 ### 示例 此示例将一个类实例同时注册为属性源(通过带 [**IsAppObject**](./#IsAppObject) 的 [**AddCustomBinderObject**](/official/Reference/VBA/TbExpressionService/AddCustomBinderObject))和自定义绑定器。表达式中的裸符号首先通过属性源作为 `Me` 的成员查找;未匹配的符号将传递给 `Me.Bind`,后者可以动态解析——例如,针对活动记录集。 ```vb ' Inside a class that does: Implements ITbCustomBinder Dim Service As TbExpressionService = New TbExpressionService Service.AddStdLibraryBinder() Service.AddCustomBinderObject "Report", Me, IsAppObject Service.AddCustomBinder Me Dim Expr As ITbExpression = Service.Compile("UCase(FieldName) & "" — "" & Title") ``` ### 另请参阅 * [Bind](/official/Reference/VBA/TbExpressionService/Bind) 方法 * [Compile](/official/Reference/VBA/TbExpressionService/Compile) 方法 * [AddStdLibraryBinder](/official/Reference/VBA/TbExpressionService/AddStdLibraryBinder) 方法 * [AddCustomBinderObject](/official/Reference/VBA/TbExpressionService/AddCustomBinderObject) 方法 --- --- url: /en/official/Reference/VBA/TbExpressionService/AddCustomBinderObject.md --- # AddCustomBinderObject Exposes the public members of an object so that compiled expressions can reach them. Syntax: *service*.**AddCustomBinderObject** *name*, *object* \[ **,** *flags* ] *service* : *required* An object expression that evaluates to a **TbExpressionService** object. *name* : *required* A **String** giving the qualifier under which *object*'s members are visible to expressions compiled by *service*. *object* : *required* The object whose public members are exposed. *flags* : *optional* A combination of [**ExpressionEngineBinderFlags**](./#expressionenginebinderflags) values. The default is `0`, in which case the object's members are reachable only when qualified by *name* (e.g. `Report.Title`). Pass [**IsAppObject**](./#IsAppObject) to additionally make the members reachable without qualification, the way an Office host's **Application** members are. Member resolution is performed by name through the standard COM/IDispatch protocol --- any property or method that is callable from outside the object is callable from the expression. The object must remain alive for as long as expressions might be evaluated against it. Multiple objects can be bound to the same service, each under its own *name*. They are consulted in the order they were added. ### Example This example exposes the host's report object so that an expression can refer to its properties either by qualified name or by bare name. ```vb Dim Service As TbExpressionService = New TbExpressionService Service.AddStdLibraryBinder() Service.AddCustomBinderObject "Report", Me, IsAppObject Debug.Print Service.Compile("Report.Title").Evaluate() ' "Sales Q4" Debug.Print Service.Compile("Title").Evaluate() ' "Sales Q4" — IsAppObject in effect ``` ### See Also * [Compile](/en/official/Reference/VBA/TbExpressionService/Compile) method * [AddStdLibraryBinder](/en/official/Reference/VBA/TbExpressionService/AddStdLibraryBinder) method * [AddCustomBinder](/en/official/Reference/VBA/TbExpressionService/AddCustomBinder) method --- --- url: /zh/official/Reference/VBA/TbExpressionService/AddCustomBinderObject.md --- # AddCustomBinderObject 暴露对象的公共成员,使编译表达式可以访问它们。 语法:*service*.**AddCustomBinderObject** *name*, *object* \[ **,** *flags* ] *service* : *必需* 计算结果为 **TbExpressionService** 对象的对象表达式。 *name* : *必需* 一个 **String**,给出 *object* 的成员对 *service* 编译的表达式可见时的限定名。 *object* : *必需* 要暴露公共成员的对象。 *flags* : *可选* [**ExpressionEngineBinderFlags**](./#expressionenginebinderflags) 值的组合。默认为 `0`,此时对象的成员仅当由 *name* 限定时才可访问(例如 `Report.Title`)。传入 [**IsAppObject**](./#IsAppObject) 可以使成员无需限定即可访问,类似于 Office 宿主的 **Application** 成员。 成员解析通过标准 COM/IDispatch 协议按名称执行——任何可从对象外部调用的属性或方法都可从表达式中调用。只要可能对表达式求值,对象就必须保持活动状态。 多个对象可以绑定到同一服务,每个对象有自己的 *name*。按添加顺序查询。 ### 示例 此示例暴露宿主的报表对象,使表达式可以通过限定名或裸名引用其属性。 ```vb Dim Service As TbExpressionService = New TbExpressionService Service.AddStdLibraryBinder() Service.AddCustomBinderObject "Report", Me, IsAppObject Debug.Print Service.Compile("Report.Title").Evaluate() ' "Sales Q4" Debug.Print Service.Compile("Title").Evaluate() ' "Sales Q4" — IsAppObject in effect ``` ### 另请参阅 * [Compile](/official/Reference/VBA/TbExpressionService/Compile) 方法 * [AddStdLibraryBinder](/official/Reference/VBA/TbExpressionService/AddStdLibraryBinder) 方法 * [AddCustomBinder](/official/Reference/VBA/TbExpressionService/AddCustomBinder) 方法 --- --- url: /en/official/Reference/tbIDE/AddIn.md --- # AddIn class The contract every addin's main class must implement. One read-only property --- [**Name**](#name) --- that the IDE reads to label the addin in error messages, log lines, and any addin-management UI added later. The IDE never creates an **AddIn** itself; the addin DLL constructs the object inside [`tbCreateCompilerAddin`](/en/official/Reference/tbIDE/#building-and-loading-an-addin) and returns it. ```vb Private Class MyAddIn Implements AddIn Private WithEvents Host As Host Public Sub New(ByVal Host As Host) Set Me.Host = Host End Sub Private Property Get AddIn_Name() As String Return "My AddIn" End Property End Class ``` The class implementing **AddIn** is also the natural place to hold every other `WithEvents` reference the addin uses ([**Host**](/en/official/Reference/tbIDE/Host), each [**Button**](/en/official/Reference/tbIDE/Button), each [**ToolWindow**](/en/official/Reference/tbIDE/ToolWindow), an optional [**AddinTimer**](/en/official/Reference/tbIDE/AddinTimer), …) --- its lifetime is tied to the addin's loaded state. ## Properties ### Name A short human-readable name for the addin. **String**, read-only. The IDE captures this once when the addin is loaded. Syntax: *addIn*.**Name** **As String** --- --- url: /zh/official/Reference/tbIDE/AddIn.md --- # AddIn 类 每个插件的主类必须实现的契约。一个只读属性——[**Name**](#name)——IDE 读取它来在错误消息、日志行和日后可能添加的插件管理 UI 中标注插件。IDE 永远不会自己创建 **AddIn**;插件 DLL 在 [`tbCreateCompilerAddin`](/official/Reference/tbIDE/#构建和加载插件) 内部构造该对象并返回它。 ```vb Private Class MyAddIn Implements AddIn Private WithEvents Host As Host Public Sub New(ByVal Host As Host) Set Me.Host = Host End Sub Private Property Get AddIn_Name() As String Return "My AddIn" End Property End Class ``` 实现 **AddIn** 的类也是存放插件使用的所有其他 `WithEvents` 引用([**Host**](/official/Reference/tbIDE/Host)、每个 [**Button**](/official/Reference/tbIDE/Button)、每个 [**ToolWindow**](/official/Reference/tbIDE/ToolWindow)、可选的 [**AddinTimer**](/official/Reference/tbIDE/AddinTimer) 等)的自然位置——其生命周期与插件的加载状态绑定。 ## 属性 ### Name 插件的一个简短可读名称。**String**,只读。IDE 在加载插件时捕获此值一次。 语法:*addIn*.**Name** **As String** --- --- url: /en/official/Reference/tbIDE/AddinTimer.md --- # AddinTimer class A simple periodic-callback helper. **AddinTimer** is the **only user-instantiable class** in the package --- every other CoClass is supplied to the addin by the IDE; this one the addin creates with `New`. Internally it wraps the Win32 `SetTimer` / `KillTimer` pair against `hwnd = 0` and fires its [**Timer**](#timer) event from the IDE's UI thread. ```vb Private WithEvents Timer As AddinTimer Private Sub Button1_OnClick() Set Timer = New AddinTimer Timer.Interval = 500 ' milliseconds Timer.Enabled = True End Sub Private Sub Timer_Timer() ' fires every 500 ms on the IDE's UI thread End Sub ``` Stop the timer by setting [**Enabled**](#enabled) = **False**, or simply by dropping the last reference --- `Class_Terminate` cancels the underlying Win32 timer automatically. Both [**Enabled**](#enabled) and [**Interval**](#interval) are live: assigning to either re-arms the underlying Win32 timer using the new values, so changing the interval while the timer is running takes effect immediately. Nothing in the package *requires* this helper --- a direct `SetTimer` / `KillTimer` pair (or any other periodic mechanism) works just as well; sample 15's dwell-time pattern uses raw Win32 calls. **AddinTimer** is the right choice when the convenience of an event-bound class is preferable to managing the Win32 plumbing directly. ## Properties ### Enabled Controls whether the underlying Win32 timer is running. **Boolean**, default **False**. Assigning to **Enabled** re-arms (or cancels) the timer immediately. Syntax: *timer*.**Enabled** \[ = *value* ] ### Interval The timer's period, in milliseconds. **Long**, default **0**. With **Interval = 0** the timer is effectively inert; set a positive value and [**Enabled**](#enabled) = **True** to start the periodic callback. Assigning to **Interval** re-arms the timer with the new value, so the next tick fires after the new interval rather than the old one. Syntax: *timer*.**Interval** \[ = *milliseconds* ] ## Events ### Timer Fires every [**Interval**](#interval) milliseconds while [**Enabled**](#enabled) is **True**. Runs on the IDE's UI thread. Syntax: *timer*\_**Timer**() Long-running work inside the handler will block the UI thread until it returns --- keep the handler short and offload heavy work to a background mechanism when needed. --- --- url: /zh/official/Reference/tbIDE/AddinTimer.md --- # AddinTimer 类 一个简单的周期性回调辅助类。**AddinTimer** 是包中**唯一可由用户实例化的类**——其他每个 CoClass 都由 IDE 提供给插件;这个类由插件用 `New` 创建。内部封装了 Win32 的 `SetTimer` / `KillTimer` 对,针对 `hwnd = 0`,并从 IDE 的 UI 线程触发其 [**Timer**](#timer) 事件。 ```vb Private WithEvents Timer As AddinTimer Private Sub Button1_OnClick() Set Timer = New AddinTimer Timer.Interval = 500 ' 毫秒 Timer.Enabled = True End Sub Private Sub Timer_Timer() ' 每 500 毫秒在 IDE 的 UI 线程上触发 End Sub ``` 通过设置 [**Enabled**](#enabled) = **False** 来停止计时器,或者简单地释放最后一个引用——`Class_Terminate` 会自动取消底层 Win32 计时器。[**Enabled**](#enabled) 和 [**Interval**](#interval) 都是实时的:对任一属性赋值都会用新值重新启动底层 Win32 计时器,因此在计时器运行时更改间隔会立即生效。 包中没有任何内容*要求*使用此辅助类——直接使用 `SetTimer` / `KillTimer` 对(或任何其他周期性机制)同样有效;示例 15 的停留时间模式就使用了原始 Win32 调用。当事件绑定类的便利性优于直接管理 Win32 管道时,**AddinTimer** 是正确的选择。 ## 属性 ### Enabled 控制底层 Win32 计时器是否运行。**Boolean**,默认 **False**。对 **Enabled** 赋值会立即重新启动(或取消)计时器。 语法:*timer*.**Enabled** \[ = *value* ] ### Interval 计时器的周期,以毫秒为单位。**Long**,默认 **0**。**Interval = 0** 时计时器实际上是惰性的;设置一个正值并将 [**Enabled**](#enabled) 设为 **True** 以启动周期性回调。对 **Interval** 赋值会用新值重新启动计时器,因此下一次触发将在新间隔后发生,而非旧间隔。 语法:*timer*.**Interval** \[ = *milliseconds* ] ## 事件 ### Timer 当 [**Enabled**](#enabled) 为 **True** 时,每隔 [**Interval**](#interval) 毫秒触发一次。在 IDE 的 UI 线程上运行。 语法:*timer*\_**Timer**() 处理程序中的长时间运行工作会阻塞 UI 线程直到其返回——保持处理程序简短,需要时将繁重工作卸载到后台机制。 --- --- url: /en/official/Reference/Core/AddressOf.md --- # AddressOf operator A unary operator that returns a function-pointer reference to its operand. Syntax: > **AddressOf** *procedurename*\ > **AddressOf** *instance*.*procedurename* *(twinBASIC)* *procedurename* : The name of a [**Sub**](/en/official/Reference/Core/Sub), [**Function**](/en/official/Reference/Core/Function), or [**Property**](/en/official/Reference/Core/Property) procedure whose address is taken. *instance* : *optional* (twinBASIC) An object reference whose member *procedurename* is targeted. The resulting pointer is bound to *instance*, so calling through it invokes the method on that specific object. When a procedure name appears in an argument list, normally the procedure is *called* and the procedure's return value is passed. **AddressOf** suppresses the call and substitutes the procedure's address instead. The most common use is to install a callback in a Windows API --- the API then invokes the procedure from outside the project's code, in a process known as a *callback*. The value **AddressOf** produces is bit-compatible with **LongPtr**, so it can be passed wherever a function pointer is expected --- including legacy [**Declare**](/en/official/Reference/Core/Declare) parameters typed **As Long** or **As LongPtr**. When the destination type is a [**Delegate**](/en/official/Reference/Core/Delegate), the compiler additionally checks that the operand's signature matches the delegate's. In classic VBA, *procedurename* must name a procedure in a standard [**Module**](/en/official/Reference/Core/Module) of the current project; the destination parameter must be typed **As Long**; and the resulting pointer can only be invoked by code outside Basic (e.g. a DLL). twinBASIC lifts each of these restrictions --- see [twinBASIC enhancements](#twinbasic-enhancements) below. ::: warning Errors raised inside a callback cannot propagate back to the foreign caller --- the API runs outside the project's error-handling chain. Place `On Error Resume Next` (or an explicit handler) at the top of any procedure used as an **AddressOf** target. ::: ### twinBASIC enhancements * **Indirect calls back through Basic.** A delegate variable holding an **AddressOf** value can be called directly: `Dim op As Operation = AddressOf Add: r = op(5, 6)`. Classic VBA can pass such pointers between procedures but cannot invoke through them inside Basic. See [**Delegate**](/en/official/Reference/Core/Delegate). * **Class, form, and user-control members.** **AddressOf** accepts methods declared on a class, form, or user-control. Take a pointer to an instance method by qualifying the name with the object reference: `AddressOf myInstance.MyMethod`. The resulting pointer remembers the instance --- calling through it dispatches to that object. * **CDecl callbacks.** Mark both the target procedure and the matching [**Delegate**](/en/official/Reference/Core/Delegate) (or [**Declare**](/en/official/Reference/Core/Declare) parameter) with **CDecl** to model `cdecl` callbacks. Classic VBA's **AddressOf** is hard-wired to `__stdcall`. See [API Declarations](/en/official/Features/Advanced/API-Declarations#cdecl-callbacks). * **No `FARPROC` shim needed.** Assigning a function pointer to a local variable is direct --- `Dim lpfn As LongPtr = AddressOf MyFunc` --- without writing an intermediate forwarding procedure. ### Example Calling through a typed delegate, inside Basic: ```vb Private Delegate Function Operation (ByVal A As Long, ByVal B As Long) As Long Public Function Addition(ByVal A As Long, ByVal B As Long) As Long Return A + B End Function Private Sub Demo() Dim op As Operation = AddressOf Addition Debug.Print op(5, 6) ' 11 End Sub ``` Installing a callback in a Win32 API. `EnumWindows` invokes *EnumProc* once per top-level window: ```vb Public Declare PtrSafe Function EnumWindows Lib "user32" ( _ ByVal lpEnumFunc As LongPtr, ByVal lParam As LongPtr) As Long Public Function EnumProc(ByVal hwnd As LongPtr, ByVal lParam As LongPtr) As Long On Error Resume Next Debug.Print hwnd EnumProc = 1 ' Continue enumeration. End Function Public Sub ListTopLevelWindows() EnumWindows AddressOf EnumProc, 0 End Sub ``` Taking a pointer to an instance method by qualifying with the object reference: ```vb Class CFoo Public Sub Bar() Debug.Print "Bar on instance" End Sub End Class Public Sub Demo() Dim foo1 As New CFoo Dim lpfn As LongPtr = AddressOf foo1.Bar End Sub ``` ### See Also * [**Delegate** statement](/en/official/Reference/Core/Delegate) * [**Declare** statement](/en/official/Reference/Core/Declare) * [Delegate Types](/en/official/Features/Language/Delegates) * [Enhanced Pointer Functionality](/en/official/Features/Language/Pointers) * [API Declarations](/en/official/Features/Advanced/API-Declarations) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/AddressOf.md --- # AddressOf 运算符 一元运算符,返回其操作数的函数指针引用。 语法: > **AddressOf** *procedurename*\ > **AddressOf** *instance*.*procedurename* *(twinBASIC)* *procedurename* : 需要获取地址的 [**Sub**](/official/Reference/Core/Sub)、[**Function**](/official/Reference/Core/Function) 或 [**Property**](/official/Reference/Core/Property) 过程的名称。 *instance* : *可选* (twinBASIC) 对象引用,其成员 *procedurename* 为目标。生成的指针绑定到 *instance*,因此通过该指针调用会在该特定对象上调用方法。 当过程名出现在参数列表中时,通常会*调用*该过程并传递其返回值。**AddressOf** 抑制调用,改为传递过程的地址。最常见的用途是在Windows API中安装回调——API随后从项目代码外部调用该过程,这个过程称为*回调*。 **AddressOr** 生成的值与 **LongPtr** 在位级别兼容,因此可以传递给任何需要函数指针的地方——包括使用 **As Long** 或 **As LongPtr** 类型的传统 [**Declare**](/official/Reference/Core/Declare) 参数。当目标类型为 [**Delegate**](/official/Reference/Core/Delegate) 时,编译器还会检查操作数的签名是否与委托的签名匹配。 在经典VBA中,*procedurename* 必须是当前项目标准 [**Module**](/official/Reference/Core/Module) 中的过程名称;目标参数必须为 **As Long** 类型;生成的指针只能由Basic外部的代码(如DLL)调用。twinBASIC解除了所有限制——参见下文[twinBASIC增强功能](#twinbasic-enhancements)。 ::: warning 回调内部引发的错误无法传播回外部调用者——API运行在项目的错误处理链之外。在用作 **AddressOf** 目标的任何过程顶部放置 `On Error Resume Next`(或显式错误处理程序)。 ::: ### twinBASIC增强功能 * **通过Basic间接回调。** 持有 **AddressOf** 值的委托变量可以直接调用:`Dim op As Operation = AddressOf Add: r = op(5, 6)`。经典VBA可以在过程之间传递此类指针,但无法在Basic内部通过它们调用。参见 [**Delegate**](/official/Reference/Core/Delegate)。 * **类、窗体和用户控件的成员。** **AddressOf** 接受在类、窗体或用户控件上声明的方法。通过用对象引用限定名称来获取实例方法的指针:`AddressOf myInstance.MyMethod`。生成的指针记住实例——通过它调用会分派到该对象。 * **CDecl回调。** 在目标过程和匹配的 [**Delegate**](/official/Reference/Core/Delegate)(或 [**Declare**](/official/Reference/Core/Declare) 参数)上同时标记 **CDecl**,以建模 `cdecl` 回调。经典VBA的 **AddressOf** 固定使用 `__stdcall`。参见 [API声明](/official/Features/Advanced/API-Declarations#cdecl-callbacks)。 * **无需 `FARPROC` 垫片。** 将函数指针赋值给局部变量是直接的——`Dim lpfn As LongPtr = AddressOf MyFunc`——无需编写中间转发过程。 ### 示例 在Basic内部通过类型化委托调用: ```vb Private Delegate Function Operation (ByVal A As Long, ByVal B As Long) As Long Public Function Addition(ByVal A As Long, ByVal B As Long) As Long Return A + B End Function Private Sub Demo() Dim op As Operation = AddressOf Addition Debug.Print op(5, 6) ' 11 End Sub ``` 在Win32 API中安装回调。`EnumWindows` 对每个顶层窗口调用一次 *EnumProc*: ```vb Public Declare PtrSafe Function EnumWindows Lib "user32" ( _ ByVal lpEnumFunc As LongPtr, ByVal lParam As LongPtr) As Long Public Function EnumProc(ByVal hwnd As LongPtr, ByVal lParam As LongPtr) As Long On Error Resume Next Debug.Print hwnd EnumProc = 1 ' Continue enumeration. End Function Public Sub ListTopLevelWindows() EnumWindows AddressOf EnumProc, 0 End Sub ``` 通过用对象引用限定来获取实例方法的指针: ```vb Class CFoo Public Sub Bar() Debug.Print "Bar on instance" End Sub End Class Public Sub Demo() Dim foo1 As New CFoo Dim lpfn As LongPtr = AddressOf foo1.Bar End Sub ``` ### 另请参阅 * [**Delegate** 语句](/official/Reference/Core/Delegate) * [**Declare** 语句](/official/Reference/Core/Declare) * [委托类型](/official/Features/Language/Delegates) * [增强指针功能](/official/Features/Language/Pointers) * [API声明](/official/Features/Advanced/API-Declarations) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Reference/VBA/TbExpressionService/AddStdLibraryBinder.md --- # AddStdLibraryBinder Registers the standard-library binder so compiled expressions can call the common runtime functions. Syntax: *service*.**AddStdLibraryBinder** *service* : *required* An object expression that evaluates to a **TbExpressionService** object. After **AddStdLibraryBinder** has been called, expressions compiled by *service* can reference any procedure or property in the standard runtime library --- math functions like [**Sqr**](/en/official/Reference/VBA/Math/Sqr), [**Sin**](/en/official/Reference/VBA/Math/Sin), and [**Round**](/en/official/Reference/VBA/Math/Round); string functions like [**Len**](/en/official/Reference/VBA/Strings/Len), [**Mid**](/en/official/Reference/VBA/Strings/Mid), and [**Format**](/en/official/Reference/VBA/Strings/Format); conversion functions like [**CStr**](/en/official/Reference/VBA/Conversion/CStr) and [**CInt**](/en/official/Reference/VBA/Conversion/CInt); and so on. A new **TbExpressionService** has no binders registered. Without at least one binder, compiled expressions can do little more than evaluate literal arithmetic --- any reference to a named symbol fails compilation with a run-time error. ### Example ```vb Dim Service As TbExpressionService = New TbExpressionService Service.AddStdLibraryBinder() Debug.Print Service.Compile("Sqr(2) + Sqr(3)").Evaluate() ' 3.14... Debug.Print Service.Compile("UCase(""hello"")").Evaluate() ' HELLO ``` ### See Also * [Compile](/en/official/Reference/VBA/TbExpressionService/Compile) method * [AddCustomBinderObject](/en/official/Reference/VBA/TbExpressionService/AddCustomBinderObject) method * [AddCustomBinder](/en/official/Reference/VBA/TbExpressionService/AddCustomBinder) method --- --- url: /zh/official/Reference/VBA/TbExpressionService/AddStdLibraryBinder.md --- # AddStdLibraryBinder 注册标准库绑定器,使编译表达式可以调用常用运行时函数。 语法:*service*.**AddStdLibraryBinder** *service* : *必需* 计算结果为 **TbExpressionService** 对象的对象表达式。 调用 **AddStdLibraryBinder** 后,*service* 编译的表达式可以引用标准运行时库中的任何过程或属性——数学函数如 [**Sqr**](/official/Reference/VBA/Math/Sqr)、[**Sin**](/official/Reference/VBA/Math/Sin) 和 [**Round**](/official/Reference/VBA/Math/Round);字符串函数如 [**Len**](/official/Reference/VBA/Strings/Len)、[**Mid**](/official/Reference/VBA/Strings/Mid) 和 [**Format**](/official/Reference/VBA/Strings/Format);转换函数如 [**CStr**](/official/Reference/VBA/Conversion/CStr) 和 [**CInt**](/official/Reference/VBA/Conversion/CInt) 等等。 新的 **TbExpressionService** 没有注册任何绑定器。没有至少一个绑定器,编译表达式只能执行字面量算术——任何对命名符号的引用都会因运行时错误导致编译失败。 ### 示例 ```vb Dim Service As TbExpressionService = New TbExpressionService Service.AddStdLibraryBinder() Debug.Print Service.Compile("Sqr(2) + Sqr(3)").Evaluate() ' 3.14... Debug.Print Service.Compile("UCase(""hello"")").Evaluate() ' HELLO ``` ### 另请参阅 * [Compile](/official/Reference/VBA/TbExpressionService/Compile) 方法 * [AddCustomBinderObject](/official/Reference/VBA/TbExpressionService/AddCustomBinderObject) 方法 * [AddCustomBinder](/official/Reference/VBA/TbExpressionService/AddCustomBinder) 方法 --- --- url: /en/official/Features/Advanced.md --- # Advanced Features Advanced twinBASIC features for low-level programming and system integration. ## Topics * [Multithreading](/en/official/Features/Advanced/Multithreading) - Thread safety and multithreading support * [Assembly](/en/official/Features/Advanced/Assembly) - Direct assembly insertion with Emit() * [Static Linking](/en/official/Features/Advanced/Static-Linking) - Static linking of OBJ and LIB files * [API Declarations](/en/official/Features/Advanced/API-Declarations) - Enhanced API and method declarations * [Class and Module Features](/en/official/Features/Advanced/Classes-and-Modules) - Parameterized constructors, ReadOnly, and exports --- --- url: /en/official/Reference/Core/Alias.md --- # Alias Declares an alternative name for an intrinsic type, user-defined [**Type**](/en/official/Reference/Core/Type), [**Interface**](/en/official/Reference/Core/Interface), or another **Alias**. The alias and the original type are interchangeable --- assigning between them is not a type mismatch. Comparable to `typedef` in C/C++. ::: info The **Alias** statement is a twinBASIC extension. It has no equivalent in classic VBA, where the only use of the **Alias** keyword is to name a DLL entry point in a [**Declare**](/en/official/Reference/Core/Declare) statement. ::: Syntax: > \[ **Public** | **Private** ] **Alias** *aliasname* **As** *type* **Public** : *optional* The alias is exported to the type library of an ActiveX DLL or control, so consumers in other projects see *aliasname* itself. **Private** : *optional* The alias is visible only within the project. Usages of a **Private** alias are replaced with the underlying *type* during compilation, so *aliasname* never appears in the project's type library. *aliasname* : The name of the alias. Must be a valid twinBASIC identifier. *type* : The original type. May be an intrinsic type, a user-defined [**Type**](/en/official/Reference/Core/Type), an [**Interface**](/en/official/Reference/Core/Interface), or another **Alias**. **Alias** statements are valid only in `.twin` source files (not legacy `.bas` or `.cls` files), and must appear at file scope --- outside of [**Module**](/en/official/Reference/Core/Module) and [**Class**](/en/official/Reference/Core/Class) blocks, alongside [**Interface**](/en/official/Reference/Core/Interface) and [**CoClass**](/en/official/Reference/Core/CoClass) declarations. ### Example Aliasing intrinsic types and a user-defined type: ```vb Public Type POINT x As Long y As Long End Type Public Alias POINTAPI As POINT Public Alias CBoolean As Byte Public Alias KAFFINITY As LongPtr ``` A variable declared with the alias and a variable declared with the original type are interchangeable: ```vb Dim p As POINT Dim q As POINTAPI p = q ' OK — no type mismatch. ``` ### See Also * [**Type** statement](/en/official/Reference/Core/Type) * [**Interface** statement](/en/official/Reference/Core/Interface) * [**CoClass** statement](/en/official/Reference/Core/CoClass) * [Alias Types](/en/official/Features/Language/Alias-Types) --- --- url: /zh/official/Reference/Core/Alias.md --- # Alias 为内部类型、用户自定义 [**Type**](/official/Reference/Core/Type)、[**Interface**](/official/Reference/Core/Interface) 或另一个 **Alias** 声明替代名称。别名与原始类型可互换——它们之间赋值不会产生类型不匹配。类似于C/C++中的 `typedef`。 ::: info **Alias** 语句是twinBASIC扩展。经典VBA中没有等价功能,VBA中 **Alias** 关键字的唯一用途是在 [**Declare**](/official/Reference/Core/Declare) 语句中命名DLL入口点。 ::: 语法: > \[ **Public** | **Private** ] **Alias** *aliasname* **As** *type* **Public** : *可选* 别名导出到ActiveX DLL或控件的类型库,因此其他项目的使用者可以看到 *aliasname* 本身。 **Private** : *可选* 别名仅在项目内可见。**Private** 别名的使用在编译时会被替换为底层 *type*,因此 *aliasname* 不会出现在项目的类型库中。 *aliasname* : 别名的名称。必须是有效的twinBASIC标识符。 *type* : 原始类型。可以是内部类型、用户自定义 [**Type**](/official/Reference/Core/Type)、[**Interface**](/official/Reference/Core/Interface) 或另一个 **Alias**。 **Alias** 语句仅在 `.twin` 源文件中有效(不支持传统 `.bas` 或 `.cls` 文件),且必须出现在文件作用域——在 [**Module**](/official/Reference/Core/Module) 和 [**Class**](/official/Reference/Core/Class) 块之外,与 [**Interface**](/official/Reference/Core/Interface) 和 [**CoClass**](/official/Reference/Core/CoClass) 声明并列。 ### 示例 为内部类型和用户自定义类型创建别名: ```vb Public Type POINT x As Long y As Long End Type Public Alias POINTAPI As POINT Public Alias CBoolean As Byte Public Alias KAFFINITY As LongPtr ``` 使用别名声明的变量与使用原始类型声明的变量可以互换: ```vb Dim p As POINT Dim q As POINTAPI p = q ' OK — no type mismatch. ``` ### 另请参阅 * [**Type** 语句](/official/Reference/Core/Type) * [**Interface** 语句](/official/Reference/Core/Interface) * [**CoClass** 语句](/official/Reference/Core/CoClass) * [别名类型](/official/Features/Language/Alias-Types) --- --- url: /en/official/Features/Language/Alias-Types.md --- # Alias Types An alias is an alternative name for a User-Defined Type, intrinsic type, or interface. This is similar to C/C++'s `typedef` statement. These can then be used in place of the original type and will be treated as if the original was used (would not be a type mismatch). `[Public|Private] Alias AltName As OrigName` ### Example With intrinsic types, or if you have a type such as: ```vb Public Type POINT x As Long y As Long End Type ``` You can create aliases: ```vb Public Alias POINTAPI As POINT Public Alias CBoolean As Byte Public Alias KAFFINITY As LongPtr ``` Like interfaces and coclasses, these must be placed in a .twin file, outside of `Module` and `Class` blocks. You can create aliases of other aliases. The optional `Public` and `Private` modifiers determine whether the alias is exported to the Type Library of an ActiveX DLL or Control. A `Private` alias would result in usage of it being replaced with the original type. --- --- url: /en/official/Reference/VBRUN/Constants/AlignConstants.md --- # AlignConstants Values for the **Align** property of forms and controls --- picture boxes, data controls, and toolbars --- that anchor a control to one edge of its container. | Constant | Value | Description | |----------|-------|-------------| | **vbAlignNone** | 0 | Size and location are set at design time or in code. | | **vbAlignTop** | 1 | Control is anchored to the top edge of the container. | | **vbAlignBottom** | 2 | Control is anchored to the bottom edge of the container. | | **vbAlignLeft** | 3 | Control is anchored to the left edge of the container. | | **vbAlignRight** | 4 | Control is anchored to the right edge of the container. | --- --- url: /zh/official/Reference/VBRUN/Constants/AlignConstants.md --- # AlignConstants 窗体和控件 --- 图片框、数据控件和工具栏 --- 的**Align**属性值,将控件锚定到其容器的某一边缘。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbAlignNone** | 0 | 大小和位置在设计时或代码中设置。 | | **vbAlignTop** | 1 | 控件锚定到容器的顶部边缘。 | | **vbAlignBottom** | 2 | 控件锚定到容器的底部边缘。 | | **vbAlignLeft** | 3 | 控件锚定到容器的左侧边缘。 | | **vbAlignRight** | 4 | 控件锚定到容器的右侧边缘。 | --- --- url: /en/official/Reference/VBRUN/Constants/AlignmentConstants.md --- # AlignmentConstants Text alignment values for the **Alignment** property of label, text box, and option button controls. | Constant | Value | Description | |----------|-------|-------------| | **vbLeftJustify** | 0 | Text is left-justified. | | **vbRightJustify** | 1 | Text is right-justified. | | **vbCenter** | 2 | Text is centred. | --- --- url: /zh/official/Reference/VBRUN/Constants/AlignmentConstants.md --- # AlignmentConstants 标签、文本框和选项按钮控件的**Alignment**属性的文本对齐值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbLeftJustify** | 0 | 文本左对齐。 | | **vbRightJustify** | 1 | 文本右对齐。 | | **vbCenter** | 2 | 文本居中。 | --- --- url: /en/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter.md --- # AlignmentConstantsNoCenter Text alignment values for properties whose appearance does not include a centred option --- for example, scroll-bar--aligned values or text fields that only support left/right justification. | Constant | Value | Description | |----------|-------|-------------| | **tbLeftJustify** | 0 | Text is left-justified. | | **tbRightJustify** | 1 | Text is right-justified. | --- --- url: /zh/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter.md --- # AlignmentConstantsNoCenter 外观不包括居中选项的属性的文本对齐值 --- 例如滚动条对齐值或仅支持左/右对齐的文本字段。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **tbLeftJustify** | 0 | 文本左对齐。 | | **tbRightJustify** | 1 | 文本右对齐。 | --- --- url: /en/official/Reference/VBA/HiddenModule/AllocMem.md --- # AllocMem Allocates a block of native memory and returns its address. Syntax: **AllocMem(** *BytesToAlloc* **)** **As LongPtr** *BytesToAlloc* : *required* **Long**. The size of the block to allocate, in bytes. The contents of the new block are unspecified. Release the block with [**FreeMem**](/en/official/Reference/VBA/HiddenModule/FreeMem) when no longer needed; passing the address to anything else (e.g. a Win32 `HeapFree`) will not work, since the block is owned by the twinBASIC runtime's heap. If the allocation fails, **AllocMem** raises a run-time error. ### Example ```vb Dim Buffer As LongPtr = AllocMem(1024) PutMem4 Buffer, &HDEADBEEF '... use Buffer ... FreeMem Buffer ``` ### See Also * [FreeMem](/en/official/Reference/VBA/HiddenModule/FreeMem) procedure * [vbaCopyBytes](/en/official/Reference/VBA/HiddenModule/vbaCopyBytes) function --- --- url: /zh/official/Reference/VBA/HiddenModule/AllocMem.md --- # AllocMem 分配一块本机内存并返回其地址。 语法:**AllocMem(** *BytesToAlloc* **)** **As LongPtr** *BytesToAlloc* : *必需* **Long**。要分配的块大小,以字节为单位。 新块的内容未指定。不再需要时使用[**FreeMem**](/official/Reference/VBA/HiddenModule/FreeMem)释放该块;将地址传递给其他任何东西(例如Win32的`HeapFree`)将不起作用,因为该块由twinBASIC运行时的堆拥有。 如果分配失败,**AllocMem**将引发运行时错误。 ### 示例 ```vb Dim Buffer As LongPtr = AllocMem(1024) PutMem4 Buffer, &HDEADBEEF '... use Buffer ... FreeMem Buffer ``` ### 另请参阅 * [FreeMem](/official/Reference/VBA/HiddenModule/FreeMem)过程 * [vbaCopyBytes](/official/Reference/VBA/HiddenModule/vbaCopyBytes)函数 --- --- url: /en/official/Reference/VBRUN/AmbientProperties.md --- # AmbientProperties class The **AmbientProperties** object exposes information about the environment in which a control is hosted. The container --- a form, a property page, the IDE designer surface --- populates this object with hints about its appearance, locale, and operating mode so that an embedded control can adapt itself to fit in. Every property is read-only: the container, not the control, decides what these values should be. ## Detecting design-time versus run-time A control often needs to behave differently while it is being placed on a designer surface than when it is actually running inside an application. [**UserMode**](/en/official/Reference/VBRUN/AmbientProperties/UserMode) returns **False** in the IDE designer and **True** at run time, and [**UIDead**](/en/official/Reference/VBRUN/AmbientProperties/UIDead) becomes **True** while execution is paused under the debugger so that a control knows not to repaint or respond to input. [**ShowGrabHandles**](/en/official/Reference/VBRUN/AmbientProperties/ShowGrabHandles) and [**ShowHatching**](/en/official/Reference/VBRUN/AmbientProperties/ShowHatching) tell a control whether the container would like it to draw the usual selection adornments while it is being edited. ```vb Sub AdaptToHost(ByVal Host As AmbientProperties) If Host.UserMode Then ' Running in the host application — render normally. Else ' Embedded in a designer — show edit-time decorations instead. End If End Sub ``` ## Visual defaults from the container The container suggests a default colour scheme and typeface so that embedded controls fit in with their surroundings. [**BackColor**](/en/official/Reference/VBRUN/AmbientProperties/BackColor) and [**ForeColor**](/en/official/Reference/VBRUN/AmbientProperties/ForeColor) supply the suggested background and foreground colours as **OLE\_COLOR** values, [**Font**](/en/official/Reference/VBRUN/AmbientProperties/Font) returns the suggested **stdole.IFontDisp**, and [**Palette**](/en/official/Reference/VBRUN/AmbientProperties/Palette) returns a hint palette as an **stdole.IPictureDisp**. [**TextAlign**](/en/official/Reference/VBRUN/AmbientProperties/TextAlign) reports the container's preferred text alignment, and [**RightToLeft**](/en/official/Reference/VBRUN/AmbientProperties/RightToLeft) is **True** when the container is laid out for a right-to-left language. ## Layout and other UI hints [**ScaleUnits**](/en/official/Reference/VBRUN/AmbientProperties/ScaleUnits) names the unit of measure the container uses to size itself --- for example `"Twip"` or `"Pixel"`. [**SupportsMnemonics**](/en/official/Reference/VBRUN/AmbientProperties/SupportsMnemonics) is **True** when the container will dispatch keyboard mnemonics --- the underlined letters following an `&` --- to its controls. [**DisplayAsDefault**](/en/official/Reference/VBRUN/AmbientProperties/DisplayAsDefault) is **True** if the container is treating this control as its default control, so the control can paint itself with a heavier border. [**MessageReflect**](/en/official/Reference/VBRUN/AmbientProperties/MessageReflect) indicates whether the container reflects window messages addressed to the control back to the control's own message handler. ## Locale and identity [**LocaleID**](/en/official/Reference/VBRUN/AmbientProperties/LocaleID) returns the Locale ID of the container, so a control can format text and numbers consistently with its host. [**DisplayName**](/en/official/Reference/VBRUN/AmbientProperties/DisplayName) returns the name the container has assigned to the control --- a useful string for error messages or property browsers. ## Members * [BackColor](/en/official/Reference/VBRUN/AmbientProperties/BackColor) -- returns the container's suggested background colour * [DisplayAsDefault](/en/official/Reference/VBRUN/AmbientProperties/DisplayAsDefault) -- returns whether the container is treating this control as its default * [DisplayName](/en/official/Reference/VBRUN/AmbientProperties/DisplayName) -- returns the name the container has assigned to the control * [Font](/en/official/Reference/VBRUN/AmbientProperties/Font) -- returns the container's suggested font * [ForeColor](/en/official/Reference/VBRUN/AmbientProperties/ForeColor) -- returns the container's suggested foreground colour * [LocaleID](/en/official/Reference/VBRUN/AmbientProperties/LocaleID) -- returns the container's Locale ID * [MessageReflect](/en/official/Reference/VBRUN/AmbientProperties/MessageReflect) -- returns whether the container reflects window messages back to the control * [Palette](/en/official/Reference/VBRUN/AmbientProperties/Palette) -- returns the container's suggested colour palette * [RightToLeft](/en/official/Reference/VBRUN/AmbientProperties/RightToLeft) -- returns whether the container is laid out right-to-left * [ScaleUnits](/en/official/Reference/VBRUN/AmbientProperties/ScaleUnits) -- returns the unit of measure used by the container * [ShowGrabHandles](/en/official/Reference/VBRUN/AmbientProperties/ShowGrabHandles) -- returns whether the container wants the control to draw selection grab handles * [ShowHatching](/en/official/Reference/VBRUN/AmbientProperties/ShowHatching) -- returns whether the container wants the control to draw a selection hatching pattern * [SupportsMnemonics](/en/official/Reference/VBRUN/AmbientProperties/SupportsMnemonics) -- returns whether the container will dispatch keyboard mnemonics to controls * [TextAlign](/en/official/Reference/VBRUN/AmbientProperties/TextAlign) -- returns the container's preferred text alignment * [UIDead](/en/official/Reference/VBRUN/AmbientProperties/UIDead) -- returns whether the user interface is non-responsive (for example, paused in the debugger) * [UserMode](/en/official/Reference/VBRUN/AmbientProperties/UserMode) -- returns **True** at run time and **False** when hosted in a designer --- --- url: /zh/official/Reference/VBRUN/AmbientProperties.md --- # AmbientProperties 类 **AmbientProperties**对象公开控件宿主环境的信息。容器——窗体、属性页、IDE设计器表面——填充此对象,提供有关其外观、区域设置和操作模式的提示,使嵌入控件能够自行适应。每个属性均为只读:由容器而非控件决定这些值。 ## 检测设计时与运行时 控件在设计器表面上放置时通常需要与在应用程序中实际运行时表现不同。[**UserMode**](/official/Reference/VBRUN/AmbientProperties/UserMode)在IDE设计器中返回**False**,在运行时返回**True**;[**UIDead**](/official/Reference/VBRUN/AmbientProperties/UIDead)在调试器暂停执行时变为**True**,使控件知道不要重绘或响应输入。[**ShowGrabHandles**](/official/Reference/VBRUN/AmbientProperties/ShowGrabHandles)和[**ShowHatching**](/official/Reference/VBRUN/AmbientProperties/ShowHatching)告诉控件容器是否希望它在被编辑时绘制常规的选择装饰。 ```vb Sub AdaptToHost(ByVal Host As AmbientProperties) If Host.UserMode Then ' 在宿主应用程序中运行——正常渲染。 Else ' 嵌入在设计器中——改为显示编辑时装饰。 End If End Sub ``` ## 容器的视觉默认值 容器建议默认配色方案和字体,使嵌入控件与周围环境协调。[**BackColor**](/official/Reference/VBRUN/AmbientProperties/BackColor)和[**ForeColor**](/official/Reference/VBRUN/AmbientProperties/ForeColor)以**OLE\_COLOR**值提供建议的背景色和前景色,[**Font**](/official/Reference/VBRUN/AmbientProperties/Font)返回建议的**stdole.IFontDisp**,[**Palette**](/official/Reference/VBRUN/AmbientProperties/Palette)以**stdole.IPictureDisp**返回提示调色板。[**TextAlign**](/official/Reference/VBRUN/AmbientProperties/TextAlign)报告容器首选的文本对齐方式,[**RightToLeft**](/official/Reference/VBRUN/AmbientProperties/RightToLeft)在容器为从右到左语言布局时为**True**。 ## 布局和其他UI提示 [**ScaleUnits**](/official/Reference/VBRUN/AmbientProperties/ScaleUnits)命名容器用于自身尺寸的度量单位——例如"Twip"或"Pixel"。[**SupportsMnemonics**](/official/Reference/VBRUN/AmbientProperties/SupportsMnemonics)在容器将键盘助记符——&后的带下划线字母——分派给控件时为**True**。[**DisplayAsDefault**](/official/Reference/VBRUN/AmbientProperties/DisplayAsDefault)在容器将此控件视为其默认控件时为**True**,控件可以用更粗的边框绘制自身。[**MessageReflect**](/official/Reference/VBRUN/AmbientProperties/MessageReflect)指示容器是否将发送给控件的窗口消息反射回控件自身的消息处理器。 ## 区域设置和标识 [**LocaleID**](/official/Reference/VBRUN/AmbientProperties/LocaleID)返回容器的区域设置ID,使控件可以与其宿主一致地格式化文本和数字。[**DisplayName**](/official/Reference/VBRUN/AmbientProperties/DisplayName)返回容器分配给控件的名称——用于错误消息或属性浏览器的实用字符串。 ## 成员 * [BackColor](/official/Reference/VBRUN/AmbientProperties/BackColor) -- 返回容器建议的背景色 * [DisplayAsDefault](/official/Reference/VBRUN/AmbientProperties/DisplayAsDefault) -- 返回容器是否将此控件视为默认控件 * [DisplayName](/official/Reference/VBRUN/AmbientProperties/DisplayName) -- 返回容器分配给控件的名称 * [Font](/official/Reference/VBRUN/AmbientProperties/Font) -- 返回容器建议的字体 * [ForeColor](/official/Reference/VBRUN/AmbientProperties/ForeColor) -- 返回容器建议的前景色 * [LocaleID](/official/Reference/VBRUN/AmbientProperties/LocaleID) -- 返回容器的区域设置ID * [MessageReflect](/official/Reference/VBRUN/AmbientProperties/MessageReflect) -- 返回容器是否将窗口消息反射回控件 * [Palette](/official/Reference/VBRUN/AmbientProperties/Palette) -- 返回容器建议的调色板 * [RightToLeft](/official/Reference/VBRUN/AmbientProperties/RightToLeft) -- 返回容器是否为从右到左布局 * [ScaleUnits](/official/Reference/VBRUN/AmbientProperties/ScaleUnits) -- 返回容器使用的度量单位 * [ShowGrabHandles](/official/Reference/VBRUN/AmbientProperties/ShowGrabHandles) -- 返回容器是否要求控件绘制选择抓取手柄 * [ShowHatching](/official/Reference/VBRUN/AmbientProperties/ShowHatching) -- 返回容器是否要求控件绘制选择阴影图案 * [SupportsMnemonics](/official/Reference/VBRUN/AmbientProperties/SupportsMnemonics) -- 返回容器是否将键盘助记符分派给控件 * [TextAlign](/official/Reference/VBRUN/AmbientProperties/TextAlign) -- 返回容器首选的文本对齐方式 * [UIDead](/official/Reference/VBRUN/AmbientProperties/UIDead) -- 返回用户界面是否无响应(例如在调试器中暂停) * [UserMode](/official/Reference/VBRUN/AmbientProperties/UserMode) -- 运行时返回**True**,在设计器中宿主时返回**False** --- --- url: /en/official/Reference/CustomControls/Styles/Anchors.md --- # Anchors class Determines which sides of a control are attached to its parent container when the container is resized. A control with both **Left** and **Right** set to **True**, for example, keeps its left and right edges at the same distance from the container's edges, stretching horizontally as the container grows. Controls receive this object through their inherited **Anchors** property. The default is **Left**=**True**, **Top**=**True**, **Right**=**False**, **Bottom**=**False** --- the control stays at the same offset from the upper-left corner of the container and does not resize. To make a control fill the bottom of its container as the form is resized, anchor it to **Left**, **Right**, and **Bottom**. ```vb With txtNotes.Anchors .Left = True .Top = True .Right = True .Bottom = True End With ``` ## Properties ### Bottom When **True**, the control's bottom edge stays at the same distance from the container's bottom edge. **Boolean**, default **False**. ### Left When **True**, the control's left edge stays at the same distance from the container's left edge. **Boolean**, default **True**. ### Right When **True**, the control's right edge stays at the same distance from the container's right edge. **Boolean**, default **False**. ### Top When **True**, the control's top edge stays at the same distance from the container's top edge. **Boolean**, default **True**. ## Events ### OnChanged Raised whenever any of the four anchor flags is assigned. The hosting control listens for this event and re-applies the docking layout. Application code does not normally subscribe directly. --- --- url: /zh/official/Reference/CustomControls/Styles/Anchors.md --- # Anchors 类 决定容器调整大小时控件的哪些边附着到其父容器。例如,**Left** 和 **Right** 都设为 **True** 的控件保持其左右边缘与容器边缘等距,容器增长时水平拉伸。控件通过其继承的 **Anchors** 属性接收此对象。 默认为 **Left**=**True**、**Top**=**True**、**Right**=**False**、**Bottom**=**False**——控件保持与容器左上角相同的偏移且不调整大小。要使控件在窗体调整大小时填充容器底部,将其锚定到 **Left**、**Right** 和 **Bottom**。 ```vb With txtNotes.Anchors .Left = True .Top = True .Right = True .Bottom = True End With ``` ## 属性 ### Bottom 当 **True** 时,控件底边与容器底边保持等距。**Boolean**,默认 **False**。 ### Left 当 **True** 时,控件左边与容器左边保持等距。**Boolean**,默认 **True**。 ### Right 当 **True** 时,控件右边与容器右边保持等距。**Boolean**,默认 **False**。 ### Top 当 **True** 时,控件顶边与容器顶边保持等距。**Boolean**,默认 **True**。 ## 事件 ### OnChanged 四个锚定标志中任一个被赋值时触发。承载控件监听此事件并重新应用停靠布局。应用程序代码通常不直接订阅。 --- --- url: /en/official/Reference/Core/And.md --- # And operator Used to perform a bitwise conjunction on two expressions. Syntax: > *result* **=** *expression1* **And** *expression2* *result* : Any numeric variable. *expression1*, *expression2* : Any expressions. If both expressions evaluate to **True**, *result* is **True**. If either expression evaluates to **False**, *result* is **False**. The following table illustrates how *result* is determined: | If *expression1* is | And *expression2* is | The *result* is | | :------------------ | :------------------- | :-------------- | | **True** | **True** | **True** | | **True** | **False** | **False** | | **True** | **Null** | **Null** | | **False** | **True** | **False** | | **False** | **False** | **False** | | **False** | **Null** | **False** | | **Null** | **True** | **Null** | | **Null** | **False** | **False** | | **Null** | **Null** | **Null** | The **And** operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in *result* according to the following table: | If bit in *expression1* is | And bit in *expression2* is | The *result* is | | :------------------------: | :-------------------------: | :-------------: | | 0 | 0 | 0 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | ::: info **And** evaluates *both* operands every time, even when *expression1* alone determines the result. Use [**AndAlso**](/en/official/Reference/Core/AndAlso) for short-circuit evaluation --- for example, when *expression2* is expensive, has side effects, or would fail without the guard provided by *expression1*. ::: ### Example This example uses the **And** operator to perform a logical conjunction on two expressions. ```vb Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B And B > C ' Returns True. MyCheck = B > A And B > C ' Returns False. MyCheck = A > B And B > D ' Returns Null. MyCheck = A And B ' Returns 8 (bitwise comparison). ``` ### See Also * [**AndAlso** operator](/en/official/Reference/Core/AndAlso) * [**Or** operator](/en/official/Reference/Core/Or) * [**Not** operator](/en/official/Reference/Core/Not) * [**Xor** operator](/en/official/Reference/Core/Xor) * [**Eqv** operator](/en/official/Reference/Core/Eqv) * [**Imp** operator](/en/official/Reference/Core/Imp) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/And.md --- # And 运算符 用于对两个表达式执行按位合取运算。 语法: > *result* **=** *expression1* **And** *expression2* *result* : 任意数值变量。 *expression1*, *expression2* : 任意表达式。 如果两个表达式求值均为 **True**,则 *result* 为 **True**。如果任一表达式求值为 **False**,则 *result* 为 **False**。下表说明了 *result* 的确定方式: | 如果 *expression1* 为 | 且 *expression2* 为 | 则 *result* 为 | |:-----|:-----|:-----| | **True** | **True** | **True** | | **True** | **False** | **False** | | **True** | **Null** | **Null** | | **False** | **True** | **False** | | **False** | **False** | **False** | | **False** | **Null** | **False** | | **Null** | **True** | **Null** | | **Null** | **False** | **False** | | **Null** | **Null** | **Null** | **And** 运算符对两个数值表达式中相同位置的位执行按位比较,并根据下表在 *result* 中设置相应的位: | 如果 *expression1* 中的位为 | 且 *expression2* 中的位为 | 则 *result* 为 | |:-----:|:-----:|:-----:| | 0 | 0 | 0 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | ::: info **And** 每次都会求值*两个*操作数,即使仅 *expression1* 就能确定结果。使用 [**AndAlso**](/official/Reference/Core/AndAlso) 进行短路求值——例如,当 *expression2* 计算开销大、有副作用,或在没有 *expression1* 提供保护时会失败的情况。 ::: ### 示例 本示例使用 **And** 运算符对两个表达式执行逻辑合取运算。 ```vb Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B And B > C ' Returns True. MyCheck = B > A And B > C ' Returns False. MyCheck = A > B And B > D ' Returns Null. MyCheck = A And B ' Returns 8 (bitwise comparison). ``` ### 另请参阅 * [**AndAlso** 运算符](/official/Reference/Core/AndAlso) * [**Or** 运算符](/official/Reference/Core/Or) * [**Not** 运算符](/official/Reference/Core/Not) * [**Xor** 运算符](/official/Reference/Core/Xor) * [**Eqv** 运算符](/official/Reference/Core/Eqv) * [**Imp** 运算符](/official/Reference/Core/Imp) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Reference/Core/AndAlso.md --- # AndAlso operator Performs a short-circuit logical conjunction of two **Boolean** expressions. If the left operand evaluates to **False**, the right operand is not evaluated. ::: info **AndAlso** is a twinBASIC extension. The classic [**And**](/en/official/Reference/Core/And) operator always evaluates both operands and returns a bitwise result; **AndAlso** evaluates the right operand only when needed and always returns a **Boolean**. ::: Syntax: > *result* **=** *expression1* **AndAlso** *expression2* *result* : A **Boolean** variable. *expression1*, *expression2* : Any expressions that evaluate to **Boolean** (or are coercible to **Boolean**). If *expression1* is **False**, *result* is **False** and *expression2* is not evaluated. Otherwise *expression2* is evaluated and its **Boolean** value becomes *result*. This is the standard "short-circuit AND". It is useful when *expression2* depends on *expression1* having succeeded --- for example, a null-check guarding a property access. ### Example Guarding a property access by first verifying the object reference: ```vb If obj IsNot Nothing AndAlso obj.IsReady Then ' Safe to call - obj.IsReady is only evaluated when obj is non-Nothing. obj.DoWork End If ``` Compare with the equivalent code using **And**, which would crash if `obj` were **Nothing** because both operands are always evaluated: ```vb ' WRONG - obj.IsReady is evaluated even when obj is Nothing. If obj IsNot Nothing And obj.IsReady Then obj.DoWork End If ``` ### See Also * [**OrElse** operator](/en/official/Reference/Core/OrElse) * [**And** operator](/en/official/Reference/Core/And) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/AndAlso.md --- # AndAlso 运算符 对两个 **Boolean** 表达式执行短路逻辑合取运算。如果左操作数求值为 **False**,则不再对右操作数求值。 ::: info **AndAlso** 是twinBASIC扩展。经典 [**And**](/official/Reference/Core/And) 运算符总是对两个操作数求值并返回按位结果;**AndAlso** 仅在需要时才对右操作数求值,且始终返回 **Boolean**。 ::: 语法: > *result* **=** *expression1* **AndAlso** *expression2* *result* : **Boolean** 变量。 *expression1*, *expression2* : 任何求值为 **Boolean**(或可强制转换为 **Boolean**)的表达式。 如果 *expression1* 为 **False**,则 *result* 为 **False**,且不再求值 *expression2*。否则对 *expression2* 求值,其 **Boolean** 值即为 *result*。 这是标准的"短路AND"。当 *expression2* 依赖于 *expression1* 成功时非常有用——例如,空值检查保护属性访问。 ### 示例 通过先验证对象引用来保护属性访问: ```vb If obj IsNot Nothing AndAlso obj.IsReady Then ' Safe to call - obj.IsReady is only evaluated when obj is non-Nothing. obj.DoWork End If ``` 与使用 **And** 的等价代码对比,当 `obj` 为 **Nothing** 时会崩溃,因为两个操作数总是被求值: ```vb ' WRONG - obj.IsReady is evaluated even when obj is Nothing. If obj IsNot Nothing And obj.IsReady Then obj.DoWork End If ``` ### 另请参阅 * [**OrElse** 运算符](/official/Reference/Core/OrElse) * [**And** 运算符](/official/Reference/Core/And) * [运算符](/official/Reference/Operators) --- --- url: /en/packages/vbccr/ranges/animation.md description: >- Animation Control - VBCCR Development Manual, complete API reference based on source code --- # Animation Control Wraps the SysAnimate32 system animation control for playing silent AVI animations. ## Enumerations ### CCBackStyleConstants See common enumerations. ## Properties ### AutoPlay ```vb Property Get AutoPlay() As Boolean Property Let AutoPlay(ByVal Value As Boolean) ``` Auto play; starts playing immediately after the control is created. ### BackStyle ```vb Property Get BackStyle() As CCBackStyleConstants Property Let BackStyle(ByVal Value As CCBackStyleConstants) ``` Background style, transparent or opaque. ### Center ```vb Property Get Center() As Boolean Property Let Center(ByVal Value As Boolean) ``` Whether to center the AVI animation display. ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` Right-to-left display direction. ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` Right-to-left mirrored layout. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` Right-to-left mode. See common enumerations. ### hWnd ```vb Property Get hWnd() As LongPtr ``` Window handle of the animation control. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Window handle of the user control. ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` Font. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` Mouse pointer style. See common enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` Custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Whether to enable mouse enter/leave tracking. ### Playing ```vb Property Get Playing() As Boolean ``` Whether the animation is currently playing. Read-only. ### Name ```vb Property Get Name() As String ``` Control name. Read-only. ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` Custom data. ### Parent ```vb Property Get Parent() As Object ``` Parent object. Read-only. ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` Container object. ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` Left position. ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` Top position. ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` Width. ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` Height. ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` Whether the control is visible. ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` Tooltip text. ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` Help context ID. ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "What's This" help ID. ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` Drag icon. ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` Drag mode. ## Methods ### Play ```vb Public Sub Play(Optional ByVal FromFrame As Variant, Optional ByVal ToFrame As Variant, Optional ByVal RepeatCount As Variant) ``` Plays the animation. Can specify the start frame, end frame, and repeat count. ### StopPlay ```vb Public Sub StopPlay() ``` Stops playing the animation. ### LoadFile ```vb Public Sub LoadFile(ByVal PathName As String) ``` Loads an AVI animation from a file. ### LoadRes ```vb Public Sub LoadRes(ByVal ResourceID As Variant) ``` Loads an AVI animation from a resource. Supports string or numeric resource IDs. ### Unload ```vb Public Sub Unload() ``` Unloads the current animation. ### Refresh ```vb Public Sub Refresh() ``` Forces the control to repaint. ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag-and-drop operation. ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` Starts, ends, or cancels a drag operation. ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` Adjusts the Z-order. ### SetFocus ```vb Public Sub SetFocus() ``` Sets focus. ### Move ```vb Public Sub Move(ByVal Left As Single, Optional ByVal Top As Variant, Optional ByVal Width As Variant, Optional ByVal Height As Variant) ``` Moves and resizes the control. ## Events ### Click ```vb Public Event Click() ``` Click. ### DblClick ```vb Public Event DblClick() ``` Double-click. ### Change ```vb Public Event Change() ``` Fired when the animation state changes. ### PreviewKeyDown ```vb Public Event PreviewKeyDown(KeyCode As Integer, Shift As Integer) ``` Preview key event, fired before KeyDown. ### PreviewKeyUp ```vb Public Event PreviewKeyUp(KeyCode As Integer, Shift As Integer) ``` Preview key up event, fired before KeyUp. ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` Key pressed. ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` Key released. ### KeyPress ```vb Public Event KeyPress(KeyAscii As Integer) ``` Key character. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Mouse button pressed. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Mouse moved. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Mouse button released. ### MouseEnter ```vb Public Event MouseEnter() ``` Mouse entered the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Mouse left the control. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE drag-and-drop completed. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE drag-and-drop drop. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE drag-and-drop hover. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE give feedback. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE set data. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE start drag. ## Code Examples ### Basic Usage ```vb ' Load and play an AVI animation Animation1.LoadFile "C:\Icons\filecopy.avi" Animation1.AutoPlay = True ' Play from frame 5 to frame 20, repeat 3 times Animation1.Play 5, 20, 3 ' Stop playing Animation1.StopPlay ' Load from resource Animation1.LoadRes 101 ' Unload animation Animation1.Unload ``` --- --- url: /en/official/Reference/VB/App.md --- # App class The **App** class wraps the running application's identity and version metadata, plus a small amount of process-level state (the module handle, the main thread ID, whether the process is running inside the twinBASIC IDE or with elevated privileges, …). It is a singleton --- there is exactly one **App** instance per process, owned by the runtime and exposed through the global **App** property of the [**Global**](/en/official/Reference/VB/Global/) object. Code reaches it without qualification: ```vb Debug.Print "Running from " & App.Path Debug.Print "Version " & App.Major & "." & App.Minor & "." & App.Revision & "." & App.Build If App.PrevInstance Then MsgBox "Another instance is already running.", vbExclamation End End If App.HelpFile = App.Path & "\help.chm" ``` Most properties are read-only and are populated from the project settings (compiled into the executable's Win32 `VERSIONINFO` resource) at build time. The few read/write properties --- [**Title**](#title) and [**HelpFile**](#helpfile) --- let code change a small amount of run-time state that other parts of the runtime (notably the form caption defaults and the **F1** help dispatcher) consult. ## Singleton and access **App** is not creatable: there is no `New App` and no public coclass to instantiate. The runtime exposes the singleton through the [**App**](/en/official/Reference/VB/Global/#app) property on the [**Global**](/en/official/Reference/VB/Global/) app-object, which is itself accessible without qualification. References returned by **App** are cached and stable for the lifetime of the process. ## File and module location [**Path**](#path) and [**ModulePath**](#modulepath) describe where the executable lives: * [**Path**](#path) returns the folder containing the EXE, with no trailing backslash (e.g. `"C:\Program Files\MyApp"`). * [**ModulePath**](#modulepath) returns the full path to the EXE itself (e.g. `"C:\Program Files\MyApp\MyApp.exe"`). * [**EXEName**](#exename) returns the EXE's base name without the extension (e.g. `"MyApp"`). When the project is running inside the twinBASIC IDE --- `App.IsInIDE` is **True** --- [**Path**](#path) is the folder of the *project file* rather than of a compiled EXE, so it remains useful as a "where the application is" anchor for opening relative resources at design time. [**LastBuildPath**](#lastbuildpath) is a twinBASIC-specific extension that records the path the most recent IDE build wrote its EXE to --- useful for build scripts that need to chain steps after an IDE build. ## Version metadata The version-info properties read straight from the EXE's `VERSIONINFO` resource: * [**Major**](#major), [**Minor**](#minor), [**Revision**](#revision), and [**Build**](#build) -- the four parts of the four-part version number set in the project's *Make* tab. * [**Comments**](#comments), [**CompanyName**](#companyname), [**FileDescription**](#filedescription), [**LegalCopyright**](#legalcopyright), [**LegalTrademarks**](#legaltrademarks), and [**ProductName**](#productname) -- the standard text fields of the same resource. * [**Title**](#title) -- the friendly application title shown in tasklist and message-box defaults; readable and writable. [**hInstance**](#hinstance) and [**ThreadID**](#threadid) expose the underlying Win32 module handle and the ID of the application's main thread --- useful for interop with Windows API functions that need either. ## Properties ### Build The **Build** component of the application's four-part version number, as set on the project's *Make* tab. **Integer**, read-only. ### Comments The free-form **Comments** field of the application's `VERSIONINFO` resource. **String**, read-only. ### CompanyName The **CompanyName** field of the application's `VERSIONINFO` resource. **String**, read-only. ### EXEName The base name of the executable --- the file name minus its `.exe` extension and any directory component. **String**, read-only. When running inside the IDE, this is the project's compile-time output name rather than the IDE host's name. ### FileDescription The **FileDescription** field of the application's `VERSIONINFO` resource. **String**, read-only. ### HelpFile The full path to the application's help file (`.hlp` or `.chm`). **String**, readable and writable. The runtime consults this property when a control's [**HelpContextID**](/en/official/Reference/VB/CheckBox/#helpcontextid) is non-zero and the user presses **F1**, and when application code calls `MsgBox` with a help-file argument. ### hInstance The Win32 module handle (`HINSTANCE`) for the executable. **LongPtr**, read-only. Useful when calling Windows API functions that load resources or create windows on the application's behalf. ### IsElevated **True** if the process is running with administrative privileges (a "Run as administrator" elevation token), **False** otherwise. **Boolean**, read-only. ### IsInIDE **True** if the running process is the twinBASIC IDE host rather than a stand-alone compiled executable. **Boolean**, read-only. Useful for code paths that should only run at design time, or for diagnostic logging that should be suppressed in shipping builds. ### LastBuildPath The full path that the IDE wrote the most recent build to. **String**, read-only. Empty when the IDE has not yet produced a build during the current session. twinBASIC-specific --- VB6 had no equivalent. ### LegalCopyright The **LegalCopyright** field of the application's `VERSIONINFO` resource. **String**, read-only. ### LegalTrademarks The **LegalTrademarks** field of the application's `VERSIONINFO` resource. **String**, read-only. ### LogMode The current logging mode, as a member of [**LogModeConstants**](/en/official/Reference/VBRUN/Constants/LogModeConstants). Read-only. ::: info twinBASIC currently reports only **vbLogOff** and **vbLogAuto**, distinguishing IDE-detection cases. The other VB6 logging modes (file, NT event log) are not yet honoured. ::: ### LogPath ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### Major The **Major** component of the application's four-part version number. **Integer**, read-only. ### Minor The **Minor** component of the application's four-part version number. **Integer**, read-only. ### ModulePath The full path to the executable file. **String**, read-only. This is what `GetModuleFileName(App.hInstance, …)` would return. ### NonModalAllowed ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### OleRequestPendingMsgText ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### OleRequestPendingMsgTitle ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### OleRequestPendingTimeout ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### OleServerBusyMsgText ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### OleServerBusyMsgTitle ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### OleServerBusyRaiseError ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### OleServerBusyTimeout ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### Path The folder containing the executable, with no trailing backslash. **String**, read-only. When running inside the IDE, this is the folder containing the project file rather than the IDE host's folder, so code that opens files relative to the application location works identically at design time and at run time. ### PrevInstance **True** if another instance of the application is already running, **False** otherwise. **Boolean**, read-only. Typically tested at startup so the second instance can bring the first to the foreground or exit gracefully. ### ProductName The **ProductName** field of the application's `VERSIONINFO` resource. **String**, read-only. ### RetainedProject ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### Revision The **Revision** component of the application's four-part version number. **Integer**, read-only. ### StartMode ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### TaskVisible ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### ThreadID The Win32 thread ID of the application's main (UI) thread. **Long**, read-only. ### Title The application title shown to the OS (in the tasklist) and used as the default title for `MsgBox`, `InputBox`, and other system dialogs. **String**, readable and writable. Defaults to the executable's [**FileDescription**](#filedescription) (or [**EXEName**](#exename) if no description is set). ### UnattendedApp ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ## Methods ### LogEvent ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: Syntax: *object*.**LogEvent** *LogBuffer*, *EventType* ### StartLogging ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: Syntax: *object*.**StartLogging** *LogTarget*, *LogModes* --- --- url: /zh/official/Reference/VB/App.md --- # App 类 **App**类包装运行中应用程序的标识和版本元数据,以及少量进程级状态(模块句柄、主线程ID、进程是否在twinBASIC IDE内运行或具有提升权限等)。它是单例——每个进程恰好有一个**App**实例,由运行时拥有,通过[**Global**](/official/Reference/VB/Global/)对象的全局**App**属性公开。代码无需限定即可访问: ```vb Debug.Print "Running from " & App.Path Debug.Print "Version " & App.Major & "." & App.Minor & "." & App.Revision & "." & App.Build If App.PrevInstance Then MsgBox "Another instance is already running.", vbExclamation End End If App.HelpFile = App.Path & "\help.chm" ``` 大多数属性为只读,在构建时从项目设置填充到可执行文件的Win32 `VERSIONINFO`资源中。少数读/写属性——[**Title**](#title)和[**HelpFile**](#helpfile)——允许代码更改少量运行时状态,运行时的其他部分(特别是窗体标题默认值和**F1**帮助分派器)会查询这些状态。 ## 单例和访问 **App**不可创建:没有`New App`,也没有可实例化的公共coclass。运行时通过[**Global**](/official/Reference/VB/Global/)应用对象上的[**App**](/official/Reference/VB/Global/#app)属性公开此单例,该对象本身无需限定即可访问。**App**返回的引用在进程生命周期内被缓存且稳定。 ## 文件和模块位置 [**Path**](#path)和[**ModulePath**](#modulepath)描述可执行文件所在位置: * [**Path**](#path)返回包含EXE的文件夹,无尾部反斜杠(例如`"C:\Program Files\MyApp"`)。 * [**ModulePath**](#modulepath)返回EXE本身的完整路径(例如`"C:\Program Files\MyApp\MyApp.exe"`)。 * [**EXEName**](#exename)返回EXE的不含扩展名的基本名称(例如`"MyApp"`)。 当项目在twinBASIC IDE中运行时——`App.IsInIDE`为**True**——[**Path**](#path)是*项目文件*的文件夹而非已编译EXE的文件夹,因此它仍然可用作"应用程序所在位置"的锚点,用于在设计时打开相对路径的资源。 [**LastBuildPath**](#lastbuildpath)是twinBASIC特有的扩展,记录最近IDE构建写入EXE的路径——对于需要在IDE构建后链接步骤的构建脚本很有用。 ## 版本元数据 版本信息属性直接从EXE的`VERSIONINFO`资源读取: * [**Major**](#major)、[**Minor**](#minor)、[**Revision**](#revision)和[**Build**](#build)——项目*Make*选项卡中设置的四部分版本号的四个组成部分。 * [**Comments**](#comments)、[**CompanyName**](#companyname)、[**FileDescription**](#filedescription)、[**LegalCopyright**](#legalcopyright)、[**LegalTrademarks**](#legaltrademarks)和[**ProductName**](#productname)——同一资源的标准文本字段。 * [**Title**](#title)——在任务列表和消息框默认值中显示的友好应用程序标题;可读可写。 [**hInstance**](#hinstance)和[**ThreadID**](#threadid)公开底层Win32模块句柄和应用程序主线程的ID——对于需要它们之一的Windows API函数互操作很有用。 ## 属性 ### Build 应用程序四部分版本号的**Build**组件,在项目*Make*选项卡中设置。**Integer**,只读。 ### Comments 应用程序`VERSIONINFO`资源的自由格式**Comments**字段。**String**,只读。 ### CompanyName 应用程序`VERSIONINFO`资源的**CompanyName**字段。**String**,只读。 ### EXEName 可执行文件的基本名称——文件名减去其`.exe`扩展名和任何目录部分。**String**,只读。在IDE内运行时,这是项目的编译时输出名称而非IDE宿主的名称。 ### FileDescription 应用程序`VERSIONINFO`资源的**FileDescription**字段。**String**,只读。 ### HelpFile 应用程序帮助文件(`.hlp`或`.chm`)的完整路径。**String**,可读可写。当控件的[**HelpContextID**](/official/Reference/VB/CheckBox/#helpcontextid)非零且用户按下**F1**时,以及应用程序代码调用带帮助文件参数的`MsgBox`时,运行时查询此属性。 ### hInstance 可执行文件的Win32模块句柄(`HINSTANCE`)。**LongPtr**,只读。在调用代表应用程序加载资源或创建窗口的Windows API函数时很有用。 ### IsElevated 如果进程以管理员权限("以管理员身份运行"提升令牌)运行则为**True**,否则为**False**。**Boolean**,只读。 ### IsInIDE 如果运行中的进程是twinBASIC IDE宿主而非独立编译的可执行文件则为**True**。**Boolean**,只读。用于仅在设计时运行的代码路径,或应在发布版本中抑制的诊断日志。 ### LastBuildPath IDE写入最近构建的完整路径。**String**,只读。当IDE在当前会话中尚未生成构建时为空。twinBASIC特有——VB6没有对应功能。 ### LegalCopyright 应用程序`VERSIONINFO`资源的**LegalCopyright**字段。**String**,只读。 ### LegalTrademarks 应用程序`VERSIONINFO`资源的**LegalTrademarks**字段。**String**,只读。 ### LogMode 当前日志记录模式,作为[**LogModeConstants**](/official/Reference/VBRUN/Constants/LogModeConstants)的成员。只读。 ::: info twinBASIC目前仅报告**vbLogOff**和**vbLogAuto**,区分IDE检测情况。其他VB6日志记录模式(文件、NT事件日志)尚未支持。 ::: ### LogPath ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### Major 应用程序四部分版本号的**Major**组件。**Integer**,只读。 ### Minor 应用程序四部分版本号的**Minor**组件。**Integer**,只读。 ### ModulePath 可执行文件的完整路径。**String**,只读。这是`GetModuleFileName(App.hInstance, …)`会返回的值。 ### NonModalAllowed ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### OleRequestPendingMsgText ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### OleRequestPendingMsgTitle ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### OleRequestPendingTimeout ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### OleServerBusyMsgText ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### OleServerBusyMsgTitle ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### OleServerBusyRaiseError ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### OleServerBusyTimeout ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### Path 包含可执行文件的文件夹,无尾部反斜杠。**String**,只读。在IDE内运行时,这是包含项目文件的文件夹而非IDE宿主的文件夹,因此相对于应用程序位置打开文件的代码在设计时和运行时行为一致。 ### PrevInstance 如果应用程序的另一个实例已在运行则为**True**,否则为**False**。**Boolean**,只读。通常在启动时测试,以便第二个实例可以将第一个带到前台或优雅退出。 ### ProductName 应用程序`VERSIONINFO`资源的**ProductName**字段。**String**,只读。 ### RetainedProject ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### Revision 应用程序四部分版本号的**Revision**组件。**Integer**,只读。 ### StartMode ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### TaskVisible ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ### ThreadID 应用程序主(UI)线程的Win32线程ID。**Long**,只读。 ### Title 向操作系统显示的应用程序标题(在任务列表中)以及`MsgBox`、`InputBox`和其他系统对话框的默认标题。**String**,可读可写。默认为可执行文件的[**FileDescription**](#filedescription)(如果未设置描述则为[**EXEName**](#exename))。 ### UnattendedApp ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: ## 方法 ### LogEvent ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: 语法:*object*.**LogEvent** *LogBuffer*, *EventType* ### StartLogging ::: info 保留用于VB6兼容性;twinBASIC中目前未实现。 ::: 语法:*object*.**StartLogging** *LogTarget*, *LogModes* --- --- url: /en/official/Reference/VBA/Interaction/AppActivate.md --- # AppActivate Activates an application window. Syntax: * **AppActivate** *title* \[ **,** *wait* ] *title* : *required* A string expression specifying the title in the title bar of the application window to activate. *wait* : *optional* A Boolean value specifying whether the calling application has the focus before activating another. If **False** (default), the specified application is immediately activated, even if the calling application does not have the focus. If **True**, the calling application waits until it has the focus, then activates the specified application. * **AppActivate** *taskId* \[ **,** *wait* ] *taskId* : *required* The task ID returned by the [**Shell**](/en/official/Reference/VBA/Interaction/Shell) function can be used in place of *title* to activate an application. The **AppActivate** statement changes the focus to the named application or window but does not affect whether it is maximized or minimized. Focus moves from the activated application window when the user takes some action to change the focus or close the window. Use the [**Shell**](/en/official/Reference/VBA/Interaction/Shell) function to start an application and set the window style. In determining which application to activate, *title* is compared to the title string of each running application. If there is no exact match, any application whose title string begins with *title* is activated. If there is more than one instance of the application named by *title*, one instance is arbitrarily activated. ### Example This example illustrates various uses of the **AppActivate** statement to activate an application window. The **Shell** statements assume the applications are in the paths specified. ```vb Dim MyAppID, ReturnValue AppActivate "Microsoft Word" ' Activate Microsoft ' Word. ' AppActivate can also use the return value of the Shell function. MyAppID = Shell("C:\WORD\WINWORD.EXE", 1) ' Run Microsoft Word. AppActivate MyAppID ' Activate Microsoft ' Word. ' You can also use the return value of the Shell function. ReturnValue = Shell("c:\EXCEL\EXCEL.EXE",1) ' Run Microsoft Excel. AppActivate ReturnValue ' Activate Microsoft ' Excel. ``` ### See Also * [SendKeys](/en/official/Reference/VBA/Interaction/SendKeys) statement * [Shell](/en/official/Reference/VBA/Interaction/Shell) function --- --- url: /zh/official/Reference/VBA/Interaction/AppActivate.md --- # AppActivate 激活应用程序窗口。 语法: * **AppActivate** *title* \[ **,** *wait* ] *title* : *必需* 字符串表达式,指定要激活的应用程序窗口标题栏中的标题。 *wait* : *可选* Boolean值,指定调用应用程序在激活另一个应用程序之前是否需要具有焦点。如果为**False**(默认),则立即激活指定应用程序,即使调用应用程序不具有焦点。如果为**True**,调用应用程序等待直到获得焦点,然后激活指定应用程序。 * **AppActivate** *taskId* \[ **,** *wait* ] *taskId* : *必需* [**Shell**](/official/Reference/VBA/Interaction/Shell)函数返回的任务ID可代替*title*用于激活应用程序。 **AppActivate**语句将焦点更改到命名应用程序或窗口,但不影响其是否最大化或最小化。当用户采取某些操作更改焦点或关闭窗口时,焦点从激活的应用程序窗口移开。使用[**Shell**](/official/Reference/VBA/Interaction/Shell)函数启动应用程序并设置窗口样式。 在确定要激活哪个应用程序时,*title*与每个运行中应用程序的标题字符串进行比较。如果没有完全匹配,则激活标题字符串以*title*开头的任何应用程序。如果*title*指定的应用程序有多个实例,则任意激活一个实例。 ### 示例 本示例演示**AppActivate**语句激活应用程序窗口的各种用法。**Shell**语句假设应用程序位于指定路径。 ```vb Dim MyAppID, ReturnValue AppActivate "Microsoft Word" ' Activate Microsoft ' Word. ' AppActivate can also use the return value of the Shell function. MyAppID = Shell("C:\WORD\WINWORD.EXE", 1) ' Run Microsoft Word. AppActivate MyAppID ' Activate Microsoft ' Word. ' You can also use the return value of the Shell function. ReturnValue = Shell("c:\EXCEL\EXCEL.EXE",1) ' Run Microsoft Excel. AppActivate ReturnValue ' Activate Microsoft ' Excel. ``` ### 另请参阅 * [SendKeys](/official/Reference/VBA/Interaction/SendKeys)语句 * [Shell](/official/Reference/VBA/Interaction/Shell)函数 --- --- url: /zh/official/Reference/Core/AppActivate.md --- # AppActivate 语句 appActivate 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/AppActivate.md --- # AppActivate Statement Documentation for the appactivate keyword is not yet available. --- --- url: /en/official/Reference/VBRUN/Constants/AppearanceConstants.md --- # AppearanceConstants Drawing-style values for the **Appearance** property of forms and controls. | Constant | Value | Description | |----------|-------|-------------| | **vbAppearFlat** | 0 | The control is drawn without 3-D effects. | | **vbAppear3d** | 1 | The control is drawn with 3-D shading on its borders and edges. | --- --- url: /zh/official/Reference/VBRUN/Constants/AppearanceConstants.md --- # AppearanceConstants 窗体和控件的**Appearance**属性的绘图样式值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbAppearFlat** | 0 | 控件不带三维效果绘制。 | | **vbAppear3d** | 1 | 控件边框和边缘带三维阴影绘制。 | --- --- url: /en/official/Reference/VBRUN/Constants/ApplicationStartConstants.md --- # ApplicationStartConstants Mode values reported by the application's start-up logic --- whether it was launched as a stand-alone program or invoked via Automation by another application. | Constant | Value | Description | |----------|-------|-------------| | **vbSModeStandalone** | 0 | The application was launched directly by the user. | | **vbSModeAutomation** | 1 | The application was started through Automation, in response to a request from another application. | --- --- url: /zh/official/Reference/VBRUN/Constants/ApplicationStartConstants.md --- # ApplicationStartConstants 应用程序启动逻辑报告的模式值 --- 是作为独立程序启动还是通过Automation由另一应用程序调用。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbSModeStandalone** | 0 | 应用程序由用户直接启动。 | | **vbSModeAutomation** | 1 | 应用程序通过Automation启动,响应另一应用程序的请求。 | --- --- url: /en/official/Reference/VBA/Information/Array.md --- # Array Returns a **Variant** containing an array built from a comma-separated list of values, or --- when used on the left of an assignment --- destructures an array on the right-hand side into the supplied variables. Syntax: * *result* **= Array(** \[ *ArgList* ] **)** --- array creation. * **Array(** *Var1*, *Var2*, ... **) =** *RhsArray* --- destructuring assignment. *ArgList* : *optional* A comma-delimited list of values that are assigned to the elements of the new array. If no arguments are supplied, an empty array is returned. *Var1*, *Var2*, ... : *required* (destructuring form) The variables to receive successive elements of *RhsArray*. Pass `_` to skip an element. *RhsArray* : *required* (destructuring form) An array; non-array values raise an error. The lower bound of an array created with **Array** is determined by the **Option Base** statement at the component scope, defaulting to `0`. ```vb Option Base 1 Dim a As Variant a = Array(10, 20, 30) Debug.Print a(1) ' 10 ``` The destructuring form unpacks an array into the named variables in order, starting from the array's lower bound. The argument list can mix variables and the `_` placeholder to skip elements: ```vb Dim x As Variant, y As Variant, z As Variant Array(x, y, z) = Array("one", "two", "three") ' x = "one", y = "two", z = "three" Dim a As Variant, b As Variant Array(a, _, b) = Array(1, 2, 3) ' a = 1, b = 3 — the second element is discarded ``` ::: info A **Variant** that is not declared as an array can still contain an array, and a **Variant** array can hold values of any type except fixed-length strings and user-defined types. Although a **Variant** containing an array is conceptually different from an array of **Variant** elements, indexing works the same way for both. ::: ### Example This example uses the **Array** function to return a **Variant** containing an array. ```vb Dim MyWeek As Variant Dim MyDay As Variant MyWeek = Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") MyDay = MyWeek(2) ' MyDay contains "Wed" with default Option Base 0, ' or "Tue" under Option Base 1. ``` ### See Also * [Option](/en/official/Reference/Core/Option) statement * [LBound](/en/official/Reference/VBA/Information/LBound), [UBound](/en/official/Reference/VBA/Information/UBound) functions --- --- url: /zh/official/Reference/VBA/Information/Array.md --- # Array 返回一个包含由逗号分隔值列表构建的数组的**Variant**,或者——在赋值左侧使用时——将右侧的数组解构到提供的变量中。 语法: * *result* **= Array(** \[ *ArgList* ] **)** — 数组创建。 * **Array(** *Var1*, *Var2*, ... **) =** *RhsArray* — 解构赋值。 *ArgList* : *可选* 逗号分隔的值列表,分配给新数组的元素。如果未提供参数,则返回空数组。 *Var1*, *Var2*, ... : *必需*(解构形式)接收*RhsArray*连续元素的变量。传入`_`可跳过元素。 *RhsArray* : *必需*(解构形式)一个数组;非数组值会产生错误。 使用**Array**创建的数组的下界由组件范围的**Option Base**语句确定,默认为`0`。 ```vb Option Base 1 Dim a As Variant a = Array(10, 20, 30) Debug.Print a(1) ' 10 ``` 解构形式按顺序将数组解包到命名变量中,从数组的下界开始。参数列表可以混合变量和`_`占位符以跳过元素: ```vb Dim x As Variant, y As Variant, z As Variant Array(x, y, z) = Array("one", "two", "three") ' x = "one", y = "two", z = "three" Dim a As Variant, b As Variant Array(a, _, b) = Array(1, 2, 3) ' a = 1, b = 3 — the second element is discarded ``` ::: info 未声明为数组的**Variant**仍可包含数组,**Variant**数组可以保存除定长字符串和用户自定义类型之外的任何类型的值。虽然包含数组的**Variant**与**Variant**元素数组在概念上不同,但两者的索引方式相同。 ::: ### 示例 本示例使用**Array**函数返回一个包含数组的**Variant**。 ```vb Dim MyWeek As Variant Dim MyDay As Variant MyWeek = Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") MyDay = MyWeek(2) ' MyDay contains "Wed" with default Option Base 0, ' or "Tue" under Option Base 1. ``` ### 另请参阅 * [Option](/official/Reference/Core/Option)语句 * [LBound](/official/Reference/VBA/Information/LBound)、[UBound](/official/Reference/VBA/Information/UBound)函数 --- --- url: /zh/official/Reference/Core/Array.md --- # Array 函数 array 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/Array.md --- # Array Function Documentation for the array keyword is not yet available. --- --- url: /en/official/Tutorials/Arrays.md --- # Arrays Arrays come in two kinds: 1. Fixed size arrays, whose size specification is a compile-time constant.\ `Dim MyInts(10) As Integer` `Dim MyLongs(10 To 19) As Long` 2. Dynamic arrays, who aren't initialized initially, and must be (re-)dimensioned prior to use.\ `Dim MyLongs() As Long` Fixed size arrays have lower memory and runtime overhead than dynamic arrays. They perform better as small arrays -- up to 8 cache lines in size, or up to 512 bytes in size. In arrays larger than that, the overhead of a dynamic array becomes negligible when creating (dimensioning) the array. However, there is still slight runtime overhead on element access, independently of the size of a dynamic array. ## Array Declaration Syntax Fixed size arrays can only be used for variables or class and UDT fields.\ Dynamic arrays can be used for variables, fields, parameter types and return types.\ A fixed size array can be passed as an argument accepting a dynamic array. ::: info Fixed size arrays cannot be used as return types directly. They can be returned when wrapped in a UDT. ::: * Syntax for variable declarations in procedures\ **Dim** | **Static** name **()** \[ **As** type ] -- dynamic array\ **Dim** | **Static** name **(** size \[ **,** size ... ] **)** \[ **As** type ] -- fixed array * Syntax for procedure parameter types; only dynamic arrays are valid and both syntaxes below are equivalent\ name **()** \[ **As** type ]\ name **As** type **()** * Syntax for procedure return types; only dynamic arrays are valid\ name **As** type **()** * Syntax for field declarations in classes\ **Dim** | **Private** | **Protected** | **Public** name **()** \[ **As** type ] -- dynamic array\ **Dim** | **Private** | **Protected** | **Public** name **(** size \[ **,** size ....] **)** \[ **As** type ] -- static array * Syntax for field declarations in types (UDTs)\ name **()** \[ **As** type ] -- dynamic array\ name **(** size \[ **,** size ....] **)** \[ **As** type ] -- static array Each size specification is a range, but the lower bound is optional and defaults to currently active **Option Base**: * ubound, e.g. `Dim A(10, 20)` * lbound **To** ubound -- range, inclusive of both bounds, e.g. `Dim A(1 To 10, 1 To 20)` Both variants of size specifications can be mixed in one declaration, e.g.\ `Dim B(10, 1 To 20)` Here is how **Option Base** controls the default lower bound of a dimension: ```vb Option Base 0 Dim A(10, 20) ' is equivalent to... Dim A(0 To 10, 0 To 20) ' i.e. a 21 x 11 array Option Base 1 Dim A(10, 20) ' is equivalent to... Dim A(1 To 10, 1 To 20) ' i.e. a 20 x 10 array ``` Only the dynamic arrays can be passed as procedure arguments: ```vb Sub OkSub1(data() As Byte) ' Dynamic array parameter Sub OkSub2(data As Byte()) ' Alternate syntax Sub BadSub1(data(10) As Byte) ' Invalid, fixed array types are not allowed as parameters... Sub BadSub2(data As Byte(10)) ' ... in neither syntax ``` ## Dimensioning Dynamic Arrays A dynamic array is uninitialized after declaration. It cannot be used in any way other than to be dimensioned. Dimensioning is performed by the **ReDim** statement: ```vb Dim array() Debug.Assert IsArrayInitialized(array) = False Debug.Print LBound(array) ' raises a runtime error since the array is uninitialized, ' and no operations are valid on it other than a ReDim ReDim array(1 to 10) ' now the array is initialized Debug.Assert IsArrayInitialized(array) = True Debug.Assert LBound(array) = 1 Debug.Assert UBound(array) = 10 ``` **ReDim** has two operating modes: by default, it discards the existing data in the array. Optionally, it can preserve the existing data to the extent that new dimensions allow it. Syntax: * **ReDim** \[ **Preserve** ] name **(** size \[ **,** size ...] **)** ::: warning Only the upper bound of an array dimension can be changed with **ReDim Preserve**. Non-preserving **ReDim** allows arbitrary changes. ::: ```vb Dim a() As Long ReDim a(1 To 2) ' Initial dimensioning a(1) = 10 a(2) = 20 ReDim Preserve a(1 To 3) ' Change of an upper bound of 1st dimension Debug.Assert a(1) = 10 Debug.Assert a(2) = 20 Debug.Assert a(3) = 0 ReDim Preserve a(2 To 3) ' Causes a runtime error ReDim a(5 To 8) ' Change of both bounds of 1st dimension while losing data Debug.Assert a(5) = 0 ``` ## Determining Array Dimension Bounds Every dimension of an *initialized* array has an associated lower and upper bound. These bounds are accessed with the **LBound** and **UBound** functions. ```vb Dim array(1 To 10, 3 To 20) Debug.Assert LBound(array) = 1 ' 1st dimension by default Debug.Assert LBound(array, 1) = 1 ' 1st dimension Debug.Assert LBound(array, 2) = 3 ' 2nd dimension Debug.Assert UBound(array, 2) = 20 ' 2nd dimension, upper bound' ``` ## Determining Array Size An attempt to use **LBound** or **UBound** on an uninitialized array causes a runtime error. Thus, a function that determines the number of elements in a given dimension of an array, must first check if the array is initialized: ```vb Sub ArrayLen(Of T)(array() Of T, ByVal dimension% = 1) As Long ' zero is the default return value If IsArrayInitialized(array) Then Return 1 + UBound(array, dimension) - LBound(array, dimension) End If End Sub ``` See also [Efficient low-level access of a 1D array](#efficient-low-level-access-of-a-1d-array). ## Array Element Access To access array elements, indices for all dimensions should be provided as a parenthesized list after the name of the array variable: ```vb Dim array(1 To 10) As Long array(1) = 42 Debug.Assert array(1) = 42 Dim array2(1 To 10, 1 To 2) As Long array(1, 2) = 42 Debug.Assert array(1, 2) = 42 ``` Array elements are initialized to zero/null, just as all the other types are in twinBASIC: ```vb Dim intArray(1 To 10) As Integer Debug.Assert intArray(1) = 0 AndAlso intArray(10) = 0 Dim strArray(20 To 25) As String Debug.Assert strArray(20) = vbNullString ``` ## Returning Arrays Any array can be returned as a dynamic array: ```vb Function Fn1() As Long() Dim array1() As Long Dim array2(11) As Long Return array1 Return array2 End Function ``` To return a fixed size array, it has to be wrapped in a UDT: ```vb Type Wrapper array(11) As Long End Type Function Fn2() As Wrapper ' The procedure name is used to access the returned value Fn2.array(5) = 10 End Function Sub Test() Dim arr As Wrapper = Fn2() Debug.Assert arr.array(5) = 10 End Sub ``` ## Efficient low-level access of a 1D array In twinBASIC, array types are implemented as pointers to a pointer to the Windows API **SAFEARRAY** structure. This can be used to efficiently access: * the count of elements in the 1st dimension * as the pointer to the data (to the 1st element in the array) * the size of the array in bytes ```vb Function ArrayLen(Of T)(array() As T) As Long Dim p As LongPtr GetMemPtr(VarPtr(array), p) If p <> 0 Then ' if the array is initialized #If win64 Then GetMem4(p + 24, Len) #Else GetMem4(p + 16, Len) #End If End If End Function Function ArrayPtr(Of T)(array() As T) As LongPtr Dim p As LongPtr GetMemPtr(VarPtr(array), p) If p <> 0 Then #If win64 Then GetMemPtr(p + 16, Ptr) #Else GetMemPtr(p + 12, Ptr) #End If End If End Function Function ArrayBytes(Of T)(array() As T) As Long Return ArrayLen(array) * LenB(Of T) End Function ``` These functions are useful to pass arrays and array counts to external **Declare**-d procedures. For example: ```vb Declare Sub SaveData Lib "mylib" (ByVal ptr As LongPtr, ByVal count&) Declare Sub WriteData Lib "mylib" (ByVal ptr As LongPtr, ByVal numBytes&) Sub Save(array() As Long) Debug.Assert ArrayBytes(array) = ArrayLen(array) * 4 ' 4 = size of a Long SaveLongData(ArrayPtr(array), ArrayLen(array)) End Sub Sub Write(array() As Long) WriteData(ArrayPtr(array), ArrayBytes(array)) End Sub ``` Without these functions, this would have been more cumbersome: ```vb Sub Save(array() As Long) If IsArrayInitialized(array) Then SaveLongData( _ VarPtr(array(LBound(array))), _ 1 + UBound(array) - LBound(array)) Else SaveLongData(0, 0) ' ArrayLen, ArraySize, and ArrayPtr would ' return 0 for an uninitialized array End If End Sub ``` --- --- url: /en/official/Reference/VBA/Strings/Asc.md --- # Asc, AscB, AscW Returns an **Integer** representing the character code corresponding to the first letter in a string. Syntax: * **Asc(** *string* **)** * **AscB(** *string* **)** * **AscW(** *string* **)** *string* : *required* Any valid string expression. If *string* contains no characters, a run-time error occurs. The range for returns from **Asc** is 0--255 on non-DBCS systems, but -32768--32767 on DBCS systems. ::: info The **AscB** function is used with byte data contained in a string. Instead of returning the character code for the first character, **AscB** returns the first byte. The **AscW** function returns the Unicode character code. ::: The functions [**Chr**, **ChrB**, and **ChrW**](/en/official/Reference/VBA/Strings/Chr) are the opposite of **Asc**, **AscB**, and **AscW**. The **Chr** functions convert an integer to a character string. ### Example This example uses the **Asc** function to return a character code corresponding to the first letter in the string. ```vb Dim MyNumber MyNumber = Asc("A") ' Returns 65. MyNumber = Asc("a") ' Returns 97. MyNumber = Asc("Apple") ' Returns 65. ``` ### See Also * [Chr](/en/official/Reference/VBA/Strings/Chr) function --- --- url: /zh/official/Reference/VBA/Strings/Asc.md --- # Asc, AscB, AscW 返回一个**Integer**,表示与字符串中第一个字母对应的字符代码。 语法: * **Asc(** *string* **)** * **AscB(** *string* **)** * **AscW(** *string* **)** *string* : *必需* 任意有效的字符串表达式。如果*string*不包含任何字符,将产生运行时错误。 **Asc**的返回值范围在非DBCS系统上为0--255,在DBCS系统上为-32768--32767。 ::: info **AscB**函数用于处理字符串中包含的字节数据。**AscB**不返回第一个字符的字符代码,而是返回第一个字节。**AscW**函数返回Unicode字符代码。 ::: 函数[**Chr**、**ChrB**和**ChrW**](/official/Reference/VBA/Strings/Chr)与**Asc**、**AscB**和**AscW**互为相反。**Chr**函数将整数转换为字符串。 ### 示例 本示例使用**Asc**函数返回与字符串中第一个字母对应的字符代码。 ```vb Dim MyNumber MyNumber = Asc("A") ' Returns 65. MyNumber = Asc("a") ' Returns 97. MyNumber = Asc("Apple") ' Returns 65. ``` ### 另请参阅 * [Chr](/official/Reference/VBA/Strings/Chr)函数 --- --- url: /en/official/Reference/VBRUN/Constants/AspectTypeConstants.md --- # AspectTypeConstants Rendering aspect identifiers used by [**DataObjectFormat.AspectType**](/en/official/Reference/VBRUN/DataObject/DataObjectFormat#aspecttype) and other OLE-data routines to choose which view of a piece of data is being negotiated. | Constant | Value | Description | |----------|-------|-------------| | **vbContent** | 1 | The data itself, suitable for display or editing. | | **vbThumbnail** | 2 | A small preview of the data. | | **vbIcon** | 4 | An icon-sized representation. | | **vbDocPrint** | 8 | A rendering suitable for sending to a printer. | --- --- url: /zh/official/Reference/VBRUN/Constants/AspectTypeConstants.md --- # AspectTypeConstants [**DataObjectFormat.AspectType**](/official/Reference/VBRUN/DataObject/DataObjectFormat#aspecttype)和其他OLE数据例程使用的呈现方面标识符,用于选择正在协商的数据视图。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbContent** | 1 | 数据本身,适合显示或编辑。 | | **vbThumbnail** | 2 | 数据的小型预览。 | | **vbIcon** | 4 | 图标大小的表示。 | | **vbDocPrint** | 8 | 适合发送到打印机的呈现。 | --- --- url: /zh/official/Reference/Assert.md --- # Assert 包 **Assert** 内置包提供了用于编写 twinBASIC 代码单元测试的断言函数。每个断言检查一个预期条件;失败时,它会记录测试失败以及调用位置和可选消息。测试运行器---twinBASIC IDE 的测试资源管理器或任何等效的工具---收集这些结果,决定哪些测试通过、失败或被跳过,并进行报告。 该包的三个模块---[**Exact**](/official/Reference/Assert/Exact)、[**Strict**](/official/Reference/Assert/Strict) 和 [**Permissive**](/official/Reference/Assert/Permissive)---公开了相同的十五个断言函数;只有*比较语义*不同。每种风格对应相等性评估的不同严格级别。 | 模块 | 字符串比较 | 数值及其他比较 | |------------------------------|--------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**Exact**](/official/Reference/Assert/Exact) | 区分大小写 | 无隐式转换;数据类型必须完全匹配(`5` ≠ `5.0`);`vbNullString` 与 `""` 不同;`Empty` 与 `0`、`False` 和 `""` 不同;不评估对象默认成员 | | [**Strict**](/official/Reference/Assert/Strict) | 区分大小写 | 按照比较直接写在 twinBASIC 代码中的方式评估;不评估对象默认成员 | | [**Permissive**](/official/Reference/Assert/Permissive) | 不区分大小写 | 按照比较直接写在 twinBASIC 代码中的方式评估 | 在三种风格中,`Null` 永远不被认为等于任何值---甚至不等于自身。要显式测试 **Null**,请使用 [**IsNull**](/official/Reference/Assert/Exact#isnull) / [**IsNotNull**](/official/Reference/Assert/Exact#isnotnull) 断言,而不是 `AreEqual(..., Null)`。 ```vb Sub TestStringReverse() Strict.AreEqual "olleh", StrReverse("hello") Strict.AreEqual "", StrReverse("") End Sub ``` ## 调用约定 每个模块的每个成员都标记了 `[MustBeQualified(True)]`---调用*必须*带有模块名称,即使是在已导入 **Assert** 包的项目内部: ```vb Strict.IsTrue x > 0 ' 正确 IsTrue x > 0 ' 编译错误——需要模块限定符 ``` 如果一个项目引用了多个暴露名为 **Strict** 的模块的包,还需使用包名进一步限定:**Assert.Strict.IsTrue** *x*。 ## 仅调试模式 每个断言都标记了 `[DebugOnly(True)]`---调用在发布构建中编译为*空*,与 [**Debug.Print**](/official/Reference/Core/Print) 和 **Debug.Assert** 语句的方式相同。因此测试运行器需要在启用调试的情况下构建项目。 ## 模块 * [Exact](/official/Reference/Assert/Exact) -- 最严格的比较;数据类型必须匹配且不会发生转换 * [Strict](/official/Reference/Assert/Strict) -- 区分大小写字符串,但相等性其他方面与 twinBASIC 代码中的直接比较一致 * [Permissive](/official/Reference/Assert/Permissive) -- 不区分大小写字符串;其他方面相等性与 twinBASIC 代码中的直接比较一致 ## 成员 每个模块公开相同的十五个函数,按用途分组: * **诊断结果** --- **Succeed**、**Fail**、**Inconclusive** * **相等性** --- **AreEqual** / **AreNotEqual**、**AreSame** / **AreNotSame** * **布尔** --- **IsTrue**、**IsFalse** * **引用和值状态** --- **IsNothing** / **IsNotNothing**、**IsNull** / **IsNotNull** * **序列** --- **SequenceEquals** / **NotSequenceEquals** 详见各模块页面了解完整签名和适用于每个成员的比较语义。 --- --- url: /en/official/Reference/Assert.md --- # Assert Package The **Assert** built-in package supplies the assertion functions used to write unit tests for twinBASIC code. Each assertion checks an expected condition; on failure, it records a test failure with the call site and an optional message. The test runner --- the twinBASIC IDE's Test Explorer, or any equivalent harness --- collects those results, decides which tests passed, failed, or were skipped, and reports them. The package's three modules --- [**Exact**](/en/official/Reference/Assert/Exact), [**Strict**](/en/official/Reference/Assert/Strict), and [**Permissive**](/en/official/Reference/Assert/Permissive) --- expose the same fifteen assertion functions; only the *comparison semantics* differ. Each flavour matches a different strictness level for equality evaluation. | Module | String comparisons | Numeric and other comparisons | |------------------------------|--------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**Exact**](/en/official/Reference/Assert/Exact) | case-sensitive | no implicit conversions; datatypes must match exactly (`5` ≠ `5.0`); `vbNullString` is distinct from `""`; `Empty` is distinct from `0`, `False`, and `""`; object default members are *not* evaluated | | [**Strict**](/en/official/Reference/Assert/Strict) | case-sensitive | evaluated as if the comparison were written directly in twinBASIC code; object default members are *not* evaluated | | [**Permissive**](/en/official/Reference/Assert/Permissive) | case-insensitive | evaluated as if the comparison were written directly in twinBASIC code | `Null` is never considered equal to anything --- not even to itself --- under any of the three flavours. To test for **Null** explicitly, use the [**IsNull**](/en/official/Reference/Assert/Exact#isnull) / [**IsNotNull**](/en/official/Reference/Assert/Exact#isnotnull) assertions rather than `AreEqual(..., Null)`. ```vb Sub TestStringReverse() Strict.AreEqual "olleh", StrReverse("hello") Strict.AreEqual "", StrReverse("") End Sub ``` ## Calling convention Every member of every module is tagged `[MustBeQualified(True)]` --- calls *must* be written with the module name, even from inside a project that has imported the **Assert** package: ```vb Strict.IsTrue x > 0 ' OK IsTrue x > 0 ' compile error — module qualifier required ``` If a project references more than one package that exposes a module called **Strict**, qualify further with the package name as well: **Assert.Strict.IsTrue** *x*. ## Debug-only Every assertion is tagged `[DebugOnly(True)]` --- the calls compile to *nothing* in release builds, in the same way that [**Debug.Print**](/en/official/Reference/Core/Print) and the **Debug.Assert** statement do. A test runner therefore needs to build the project with debug enabled. ## Modules * [Exact](/en/official/Reference/Assert/Exact) -- strictest comparisons; datatypes must match and conversions never happen * [Strict](/en/official/Reference/Assert/Strict) -- case-sensitive strings, but otherwise equality matches a direct comparison in twinBASIC code * [Permissive](/en/official/Reference/Assert/Permissive) -- case-insensitive strings; otherwise equality matches a direct comparison in twinBASIC code ## Members Each module exposes the same fifteen functions, grouped here by purpose: * **Diagnostic outcome** --- **Succeed**, **Fail**, **Inconclusive** * **Equality** --- **AreEqual** / **AreNotEqual**, **AreSame** / **AreNotSame** * **Boolean** --- **IsTrue**, **IsFalse** * **Reference and value state** --- **IsNothing** / **IsNotNothing**, **IsNull** / **IsNotNull** * **Sequence** --- **SequenceEquals** / **NotSequenceEquals** See the per-module pages for the full signatures and the comparison semantics that apply to each member. --- --- url: /en/official/Reference/VBRUN/AsyncProperty.md --- # AsyncProperty class The **AsyncProperty** object holds the results of an asynchronous read started with **UserControl.AsyncRead**. It is passed to the **AsyncReadComplete** and **AsyncReadProgress** events, where it identifies which read this notification refers to, reports how far the download has got, and --- once complete --- supplies the downloaded value. Every property is read-only: the runtime fills the object in before raising the event. ## Identifying the read A user control may have several outstanding asynchronous reads at once, so the **AsyncProperty** passed to each event has to identify the one the event is for. [**PropertyName**](/en/official/Reference/VBRUN/AsyncProperty/PropertyName) returns the name supplied to **AsyncRead** when the request was started --- typically the name of the property the control is going to assign the value to. [**Target**](/en/official/Reference/VBRUN/AsyncProperty/Target) returns the URL or file path that was being downloaded. [**AsyncType**](/en/official/Reference/VBRUN/AsyncProperty/AsyncType) returns an **AsyncTypeConstants** value identifying how the data is being delivered --- as a picture, a file, or a byte array. ```vb Private Sub UserControl_AsyncReadComplete(ByVal Prop As AsyncProperty) Select Case Prop.PropertyName Case "Picture" Set Picture = Prop.Value Case "DataFile" ' Prop.Value is the path to the downloaded temporary file. End Select End Sub ``` ## The downloaded value Once the read finishes, [**Value**](/en/official/Reference/VBRUN/AsyncProperty/Value) holds the result. Its concrete subtype is determined by **AsyncType**: an **stdole.IPictureDisp** when the data was requested as a picture, a **String** containing the path of a downloaded temporary file when it was requested as a file, or a **Byte** array when the raw bytes were requested. **Value** is only meaningful in the **AsyncReadComplete** event --- during a progress notification the read has not yet finished. ## Tracking progress While a read is in progress, the runtime raises **AsyncReadProgress** periodically so the control can update a progress indicator. [**BytesRead**](/en/official/Reference/VBRUN/AsyncProperty/BytesRead) reports how many bytes have arrived so far, and [**BytesMax**](/en/official/Reference/VBRUN/AsyncProperty/BytesMax) the total number expected --- though **BytesMax** may be zero when the server has not advertised a content length. [**Status**](/en/official/Reference/VBRUN/AsyncProperty/Status) returns a human-readable description of the current step ("Connecting", "Receiving response", and so on), and [**StatusCode**](/en/official/Reference/VBRUN/AsyncProperty/StatusCode) returns the corresponding **AsyncStatusCodeConstants** value for programmatic inspection. ## Members * [AsyncType](/en/official/Reference/VBRUN/AsyncProperty/AsyncType) -- returns the kind of data being read (picture, file, or byte array) * [BytesMax](/en/official/Reference/VBRUN/AsyncProperty/BytesMax) -- returns the total number of bytes expected for the read * [BytesRead](/en/official/Reference/VBRUN/AsyncProperty/BytesRead) -- returns the number of bytes that have been read so far * [PropertyName](/en/official/Reference/VBRUN/AsyncProperty/PropertyName) -- returns the name of the property the read is being performed for * [Status](/en/official/Reference/VBRUN/AsyncProperty/Status) -- returns a human-readable description of the current read state * [StatusCode](/en/official/Reference/VBRUN/AsyncProperty/StatusCode) -- returns the **AsyncStatusCodeConstants** value for the current read state * [Target](/en/official/Reference/VBRUN/AsyncProperty/Target) -- returns the URL or path being read * [Value](/en/official/Reference/VBRUN/AsyncProperty/Value) -- returns the downloaded value once the read has completed --- --- url: /zh/official/Reference/VBRUN/AsyncProperty.md --- # AsyncProperty 类 **AsyncProperty**对象保存由**UserControl.AsyncRead**启动的异步读取结果。它被传递给**AsyncReadComplete**和**AsyncReadProgress**事件,在其中标识此通知对应的读取,报告下载进度,并在完成时提供下载的值。每个属性均为只读:运行时在引发事件前填充此对象。 ## 标识读取 用户控件可能同时有多个未完成的异步读取,因此传递给每个事件的**AsyncProperty**必须标识该事件对应的读取。[**PropertyName**](/official/Reference/VBRUN/AsyncProperty/PropertyName)返回启动请求时提供给**AsyncRead**的名称——通常是控件将要赋值的属性名称。[**Target**](/official/Reference/VBRUN/AsyncProperty/Target)返回正在下载的URL或文件路径。[**AsyncType**](/official/Reference/VBRUN/AsyncProperty/AsyncType)返回**AsyncTypeConstants**值,标识数据的传递方式——图片、文件或字节数组。 ```vb Private Sub UserControl_AsyncReadComplete(ByVal Prop As AsyncProperty) Select Case Prop.PropertyName Case "Picture" Set Picture = Prop.Value Case "DataFile" ' Prop.Value是下载的临时文件路径。 End Select End Sub ``` ## 下载的值 读取完成后,[**Value**](/official/Reference/VBRUN/AsyncProperty/Value)保存结果。其具体子类型由**AsyncType**决定:请求数据为图片时为**stdole.IPictureDisp**,请求为文件时为包含下载临时文件路径的**String**,请求原始字节时为**Byte**数组。**Value**仅在**AsyncReadComplete**事件中有意义——在进度通知期间读取尚未完成。 ## 跟踪进度 读取进行中时,运行时定期引发**AsyncReadProgress**,使控件能够更新进度指示器。[**BytesRead**](/official/Reference/VBRUN/AsyncProperty/BytesRead)报告目前已到达的字节数,[**BytesMax**](/official/Reference/VBRUN/AsyncProperty/BytesMax)报告预期总字节数——但当服务器未公布内容长度时**BytesMax**可能为零。[**Status**](/official/Reference/VBRUN/AsyncProperty/Status)返回当前步骤的人类可读描述("正在连接"、"正在接收响应"等),[**StatusCode**](/official/Reference/VBRUN/AsyncProperty/StatusCode)返回对应的**AsyncStatusCodeConstants**值,供编程检查。 ## 成员 * [AsyncType](/official/Reference/VBRUN/AsyncProperty/AsyncType) -- 返回正在读取的数据类型(图片、文件或字节数组) * [BytesMax](/official/Reference/VBRUN/AsyncProperty/BytesMax) -- 返回读取的预期总字节数 * [BytesRead](/official/Reference/VBRUN/AsyncProperty/BytesRead) -- 返回目前已读取的字节数 * [PropertyName](/official/Reference/VBRUN/AsyncProperty/PropertyName) -- 返回执行读取的属性名称 * [Status](/official/Reference/VBRUN/AsyncProperty/Status) -- 返回当前读取状态的人类可读描述 * [StatusCode](/official/Reference/VBRUN/AsyncProperty/StatusCode) -- 返回当前读取状态的**AsyncStatusCodeConstants**值 * [Target](/official/Reference/VBRUN/AsyncProperty/Target) -- 返回正在读取的URL或路径 * [Value](/official/Reference/VBRUN/AsyncProperty/Value) -- 读取完成后返回下载的值 --- --- url: /en/official/Reference/VBRUN/Constants/AsyncReadConstants.md --- # AsyncReadConstants Bit flags for the *AsyncReadOptions* argument of **UserControl.AsyncRead**, controlling caching, synchronisation, and offline behaviour for an asynchronous download. | Constant | Value | Description | |----------|-------|-------------| | **vbAsyncReadSynchronousDownload** | 1 | The call does not return until the download has finished. | | **vbAsyncReadOfflineOperation** | 8 | The runtime should not contact the network if the resource is not already cached. | | **vbAsyncReadForceUpdate** | \&H10 | The cached copy is bypassed and the resource is fetched fresh. | | **vbAsyncReadResynchronize** | \&H200 | The cached copy is used only after revalidating it against the server. | | **vbAsyncReadGetFromCacheIfNetFail** | \&H80000 | If the network request fails, fall back to the cached copy if any. | --- --- url: /zh/official/Reference/VBRUN/Constants/AsyncReadConstants.md --- # AsyncReadConstants **UserControl.AsyncRead**的*AsyncReadOptions*参数的位标志,控制异步下载的缓存、同步和脱机行为。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbAsyncReadSynchronousDownload** | 1 | 调用在下载完成之前不返回。 | | **vbAsyncReadOfflineOperation** | 8 | 如果资源未缓存,运行时不应连接网络。 | | **vbAsyncReadForceUpdate** | \&H10 | 绕过缓存副本,重新获取资源。 | | **vbAsyncReadResynchronize** | \&H200 | 仅在与服务器重新验证后才使用缓存副本。 | | **vbAsyncReadGetFromCacheIfNetFail** | \&H80000 | 如果网络请求失败,则回退到缓存副本(如有)。 | --- --- url: /en/official/Reference/VBRUN/Constants/AsyncStatusCodeConstants.md --- # AsyncStatusCodeConstants Status codes reported by [**AsyncProperty.StatusCode**](/en/official/Reference/VBRUN/AsyncProperty/StatusCode) during an **AsyncReadProgress** notification, identifying which step of the download is currently in progress. | Constant | Value | Description | |----------|-------|-------------| | **vbAsyncStatusCodeError** | 0 | An error has occurred during the read. | | **vbAsyncStatusCodeFindingResource** | 1 | The runtime is locating the target server. | | **vbAsyncStatusCodeConnecting** | 2 | A connection to the target server is being established. | | **vbAsyncStatusCodeRedirecting** | 3 | The request is being redirected to a different URL. | | **vbAsyncStatusCodeBeginDownloadData** | 4 | The download of the resource data is starting. | | **vbAsyncStatusCodeDownloadingData** | 5 | The resource data is being received. | | **vbAsyncStatusCodeEndDownloadData** | 6 | The resource data has finished downloading. | | **vbAsyncStatusCodeUsingCachedCopy** | 10 | The resource is being served from the local cache rather than the network. | | **vbAsyncStatusCodeSendingRequest** | 11 | The request is being sent to the server. | | **vbAsyncStatusCodeMIMETypeAvailable** | 13 | The MIME type of the resource is now known. | | **vbAsyncStatusCodeCacheFileNameAvailable** | 14 | The local cache filename for the resource is now known. | | **vbAsyncStatusCodeBeginSyncOperation** | 15 | A synchronous portion of the operation is starting. | | **vbAsyncStatusCodeEndSyncOperation** | 16 | A synchronous portion of the operation has finished. | --- --- url: /zh/official/Reference/VBRUN/Constants/AsyncStatusCodeConstants.md --- # AsyncStatusCodeConstants **AsyncReadProgress**通知期间由[**AsyncProperty.StatusCode**](/official/Reference/VBRUN/AsyncProperty/StatusCode)报告的状态代码,标识下载当前正在进行的步骤。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbAsyncStatusCodeError** | 0 | 读取期间发生错误。 | | **vbAsyncStatusCodeFindingResource** | 1 | 运行时正在定位目标服务器。 | | **vbAsyncStatusCodeConnecting** | 2 | 正在建立与目标服务器的连接。 | | **vbAsyncStatusCodeRedirecting** | 3 | 请求正在重定向到不同的URL。 | | **vbAsyncStatusCodeBeginDownloadData** | 4 | 资源数据下载即将开始。 | | **vbAsyncStatusCodeDownloadingData** | 5 | 正在接收资源数据。 | | **vbAsyncStatusCodeEndDownloadData** | 6 | 资源数据下载已完成。 | | **vbAsyncStatusCodeUsingCachedCopy** | 10 | 正从本地缓存而非网络提供资源。 | | **vbAsyncStatusCodeSendingRequest** | 11 | 请求正在发送到服务器。 | | **vbAsyncStatusCodeMIMETypeAvailable** | 13 | 资源的MIME类型现在已知。 | | **vbAsyncStatusCodeCacheFileNameAvailable** | 14 | 资源的本地缓存文件名现在已知。 | | **vbAsyncStatusCodeBeginSyncOperation** | 15 | 操作的同步部分即将开始。 | | **vbAsyncStatusCodeEndSyncOperation** | 16 | 操作的同步部分已完成。 | --- --- url: /en/official/Reference/VBRUN/AsyncProperty/AsyncType.md --- # AsyncType Returns the kind of data being read, as an **AsyncTypeConstants** value. Read-only. Syntax: *object*.**AsyncType** *object* : *required* An object expression that evaluates to an **AsyncProperty** object. The value mirrors the *AsyncType* argument passed to **UserControl.AsyncRead** when the read was started. It also determines the subtype of [**Value**](/en/official/Reference/VBRUN/AsyncProperty/Value) once the read completes: * `vbAsyncTypePicture` (0) --- the data is being delivered as an **stdole.IPictureDisp**. * `vbAsyncTypeFile` (1) --- the data is being saved to a temporary file; **Value** holds its path as a **String**. * `vbAsyncTypeByteArray` (2) --- the data is being delivered as a **Byte** array. ### Example This example checks **AsyncType** in the completion event and assigns the result to the appropriate property. ```vb Private Sub UserControl_AsyncReadComplete(AsyncProp As AsyncProperty) If AsyncProp.PropertyName = "Picture" Then If AsyncProp.AsyncType = vbAsyncTypePicture Then Set UserControl.Picture = AsyncProp.Value End If End If End Sub ``` ### See Also * [Value](/en/official/Reference/VBRUN/AsyncProperty/Value) property * [PropertyName](/en/official/Reference/VBRUN/AsyncProperty/PropertyName) property * [Target](/en/official/Reference/VBRUN/AsyncProperty/Target) property --- --- url: /zh/official/Reference/VBRUN/AsyncProperty/AsyncType.md --- # AsyncType 返回正在读取的数据类型,类型为**AsyncTypeConstants**值。只读。 语法:*object*.**AsyncType** *object* : *必需* 求值为**AsyncProperty**对象的对象表达式。 该值反映启动读取时传递给**UserControl.AsyncRead**的*AsyncType*参数。它还决定读取完成后[**Value**](/official/Reference/VBRUN/AsyncProperty/Value)的子类型: * `vbAsyncTypePicture` (0) —— 数据以**stdole.IPictureDisp**形式传递。 * `vbAsyncTypeFile` (1) —— 数据保存到临时文件;**Value**以**String**形式保存其路径。 * `vbAsyncTypeByteArray` (2) —— 数据以**Byte**数组形式传递。 ### 示例 此示例在完成事件中检查**AsyncType**并将结果赋给相应属性。 ```vb Private Sub UserControl_AsyncReadComplete(AsyncProp As AsyncProperty) If AsyncProp.PropertyName = "Picture" Then If AsyncProp.AsyncType = vbAsyncTypePicture Then Set UserControl.Picture = AsyncProp.Value End If End If End Sub ``` ### 另见 * [Value](/official/Reference/VBRUN/AsyncProperty/Value) 属性 * [PropertyName](/official/Reference/VBRUN/AsyncProperty/PropertyName) 属性 * [Target](/official/Reference/VBRUN/AsyncProperty/Target) 属性 --- --- url: /en/official/Reference/VBRUN/Constants/AsyncTypeConstants.md --- # AsyncTypeConstants The kind of data being delivered by **UserControl.AsyncRead**, also reported back through [**AsyncProperty.AsyncType**](/en/official/Reference/VBRUN/AsyncProperty/AsyncType). | Constant | Value | Description | |----------|-------|-------------| | **vbAsyncTypePicture** | 0 | The data is delivered as an **stdole.IPictureDisp**. | | **vbAsyncTypeFile** | 1 | The data is downloaded to a temporary file; **Value** holds the file's path. | | **vbAsyncTypeByteArray** | 2 | The data is delivered as a **Byte** array. | --- --- url: /zh/official/Reference/VBRUN/Constants/AsyncTypeConstants.md --- # AsyncTypeConstants **UserControl.AsyncRead**传递的数据类型,也通过[**AsyncProperty.AsyncType**](/official/Reference/VBRUN/AsyncProperty/AsyncType)报告。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbAsyncTypePicture** | 0 | 数据以**stdole.IPictureDisp**形式传递。 | | **vbAsyncTypeFile** | 1 | 数据下载到临时文件;**Value**保存文件路径。 | | **vbAsyncTypeByteArray** | 2 | 数据以**Byte**数组形式传递。 | --- --- url: /en/official/Reference/VBA/Math/Atn.md --- # Atn Returns a **Double** specifying the arctangent of a number. Syntax: **Atn(** *number* **)** *number* : *required* A **Double** or any valid numeric expression. The **Atn** function takes the ratio of two sides of a right triangle (*number*) and returns the corresponding angle in radians. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle. The range of the result is -pi/2 to pi/2 radians. To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi. ::: info **Atn** is the inverse trigonometric function of [**Tan**](/en/official/Reference/VBA/Math/Tan), which takes an angle as its argument and returns the ratio of two sides of a right triangle. Do not confuse **Atn** with the cotangent, which is the simple inverse of a tangent (1/tangent). ::: ### Example This example uses **Atn** to derive an approximation of pi. ```vb Const Pi As Double = Atn(1) * 4 ' pi ≈ 3.14159265358979 Debug.Print Pi Debug.Print Pi / 180 ' one degree in radians ≈ 0.0174532925199433 ``` ### See Also * [Cos](/en/official/Reference/VBA/Math/Cos), [Sin](/en/official/Reference/VBA/Math/Sin), [Tan](/en/official/Reference/VBA/Math/Tan) functions --- --- url: /zh/official/Reference/VBA/Math/Atn.md --- # Atn 返回一个 **Double**,指定数字的反正切值。 语法:**Atn(** *number* **)** *number* : *必需* **Double** 或任何有效的数值表达式。 **Atn** 函数取直角三角形两边的比值(*number*),返回对应的弧度角。该比值是对边长度除以邻边长度。 结果范围为 -pi/2 到 pi/2 弧度。要将角度转换为弧度,将角度乘以 pi/180。要将弧度转换为角度,将弧度乘以 180/pi。 ::: info **Atn** 是 [**Tan**](/official/Reference/VBA/Math/Tan) 的反三角函数,后者以角度为参数返回直角三角形两边的比值。不要将 **Atn** 与余切混淆,余切是正切的简单倒数(1/正切)。 ::: ### 示例 此示例使用 **Atn** 推导 pi 的近似值。 ```vb Const Pi As Double = Atn(1) * 4 ' pi ≈ 3.14159265358979 Debug.Print Pi Debug.Print Pi / 180 ' one degree in radians ≈ 0.0174532925199433 ``` ### 另请参阅 * [Cos](/official/Reference/VBA/Math/Cos)、[Sin](/official/Reference/VBA/Math/Sin)、[Tan](/official/Reference/VBA/Math/Tan) 函数 --- --- url: /en/official/Features/Attributes-Intro.md --- # Attributes twinBASIC supports defining attributes directly in code to annotate modules, classes, types, procedures, and more. These attributes provide compiler instructions and metadata. Attributes have two major functions: * they can act as instructions to compiler to influence how code is generated, or * to annotate Forms, Modules, Classes, Types, Enums, Declares, and [procedures](/en/official/Reference/Glossary#procedure) i.e. Subs/Functions/Properties. Previously in VBx, these attributes, such as procedure description, hidden, default member, and others, were set via hidden text the IDE's editor didn't show you, configured via the Procedure Attributes dialog or some other places. In tB, these are all visible in the code editor. The legacy ones from VBx are supported for compatibility, but new attributes use the following syntax: `[Attribute]` or `[Attribute(value)]` Many new attributes enable the additional language features twinBASIC provides, so some of the following items have their associated attributes included in their description. See also [the comprehensive reference for attributes](/en/official/Reference/Attributes). --- --- url: /en/official/Reference/Attributes.md --- # Attributes Attributes have two major functions: * they can act as instructions to compiler to influence how code is generated, or * to annotate Forms, Modules, Classes, Types, Enums, Declares, and [procedures](/en/official/Reference/Glossary#procedure) i.e. Subs/Functions/Properties. Previously in VBx, these attributes, such as the procedure description, hidden, default member, and others, were set via hidden text the IDE's editor didn't show you, configured via the Procedure Attributes dialog or some other places. In tB, these are all visible in the code editor. The legacy ones from VBx are supported for compatibility, but new attributes use the following syntax:\ `[Attribute]` or `[Attribute(value)]` In attributes that take an optional boolean argument, the value of the argument is taken to be **True** if no value is provided. This does not mean that the default value of the attribute is True, just that if the attribute is specified within the braces with no value, its value will be set to True. Different boolean-valued attributes have different default values. Those values apply unless the user has explicitly provided the attribute. Multiple attributes can be specified in the same square braces, separated by comma:\ `[Attribute1, Attribute2(param), Attribute3]` *** ## The available attributes are listed below in alphabetic order. Not every attribute applies to every language element. The applicability of each attribute is given below its syntax. ## AppObject (optional Bool) Syntax: **\[AppObject** \[ **( True** | **False )** ] **]** Applicable to: [**CoClass**](/en/official/Reference/Core/CoClass) Legacy VB attribute: *VB\_GlobalNameSpace* Indicates the class is part of the global namespace. You should not include this attribute without a full understanding of the meaning. The **Global** class is an AppObject. For more details, see [this VBA documentation page](https://learn.microsoft.com/en-us/openspecs/microsoft_general_purpose_programming_languages/ms-vbal/189fb41b-cc3a-4999-a6d2-ba89f72d2870). ## ArrayBoundsChecks (optional Bool) Syntax: **\[ArrayBoundsChecks** \[ **( True** | **False )** ] **]** Applicable to: [**Class**](/en/official/Reference/Core/Class), [**Module**](/en/official/Reference/Core/Module), [procedure](/en/official/Reference/Glossary#procedure) Disables or enables array element access bounds checking within the scope of a class, module, or a single procedure/method. Used on performance-critical routines. ## BindOnlyIfNoArguments (optional Bool) Syntax: **\[BindOnlyIfNoArguments** \[ **( True** | **False )** ] **]** Applicable to: [procedure](/en/official/Reference/Glossary#procedure) Only binds this name to a callsite when no arguments are present. Normally false, but see below for an exception. This attribute resolves the cases where compiler's special treatment of certain procedure names conflicts with a procedure of the same name that shouldn't be treated specially. This currently affects procedures named `Left`. Such procedures get an implicit `[BindOnlyIfNoArguments(True)]` assigned by the compiler. If the user wants to have a procedure of this name, it should include `[BindOnlyIfNoArguments(False)]`. ## BindOnlyIfStringSuffix (optional Bool) Syntax: **\[BindOnlyIfStringSuffix** \[ **( True** | **False )** ] **]** Applicable to: [procedure](/en/official/Reference/Glossary#procedure) ## ClassId (String) Syntax: **\[ClassId("** 00000000-0000-0000-0000-000000000000 **")]** Applicable to: [**Class**](/en/official/Reference/Core/Class) Assigns a COM CLSID to a class. For details, [see this COM documentation page](https://learn.microsoft.com/en-us/windows/win32/com/com-class-objects-and-clsids). ## ClassInterface twinBASIC doesn't supports this attribute directly. It supports its values under different names. See: * [DualInterface](#dualinterface) * [DispInterface](#dispinterface) ## CoClassCustomConstructor (String) Syntax: **\[CoClassCustomConstructor("** fully qualified path to factory method **")]** Applicable to: [**CoClass**](/en/official/Reference/Core/CoClass) Allows custom logic for creating and returning a new instance of the coclass' implementation. Example: ```vb [CoClassId("7980D953-10BF-478C-93BB-DD0093315D96")] [CoClassCustomConstructor("FooFactory.CreateFoo")] [COMCreatable(True)] Public CoClass Foo ' ... End CoClass ``` For an overview of coclasses in tB, see [Defining coclasses](/en/official/Features/Language/Interfaces-CoClasses#defining-coclasses). ## CoClassId (String) Syntax: **\[CoClassId("** 00000000-0000-0000-0000-000000000000 **")]** Applicable to: [**CoClass**](/en/official/Reference/Core/CoClass) In addition to interfaces, twinBASIC also allows defining coclasses -- creatable classes that implement one or more defined interfaces. Like interfaces, these too must be in .twin files and not legacy .bas/.cls files, and must appear prior to the `Class` or `Module` statement. The generic form is: ```vb [CoClassId("00000000-0000-0000-0000-000000000000")] *<attributes>* CoClass <name> [Default] Interface <interface name> *[Default, Source] Interface <event interface name>* *<additional Interface items>* End CoClass ``` The methods are [procedures](/en/official/Reference/Glossary#procedure). For an overview of coclasses in tB, see [Defining coclasses](/en/official/Features/Language/Interfaces-CoClasses#defining-coclasses). ## COMControl (optional Bool) Syntax: **\[COMControl** \[ **( True** | **False )** ] **]** Applicable to: [**Interface**](/en/official/Reference/Core/Interface) ## COMCreatable (optional Bool) Syntax: **\[COMCreatable** \[ **( True** | **False )** ] **]** Applicable to: [**Class**](/en/official/Reference/Core/Class), [**CoClass**](/en/official/Reference/Core/CoClass) Indicates that this coclass can be created with the [**New**](/en/official/Reference/Core/New) keyword. ## COMExtensible (optional Bool) Syntax: **\[COMExtensible** \[ **( True** | **False )** ] **]** Applicable to: [**Interface**](/en/official/Reference/Core/Interface), [procedure in an Interface](/en/official/Reference/Glossary#procedure) Specifies whether new members added at runtime can be called by name through an interface implementing **IDispatch**. This attribute is set to **False** by default. ## ComImport (optional Bool) Syntax: **\[ComImport** \[ **( True** | **False )** ] **]** Applicable to: [**Interface**](/en/official/Reference/Core/Interface) Specifies that an interface is an import from an external COM library, for instance, the Windows shell. ## CompileIf (Bool) Syntax: **\[CompileIf(** condition **)]** Applicable to: [procedure definitions](/en/official/Reference/Glossary#procedure) Controls the conditional compilation of a procedure definition. Has no default value. ## CompilerOptions (String) Syntax: **\[CompilerOptions( "** options **" )]** Applicable to: [procedure definitions](/en/official/Reference/Glossary#procedure) Typical use would be `[CompilerOptions("+llvm,+optimize,+optimizesize")]` ⁠to compile the procedure using built-in LLVMinstead of the default compiler, with chosen optimizations. Compiler options available: * **+llvm** - uses LLVM to compile this procedure. This feature is experimental at the moment, and cannot be used to compile functions with "complex" argument/variable types, such as objects, strings and dynamic arrays. The LLVM compiler back-end is built into twinBASIC. It is not necessary to have LLVM separately installed, and any such installation is ignored by twinBASIC. * **+optimize** - enables optimization during compilation of this procedure * **+optimizesize** - optimize this procedure for small code size, potentially at the expense of slower speed of the procedure * **+optimizespeed** - optimize this procedure for fast speed, potentially at the expense of larger code size post-compilation ## ConstantFoldable (optional Bool) Syntax: **\[ConstantFoldable** \[ **( True** | **False )** ] **]** Applicable to: [**Function**](/en/official/Reference/Core/Function) Specify this attribute for functions where when called with non-variable input, will be computed at compile time, rather than runtime. For example, a function to converted string literals to ANSI. The result would never change, so the resulting ANSI string is stored, rather than recomputing every run. Such functions are also called *pure functions*, because their output only depends on the arguments, and not on the state of the program. ## ConstantFoldableNumericsOnly (optional Bool) Syntax: **\[ConstantFoldableNumericsOnly** \[ **( True** | **False )** ] **]** Applicable to: [**Function**](/en/official/Reference/Core/Function) A limited case of [constant foldable attribute](#constantfoldable), which applies only if the function was called with a numeric parameter. ## CustomControl (String) Syntax: **\[Description("** image file name **")]** Applicable to: [**Class**](/en/official/Reference/Core/Class) ## Debuggable (optional Bool) Syntax: **\[Debuggable** \[ **( True** | **False )** ] **]** Applicable to: [**Module**](/en/official/Reference/Core/Module), [procedure in a **Class** or **Module**](/en/official/Reference/Glossary#procedure) When false, turns of breakpoints and stepping for the method or module. The default value is **True**. ## DebugOnly (optional Bool) Syntax: **\[DebugOnly** \[ **( True** | **False )** ] **]** Applicable to: [procedure definitions](/en/official/Reference/Glossary#procedure) Excludes calls to this procedure from the Build. They are only available when running from the IDE, i.e. debugging. ## DefaultMember (optional Bool) Syntax: **\[DefaultMember** \[ **(** **True** | **False** **)** ] **]** Applicable to: [procedure in a **Class**](/en/official/Reference/Glossary#procedure) Default members are accessed under the instance of the object itself, without specifying their name. For example, a class that offers indexable elements may have an **Item** property that is the default member: ```vb Class MyCollection [DefaultMember] Property Get Item(ByVal index&) As String ' ... End Property [DefaultMember] Property Let Item(ByVal index&, ByVal value$) ' ... End Property End Class Sub Example() Dim coll As New MyCollection Debug.Print "Item #3: ", coll(3) ' Property Get Item is invoked coll(4) = "Item 4" ' Property Let Item is invoked End Sub ``` ## Description (String) Syntax: **\[Description("** arbitrary text **")]** Applicable to: [**Class**](/en/official/Reference/Core/Class), [**CoClass**](/en/official/Reference/Core/CoClass), [**Const**](/en/official/Reference/Core/Const), [**Declare** (API declaration)](/en/official/Reference/Core/Declare), [**Interface**](/en/official/Reference/Core/Interface), [**Module**](/en/official/Reference/Core/Module), [**Type** (UDT)](/en/official/Reference/Core/Type) Provides a description in information popups in the IDE, and is exported as a `helpstring` attribute in the type library (if applicable). ## DispId (Integer) Syntax: **\[DispId(** 123 **)]** Applicable to: [procedure in an Interface](/en/official/Reference/Glossary#procedure) Defines a dispatch ID associated with the procedure when exposed via **IDispatch**. ## DispInterface Syntax: **\[DispInterface]** Applicable to: [**Interface**](/en/official/Reference/Core/Interface) in a **Library** ::: info This attribute is generated in the **Library** modules that twinBASIC generates for COM references in a project. It cannot be manually created. ::: Indicates that the interface exposes methods via **IDispatch** late-binding. This is the default. Note that [**DualInterface**](#dualinterface) can also be specified, giving much improved performance over that of **IDispatch**-based interfaces. ## DllExport (optional Bool) Syntax: **\[DllExport** \[ **( True** | **False )** ] **]** Applicable to: [procedures](/en/official/Reference/Glossary#procedure) and variables in a module. It's possible to export a function or variable from standard modules. Example: ```vb [DllExport] Public Const MyExportedSymbol As Long = &H00000001 ``` ## DLLStackCheck (optional Bool) Syntax: **\[DLLStackCheck** \[ **( True** | **False)** ] **]** Applicable to: [**Declare** (API declaration)](/en/official/Reference/Core/Declare) Gives minor codegen size reduction on 32-bit API calls on the Intel platform. Has no effect on other platforms. ## DualInterface Syntax: **\[DualInterface]** Applicable to: [**Interface**](/en/official/Reference/Core/Interface) in a **Library** ::: info This attribute is generated in the **Library** modules that twinBASIC generates for COM references in a project. It cannot be manually created. ::: Indicates that the interface exposes methods through the OLE VTable binding. The latter has much improved performance over that of **IDispatch**-based interfaces. ## EnforceErrors (optional Bool) Syntax: **\[EnforceErrors** \[ **( True** | **False )** ] **]** Applicable to: [procedures](/en/official/Reference/Glossary#procedure). ## EnforceWarnings (optional Bool) Syntax: **\[EnforceWarnings** \[ **( True** | **False )** ] **]** Applicable to: [procedures](/en/official/Reference/Glossary#procedure). ## EnumId (String) Syntax: **\[EnumId("** 00000000-0000-0000-0000-000000000000 **")]** Applicable to: [**Enum**](/en/official/Reference/Core/Enum) Specifies a GUID to be associated with an enum in type libraries. ## EventInterfaceId (String) Syntax: **\[EventInterfaceId("** 00000000-0000-0000-0000-000000000000 **")]** ## EventsUseDispInterface (optional Bool) Syntax: **\[EventsUseDispInterface** \[ **( True** | **False )** ] **]** ## Flags (optional Bool) Syntax: **\[Flags** \[ **( True** | **False )** ] **]** Applicable to: [**Enum**](/en/official/Reference/Core/Enum) Calculate implicit enum values as a flag set (powers of 2). ::: info To prevent confusion, once an explicit value is used, all remaining values after it must also be explicit) ::: ![image](/assets/flags-attribute.IxK5Gpre.png) ## FloatingPointErrorChecks (optional Bool) Syntax: **\[FloatingPointErrorChecks** \[ **( True** | **False)** ] **]** Applicable to: [**Class**](/en/official/Reference/Core/Class), [**Module**](/en/official/Reference/Core/Module), [procedure](/en/official/Reference/Glossary#procedure) Disables floating point error checks. Used on performance-critical routines. The default value is **True**. ## FormDesignerId (String) Syntax: **\[FormDesignerId("** 00000000-0000-0000-0000-000000000000 **")]** Applicable to: [**Class**](/en/official/Reference/Core/Class) ## Hidden (optional Bool) Syntax: **\[Hidden** \[ **(** **True** | **False** **)** ] **]** Applicable to: [**Class**](/en/official/Reference/Core/Class), [**CoClass**](/en/official/Reference/Core/CoClass), [**Interface**](/en/official/Reference/Core/Interface) Hides the interface or class from certain Intellisense and other lists. ## IdeButton (String) Syntax: **\[IdeButton("** caption **")]** Applicable to: [procedure](/en/official/Reference/Glossary#procedure) definition in a module. ## IgnoreWarnings (String List) Syntax: **\[IgnoreWarnings** **(** **TBnnnn** \[ **,** **TBmmmm** ]... **)** **]** Disables certain warnings. The list of strings should enumerate the warnings that are to be suppressed. ## IntegerOverflowChecks (optional Bool) Syntax: **\[IntegerOverflowChecks** \[ **( True** | **False )** ] **]** Applicable to: [**Class**](/en/official/Reference/Core/Class), [**Module**](/en/official/Reference/Core/Module), [procedure](/en/official/Reference/Glossary#procedure) Disables integer overflow checks. Used on performance-critical routines. The default value is **True**. ## InterfaceId (String) Syntax: **\[InterfaceId( "**00000000-0000-0000-0000-000000000000**" )]** Applicable to: [**Interface**](/en/official/Reference/Core/Interface) twinBASIC supports defining COM interfaces using BASIC syntax, rather than needing an type library with IDL and C++. These are only supported in .twin files, not in legacy .bas or .cls files. They must appear *before* the [**Class**](/en/official/Reference/Core/Class) or [**Module**](/en/official/Reference/Core/Module) statement, and will always have a project-wide scope. the The generic form for is as follows: ```vb [InterfaceId ("00000000-0000-0000-0000-000000000000")] *<attributes>* Interface <name> Extends <base-interface> *<attributes>* <method 1> *<attributes>* <method 2> ' ... End Interface ``` The methods are [procedures](/en/official/Reference/Glossary#procedure). For an overview of interfaces in tB, see [Defining interfaces](/en/official/Features/Language/Interfaces-CoClasses#defining-interfaces). ## MustBeQualified (optional Bool) Syntax: **\[MustBeQualified** \[ **(True** | **False )** ] **]** Applicable to: [procedure](/en/official/Reference/Glossary#procedure) ## OleAutomation (optional Bool) Syntax: **\[OleAutomation** \[ **(True** | **False )** ] **]** Applicable to: [**Interface**](/en/official/Reference/Core/Interface) Controls whether this attribute is applied in the typelibrary. This attribute is set to **True** by default. ## PackingAlignment (Integer) Syntax: **\[PackingAlignment( 1** | **2** | **4** | **8** | **16** | **32** | **64 )]** Applicable to: [**Type** (UDT)](/en/official/Reference/Core/Type) twinBASIC normally aligns objects naturally within UDTs, e.g. an 8-byte object is aligned at the 8-byte boundary relative to the beginning of the UDT. This can leave gaps between UDT fields. A tighter packing can be achieved with a smaller **PackingAlignment**: ```vb [PackingAlignment(2)] Private Type MyUDT x As Integer y As Long z As Integer End Type Private t As MyUDT Debug.Assert Len(t) = 8 And LenB(t) = 8 ``` You'll now find that both `Len(t)` and `LenB(t)` are 8. ::: info Alignment, not packing alignment, is not set this way. Specifying 16 would not get you a 16-byte structure for `t`. twinBASIC does not currently have an equivalent for `__declspec_align(n)`, but such a feature is planned. This is rare outside kernel mode programming. ::: For introduction to this feature, see [Custom UDT Packing](/en/official/Features/Language/UDTs#custom-udt-packing). ## PopulateFrom (...) Syntax: **\[PopulateFrom( "json", "**internal path to .json**", "** table field **", "** name field **", "** value field **" )]** Applicable to: [**Enum**](/en/official/Reference/Core/Enum) Populates an **Enum** with values from a json file bundled with the project. The path to the .json file, and the field names, are arbitrary. Thus, the json file doesn't have to be in the Resources folder within the project. In the future, this attribute may be expanded to allow more data file types, and more context of use besides **Enum**. For example, consider this enum declaration in a .twin file: ```vb [PopulateFrom("json", "/Resources/MESSAGETABLE/Strings.json", "events", "name", "id")] Enum EVENTS End Enum ``` Then, there should be a `/Resources/MESSAGETABLE/Strings.json` file with following structure: ```json { "events": [ { "id": -1073610751, "name": "service_started", "LCID_0000": "%1 service started" }, ], } ``` The result is as-if we hand-typed the following **Enum** definition: ```vb Enum EVENTS service_started = -1073610751 End Enum ``` ## PredeclaredID (optional Bool) Syntax: **\[PredeclaredId** \[ **( True** | **False )** ] **]** Applicable to: [**Class**](/en/official/Reference/Core/Class) When set, a global instance of the class is created when the application starts. This attribute is equivalent to the `VB_PredeclaredId` attribute in VBx .cls files. ## PreserveSig (optional Bool) Syntax: **\[PreserveSig** \[ **(** **True** | **False** **)** ] **]** Applicable to: Method in an [Interface](/en/official/Reference/Core/Interface), [API Declarations](/en/official/Reference/Core/Declare). Default value: **False** in an Interface, **True** in an API Declare. In COM interfaces, the default value of this attribute is **False**, since normally methods return an HRESULT that the language hides from you. **\[PreserveSig** \[ **(True)** ] **]** overrides this behavior and defines the function exactly as you provide. This is necessary if you need to define it as returning something other than a 4-byte **Long**, or want to handle the result yourself, bypassing the normal runtime error raised if the return value is negative (this is helpful when a negative value indicates an expected, acceptable failure, rather than a true error, like when an enum interface is out of items). In APIs, the default value of this attribute is `True`. So therefore, you can specify `False` to rewrite the last parameter as a return. Example: ```vb Public Declare PtrSafe Function SHGetDesktopFolder Lib "shell32" (ppshf As IShellFolder) As Long ``` can be rewritten as ```vb [PreserveSig(False)] Public Declare PtrSafe Function SHGetDesktopFolder Lib "shell32" () As IShellFolder` ``` ## Restricted (optional Bool) Syntax: **\[Restricted** \[ **( True** | **False )** ] **]** Applicable to: [**Interface**](/en/official/Reference/Core/Interface) Restricts the interface methods from being called in most contexts. This is attribute has the same function as the [**restricted** MIDL attribute][MIDL restricted]. [MIDL restricted]: https://learn.microsoft.com/en-us/windows/win32/midl/restricted ## RunAfterBuild (optional Bool) Syntax: **\[RunAfterBuild** \[ **( True** | **False )** ] **]** Applicable to: [**Function**](/en/official/Reference/Core/Function), [**Sub**](/en/official/Reference/Core/Sub) Specifies a function that runs after your exe is built. Tthere's `App.LastBuildPath` to know where it is if you're e.g. signing the executable. ## Serialize (optional Bool) Syntax: **\[Serialize** \[ **( True** | **False )** ] **]** Applicable to: variables in a [**Class**](/en/official/Reference/Core/Class) ## SetDllDirectory (optional Bool) Syntax: **\[SetDllDirectory** \[ **( True** | **False )** ] **]** Applicable to: [**Declare** (API declaration)](/en/official/Reference/Core/Declare), [**Module**](/en/official/Reference/Core/Module) Allows an explicitly loaded DLL to load its own dependencies from it's load path. Also has the effect of allowing searching the app path for the DLLs in the base app's declare statements. It can be used per-declare or within a module. ## SimplerByVals (optional Bool) Syntax: **\[SimplerByVals** \[ **( True** | **False )** ] **]** Applicable to: [procedure](/en/official/Reference/Glossary#procedure) ## SpecialCompilerBinding (optional Bool) Syntax: **\[SpecialCompilerBinding** \[ **( True** | **False )** ] **]** ## TestCase (optional Bool) Syntax: **\[TestCase** \[ **( True** | **False )** ] **]** Applicable to: [procedure](/en/official/Reference/Glossary#procedure) definition in a module. ## TestFixture (optional Bool) Syntax: \*\*\[TestFixture \*\*\[ **( True** | **False )** ] **]** Applicable to: [**Module**](/en/official/Reference/Core/Module) ## TypeHint (EnumType) Syntax: **\[TypeHint(** an enum type **)]** Applicable to: [procedure](/en/official/Reference/Glossary#procedure) parameters Allows populating Intellisense with an enum for types other than **Long**. ## Unimplemented (optional Bool) Syntax: **\[Unimplemented** \[ **( True** | **False )** ] **]** Applicable to: [procedure](/en/official/Reference/Glossary#procedure) definitions Makes the compiler issue a warning about the procedure being unimplemented wherever it's called. You can upgrade it to an error too. ## UseGetLastError (optional Bool) Syntax: **\[UseGetLastError** \[ **( True** | **False )** ] **]** Applicable to: [**Declare** (API declaration)](/en/official/Reference/Core/Declare) If the declared function indicates an error condition, the compiler won't automatically call `GetLastError` to retrieve the error code. The default value of this attribute is **True**, i.e. Declare-d functions are assumed to set `LastError` upon error. ## UserDefinedTypeIsAnAlias (optional Bool) Syntax: **\[UserDefinedTypeIsAnAlias** \[ **( True** | **False )** ] **]** Applicable to: [**Type** (UDT)](/en/official/Reference/Core/Type) ## WindowsControl (optional Bool) Syntax: **\[WindowsControl** \[ **( True** | **False )** ] **]** --- --- url: /zh/official/Reference/Core/Attributes.md --- # Attributes 语句 attributes 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/Attributes.md --- # Attributes Statement Documentation for the attributes keyword is not yet available. --- --- url: /en/official/Reference/VBRUN/DataObject/AvailableFormats.md --- # AvailableFormats Returns a [**DataObjectFormats**](/en/official/Reference/VBRUN/DataObject/DataObjectFormats) collection describing every format the **DataObject** currently holds a value in. Syntax: *object*.**AvailableFormats** *object* : *required* An object expression that evaluates to a **DataObject**. Each element of the returned collection is a [**DataObjectFormat**](/en/official/Reference/VBRUN/DataObject/DataObjectFormat) descriptor with the format's `Name`, its `FormatType` from **ClipboardConstants**, and information about how the format is stored. Use this when the consumer side does not know in advance which formats the source has supplied --- typically in OLE drag-and-drop or paste operations from another application. ::: info **AvailableFormats** is a twinBASIC addition; VB6 callers had to probe each format of interest with **GetFormat** instead. ::: ### Example ```vb Dim F As DataObjectFormat For Each F In Data.AvailableFormats Debug.Print F.Name, F.FormatType Next F ``` ### See Also * [DataObjectFormats](/en/official/Reference/VBRUN/DataObject/DataObjectFormats) collection * [DataObjectFormat](/en/official/Reference/VBRUN/DataObject/DataObjectFormat) * [GetFormat](/en/official/Reference/VBRUN/DataObject/GetFormat) method * [GetFormatByName](/en/official/Reference/VBRUN/DataObject/GetFormatByName) method --- --- url: /zh/official/Reference/VBRUN/DataObject/AvailableFormats.md --- # AvailableFormats 返回[**DataObjectFormats**](/official/Reference/VBRUN/DataObject/DataObjectFormats)集合,描述**DataObject**当前保存值的所有格式。 语法:*object*.**AvailableFormats** *object* : *必需* 求值为**DataObject**的对象表达式。 返回集合的每个元素是[**DataObjectFormat**](/official/Reference/VBRUN/DataObject/DataObjectFormat)描述符,包含格式的`Name`、来自**ClipboardConstants**的`FormatType`以及格式存储方式的信息。当消费端事先不知道源端提供了哪些格式时使用——通常在OLE拖放或从其他应用程序粘贴操作中。 ::: info **AvailableFormats**是twinBASIC新增功能;VB6调用方必须使用**GetFormat**逐一探测每种格式。 ::: ### 示例 ```vb Dim F As DataObjectFormat For Each F In Data.AvailableFormats Debug.Print F.Name, F.FormatType Next F ``` ### 另见 * [DataObjectFormats](/official/Reference/VBRUN/DataObject/DataObjectFormats) 集合 * [DataObjectFormat](/official/Reference/VBRUN/DataObject/DataObjectFormat) * [GetFormat](/official/Reference/VBRUN/DataObject/GetFormat) 方法 * [GetFormatByName](/official/Reference/VBRUN/DataObject/GetFormatByName) 方法 --- --- url: /en/official/Reference/VBRUN/AmbientProperties/BackColor.md --- # BackColor Returns the background colour the container would like its embedded controls to use by default, as an **stdole.OLE\_COLOR**. Read-only. Syntax: *object*.**BackColor** *object* : *required* An object expression that evaluates to an **AmbientProperties** object. A control that does not have its own background colour explicitly set should paint its background using this colour, so that it blends in with the surrounding container. The value is an **OLE\_COLOR**: an RGB value, a system-colour reference, or a palette-index reference. Pass it through [**TranslateColor**](/en/official/Reference/VBA/Information/TranslateColor) to obtain a plain RGB value if needed. ### Example This example responds to an ambient **BackColor** change and applies it to the control's background. ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "BackColor" UserControl.BackColor = Ambient.BackColor End Select End Sub ``` ### See Also * [ForeColor](/en/official/Reference/VBRUN/AmbientProperties/ForeColor) property * [Font](/en/official/Reference/VBRUN/AmbientProperties/Font) property * [Palette](/en/official/Reference/VBRUN/AmbientProperties/Palette) property --- --- url: /zh/official/Reference/VBRUN/AmbientProperties/BackColor.md --- # BackColor 返回容器希望其嵌入控件默认使用的背景色,类型为**stdole.OLE\_COLOR**。只读。 语法:*object*.**BackColor** *object* : *必需* 求值为**AmbientProperties**对象的对象表达式。 未显式设置自身背景色的控件应使用此颜色绘制其背景,以与周围容器融合。该值为**OLE\_COLOR**:RGB值、系统颜色引用或调色板索引引用。如需获取普通RGB值,可通过[**TranslateColor**](/official/Reference/VBA/Information/TranslateColor)转换。 ### 示例 此示例响应环境**BackColor**更改并将其应用于控件背景。 ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "BackColor" UserControl.BackColor = Ambient.BackColor End Select End Sub ``` ### 另见 * [ForeColor](/official/Reference/VBRUN/AmbientProperties/ForeColor) 属性 * [Font](/official/Reference/VBRUN/AmbientProperties/Font) 属性 * [Palette](/official/Reference/VBRUN/AmbientProperties/Palette) 属性 --- --- url: /en/official/Reference/VBRUN/Constants/BackFillStyleConstants.md --- # BackFillStyleConstants Whether a control's background fill is opaque or transparent. | Constant | Value | Description | |----------|-------|-------------| | **vbBFTransparent** | 0 | The background of the control is transparent --- whatever is behind it shows through. | | **vbBFOpaque** | 1 | The background of the control is filled solidly with its **BackColor**. | --- --- url: /zh/official/Reference/VBRUN/Constants/BackFillStyleConstants.md --- # BackFillStyleConstants 控件背景填充是不透明还是透明。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbBFTransparent** | 0 | 控件背景透明 --- 后面的内容可见。 | | **vbBFOpaque** | 1 | 控件背景用其**BackColor**纯色填充。 | --- --- url: /en/official/Reference/VBA/Interaction/Beep.md --- # Beep Sounds a tone through the computer's speaker. Syntax: **Beep** The frequency and duration of the beep depend on the hardware and system software, and vary among computers. ### Example This example uses the **Beep** statement to sound three consecutive tones through the computer's speaker. ```vb Dim I% For I = 1 To 3 ' Loop 3 times. Beep ' Sound a tone. Next I ``` ### See Also * [DoEvents](/en/official/Reference/VBA/Interaction/DoEvents) function * [Shell](/en/official/Reference/VBA/Interaction/Shell) function * [MsgBox](/en/official/Reference/VBA/Interaction/MsgBox) function --- --- url: /zh/official/Reference/VBA/Interaction/Beep.md --- # Beep 通过计算机扬声器发出提示音。 语法:**Beep** 提示音的频率和持续时间取决于硬件和系统软件,因计算机而异。 ### 示例 本示例使用**Beep**语句通过计算机扬声器连续发出三次提示音。 ```vb Dim I% For I = 1 To 3 ' Loop 3 times. Beep ' Sound a tone. Next I ``` ### 另请参阅 * [DoEvents](/official/Reference/VBA/Interaction/DoEvents)函数 * [Shell](/official/Reference/VBA/Interaction/Shell)函数 * [MsgBox](/official/Reference/VBA/Interaction/MsgBox)函数 --- --- url: /zh/official/Reference/Core/Beep.md --- # Beep 语句 beep 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/Beep.md --- # Beep Statement Documentation for the beep keyword is not yet available. --- --- url: /en/official/Reference/VBA/TbExpressionService/Bind.md --- # Bind Resolves a symbol referenced in an expression to an [**ITbExpression**](./#itbexpression-interface) that produces its value. Syntax: *binder*.**Bind(** *symbol*, *argCount* **)** *binder* : *required* An object expression that evaluates to an [**ITbCustomBinder**](./#itbcustombinder-interface) object. *symbol* : *required* A **String** containing the name being looked up --- the identifier as it appears in the source of the expression being compiled. *argCount* : *required* A **Long** giving the number of arguments at the call site, or `0` if *symbol* is referenced as a bare value (a property-style access). The return value is an [**ITbExpression**](./#itbexpression-interface) whose [**Evaluate**](/en/official/Reference/VBA/TbExpressionService/Evaluate) method produces the value of *symbol* when invoked, or **Nothing** to indicate that this binder cannot resolve *symbol* and the engine should fall through to the next binder. **Bind** is called by the engine during compilation --- once per unresolved symbol encountered in the expression source --- not at evaluation time. The implementer is expected either to construct an **ITbExpression** that, when later evaluated, produces the value, or to return **Nothing** so that another binder gets a chance. The *argCount* parameter lets the implementer distinguish a property-style reference (`MyName`, where *argCount* is `0`) from a function-style call (`MyName(1, 2, 3)`, where *argCount* is `3`), and bind them to different things. A class registers itself as a binder by including `Implements ITbCustomBinder` and then passing itself to [**AddCustomBinder**](/en/official/Reference/VBA/TbExpressionService/AddCustomBinder). ### Example This **ITbCustomBinder** implementation looks up zero-argument symbols against the current row of an external recordset, deferring to the next binder for everything else. ```vb Implements ITbCustomBinder Public Recordset As Object Protected Function Bind(ByVal Symbol As String, ByVal ArgCount As Long) As ITbExpression _ Implements ITbCustomBinder.Bind If ArgCount = 0 AndAlso Recordset IsNot Nothing Then Dim Field As Object = Recordset.GetFieldBinder(Symbol) If TypeOf Field Is ITbExpression Then Return CType(Of ITbExpression)(Field) End If End If ' Returning Nothing lets the next binder try. End Function ``` ### See Also * [AddCustomBinder](/en/official/Reference/VBA/TbExpressionService/AddCustomBinder) method * [Evaluate](/en/official/Reference/VBA/TbExpressionService/Evaluate) method * [Compile](/en/official/Reference/VBA/TbExpressionService/Compile) method --- --- url: /zh/official/Reference/VBA/TbExpressionService/Bind.md --- # Bind 将表达式中引用的符号解析为产生其值的 [**ITbExpression**](./#itbexpression-interface)。 语法:*binder*.**Bind(** *symbol*, *argCount* **)** *binder* : *必需* 计算结果为 [**ITbCustomBinder**](./#itbcustombinder-interface) 对象的对象表达式。 *symbol* : *必需* 包含正在查找的名称的 **String**——即正在编译的表达式源中出现的标识符。 *argCount* : *必需* 给出调用点参数数量的 **Long**,如果 *symbol* 作为裸值引用(属性式访问)则为 `0`。 返回值是一个 [**ITbExpression**](./#itbexpression-interface),其 [**Evaluate**](/official/Reference/VBA/TbExpressionService/Evaluate) 方法在调用时产生 *symbol* 的值,或返回 **Nothing** 以指示此绑定器无法解析 *symbol*,引擎应继续查询下一个绑定器。 **Bind** 在编译期间由引擎调用——对表达式源中遇到的每个未解析符号调用一次——而非在求值时。实现者应构造一个 **ITbExpression**,在稍后求值时产生该值,或返回 **Nothing** 以便另一个绑定器有机会处理。 *argCount* 参数使实现者可以区分属性式引用(`MyName`,*argCount* 为 `0`)和函数式调用(`MyName(1, 2, 3)`,*argCount* 为 `3`),并将它们绑定到不同的事物。 类通过包含 `Implements ITbCustomBinder` 然后将其自身传递给 [**AddCustomBinder**](/official/Reference/VBA/TbExpressionService/AddCustomBinder) 来将自身注册为绑定器。 ### 示例 此 **ITbCustomBinder** 实现针对外部记录集的当前行查找零参数符号,将其他所有内容推迟到下一个绑定器。 ```vb Implements ITbCustomBinder Public Recordset As Object Protected Function Bind(ByVal Symbol As String, ByVal ArgCount As Long) As ITbExpression _ Implements ITbCustomBinder.Bind If ArgCount = 0 AndAlso Recordset IsNot Nothing Then Dim Field As Object = Recordset.GetFieldBinder(Symbol) If TypeOf Field Is ITbExpression Then Return CType(Of ITbExpression)(Field) End If End If ' Returning Nothing lets the next binder try. End Function ``` ### 另请参阅 * [AddCustomBinder](/official/Reference/VBA/TbExpressionService/AddCustomBinder) 方法 * [Evaluate](/official/Reference/VBA/TbExpressionService/Evaluate) 方法 * [Compile](/official/Reference/VBA/TbExpressionService/Compile) 方法 --- --- url: /en/official/Documentation/Book-Configuration.md --- # Book Configuration `docs/_book.yml` defines the chapter manifest for the PDF book: which pages appear, in what order, and how they map to named parts and chapters. `book.mjs` reads this file during Phase 2 (to resolve page selectors) and Phase 8 (to assemble `book.html`). See [Pipeline Stages](/en/official/Documentation/Pipeline-Stages) for the relevant interface contracts. ## File location and load order **File:** `docs/_book.yml` `data.mjs` loads `_book.yml` during Phase 2 and makes it available as `site.data.book`. The orchestrator then exposes `site.data.book` as `site.bookData` and passes it to `resolveBookChapters`. That call traverses the entire structure and resolves every selector to a concrete `Page[]` stored as `entry._chapters`, so Phase 8's `assembleBook` has no further page lookups to do. Run `build.bat` then `book.bat` to see the effect of changes. The `check.bat` integrity check also runs a PDF build pass. ## Top-level structure ```yaml front_matter: - <entry> # zero or more entries, emitted before the first Part - ... parts: - <part> # one or more numbered Parts - ... ``` **`front_matter`** entries are emitted between the title page and the first numbered Part. They produce no divider page and no part number. **`parts`** entries each produce a numbered divider page. A part may contain a flat set of pages or an ordered list of `chapters`, each of which produces its own sub-divider page. Both `front_matter` entries and parts (and their chapters) share the [selector schema](#selector-schema) and [common entry options](#common-entry-options) described below. ## Selector schema Every entry may combine any of these keys to select the pages it contributes to the book. All matches are `contains` by default --- the page's URL or nav-path must contain the prefix string. Set `no_descent: true` on the entry to switch all its matches to exact equality. | Key | Type | Description | | ------------ | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `page` | `string` | Single URL prefix. Shorthand for a one-element `pages:` list. | | `pages` | `string[]` | List of URL prefixes. Each prefix is tested against the page's `permalink` field. | | `nav_page` | `string` | Single nav-path prefix. Shorthand for a one-element `nav_pages:` list. A page's nav-path is its slash-joined `grand_parent / parent / title` chain, as populated by `nav.mjs`. | | `nav_pages` | `string[]` | List of nav-path prefixes, tested against each page's `navPath` field. | | `no_descent` | `boolean` | When `true`, switches every match on this entry from `contains` to exact equality. Use this when a prefix like `/Foo/` should match only the index page and not its sub-pages, or when `page: /` would otherwise sweep in every page on the site. | All selector keys are combinable within one entry. An entry with both `page` and `nav_page` collects the union of both selections. Selectors on a chapter entry are independent of the selectors on the containing part --- a chapter collects its own pages; the part does not automatically inherit them. ## Common entry options Front\_matter entries, parts, and chapters all support these options. Where behaviour differs between parts and chapters, the part form is noted first with the chapter form in parentheses. ### `title` / `subtitle` ```yaml title: "VBA Package" subtitle: "Standard runtime modules --- Strings, Math, FileSystem, and the rest" ``` `title` is the text for the divider heading --- H1 for parts, H2 for chapters. `subtitle` is an optional subheading rendered below `title`. Both are used as the PDF bookmark label. When `landing_is_target:` is set, `title` is injected into the landing page's article rather than rendered on a standalone divider page. ### `landing_page` ```yaml landing_page: /tB/Packages/VBA ``` A single absolute URL. The named page is emitted first in the entry's content list, before any prefix-swept pages. It is excluded from prefix matches so it is not emitted twice. Its source H1 is stripped by the rewriter so the divider heading remains the sole PDF outline entry for the entry. Unlike `foreword_page:`, a `landing_page` renders with a normal running header and regular article styling. ### `landing_is_target` ```yaml landing_page: /tB/Packages/VBA landing_is_target: true ``` Requires `landing_page:`. When set, the divider page renders silently and the entry `title` is injected as an H1 (part) or H2 (chapter) at the start of the landing-page article. The PDF bookmark navigates to the landing page rather than to a blank divider page. The landing's own source H1 is still stripped. Pair with `outline_closed:` to start the bookmark collapsed. ### `no_outline_entry` ```yaml no_outline_entry: true ``` Emits the divider `title` as a silent `<p>` instead of an H1 or H2. PagedJS skips silent paragraphs when building the PDF outline, so the entry has no bookmark of its own. The first content heading in the entry's pages becomes the bookmark target instead. When combined with `landing_page:`, the landing's source H1 strip is skipped --- the landing's own first heading becomes the bookmark target. Pair with `no_heading_shift:` to keep that heading at the correct depth. ### `no_heading_shift` ```yaml no_heading_shift: true ``` Controls how the heading assembler shifts levels to prevent multiple H1s in the combined `book.html`. See [Heading-shift mechanics](#heading-shift-mechanics) below. ### `outline_closed` ```yaml outline_closed: true ``` Starts the PDF bookmark for this entry collapsed (children hidden until expanded in a PDF reader). The `data-pdf-bookmark-closed` attribute is stamped on: * the divider H1 / H2, for entries with a visible divider heading; * the first content article, for `no_outline_entry` entries (PagedJS finds the heading via `closest()`); * the injected heading directly, for `landing_is_target` entries. ## Part-only options ### `foreword_page` ```yaml foreword_page: /tB/Packages/ ``` A single absolute URL. The named page is emitted as `<article class="part-foreword">` right after the part divider, before any chapter dividers. No running header (CSS suppresses the page chrome for foreword articles). The foreword's source H1 is not stripped and it does not become a PDF outline entry. Distinct from `landing_page:` in two ways: the source H1 is preserved, and there is no outline contribution from the foreword itself. ### `chapters` ```yaml chapters: - title: VBA Package ... - title: VBRUN Package ... ``` An ordered list of chapter entries. Each chapter produces its own divider page (H2) and uses the same selector schema and common entry options above. No chapter-specific options exist beyond those shared with parts. ## Heading-shift mechanics The PDF assembler shifts heading levels to prevent source H1s from competing with part and chapter divider headings: * **Parts (no chapters):** every page in the part receives a +1 shift --- source H1 renders as H2, H2 as H3, and so on. Set `no_heading_shift: true` on the part entry to skip this shift and keep source H1 as H1. * **Chapters inside a part:** every page receives a +2 shift total (base +1 from the part, plus an additional +1 for the chapter level) --- source H1 renders as H3. Set `no_heading_shift: true` on the chapter entry to skip only the extra +1, so source H1 renders as H2 instead of H3. Typical pattern: pair `no_outline_entry: true` with `no_heading_shift: true` when a single-page part or chapter should use the landing's own H1 as the PDF bookmark target without a redundant silent divider above it. ## Sort order Within each entry, selected pages are ordered by `sortByNavOrder`: 1. **Index pages first** --- any page whose URL ends in `/`. 2. **Pages with `nav_order`** --- ascending by `nav_order` value, with `title` as the tie-breaker. 3. **Pages without `nav_order`** --- alphabetically by `title`. 4. **Grouped by owning index** --- an index page and its direct sub-pages stay adjacent. A `landing_page:` URL is always placed first, before the sorted set, and is excluded from the sorted set so it is not emitted twice. ## Worked examples ### Chapter with `landing_is_target` ```yaml - title: VBA Package subtitle: Standard runtime modules --- Strings, Math, FileSystem, and the rest landing_page: /tB/Packages/VBA page: /tB/Modules/ landing_is_target: true outline_closed: true ``` What this produces in the PDF: 1. A chapter divider rendered silently (no visible H2 page), because `landing_is_target: true`. 2. The VBA landing page at `/tB/Packages/VBA` --- first article, with `"VBA Package"` injected as an H2 at the top of its content. Its original source H1 is stripped. 3. Every page whose URL contains `/tB/Modules/`, sorted by `sortByNavOrder`. 4. The PDF bookmark for this chapter navigates to the VBA landing page and starts collapsed. *** ### Chapter with a visible divider and `nav_page` selector ```yaml - title: Operators nav_page: Reference Section/Operators outline_closed: true ``` What this produces: 1. A visible H2 divider page titled "Operators". 2. All pages whose `navPath` contains `Reference Section/Operators`, in nav order. 3. A PDF bookmark navigating to the divider page, starting collapsed. *** ### Front-matter entry with `no_outline_entry` and `no_descent` ```yaml front_matter: - title: Introduction page: / no_outline_entry: true no_heading_shift: true no_descent: true outline_closed: true ``` What this produces: 1. The root page (`/`) only --- `no_descent: true` prevents `/` from sweeping in every page on the site. 2. The divider title "Introduction" renders as a silent `<p>` (no own bookmark). The page's source H1 becomes the PDF bookmark target instead. 3. Because `no_heading_shift: true` is set, the source H1 renders as H1 rather than H2. 4. The bookmark starts collapsed. *** ### Part with a foreword and nested chapters ```yaml - title: Packages subtitle: The runtime and library packages shipped with twinBASIC outline_closed: true foreword_page: /tB/Packages/ chapters: - title: VBA Package ... - title: VBRUN Package ... ``` What this produces: 1. A part divider page (H1) titled "Packages". 2. The page at `/tB/Packages/` emitted as a foreword article (no running header, no outline entry). Its H1 is preserved. 3. Chapter divider pages (H2) for each chapter, followed by that chapter's pages in nav order. ## See Also * [Pipeline Stages](/en/official/Documentation/Pipeline-Stages) -- the `book.mjs` interface contracts. * [tbdocs Builder](/en/official/Documentation/Builder) -- design rationale for `book.mjs`. --- --- url: /en/official/Reference/CustomControls/Styles/Borders.md --- # Borders class The collection of border strokes drawn around a region. Each stroke is an independent [**Border**](#border-class) sub-object with its own thickness, fill, and blending behaviour, layered in source order. A single thin black outline is a one-element collection --- easiest constructed by calling [**SetSimpleBorder**](#setsimpleborder). Accessed as `<state>.Borders`, [**CellRenderingOptions.Borders**](/en/official/Reference/CustomControls/WaynesGrid/CellRenderingOptions#borders), and the slider's `<sliderState>.BackgroundBorders` / `BlockBorders`. The array of [**Border**](#border-class) sub-objects on a [**TextRendering**](/en/official/Reference/CustomControls/Styles/TextRendering)'s **Outlines** member uses the same element type. ```vb btnGo.NormalState.Borders.SetSimpleBorder StrokeSize:=1, ColorRGB:=vbBlack ``` Layered borders --- multiple [**Border**](#border-class) instances stroked in order --- are assigned to the [**Elements**](#elements) array directly. Each element can have its own [**StrokeSize**](#strokesize) and its own [**Fill**](/en/official/Reference/CustomControls/Styles/Fill), so a thin black outline can sit on top of a wide coloured band, or three bands of different colours can stack into a "shadow": ```vb Dim elems(0 To 2) As Border Set elems(0) = New Border elems(0).StrokeSize = 4 elems(0).Fill.ColorPoints.SetSolidColor vbBlack Set elems(1) = New Border elems(1).StrokeSize = 7 elems(1).Fill.ColorPoints.SetSolidColor &H99CCFF ' light blue band Set elems(2) = New Border elems(2).StrokeSize = 4 elems(2).Fill.ColorPoints.SetSolidColor &H4D7AB4 ' deeper blue btnGo.NormalState.Borders.Elements = elems ``` A single [**Border**](#border-class) can also display a gradient instead of a solid colour --- assign a multi-stop [**Fill**](/en/official/Reference/CustomControls/Styles/Fill) to its [**Fill**](#fill) member. Set [**BlendWithBackgroundFill**](#blendwithbackgroundfill) to **True** on a translucent border to make it tint with the control's own **BackgroundFill** rather than with whatever lies under the control. ## Properties ### Elements The array of [**Border**](#border-class) sub-objects, drawn in order from index 0 outward. Read-write but in practice populated through [**SetSimpleBorder**](#setsimpleborder) or [**SetSimpleBorderRGBA**](#setsimpleborderrgba). ## Methods ### SetSimpleBorder Replaces the [**Elements**](#elements) array with a single border stroke of the given thickness and fully-opaque colour. Syntax: *object*.**SetSimpleBorder** *StrokeSize*, *ColorRGB* *StrokeSize* : *required* A **Long** giving the stroke thickness in pixels. *ColorRGB* : *required* A **Long** RGB colour for the stroke fill. ### SetSimpleBorderRGBA Replaces the [**Elements**](#elements) array with a single border stroke whose alpha is taken from the supplied [**ColorRGBA**](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) rather than forced opaque. Useful for transparent borders that are present only as visual padding (the slider uses a fully transparent border on the **BlockBorders** to indent the block inside the background). Syntax: *object*.**SetSimpleBorderRGBA** *StrokeSize*, *ColorRGBA* *StrokeSize* : *required* A **Long** giving the stroke thickness in pixels. *ColorRGBA* : *required* A [**ColorRGBA**](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) value for the stroke fill. ## Events ### OnChanged Raised when the [**Elements**](#elements) array is reassigned, or when any single [**Border**](#border-class) element raises its own **OnChanged**. ## Border class A single border stroke. Elements of [**Borders.Elements**](#elements), and also of [**TextRendering.Outlines**](/en/official/Reference/CustomControls/Styles/TextRendering#outlines). ### BlendWithBackgroundFill When **True**, the border's colour alpha-blends with the control's **BackgroundFill** rather than with whatever is painted underneath the control. Lets a translucent border colour use the background tint instead of the form's. **Boolean**. Default: **False**. ### Fill The [**Fill**](/en/official/Reference/CustomControls/Styles/Fill) that supplies the colour or gradient used to stroke the border. Newly-constructed [**Border**](#border-class) objects pre-set this to a solid black fill. ### StrokeSize The stroke thickness in pixels. [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount). Default: 1. ### New Constructs a [**Border**](#border-class) with a default solid-black [**Fill**](#fill). Syntax: **New Border** ### OnChanged Raised when [**StrokeSize**](#strokesize), [**Fill**](#fill), or [**BlendWithBackgroundFill**](#blendwithbackgroundfill) is assigned, or when the contained [**Fill**](#fill) raises its own **OnChanged**. --- --- url: /zh/official/Reference/CustomControls/Styles/Borders.md --- # Borders 类 绘制在区域周围的边框笔触集合。每条笔触是独立的 [**Border**](#border-class) 子对象,具有自己的粗细、填充和混合行为,按源顺序分层。单条细黑色轮廓是单元素集合——最简单的构建方式是调用 [**SetSimpleBorder**](#setsimpleborder)。 通过 `<state>.Borders`、[**CellRenderingOptions.Borders**](/official/Reference/CustomControls/WaynesGrid/CellRenderingOptions#borders) 以及滑块的 `<sliderState>.BackgroundBorders` / `BlockBorders` 访问。[**TextRendering**](/official/Reference/CustomControls/Styles/TextRendering) 的 **Outlines** 成员上的 [**Border**](#border-class) 子对象数组使用相同的元素类型。 ```vb btnGo.NormalState.Borders.SetSimpleBorder StrokeSize:=1, ColorRGB:=vbBlack ``` 分层边框——按顺序绘制多条 [**Border**](#border-class) 实例——直接赋给 [**Elements**](#elements) 数组。每个元素可以有自己的 [**StrokeSize**](#strokesize) 和 [**Fill**](/official/Reference/CustomControls/Styles/Fill),因此细黑轮廓可以位于宽彩色带之上,或三条不同颜色的色带叠加形成"阴影": ```vb Dim elems(0 To 2) As Border Set elems(0) = New Border elems(0).StrokeSize = 4 elems(0).Fill.ColorPoints.SetSolidColor vbBlack Set elems(1) = New Border elems(1).StrokeSize = 7 elems(1).Fill.ColorPoints.SetSolidColor &H99CCFF ' light blue band Set elems(2) = New Border elems(2).StrokeSize = 4 elems(2).Fill.ColorPoints.SetSolidColor &H4D7AB4 ' deeper blue btnGo.NormalState.Borders.Elements = elems ``` 单个 [**Border**](#border-class) 也可以显示渐变而非纯色——为其 [**Fill**](#fill) 成员赋多 stop [**Fill**](/official/Reference/CustomControls/Styles/Fill)。在半透明边框上将 [**BlendWithBackgroundFill**](#blendwithbackgroundfill) 设为 **True** 可使其与控件自身的 **BackgroundFill** 混合而非与控件下方的内容混合。 ## 属性 ### Elements [**Border**](#border-class) 子对象数组,从索引 0 向外按顺序绘制。可读写,但实际上通过 [**SetSimpleBorder**](#setsimpleborder) 或 [**SetSimpleBorderRGBA**](#setsimpleborderrgba) 填充。 ## 方法 ### SetSimpleBorder 用给定粗细和完全不透明颜色的单条边框笔触替换 [**Elements**](#elements) 数组。 语法:*object*.**SetSimpleBorder** *StrokeSize*, *ColorRGB* *StrokeSize* : *必需* **Long**,给出笔触粗细(像素)。 *ColorRGB* : *必需* **Long** RGB 颜色,用于笔触填充。 ### SetSimpleBorderRGBA 用单条边框笔触替换 [**Elements**](#elements) 数组,其 alpha 取自提供的 [**ColorRGBA**](/official/Reference/CustomControls/Enumerations/ColorRGBA) 而非强制不透明。适用于仅作为视觉内边距存在的透明边框(滑块在 **BlockBorders** 上使用完全透明边框以在背景内缩进滑块)。 语法:*object*.**SetSimpleBorderRGBA** *StrokeSize*, *ColorRGBA* *StrokeSize* : *必需* **Long**,给出笔触粗细(像素)。 *ColorRGBA* : *必需* [**ColorRGBA**](/official/Reference/CustomControls/Enumerations/ColorRGBA) 值,用于笔触填充。 ## 事件 ### OnChanged [**Elements**](#elements) 数组被重新赋值或任一 [**Border**](#border-class) 元素触发其自身的 **OnChanged** 时触发。 ## Border 类 单条边框笔触。[**Borders.Elements**](#elements) 的元素,也是 [**TextRendering.Outlines**](/official/Reference/CustomControls/Styles/TextRendering#outlines) 的元素。 ### BlendWithBackgroundFill 当 **True** 时,边框颜色与控件的 **BackgroundFill** 进行 alpha 混合而非与控件下方绘制的内容混合。使半透明边框颜色使用背景色调而非窗体的颜色。**Boolean**。默认:**False**。 ### Fill 提供用于绘制边框的颜色或渐变的 [**Fill**](/official/Reference/CustomControls/Styles/Fill)。新构造的 [**Border**](#border-class) 对象将其预设为纯黑色填充。 ### StrokeSize 笔触粗细(像素)。[**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount)。默认:1。 ### New 用默认纯黑色 [**Fill**](#fill) 构造 [**Border**](#border-class)。 语法:**New Border** ### OnChanged [**StrokeSize**](#strokesize)、[**Fill**](#fill) 或 [**BlendWithBackgroundFill**](#blendwithbackgroundfill) 被赋值时,或包含的 [**Fill**](#fill) 触发其自身的 **OnChanged** 时触发。 --- --- url: /en/official/Reference/CustomControls/Enumerations/BorderStyle.md --- # BorderStyle The Win32 frame style used by a [**WaynesForm**](/en/official/Reference/CustomControls/WaynesForm/) window. Determines whether the window has a thick or thin border, whether it can be resized by dragging an edge, and whether it shows a normal title bar or the smaller tool-window title bar. Used by [**WindowsFormOptions.BorderStyle**](/en/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#borderstyle). | Constant | Value | Description | | ----------------------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **tbNone** | 0 | No border at all --- the form is a borderless, captionless rectangle. | | **tbFixedSingle** | 1 | Thin single-line border; size is fixed at run time. | | **tbFixedSizable** | 2 | Standard resizable border with a normal title bar. The default for newly-constructed [**WindowsFormOptions**](/en/official/Reference/CustomControls/WaynesForm/WindowsFormOptions). | | **tbFixedDialog** | 3 | Dialog-frame border; size is fixed and the system menu offers only **Move** / **Close**. | | **tbFixedToolWindow** | 4 | Tool-window border with the smaller title bar; size is fixed. | | **tbSizableToolWindow** | 5 | Tool-window border with the smaller title bar; the window is resizable. | Most border styles cannot be combined with **MinimizeButton** or **MaximizeButton** --- only **tbFixedSizable** shows full sizing controls. Setting [**MinimizeButton**](/en/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#minimizebutton) or [**MaximizeButton**](/en/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#maximizebutton) to **True** on a window style that does not include them has no effect. --- --- url: /zh/official/Reference/CustomControls/Enumerations/BorderStyle.md --- # BorderStyle [**WaynesForm**](/official/Reference/CustomControls/WaynesForm/) 窗口使用的 Win32 框架样式。决定窗口是否有粗或细边框、是否可以通过拖动边缘调整大小,以及是显示普通标题栏还是较小的工具窗口标题栏。由 [**WindowsFormOptions.BorderStyle**](/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#borderstyle) 使用。 | 常量 | 值 | 说明 | |------|----|------| | **tbNone** | 0 | 无边框——窗体为无边框、无标题的矩形。 | | **tbFixedSingle** | 1 | 细单线边框;运行时大小固定。 | | **tbFixedSizable** | 2 | 带普通标题栏的标准可调大小边框。新构造的 [**WindowsFormOptions**](/official/Reference/CustomControls/WaynesForm/WindowsFormOptions) 的默认值。 | | **tbFixedDialog** | 3 | 对话框框架边框;大小固定,系统菜单只提供 **移动** / **关闭**。 | | **tbFixedToolWindow** | 4 | 带较小标题栏的工具窗口边框;大小固定。 | | **tbSizableToolWindow** | 5 | 带较小标题栏的工具窗口边框;窗口可调大小。 | 大多边框样式不能与 **MinimizeButton** 或 **MaximizeButton** 组合——只有 **tbFixedSizable** 显示完整的大小控件。在不包含这些按钮的窗口样式上将 [**MinimizeButton**](/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#minimizebutton) 或 [**MaximizeButton**](/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#maximizebutton) 设为 **True** 无效。 --- --- url: /en/official/Reference/VBRUN/Constants/BorderStyleConstants.md --- # BorderStyleConstants Line-style values for the **BorderStyle** property of **Shape** and **Line** controls. | Constant | Value | Description | |----------|-------|-------------| | **vbTransparent** | 0 | No border is drawn. | | **vbBSSolid** | 1 | A solid border. | | **vbBSDash** | 2 | A dashed border. | | **vbBSDot** | 3 | A dotted border. | | **vbBSDashDot** | 4 | A dash-dot border. | | **vbBSDashDotDot** | 5 | A dash-dot-dot border. | | **vbBSInsideSolid** | 6 | A solid border drawn entirely within the shape's bounds. | --- --- url: /zh/official/Reference/VBRUN/Constants/BorderStyleConstants.md --- # BorderStyleConstants **Shape**和**Line**控件的**BorderStyle**属性的线条样式值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbTransparent** | 0 | 不绘制边框。 | | **vbBSSolid** | 1 | 实线边框。 | | **vbBSDash** | 2 | 虚线边框。 | | **vbBSDot** | 3 | 点线边框。 | | **vbBSDashDot** | 4 | 点划线边框。 | | **vbBSDashDotDot** | 5 | 双点划线边框。 | | **vbBSInsideSolid** | 6 | 完全在形状边界内绘制的实线边框。 | --- --- url: /en/official/Tutorials/CEF/Building-a-browser-shell.md --- # Building a browser shell A short worked tutorial: turn a [**CefBrowser**](/en/official/Reference/CEF/CefBrowser/) control into a working browser with an address bar, back / forward / reload buttons, zoom, and a few helpers (DevTools, PDF export). The complete project ships as *Sample 1b --- Chromium Embedded Framework Examples* in the New-Project dialog (form *Example 1*). This tutorial describes its key pieces. ## The form Drop a [**CefBrowser**](/en/official/Reference/CEF/CefBrowser/) control onto a Form and rename it `WebView`. Around it, add a `TextBox` named `AddressBar` plus six `CommandButton`s --- `btnBack`, `btnForward`, `btnRefresh`, `btnZoomIn`, `btnZoomOut`, `btnPDF`, `btnDevTools`. ## Navigating The bare-bones navigation methods --- [**Navigate**](/en/official/Reference/CEF/CefBrowser/#navigate), [**GoBack**](/en/official/Reference/CEF/CefBrowser/#goback), [**GoForward**](/en/official/Reference/CEF/CefBrowser/#goforward), [**Reload**](/en/official/Reference/CEF/CefBrowser/#reload) --- are one-liners: ```vb Private Sub btnBack_Click() Handles btnBack.Click WebView.GoBack() End Sub Private Sub btnForward_Click() Handles btnForward.Click WebView.GoForward() End Sub Private Sub btnRefresh_Click() Handles btnRefresh.Click WebView.Reload() End Sub ``` To make the back / forward buttons follow the actual history state, sync them against [**CanGoBack**](/en/official/Reference/CEF/CefBrowser/#cangoback) and [**CanGoForward**](/en/official/Reference/CEF/CefBrowser/#cangoforward) after every navigation: ```vb Private Sub WebView_NavigationComplete( _ ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) _ Handles WebView.NavigationComplete btnBack.Enabled = WebView.CanGoBack btnForward.Enabled = WebView.CanGoForward End Sub ``` ::: info *IsSuccess* and *WebErrorStatus* are part of the event signature but currently return placeholder values (`True` and `0`) --- use [**DocumentURL**](/en/official/Reference/CEF/CefBrowser/#documenturl) to confirm where the browser actually landed. ::: ## The address bar Pressing **Enter** in the address bar triggers a navigation. The reverse direction --- keeping the visible URL in sync with the page --- is the [**SourceChanged**](/en/official/Reference/CEF/CefBrowser/#sourcechanged) event, which fires whenever [**DocumentURL**](/en/official/Reference/CEF/CefBrowser/#documenturl) changes (including same-document `history.pushState` updates): ```vb Private Sub AddressBar_KeyDown(KeyCode As Integer, Shift As Integer) _ Handles AddressBar.KeyDown If KeyCode = vbKeyReturn Then WebView.Navigate AddressBar.Text End Sub Private Sub WebView_SourceChanged(ByVal IsNewDocument As Boolean) _ Handles WebView.SourceChanged AddressBar.Text = WebView.DocumentURL End Sub ``` [**Navigate**](/en/official/Reference/CEF/CefBrowser/#navigate) requires a full URI with scheme --- `http://`, `https://`, `file://`, … Unlike [**WebView2**](/en/official/Reference/WebView2/WebView2/#navigate), no automatic `https://` prefix is added when the scheme is missing. ## Zoom [**ZoomFactor**](/en/official/Reference/CEF/CefBrowser/#zoomfactor) is a **Double** --- `1.0` is 100%, `1.5` is 150%. The value reads as `0` until the browser has reached [**Ready**](/en/official/Reference/CEF/CefBrowser/#ready), so arithmetic that multiplies the current value silently starts from zero unless you clamp first: ```vb Private Sub btnZoomIn_Click() Handles btnZoomIn.Click If WebView.ZoomFactor = 0 Then WebView.ZoomFactor = 1 On Error Resume Next WebView.ZoomFactor *= 1.1 End Sub Private Sub btnZoomOut_Click() Handles btnZoomOut.Click If WebView.ZoomFactor = 0 Then WebView.ZoomFactor = 1 On Error Resume Next WebView.ZoomFactor /= 1.1 End Sub ``` The `On Error Resume Next` catches the "control not ready" error that fires when the button is clicked before [**Ready**](/en/official/Reference/CEF/CefBrowser/#ready) has fired. ## PDF export [**PrintToPdf**](/en/official/Reference/CEF/CefBrowser/#printtopdf) saves the current document to disk asynchronously --- the result arrives as [**PrintToPdfCompleted**](/en/official/Reference/CEF/CefBrowser/#printtopdfcompleted) or [**PrintToPdfFailed**](/en/official/Reference/CEF/CefBrowser/#printtopdffailed): ```vb Private Sub btnPDF_Click() Handles btnPDF.Click Dim outputPath As String = _ Environ$("USERPROFILE") & "\Documents\page.pdf" WebView.PrintToPdf(outputPath) End Sub Private Sub WebView_PrintToPdfCompleted() Handles WebView.PrintToPdfCompleted MsgBox "PDF saved.", vbInformation End Sub ``` The optional parameters that follow *outputPath* --- [**cefPrintOrientation**](/en/official/Reference/CEF/Enumerations/cefPrintOrientation), page size in microns, margins, header/footer toggles --- let the host override Chromium's defaults. See the [**PrintToPdf** reference](/en/official/Reference/CEF/CefBrowser/#printtopdf) for the full signature. ## DevTools The Chromium DevTools window opens in its own top-level window: ```vb Private Sub btnDevTools_Click() Handles btnDevTools.Click WebView.OpenDevToolsWindow() End Sub ``` The CEF package does not currently expose **WebView2**'s **OpenTaskManagerWindow** equivalent --- see the [WebView2 parity](/en/official/Reference/CEF/#webview2-parity) section of the reference for the current gap list. ## Form-title sync To make the host window's caption track the page's `<title>`, listen for [**DocumentTitleChanged**](/en/official/Reference/CEF/CefBrowser/#documenttitlechanged) and read [**DocumentTitle**](/en/official/Reference/CEF/CefBrowser/#documenttitle): ```vb Private Sub WebView_DocumentTitleChanged() Handles WebView.DocumentTitleChanged Me.Caption = WebView.DocumentTitle End Sub ``` ## Where next * [Hosting local web assets](/en/official/Tutorials/CEF/Hosting-local-web-assets) -- serve HTML / JS / CSS from a folder without an HTTP server. * [JavaScript interop](/en/official/Tutorials/CEF/JavaScript-interop) -- pass values and method calls between BASIC and the page. * [Re-entrancy](/en/official/Tutorials/CEF/Re-entrancy) -- the one thing to know about [**JsRun**](/en/official/Reference/CEF/CefBrowser/#jsrun) before you use it. * [CefBrowser reference](/en/official/Reference/CEF/CefBrowser/) -- every property, method, and event. --- --- url: /en/official/Tutorials/WebView2/Building-a-browser-shell.md --- # Building a browser shell A short worked tutorial: turn a [**WebView2**](/en/official/Reference/WebView2/WebView2/) control into a working browser with an address bar, back / forward / reload buttons, zoom, and a few helpers (DevTools, Task Manager, PDF export). The complete project ships as *Sample 0 --- WebView2 Examples* in the New-Project dialog (form *Example 1*). This tutorial describes its key pieces. ## The form Drop a [**WebView2**](/en/official/Reference/WebView2/WebView2/) control onto a Form and rename it `WebView`. Around it, add a `TextBox` named `AddressBar` plus seven `CommandButton`s --- `btnBack`, `btnForward`, `btnRefresh`, `btnZoomIn`, `btnZoomOut`, `btnPDF`, `btnDevTools`, `btnTaskMgr`. ## Navigating The bare-bones navigation methods --- [**Navigate**](/en/official/Reference/WebView2/WebView2/#navigate), [**GoBack**](/en/official/Reference/WebView2/WebView2/#goback), [**GoForward**](/en/official/Reference/WebView2/WebView2/#goforward), [**Reload**](/en/official/Reference/WebView2/WebView2/#reload) --- are one-liners: ```vb Private Sub btnBack_Click() Handles btnBack.Click WebView.GoBack() End Sub Private Sub btnForward_Click() Handles btnForward.Click WebView.GoForward() End Sub Private Sub btnRefresh_Click() Handles btnRefresh.Click WebView.Reload() End Sub ``` To make the back / forward buttons follow the actual history state, sync them against [**CanGoBack**](/en/official/Reference/WebView2/WebView2/#cangoback) and [**CanGoForward**](/en/official/Reference/WebView2/WebView2/#cangoforward) after every navigation: ```vb Private Sub WebView_NavigationComplete( _ ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) _ Handles WebView.NavigationComplete btnBack.Enabled = WebView.CanGoBack btnForward.Enabled = WebView.CanGoForward End Sub ``` ## The address bar Pressing **Enter** in the address bar triggers a navigation. The reverse direction --- keeping the visible URL in sync with the page --- is the [**SourceChanged**](/en/official/Reference/WebView2/WebView2/#sourcechanged) event, which fires whenever [**DocumentURL**](/en/official/Reference/WebView2/WebView2/#documenturl) changes (including same-document `history.pushState` updates): ```vb Private Sub AddressBar_KeyDown(KeyCode As Integer, Shift As Integer) _ Handles AddressBar.KeyDown If KeyCode = vbKeyReturn Then WebView.Navigate AddressBar.Text End Sub Private Sub WebView_SourceChanged(ByVal IsNewDocument As Boolean) _ Handles WebView.SourceChanged AddressBar.Text = WebView.DocumentURL End Sub ``` [**Navigate**](/en/official/Reference/WebView2/WebView2/#navigate) accepts any URI string; if the scheme prefix is missing, `https://` is added automatically. ## Zoom [**ZoomFactor**](/en/official/Reference/WebView2/WebView2/#zoomfactor) is a **Double** --- `1.0` is 100%, `1.5` is 150%. The design-time default is `0`, meaning *"don't override Edge's default of 1.0"* --- so multiplying by `1.1` from cold gives `0`, not `1.1`. Clamp to `1` before scaling: ```vb Private Sub btnZoomIn_Click() Handles btnZoomIn.Click If WebView.ZoomFactor = 0 Then WebView.ZoomFactor = 1 WebView.ZoomFactor *= 1.1 End Sub Private Sub btnZoomOut_Click() Handles btnZoomOut.Click If WebView.ZoomFactor = 0 Then WebView.ZoomFactor = 1 WebView.ZoomFactor /= 1.1 End Sub ``` ## PDF export [**PrintToPdf**](/en/official/Reference/WebView2/WebView2/#printtopdf) saves the current document to disk asynchronously --- the result arrives as [**PrintToPdfCompleted**](/en/official/Reference/WebView2/WebView2/#printtopdfcompleted) or [**PrintToPdfFailed**](/en/official/Reference/WebView2/WebView2/#printtopdffailed): ```vb Private Sub btnPDF_Click() Handles btnPDF.Click Dim outputPath As String = _ Environ$("USERPROFILE") & "\Documents\page.pdf" WebView.PrintToPdf(outputPath) End Sub Private Sub WebView_PrintToPdfCompleted() Handles WebView.PrintToPdfCompleted MsgBox "PDF saved.", vbInformation End Sub ``` ## DevTools and Task Manager Both windows are one-shot --- call the matching method and Edge opens the window in its own process: ```vb Private Sub btnDevTools_Click() Handles btnDevTools.Click WebView.OpenDevToolsWindow() End Sub Private Sub btnTaskMgr_Click() Handles btnTaskMgr.Click WebView.OpenTaskManagerWindow() End Sub ``` [**OpenDevToolsWindow**](/en/official/Reference/WebView2/WebView2/#opendevtoolswindow) works even when [**AreDevToolsEnabled**](/en/official/Reference/WebView2/WebView2/#aredevtoolsenabled) is **False** (that setting only disables the user-initiated path --- keyboard shortcut and context menu). ## Form-title sync To make the host window's caption track the page's `<title>`, listen for [**DocumentTitleChanged**](/en/official/Reference/WebView2/WebView2/#documenttitlechanged) and read [**DocumentTitle**](/en/official/Reference/WebView2/WebView2/#documenttitle): ```vb Private Sub WebView_DocumentTitleChanged() Handles WebView.DocumentTitleChanged Me.Caption = WebView.DocumentTitle End Sub ``` ## Where next * [Hosting local web assets](/en/official/Tutorials/WebView2/Hosting-local-web-assets) -- serve HTML / JS / CSS from a folder without an HTTP server. * [JavaScript interop](/en/official/Tutorials/WebView2/JavaScript-interop) -- pass values and method calls between BASIC and the page. * [WebView2 reference](/en/official/Reference/WebView2/WebView2/) -- every property, method, and event. --- --- url: /en/official/Documentation/Building.md --- # Building and Deployment The day-to-day workflow for editing documentation: requirements, building, serving locally, link checking, Mermaid diagrams, screenshots, and the deployment to [docs.twinbasic.com](https://docs.twinbasic.com). Aimed at content contributors --- if you are modifying the build pipeline itself, see [tbdocs Internals](/en/official/Documentation/Builder) instead. ## Development environment The documentation is rendered to HTML by `tbdocs`, a custom Node.js static site generator that lives under [`builder/`](https://github.com/twinbasic/documentation/tree/main/builder). The day-to-day commands below are Windows batch files that wrap the generator; their POSIX equivalents are listed alongside. 1. Ensure the [requirements](#requirements) below are met. 2. Fork [https://github.com/twinbasic/documentation][docs-repo] to your own GitHub account if you plan on making any changes, or for convenience. Skip this if you only want to build the docs locally without contributing changes. 3. Clone either your fork or the [documentation repository itself][docs-repo]. ### Requirements * **Node.js 22+** for `tbdocs` itself. The site builds offline with no Ruby toolchain. * **`npm ci`** at the repository root installs everything: the static site generator's deps, the PDF renderer's deps, and `puppeteer` (shared by both the PDF renderer and mermaid's `.mmd` → `.svg` regenerator). A single `package.json` at the repo root carries the whole dependency set. The `build.bat` / `serve.bat` wrappers assume the install has run. * **Chromium** is required whenever an `.mmd` diagram needs regenerating and whenever the PDF book is rendered. It is downloaded once by `npx puppeteer browsers install chrome --install-deps`. A missing Chromium during a build downgrades to a warning and reuses the on-disk `.svg`, so first-time setups that skip the install step still build (just without diagram updates). ## Building To render the documentation from `.md` files into the `_site/` (online), `_site-offline/` (offline mirror), and `_site-pdf/` (sparse PDF source) folders: ``` build.bat ``` or directly: ``` node builder\tbdocs.mjs --src docs ``` A single `tbdocs` run produces all three trees. The `also_build_offline` and `also_build_pdf` keys in `_config.yml` toggle the sibling outputs; the `--no-offline` and `--no-pdf` flags do the same from the command line if you only want `_site/`. The full set of `tbdocs` CLI flags --- every flag, what each one does, when to use it --- lives on the [Tools and Scripts](/en/official/Documentation/Tools#tbdocs) page. ## Building and local serving The simplest local preview is `build.bat` followed by opening the rendered files in any browser. To get a localhost server instead: ``` serve.bat ``` This runs `tbdocs --serve`: after an initial build, an HTTP server binds to port 4000 (pass `--port <N>` to use a different port), a recursive source-tree watcher fires a debounced rebuild on each file change, and any browser tab open on the page auto-reloads via SSE after each successful rebuild. Only failures (4xx, 5xx, server exceptions) are logged --- successful requests are silent. Ctrl+C exits cleanly. Serve writes to `docs/_serve/`, completely disjoint from `build.bat`'s `_site/` family. That separation means a one-off `build.bat` invocation (e.g., to refresh `_site-pdf/` for `book.bat`, or to re-check `_site-offline/` link integrity) never touches the tree the live preview is serving, and the preview keeps showing whatever serve last rebuilt. ## Checking link integrity Before checking link integrity, the documentation must be built: ``` check.bat ``` This runs two passes of `scripts/check_links.mjs`: one against `_site/` (the online tree) and one against `_site-offline/` (the `file://`-browsable mirror) with `--forbid 'https://docs.twinbasic.com'` to also flag any surviving live-site link --- the offline mirror should never navigate back to the live docs site. Both checks also assert HTML well-formedness, duplicate-`id` detection, anchor resolution, accessibility hints, and (for the online tree) the sitemap and search-index integrity. The same two checks run in CI on every pull request and on every push to `staging`. A clean `check.bat` run is the bar for "ready to commit". ## Mermaid diagrams Mermaid diagrams live as `.mmd` source files under `docs/assets/images/mmd/` and are referenced from markdown as `.svg`: ``` ![Diagram](/assets/images/mmd/<hash>.svg) ``` `tbdocs` regenerates each `.svg` from its `.mmd` sibling when the SVG is missing or older than its source --- editing a `.mmd` by one character regenerates the SVG on the next build. Both files belong in git; the `.mmd` is the canonical source, the `.svg` is the build artifact that the browser actually loads. The renderer drives `puppeteer` + the `mermaid` package directly (both regular dependencies in the repo-root `package.json`). One headless Chromium covers the whole batch --- previously the project shelled out to `@mermaid-js/mermaid-cli` which forked a fresh node + Chrome process per diagram and shipped its own bundled puppeteer-core. The direct path keeps the dependency tree smaller, removes the per-file process startup overhead, and uses the same Chromium cache as `render-book.mjs`. Two failure modes are handled distinctly: * **Setup failures** (no puppeteer, no Chrome, no mermaid) emit a one-line warning, retain the existing on-disk SVGs, and let the build exit 0 --- a fresh checkout without `npm install` or a sandbox without Chromium doesn't break unrelated work. * **Content failures** (broken `.mmd` syntax, render exception) emit the parser error verbatim, leave that diagram's previous SVG in place, continue rendering the rest of the batch, and flip `process.exitCode = 1` so CI catches the bad diagram. In serve mode the watcher ignores writes to `assets/images/mmd/*.svg`. The `.mmd` is the source of truth; the `.svg` is the build artifact mermaid emits back under `srcRoot`. Without the filter, each `.mmd` edit would fire two rebuilds (one on the edit, one on the SVG write) and the browser would reload twice for one user change. ## Deploying to docs.twinbasic.com 1. Push your changes to your GitHub fork of the [documentation repository][docs-repo]. 2. [Open a new pull request in the documentation repository][docs-pr]. 3. Click **compare across forks**. 4. Select your repository and branch to merge from. ![img](/assets/compare-changes.DFURGOIT.png) 5. Create the pull request. ![img](/assets/create-pull-request.Cs58mWhB.png) A maintainer will merge the pull request into the documentation repository. You may wish to mention an outstanding request on the [#docs][hash-docs] channel, although the [#github-docs][hash-github-docs] channel provides automated notifications of pull requests. Normally, a maintainer will get a notification of a new pull request via Discord, and will merge it or comment with a request for changes. **The steps below are done by maintainers.** 6. Review, then merge the pull request or comment with required changes. ![img](/assets/merge-pull-request.-xevR28n.png) ![img](/assets/confirm-merge.B-aESd2K.png) 7. Select the **Build & deploy docs** action. ![img](/assets/choose-workflow.kFwp_r80.png){width="75%"} 8. Manually run the build and deployment workflow if a release snapshot is needed. (Pushes to `staging` deploy to Pages automatically; only the manual run additionally cuts a GitHub release with the offline-browsable site copy attached as a zip and the PDF book attached.) ![img](/assets/run-workflow.BgsgOvro.png){width="50%"} ## Editing screenshots One way to edit screenshots is to use an integrated vector / pixel program like [Affinity][af]1. A possible workflow: 1. PrtSc to capture the screenshot. 2. In Affinity, Ctrl-Alt-Shift-N (File, New from Clipboard) to get the entire screenshot into the program. 3. Use the Vector Crop tool (from the Vector studio) to crop the screenshot down to the relevant part. ![img](/assets/af-vector-studio.Ck0bWZQb.png) ![img](/assets/af-vector-crop-tool.DXF8qLLE.png) 4. Select the cropped image and copy it to the clipboard with Ctrl-C. 5. Create a new file from clipboard again to open a document with just the cropped screenshot Ctrl-Alt-Shift-N (File, New from Clipboard). 6. Close the file you opened in step 2. 7. Add arrows and labels as needed. Those can be copy-pasted from other `.af` files in this repository. 8. Export to PNG via Ctrl-Alt-Shift-W (File, Export, Export...). ::: info It is a convention to put the `.af` ("source") files in the `_Images` folder, and the exported `.png` files in the `Images` folder. Only the latter is published to the website. The former is preserved as the source for easy editing and updates. ::: *** 1 Affinity is a free-as-in-beer suite that combines a vector editor, a bitmap editor, and a publishing layout editor. A Canva account is required to download; the accounts are free. [af]: https://www.affinity.studio/download [docs-pr]: https://github.com/twinbasic/documentation/compare [docs-repo]: https://github.com/twinbasic/documentation [hash-docs]: https://discord.com/channels/927638153546829845/1021635324809596988 [hash-github-docs]: https://discord.com/channels/927638153546829845/1111554338221989908 --- --- url: /en/official/Reference/tbIDE/Button.md --- # Button class An addin-created toolbar button. Returned by [**Toolbar.AddButton**](/en/official/Reference/tbIDE/Toolbar#addbutton); held via `WithEvents` to receive [**OnClick**](#onclick) notifications. The button's [**Caption**](#caption) and [**IconData**](#icondata) are mutable at run time --- the caption can reflect a state, or the icon can reflect a toggle. ```vb Private WithEvents RefreshButton As Button Private Sub Host_OnProjectLoaded() Set RefreshButton = Host.Toolbars(0).AddButton("MyAddIn.Refresh", "Refresh project", _ LoadResData("refresh.png", "ICONS")) End Sub Private Sub RefreshButton_OnClick() Host.CurrentProject.Save End Sub ``` ## Properties ### Caption The button's caption. **String**. When [**IconData**](#icondata) is set, the caption is shown as a tooltip on hover. When [**IconData**](#icondata) is empty, the caption is shown inline as the button's text. Read / write. Syntax: *button*.**Caption** \[ = *value* ] ### IconData The icon graphic as a **Byte()** array --- typically the bytes of an embedded PNG / ICO resource. Pass **Empty** to remove the icon and fall back to showing the [**Caption**](#caption) inline. Read / write. Syntax: *button*.**IconData** \[ = *bytes* ] *bytes* : A **Byte()** array (or **Empty**). **Variant**. ### ID The unique ID assigned to the button when it was created via [**Toolbar.AddButton**](/en/official/Reference/tbIDE/Toolbar#addbutton). **String**, read-only. ## Events ### OnClick Fires when the user clicks the button. Syntax: *button*\_**OnClick**() --- --- url: /zh/official/Reference/tbIDE/Button.md --- # Button 类 一个由插件创建的工具栏按钮。由 [**Toolbar.AddButton**](/official/Reference/tbIDE/Toolbar#addbutton) 返回;通过 `WithEvents` 持有以接收 [**OnClick**](#onclick) 通知。按钮的 [**Caption**](#caption) 和 [**IconData**](#icondata) 在运行时可变——标题可以反映状态,图标可以反映切换。 ```vb Private WithEvents RefreshButton As Button Private Sub Host_OnProjectLoaded() Set RefreshButton = Host.Toolbars(0).AddButton("MyAddIn.Refresh", "Refresh project", _ LoadResData("refresh.png", "ICONS")) End Sub Private Sub RefreshButton_OnClick() Host.CurrentProject.Save End Sub ``` ## 属性 ### Caption 按钮的标题。**String**。当设置了 [**IconData**](#icondata) 时,标题在悬停时显示为工具提示。当 [**IconData**](#icondata) 为空时,标题以内联方式显示为按钮文本。可读/写。 语法:*button*.**Caption** \[ = *value* ] ### IconData 图标图形,为 **Byte()** 数组——通常是嵌入的 PNG / ICO 资源的字节。传入 **Empty** 以移除图标并回退到以内联方式显示 [**Caption**](#caption)。可读/写。 语法:*button*.**IconData** \[ = *bytes* ] *bytes* : 一个 **Byte()** 数组(或 **Empty**)。**Variant**。 ### ID 通过 [**Toolbar.AddButton**](/official/Reference/tbIDE/Toolbar#addbutton) 创建按钮时分配的唯一 ID。**String**,只读。 ## 事件 ### OnClick 当用户点击按钮时触发。 语法:*button*\_**OnClick**() --- --- url: /en/official/Reference/VBRUN/Constants/ButtonConstants.md --- # ButtonConstants Style values for command buttons that support an optional graphical (image-based) appearance. | Constant | Value | Description | |----------|-------|-------------| | **vbButtonStandard** | 0 | The button is drawn as a standard system push-button. | | **vbButtonGraphical** | 1 | The button is drawn as a graphical button able to display a picture. Available only when the **FEATURE\_GRAPHICAL\_BUTTONS** feature is enabled. | --- --- url: /zh/official/Reference/VBRUN/Constants/ButtonConstants.md --- # ButtonConstants 支持可选图形(基于图像)外观的命令按钮的样式值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbButtonStandard** | 0 | 按钮作为标准系统按钮绘制。 | | **vbButtonGraphical** | 1 | 按钮作为可显示图片的图形按钮绘制。仅在启用**FEATURE\_GRAPHICAL\_BUTTONS**功能时可用。 | --- --- url: /en/official/Reference/VBRUN/AsyncProperty/BytesMax.md --- # BytesMax Returns the total number of bytes expected for the read, as a **Long**. Read-only. Syntax: *object*.**BytesMax** *object* : *required* An object expression that evaluates to an **AsyncProperty** object. Used together with [**BytesRead**](/en/official/Reference/VBRUN/AsyncProperty/BytesRead) to update a progress indicator during an **AsyncReadProgress** event. **BytesMax** can be zero when the server has not advertised a content length --- for example with an HTTP chunked transfer --- in which case the total size is not known until the read completes and a determinate progress bar cannot be shown. ### Example This example shows progress as a ratio when the total size is known. ```vb Private Sub UserControl_AsyncReadProgress(AsyncProp As AsyncProperty) If AsyncProp.BytesMax > 0 Then Dim pct As Long pct = CLng(AsyncProp.BytesRead * 100 \ AsyncProp.BytesMax) ProgressBar1.Value = pct End If End Sub ``` ### See Also * [BytesRead](/en/official/Reference/VBRUN/AsyncProperty/BytesRead) property * [Status](/en/official/Reference/VBRUN/AsyncProperty/Status) property * [StatusCode](/en/official/Reference/VBRUN/AsyncProperty/StatusCode) property --- --- url: /zh/official/Reference/VBRUN/AsyncProperty/BytesMax.md --- # BytesMax 返回读取的预期总字节数,类型为**Long**。只读。 语法:*object*.**BytesMax** *object* : *必需* 求值为**AsyncProperty**对象的对象表达式。 与[**BytesRead**](/official/Reference/VBRUN/AsyncProperty/BytesRead)一起使用,在**AsyncReadProgress**事件期间更新进度指示器。当服务器未公布内容长度时——例如HTTP分块传输——**BytesMax**可能为零,此时直到读取完成才知道总大小,无法显示确定性进度条。 ### 示例 此示例在总大小已知时以比率形式显示进度。 ```vb Private Sub UserControl_AsyncReadProgress(AsyncProp As AsyncProperty) If AsyncProp.BytesMax > 0 Then Dim pct As Long pct = CLng(AsyncProp.BytesRead * 100 \ AsyncProp.BytesMax) ProgressBar1.Value = pct End If End Sub ``` ### 另见 * [BytesRead](/official/Reference/VBRUN/AsyncProperty/BytesRead) 属性 * [Status](/official/Reference/VBRUN/AsyncProperty/Status) 属性 * [StatusCode](/official/Reference/VBRUN/AsyncProperty/StatusCode) 属性 --- --- url: /en/official/Reference/VBRUN/AsyncProperty/BytesRead.md --- # BytesRead Returns the number of bytes that have been read so far, as a **Long**. Read-only. Syntax: *object*.**BytesRead** *object* : *required* An object expression that evaluates to an **AsyncProperty** object. The value accumulates across successive **AsyncReadProgress** notifications and reaches its final total by the time **AsyncReadComplete** fires. When [**BytesMax**](/en/official/Reference/VBRUN/AsyncProperty/BytesMax) is non-zero, the ratio `BytesRead / BytesMax` gives the fraction of the read that has completed. ### Example This example logs the current download progress using **BytesRead** and **BytesMax**. ```vb Private Sub UserControl_AsyncReadProgress(AsyncProp As AsyncProperty) If AsyncProp.PropertyName = "Picture" Then Debug.Print AsyncProp.BytesRead & " / " & AsyncProp.BytesMax End If End Sub ``` ### See Also * [BytesMax](/en/official/Reference/VBRUN/AsyncProperty/BytesMax) property * [Status](/en/official/Reference/VBRUN/AsyncProperty/Status) property * [StatusCode](/en/official/Reference/VBRUN/AsyncProperty/StatusCode) property --- --- url: /zh/official/Reference/VBRUN/AsyncProperty/BytesRead.md --- # BytesRead 返回目前已读取的字节数,类型为**Long**。只读。 语法:*object*.**BytesRead** *object* : *必需* 求值为**AsyncProperty**对象的对象表达式。 该值在连续的**AsyncReadProgress**通知中累积,到**AsyncReadComplete**触发时达到最终总数。当[**BytesMax**](/official/Reference/VBRUN/AsyncProperty/BytesMax)非零时,比率`BytesRead / BytesMax`给出已完成读取的比例。 ### 示例 此示例使用**BytesRead**和**BytesMax**记录当前下载进度。 ```vb Private Sub UserControl_AsyncReadProgress(AsyncProp As AsyncProperty) If AsyncProp.PropertyName = "Picture" Then Debug.Print AsyncProp.BytesRead & " / " & AsyncProp.BytesMax End If End Sub ``` ### 另见 * [BytesMax](/official/Reference/VBRUN/AsyncProperty/BytesMax) 属性 * [Status](/official/Reference/VBRUN/AsyncProperty/Status) 属性 * [StatusCode](/official/Reference/VBRUN/AsyncProperty/StatusCode) 属性 --- --- url: /en/official/Reference/VBA/DateTime/Calendar.md --- # Calendar Returns or sets a value specifying the type of calendar used by the project. Syntax: **Calendar** \[ **=** *calendartype* ] *calendartype* : A **VbCalendar** constant specifying the calendar type. | Constant | Value | Description | |----------------|-------|--------------------------------| | **vbCalGreg** | 0 | Gregorian calendar (default). | | **vbCalHijri** | 1 | Hijri calendar. | The **Calendar** property can only be set programmatically. The setting of **Calendar** affects the string returned by the [**Date$**](/en/official/Reference/VBA/DateTime/Date#date-1) property when the calendar is set to Hijri. ### Example This example sets the calendar type to Hijri. ```vb Calendar = vbCalHijri ``` ### See Also * [Date](/en/official/Reference/VBA/DateTime/Date) property --- --- url: /zh/official/Reference/VBA/DateTime/Calendar.md --- # Calendar 返回或设置一个值,指定项目使用的日历类型。 语法:**Calendar** \[ **=** *calendartype* ] *calendartype* : 一个指定日历类型的 **VbCalendar** 常量。 | 常量 | 值 | 描述 | |------|-----|------| | **vbCalGreg** | 0 | 公历(默认)。 | | **vbCalHijri** | 1 | 回历。 | **Calendar** 属性只能通过编程方式设置。将日历设置为回历时,**Calendar** 的设置会影响 [**Date$**](/official/Reference/VBA/DateTime/Date#date-1) 属性返回的字符串。 ### 示例 此示例将日历类型设置为回历。 ```vb Calendar = vbCalHijri ``` ### 另请参阅 * [Date](/official/Reference/VBA/DateTime/Date) 属性 --- --- url: /zh/official/Reference/Core/Calendar.md --- # Calendar 语句 calendar 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/Calendar.md --- # Calendar Statement Documentation for the calendar keyword is not yet available. --- --- url: /en/official/Reference/Core/Call.md --- # Call Transfers control to a **Sub** [procedure](/en/official/Reference/Glossary#procedure), **Function** procedure, or dynamic-link library (DLL) procedure. Syntax: * **Call** *name* **(** \[ *argumentlist* ] **)**\ When the **Call** keyword is specified, the *argumentlist* must be enclosed in parentheses. * *name* **(** \[ *argumentlist* ] **)**\ Without the **Call** keyword, the *argumentlist* can be optionally enclosed in parentheses, * *name* \[ *argumentlist* ] *name* : The name of the procedure to call *argumentlist* : *optional* A comma-delimited list of variables, arrays or expressions to pass to the procedure. Components of *argumentlist* may include the keywords **ByVal** or **ByRef** to describe how the arguments are to be passed to the called procedure. The **Call** keyword is not required when calling a procedure. However, when the **Call** keyword is used to call a procedure that requires arguments, *argumentlist* must be enclosed in parentheses. When the **Call** keyword is omitted, the parentheses around *argumentlist* must also be omitted. When either **Call** syntax is used to call any intrinsic or user-defined function, the function's return value is discarded. To pass a whole array to a procedure, use the array name followed by empty parentheses. ### Example This example illustrates how the **Call** statement is used to transfer control to a **Sub** procedure, an intrinsic function, and a dynamic-link library (DLL) procedure. ```vb ' Call a Sub procedure. Call PrintToDebugWindow("Hello World") ' The above statement causes control to be passed to the following ' Sub procedure. Sub PrintToDebugWindow(AnyString) Debug.Print AnyString ' Print to the Immediate window. End Sub ' Call an intrinsic function. The return value of the function is ' discarded. Call Shell(AppName, 1) ' AppName contains the path of the ' executable file. ' Call a Microsoft Windows DLL procedure. The Declare statement must be ' Private in a Class Module, but not in a standard Module. Private Declare Sub MessageBeep Lib "User" (ByVal N As Integer) Sub CallMyDll() Call MessageBeep(0) ' Call Windows DLL procedure. MessageBeep 0 ' Call again without Call keyword. End Sub ``` ### See Also * [**Declare** statement](/en/official/Reference/Core/Declare) * [**Function** statement](/en/official/Reference/Core/Function) * [**Sub** statement](/en/official/Reference/Core/Sub) --- --- url: /zh/official/Reference/Core/Call.md --- # Call 将控制权转移到 **Sub** [过程](/official/Reference/Glossary#procedure)、**Function** 过程或动态链接库(DLL)过程。 语法: * **Call** *name* **(** \[ *argumentlist* ] **)**\ 当指定 **Call** 关键字时,*argumentlist* 必须用括号括起来。 * *name* **(** \[ *argumentlist* ] **)**\ 不使用 **Call** 关键字时,*argumentlist* 可以选择是否用括号括起来, * *name* \[ *argumentlist* ] *name* : 要调用的过程名称 *argumentlist* : *可选* 传递给过程的变量、数组或表达式的逗号分隔列表。*argumentlist* 的组成部分可以包含 **ByVal** 或 **ByRef** 关键字,以描述参数传递给被调用过程的方式。 调用过程时不需要 **Call** 关键字。但是,当使用 **Call** 关键字调用需要参数的过程时,*argumentlist* 必须用括号括起来。省略 **Call** 关键字时,*argumentlist* 周围的括号也必须省略。使用任一 **Call** 语法调用任何内部或用户自定义函数时,函数的返回值将被丢弃。 要将整个数组传递给过程,请使用数组名后跟空括号。 ### 示例 本示例演示如何使用 **Call** 语句将控制权转移到 **Sub** 过程、内部函数和动态链接库(DLL)过程。 ```vb ' Call a Sub procedure. Call PrintToDebugWindow("Hello World") ' The above statement causes control to be passed to the following ' Sub procedure. Sub PrintToDebugWindow(AnyString) Debug.Print AnyString ' Print to the Immediate window. End Sub ' Call an intrinsic function. The return value of the function is ' discarded. Call Shell(AppName, 1) ' AppName contains the path of the ' executable file. ' Call a Microsoft Windows DLL procedure. The Declare statement must be ' Private in a Class Module, but not in a standard Module. Private Declare Sub MessageBeep Lib "User" (ByVal N As Integer) Sub CallMyDll() Call MessageBeep(0) ' Call Windows DLL procedure. MessageBeep 0 ' Call again without Call keyword. End Sub ``` ### 另请参阅 * [**Declare** 语句](/official/Reference/Core/Declare) * [**Function** 语句](/official/Reference/Core/Function) * [**Sub** 语句](/official/Reference/Core/Sub) --- --- url: /en/official/IDE/Call-Stack.md --- # Call Stack ![Call Stack](/assets/CallStack.BS03A-08.png "Call Stack") The Call Stack pane lists the active chain of procedure calls at the current execution point during a debugging session, with the most recent call at the top. Clicking an entry in the list navigates the editor to that call site. --- --- url: /en/official/Reference/VBA/Interaction/CallByDispId.md --- # CallByDispId Calls a method, or reads or writes a property, on an object --- looked up by raw IDispatch dispatch ID at run time. **CallByDispId** is a twinBASIC addition; the by-name variant, [**CallByName**](/en/official/Reference/VBA/Interaction/CallByName), exists in VBA as well. Syntax: **CallByDispId(** *object* **,** *dispid* **,** *calltype* \[ **,** *args* ... ] **)** *object* : *required* **Object**. The object whose member is to be invoked. *dispid* : *required* **Long**. The IDispatch dispatch ID (`DISPID`) of the method or property to invoke. *calltype* : *required* A [**VbCallType**](/en/official/Reference/VBA/Constants/VbCallType) value indicating the kind of member: `vbMethod`, `vbGet`, `vbLet`, or `vbSet`. *args* : *optional* The arguments to pass to the method, **Property Get**, **Property Let**, or **Property Set**. The return value is a **Variant** containing whatever the call returned. For methods that return nothing, or for property assignments, the result is **Empty**. **CallByDispId** skips the name lookup that [**CallByName**](/en/official/Reference/VBA/Interaction/CallByName) performs, which is useful in two situations: when the dispatch ID is already known and the cost of a `GetIDsOfNames` round trip should be avoided, and when the target member is not exposed by name (e.g. a default member with `DISPID_VALUE = 0`, an explicit-DISPID extension, or a hidden/restricted member). ### Example This example invokes the default member of an object --- `DISPID_VALUE`, defined as 0 --- by dispatch ID. ```vb Const DISPID_VALUE As Long = 0 Dim Result As Variant Result = CallByDispId(SomeObject, DISPID_VALUE, vbGet) ``` ### See Also * [CallByName](/en/official/Reference/VBA/Interaction/CallByName) function * [VbCallType](/en/official/Reference/VBA/Constants/VbCallType) enumeration --- --- url: /zh/official/Reference/VBA/Interaction/CallByDispId.md --- # CallByDispId 在运行时通过原始IDispatch调度ID查找并调用对象上的方法,或读取或写入属性。**CallByDispId**是twinBASIC新增项;按名称变体[**CallByName**](/official/Reference/VBA/Interaction/CallByName)在VBA中也存在。 语法:**CallByDispId(** *object* **,** *dispid* **,** *calltype* \[ **,** *args* ... ] **)** *object* : *必需* **Object**。要调用其成员的对象。 *dispid* : *必需* **Long**。要调用的方法或属性的IDispatch调度ID(`DISPID`)。 *calltype* : *必需* [**VbCallType**](/official/Reference/VBA/Constants/VbCallType)值,指示成员类型:`vbMethod`、`vbGet`、`vbLet`或`vbSet`。 *args* : *可选* 传给方法、**Property Get**、**Property Let**或**Property Set**的参数。 返回值是一个**Variant**,包含调用返回的任何内容。对于不返回值的方法或属性赋值,结果为**Empty**。 **CallByDispId**跳过了[**CallByName**](/official/Reference/VBA/Interaction/CallByName)执行的名称查找,这在两种情况下很有用:当调度ID已知且应避免`GetIDsOfNames`往返开销时,以及当目标成员不按名称公开时(例如具有`DISPID_VALUE = 0`的默认成员、显式DISPID扩展或隐藏/受限成员)。 ### 示例 本示例通过调度ID调用对象的默认成员——`DISPID_VALUE`,定义为0。 ```vb Const DISPID_VALUE As Long = 0 Dim Result As Variant Result = CallByDispId(SomeObject, DISPID_VALUE, vbGet) ``` ### 另请参阅 * [CallByName](/official/Reference/VBA/Interaction/CallByName)函数 * [VbCallType](/official/Reference/VBA/Constants/VbCallType)枚举 --- --- url: /en/official/Reference/VBA/Interaction/CallByName.md --- # CallByName Calls a method, or reads or writes a property, on an object --- looked up by name at run time. Syntax: **CallByName(** *object* **,** *procname* **,** *calltype* \[ **,** *args* ... ] **)** *object* : *required* **Object**. The object whose member is to be invoked. *procname* : *required* **String**. The name of the method or property to invoke on *object*. *calltype* : *required* A [**VbCallType**](/en/official/Reference/VBA/Constants/VbCallType) value indicating the kind of member: `vbMethod`, `vbGet`, `vbLet`, or `vbSet`. *args* : *optional* The arguments to pass to the method, **Property Get**, **Property Let**, or **Property Set**. The return value is a **Variant** containing whatever the call returned. For methods that return nothing, or for property assignments, the result is **Empty**. ### Example These three calls use **CallByName** to operate on a control by name. The first sets its **MousePointer** property to the crosshair cursor, the second reads the same property back out, and the third invokes the **Move** method to reposition the control. ```vb CallByName Text1, "MousePointer", vbLet, vbCrosshair Result = CallByName(Text1, "MousePointer", vbGet) CallByName Text1, "Move", vbMethod, 100, 100 ``` ### See Also * [CallByDispId](/en/official/Reference/VBA/Interaction/CallByDispId) function * [VbCallType](/en/official/Reference/VBA/Constants/VbCallType) enumeration --- --- url: /zh/official/Reference/VBA/Interaction/CallByName.md --- # CallByName 在运行时按名称查找并调用对象上的方法,或读取或写入属性。 语法:**CallByName(** *object* **,** *procname* **,** *calltype* \[ **,** *args* ... ] **)** *object* : *必需* **Object**。要调用其成员的对象。 *procname* : *必需* **String**。要在*object*上调用的方法或属性的名称。 *calltype* : *必需* [**VbCallType**](/official/Reference/VBA/Constants/VbCallType)值,指示成员类型:`vbMethod`、`vbGet`、`vbLet`或`vbSet`。 *args* : *可选* 传给方法、**Property Get**、**Property Let**或**Property Set**的参数。 返回值是一个**Variant**,包含调用返回的任何内容。对于不返回值的方法或属性赋值,结果为**Empty**。 ### 示例 这三个调用使用**CallByName**按名称操作控件。第一个将其**MousePointer**属性设置为十字光标,第二个读回同一属性,第三个调用**Move**方法重新定位控件。 ```vb CallByName Text1, "MousePointer", vbLet, vbCrosshair Result = CallByName(Text1, "MousePointer", vbGet) CallByName Text1, "Move", vbMethod, 100, 100 ``` ### 另请参阅 * [CallByDispId](/official/Reference/VBA/Interaction/CallByDispId)函数 * [VbCallType](/official/Reference/VBA/Constants/VbCallType)枚举 --- --- url: /en/official/Tutorials/Windows-API.md --- # Calling the Windows API This tutorial demonstrates an end-to-end Windows API call --- writing a `Declare` statement, calling the function, handling the result, and reading error information when things go wrong. By the end you will have a small form that tracks and displays the current mouse cursor position in real time. ## Background The Windows API is a large set of C functions exposed by system DLLs such as `user32.dll`, `kernel32.dll`, and `gdi32.dll`. VBA and twinBASIC can call these functions directly using a `Declare` statement, which maps an external function into the module's namespace with a typed signature. The two things that matter most when writing a Declare: 1. **The correct type for every parameter.** A wrong type can pass the wrong number of bytes and corrupt the stack or heap. 2. **32-bit vs. 64-bit compatibility.** Many Win32 types are pointer-sized; they are 4 bytes in a 32-bit build and 8 bytes in a 64-bit build. twinBASIC handles both concerns through **LongPtr** (a pointer-width integer) and the `PtrSafe` keyword (which signals that a Declare is safe to use in a 64-bit process). ## The example: tracking mouse coordinates `GetCursorPos` reads the current screen coordinates of the mouse pointer and writes them into a caller-supplied `POINT` structure. It is a simple, safe function with no side effects --- a good starting point for learning the pattern. The C prototype from the Windows SDK: ```c BOOL GetCursorPos(LPPOINT lpPoint); ``` * Return value: non-zero on success, zero on failure. * The single parameter is a pointer to a `POINT` structure that the function fills. A twinBASIC translation: ```vb Private Type POINT x As Long y As Long End Type Private Declare PtrSafe Function GetCursorPos Lib "user32" _ (lpPoint As POINT) As Long ``` `POINT` contains two 32-bit integer fields. Even in a 64-bit build the fields themselves remain 32-bit --- only pointer values change width. `Long` is correct here. The parameter `lpPoint As POINT` is passed **ByRef** by default. ByRef means twinBASIC passes the address of the local `POINT` variable to the function, which writes the coordinates back into it through that pointer. This is the standard Windows pattern for output parameters typed as `LP<Something>`. ## Step 1: Create the project and form Create a new Standard EXE project (or open an existing one). On `Form1`, add: | Control | Name | Caption | Notes | |---------|------|---------|-------| | Label | `lblCoords` | `(waiting...)` | Shows the current coordinates | | Timer | `Timer1` | --- | Set **Interval** to `100` (ms), **Enabled** to `True` | The Timer fires its `Timer` event every 100 milliseconds. Each firing will call `GetCursorPos` and update the label. ## Step 2: Add the Declare and the UDT Open the Code Editor for `Form1`. At the top of the module, before any procedures, add the UDT and the Declare: ```vb Private Type POINT x As Long y As Long End Type Private Declare PtrSafe Function GetCursorPos Lib "user32" _ (lpPoint As POINT) As Long ``` ::: info `PtrSafe` is required on any `Declare` that will be used in a 64-bit build. It tells the compiler that the signature has been reviewed for pointer-width correctness. Including `PtrSafe` on a 32-bit-only project has no effect, so it is good practice to use it everywhere. ::: ## Step 3: Call the function and handle the result Double-click the Timer control in the designer to generate the `Timer1_Timer` event handler, then fill it in: ```vb Private Sub Timer1_Timer() Dim pt As POINT Dim success As Long success = GetCursorPos(pt) If success <> 0 Then lblCoords.Caption = "X: " & pt.x & " Y: " & pt.y Else lblCoords.Caption = "(error)" End If End Sub ``` `GetCursorPos` returns non-zero when it succeeds and zero when it fails. The `POINT` fields `x` and `y` are valid only when the return is non-zero. ## Step 4: Run the application Press **F5**. Move the mouse over the form. The label updates ten times per second with the current screen coordinates (in pixels, measured from the top-left corner of the primary monitor). ## Error handling with GetLastError When a Win32 function returns a failure code, the extended error information is available through `GetLastError` --- another kernel32 function: ```vb Private Declare PtrSafe Function GetLastError Lib "kernel32" () As Long ``` ::: info In VBA-compatible code you can also read the last Win32 error through [**Err.LastDllError**](/en/official/Reference/VBA/Information/Err), which is populated automatically after any DLL call. Both return the same value; `Err.LastDllError` does not require an extra Declare. ::: A robust version of the Timer handler: ```vb Private Sub Timer1_Timer() Dim pt As POINT If GetCursorPos(pt) <> 0 Then lblCoords.Caption = "X: " & pt.x & " Y: " & pt.y Else lblCoords.Caption = "GetCursorPos failed (error " & Err.LastDllError & ")" End If End Sub ``` In practice `GetCursorPos` almost never fails; checking the return code matters for functions that deal with file handles, network connections, or security contexts where failure is routine. ## 32-bit vs. 64-bit considerations For `GetCursorPos` the distinction does not arise because all its types are concrete 32-bit integers. Many other API functions use pointer-sized types that require care: | C type | twinBASIC type | Why | |--------|----------------|-----| | `HWND`, `HANDLE` | **LongPtr** | Window and object handles are pointer-sized | | `HINSTANCE`, `HMODULE` | **LongPtr** | Instance handles are pointer-sized | | `LPCWSTR`, `LPWSTR` | **LongPtr** (with StrPtr) or **String** | String pointers are pointer-sized | | `DWORD` | **Long** | Always 32-bit | | `BOOL` | **Long** | Always 32-bit | | `INT`, `int` | **Long** | Always 32-bit | A Declare that uses `Long` for a handle type compiles and runs in 32-bit mode but fails or crashes in 64-bit mode because a 64-bit handle does not fit in 4 bytes. Always use `LongPtr` for handle and pointer parameters. ### Example: GetForegroundWindow ```vb Private Declare PtrSafe Function GetForegroundWindow Lib "user32" () As LongPtr Private Sub ShowActiveWindow() Dim hwnd As LongPtr hwnd = GetForegroundWindow() MsgBox "Active window handle: " & hwnd End Sub ``` The return type is `LongPtr` because a window handle is pointer-sized. In a 32-bit build `LongPtr` is 4 bytes; in a 64-bit build it is 8 bytes. The same Declare and the same calling code work in both targets without any `#If Win64` conditional. ## ANSI vs. Unicode function variants Most Win32 text-related functions come in two variants: an ANSI version (suffix `A`) that takes `LPSTR` / `char*` strings, and a Unicode version (suffix `W`) that takes `LPWSTR` / `wchar_t*` strings. twinBASIC strings are Unicode (`BSTR`), so always prefer the `W` variant. Specify the Unicode function name in the `Alias` clause when the unaliased name would resolve to the ANSI variant: ```vb ' Without Alias, the linker resolves to the ANSI variant on some systems. ' Alias forces the Unicode variant explicitly: Private Declare PtrSafe Function GetWindowText Lib "user32" _ Alias "GetWindowTextW" _ (ByVal hwnd As LongPtr, _ ByVal lpString As Long, _ ByVal nMaxCount As Long) As Long ``` For functions where twinBASIC can pass a **String** directly, `DeclareWide` is an alternative to manually managing the buffer pointer --- see [Features → Enhanced API Declarations](/en/official/Features/Advanced/API-Declarations) for the `DeclareWide` and `CDecl` extensions. ## Putting it together The full module for the cursor-tracking form: ```vb Private Type POINT x As Long y As Long End Type Private Declare PtrSafe Function GetCursorPos Lib "user32" _ (lpPoint As POINT) As Long Private Sub Form_Load() Me.Caption = "Cursor position" lblCoords.Caption = "(waiting...)" Timer1.Interval = 100 Timer1.Enabled = True End Sub Private Sub Timer1_Timer() Dim pt As POINT If GetCursorPos(pt) <> 0 Then lblCoords.Caption = "X: " & pt.x & " Y: " & pt.y Else lblCoords.Caption = "GetCursorPos failed (error " & Err.LastDllError & ")" End If End Sub ``` ## Where to go next * **Enhanced API Declarations** -- `DeclareWide`, `CDecl`, `ByVal` UDTs, variadic arguments: [Features → Enhanced API Declarations](/en/official/Features/Advanced/API-Declarations) * **Forms basics** -- the standard VB controls and event model: [Forms basics](/en/official/Tutorials/Forms) * **Unit testing** -- verifying functions that wrap API calls: [Writing unit tests with Assert](/en/official/Tutorials/Testing-with-Assert) --- --- url: /en/official/Reference/CustomControls/Framework/Canvas.md --- # Canvas type (UDT) The drawing surface a custom control paints onto. Passed to [**ICustomControl.Paint**](/en/official/Reference/CustomControls/Framework/ICustomControl#paint) on every redraw pass and used exclusively from inside that method --- its lifetime is the duration of the single paint pass. A custom control builds up one or more `ElementDescriptor` records describing the rectangles to draw --- each with a position, size, fill, borders, corners, text, cursor, tab-index, and a set of `AddressOf`-registered input callbacks --- and passes each descriptor to [**RuntimeUICCCanvasAddElement**](#runtimeuicccanvasaddelement). The framework rasterises the descriptor, routes hit-testing to the registered callbacks, and (where the descriptor opts in) tracks keyboard tab order and focus. ```vb Private Sub OnPaint(ByVal Canvas As CustomControls.Canvas) _ Implements CustomControls.ICustomControl.Paint Dim descriptor As ElementDescriptor With descriptor .Left = 0 .Top = 0 .Width = Canvas.RuntimeUICCGetWidth() .Height = Canvas.RuntimeUICCGetHeight() Set .BackgroundFill = Me.NormalState.BackgroundFill .Text = Me.Caption Set .TextRenderingOptions = Me.NormalState.TextRendering .OnClick = AddressOf BtnClick Canvas.RuntimeUICCCanvasAddElement(descriptor) End With End Sub ``` ## Methods ### RuntimeUICCCanvasAddElement Adds an `ElementDescriptor` to the canvas. Each element becomes one painted rectangle plus its input-handling region. Descriptors are rendered in the order they are added, so later elements paint on top of earlier ones. Syntax: *Canvas*.**RuntimeUICCCanvasAddElement** *ElementDescriptor* *ElementDescriptor* : *required* A `ByRef` reference to the populated `ElementDescriptor` UDT. The framework copies the values it needs out of the record; the caller can reuse the variable for the next element. ### RuntimeUICCGetDpi Returns the DPI of the monitor the control is currently displayed on, as an integer (the standard 96 / 120 / 144 / … values). Syntax: *Canvas*.**RuntimeUICCGetDpi** ( ) **As Long** ### RuntimeUICCGetDpiScaleFactor Returns the DPI scale factor --- `RuntimeUICCGetDpi / 96` --- as a **Double**. Multiply [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount)-typed measurements by this value to convert from design-time pixels to device pixels at paint time. Syntax: *Canvas*.**RuntimeUICCGetDpiScaleFactor** ( ) **As Double** ### RuntimeUICCGetHeight Returns the height of the canvas in device pixels. Syntax: *Canvas*.**RuntimeUICCGetHeight** ( ) **As Long** ### RuntimeUICCGetWidth Returns the width of the canvas in device pixels. Syntax: *Canvas*.**RuntimeUICCGetWidth** ( ) **As Long** --- --- url: /zh/official/Reference/CustomControls/Framework/Canvas.md --- # Canvas 类型(UDT) 自定义控件绘制到的绘图表面。每次重绘过程传递给 [**ICustomControl.Paint**](/official/Reference/CustomControls/Framework/ICustomControl#paint),仅在该方法内部使用——其生命周期为单次绘制过程的持续时间。 自定义控件构建一个或多个 `ElementDescriptor` 记录描述要绘制的矩形——每个具有位置、大小、填充、边框、角、文本、光标、tab 索引和一组 `AddressOf` 注册的输入回调——并通过 [**RuntimeUICCCanvasAddElement**](#runtimeuicccanvasaddelement) 传递每个描述符。框架对描述符进行光栅化,将命中测试路由到已注册的回调,并(在描述符选择加入时)跟踪键盘 tab 顺序和焦点。 ```vb Private Sub OnPaint(ByVal Canvas As CustomControls.Canvas) _ Implements CustomControls.ICustomControl.Paint Dim descriptor As ElementDescriptor With descriptor .Left = 0 .Top = 0 .Width = Canvas.RuntimeUICCGetWidth() .Height = Canvas.RuntimeUICCGetHeight() Set .BackgroundFill = Me.NormalState.BackgroundFill .Text = Me.Caption Set .TextRenderingOptions = Me.NormalState.TextRendering .OnClick = AddressOf BtnClick Canvas.RuntimeUICCCanvasAddElement(descriptor) End With End Sub ``` ## 方法 ### RuntimeUICCCanvasAddElement 向画布添加 `ElementDescriptor`。每个元素成为一个绘制的矩形及其输入处理区域。描述符按添加顺序渲染,因此后添加的元素绘制在先添加的元素之上。 语法:*Canvas*.**RuntimeUICCCanvasAddElement** *ElementDescriptor* *ElementDescriptor* : *必需* 已填充 `ElementDescriptor` UDT 的 `ByRef` 引用。框架从中复制所需值;调用者可以重用该变量来描述下一个元素。 ### RuntimeUICCGetDpi 返回控件当前显示所在监视器的 DPI,以整数形式(标准值 96 / 120 / 144 / …)。 语法:*Canvas*.**RuntimeUICCGetDpi** ( ) **As Long** ### RuntimeUICCGetDpiScaleFactor 返回 DPI 缩放因子——`RuntimeUICCGetDpi / 96`——以 **Double** 形式。将 [**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount) 类型的测量值乘以此值以将设计时像素转换为绘制时的设备像素。 语法:*Canvas*.**RuntimeUICCGetDpiScaleFactor** ( ) **As Double** ### RuntimeUICCGetHeight 返回画布高度(设备像素)。 语法:*Canvas*.**RuntimeUICCGetHeight** ( ) **As Long** ### RuntimeUICCGetWidth 返回画布宽度(设备像素)。 语法:*Canvas*.**RuntimeUICCGetWidth** ( ) **As Long** --- --- url: /en/official/Reference/Categories.md --- This chapter lists the global statements and procedures that form the core of the twinBASIC language. # Categorical List ## Compiler Control * [Option](/en/official/Reference/Core/Option) - configure a compiler option * [#If ... Then ... Else](/en/official/Reference/Core/Topic-Preprocessor) - enable or disable compilation of enclosed code * [#Const](/en/official/Reference/Core/Topic-Preprocessor) - define a module-private conditional compiler constant ## Declarations and Definitions * [Class](/en/official/Reference/Core/Class), [Module](/en/official/Reference/Core/Module) - define a class or module * [Interface](/en/official/Reference/Core/Interface), [CoClass](/en/official/Reference/Core/CoClass) - (twinBASIC) define a COM interface or coclass using twinBASIC syntax * [Sub](/en/official/Reference/Core/Sub) - define a procedure * [Function](/en/official/Reference/Core/Function) - define a function * [Property](/en/official/Reference/Core/Property) - define a property * [ParamArray](/en/official/Reference/Core/ParamArray) - declare a procedure's final parameter as a variadic argument list * [Enum](/en/official/Reference/Core/Enum) - define an enumeration type with associated constants * [Type](/en/official/Reference/Core/Type) - declare a user-defined data type (UDT)/a structure * [Declare](/en/official/Reference/Core/Declare) - declare an external/library procedure or function * [Event](/en/official/Reference/Core/Event) - declare an event * [Implements](/en/official/Reference/Core/Implements) - specifies that a class implements a given interface * [End](/en/official/Reference/Core/End) - terminate execution, finish a Function, Sub, Property, or Enum definition, finish a Type declaration; finish a Class or Module, finish an If, Select, or With block ## Flow Control Statements: * [Call](/en/official/Reference/Core/Call) - invokes a procedure or function * [Do ... Loop](/en/official/Reference/Core/Do-Loop), [For ... Next](/en/official/Reference/Core/For-Next), [For Each ... Next](/en/official/Reference/Core/For-Each-Next), [While ... Wend](/en/official/Reference/Core/While-Wend) - loops * [If ... Then ... Else](/en/official/Reference/Core/If-Then-Else) - execute code conditionally * [Continue](/en/official/Reference/Core/Continue) - skip to the next iteration of the loop * [Exit](/en/official/Reference/Core/Exit) - exit a loop, procedure, function or property * [Return](/en/official/Reference/Core/Return) - return from a **GoSub** subroutine, or (twinBASIC) return a value and exit from a **Function** or **Property Get** * [Select Case](/en/official/Reference/Core/Select-Case) - execute a code block selected by an expression * [With](/en/official/Reference/Core/With) - bring a variable or expression into scope * [Goto](/en/official/Reference/Core/GoTo), [GoSub ... Return](/en/official/Reference/Core/GoSub-Return) - transfer execution to another location * [On ... GoTo](/en/official/Reference/Core/On-GoTo), [On ... GoSub](/en/official/Reference/Core/On-GoSub) - transfer execution to a location selected by an expression * [Stop](/en/official/Reference/Core/Stop) - interrupt execution Inline conditional functions --- expression-level alternatives to the **If...Then...Else** and **Select Case** statements above: * [If](/en/official/Reference/VBA/Interaction/If) - evaluate an expression and return one of two values; only the chosen branch is evaluated (twinBASIC addition) * [IIf](/en/official/Reference/VBA/Interaction/IIf) - evaluate an expression and return one of two values; both branches are always evaluated * [Choose](/en/official/Reference/VBA/Interaction/Choose) - return one value from a list, selected by 1-based index * [Switch](/en/official/Reference/VBA/Interaction/Switch) - return the value paired with the first **True** condition in a list of (condition, value) pairs See also: * [End](/en/official/Reference/Core/End) - terminate execution. * [On Error](/en/official/Reference/Core/On-Error), [Resume](/en/official/Reference/Core/Resume) - flow control for run-time errors (see [Error Handling](#error-handling)) ## Error Handling Statements: * [On Error](/en/official/Reference/Core/On-Error) - specifies what to do when an error occurs * [Resume](/en/official/Reference/Core/Resume) - resumes execution after an error has been caught * [Error](/en/official/Reference/Core/Error) statement - simulates the occurrence of an error (legacy; prefer **Err.Raise**) Procedures: * [Err](/en/official/Reference/VBA/Information/Err) - returns the **ErrObject** describing the current run-time error state * [Erl](/en/official/Reference/VBA/Information/Erl) - returns the line number where the most recent run-time error occurred * [Error$, Error](/en/official/Reference/VBA/Conversion/Error) function - returns the error message that corresponds to a given error number * [CVErr](/en/official/Reference/VBA/Conversion/CVErr) - wraps a numeric expression in a **Variant** of subtype **Error** * [SetThreadGlobalErrorTrap](/en/official/Reference/VBA/HiddenModule/SetThreadGlobalErrorTrap) - register a callback that fires when an unhandled run-time error escapes the active error handler chain on the calling thread ## Variable Declaration Statements: * [Dim](/en/official/Reference/Core/Dim) - declare a typed scalar or array variable * [Const](/en/official/Reference/Core/Const) - declare a constant * [Public](/en/official/Reference/Core/Public) - declare a public variable in a class or module * [Private](/en/official/Reference/Core/Private) - declare a private variable in a class or module * [Protected](/en/official/Reference/Core/Protected) - (twinBASIC) declare a class member accessible within the class and its derived classes * [Static](/en/official/Reference/Core/Static) - declare a a variable of static duration ## Variable Assignment and Modification Statements: * [Let](/en/official/Reference/Core/Let) - sets the value of a variable * [Set](/en/official/Reference/Core/Set) - changes the object referred by the variable * [New](/en/official/Reference/Core/New) - create a new instance of a class * [LSet](/en/official/Reference/Core/LSet) - assigns a user-defined type, or left-aligns a string * [RSet](/en/official/Reference/Core/RSet) - right-aligns a string Operators: * [Is](/en/official/Reference/Core/Is) - compares two object references for identity * [IsNot](/en/official/Reference/Core/IsNot) - (twinBASIC) the logical inverse of **Is** ## Arrays Statements: * [ReDim](/en/official/Reference/Core/ReDim) - allocate or change the size of a dynamically-sized array * [Erase](/en/official/Reference/Core/Erase) - fill a fixed-size array with default values, or invalidate a dynamic array Procedures: * [LBound](/en/official/Reference/VBA/Information/LBound) - smallest valid subscript for an array dimension * [UBound](/en/official/Reference/VBA/Information/UBound) - largest valid subscript for an array dimension * [IsArray](/en/official/Reference/VBA/Information/IsArray) - returns whether a variable is an array * [IsArrayInitialized](/en/official/Reference/VBA/Information/IsArrayInitialized) - returns whether an array has been dimensioned See also: * [Dim](/en/official/Reference/Core/Dim) - allocate a scalar or array variable * [Array](/en/official/Reference/VBA/Information/Array), [Filter](/en/official/Reference/VBA/Strings/Filter), [Join](/en/official/Reference/VBA/Strings/Join), [Split](/en/official/Reference/VBA/Strings/Split) - array helpers * [vbaAryMove](/en/official/Reference/VBA/HiddenModule/vbaAryMove), [vbaRefVarAry](/en/official/Reference/VBA/HiddenModule/vbaRefVarAry) - low-level **Variant**-array helpers (see [Memory and Pointers](#memory-and-pointers)) ## File I/O Statements: * [Open](/en/official/Reference/Core/Open), [Close](/en/official/Reference/Core/Close) - open/close a file for I/O operations * [Get](/en/official/Reference/Core/Get), [Put](/en/official/Reference/Core/Put) - read/write data from an open random access file * [Line Input](/en/official/Reference/Core/Line-Input), [Print](/en/official/Reference/Core/Print) - read/write a line from/to an open text file * [Input](/en/official/Reference/Core/Input), [Write](/en/official/Reference/Core/Write) - read/write data from an open sequential access file * [Seek](/en/official/Reference/Core/Seek) - change the current access position in an open file * [Lock](/en/official/Reference/Core/Lock), [Unlock](/en/official/Reference/Core/Unlock) - lock/unlock a range of records in an open file Procedures: * [Reset](/en/official/Reference/Core/Reset) - close all open disk files * [Width](/en/official/Reference/VBA/FileSystem/Width) - set the limit for line lengths when printing * [Input, Input$](/en/official/Reference/VBA/FileSystem/Input) - read a fixed number of characters from a sequential file * [InputB, InputB$](/en/official/Reference/VBA/FileSystem/InputB) - read a fixed number of bytes from a sequential file * [ChDir](/en/official/Reference/Core/ChDir), [ChDrive](/en/official/Reference/Core/ChDrive) - change the current working directory and disk drive * [MkDir](/en/official/Reference/Core/MkDir), [RmDir](/en/official/Reference/Core/RmDir) - create/remove a directory on disk * [Name](/en/official/Reference/Core/Name) - rename a file or directory on disk * [SetAttr](/en/official/Reference/Core/SetAttr) - set attributes of a file on disk * [FileCopy](/en/official/Reference/Core/FileCopy) - copy a file on disk * [Kill](/en/official/Reference/Core/Kill) - delete a file from disk * [SavePicture](/en/official/Reference/Core/SavePicture) - write a `Picture` or `Image` to a disk file * [MacID](/en/official/Reference/VBA/Conversion/MacID) - convert a 4-character Mac file-type code (legacy) ## State Management Procedures: * [Load](/en/official/Reference/Core/Load), [Unload](/en/official/Reference/Core/Unload) - load/unload a form or control into memory * [GetSetting](/en/official/Reference/VBA/Interaction/GetSetting), [SaveSetting](/en/official/Reference/VBA/Interaction/SaveSetting) - retrieve/store a string value from/to the system registry * [GetAllSettings](/en/official/Reference/VBA/Interaction/GetAllSettings) - retrieve every key/value pair in a section of an application's registry entry * [DeleteSetting](/en/official/Reference/VBA/Interaction/DeleteSetting) - remove value from the system registry ## Events Statements: * [RaiseEvent](/en/official/Reference/Core/RaiseEvent) - raise an event that may be handled by event handlers Procedures: * [RaiseEventByName](/en/official/Reference/VBA/Interaction/RaiseEventByName) - raise an event by name on an object, taking arguments as a **Variant** array * [RaiseEventByName2](/en/official/Reference/VBA/Interaction/RaiseEventByName2) - raise an event by name on an object, taking a variable-length argument list * [RuntimeCreateGetMessageHook](/en/official/Reference/VBA/HiddenModule/RuntimeCreateGetMessageHook) - create an **IGetMessageHook** for filtering Windows messages destined for a window and (optionally) its descendants See also * [Event](/en/official/Reference/Core/Event) - declare an event * [IGetMessageHook interface](/en/official/Reference/VBA/HiddenModule/#igetmessagehook-interface) - subscribe a callback to a Windows message type, then start/stop delivery ## User Dialogs Procedures: * [MsgBox](/en/official/Reference/VBA/Interaction/MsgBox) - display a modal message dialog and return the button the user clicked * [InputBox](/en/official/Reference/VBA/Interaction/InputBox) - prompt the user for a line of text and return what was entered * [Beep](/en/official/Reference/VBA/Interaction/Beep) - sound a system beep ## Process Control Procedures: * [Shell](/en/official/Reference/VBA/Interaction/Shell) - run another program asynchronously and return its task ID * [AppActivate](/en/official/Reference/VBA/Interaction/AppActivate) - change the focus to, or activate, a named window * [SendKeys](/en/official/Reference/VBA/Interaction/SendKeys) - send keystrokes to the active window * [DoEvents](/en/official/Reference/VBA/Interaction/DoEvents) - yield control to the message loop so pending events can be processed ## COM and Automation Procedures: * [CreateObject](/en/official/Reference/VBA/Interaction/CreateObject) - create a new instance of a COM/Automation object * [GetObject](/en/official/Reference/VBA/Interaction/GetObject) - obtain a reference to an Automation object loaded from a file or already running * [CallByName](/en/official/Reference/VBA/Interaction/CallByName) - invoke a method or property on an object dynamically by name * [CallByDispId](/en/official/Reference/VBA/Interaction/CallByDispId) - invoke a method or property on an object dynamically by IDispatch dispatch ID (twinBASIC addition) * [CreateGUID](/en/official/Reference/VBA/HiddenModule/CreateGUID) - generate a fresh GUID and return it as a registry-formatted string * [vbaCastObj](/en/official/Reference/VBA/HiddenModule/vbaCastObj) - reinterpret an object as another COM interface (a typed `QueryInterface`) * [vbaObjSet](/en/official/Reference/VBA/HiddenModule/vbaObjSet), [vbaObjSetAddref](/en/official/Reference/VBA/HiddenModule/vbaObjSetAddref) - assign a raw object pointer to an **Object** variable, with or without addref * [vbaObjAddref](/en/official/Reference/VBA/HiddenModule/vbaObjAddref) - increment the COM reference count of the object at a given address See also: * [ObjPtr](/en/official/Reference/VBA/Information/ObjPtr) - return the COM-identity address of an object (see [Memory and Pointers](#memory-and-pointers)) ## Command Line and Environment Procedures: * [Command$, Command](/en/official/Reference/VBA/Interaction/Command) - return the command-line arguments passed to the program * [Environ$, Environ](/en/official/Reference/VBA/Interaction/Environ) - return the value of a process environment variable ## Colours Procedures: * [RGB](/en/official/Reference/VBA/Information/RGB) - build an RGB colour value from red, green, and blue components * [RGBA](/en/official/Reference/VBA/Information/RGBA) - build an RGBA colour value from red, green, blue, and alpha components * [RGB\_R](/en/official/Reference/VBA/Information/RGB_R), [RGB\_G](/en/official/Reference/VBA/Information/RGB_G), [RGB\_B](/en/official/Reference/VBA/Information/RGB_B), [RGBA\_A](/en/official/Reference/VBA/Information/RGBA_A) - extract individual colour components * [QBColor](/en/official/Reference/VBA/Information/QBColor) - return the RGB colour value for a QuickBASIC colour index * [TranslateColor](/en/official/Reference/VBA/Information/TranslateColor) - translate an OLE colour value to a plain RGB colour value ## Mathematics Procedures: * [Atn](/en/official/Reference/VBA/Math/Atn), [Cos](/en/official/Reference/VBA/Math/Cos), [Sin](/en/official/Reference/VBA/Math/Sin), [Tan](/en/official/Reference/VBA/Math/Tan) - trigonometric functions * [Sqr](/en/official/Reference/VBA/Math/Sqr) - take a square root * [Exp](/en/official/Reference/VBA/Math/Exp) - calculate an exponential with base $e$ * [Log](/en/official/Reference/VBA/Math/Log) - calculate the natural (base $e$) logarithm of a number * [Sgn](/en/official/Reference/VBA/Math/Sgn) - return the sign of a number * [Abs](/en/official/Reference/VBA/Math/Abs) - returns the absolute value of a number * [Round](/en/official/Reference/VBA/Math/Round) - round the number to a given number of decimal places * [Rnd](/en/official/Reference/VBA/Math/Rnd) - generate a random number in the range \[0.0, 1.0) * [Randomize](/en/official/Reference/VBA/Math/Randomize) - seed the random number generator * [Partition](/en/official/Reference/VBA/Interaction/Partition) - return a string label identifying which of a series of equal-width numeric ranges a value falls into (histogram-style bucketing) See also: * [Fix](/en/official/Reference/VBA/Conversion/Fix), [Int](/en/official/Reference/VBA/Conversion/Int) - extract the integer portion of a number * [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CLngLng](/en/official/Reference/VBA/Conversion/CLngLng), [CLngPtr](/en/official/Reference/VBA/Conversion/CLngPtr) - coerce to integer types (rounds half-to-even) ## Type Conversion Procedures that coerce an expression to a specific type: * [CBool](/en/official/Reference/VBA/Conversion/CBool), [CByte](/en/official/Reference/VBA/Conversion/CByte), [CCur](/en/official/Reference/VBA/Conversion/CCur), [CDbl](/en/official/Reference/VBA/Conversion/CDbl), [CDec](/en/official/Reference/VBA/Conversion/CDec), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CLngLng](/en/official/Reference/VBA/Conversion/CLngLng), [CLngPtr](/en/official/Reference/VBA/Conversion/CLngPtr), [CSng](/en/official/Reference/VBA/Conversion/CSng) - coerce to a specific numeric type * [CStr](/en/official/Reference/VBA/Conversion/CStr) - coerce to **String** (locale-aware; preferred over [Str](/en/official/Reference/VBA/Conversion/Str)) * [CVar](/en/official/Reference/VBA/Conversion/CVar) - coerce to **Variant** * [CDate](/en/official/Reference/VBA/Conversion/CDate) - coerce to **Date**; [CVDate](/en/official/Reference/VBA/Conversion/CVDate) returns a **Variant** of subtype **Date** (legacy) * [CType](/en/official/Reference/VBA/Conversion/CType) - explicit cast operator with a caller-supplied target type (twinBASIC extension) Procedures that convert between numbers and strings: * [Hex$, Hex](/en/official/Reference/VBA/Conversion/Hex) - hexadecimal string representation of a number * [Oct$, Oct](/en/official/Reference/VBA/Conversion/Oct) - octal string representation of a number * [Str$, Str](/en/official/Reference/VBA/Conversion/Str) - decimal string representation of a number * [Val](/en/official/Reference/VBA/Conversion/Val) - parse a string into a **Double** * [ValDec](/en/official/Reference/VBA/Conversion/ValDec) - parse a string into a **Decimal** Procedures that extract the integer portion of a number: * [Fix](/en/official/Reference/VBA/Conversion/Fix) - truncates toward zero * [Int](/en/official/Reference/VBA/Conversion/Int) - rounds toward negative infinity Other: * [Nz](/en/official/Reference/VBA/Conversion/Nz) - replace **Null** with a default value See also: * [Format$, Format](/en/official/Reference/VBA/Strings/Format) - locale-aware number formatting * [FormatNumber](/en/official/Reference/VBA/Strings/FormatNumber), [FormatPercent](/en/official/Reference/VBA/Strings/FormatPercent), [FormatCurrency](/en/official/Reference/VBA/Strings/FormatCurrency), [FormatDateTime](/en/official/Reference/VBA/Strings/FormatDateTime) - typed formatters * [CVErr](/en/official/Reference/VBA/Conversion/CVErr), [Error$, Error](/en/official/Reference/VBA/Conversion/Error) function - error helpers (see [Error Handling](#error-handling)) ## Type Inspection Procedures that name or identify a variable's subtype: * [VarType](/en/official/Reference/VBA/Information/VarType) - returns the **VbVarType** code identifying a variable's subtype * [TypeName](/en/official/Reference/VBA/Information/TypeName) - returns the name of a variable's data type as a **String** Procedures that test a value's state or subtype: * [IsDate](/en/official/Reference/VBA/Information/IsDate) - returns whether an expression can be evaluated as a date * [IsEmpty](/en/official/Reference/VBA/Information/IsEmpty) - returns whether a **Variant** is uninitialised * [IsError](/en/official/Reference/VBA/Information/IsError) - returns whether an expression is an error subtype * [IsMissing](/en/official/Reference/VBA/Information/IsMissing) - returns whether an optional argument was supplied * [IsNull](/en/official/Reference/VBA/Information/IsNull) - returns whether a variable contains a **Null** value * [IsNumeric](/en/official/Reference/VBA/Information/IsNumeric) - returns whether an expression can be evaluated as a number * [IsObject](/en/official/Reference/VBA/Information/IsObject) - returns whether a variable refers to an object See also: * [IsArray](/en/official/Reference/VBA/Information/IsArray), [IsArrayInitialized](/en/official/Reference/VBA/Information/IsArrayInitialized) - in [Arrays](#arrays) ## String Handling Statements that modify strings: * [Mid =](/en/official/Reference/Core/Mid-equals), [MidB =](/en/official/Reference/Core/MidB-equals) - assign to or replace characters or wide/narrow string sections Procedures that check properties of strings: * [Len](/en/official/Reference/VBA/Strings/Len), [LenB](/en/official/Reference/VBA/Strings/Len) - the length of a string * [Asc](/en/official/Reference/VBA/Strings/Asc), [AscB](/en/official/Reference/VBA/Strings/Asc), [AscW](/en/official/Reference/VBA/Strings/Asc) - returns the character code of the first letter in a string * [StrComp](/en/official/Reference/VBA/Strings/StrComp) - compares two strings * [InStr$](/en/official/Reference/VBA/Strings/InStr), [InStrB](/en/official/Reference/VBA/Strings/InStr), [InStr](/en/official/Reference/VBA/Strings/InStr) - finds the position of a given substring in a string Procedures that create strings: * [Chr$](/en/official/Reference/VBA/Strings/Chr), [Chr](/en/official/Reference/VBA/Strings/Chr), [ChrB$](/en/official/Reference/VBA/Strings/Chr), [ChrB](/en/official/Reference/VBA/Strings/Chr), [ChrW$](/en/official/Reference/VBA/Strings/Chr), [ChrW](/en/official/Reference/VBA/Strings/Chr) - returns the character having a given code * [Space$](/en/official/Reference/VBA/Strings/Space), [Space](/en/official/Reference/VBA/Strings/Space) - return a string of spaces * [String$](/en/official/Reference/VBA/Strings/String), [String](/en/official/Reference/VBA/Strings/String) - return a string of specified characters Procedures that return modified strings: * [Left$](/en/official/Reference/VBA/Strings/Left), [Left](/en/official/Reference/VBA/Strings/Left), [LeftB$](/en/official/Reference/VBA/Strings/Left), [LeftB](/en/official/Reference/VBA/Strings/Left) - extract a left substring of a string * [Mid$](/en/official/Reference/VBA/Strings/Mid), [Mid](/en/official/Reference/VBA/Strings/Mid), [MidB$](/en/official/Reference/VBA/Strings/Mid), [MidB](/en/official/Reference/VBA/Strings/Mid) - extract a substring of a string * [Right$](/en/official/Reference/VBA/Strings/Right), [Right](/en/official/Reference/VBA/Strings/Right), [RightB$](/en/official/Reference/VBA/Strings/Right), [RightB](/en/official/Reference/VBA/Strings/Right) - extract a right substring of a string * [LTrim$](/en/official/Reference/VBA/Strings/LTrim), [LTrim](/en/official/Reference/VBA/Strings/LTrim), [RTrim$](/en/official/Reference/VBA/Strings/RTrim), [RTrim](/en/official/Reference/VBA/Strings/RTrim) - removes leading/trailing spaces from a string * [Trim$](/en/official/Reference/VBA/Strings/Trim), [Trim](/en/official/Reference/VBA/Strings/Trim) - removes leading and trailing spaces from a string * [StrReverse](/en/official/Reference/VBA/Strings/StrReverse) - reverses the order of characters of a string * [LCase$](/en/official/Reference/VBA/Strings/LCase), [LCase](/en/official/Reference/VBA/Strings/LCase), [UCase$](/en/official/Reference/VBA/Strings/UCase), [UCase](/en/official/Reference/VBA/Strings/UCase) - capitalizes or lowercases a string * [StrConv](/en/official/Reference/VBA/Strings/StrConv) - converts the string to a specified format * [Join](/en/official/Reference/VBA/Strings/Join) - concatenates a string array using a given delimiter * [Split](/en/official/Reference/VBA/Strings/Split) - splits a string into a string array * [Replace](/en/official/Reference/VBA/Strings/Replace) - replaces substrings in a string * [Filter](/en/official/Reference/VBA/Strings/Filter) - filters a string array into a subset according to criteria * [InStrRev](/en/official/Reference/VBA/Strings/InStrRev) - returns the position of a given substring in a string, searching from the end * [Format$](/en/official/Reference/VBA/Strings/Format), [Format](/en/official/Reference/VBA/Strings/Format) - format a numeric expression in a specific way * [FormatNumber](/en/official/Reference/VBA/Strings/FormatNumber) - formats an expression as a numeric string * [FormatPercent](/en/official/Reference/VBA/Strings/FormatPercent) - formats an expression as a percent string Procedures that convert between numbers and strings: * [CStr](/en/official/Reference/VBA/Conversion/CStr) - coerce a value to **String** (locale-aware) * [Hex$, Hex](/en/official/Reference/VBA/Conversion/Hex) - hexadecimal string representation of a number * [Oct$, Oct](/en/official/Reference/VBA/Conversion/Oct) - octal string representation of a number * [Str$, Str](/en/official/Reference/VBA/Conversion/Str) - decimal string representation of a number * [Val](/en/official/Reference/VBA/Conversion/Val) - parse a string into a **Double** * [ValDec](/en/official/Reference/VBA/Conversion/ValDec) - parse a string into a **Decimal** See also: * [FormatCurrency](/en/official/Reference/VBA/Strings/FormatCurrency) - format an expression as a currency string * [FormatDateTime](/en/official/Reference/VBA/Strings/FormatDateTime) - formats an expression as a date/time string ## Date and Time Procedures: * [Date](/en/official/Reference/Core/Date), [Time](/en/official/Reference/Core/Time) - set the current date and time * [FormatDateTime](/en/official/Reference/VBA/Strings/FormatDateTime) - formats an expression as a date/time string * [MonthName](/en/official/Reference/VBA/Strings/MonthName) - returns the name of the specified month * [WeekdayName](/en/official/Reference/VBA/Strings/WeekdayName) - returns the name of the specified day of the week See also: * [CDate](/en/official/Reference/VBA/Conversion/CDate), [CVDate](/en/official/Reference/VBA/Conversion/CVDate) - coerce an expression to **Date** or **Variant** (subtype **Date**) ## Introspection Procedures: * [CurrentProjectName](/en/official/Reference/VBA/Compilation/CurrentProjectName) - returns the name of the current project * [CurrentComponentName](/en/official/Reference/VBA/Compilation/CurrentComponentName) - returns the name of the current component (module or class) * [CurrentComponentCLSID](/en/official/Reference/VBA/Compilation/CurrentComponentCLSID) - returns the Class ID (CLSID) of the current class * [CurrentProcedureName](/en/official/Reference/VBA/Compilation/CurrentProcedureName) - returns the name of the procedure in which the function is called * [CurrentSourceFile](/en/official/Reference/VBA/Compilation/CurrentSourceFile) - returns the full path of the current source file * [ProcessorArchitecture](/en/official/Reference/VBA/Compilation/ProcessorArchitecture) - returns the processor architecture of the running application * [CompilerVersion](/en/official/Reference/VBA/Compilation/CompilerVersion) - returns the twinBASIC compiler version number * [GetDeclaredTypeProgId](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId), [GetDeclaredTypeClsid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid), [GetDeclaredTypeIid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid), [GetDeclaredTypeEventIid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid) - return the COM ProgID/CLSID/IID/event IID of a declared type, resolved at compile time * [GetDeclaredMinEnumValue](/en/official/Reference/VBA/HiddenModule/GetDeclaredMinEnumValue), [GetDeclaredMaxEnumValue](/en/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue) - return the smallest/largest value of a declared enumeration, resolved at compile time See also: * [IMEStatus](/en/official/Reference/VBA/Information/IMEStatus) - the current Input Method Editor mode (East Asian Windows only) ## Memory and Pointers Procedures: * [ObjPtr](/en/official/Reference/VBA/Information/ObjPtr) - return the COM-identity address of an object * [StrPtr](/en/official/Reference/VBA/Information/StrPtr) - return the address of the underlying buffer of a **String** * [VarPtr](/en/official/Reference/VBA/Information/VarPtr) - return the address of a variable * [AllocMem](/en/official/Reference/VBA/HiddenModule/AllocMem), [FreeMem](/en/official/Reference/VBA/HiddenModule/FreeMem) - allocate/release native memory blocks * [GetMem1](/en/official/Reference/VBA/HiddenModule/GetMem1), [GetMem2](/en/official/Reference/VBA/HiddenModule/GetMem2), [GetMem4](/en/official/Reference/VBA/HiddenModule/GetMem4), [GetMem8](/en/official/Reference/VBA/HiddenModule/GetMem8), [GetMemPtr](/en/official/Reference/VBA/HiddenModule/GetMemPtr) - read N bytes from a memory address into a typed variable * [PutMem1](/en/official/Reference/VBA/HiddenModule/PutMem1), [PutMem2](/en/official/Reference/VBA/HiddenModule/PutMem2), [PutMem4](/en/official/Reference/VBA/HiddenModule/PutMem4), [PutMem8](/en/official/Reference/VBA/HiddenModule/PutMem8), [PutMemPtr](/en/official/Reference/VBA/HiddenModule/PutMemPtr) - write a typed value of N bytes to a memory address * [vbaCopyBytes](/en/official/Reference/VBA/HiddenModule/vbaCopyBytes), [vbaCopyBytesZero](/en/official/Reference/VBA/HiddenModule/vbaCopyBytesZero) - copy a block of bytes; the *Zero* form clears the source after the copy See also: * [vbaAryMove](/en/official/Reference/VBA/HiddenModule/vbaAryMove), [vbaRefVarAry](/en/official/Reference/VBA/HiddenModule/vbaRefVarAry) - low-level **Variant**-array helpers (see [Arrays](#arrays)) * [vbaObjSet](/en/official/Reference/VBA/HiddenModule/vbaObjSet), [vbaObjSetAddref](/en/official/Reference/VBA/HiddenModule/vbaObjSetAddref), [vbaObjAddref](/en/official/Reference/VBA/HiddenModule/vbaObjAddref) - object-pointer assignment and refcounting (see [COM and Automation](#com-and-automation)) ## Threading and Atomics Procedures: * [InterlockedExchangePointer](/en/official/Reference/VBA/HiddenModule/InterlockedExchangePointer) - atomically exchange a pointer-sized value * [InterlockedCompareExchangePointer](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer) - atomically compare-and-swap a pointer-sized value * [InterlockedCompareExchange32](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32), [InterlockedCompareExchange64](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64) - atomic 32-bit / 64-bit compare-and-swap * [InterlockedIncrement32](/en/official/Reference/VBA/HiddenModule/InterlockedIncrement32), [InterlockedDecrement32](/en/official/Reference/VBA/HiddenModule/InterlockedDecrement32) - atomic 32-bit increment / decrement See also: * [SetThreadGlobalErrorTrap](/en/official/Reference/VBA/HiddenModule/SetThreadGlobalErrorTrap) - per-thread error trap (see [Error Handling](#error-handling)) ## Inline Assembly and Codegen Procedures: * [Emit](/en/official/Reference/VBA/HiddenModule/Emit) - inject custom **Byte** values into the codegen of the enclosing procedure * [EmitAny](/en/official/Reference/VBA/HiddenModule/EmitAny) - inject custom typed values into the codegen of the enclosing procedure (size inferred from each value's data type) * [StackOffset](/en/official/Reference/VBA/HiddenModule/StackOffset) - return the stack-frame offset of a variable, resolved at compile time * [StackArgsSize](/en/official/Reference/VBA/HiddenModule/StackArgsSize) - return the total size of stack-passed arguments to the enclosing procedure * [UnprotectedAccess](/en/official/Reference/VBA/HiddenModule/UnprotectedAccess) - return an object reference that bypasses access checks on private members See also: * [Direct Assembly Insertion](/en/official/Features/Advanced/Assembly) - the `Naked` modifier and worked examples ## Expression Evaluation Procedures: * [Eval](/en/official/Reference/VBA/HiddenModule/Eval) - compile and evaluate a twinBASIC expression supplied as a string See also: * [ExpressionService module](/en/official/Reference/VBA/TbExpressionService/) - the underlying engine, when more control over binders or compiled-expression reuse is needed ## Financial Procedures: * [DDB](/en/official/Reference/VBA/Financial/DDB) - depreciation of an asset via the Double-Declining Balance method * [FV](/en/official/Reference/VBA/Financial/FV) - future value of an investment with constant deposits and interest * [Pmt](/en/official/Reference/VBA/Financial/Pmt) - payment for a loan with constant payments and interest * [IPmt](/en/official/Reference/VBA/Financial/IPmt) - interest payment for a loan with constant payments and interest * [PPmt](/en/official/Reference/VBA/Financial/PPmt) - principal payment for a loan with constant payments and interest * [SYD](/en/official/Reference/VBA/Financial/SYD) - sum-of-years' digits depreciation of an asset * [SLN](/en/official/Reference/VBA/Financial/SLN) - straight-line depreciation of an asset in one period * [PV](/en/official/Reference/VBA/Financial/PV) - present value of investment * [IRR](/en/official/Reference/VBA/Financial/IRR) - internal rate of return for a series of cash flows * [MIRR](/en/official/Reference/VBA/Financial/MIRR) - modified internal rate of return for a series of cash flow * [Rate](/en/official/Reference/VBA/Financial/Rate) - interest rate per period of an annuity * [NPV](/en/official/Reference/VBA/Financial/NPV) - net present value of an investment * [NPer](/en/official/Reference/VBA/Financial/NPer) - number of periods for an investment with constant deposits and interest * [FormatCurrency](/en/official/Reference/VBA/Strings/FormatCurrency) - format an expression as a currency string ## Unit Testing Modules of the [Assert](/en/official/Reference/Assert/) package: * [Exact](/en/official/Reference/Assert/Exact) - strictest comparison semantics; datatypes must match and no implicit conversions happen * [Strict](/en/official/Reference/Assert/Strict) - case-sensitive strings, otherwise standard twinBASIC equality * [Permissive](/en/official/Reference/Assert/Permissive) - case-insensitive strings, otherwise standard twinBASIC equality Each module exposes the same fifteen assertions: **Succeed**, **Fail**, **Inconclusive**, **AreEqual** / **AreNotEqual**, **AreSame** / **AreNotSame**, **IsTrue** / **IsFalse**, **IsNothing** / **IsNotNothing**, **IsNull** / **IsNotNull**, **SequenceEquals** / **NotSequenceEquals**. All are tagged `[DebugOnly(True)]` and compile out of release builds. ## Deprecated Statements: * [DefBool, DefByte, DefInt, DefLng, DefCur, DefSng, DefDbl, DefDec, DefDate, DefStr, DefObj, DefVar](/en/official/Reference/Core/Deftype) - used to give implicit types to single-letter variables --- --- url: /en/official/Reference/VBA/Conversion/CBool.md --- # CBool Coerces an expression to a **Boolean**. Syntax: **CBool(** *expression* **)** *expression* : *required* Any valid string or numeric expression. The return type is **Boolean**. If *expression* evaluates to a nonzero value, **CBool** returns **True**; otherwise, it returns **False**. If *expression* cannot be interpreted as a numeric value, a run-time error occurs. The data-type conversion functions document code by showing that the result of some operation should be expressed as a particular data type rather than the default data type. ### Example This example uses the **CBool** function to convert an expression to a **Boolean**. ```vb Dim A, B, Check A = 5: B = 5 ' Initialize variables. Check = CBool(A = B) ' Check contains True. A = 0 ' Define variable. Check = CBool(A) ' Check contains False. ``` ### See Also * [CByte](/en/official/Reference/VBA/Conversion/CByte), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CDbl](/en/official/Reference/VBA/Conversion/CDbl), [CSng](/en/official/Reference/VBA/Conversion/CSng), [CStr](/en/official/Reference/VBA/Conversion/CStr), [CVar](/en/official/Reference/VBA/Conversion/CVar) functions --- --- url: /zh/official/Reference/VBA/Conversion/CBool.md --- # CBool 将表达式强制转换为 **Boolean**。 语法:**CBool(** *expression* **)** *expression* : *必需* 任何有效的字符串或数值表达式。 返回类型为 **Boolean**。如果 *expression* 的计算结果为非零值,**CBool** 返回 **True**;否则返回 **False**。 如果 *expression* 不能被解释为数值,将发生运行时错误。 数据类型转换函数通过表明某个运算的结果应以特定数据类型而非默认数据类型来表达,从而为代码提供文档说明。 ### 示例 此示例使用 **CBool** 函数将表达式转换为 **Boolean**。 ```vb Dim A, B, Check A = 5: B = 5 ' Initialize variables. Check = CBool(A = B) ' Check contains True. A = 0 ' Define variable. Check = CBool(A) ' Check contains False. ``` ### 另请参阅 * [CByte](/official/Reference/VBA/Conversion/CByte)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLng](/official/Reference/VBA/Conversion/CLng)、[CDbl](/official/Reference/VBA/Conversion/CDbl)、[CSng](/official/Reference/VBA/Conversion/CSng)、[CStr](/official/Reference/VBA/Conversion/CStr)、[CVar](/official/Reference/VBA/Conversion/CVar) 函数 --- --- url: /en/official/Reference/VBA/Conversion/CByte.md --- # CByte Coerces an expression to a **Byte**. Syntax: **CByte(** *expression* **)** *expression* : *required* Any valid string or numeric expression in the range `0` to `255`. The return type is **Byte**. If *expression* is outside the range of a **Byte**, a run-time error occurs. Fractions are rounded --- when the fractional part is exactly `0.5`, **CByte** rounds to the nearest even number. ### Example This example uses the **CByte** function to convert an expression to a **Byte**. ```vb Dim MyDouble, MyByte MyDouble = 125.5678 ' MyDouble is a Double. MyByte = CByte(MyDouble) ' MyByte contains 126. ``` ### See Also * [CBool](/en/official/Reference/VBA/Conversion/CBool), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CDbl](/en/official/Reference/VBA/Conversion/CDbl), [CSng](/en/official/Reference/VBA/Conversion/CSng), [CStr](/en/official/Reference/VBA/Conversion/CStr), [CVar](/en/official/Reference/VBA/Conversion/CVar) functions --- --- url: /zh/official/Reference/VBA/Conversion/CByte.md --- # CByte 将表达式强制转换为 **Byte**。 语法:**CByte(** *expression* **)** *expression* : *必需* 范围在 `0` 到 `255` 之间的任何有效字符串或数值表达式。 返回类型为 **Byte**。如果 *expression* 超出 **Byte** 的范围,将发生运行时错误。小数部分会四舍五入——当小数部分恰好为 `0.5` 时,**CByte** 舍入到最接近的偶数。 ### 示例 此示例使用 **CByte** 函数将表达式转换为 **Byte**。 ```vb Dim MyDouble, MyByte MyDouble = 125.5678 ' MyDouble is a Double. MyByte = CByte(MyDouble) ' MyByte contains 126. ``` ### 另请参阅 * [CBool](/official/Reference/VBA/Conversion/CBool)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLng](/official/Reference/VBA/Conversion/CLng)、[CDbl](/official/Reference/VBA/Conversion/CDbl)、[CSng](/official/Reference/VBA/Conversion/CSng)、[CStr](/official/Reference/VBA/Conversion/CStr)、[CVar](/official/Reference/VBA/Conversion/CVar) 函数 --- --- url: /en/official/Reference/VBA/Conversion/CCur.md --- # CCur Coerces an expression to a **Currency**. Syntax: **CCur(** *expression* **)** *expression* : *required* Any valid string or numeric expression in the range `-922,337,203,685,477.5808` to `922,337,203,685,477.5807`. The return type is **Currency**. If *expression* is outside that range, a run-time error occurs. **CCur** forces currency arithmetic in cases where single-precision, double-precision, or integer arithmetic would normally occur. **CCur** is the internationally aware alternative to **Val** for converting between data types. **CCur** recognizes different decimal separators, different thousand separators, and various currency options properly, depending on the system's locale setting. ### Example This example uses the **CCur** function to convert an expression to a **Currency**. ```vb Dim MyDouble, MyCurr MyDouble = 543.214588 ' MyDouble is a Double. MyCurr = CCur(MyDouble * 2) ' Convert result of MyDouble * 2 ' (1086.429176) to a ' Currency (1086.4292). ``` ### See Also * [CBool](/en/official/Reference/VBA/Conversion/CBool), [CByte](/en/official/Reference/VBA/Conversion/CByte), [CDbl](/en/official/Reference/VBA/Conversion/CDbl), [CDec](/en/official/Reference/VBA/Conversion/CDec), [CSng](/en/official/Reference/VBA/Conversion/CSng), [CStr](/en/official/Reference/VBA/Conversion/CStr), [CVar](/en/official/Reference/VBA/Conversion/CVar) functions --- --- url: /zh/official/Reference/VBA/Conversion/CCur.md --- # CCur 将表达式强制转换为 **Currency**。 语法:**CCur(** *expression* **)** *expression* : *必需* 范围在 `-922,337,203,685,477.5808` 到 `922,337,203,685,477.5807` 之间的任何有效字符串或数值表达式。 返回类型为 **Currency**。如果 *expression* 超出该范围,将发生运行时错误。 **CCur** 在通常会发生单精度、双精度或整数运算的情况下强制进行货币运算。 **CCur** 是替代 **Val** 进行数据类型转换的区域感知方案。**CCur** 根据系统的区域设置正确识别不同的小数分隔符、千位分隔符和各种货币选项。 ### 示例 此示例使用 **CCur** 函数将表达式转换为 **Currency**。 ```vb Dim MyDouble, MyCurr MyDouble = 543.214588 ' MyDouble is a Double. MyCurr = CCur(MyDouble * 2) ' Convert result of MyDouble * 2 ' (1086.429176) to a ' Currency (1086.4292). ``` ### 另请参阅 * [CBool](/official/Reference/VBA/Conversion/CBool)、[CByte](/official/Reference/VBA/Conversion/CByte)、[CDbl](/official/Reference/VBA/Conversion/CDbl)、[CDec](/official/Reference/VBA/Conversion/CDec)、[CSng](/official/Reference/VBA/Conversion/CSng)、[CStr](/official/Reference/VBA/Conversion/CStr)、[CVar](/official/Reference/VBA/Conversion/CVar) 函数 --- --- url: /en/official/Reference/VBA/Conversion/CDate.md --- # CDate Coerces an expression to a **Date**. Syntax: **CDate(** *expression* **)** *expression* : *required* Any valid date expression --- a date literal, a date/time string, or a number that falls within the range of acceptable dates. The return type is **Date**. Use the **IsDate** function to determine whether *expression* can be converted to a date or time. **CDate** recognizes date literals and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number to a date, the whole-number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight. **CDate** recognizes date formats according to the system locale setting. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In addition, a long date format is not recognized if it also contains the day-of-the-week string. [**CVDate**](/en/official/Reference/VBA/Conversion/CVDate) is also provided for compatibility with previous versions of Visual Basic. The syntax of **CVDate** is identical to **CDate**; however, **CVDate** returns a **Variant** whose subtype is **Date** instead of an actual **Date** type. ### Example This example uses the **CDate** function to convert a string to a **Date**. In general, hard-coding dates and times as strings (as shown in this example) is not recommended. Use date literals and time literals, such as `#2/12/1969#` and `#4:45:23 PM#`, instead. ```vb Dim MyDate, MyShortDate, MyTime, MyShortTime MyDate = "February 12, 1969" ' Define date. MyShortDate = CDate(MyDate) ' Convert to Date data type. MyTime = "4:35:47 PM" ' Define time. MyShortTime = CDate(MyTime) ' Convert to Date data type. ``` ### See Also * [CVDate](/en/official/Reference/VBA/Conversion/CVDate), [DateValue](/en/official/Reference/VBA/DateTime/DateValue), [TimeValue](/en/official/Reference/VBA/DateTime/TimeValue) functions --- --- url: /zh/official/Reference/VBA/Conversion/CDate.md --- # CDate 将表达式强制转换为 **Date**。 语法:**CDate(** *expression* **)** *expression* : *必需* 任何有效的日期表达式——日期字面量、日期/时间字符串,或在可接受日期范围内的数字。 返回类型为 **Date**。 使用 **IsDate** 函数可以确定 *expression* 是否可以转换为日期或时间。**CDate** 可以识别日期字面量和时间字面量,以及在可接受日期范围内的一些数字。将数字转换为日期时,整数部分转换为日期。数字的小数部分转换为一天中的时间,从午夜开始。 **CDate** 根据系统区域设置识别日期格式。如果提供的日期格式不在已识别的日期设置之中,可能无法确定日、月、年的正确顺序。此外,如果长日期格式还包含星期字符串,则无法被识别。 同样提供了 [**CVDate**](/official/Reference/VBA/Conversion/CVDate) 以与先前版本的 Visual Basic 兼容。**CVDate** 的语法与 **CDate** 相同;但是,**CVDate** 返回的是子类型为 **Date** 的 **Variant**,而非实际的 **Date** 类型。 ### 示例 此示例使用 **CDate** 函数将字符串转换为 **Date**。通常,不建议将日期和时间硬编码为字符串(如本示例所示)。请改用日期字面量和时间字面量,例如 `#2/12/1969#` 和 `#4:45:23 PM#`。 ```vb Dim MyDate, MyShortDate, MyTime, MyShortTime MyDate = "February 12, 1969" ' Define date. MyShortDate = CDate(MyDate) ' Convert to Date data type. MyTime = "4:35:47 PM" ' Define time. MyShortTime = CDate(MyTime) ' Convert to Date data type. ``` ### 另请参阅 * [CVDate](/official/Reference/VBA/Conversion/CVDate)、[DateValue](/official/Reference/VBA/DateTime/DateValue)、[TimeValue](/official/Reference/VBA/DateTime/TimeValue) 函数 --- --- url: /en/official/Reference/VBA/Conversion/CDbl.md --- # CDbl Coerces an expression to a **Double**. Syntax: **CDbl(** *expression* **)** *expression* : *required* Any valid string or numeric expression in the **Double** range --- `-1.79769313486231E308` to `-4.94065645841247E-324` for negative values, and `4.94065645841247E-324` to `1.79769313486232E308` for positive values. The return type is **Double**. If *expression* is outside the range of a **Double**, a run-time error occurs. **CDbl** is the internationally aware alternative to [**Val**](/en/official/Reference/VBA/Conversion/Val) for converting a string to a numeric type. **CDbl** recognizes different decimal separators and different thousand separators properly, depending on the system's locale setting. ### Example This example uses the **CDbl** function to convert an expression to a **Double**. ```vb Dim MyCurr, MyDouble MyCurr = CCur(234.456784) ' MyCurr is a Currency. MyDouble = CDbl(MyCurr * 8.2 * 0.01) ' Convert result to a Double. ``` ### See Also * [CCur](/en/official/Reference/VBA/Conversion/CCur), [CDec](/en/official/Reference/VBA/Conversion/CDec), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CSng](/en/official/Reference/VBA/Conversion/CSng), [CStr](/en/official/Reference/VBA/Conversion/CStr), [CVar](/en/official/Reference/VBA/Conversion/CVar) functions --- --- url: /zh/official/Reference/VBA/Conversion/CDbl.md --- # CDbl 将表达式强制转换为 **Double**。 语法:**CDbl(** *expression* **)** *expression* : *必需* **Double** 范围内的任何有效字符串或数值表达式——负值为 `-1.79769313486231E308` 到 `-4.94065645841247E-324`,正值为 `4.94065645841247E-324` 到 `1.79769313486232E308`。 返回类型为 **Double**。如果 *expression* 超出 **Double** 的范围,将发生运行时错误。 **CDbl** 是替代 [**Val**](/official/Reference/VBA/Conversion/Val) 将字符串转换为数值类型的区域感知方案。**CDbl** 根据系统的区域设置正确识别不同的小数分隔符和千位分隔符。 ### 示例 此示例使用 **CDbl** 函数将表达式转换为 **Double**。 ```vb Dim MyCurr, MyDouble MyCurr = CCur(234.456784) ' MyCurr is a Currency. MyDouble = CDbl(MyCurr * 8.2 * 0.01) ' Convert result to a Double. ``` ### 另请参阅 * [CCur](/official/Reference/VBA/Conversion/CCur)、[CDec](/official/Reference/VBA/Conversion/CDec)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLng](/official/Reference/VBA/Conversion/CLng)、[CSng](/official/Reference/VBA/Conversion/CSng)、[CStr](/official/Reference/VBA/Conversion/CStr)、[CVar](/official/Reference/VBA/Conversion/CVar) 函数 --- --- url: /en/official/Reference/VBA/Conversion/CDec.md --- # CDec Coerces an expression to a **Decimal**. Syntax: **CDec(** *expression* **)** *expression* : *required* Any valid string or numeric expression. The range for zero-scaled numbers (no decimal places) is `±79,228,162,514,264,337,593,543,950,335`. For numbers with 28 decimal places, the range is `±7.9228162514264337593543950335`. The smallest possible non-zero number is `0.0000000000000000000000000001`. The return type is **Decimal**. ::: info In VBA, **CDec** does not return a discrete data type; it always returns a **Variant** whose value has been converted to a **Decimal** subtype. In twinBASIC, **Decimal** is a full first-class data type, so **CDec** returns a **Decimal** directly. The result can be assigned to a **Variant** for VBA-compatible behavior. ::: **CDec** is the internationally aware alternative to [**Val**](/en/official/Reference/VBA/Conversion/Val) for converting a string to a numeric type. ### Example This example uses the **CDec** function to convert a numeric value to a **Decimal**. ```vb Dim MyDecimal As Decimal, MyCurr As Currency MyCurr = 10000000.0587 ' MyCurr is a Currency. MyDecimal = CDec(MyCurr) ' MyDecimal is a Decimal. ``` ### See Also * [CCur](/en/official/Reference/VBA/Conversion/CCur), [CDbl](/en/official/Reference/VBA/Conversion/CDbl), [CSng](/en/official/Reference/VBA/Conversion/CSng), [ValDec](/en/official/Reference/VBA/Conversion/ValDec) functions --- --- url: /zh/official/Reference/VBA/Conversion/CDec.md --- # CDec 将表达式强制转换为 **Decimal**。 语法:**CDec(** *expression* **)** *expression* : *必需* 任何有效的字符串或数值表达式。零标度数字(无小数位)的范围是 `±79,228,162,514,264,337,593,543,950,335`。具有 28 位小数的数字范围是 `±7.9228162514264337593543950335`。可能的最小非零数是 `0.0000000000000000000000000001`。 返回类型为 **Decimal**。 ::: info 在 VBA 中,**CDec** 不返回离散数据类型;它始终返回值已转换为 **Decimal** 子类型的 **Variant**。在 twinBASIC 中,**Decimal** 是完整的一等数据类型,因此 **CDec** 直接返回 **Decimal**。可以将结果赋值给 **Variant** 以实现与 VBA 兼容的行为。 ::: **CDec** 是替代 [**Val**](/official/Reference/VBA/Conversion/Val) 将字符串转换为数值类型的区域感知方案。 ### 示例 此示例使用 **CDec** 函数将数值转换为 **Decimal**。 ```vb Dim MyDecimal As Decimal, MyCurr As Currency MyCurr = 10000000.0587 ' MyCurr is a Currency. MyDecimal = CDec(MyCurr) ' MyDecimal is a Decimal. ``` ### 另请参阅 * [CCur](/official/Reference/VBA/Conversion/CCur)、[CDbl](/official/Reference/VBA/Conversion/CDbl)、[CSng](/official/Reference/VBA/Conversion/CSng)、[ValDec](/official/Reference/VBA/Conversion/ValDec) 函数 --- --- url: /en/official/Tutorials/CEF.md --- # CEF The [**CefBrowser**](/en/official/Reference/CEF/CefBrowser/) control hosts a Chromium browser inside a twinBASIC form --- navigate to web pages, run local web apps, exchange messages and method calls with JavaScript, and print pages to PDF. Unlike [**WebView2**](/en/official/Tutorials/WebView2/), the Chromium runtime ships *alongside* the application rather than being a system component, so the browser version is under the developer's control and the same package works on machines without Edge installed. These tutorials demonstrate the most common patterns: * [Getting started](/en/official/Tutorials/CEF/Getting-started) -- adding the package reference, downloading the matching CEF runtime, and dropping a control onto a form. * [Customize the UserDataFolder](/en/official/Tutorials/CEF/Customize-the-UserDataFolder) -- relocating the runtime's working folder for hosted scenarios (Office add-ins, kiosk installs, portable deployments). * [Re-entrancy](/en/official/Tutorials/CEF/Re-entrancy) -- what the control's deferred-event machinery does for you, and the one place ([**JsRun**](/en/official/Reference/CEF/CefBrowser/#jsrun)) where you still have to think about it. * [Building a browser shell](/en/official/Tutorials/CEF/Building-a-browser-shell) -- address bar, back / forward / reload, zoom, PDF export --- turning the control into a working browser. * [Hosting local web assets](/en/official/Tutorials/CEF/Hosting-local-web-assets) -- serve HTML / JS / CSS from a project resource folder, without an HTTP server. * [JavaScript interop](/en/official/Tutorials/CEF/JavaScript-interop) -- the two bridges between BASIC and the page: messages and scripted calls. * [Driving Monaco from twinBASIC](/en/official/Tutorials/CEF/Driving-Monaco) -- a case study combining everything above: embed Microsoft's Monaco editor next to a live HTML preview pane. The complete sample code for the last four tutorials ships as *Sample 1b --- Chromium Embedded Framework Examples* in the New-Project dialog, mirroring *Sample 1a --- WebView2 Examples* almost feature-for-feature. ::: warning The CEF package is currently in **BETA**. Several features available on [**WebView2**](/en/official/Reference/WebView2/WebView2/) are not yet exposed --- see the [WebView2 parity](/en/official/Reference/CEF/#webview2-parity) section of the reference for the current gap list. ::: For the full set of members on the control itself, see the [**CefBrowser** class reference](/en/official/Reference/CEF/CefBrowser/). --- --- url: /zh/official/Tutorials/CEF.md --- # CEF [**CefBrowser**](/official/Reference/CEF/CefBrowser/)控件在twinBASIC窗体中托管Chromium浏览器——导航到网页、运行本地Web应用、与JavaScript交换消息和方法调用以及将页面打印为PDF。与[**WebView2**](/official/Tutorials/WebView2/)不同,Chromium运行时*随*应用程序一起发布,而不是系统组件,因此浏览器版本由开发者控制,相同的包可在未安装Edge的机器上运行。 这些教程演示了最常见的模式: * [入门](/official/Tutorials/CEF/Getting-started) —— 添加包引用、下载匹配的CEF运行时并将控件放置到窗体上。 * [自定义UserDataFolder](/official/Tutorials/CEF/Customize-the-UserDataFolder) —— 重新定位运行时的工作文件夹,用于宿主场景(Office加载项、信息亭安装、便携部署)。 * [重入性](/official/Tutorials/CEF/Re-entrancy) —— 控件的延迟事件机制为你做了什么,以及你仍需注意的一个地方([**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun))。 * [构建浏览器外壳](/official/Tutorials/CEF/Building-a-browser-shell) —— 地址栏、后退/前进/刷新、缩放、PDF导出——将控件变成可工作的浏览器。 * [托管本地Web资源](/official/Tutorials/CEF/Hosting-local-web-assets) —— 从项目资源文件夹提供HTML/JS/CSS,无需HTTP服务器。 * [JavaScript互操作](/official/Tutorials/CEF/JavaScript-interop) —— BASIC和页面之间的两座桥:消息和脚本调用。 * [从twinBASIC驱动Monaco](/official/Tutorials/CEF/Driving-Monaco) —— 综合以上所有内容的案例研究:嵌入Microsoft Monaco编辑器与实时HTML预览面板。 后四个教程的完整示例代码以*示例1b——Chromium Embedded Framework示例*的形式在新项目对话框中提供,几乎逐功能镜像*示例1a——WebView2示例*。 ::: warning CEF包目前处于**BETA**阶段。[**WebView2**](/official/Reference/WebView2/WebView2/)上的几个功能尚未暴露——参见参考的[WebView2对等](/official/Reference/CEF/#webview2-parity)部分了解当前差距列表。 ::: 关于控件本身的完整成员集,参见[**CefBrowser**类参考](/official/Reference/CEF/CefBrowser/)。 --- --- url: /zh/official/Reference/CEF.md --- # CEF 包 **cefPackage** 封装了 [Chromium Embedded Framework](https://chromiumembedded.github.io/cef/) 并将其作为普通的 twinBASIC 控件暴露。将 [**CefBrowser**](/official/Reference/CEF/CefBrowser/) 拖放到窗体上,Chromium 浏览器即可在其内部渲染Web内容——导航到URL、运行JavaScript、将页面打印为PDF,以及与已加载的页面交换消息。 该包是随 twinBASIC 一起发布的内置包,但 CEF 运行时本身是*单独*分发的——应用程序必须将匹配的运行时ZIP与可执行文件一起发布。参见下方的[运行时文件](#runtime-files)。 ::: warning CEF 包目前处于 **BETA** 阶段。[**WebView2**](/official/Reference/WebView2/) 上可用的若干功能尚未暴露;参见下方的 [WebView2 对等性](#webview2-parity)。 ::: ## 为什么选择 CEF 而不是 WebView2? CEF 和 [**WebView2**](/official/Reference/WebView2/) 都将基于Chromium的浏览器封装在 twinBASIC 控件中。CEF 对某些应用具有更重要的优势: * **跨平台就绪。** CEF 可在 Windows、Linux 和 macOS 上运行。[**WebView2**](/official/Reference/WebView2/) 仅限 Windows。 * **完全控制运行时栈。** 应用程序以特定的 Chromium 构建为目标,并将其与软件一起分发。应用程序控制之外不会有自动运行时更新,因此行为在不同部署之间保持一致。 * **更深入的运行时集成。** CEF 允许在渲染器/JavaScript进程内托管 twinBASIC 代码——这是更受限的 WebView2 对象模型无法做到的。 当仅面向现代 Windows 且可接受系统安装的 Edge 运行时时,[**WebView2**](/official/Reference/WebView2/) 是正确的选择;当需要控制 Chromium 版本或跨平台就绪性时,**CEF** 更为可取。 ## 支持的运行时 支持三个 CEF 版本,每个版本有不同的 Chromium 基线和不同的操作系统覆盖范围: | 运行时版本 | 支持的操作系统 | 备注 | | ---------- | -------------- | ------------------------------------------ | | **v49** | Windows XP+ | 最后一个支持 Windows XP 的 Chromium 版本。 | | **v109** | Windows 7+ | 最后一个支持 Windows 7 的 Chromium 版本。 | | **v145** | Windows 10+ | 推荐的现代运行时。 | ::: warning 较旧的 Chromium 版本通常不应用于不受限制的互联网浏览——它们存在未修补的安全漏洞。但对于浏览器仅加载受信任的本地或内部内容的严格受控环境,它们仍然适用。 ::: 用户在两个必须一致的位置选择运行时: * **编译时**——通过向项目添加匹配的 `[COMPILER PACKAGE] twinBASIC - Chromium Embedded Framework Package v<N>` 引用。这设置了包自身源代码编译时使用的 `CEF_VERSION` 条件编译常量(49、109 或 145)。[**CefBrowser.CefMajorVersion**](/official/Reference/CEF/CefBrowser/#cefmajorversion) 在运行时返回此值。 * **部署时**——通过发布匹配的运行时ZIP,解压到[发现文件夹](#installing-runtime-files)或通过 [**EnvironmentOptions.BrowserExecutableFolder**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#browserexecutablefolder) 指定。 运行时的位数必须与应用程序的位数匹配——32位应用程序需要32位运行时ZIP,64位应用程序需要64位ZIP。 ## 运行时文件 运行时与包分开发布。下载与 CEF 版本和应用程序位数都匹配的ZIP: | 版本 | Win32 | Win64 | | ---- | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | v49 | [cefRuntime49\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime49_win32.zip) | [cefRuntime49\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime49_win64.zip) | | v109 | [cefRuntime109\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime109_win32.zip) | [cefRuntime109\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime109_win64.zip) | | v145 | [cefRuntime145\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime145_win32.zip) | [cefRuntime145\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime145_win64.zip) | 另请参阅 [CEF Runtime Releases](https://github.com/twinbasic/cef-runtimes/releases/) 获取最新版本。 ### 安装运行时文件 将ZIP解压到: ```text %LocalAppData%\twinBASIC_CEF_Runtime\ ``` 例如,v145 Win64 运行时最终位于: ```text %LocalAppData%\twinBASIC_CEF_Runtime\145_0_7632_160_Win64\ ``` 带版本戳的文件夹必须包含 `libcef.dll` 及其同级运行时文件。 启动时,[**CefBrowser**](/official/Reference/CEF/CefBrowser/) 在此默认位置搜索运行时。如果找不到 `libcef.dll`,[**Error**](/official/Reference/CEF/CefBrowser/#error) 事件将触发,并附带所搜索的确切路径。 ### 覆盖运行时位置 可以通过在 [**Create**](/official/Reference/CEF/CefBrowser/#create) 事件之前或期间赋值 [**EnvironmentOptions.BrowserExecutableFolder**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#browserexecutablefolder) 来选择不同的文件夹——例如便携式并排部署: ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.BrowserExecutableFolder = _ "D:\MyApp\CEF\145_0_7632_160_Win64" End Sub ``` 该文件夹必须包含 `libcef.dll`。 ## WebView2 对等性 以下 [**WebView2**](/official/Reference/WebView2/) 功能尚未在 **CefBrowser** 上暴露,且没有已记录的对应项: * 方法:**OpenTaskManagerWindow**、**AddObject**(用于JavaScript的宿主对象发布)、**AddWebResourceRequestedFilter** 及周围的请求拦截机制。 * 事件:**AcceleratorKeyPressed**、**PermissionRequested**、**WebResourceRequested**、**ProcessFailed**、**ScriptDialogOpening**、**UserContextMenu**、**SuspendCompleted**、**SuspendFailed**、**DownloadStarting**、**NewWindowRequested**。 [**NavigationComplete**](/official/Reference/CEF/CefBrowser/#navigationcomplete) 事件在其签名中有 **IsSuccess** 和 **WebErrorStatus** 参数,但目前返回占位值(`True` 和 `0`)——填充它们的底层 CEF 回调尚未连接。 API 将继续增长;此列表是当前测试版的快照,而非长期限制。 ## 类 * [CefBrowser](/official/Reference/CEF/CefBrowser/) -- 控件:导航、脚本、虚拟主机映射、PDF打印和由匹配的CEF运行时控制的生命周期事件 * [CefEnvironmentOptions](/official/Reference/CEF/CefBrowser/EnvironmentOptions) -- CEF环境的预创建配置(可执行文件夹、用户数据文件夹、日志文件、日志严重级别);通过控件的 **EnvironmentOptions** 属性访问 ## 枚举 * [CefLogSeverity](/official/Reference/CEF/Enumerations/CefLogSeverity) -- CEF调试日志的详细级别阈值;由 [**EnvironmentOptions.LogSeverity**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#logseverity) 使用 * [cefPrintOrientation](/official/Reference/CEF/Enumerations/cefPrintOrientation) -- 传递给 [**PrintToPdf**](/official/Reference/CEF/CefBrowser/#printtopdf) 的页面方向 ## 教程 * [入门指南](/official/Tutorials/CEF/Getting-started) -- 包引用、运行时下载、安装路径 * [自定义 UserDataFolder](/official/Tutorials/CEF/Customize-the-UserDataFolder) -- 重定位运行时的工作文件夹 * [重入性](/official/Tutorials/CEF/Re-entrancy) -- 延迟事件模型和仍需注意的唯一位置([**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun)) * [构建浏览器外壳](/official/Tutorials/CEF/Building-a-browser-shell) -- 后退/前进/刷新/缩放/PDF * [托管本地Web资源](/official/Tutorials/CEF/Hosting-local-web-assets) -- 虚拟主机文件夹映射 * [JavaScript互操作](/official/Tutorials/CEF/JavaScript-interop) -- BASIC与页面之间的消息和脚本调用 * [用twinBASIC驱动Monaco](/official/Tutorials/CEF/Driving-Monaco) -- 综合以上所有内容的案例研究 --- --- url: /en/official/Reference/CEF.md --- # CEF Package The **cefPackage** wraps the [Chromium Embedded Framework](https://chromiumembedded.github.io/cef/) and exposes it as an ordinary twinBASIC control. Drop a [**CefBrowser**](/en/official/Reference/CEF/CefBrowser/) onto a form and a Chromium browser renders web content inside it --- navigate to URLs, run JavaScript, print pages to PDF, and exchange messages with the loaded page. The package is a built-in package shipped with twinBASIC, but the CEF runtime itself is distributed *separately* --- applications must ship the matching runtime ZIP alongside the executable. See [Runtime files](#runtime-files) below. ::: warning The CEF package is currently in **BETA**. Several features available on [**WebView2**](/en/official/Reference/WebView2/) are not yet exposed; see [WebView2 parity](#webview2-parity) below. ::: ## Why CEF instead of WebView2? CEF and [**WebView2**](/en/official/Reference/WebView2/) both wrap a Chromium-based browser inside a twinBASIC control. CEF brings advantages that matter for some applications: * **Cross-platform ready.** CEF runs on Windows, Linux, and macOS. [**WebView2**](/en/official/Reference/WebView2/) is Windows-only. * **Full control over the runtime stack.** The application targets a specific Chromium build and distributes it alongside the software. There is no automatic runtime update outside the application's control, so behavior stays consistent across deployments. * **Deeper runtime integration.** CEF allows hosting twinBASIC code inside the renderer / JavaScript process --- something the more restricted WebView2 object model cannot do. [**WebView2**](/en/official/Reference/WebView2/) is the right fit when targeting only modern Windows and the system-installed Edge runtime is acceptable; **CEF** is preferable when control over the Chromium version or cross-platform readiness matters. ## Supported runtimes Three CEF versions are supported, each with a different Chromium baseline and different OS reach: | Runtime version | Supported OS | Notes | | --------------- | ------------ | ----------------------------------------------- | | **v49** | Windows XP+ | Last Chromium version that supports Windows XP. | | **v109** | Windows 7+ | Last Chromium version that supports Windows 7. | | **v145** | Windows 10+ | Recommended modern runtime. | ::: warning Older Chromium versions should not generally be used for unrestricted internet browsing --- they have unpatched security vulnerabilities. They remain appropriate for tightly controlled environments where the browser loads only trusted local or internal content. ::: The user picks a runtime in two places that must agree: * **At compile time** --- by adding the matching `[COMPILER PACKAGE] twinBASIC - Chromium Embedded Framework Package v<N>` reference to the project. This sets the `CEF_VERSION` conditional-compilation constant (49, 109, or 145) that the package's own sources compile against. [**CefBrowser.CefMajorVersion**](/en/official/Reference/CEF/CefBrowser/#cefmajorversion) returns this value at run time. * **At deploy time** --- by shipping the matching runtime ZIP, extracted into [the discovery folder](#installing-runtime-files) or pointed at via [**EnvironmentOptions.BrowserExecutableFolder**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#browserexecutablefolder). The runtime bitness must match the application bitness --- a 32-bit application needs the 32-bit runtime ZIP, a 64-bit application needs the 64-bit ZIP. ## Runtime files The runtime ships separately from the package. Download the ZIP that matches both the CEF version and the application bitness: | Version | Win32 | Win64 | | ------- | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | v49 | [cefRuntime49\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime49_win32.zip) | [cefRuntime49\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime49_win64.zip) | | v109 | [cefRuntime109\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime109_win32.zip) | [cefRuntime109\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime109_win64.zip) | | v145 | [cefRuntime145\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime145_win32.zip) | [cefRuntime145\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime145_win64.zip) | See also [CEF Runtime Releases](https://github.com/twinbasic/cef-runtimes/releases/) for the latest release. ### Installing runtime files Extract the ZIP into: ```text %LocalAppData%\twinBASIC_CEF_Runtime\ ``` For example, the v145 Win64 runtime ends up at: ```text %LocalAppData%\twinBASIC_CEF_Runtime\145_0_7632_160_Win64\ ``` The version-stamped folder must contain `libcef.dll` and its sibling runtime files. At launch, [**CefBrowser**](/en/official/Reference/CEF/CefBrowser/) searches for the runtime in this default location. If `libcef.dll` cannot be found, the [**Error**](/en/official/Reference/CEF/CefBrowser/#error) event fires with the exact path that was searched. ### Overriding the runtime location A different folder --- for example a portable side-by-side deployment --- is selected by assigning [**EnvironmentOptions.BrowserExecutableFolder**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#browserexecutablefolder) before or during the [**Create**](/en/official/Reference/CEF/CefBrowser/#create) event: ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.BrowserExecutableFolder = _ "D:\MyApp\CEF\145_0_7632_160_Win64" End Sub ``` The folder must contain `libcef.dll`. ## WebView2 parity These [**WebView2**](/en/official/Reference/WebView2/) features are not yet exposed on **CefBrowser** and have no documented counterpart: * Methods: **OpenTaskManagerWindow**, **AddObject** (host-object publication for JavaScript), **AddWebResourceRequestedFilter** and the surrounding request-interception machinery. * Events: **AcceleratorKeyPressed**, **PermissionRequested**, **WebResourceRequested**, **ProcessFailed**, **ScriptDialogOpening**, **UserContextMenu**, **SuspendCompleted**, **SuspendFailed**, **DownloadStarting**, **NewWindowRequested**. The [**NavigationComplete**](/en/official/Reference/CEF/CefBrowser/#navigationcomplete) event has **IsSuccess** and **WebErrorStatus** parameters in its signature but currently returns placeholder values (`True` and `0`) --- the underlying CEF callbacks that would populate them have not yet been connected. The API will continue to grow; this list is a snapshot of the current beta, not a long-term limitation. ## Classes * [CefBrowser](/en/official/Reference/CEF/CefBrowser/) -- the control: navigation, scripting, virtual-host mapping, PDF printing, and lifecycle events controlled by the matching CEF runtime * [CefEnvironmentOptions](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions) -- pre-creation configuration for the CEF environment (executable folder, user-data folder, log file, log severity); reached via the control's **EnvironmentOptions** property ## Enumerations * [CefLogSeverity](/en/official/Reference/CEF/Enumerations/CefLogSeverity) -- the verbosity threshold for the CEF debug log; used by [**EnvironmentOptions.LogSeverity**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#logseverity) * [cefPrintOrientation](/en/official/Reference/CEF/Enumerations/cefPrintOrientation) -- page orientation passed to [**PrintToPdf**](/en/official/Reference/CEF/CefBrowser/#printtopdf) ## Tutorials * [Getting started](/en/official/Tutorials/CEF/Getting-started) -- package reference, runtime download, install path * [Customize the UserDataFolder](/en/official/Tutorials/CEF/Customize-the-UserDataFolder) -- relocating the runtime's working folder * [Re-entrancy](/en/official/Tutorials/CEF/Re-entrancy) -- the deferred-event model and the one place ([**JsRun**](/en/official/Reference/CEF/CefBrowser/#jsrun)) that still requires attention * [Building a browser shell](/en/official/Tutorials/CEF/Building-a-browser-shell) -- back / forward / reload / zoom / PDF * [Hosting local web assets](/en/official/Tutorials/CEF/Hosting-local-web-assets) -- virtual-host folder mappings * [JavaScript interop](/en/official/Tutorials/CEF/JavaScript-interop) -- messages and scripted calls between BASIC and the page * [Driving Monaco from twinBASIC](/en/official/Tutorials/CEF/Driving-Monaco) -- case study combining everything above --- --- url: /en/official/Reference/CEF/CefBrowser.md --- # CefBrowser class A **CefBrowser** is a twinBASIC control that hosts the Chromium Embedded Framework --- drop one onto a [**Form**](/en/official/Reference/VB/Form/) and Chromium renders web content inside its rectangle. Application code can navigate to URLs, run JavaScript, exchange messages with the loaded page, register virtual-host folders, and print the document to PDF. The control spawns a separate browser process the first time it is used in a session and communicates with it across an IPC channel; many properties and methods raise *"CefBrowser control is not ready"* (run-time error 5) when called before the [**Ready**](#ready) event has fired. ```vb Private Sub Form_Load() CefBrowser1.Navigate "https://www.twinbasic.com" End Sub Private Sub CefBrowser1_Ready() Debug.Print "CEF ready: runtime v" & CefBrowser1.CefMajorVersion End Sub Private Sub CefBrowser1_NavigationComplete( _ ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) Debug.Print "Navigated to: " & CefBrowser1.DocumentURL End Sub ``` The control inherits the rect-dockable members (size, layout, **Anchors**, **Dock**) from `BaseControlRectDockable`. It does *not* inherit a focusable layer, so the keyboard / mouse / focus events available on [**WebView2**](/en/official/Reference/WebView2/WebView2/) are not part of its API --- keystrokes go straight into the page once Chromium has focus. ## Lifecycle A **CefBrowser** control progresses through three distinct phases, each triggered by an asynchronous step in the CEF runtime: | Event | When | |--------------------------------|-------------------------------------------------------------------------------------------------------------------| | [**Create**](#create) | After the container window exists, before the CEF runtime is launched. Last chance to set [**EnvironmentOptions**](#environmentoptions). | | [**Error**](#error) | The runtime could not be launched --- typically because `libcef.dll` is missing or the user-data folder is locked. | | [**Ready**](#ready) | The browser process is live and IPC has connected. The control is now fully functional. | Calling navigation, scripting, or setting accessors before [**Ready**](#ready) raises run-time error 5 with the message *"CefBrowser control is not ready."* Once **Ready** fires, the control auto-navigates to the [**DocumentURL**](#documenturl) field if it has a non-empty value (the design-time default is `https://www.twinbasic.com`). The first **CefBrowser** to initialise in a process launches the shared browser helper executable; subsequent **CefBrowser** instances share that helper. Closing the last **CefBrowser** does not terminate the helper --- it lingers for the life of the host process so that a future control can attach to it without re-launching. ## Deferred startup By default the control launches the browser helper as soon as the form is loaded (the `WS_VISIBLE` style is set on the host window and the first resize event triggers the helper). Set [**CreateInitialized**](#createinitialized) to **False** before the form loads, then call [**Initialize**](#initialize) when the browser should start --- useful when several **CefBrowser** controls live on tabs and the cost of launching the helper should be deferred until the tab is shown. ## JavaScript interop The control offers three families of BASIC ↔ JavaScript bridges: * **Posting messages** --- [**PostWebMessage**](#postwebmessage) sends a value to the page where it arrives via `window.chrome.webview.addEventListener('message', …)`. The page replies with `window.chrome.webview.postMessage(…)`, which fires the [**JsMessage**](#jsmessage) event. * **Executing script** --- [**JsRun**](#jsrun) calls a named JavaScript function and waits for the result, [**JsRunAsync**](#jsrunasync) calls one and fires [**JsAsyncResult**](#jsasyncresult) when the result arrives, and [**ExecuteScript**](#executescript) fires-and-forgets a snippet without awaiting a result. Synchronous [**JsRun**](#jsrun) blocks the BASIC thread until the renderer replies --- which means that re-entrancy from the page (a JavaScript handler that posts back into BASIC during the call) can cause a UI freeze. Use [**JsRunAsync**](#jsrunasync) whenever the call is non-trivial. ## Mapping virtual hostnames [**SetVirtualHostNameToFolderMapping**](#setvirtualhostnametofoldermapping) installs a virtual hostname that serves files from a local folder --- so the page can `fetch('https://my.app/index.html')` instead of `file:///...` (avoiding the `file://` origin's CORS restrictions). [**ClearVirtualHostNameToFolderMapping**](#clearvirtualhostnametofoldermapping) removes a mapping. ## Properties The control inherits the standard rect-dockable members from `BaseControlRectDockable` --- size, position, **Anchors**, **Dock**, **Container**, the design-time **Name** / **Index** / **Tag**. ### Anchors The container-edge anchors that control automatic resizing when the parent **Form** is resized. Inherited from `BaseControlRectDockable`. ### CanGoBack Whether the browsing history has an entry behind the current document. **Boolean**. Read-only. Available after [**Ready**](#ready). ### CanGoForward Whether the browsing history has an entry ahead of the current document. **Boolean**. Read-only. Available after [**Ready**](#ready). ### CefMajorVersion The CEF runtime major-version number selected at compile time (`49`, `109`, or `145`). **Long**. Read-only. Resolves from the `CEF_VERSION` conditional-compilation argument on the compiler-package reference --- see [Supported runtimes](/en/official/Reference/CEF/#supported-runtimes). ### Container The parent **Form** / **Frame** / **PictureBox** / **UserControl** that hosts this control. **Object**. Inherited. ### ControlType Always **vbCefBrowser** ([**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants)). Read-only. Inherited. ### CreateInitialized Whether the browser helper is launched automatically when the form first lays the control out. **Boolean**. Default: **True**. Set to **False** in code (or in the property sheet) to defer the launch until [**Initialize**](#initialize) is called. ### DocumentTitle The current document's `<title>` text. **String**. Read-only. Updated each time the page changes its title --- the [**DocumentTitleChanged**](#documenttitlechanged) event fires on every update. ### DocumentURL The current document's URL. **String**. Reading returns the live URL after every navigation; assigning is equivalent to calling [**Navigate**](#navigate). The design-time default is `https://www.twinbasic.com`, used as the auto-navigation target once [**Ready**](#ready) fires. ### Dock How the control docks against its container. A member of [**DockModeConstants**](/en/official/Reference/VBRUN/Constants/DockModeConstants). Inherited. ### EnvironmentOptions The [**CefEnvironmentOptions**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions) object that configures the runtime --- executable folder, user-data folder, log file, log severity. The control auto-creates one on initialization; assign to its fields before or during the [**Create**](#create) event for them to take effect. ### Height The control's height. **Single**. Inherited. ### hWnd The Win32 window handle of the *container* window that hosts the CEF surface --- not the HWND of the Chromium browser tab itself, which lives in a separate process. **LongPtr**. Read-only. ### Index The control-array index when the control is part of an array. **Long**. Read-only. Inherited. ### Left The control's x-position inside its container. **Single**. Inherited. ### Name The design-time name of the control. **String**. Read-only at run time. Inherited. ### Parent The **Form** (or other container) that hosts this control. **Object**. Read-only. ### Tag A user-defined string stored on the control. **String**. Inherited. ### Top The control's y-position inside its container. **Single**. Inherited. ### UserAgent The `User-Agent` string Chromium sends with HTTP requests. **String**. Read/write. The design-time default is empty, in which case Chromium uses its built-in user-agent string. Assigning at run time takes effect immediately. ### Visible Whether the control is visible. **Boolean**, default **True**. ### Width The control's width. **Single**. Inherited. ### ZoomFactor The overall page zoom factor, where `1.0` is 100%. **Double**. Default: `1.0` (design-time default; reads as `0.0` until the browser is [**Ready**](#ready)). ::: info Because the value reads as `0.0` until the browser is ready, arithmetic that multiplies the current value silently starts from zero unless the host clamps it to `1` first: ```vb If CefBrowser1.ZoomFactor = 0 Then CefBrowser1.ZoomFactor = 1 CefBrowser1.ZoomFactor *= 1.1 ' 110% on first click, 121% on second, … ``` ::: ## Methods ### ClearVirtualHostNameToFolderMapping Removes a virtual hostname → local-folder mapping previously installed by [**SetVirtualHostNameToFolderMapping**](#setvirtualhostnametofoldermapping). Syntax: *object*.**ClearVirtualHostNameToFolderMapping** *hostName* *hostName* : *required* A **String** matching the hostname passed to **SetVirtualHostNameToFolderMapping**. ### ExecuteScript Evaluates JavaScript in the page without waiting for it to finish and without returning its result. Use [**JsRun**](#jsrun) or [**JsRunAsync**](#jsrunasync) when the return value is needed. Syntax: *object*.**ExecuteScript** *jsCode* *jsCode* : *required* A **String** of JavaScript to evaluate in the page's global scope. ### GoBack Navigates one entry back in the browsing history. Silently does nothing when [**CanGoBack**](#cangoback) is **False**. Syntax: *object*.**GoBack** ### GoForward Navigates one entry forward in the browsing history. Silently does nothing when [**CanGoForward**](#cangoforward) is **False**. Syntax: *object*.**GoForward** ### Initialize Launches the browser helper process explicitly. Only needed when [**CreateInitialized**](#createinitialized) is **False**; otherwise the helper starts automatically on the first form-layout pass. Syntax: *object*.**Initialize** A second call after the helper is already running is a no-op. ### JsRun Calls a named JavaScript function with the given arguments and returns the result synchronously. Blocks the BASIC thread until the renderer replies. Syntax: *object*.**JsRun** ( *FuncName*, \[ *args* ] ) **As Variant** *FuncName* : *required* A **String** naming the JavaScript function --- e.g. `"document.querySelector"`. *args* : *optional* Any number of **Variant** arguments. Each is JSON-encoded before being passed to the function. ```vb ' Calls the page-side function `multiplyTheseNumbers(a, b)` and waits for the result. Dim product As Long = CefBrowser1.JsRun("multiplyTheseNumbers", 5, 6) Debug.Print product ' 30 ``` ::: warning A page-side handler that posts back into BASIC during the call can deadlock the UI. Prefer [**JsRunAsync**](#jsrunasync) for non-trivial calls. See the [Re-entrancy tutorial](/en/official/Tutorials/CEF/Re-entrancy) for the full discussion. ::: ### JsRunAsync Calls a named JavaScript function asynchronously and returns immediately. When the result arrives, [**JsAsyncResult**](#jsasyncresult) fires with the result and an error string. Syntax: *object*.**JsRunAsync** *FuncName*, \[ *args* ] *FuncName* : *required* A **String** naming the JavaScript function. *args* : *optional* Any number of **Variant** arguments, JSON-encoded as in [**JsRun**](#jsrun). ```vb Private Sub btnRun_Click() CefBrowser1.JsRunAsync "multiplyTheseNumbers", 5, 6 End Sub Private Sub CefBrowser1_JsAsyncResult( _ ByVal Result As Variant, Token As LongLong, ErrString As String) If LenB(ErrString) = 0 Then Debug.Print "Async result: "; Result Else Debug.Print "Async error: "; ErrString End If End Sub ``` If **JsRunAsync** is called before the renderer IPC has connected, the call is queued and dispatched once the connection is established. ### Move Repositions and resizes the control in a single call. Inherited. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] ### Navigate Loads a URL into the browser. Fires [**NavigationStarting**](#navigationstarting) and then [**NavigationComplete**](#navigationcomplete). The URI must include the protocol prefix (`http://`, `https://`, `file://`, …) --- there is no automatic prefix insertion. Syntax: *object*.**Navigate** *uri* *uri* : *required* A **String** with the full URI to load. ### NavigateToString Loads the given HTML string as if it had been served from `about:blank`. Fires [**NavigationComplete**](#navigationcomplete) when the document is fully loaded. Syntax: *object*.**NavigateToString** *html* *html* : *required* A **String** containing a full HTML document. ### OpenDevToolsWindow Opens the Chromium DevTools window for the currently loaded page in a separate top-level window. Syntax: *object*.**OpenDevToolsWindow** ### PostWebMessage Sends a value to the page; it arrives via `window.chrome.webview.addEventListener('message', …)`. The page can reply with `window.chrome.webview.postMessage(…)`, which fires the [**JsMessage**](#jsmessage) event. Syntax: *object*.**PostWebMessage** *Message* *Message* : *required* A **Variant** containing the value to send. Strings, numbers, **Boolean**, **Null**, and **Empty** are JSON-encoded for the page; objects and arrays are not currently supported. If **PostWebMessage** is called before the renderer IPC has connected, the call is queued and dispatched once the connection is established. ### PrintToPdf Writes the current document to a PDF file. Fires [**PrintToPdfCompleted**](#printtopdfcompleted) on success or [**PrintToPdfFailed**](#printtopdffailed) on failure. Syntax: *object*.**PrintToPdf** *outputPath* \[, *Orientation* \[, *ScaleFactor* \[, *PageWidth* \[, *PageHeight* \[, *MarginTop* \[, *MarginBottom* \[, *MarginLeft* \[, *MarginRight* \[, *ShouldPrintBackgrounds* \[, *ShouldPrintSelectionOnly* \[, *ShouldPrintHeaderAndFooter* \[, *HeaderTitle* \[, *FooterUri* ] ] ] ] ] ] ] ] ] ] ] ] ] *outputPath* : *required* A **String** with the destination path. Must be a writable absolute file path. An existing file is overwritten. *Orientation* : *optional* A member of [**cefPrintOrientation**](/en/official/Reference/CEF/Enumerations/cefPrintOrientation). Default: **cefPrintPortrait**. *ScaleFactor* : *optional* A **Variant** containing the print scaling factor (e.g. `1.0` for 100%). When omitted, the CEF runtime's default is used. *PageWidth* : *optional* A **Variant** with the page width in microns. When omitted, the CEF runtime's default is used. *PageHeight* : *optional* A **Variant** with the page height in microns. When omitted, the CEF runtime's default is used. *MarginTop* / *MarginBottom* / *MarginLeft* / *MarginRight* : *optional* **Variant** values for the page margins in microns. When omitted, the runtime's defaults are used. *ShouldPrintBackgrounds* : *optional* A **Boolean** controlling whether CSS background colors and images are included in the output. Default: **False**. *ShouldPrintSelectionOnly* : *optional* A **Boolean** that limits the output to the current selection. Default: **False**. *ShouldPrintHeaderAndFooter* : *optional* A **Boolean** controlling whether the page header (title) and footer (URL) are rendered. Default: **True**. *HeaderTitle* : *optional* A **Variant** **String**. When provided, overrides the document title in the header. Otherwise the document's `<title>` is used. *FooterUri* : *optional* A **Variant** **String**. When provided, overrides the URL printed in the footer. Otherwise the live document URL is used. ```vb Private Sub btnPDF_Click() Dim outputPath As String outputPath = Environ$("USERPROFILE") & "\Documents\cefDemo.pdf" CefBrowser1.PrintToPdf outputPath End Sub Private Sub CefBrowser1_PrintToPdfCompleted() MsgBox "PDF saved.", vbInformation End Sub ``` ### Reload Reloads the current document, equivalent to pressing **F5** in the browser. Syntax: *object*.**Reload** ### SetVirtualHostNameToFolderMapping Installs a virtual hostname that serves files from a local folder, so the page can reference local content over an `https://` origin instead of `file://`. Syntax: *object*.**SetVirtualHostNameToFolderMapping** *hostName*, *folderPath* *hostName* : *required* A **String** with the hostname to install (e.g. `"my.app"`). *folderPath* : *required* A **String** with the absolute path of the folder whose contents should be served under that hostname. Must end with a trailing path separator. ```vb Private Sub CefBrowser1_Ready() CefBrowser1.SetVirtualHostNameToFolderMapping _ "my.app", App.Path & "\web\" CefBrowser1.Navigate "https://my.app/index.html" End Sub ``` ## Events ### Create Raised after the container window exists but before the CEF runtime is launched. The host's last chance to populate [**EnvironmentOptions**](#environmentoptions). Syntax: *object*\_**Create**( ) ### DocumentTitleChanged Raised when the document changes its title --- typically right after a navigation, but also when client-side JavaScript writes to `document.title`. Read [**DocumentTitle**](#documenttitle) for the new value. Syntax: *object*\_**DocumentTitleChanged**( ) ### DOMContentLoaded Raised when the page reaches the `DOMContentLoaded` lifecycle event --- the DOM tree is built and JavaScript can safely traverse it, but external resources may still be loading. Syntax: *object*\_**DOMContentLoaded**( ) ### Error Raised when the CEF runtime fails to launch --- most commonly because `libcef.dll` was not found at the configured location, or because the user-data folder is locked by another process. Syntax: *object*\_**Error**( *code* **As Long**, *msg* **As String** ) ```vb Private Sub CefBrowser1_Error(ByVal code As Long, ByVal msg As String) MsgBox "CEF error " & Hex$(code) & ": " & msg, vbExclamation, "CEF" End Sub ``` ### JsAsyncResult Raised when an earlier [**JsRunAsync**](#jsrunasync) call returns. *ErrString* is a description of any runtime error, or an empty string on success. Syntax: *object*\_**JsAsyncResult**( *Result* **As Variant**, *Token* **As LongLong**, *ErrString* **As String** ) ### JsMessage Raised when JavaScript on the page calls `window.chrome.webview.postMessage(value)`. Syntax: *object*\_**JsMessage**( *Message* **As Variant** ) ```vb Private Sub CefBrowser1_JsMessage(ByVal Message As Variant) Debug.Print "From page: "; Message CefBrowser1.PostWebMessage "Hello from BASIC" End Sub ``` ### NavigationComplete Raised after a navigation initiated by [**Navigate**](#navigate), [**NavigateToString**](#navigatetostring), or by user interaction in the page has finished. Syntax: *object*\_**NavigationComplete**( *IsSuccess* **As Boolean**, *WebErrorStatus* **As Long** ) ::: info *IsSuccess* and *WebErrorStatus* are part of the event signature but currently return placeholder values (`True` and `0`) --- the underlying CEF callbacks that would populate them have not yet been connected. Use the document state ([**DocumentURL**](#documenturl), [**CanGoBack**](#cangoback)) to determine the outcome. ::: ### NavigationStarting Raised before a navigation begins. Set *Cancel* to **True** to abort the navigation; leave it **False** to let it proceed. Syntax: *object*\_**NavigationStarting**( *Uri* **As String**, *IsUserInitiated* **As Boolean**, *IsRedirected* **As Boolean**, *RequestHeaders* **As Object**, *Cancel* **As Boolean** ) *Uri* : The destination URI. *IsUserInitiated* : **True** when the navigation was triggered by a user gesture (click, **Enter** in the address bar); **False** when it was script-initiated. *IsRedirected* : **True** when this navigation is a server-side redirect from a previous one. *RequestHeaders* : **Object**. Currently typed as **Object** (the underlying `CefRequestHeaders` collection is a placeholder reserved for future use). *Cancel* : Set to **True** to abort the navigation. ```vb Private Sub CefBrowser1_NavigationStarting( _ ByVal Uri As String, ByVal IsUserInitiated As Boolean, _ ByVal IsRedirected As Boolean, ByVal RequestHeaders As Object, _ Cancel As Boolean) If InStr(Uri, "ads.example.com") > 0 Then Cancel = True End Sub ``` ### PrintToPdfCompleted Raised when an earlier [**PrintToPdf**](#printtopdf) call finishes writing the PDF. Syntax: *object*\_**PrintToPdfCompleted**( ) ### PrintToPdfFailed Raised when an earlier [**PrintToPdf**](#printtopdf) call fails --- e.g. because the output path was not writable. Syntax: *object*\_**PrintToPdfFailed**( ) ### Ready Raised after the browser helper process has launched, its IPC channel is connected, and the control is ready to accept navigation and scripting commands. If [**DocumentURL**](#documenturl) has a non-empty value when **Ready** fires (the design-time default is `https://www.twinbasic.com`), the control auto-navigates to it. Syntax: *object*\_**Ready**( ) ### SourceChanged Raised when [**DocumentURL**](#documenturl) has been updated --- typically after a navigation. Used to keep an address-bar control in sync with the browser. Syntax: *object*\_**SourceChanged**( *IsNewDocument* **As Boolean** ) *IsNewDocument* : **True** when the change reflects a fresh document load (rather than a same-document fragment / `history.pushState` update). ```vb Private Sub CefBrowser1_SourceChanged(ByVal IsNewDocument As Boolean) AddressBar.Text = CefBrowser1.DocumentURL End Sub ``` ## See Also * [CefEnvironmentOptions](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions) -- pre-creation configuration exposed through [**EnvironmentOptions**](#environmentoptions) * [CefLogSeverity](/en/official/Reference/CEF/Enumerations/CefLogSeverity) -- the verbosity threshold for the CEF debug log * [cefPrintOrientation](/en/official/Reference/CEF/Enumerations/cefPrintOrientation) -- page orientation passed to [**PrintToPdf**](#printtopdf) * [WebView2](/en/official/Reference/WebView2/WebView2/) -- the WebView2-runtime counterpart with a larger feature set * [WebView2 parity](/en/official/Reference/CEF/#webview2-parity) -- features available on **WebView2** that are not yet exposed on **CefBrowser** * [ControlTypeConstants](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) -- where **vbCefBrowser** lives --- --- url: /zh/official/Reference/CEF/CefBrowser.md --- # CefBrowser 类 **CefBrowser** 是一个托管 Chromium Embedded Framework 的 twinBASIC 控件——将一个拖放到 [**Form**](/official/Reference/VB/Form/) 上,Chromium 即可在其矩形内渲染Web内容。应用程序代码可以导航到URL、运行JavaScript、与已加载的页面交换消息、注册虚拟主机文件夹,以及将文档打印为PDF。 该控件在会话中首次使用时会生成一个单独的浏览器进程,并通过IPC通道与其通信;在 [**Ready**](#ready) 事件触发之前调用许多属性和方法会引发 *"CefBrowser control is not ready"*(运行时错误5)。 ```vb Private Sub Form_Load() CefBrowser1.Navigate "https://www.twinbasic.com" End Sub Private Sub CefBrowser1_Ready() Debug.Print "CEF ready: runtime v" & CefBrowser1.CefMajorVersion End Sub Private Sub CefBrowser1_NavigationComplete( _ ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) Debug.Print "Navigated to: " & CefBrowser1.DocumentURL End Sub ``` 该控件从 `BaseControlRectDockable` 继承了矩形可停靠成员(大小、布局、**Anchors**、**Dock**)。它*不*继承可聚焦层,因此 [**WebView2**](/official/Reference/WebView2/WebView2/) 上可用的键盘/鼠标/焦点事件不属于其API——一旦Chromium获得焦点,按键就直接进入页面。 ## 生命周期 **CefBrowser** 控件经历三个不同的阶段,每个阶段由CEF运行时中的异步步骤触发: | 事件 | 何时触发 | |--------------------------------|-------------------------------------------------------------------------------------------------------------------| | [**Create**](#create) | 容器窗口已创建之后,CEF运行时启动之前。设置 [**EnvironmentOptions**](#environmentoptions) 的最后机会。 | | [**Error**](#error) | 运行时无法启动——通常是因为 `libcef.dll` 缺失或用户数据文件夹被锁定。 | | [**Ready**](#ready) | 浏览器进程已运行且IPC已连接。控件现在完全可用。 | 在 [**Ready**](#ready) 之前调用导航、脚本或设置访问器会引发运行时错误5,消息为 *"CefBrowser control is not ready."*。一旦 **Ready** 触发,如果 [**DocumentURL**](#documenturl) 字段有非空值(设计时默认为 `https://www.twinbasic.com`),控件会自动导航到该地址。 进程中第一个初始化的 **CefBrowser** 启动共享的浏览器辅助可执行文件;后续的 **CefBrowser** 实例共享该辅助程序。关闭最后一个 **CefBrowser** 不会终止辅助程序——它会在宿主进程的整个生命周期内驻留,以便将来的控件可以附加到它而无需重新启动。 ## 延迟启动 默认情况下,控件在窗体加载后立即启动浏览器辅助程序(在宿主窗口上设置 `WS_VISIBLE` 样式,第一次调整大小事件触发辅助程序)。在窗体加载之前将 [**CreateInitialized**](#createinitialized) 设置为 **False**,然后在浏览器应启动时调用 [**Initialize**](#initialize)——这在多个 **CefBrowser** 控件位于选项卡上且应将启动辅助程序的开销推迟到选项卡显示时很有用。 ## JavaScript互操作 控件提供三个系列的BASIC ↔ JavaScript桥接: * **发布消息**——[**PostWebMessage**](#postwebmessage) 向页面发送值,通过 `window.chrome.webview.addEventListener('message', …)` 到达。页面通过 `window.chrome.webview.postMessage(…)` 回复,触发 [**JsMessage**](#jsmessage) 事件。 * **执行脚本**——[**JsRun**](#jsrun) 调用命名的JavaScript函数并等待结果,[**JsRunAsync**](#jsrunasync) 调用一个并在结果到达时触发 [**JsAsyncResult**](#jsasyncresult),[**ExecuteScript**](#executescript) 即发即忘地执行代码片段而不等待结果。 同步的 [**JsRun**](#jsrun) 会阻塞BASIC线程直到渲染器回复——这意味着页面的重入(在调用期间发回BASIC的JavaScript处理程序)可能导致UI冻结。只要调用不是简单的,请使用 [**JsRunAsync**](#jsrunasync)。 ## 映射虚拟主机名 [**SetVirtualHostNameToFolderMapping**](#setvirtualhostnametofoldermapping) 安装一个虚拟主机名,该主机名从本地文件夹提供文件——因此页面可以 `fetch('https://my.app/index.html')` 而不是 `file:///...`(避免 `file://` 来源的CORS限制)。[**ClearVirtualHostNameToFolderMapping**](#clearvirtualhostnametofoldermapping) 移除映射。 ## 属性 该控件从 `BaseControlRectDockable` 继承标准的矩形可停靠成员——大小、位置、**Anchors**、**Dock**、**Container**、设计时的 **Name** / **Index** / **Tag**。 ### Anchors 控制父 **Form** 调整大小时自动调整大小的容器边缘锚点。从 `BaseControlRectDockable` 继承。 ### CanGoBack 浏览历史中当前文档之后是否有条目。**Boolean**。只读。在 [**Ready**](#ready) 后可用。 ### CanGoForward 浏览历史中当前文档之前是否有条目。**Boolean**。只读。在 [**Ready**](#ready) 后可用。 ### CefMajorVersion 编译时选择的CEF运行时主版本号(`49`、`109` 或 `145`)。**Long**。只读。从编译器包引用上的 `CEF_VERSION` 条件编译参数解析——参见[支持的运行时](/official/Reference/CEF/#supported-runtimes)。 ### Container 承载此控件的父 **Form** / **Frame** / **PictureBox** / **UserControl**。**Object**。继承。 ### ControlType 始终为 **vbCefBrowser**([**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants))。只读。继承。 ### CreateInitialized 窗体首次布局控件时是否自动启动浏览器辅助程序。**Boolean**。默认:**True**。在代码中(或在属性表中)设置为 **False** 以推迟启动,直到调用 [**Initialize**](#initialize)。 ### DocumentTitle 当前文档的 `<title>` 文本。**String**。只读。每次页面更改标题时更新——[**DocumentTitleChanged**](#documenttitlechanged) 事件在每次更新时触发。 ### DocumentURL 当前文档的URL。**String**。读取时在每次导航后返回实时URL;赋值等效于调用 [**Navigate**](#navigate)。设计时默认为 `https://www.twinbasic.com`,作为 [**Ready**](#ready) 触发后的自动导航目标。 ### Dock 控件如何停靠到其容器。[**DockModeConstants**](/official/Reference/VBRUN/Constants/DockModeConstants) 的成员。继承。 ### EnvironmentOptions 配置运行时的 [**CefEnvironmentOptions**](/official/Reference/CEF/CefBrowser/EnvironmentOptions) 对象——可执行文件夹、用户数据文件夹、日志文件、日志严重级别。控件在初始化时自动创建一个;在 [**Create**](#create) 事件之前或期间赋值给其字段才能生效。 ### Height 控件的高度。**Single**。继承。 ### hWnd 承载CEF表面的*容器*窗口的Win32窗口句柄——不是Chromium浏览器选项卡本身的HWND,后者位于单独的进程中。**LongPtr**。只读。 ### Index 控件是数组一部分时的控件数组索引。**Long**。只读。继承。 ### Left 控件在其容器内的x位置。**Single**。继承。 ### Name 控件的设计时名称。**String**。运行时只读。继承。 ### Parent 承载此控件的 **Form**(或其他容器)。**Object**。只读。 ### Tag 存储在控件上的用户定义字符串。**String**。继承。 ### Top 控件在其容器内的y位置。**Single**。继承。 ### UserAgent Chromium 在HTTP请求中发送的 `User-Agent` 字符串。**String**。读/写。设计时默认为空,此时Chromium使用其内置的user-agent字符串。运行时赋值立即生效。 ### Visible 控件是否可见。**Boolean**,默认 **True**。 ### Width 控件的宽度。**Single**。继承。 ### ZoomFactor 整体页面缩放因子,其中 `1.0` 为100%。**Double**。默认:`1.0`(设计时默认;在浏览器 [**Ready**](#ready) 之前读取为 `0.0`)。 ::: info 由于该值在浏览器就绪之前读取为 `0.0`,如果不先将宿主值钳位到 `1`,乘以当前值的算术运算会静默从零开始: ```vb If CefBrowser1.ZoomFactor = 0 Then CefBrowser1.ZoomFactor = 1 CefBrowser1.ZoomFactor *= 1.1 ' 首次点击110%,第二次121%,… ``` ::: ## 方法 ### ClearVirtualHostNameToFolderMapping 移除之前由 [**SetVirtualHostNameToFolderMapping**](#setvirtualhostnametofoldermapping) 安装的虚拟主机名→本地文件夹映射。 语法:*对象*.**ClearVirtualHostNameToFolderMapping** *hostName* *hostName* : *必需* 与传递给 **SetVirtualHostNameToFolderMapping** 的主机名匹配的 **String**。 ### ExecuteScript 在页面中评估JavaScript,不等待其完成也不返回其结果。当需要返回值时使用 [**JsRun**](#jsrun) 或 [**JsRunAsync**](#jsrunasync)。 语法:*对象*.**ExecuteScript** *jsCode* *jsCode* : *必需* 要在页面全局作用域中评估的JavaScript **String**。 ### GoBack 在浏览历史中后退一个条目。当 [**CanGoBack**](#cangoback) 为 **False** 时静默无操作。 语法:*对象*.**GoBack** ### GoForward 在浏览历史中前进一个条目。当 [**CanGoForward**](#cangoforward) 为 **False** 时静默无操作。 语法:*对象*.**GoForward** ### Initialize 显式启动浏览器辅助程序进程。仅当 [**CreateInitialized**](#createinitialized) 为 **False** 时需要;否则辅助程序在第一次窗体布局时自动启动。 语法:*对象*.**Initialize** 辅助程序已运行后的第二次调用为无操作。 ### JsRun 以给定参数调用命名的JavaScript函数并同步返回结果。阻塞BASIC线程直到渲染器回复。 语法:*对象*.**JsRun** ( *FuncName*, \[ *args* ] ) **As Variant** *FuncName* : *必需* 命名JavaScript函数的 **String**——例如 `"document.querySelector"`。 *args* : *可选* 任意数量的 **Variant** 参数。每个参数在传递给函数之前进行JSON编码。 ```vb ' 调用页面端函数 `multiplyTheseNumbers(a, b)` 并等待结果。 Dim product As Long = CefBrowser1.JsRun("multiplyTheseNumbers", 5, 6) Debug.Print product ' 30 ``` ::: warning 页面端处理程序在调用期间发回BASIC可能导致UI死锁。对于非简单调用,优先使用 [**JsRunAsync**](#jsrunasync)。完整讨论请参阅[重入性教程](/official/Tutorials/CEF/Re-entrancy)。 ::: ### JsRunAsync 异步调用命名的JavaScript函数并立即返回。当结果到达时,[**JsAsyncResult**](#jsasyncresult) 触发并附带结果和错误字符串。 语法:*对象*.**JsRunAsync** *FuncName*, \[ *args* ] *FuncName* : *必需* 命名JavaScript函数的 **String**。 *args* : *可选* 任意数量的 **Variant** 参数,按 [**JsRun**](#jsrun) 方式进行JSON编码。 ```vb Private Sub btnRun_Click() CefBrowser1.JsRunAsync "multiplyTheseNumbers", 5, 6 End Sub Private Sub CefBrowser1_JsAsyncResult( _ ByVal Result As Variant, Token As LongLong, ErrString As String) If LenB(ErrString) = 0 Then Debug.Print "Async result: "; Result Else Debug.Print "Async error: "; ErrString End If End Sub ``` 如果在渲染器IPC连接之前调用 **JsRunAsync**,调用将被排队并在连接建立后分发。 ### Move 在单次调用中重新定位和调整控件大小。继承。 语法:*对象*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] ### Navigate 将URL加载到浏览器中。触发 [**NavigationStarting**](#navigationstarting) 然后触发 [**NavigationComplete**](#navigationcomplete)。URI必须包含协议前缀(`http://`、`https://`、`file://`、…)——没有自动前缀插入。 语法:*对象*.**Navigate** *uri* *uri* : *必需* 包含要加载的完整URI的 **String**。 ### NavigateToString 将给定的HTML字符串加载为从 `about:blank` 提供的内容。文档完全加载时触发 [**NavigationComplete**](#navigationcomplete)。 语法:*对象*.**NavigateToString** *html* *html* : *必需* 包含完整HTML文档的 **String**。 ### OpenDevToolsWindow 在单独的顶级窗口中打开当前已加载页面的Chromium DevTools窗口。 语法:*对象*.**OpenDevToolsWindow** ### PostWebMessage 向页面发送值;通过 `window.chrome.webview.addEventListener('message', …)` 到达。页面可以通过 `window.chrome.webview.postMessage(…)` 回复,触发 [**JsMessage**](#jsmessage) 事件。 语法:*对象*.**PostWebMessage** *Message* *Message* : *必需* 包含要发送的值的 **Variant**。字符串、数字、**Boolean**、**Null** 和 **Empty** 会被JSON编码后发送给页面;对象和数组目前不支持。 如果在渲染器IPC连接之前调用 **PostWebMessage**,调用将被排队并在连接建立后分发。 ### PrintToPdf 将当前文档写入PDF文件。成功时触发 [**PrintToPdfCompleted**](#printtopdfcompleted),失败时触发 [**PrintToPdfFailed**](#printtopdffailed)。 语法:*对象*.**PrintToPdf** *outputPath* \[, *Orientation* \[, *ScaleFactor* \[, *PageWidth* \[, *PageHeight* \[, *MarginTop* \[, *MarginBottom* \[, *MarginLeft* \[, *MarginRight* \[, *ShouldPrintBackgrounds* \[, *ShouldPrintSelectionOnly* \[, *ShouldPrintHeaderAndFooter* \[, *HeaderTitle* \[, *FooterUri* ] ] ] ] ] ] ] ] ] ] ] ] ] *outputPath* : *必需* 包含目标路径的 **String**。必须是可写入的绝对文件路径。已有文件将被覆盖。 *Orientation* : *可选* [**cefPrintOrientation**](/official/Reference/CEF/Enumerations/cefPrintOrientation) 的成员。默认:**cefPrintPortrait**。 *ScaleFactor* : *可选* 包含打印缩放因子的 **Variant**(例如 `1.0` 为100%)。省略时使用CEF运行时的默认值。 *PageWidth* : *可选* 包含以微米为单位的页面宽度的 **Variant**。省略时使用CEF运行时的默认值。 *PageHeight* : *可选* 包含以微米为单位的页面高度的 **Variant**。省略时使用CEF运行时的默认值。 *MarginTop* / *MarginBottom* / *MarginLeft* / *MarginRight* : *可选* 以微米为单位的页边距 **Variant** 值。省略时使用运行时的默认值。 *ShouldPrintBackgrounds* : *可选* 控制输出中是否包含CSS背景颜色和图像的 **Boolean**。默认:**False**。 *ShouldPrintSelectionOnly* : *可选* 将输出限制为当前选区的 **Boolean**。默认:**False**。 *ShouldPrintHeaderAndFooter* : *可选* 控制是否渲染页面页眉(标题)和页脚(URL)的 **Boolean**。默认:**True**。 *HeaderTitle* : *可选* **Variant** **String**。提供时覆盖页眉中的文档标题。否则使用文档的 `<title>`。 *FooterUri* : *可选* **Variant** **String**。提供时覆盖页脚中打印的URL。否则使用实时文档URL。 ```vb Private Sub btnPDF_Click() Dim outputPath As String outputPath = Environ$("USERPROFILE") & "\Documents\cefDemo.pdf" CefBrowser1.PrintToPdf outputPath End Sub Private Sub CefBrowser1_PrintToPdfCompleted() MsgBox "PDF saved.", vbInformation End Sub ``` ### Reload 重新加载当前文档,等效于在浏览器中按 **F5**。 语法:*对象*.**Reload** ### SetVirtualHostNameToFolderMapping 安装一个从本地文件夹提供文件的虚拟主机名,以便页面可以通过 `https://` 来源而非 `file://` 引用本地内容。 语法:*对象*.**SetVirtualHostNameToFolderMapping** *hostName*, *folderPath* *hostName* : *必需* 包含要安装的主机名的 **String**(例如 `"my.app"`)。 *folderPath* : *必需* 包含应在该主机名下提供内容的文件夹绝对路径的 **String**。必须以尾部路径分隔符结尾。 ```vb Private Sub CefBrowser1_Ready() CefBrowser1.SetVirtualHostNameToFolderMapping _ "my.app", App.Path & "\web\" CefBrowser1.Navigate "https://my.app/index.html" End Sub ``` ## 事件 ### Create 在容器窗口已创建但CEF运行时尚未启动之后触发。宿主填充 [**EnvironmentOptions**](#environmentoptions) 的最后机会。 语法:*对象*\_**Create**( ) ### DocumentTitleChanged 当文档更改其标题时触发——通常在导航之后,但也可能在客户端JavaScript写入 `document.title` 时触发。读取 [**DocumentTitle**](#documenttitle) 获取新值。 语法:*对象*\_**DocumentTitleChanged**( ) ### DOMContentLoaded 当页面达到 `DOMContentLoaded` 生命周期事件时触发——DOM树已构建,JavaScript可以安全地遍历它,但外部资源可能仍在加载。 语法:*对象*\_**DOMContentLoaded**( ) ### Error 当CEF运行时启动失败时触发——最常见的原因是 `libcef.dll` 在配置的位置未找到,或用户数据文件夹被另一个进程锁定。 语法:*对象*\_**Error**( *code* **As Long**, *msg* **As String** ) ```vb Private Sub CefBrowser1_Error(ByVal code As Long, ByVal msg As String) MsgBox "CEF error " & Hex$(code) & ": " & msg, vbExclamation, "CEF" End Sub ``` ### JsAsyncResult 当之前的 [**JsRunAsync**](#jsrunasync) 调用返回时触发。*ErrString* 是任何运行时错误的描述,成功时为空字符串。 语法:*对象*\_**JsAsyncResult**( *Result* **As Variant**, *Token* **As LongLong**, *ErrString* **As String** ) ### JsMessage 当页面上的JavaScript调用 `window.chrome.webview.postMessage(value)` 时触发。 语法:*对象*\_**JsMessage**( *Message* **As Variant** ) ```vb Private Sub CefBrowser1_JsMessage(ByVal Message As Variant) Debug.Print "From page: "; Message CefBrowser1.PostWebMessage "Hello from BASIC" End Sub ``` ### NavigationComplete 当由 [**Navigate**](#navigate)、[**NavigateToString**](#navigatetostring) 或页面中的用户交互发起的导航完成时触发。 语法:*对象*\_**NavigationComplete**( *IsSuccess* **As Boolean**, *WebErrorStatus* **As Long** ) ::: info *IsSuccess* 和 *WebErrorStatus* 是事件签名的一部分,但目前返回占位值(`True` 和 `0`)——填充它们的底层CEF回调尚未连接。使用文档状态([**DocumentURL**](#documenturl)、[**CanGoBack**](#cangoback))来确定结果。 ::: ### NavigationStarting 在导航开始之前触发。将 *Cancel* 设置为 **True** 以中止导航;保持 **False** 让其继续。 语法:*对象*\_**NavigationStarting**( *Uri* **As String**, *IsUserInitiated* **As Boolean**, *IsRedirected* **As Boolean**, *RequestHeaders* **As Object**, *Cancel* **As Boolean** ) *Uri* : 目标URI。 *IsUserInitiated* : 当导航由用户手势触发时(点击、在地址栏按 **Enter**)为 **True**;脚本发起时为 **False**。 *IsRedirected* : 当此导航是来自之前导航的服务器端重定向时为 **True**。 *RequestHeaders* : **Object**。目前类型为 **Object**(底层 `CefRequestHeaders` 集合是为将来使用预留的占位符)。 *Cancel* : 设置为 **True** 以中止导航。 ```vb Private Sub CefBrowser1_NavigationStarting( _ ByVal Uri As String, ByVal IsUserInitiated As Boolean, _ ByVal IsRedirected As Boolean, ByVal RequestHeaders As Object, _ Cancel As Boolean) If InStr(Uri, "ads.example.com") > 0 Then Cancel = True End Sub ``` ### PrintToPdfCompleted 当之前的 [**PrintToPdf**](#printtopdf) 调用完成写入PDF时触发。 语法:*对象*\_**PrintToPdfCompleted**( ) ### PrintToPdfFailed 当之前的 [**PrintToPdf**](#printtopdf) 调用失败时触发——例如因为输出路径不可写入。 语法:*对象*\_**PrintToPdfFailed**( ) ### Ready 在浏览器辅助程序进程已启动、其IPC通道已连接且控件已准备好接受导航和脚本命令之后触发。如果 [**DocumentURL**](#documenturl) 在 **Ready** 触发时有非空值(设计时默认为 `https://www.twinbasic.com`),控件会自动导航到该地址。 语法:*对象*\_**Ready**( ) ### SourceChanged 当 [**DocumentURL**](#documenturl) 已更新时触发——通常在导航之后。用于使地址栏控件与浏览器保持同步。 语法:*对象*\_**SourceChanged**( *IsNewDocument* **As Boolean** ) *IsNewDocument* : 当更改反映新文档加载(而非同一文档片段 / `history.pushState` 更新)时为 **True**。 ```vb Private Sub CefBrowser1_SourceChanged(ByVal IsNewDocument As Boolean) AddressBar.Text = CefBrowser1.DocumentURL End Sub ``` ## 另见 * [CefEnvironmentOptions](/official/Reference/CEF/CefBrowser/EnvironmentOptions) -- 通过 [**EnvironmentOptions**](#environmentoptions) 暴露的预创建配置 * [CefLogSeverity](/official/Reference/CEF/Enumerations/CefLogSeverity) -- CEF调试日志的详细级别阈值 * [cefPrintOrientation](/official/Reference/CEF/Enumerations/cefPrintOrientation) -- 传递给 [**PrintToPdf**](#printtopdf) 的页面方向 * [WebView2](/official/Reference/WebView2/WebView2/) -- 具有更大功能集的WebView2运行时对应项 * [WebView2 对等性](/official/Reference/CEF/#webview2-parity) -- **WebView2** 上可用但尚未在 **CefBrowser** 上暴露的功能 * [ControlTypeConstants](/official/Reference/VBRUN/Constants/ControlTypeConstants) -- **vbCefBrowser** 所在位置 --- --- url: /en/official/Reference/CEF/Enumerations/CefLogSeverity.md --- # CefLogSeverity The minimum severity at which the CEF runtime records messages to its debug log. Assigned to [**EnvironmentOptions.LogSeverity**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#logseverity) before or during the [**Create**](/en/official/Reference/CEF/CefBrowser/#create) event; messages below the chosen level are discarded, messages at or above it are written to the file named by [**LogFilePath**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#logfilepath). | Constant | Value | Description | |----------|-------|-------------| | **CefLogDisable** | 0 | Default --- logging is disabled. | | **CefLogVerbose** | 1 | All messages, including verbose tracing. | | **CefLogInfo** | 2 | Informational messages and above. | | **CefLogWarning** | 3 | Warnings and above. | | **CefLogError** | 4 | Errors and above. | | **CefLogFatal** | 5 | Fatal errors only. | --- --- url: /zh/official/Reference/CEF/Enumerations/CefLogSeverity.md --- # CefLogSeverity CEF 运行时将消息记录到其调试日志的最低严重级别。在 [**Create**](/official/Reference/CEF/CefBrowser/#create) 事件之前或期间赋值给 [**EnvironmentOptions.LogSeverity**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#logseverity);低于所选级别的消息被丢弃,等于或高于它的消息写入由 [**LogFilePath**](/official/Reference/CEF/CefBrowser/EnvironmentOptions#logfilepath) 命名的文件。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **CefLogDisable** | 0 | 默认——日志记录已禁用。 | | **CefLogVerbose** | 1 | 所有消息,包括详细跟踪。 | | **CefLogInfo** | 2 | 信息消息及以上。 | | **CefLogWarning** | 3 | 警告及以上。 | | **CefLogError** | 4 | 错误及以上。 | | **CefLogFatal** | 5 | 仅致命错误。 | --- --- url: /en/official/Reference/CEF/Enumerations/cefPrintOrientation.md --- # cefPrintOrientation Page orientation passed to [**PrintToPdf**](/en/official/Reference/CEF/CefBrowser/#printtopdf) when writing the current document to a PDF file. | Constant | Value | Description | |----------|-------|-------------| | **cefPrintPortrait** | 0 | Default --- pages are laid out with the long side vertical. | | **cefPrintLandscape** | 1 | Pages are laid out with the long side horizontal. | --- --- url: /zh/official/Reference/CEF/Enumerations/cefPrintOrientation.md --- # cefPrintOrientation 将当前文档写入PDF文件时传递给 [**PrintToPdf**](/official/Reference/CEF/CefBrowser/#printtopdf) 的页面方向。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **cefPrintPortrait** | 0 | 默认——页面以长边垂直方向排版。 | | **cefPrintLandscape** | 1 | 页面以长边水平方向排版。 | --- --- url: /en/official/Reference/CustomControls/WaynesGrid/CellRenderingOptions.md --- # CellRenderingOptions class A bundle of the style objects that describe one *category* of cell in a [**WaynesGrid**](/en/official/Reference/CustomControls/WaynesGrid/). Each grid has six parallel instances --- one for column headers, one for row headers, one for normal cells, one for the hovered cell, one for the selected cell, and one for cells inside a full-row or full-column multi-selection --- and the grid picks the appropriate instance per cell at paint time. ```vb With Grid1.SelectedCellOptions .Fill.ColorPoints.SetSolidColor &HFFEEAA ' pale blue .Borders.SetSimpleBorder StrokeSize:=2, ColorRGB:=vbBlue End With ``` ## Properties ### Borders The [**Borders**](/en/official/Reference/CustomControls/Styles/Borders) drawn around the cell. ### Corners The [**Corners**](/en/official/Reference/CustomControls/Styles/Corners) that controls the per-corner shape and radius of the cell. Most cells use the default sharp 90° corners; rounded corners only really make sense on a single highlighted cell rather than on every cell in a column. ### Cursor The mouse cursor shown when the pointer is over this category of cell. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). Defaults to **vbDefault**; the grid sets **vbHand** on the column-header and row-header instances internally to indicate that those rows / columns are clickable for multi-selection. ### Fill The [**Fill**](/en/official/Reference/CustomControls/Styles/Fill) that paints the cell background. Newly-constructed **CellRenderingOptions** instances default to a solid mid-grey background ([**WAYNESCOLOR\_GREY**](#) --- `&H808080`). ### TextRendering The [**TextRendering**](/en/official/Reference/CustomControls/Styles/TextRendering) that controls how the cell's text (supplied by the [**GetCellText**](/en/official/Reference/CustomControls/WaynesGrid/#getcelltext) event) is drawn. ## Methods ### New Constructs a [**CellRenderingOptions**](#) with the default mid-grey fill. Syntax: **New CellRenderingOptions** ## Events ### OnChanged Raised whenever any of the contained style objects raises its own **OnChanged**, or when [**Cursor**](#cursor) is assigned. The parent [**WaynesGrid**](/en/official/Reference/CustomControls/WaynesGrid/) listens for this and requests a repaint. --- --- url: /zh/official/Reference/CustomControls/WaynesGrid/CellRenderingOptions.md --- # CellRenderingOptions 类 描述 [**WaynesGrid**](/official/Reference/CustomControls/WaynesGrid/) 中一个*类别*单元格的样式对象组合。每个网格有六个并行实例——列标题、行标题、普通单元格、悬停单元格、选中单元格以及全行或全列多选内的单元格各一个——网格在绘制时为每个单元格选择适当的实例。 ```vb With Grid1.SelectedCellOptions .Fill.ColorPoints.SetSolidColor &HFFEEAA ' pale blue .Borders.SetSimpleBorder StrokeSize:=2, ColorRGB:=vbBlue End With ``` ## 属性 ### Borders 绘制在单元格周围的 [**Borders**](/official/Reference/CustomControls/Styles/Borders)。 ### Corners 控制单元格逐角形状和半径的 [**Corners**](/official/Reference/CustomControls/Styles/Corners)。大多单元格使用默认的直角 90° 角;圆角仅在单个高亮单元格上有意义,而非列中每个单元格。 ### Cursor 光标悬停在此类别单元格上时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants) 的成员。默认 **vbDefault**;网格在列标题和行标题实例上内部设置 **vbHand** 以指示这些行/列可点击进行多选。 ### Fill 绘制单元格背景的 [**Fill**](/official/Reference/CustomControls/Styles/Fill)。新构造的 **CellRenderingOptions** 实例默认为纯中灰色背景([**WAYNESCOLOR\_GREY**](#) —— `&H808080`)。 ### TextRendering 控制单元格文本(由 [**GetCellText**](/official/Reference/CustomControls/WaynesGrid/#getcelltext) 事件提供)绘制方式的 [**TextRendering**](/official/Reference/CustomControls/Styles/TextRendering)。 ## 方法 ### New 用默认中灰色填充构造 [**CellRenderingOptions**](#)。 语法:**New CellRenderingOptions** ## 事件 ### OnChanged 任一包含的样式对象触发其自身的 **OnChanged** 或 [**Cursor**](#cursor) 被赋值时触发。父 [**WaynesGrid**](/official/Reference/CustomControls/WaynesGrid/) 监听此事件并请求重绘。 --- --- url: /en/official/Challenges.md --- # Challenges From **#general** on Discord: [From Wayne](https://discord.com/channels/927638153546829845/927638154192748606/1457062373465788671) in Discord: > As we start 2026, we're introducing monthly twinBASIC challenges, giving you the chance to win a £100 account credit redeemable against future twinBASIC licences. See this on [twinBASIC Update: January 6, 2026](https://nolongerset.com/twinbasic-update-january-6-2026/) from Mike Wolfe. --- --- url: /en/official/Reference/VBA/FileSystem/ChDir.md --- # ChDir Changes the current directory or folder. Syntax: **ChDir** *path* *path* : *required* A string expression that identifies which directory or folder becomes the new default directory or folder. The *path* may include the drive. If no drive is specified, **ChDir** changes the default directory or folder on the current drive. The **ChDir** statement changes the default directory but not the default drive. For example, if the default drive is C, the following statement changes the default directory on drive D, but C remains the default drive: ```vb ChDir "D:\TMP" ' Make "D:\TMP" the current folder. ChDrive "D" ' Make "D" the current drive. ``` ### See Also * [ChDrive](/en/official/Reference/VBA/FileSystem/ChDrive), [MkDir](/en/official/Reference/VBA/FileSystem/MkDir), [RmDir](/en/official/Reference/VBA/FileSystem/RmDir) statements * [CurDir](/en/official/Reference/VBA/FileSystem/CurDir), [Dir](/en/official/Reference/VBA/FileSystem/Dir) functions ### Example This example uses the **ChDir** statement to change the current directory or folder. ```vb ' Change current directory or folder to "MYDIR". ChDir "MYDIR" ' Assume "C:" is the current drive. The following statement changes ' the default directory on drive "D:". "C:" remains the current drive. ChDir "D:\WINDOWS\SYSTEM" ``` --- --- url: /zh/official/Reference/VBA/FileSystem/ChDir.md --- # ChDir 更改当前目录或文件夹。 语法:**ChDir** *path* *path* : *必需* 字符串表达式,标识哪个目录或文件夹成为新的默认目录或文件夹。*path*可以包含驱动器。如果未指定驱动器,**ChDir**将更改当前驱动器上的默认目录或文件夹。 **ChDir**语句更改默认目录但不更改默认驱动器。例如,如果默认驱动器是C,以下语句更改驱动器D上的默认目录,但C仍然是默认驱动器: ```vb ChDir "D:\TMP" ' Make "D:\TMP" the current folder. ChDrive "D" ' Make "D" the current drive. ``` ### 另请参阅 * [ChDrive](/official/Reference/VBA/FileSystem/ChDrive)、[MkDir](/official/Reference/VBA/FileSystem/MkDir)、[RmDir](/official/Reference/VBA/FileSystem/RmDir)语句 * [CurDir](/official/Reference/VBA/FileSystem/CurDir)、[Dir](/official/Reference/VBA/FileSystem/Dir)函数 ### 示例 本示例使用**ChDir**语句更改当前目录或文件夹。 ```vb ' Change current directory or folder to "MYDIR". ChDir "MYDIR" ' Assume "C:" is the current drive. The following statement changes ' the default directory on drive "D:". "C:" remains the current drive. ChDir "D:\WINDOWS\SYSTEM" ``` --- --- url: /zh/official/Reference/Core/ChDir.md --- # ChDir 语句 chdir 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/ChDir.md --- # ChDir Statement Documentation for the chdir keyword is not yet available. --- --- url: /en/official/Reference/VBA/FileSystem/ChDrive.md --- # ChDrive Changes the current drive. Syntax: **ChDrive** *drive* *drive* : *required* A string expression that specifies an existing drive. If *drive* is a zero-length string (""), the current drive doesn't change. If the *drive* argument is a multiple-character string, **ChDrive** uses only the first letter. ### See Also * [ChDir](/en/official/Reference/VBA/FileSystem/ChDir), [MkDir](/en/official/Reference/VBA/FileSystem/MkDir), and [RmDir](/en/official/Reference/VBA/FileSystem/RmDir) statements * [CurDir](/en/official/Reference/VBA/FileSystem/CurDir) function ### Example This example uses the **ChDrive** statement to change the current drive. ```vb ChDrive "D" ' Make "D" the current drive. ``` --- --- url: /zh/official/Reference/VBA/FileSystem/ChDrive.md --- # ChDrive 更改当前驱动器。 语法:**ChDrive** *drive* *drive* : *必需* 字符串表达式,指定一个现有的驱动器。如果*drive*是零长度字符串(""),则当前驱动器不变。如果*drive*参数是多字符字符串,**ChDrive**仅使用第一个字母。 ### 另请参阅 * [ChDir](/official/Reference/VBA/FileSystem/ChDir)、[MkDir](/official/Reference/VBA/FileSystem/MkDir)和[RmDir](/official/Reference/VBA/FileSystem/RmDir)语句 * [CurDir](/official/Reference/VBA/FileSystem/CurDir)函数 ### 示例 本示例使用**ChDrive**语句更改当前驱动器。 ```vb ChDrive "D" ' Make "D" the current drive. ``` --- --- url: /zh/official/Reference/Core/ChDrive.md --- # ChDrive 语句 chdrive 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/ChDrive.md --- # ChDrive Statement Documentation for the chdrive keyword is not yet available. --- --- url: /en/official/Reference/VB/CheckBox.md --- # CheckBox class A **CheckBox** is a Win32 native control that displays a small box, optionally followed by a text caption, used to give the user a choice between two values such as *Yes*/*No*, *True*/*False*, or *On*/*Off*. It can also be put into a third, indeterminate (grey) state from code, typically to mean "not applicable" or "mixed". The control is normally placed on a **Form** or **UserControl** at design time. The default property is [**Value**](#value) and the default event is [**Click**](#click). ```vb Private Sub Form_Load() Check1.Caption = "I &agree to the terms" Check1.Value = vbUnchecked End Sub Private Sub Check1_Click() cmdContinue.Enabled = (Check1.Value = vbChecked) End Sub ``` ## Three-state behaviour [**Value**](#value) is typed as [**CheckBoxConstants**](/en/official/Reference/VBRUN/Constants/CheckBoxConstants): | Constant | Value | Meaning | |------------------|-------|--------------------------------------------------------| | **vbUnchecked** | 0 | The check box is cleared. | | **vbChecked** | 1 | The check box is selected. | | **vbGrayed** | 2 | The check box is in an indeterminate (grey) state. | Clicking an unchecked or grey check box selects it; clicking a checked or grey check box clears it. The grey state is reachable only from code --- assign **vbGrayed** to **Value** to display it. Assigning a negative number raises run-time error 380 (*Invalid property value*). ```vb Check1.Value = vbGrayed ' show the indeterminate state ``` ## Caption and mnemonics The text shown next to (or, with [**Alignment**](#alignment) `tbRightJustify`, before) the box comes from [**Caption**](#caption). An ampersand in the caption marks the next character as a keyboard mnemonic: pressing **Alt+** that character moves the focus to the check box and toggles its value. Use `&&` to display a literal ampersand. ```vb Check1.Caption = "Use && in folder names" ' renders as: Use & in folder names ``` ## Graphical style When [**Style**](#style) is **vbButtonGraphical**, the check box is owner-drawn and displays the bitmaps assigned to [**Picture**](#picture), [**DownPicture**](#downpicture), and [**DisabledPicture**](#disabledpicture) instead of the standard square. [**PictureAlignment**](#picturealignment), [**Padding**](#padding), and [**PictureDpiScaling**](#picturedpiscaling) control how the picture is positioned relative to the caption. ## Data binding Setting [**DataSource**](#datasource) and [**DataField**](#datafield) connects the control's [**Value**](#value) to a field of a **Data** control's recordset. The bound field is read as a **Boolean**: a non-zero/`True` value sets [**Value**](#value) to **vbChecked**, zero/`False` sets it to **vbUnchecked**. Assigning a non-Boolean field value raises run-time error 13 (*Type mismatch*). ## Properties ### Alignment Specifies the side of the box on which the [**Caption**](#caption) text appears. Syntax: *object*.**Alignment** \[ = *value* ] *value* : A member of [**AlignmentConstantsNoCenter**](/en/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter): **tbLeftJustify** (0, default --- caption to the right of the box) or **tbRightJustify** (1 --- caption to the left of the box). ### Appearance Determines how the control's border is drawn by the OS. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). ### BackColor The background colour, as an **OLE\_COLOR**. Defaults to the system 3-D face colour. ### Caption The text displayed next to the check box. An ampersand marks the next character as a mnemonic; `&&` produces a literal ampersand. The string is read directly from the underlying window --- assigning to **Caption** is reflected immediately. Syntax: *object*.**Caption** \[ = *string* ] ### CausesValidation Determines whether the previously focused control's [**Validate**](#validate) event runs before this control receives the focus. **Boolean**, default **True**. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a check box. Always **vbCheckBox**. ### DataField The name of the field, in the recordset of the bound [**DataSource**](#datasource), whose value is mirrored by [**Value**](#value). **String**. ### DataSource A reference to a **Data** control (or other **DataSource** provider) whose recordset supplies the value for [**DataField**](#datafield). Set with **Set**. ### DisabledPicture A **StdPicture** drawn instead of [**Picture**](#picture) when the control is disabled and [**Style**](#style) is **vbButtonGraphical**. ### DownPicture A **StdPicture** drawn instead of [**Picture**](#picture) while the control is in the depressed state, when [**Style**](#style) is **vbButtonGraphical**. ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the control accepts user input. A disabled check box shows its current value but is dimmed and ignores keyboard and mouse interaction. **Boolean**, default **True**. ### Font The **StdFont** used to render [**Caption**](#caption). The convenience properties **FontName**, **FontSize**, **FontBold**, **FontItalic**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. ### ForeColor The text colour for the caption, as an **OLE\_COLOR**. Defaults to the system button-text colour. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). **Single**. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the control has focus. ### hWnd The Win32 window handle for the underlying button, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Read-only at run time. ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Single**. ### MaskColor ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### OLEDropMode How the control responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on a CheckBox. ### Opacity The control's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Requires Windows 8 or later for child controls. ### Padding The number of pixels of empty space inserted between the picture and the caption (when [**PictureAlignment**](#picturealignment) is **vbAlignLeft** or **vbAlignRight**) or between the caption and the corresponding edge (when **vbAlignTop** or **vbAlignBottom**). **Long**, default 2. Only meaningful when [**Style**](#style) is **vbButtonGraphical**. ### Parent A reference to the [**Form**](/en/official/Reference/VB/Form/) (or **UserControl**) that contains this control. Read-only. ### Picture A **StdPicture** drawn on the control when [**Style**](#style) is **vbButtonGraphical**. Assigning **Nothing** restores an empty picture rather than removing the bitmap surface. ### PictureAlignment How [**Picture**](#picture) is positioned relative to the caption when [**Style**](#style) is **vbButtonGraphical**. A member of [**AlignConstants**](/en/official/Reference/VBRUN/Constants/AlignConstants): **vbAlignNone**, **vbAlignTop** (default), **vbAlignBottom**, **vbAlignLeft**, **vbAlignRight**. ### PictureDpiScaling When **True**, scales [**Picture**](#picture), [**DownPicture**](#downpicture), and [**DisabledPicture**](#disabledpicture) by the current DPI factor before drawing. **Boolean**, default **False**. ### RightToLeft ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. Use [**Alignment**](#alignment) to flip the caption to the left of the box. ::: ### Style Selects between the standard Win32 check-box appearance and an owner-drawn graphical button. A member of [**ButtonConstants**](/en/official/Reference/VBRUN/Constants/ButtonConstants): **vbButtonStandard** (0, default) or **vbButtonGraphical** (1). Changing **Style** at run time recreates the underlying window. ### TabIndex The position of the control in the form's TAB-key navigation order. **Long**. ### TabStop Whether the user can reach the control by pressing the **TAB** key. **Boolean**, default **True**. A disabled control is skipped regardless of this setting. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the control. ### Top The vertical distance from the top of the container to the top of the control. **Single**. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered control. Default `-1` disables the effect. Requires Windows 8 or later for child controls. ### UseMaskColor ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### Value The current state of the check box. **Default property.** Syntax: *object*.**Value** \[ = *value* ] *value* : A member of [**CheckBoxConstants**](/en/official/Reference/VBRUN/Constants/CheckBoxConstants): **vbUnchecked** (0), **vbChecked** (1), or **vbGrayed** (2). Negative numbers raise run-time error 380. Assigning a value that differs from the current one raises a [**Click**](#click) event. ### Visible Whether the control is shown. **Boolean**, default **True**. ### VisualStyles Whether the OS theme engine should be used when drawing the control. **Boolean**. ### WhatsThisHelpID A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### Width The control's width. **Single**. ## Methods ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Typically called from a [**MouseDown**](#mousedown) handler when [**DragMode**](#dragmode) is **vbManual**. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the control, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Forces an immediate repaint of the control. Syntax: *object*.**Refresh** ### SetFocus Moves the input focus to the control. The control must be both [**Visible**](#visible) and [**Enabled**](#enabled), or run-time error 5 (*Invalid procedure call or argument*) is raised. Syntax: *object*.**SetFocus** ### ShowWhatsThis Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Click Raised after [**Value**](#value) changes --- whether the user clicked the box, pressed the access key, or assigned a different value in code. **Default event.** Syntax: *object*\_**Click**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus Raised when the control receives the input focus. Syntax: *object*\_**GotFocus**( ) ### KeyDown Raised when the user presses any key while the control has focus. Syntax: *object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress Raised when the user types a character that produces an ANSI keystroke. Syntax: *object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp Raised when the user releases a key while the control has focus. Syntax: *object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus Raised when the control loses the input focus. Syntax: *object*\_**LostFocus**( ) ### MouseDown Raised when the user presses any mouse button over the control. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the control. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the control. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Validate Raised when the focus is moving to another control whose [**CausesValidation**](#causesvalidation) is **True**. Setting *Cancel* to **True** keeps the focus on this control. Syntax: *object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /zh/official/Reference/VB/CheckBox.md --- # CheckBox 类 **CheckBox**是Win32原生控件,显示一个小方框,可选后跟文本标题,用于让用户在两个值之间做出选择,如*是*/*否*、*真*/*假*或*开*/*关*。也可以从代码将其设为第三种不确定(灰色)状态,通常表示"不适用"或"混合"。 控件通常在设计时放置在**Form**或**UserControl**上。默认属性是[**Value**](#value),默认事件是[**Click**](#click)。 ```vb Private Sub Form_Load() Check1.Caption = "I &agree to the terms" Check1.Value = vbUnchecked End Sub Private Sub Check1_Click() cmdContinue.Enabled = (Check1.Value = vbChecked) End Sub ``` ## 三态行为 [**Value**](#value)的类型为[**CheckBoxConstants**](/official/Reference/VBRUN/Constants/CheckBoxConstants): | 常量 | 值 | 含义 | |------------------|----|----------------------------------------| | **vbUnchecked** | 0 | 复选框未选中。 | | **vbChecked** | 1 | 复选框已选中。 | | **vbGrayed** | 2 | 复选框处于不确定(灰色)状态。 | 点击未选中或灰色的复选框会选中它;点击已选中或灰色的复选框会取消选中。灰色状态只能从代码到达——赋值**vbGrayed**给**Value**以显示。赋值负数会引发运行时错误380(*无效属性值*)。 ```vb Check1.Value = vbGrayed ' show the indeterminate state ``` ## 标题和助记符 显示在方框旁边(或当[**Alignment**](#alignment)为`tbRightJustify`时在方框之前)的文本来自[**Caption**](#caption)。标题中的和号将下一个字符标记为键盘助记符:按\*\*Alt+\*\*该字符将焦点移到复选框并切换其值。使用`&&`显示字面和号。 ```vb Check1.Caption = "Use && in folder names" ' renders as: Use & in folder names ``` ## 图形样式 当[**Style**](#style)为**vbButtonGraphical**时,复选框为所有者绘制,显示赋给[**Picture**](#picture)、[**DownPicture**](#downpicture)和[**DisabledPicture**](#disabledpicture)的位图,而非标准方块。[**PictureAlignment**](#picturealignment)、[**Padding**](#padding)和[**PictureDpiScaling**](#picturedpiscaling)控制图片相对于标题的定位方式。 ## 数据绑定 设置[**DataSource**](#datasource)和[**DataField**](#datafield)将控件的[**Value**](#value)连接到**Data**控件记录集的字段。绑定字段作为**Boolean**读取:非零/`True`值将[**Value**](#value)设为**vbChecked**,零/`False`设为**vbUnchecked**。赋值非Boolean字段值会引发运行时错误13(*类型不匹配*)。 ## 属性 ### Alignment 指定[**Caption**](#caption)文本出现在方框的哪一侧。 语法:*object*.**Alignment** \[ = *value* ] *value* : [**AlignmentConstantsNoCenter**](/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter)的成员:**tbLeftJustify**(0,默认——标题在方框右侧)或**tbRightJustify**(1——标题在方框左侧)。 ### Appearance 决定操作系统绘制控件边框的方式。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。 ### BackColor 背景色,作为**OLE\_COLOR**。默认为系统3D表面颜色。 ### Caption 显示在复选框旁边的文本。和号将下一个字符标记为助记符;`&&`产生字面和号。字符串直接从底层窗口读取——赋值给**Caption**会立即反映。 语法:*object*.**Caption** \[ = *string* ] ### CausesValidation 决定先前聚焦控件的[**Validate**](#validate)事件是否在此控件获得焦点之前运行。**Boolean**,默认**True**。 ### ControlType 标识此控件为复选框的只读[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值。始终为**vbCheckBox**。 ### DataField 绑定的[**DataSource**](#datasource)记录集中由[**Value**](#value)镜像的字段名称。**String**。 ### DataSource 对**Data**控件(或其他**DataSource**提供者)的引用,其记录集为[**DataField**](#datafield)提供值。用**Set**设置。 ### DisabledPicture 当控件禁用且[**Style**](#style)为**vbButtonGraphical**时,替代[**Picture**](#picture)绘制的**StdPicture**。 ### DownPicture 当控件处于按下状态且[**Style**](#style)为**vbButtonGraphical**时,替代[**Picture**](#picture)绘制的**StdPicture**。 ### DragIcon 在控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自行拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual**(0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic**(1)。 ### Enabled 决定控件是否接受用户输入。禁用的复选框显示其当前值但变暗,忽略键盘和鼠标交互。**Boolean**,默认**True**。 ### Font 用于渲染[**Caption**](#caption)的**StdFont**。便捷属性**FontName**、**FontSize**、**FontBold**、**FontItalic**、**FontStrikethru**和**FontUnderline**读写此对象的对应成员。 ### ForeColor 标题的文本颜色,作为**OLE\_COLOR**。默认为系统按钮文本颜色。 ### Height 控件的高度,默认以缇为单位(或以容器的**ScaleMode**单位)。**Single**。 ### HelpContextID 标识应用程序帮助文件中主题的**Long**,当用户在控件有焦点时按**F1**时检索。 ### hWnd 底层按钮的Win32窗口句柄,作为**LongPtr**。只读。适用于传递给API函数。 ### Index 当控件是控件数组的一部分时,此实例在数组中的**Long**零基索引。运行时只读。 ### Left 从容器左边缘到控件左边缘的水平距离。**Single**。 ### MaskColor ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针在控件上方时用作鼠标光标的**StdPicture**。 ### MousePointer 指针在控件上方时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### OLEDropMode 控件如何响应OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**或**vbOLEDropManual**。CheckBox不支持自动放置模式。 ### Opacity 控件的不透明度百分比(0--100,默认100)。超出范围的值在**Initialize**时被钳制。子控件需要Windows 8或更高版本。 ### Padding 在图片和标题之间插入的空像素数(当[**PictureAlignment**](#picturealignment)为**vbAlignLeft**或**vbAlignRight**时)或在标题和对应边缘之间(当**vbAlignTop**或**vbAlignBottom**时)。**Long**,默认2。仅在[**Style**](#style)为**vbButtonGraphical**时有意义。 ### Parent 对包含此控件的[**Form**](/official/Reference/VB/Form/)(或**UserControl**)的引用。只读。 ### Picture 当[**Style**](#style)为**vbButtonGraphical**时绘制在控件上的**StdPicture**。赋值**Nothing**恢复空图片而非移除位图表面。 ### PictureAlignment 当[**Style**](#style)为**vbButtonGraphical**时[**Picture**](#picture)相对于标题的定位方式。[**AlignConstants**](/official/Reference/VBRUN/Constants/AlignConstants)的成员:**vbAlignNone**、**vbAlignTop**(默认)、**vbAlignBottom**、**vbAlignLeft**、**vbAlignRight**。 ### PictureDpiScaling 当**True**时,绘制前按当前DPI因子缩放[**Picture**](#picture)、[**DownPicture**](#downpicture)和[**DisabledPicture**](#disabledpicture)。**Boolean**,默认**False**。 ### RightToLeft ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。使用[**Alignment**](#alignment)将标题翻转到方框左侧。 ::: ### Style 在标准Win32复选框外观和所有者绘制图形按钮之间选择。[**ButtonConstants**](/official/Reference/VBRUN/Constants/ButtonConstants)的成员:**vbButtonStandard**(0,默认)或**vbButtonGraphical**(1)。在运行时更改**Style**会重新创建底层窗口。 ### TabIndex 控件在窗体TAB键导航顺序中的位置。**Long**。 ### TabStop 用户是否可以通过按**TAB**键到达控件。**Boolean**,默认**True**。禁用的控件无论此设置如何都会被跳过。 ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### ToolTipText 用户悬停在控件上方时作为工具提示显示的多行**String**。 ### Top 从容器顶部到控件顶部的垂直距离。**Single**。 ### TransparencyKey 设置后成为渲染控件中完全透明的**OLE\_COLOR**。默认`-1`禁用效果。子控件需要Windows 8或更高版本。 ### UseMaskColor ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: ### Value 复选框的当前状态。**默认属性。** 语法:*object*.**Value** \[ = *value* ] *value* : [**CheckBoxConstants**](/official/Reference/VBRUN/Constants/CheckBoxConstants)的成员:**vbUnchecked**(0)、**vbChecked**(1)或**vbGrayed**(2)。负数会引发运行时错误380。 赋值与当前值不同的值会引发[**Click**](#click)事件。 ### Visible 控件是否显示。**Boolean**,默认**True**。 ### VisualStyles 绘制控件时是否使用操作系统主题引擎。**Boolean**。 ### WhatsThisHelpID 标识应用程序帮助文件中"这是什么?"帮助弹出主题的**Long**。参见[**ShowWhatsThis**](#showwhatsthis)。 ### Width 控件的宽度。**Single**。 ## 方法 ### Drag 开始、完成或取消手动拖放操作。通常在[**DragMode**](#dragmode)为**vbManual**时从[**MouseDown**](#mousedown)处理程序调用。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel**(0)、**vbBeginDrag**(1,默认)或**vbEndDrag**(2)。 ### Move 在单次调用中重新定位并可选地调整控件的尺寸。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从控件发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### Refresh 强制立即重绘控件。 语法:*object*.**Refresh** ### SetFocus 将输入焦点移到控件。控件必须同时[**Visible**](#visible)和[**Enabled**](#enabled),否则引发运行时错误5(*无效的过程调用或参数*)。 语法:*object*.**SetFocus** ### ShowWhatsThis 以"这是什么?"弹窗形式显示由[**WhatsThisHelpID**](#whatsthishelpid)标识的主题。 语法:*object*.**ShowWhatsThis** ### ZOrder 将控件带到同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront**(0,默认)或**vbSendToBack**(1)。 ## 事件 ### Click 在[**Value**](#value)更改后引发——无论用户点击了方框、按了访问键还是在代码中赋了不同的值。**默认事件。** 语法:*object*\_**Click**( ) ### DragDrop 当手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 当手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus 当控件获得输入焦点时引发。 语法:*object*\_**GotFocus**( ) ### KeyDown 当控件有焦点时用户按下任意键时引发。 语法:*object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress 当用户输入产生ANSI按键的字符时引发。 语法:*object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp 当控件有焦点时用户释放键时引发。 语法:*object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus 当控件失去输入焦点时引发。 语法:*object*\_**LostFocus**( ) ### MouseDown 当用户在控件上方按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 当光标在控件上方移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 当用户在控件上方释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag 当OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 当用户在目标控件上放置数据时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver 当OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 在拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的格式的数据时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag 在OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Validate 当焦点移动到[**CausesValidation**](#causesvalidation)为**True**的另一个控件时引发。将*Cancel*设为**True**使焦点保留在此控件上。 语法:*object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /en/official/Reference/VBRUN/Constants/CheckBoxConstants.md --- # CheckBoxConstants State values for the **Value** property of a check-box control. | Constant | Value | Description | |----------|-------|-------------| | **vbUnchecked** | 0 | The check box is cleared. | | **vbChecked** | 1 | The check box is selected. | | **vbGrayed** | 2 | The check box is shown in an indeterminate (gray) state. | --- --- url: /zh/official/Reference/VBRUN/Constants/CheckBoxConstants.md --- # CheckBoxConstants 复选框控件的**Value**属性的状态值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbUnchecked** | 0 | 复选框未选中。 | | **vbChecked** | 1 | 复选框已选中。 | | **vbGrayed** | 2 | 复选框显示为不确定(灰色)状态。 | --- --- url: /en/packages/vbccr/buttons/checkboxw.md description: >- CheckBoxW Control - VBCCR Development Manual, complete API reference based on source code --- # CheckBoxW Control Enhanced CheckBox control with support for visual styles, owner-draw, ImageList icons, and PushLike mode. ## Enumerations ### ChkImageListAlignmentConstants | Constant | Value | Description | |----------|-------|-------------| | ChkImageListAlignmentLeft | 0 | Left alignment | | ChkImageListAlignmentRight | 1 | Right alignment | | ChkImageListAlignmentTop | 2 | Top alignment | | ChkImageListAlignmentBottom | 3 | Bottom alignment | | ChkImageListAlignmentCenter | 4 | Center alignment | ### ChkDrawModeConstants | Constant | Value | Description | |----------|-------|-------------| | ChkDrawModeNormal | 0 | Normal mode, drawn by the system | | ChkDrawModeOwnerDraw | 1 | Owner-draw mode, drawn by code | ## Properties ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` Whether to enable visual styles. ### Appearance ```vb Property Get Appearance() As CCAppearanceConstants Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` Appearance style. See Common Enumerations. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` Foreground color. ### ImageList ```vb Property Get ImageList() As Variant Property Let ImageList(ByVal Value As Variant) Property Set ImageList(ByVal Value As Variant) ``` Associated ImageList control. ### ImageListAlignment ```vb Property Get ImageListAlignment() As ChkImageListAlignmentConstants Property Let ImageListAlignment(ByVal Value As ChkImageListAlignmentConstants) ``` ImageList icon alignment. ### ImageListMargin ```vb Property Get ImageListMargin() As Single Property Let ImageListMargin(ByVal Value As Single) ``` ImageList icon margin. ### Value ```vb Property Get Value() As Integer Property Let Value(ByVal Value As Integer) ``` CheckBox state (0 - unchecked, 1 - checked, 2 - grayed). ### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` Caption text. ### Alignment ```vb Property Get Alignment() As CCLeftRightAlignmentConstants Property Let Alignment(ByVal Value As CCLeftRightAlignmentConstants) ``` CheckBox alignment. See Common Enumerations. ### TextAlignment ```vb Property Get TextAlignment() As VBRUN.AlignmentConstants Property Let TextAlignment(ByVal Value As VBRUN.AlignmentConstants) ``` Text alignment. ### PushLike ```vb Property Get PushLike() As Boolean Property Let PushLike(ByVal Value As Boolean) ``` Whether to display as a button style. ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` Picture. ### WordWrap ```vb Property Get WordWrap() As Boolean Property Let WordWrap(ByVal Value As Boolean) ``` Whether to enable word wrap. ### Transparent ```vb Property Get Transparent() As Boolean Property Let Transparent(ByVal Value As Boolean) ``` Whether to use a transparent background (effective at run time). ### VerticalAlignment ```vb Property Get VerticalAlignment() As CCVerticalAlignmentConstants Property Let VerticalAlignment(ByVal Value As CCVerticalAlignmentConstants) ``` Vertical alignment. See Common Enumerations. ### Style ```vb Property Get Style() As VBRUN.ButtonConstants Property Let Style(ByVal Value As VBRUN.ButtonConstants) ``` Appearance style (standard or graphical). ### DisabledPicture ```vb Property Get DisabledPicture() As IPictureDisp Property Let DisabledPicture(ByVal Value As IPictureDisp) Property Set DisabledPicture(ByVal Value As IPictureDisp) ``` Disabled state picture. Effective when Style is graphical. ### DownPicture ```vb Property Get DownPicture() As IPictureDisp Property Let DownPicture(ByVal Value As IPictureDisp) Property Set DownPicture(ByVal Value As IPictureDisp) ``` Pressed state picture. Effective when Style is graphical. ### UseMaskColor ```vb Property Get UseMaskColor() As Boolean Property Let UseMaskColor(ByVal Value As Boolean) ``` Whether to use mask color. Effective when Style is graphical. ### MaskColor ```vb Property Get MaskColor() As OLE_COLOR Property Let MaskColor(ByVal Value As OLE_COLOR) ``` Mask color. Effective when Style is graphical. ### DrawMode ```vb Property Get DrawMode() As ChkDrawModeConstants Property Let DrawMode(ByVal Value As ChkDrawModeConstants) ``` Draw mode. ### Pushed ```vb Property Get Pushed() As Boolean ``` Whether the control is in a pressed state. Read-only. ### Hot ```vb Property Get Hot() As Boolean ``` Whether the control is in a hot state (mouse hover). Read-only. ### hWnd ```vb Property Get hWnd() As LongPtr ``` Window handle. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` UserControl window handle. ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` Font. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE drag-drop mode. See Common Enumerations. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` Mouse pointer. See Common Enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` Custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Mouse enter/leave tracking. ### Name / Tag / Parent / Container / Left / Top / Width / Height / Visible / ToolTipText / HelpContextID / WhatsThisHelpID / DragIcon / DragMode See standard extender properties. ## Methods ### Refresh ```vb Public Sub Refresh() ``` Forces a repaint. ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag-drop operation. ### Drag / ZOrder / SetFocus / Move See standard methods. ## Events ### Click ```vb Public Event Click() ``` Single click. ### DblClick ```vb Public Event DblClick() ``` Double click. ### HotChanged ```vb Public Event HotChanged() ``` Fired when the hot state changes. ### OwnerDraw ```vb Public Event OwnerDraw(ByVal ItemAction As Long, ByVal ItemState As Long, ByVal hDC As LongPtr, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` Owner-draw event. Fired when DrawMode is OwnerDraw. ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` ### KeyPress ```vb Public Event KeyPress(KeyAscii As Integer) ``` ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` ### MouseEnter ```vb Public Event MouseEnter() ``` ### MouseLeave ```vb Public Event MouseLeave() ``` ### OLECompleteDrag / OLEDragDrop / OLEDragOver / OLEGiveFeedback / OLESetData / OLEStartDrag See OLE drag-drop events. ## Code Examples ### Basic Usage ```vb ' Set up a tri-state CheckBox CheckBoxW1.Value = vbChecked ' Checked CheckBoxW2.Value = vbUnchecked ' Unchecked CheckBoxW3.Value = vbGrayed ' Grayed ' PushLike button style CheckBoxW1.PushLike = True ' Associate ImageList Set CheckBoxW1.ImageList = ImageList1 CheckBoxW1.ImageListAlignment = ChkImageListAlignmentLeft ``` ### Owner-Draw Mode ```vb Private Sub CheckBoxW1_OwnerDraw(ByVal ItemAction As Long, ByVal ItemState As Long, _ ByVal hDC As LongPtr, ByVal Left As Long, ByVal Top As Long, _ ByVal Right As Long, ByVal Bottom As Long) ' Draw custom CheckBox here End Sub ``` --- --- url: /en/official/Reference/VB/CheckMark.md --- # CheckMark class A **CheckMark** is a windowless control that draws a single check glyph --- checked, unchecked, or grey --- that scales to fill its rectangle. Unlike [**CheckBox**](/en/official/Reference/VB/CheckBox/), it has no caption, no font, and cannot take focus or receive keyboard input; it is essentially the box from a check-box rendered at whatever size the layout requires. This makes it especially useful inside reports and other dense layouts where the fixed-size system check would look out of place, but it is also available on a **Form** or **UserControl**. The default property is [**Value**](#value) and the default event is [**Click**](#click). ```vb Private Sub Form_Load() Check1.Value = vbUnchecked End Sub Private Sub Check1_Click() Debug.Print "Check is now: " & Check1.Value End Sub ``` ## Three-state behaviour [**Value**](#value) is typed as [**CheckBoxConstants**](/en/official/Reference/VBRUN/Constants/CheckBoxConstants): | Constant | Value | Meaning | |------------------|-------|--------------------------------------------------------| | **vbUnchecked** | 0 | The check is cleared. | | **vbChecked** | 1 | The check is selected. | | **vbGrayed** | 2 | The check is in an indeterminate (grey) state. | A user click toggles **Value** between **vbChecked** and **vbUnchecked** only. The grey state is reachable from code --- assign **vbGrayed** to **Value** to display it. ```vb Check1.Value = vbGrayed ' show the indeterminate state ``` ## Drawing modes [**VisualStyles**](#visualstyles) selects how the glyph is rendered: * **VisualStyles = False** (default) --- drawn with the GDI **DrawFrameControl** primitive. Honours [**Appearance**](#appearance): **vbAppear3d** uses the classic raised/sunken look, **vbAppearFlat** uses a single-pixel outline. A disabled check, or one in the **vbGrayed** state, is drawn over the dotted three-state pattern. * **VisualStyles = True** --- drawn through the OS theme engine (UXTHEME), so the glyph uses the current visual-style theme. **Appearance** is ignored in this mode. ## Background [**BackStyle**](#backstyle) controls whether the rectangle behind the glyph is filled before the glyph is drawn: * **vbBFTransparent** (default) --- only the glyph is painted; whatever the container draws shows through. * **vbBFOpaque** --- the rectangle is filled with [**BackColor**](#backcolor) first. ## Properties ### Anchors The **Anchors** object that determines which sides of the control follow the corresponding sides of its container as the container is resized. Read-only --- set the individual sides through the returned object. ### Appearance How the glyph is shaded when [**VisualStyles**](#visualstyles) is **False**. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppear3d** (default) or **vbAppearFlat**. Ignored when [**VisualStyles**](#visualstyles) is **True**. ### BackColor The background colour, as an **OLE\_COLOR**. Defaults to the system 3-D face colour. Used only when [**BackStyle**](#backstyle) is **vbBFOpaque**. ### BackStyle Whether the control fills its rectangle before drawing the glyph. A member of **BackFillStyleConstants**: **vbBFTransparent** (default) or **vbBFOpaque**. ### Container The immediate container (a **Form**, **Frame**, **PictureBox**, or other container control) that hosts this **CheckMark**. Assigning a new value with **Set** moves the control to a different container. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a check mark. Always **vbCheckMark**. ### Dock Whether the control fills one edge of, or the entire interior of, its container. A member of **DockModeConstants**, default **vbDockNone**. ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the control reacts to mouse input. A disabled **CheckMark** still shows its current value but is drawn dimmed and ignores clicks. **Boolean**, default **True**. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). **Single**. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Reading **Index** on a control that is not part of an array raises run-time error 343 (*Object not an array*). Read-only at run time. ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Single**. ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### Parent A reference to the **Form** (or **UserControl**) that contains this control. Read-only. ### TabIndex ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. The control is not focusable, so the property has no effect at run time. ::: ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the control. ### Top The vertical distance from the top of the container to the top of the control. **Single**. ### Value The current state of the check. **Default property.** Syntax: *object*.**Value** \[ = *value* ] *value* : A member of [**CheckBoxConstants**](/en/official/Reference/VBRUN/Constants/CheckBoxConstants): **vbUnchecked** (0), **vbChecked** (1), or **vbGrayed** (2). A user click toggles **Value** between **vbChecked** and **vbUnchecked** only; **vbGrayed** is settable from code. ### Visible Whether the control is shown. **Boolean**, default **True**. ### VisualStyles When **True**, the glyph is drawn through the OS theme engine; when **False** (default), it is drawn with **DrawFrameControl** and obeys [**Appearance**](#appearance). **Boolean**. ### WhatsThisHelpID A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### Width The control's width. **Single**. ## Methods ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Typically called from a [**MouseDown**](#mousedown) handler when [**DragMode**](#dragmode) is **vbManual**. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the control, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Forces an immediate repaint of the control. Syntax: *object*.**Refresh** ### ShowWhatsThis Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Click Raised when the user clicks the control with the left mouse button --- after [**Value**](#value) has toggled between **vbChecked** and **vbUnchecked**. **Default event.** Syntax: *object*\_**Click**( ) ### DblClick Raised when the user double-clicks the control. Syntax: *object*\_**DblClick**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### MouseDown Raised when the user presses any mouse button over the control. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the control. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the control. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) --- --- url: /zh/official/Reference/VB/CheckMark.md --- # CheckMark 类 **CheckMark**是无窗口控件,绘制单个勾选字形——已勾选、未勾选或灰色——该字形会缩放以填充其矩形区域。与[**CheckBox**](/official/Reference/VB/CheckBox/)不同,它没有标题、没有字体,不能获取焦点或接收键盘输入;它本质上是复选框的方框部分,以布局所需的任意大小渲染。这使它特别适用于报表和其他密集布局中固定大小的系统勾选框看起来不协调的场景,但也适用于**Form**或**UserControl**。 默认属性是[**Value**](#value),默认事件是[**Click**](#click)。 ```vb Private Sub Form_Load() Check1.Value = vbUnchecked End Sub Private Sub Check1_Click() Debug.Print "Check is now: " & Check1.Value End Sub ``` ## 三态行为 [**Value**](#value)的类型为[**CheckBoxConstants**](/official/Reference/VBRUN/Constants/CheckBoxConstants): | 常量 | 值 | 含义 | |------------------|----|----------------------------------------| | **vbUnchecked** | 0 | 勾选已清除。 | | **vbChecked** | 1 | 勾选已选中。 | | **vbGrayed** | 2 | 勾选处于不确定(灰色)状态。 | 用户点击仅在**vbChecked**和**vbUnchecked**之间切换**Value**。灰色状态只能从代码到达——赋值**vbGrayed**给**Value**以显示。 ```vb Check1.Value = vbGrayed ' show the indeterminate state ``` ## 绘制模式 [**VisualStyles**](#visualstyles)选择字形的渲染方式: * **VisualStyles = False**(默认)——使用GDI **DrawFrameControl**原语绘制。遵循[**Appearance**](#appearance):**vbAppear3d**使用经典的凸起/凹陷外观,**vbAppearFlat**使用单像素轮廓。禁用的勾选或处于**vbGrayed**状态的勾选在虚线三态图案上绘制。 * **VisualStyles = True**——通过操作系统主题引擎(UXTHEME)绘制,因此字形使用当前视觉样式主题。此模式下**Appearance**被忽略。 ## 背景 [**BackStyle**](#backstyle)控制字形后面的矩形区域在绘制字形之前是否填充: * **vbBFTransparent**(默认)——仅绘制字形;容器绘制的内容透过显示。 * **vbBFOpaque**——先用[**BackColor**](#backcolor)填充矩形。 ## 属性 ### Anchors 决定控件的哪些边随容器对应边调整的**Anchors**对象。只读——通过返回的对象设置各个边。 ### Appearance 当[**VisualStyles**](#visualstyles)为**False**时字形的阴影方式。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppear3d**(默认)或**vbAppearFlat**。当[**VisualStyles**](#visualstyles)为**True**时被忽略。 ### BackColor 背景色,作为**OLE\_COLOR**。默认为系统3D表面颜色。仅在[**BackStyle**](#backstyle)为**vbBFOpaque**时使用。 ### BackStyle 控件在绘制字形之前是否填充其矩形区域。**BackFillStyleConstants**的成员:**vbBFTransparent**(默认)或**vbBFOpaque**。 ### Container 承载此**CheckMark**的直接容器(**Form**、**Frame**、**PictureBox**或其他容器控件)。用**Set**赋新值可将控件移动到不同的容器。 ### ControlType 标识此控件为勾选标记的只读[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值。始终为**vbCheckMark**。 ### Dock 控件是否填充容器的一条边或整个内部区域。**DockModeConstants**的成员,默认**vbDockNone**。 ### DragIcon 在控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自行拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual**(0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic**(1)。 ### Enabled 决定控件是否响应鼠标输入。禁用的**CheckMark**仍显示其当前值但变暗,忽略点击。**Boolean**,默认**True**。 ### Height 控件的高度,默认以缇为单位(或以容器的**ScaleMode**单位)。**Single**。 ### Index 当控件是控件数组的一部分时,此实例在数组中的**Long**零基索引。在非数组控件上读取**Index**会引发运行时错误343(*对象不是数组*)。运行时只读。 ### Left 从容器左边缘到控件左边缘的水平距离。**Single**。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针在控件上方时用作鼠标光标的**StdPicture**。 ### MousePointer 指针在控件上方时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### Parent 对包含此控件的**Form**(或**UserControl**)的引用。只读。 ### TabIndex ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。控件不可聚焦,因此该属性在运行时无效。 ::: ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### ToolTipText 用户悬停在控件上方时作为工具提示显示的多行**String**。 ### Top 从容器顶部到控件顶部的垂直距离。**Single**。 ### Value 勾选的当前状态。**默认属性。** 语法:*object*.**Value** \[ = *value* ] *value* : [**CheckBoxConstants**](/official/Reference/VBRUN/Constants/CheckBoxConstants)的成员:**vbUnchecked**(0)、**vbChecked**(1)或**vbGrayed**(2)。 用户点击仅在**vbChecked**和**vbUnchecked**之间切换**Value**;**vbGrayed**只能从代码设置。 ### Visible 控件是否显示。**Boolean**,默认**True**。 ### VisualStyles 当**True**时,字形通过操作系统主题引擎绘制;当**False**(默认)时,使用**DrawFrameControl**绘制并遵循[**Appearance**](#appearance)。**Boolean**。 ### WhatsThisHelpID 标识应用程序帮助文件中"这是什么?"帮助弹出主题的**Long**。参见[**ShowWhatsThis**](#showwhatsthis)。 ### Width 控件的宽度。**Single**。 ## 方法 ### Drag 开始、完成或取消手动拖放操作。通常在[**DragMode**](#dragmode)为**vbManual**时从[**MouseDown**](#mousedown)处理程序调用。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel**(0)、**vbBeginDrag**(1,默认)或**vbEndDrag**(2)。 ### Move 在单次调用中重新定位并可选地调整控件的尺寸。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从控件发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### Refresh 强制立即重绘控件。 语法:*object*.**Refresh** ### ShowWhatsThis 以"这是什么?"弹窗形式显示由[**WhatsThisHelpID**](#whatsthishelpid)标识的主题。 语法:*object*.**ShowWhatsThis** ### ZOrder 将控件带到同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront**(0,默认)或**vbSendToBack**(1)。 ## 事件 ### Click 当用户用左鼠标按钮点击控件时引发——在[**Value**](#value)在**vbChecked**和**vbUnchecked**之间切换之后。**默认事件。** 语法:*object*\_**Click**( ) ### DblClick 当用户双击控件时引发。 语法:*object*\_**DblClick**( ) ### DragDrop 当手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 当手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### MouseDown 当用户在控件上方按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 当光标在控件上方移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 当用户在控件上方释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag 当OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 当用户在目标控件上放置数据时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver 当OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 在拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的格式的数据时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag 在OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) --- --- url: /en/official/Reference/VBA/Interaction/Choose.md --- # Choose Selects and returns a value from a list of arguments by 1-based index. Syntax: **Choose(** *index* **,** *choice-1* \[ **,** *choice-2* **, ...** \[ **,** *choice-n* ] ] **)** *index* : *required* Numeric expression that evaluates to a value between 1 and the number of available choices. *choice* : *required* **Variant** expression containing one of the possible choices. If *index* is 1, **Choose** returns *choice-1*; if *index* is 2, it returns *choice-2*; and so on. If *index* is less than 1 or greater than the number of choices listed, **Choose** returns **Null**. Non-integer values of *index* are rounded to the nearest whole number before being evaluated. ::: info **Choose** evaluates *every* choice in the list, not only the one it returns. Watch for side effects: a [**MsgBox**](/en/official/Reference/VBA/Interaction/MsgBox) call inside any of the choices is invoked once per choice, not just for the selected one. To avoid this --- for example, when one of the branches would error out --- use the short-circuiting [**If**](/en/official/Reference/VBA/Interaction/If) function instead. ::: ### Example This example uses **Choose** to map a 1-based option index to a name. ```vb Function GetChoice(Ind As Integer) As String GetChoice = Choose(Ind, "Speedy", "United", "Federal") End Function ``` ### See Also * [If](/en/official/Reference/VBA/Interaction/If) function * [IIf](/en/official/Reference/VBA/Interaction/IIf) function * [Switch](/en/official/Reference/VBA/Interaction/Switch) function --- --- url: /zh/official/Reference/VBA/Interaction/Choose.md --- # Choose 按基于1的索引从参数列表中选择并返回一个值。 语法:**Choose(** *index* **,** *choice-1* \[ **,** *choice-2* **, ...** \[ **,** *choice-n* ] ] **)** *index* : *必需* 数值表达式,求值为1到可用选项数之间的值。 *choice* : *必需* **Variant**表达式,包含一个可能的选项。 如果*index*为1,**Choose**返回*choice-1*;如果*index*为2,返回*choice-2*;以此类推。如果*index*小于1或大于列出的选项数,**Choose**返回**Null**。*index*的非整数值在求值前四舍五入到最接近的整数。 ::: info **Choose**会评估列表中的*每个*选项,而不仅仅是它返回的那个。注意副作用:任何选项中的[**MsgBox**](/official/Reference/VBA/Interaction/MsgBox)调用会对每个选项调用一次,而不仅仅是选中的那个。要避免这种情况——例如当某个分支会出错时——请改用短路[**If**](/official/Reference/VBA/Interaction/If)函数。 ::: ### 示例 本示例使用**Choose**将基于1的选项索引映射到名称。 ```vb Function GetChoice(Ind As Integer) As String GetChoice = Choose(Ind, "Speedy", "United", "Federal") End Function ``` ### 另请参阅 * [If](/official/Reference/VBA/Interaction/If)函数 * [IIf](/official/Reference/VBA/Interaction/IIf)函数 * [Switch](/official/Reference/VBA/Interaction/Switch)函数 --- --- url: /en/official/Reference/VBA/Strings/Chr.md --- # Chr, ChrB, ChrW Returns a **String** containing the character associated with the specified character code. Syntax: * **Chr$(** *charcode* **)**, **Chr(** *charcode* **)** * **ChrB$(** *charcode* **)**, **ChrB(** *charcode* **)** * **ChrW$(** *charcode* **)**, **ChrW(** *charcode* **)** *charcode* : *required* A **Long** that identifies a character. The `$`-suffixed forms return a **String**; the unsuffixed forms return a **Variant** (**String**). Numbers from 0--31 are the same as standard, nonprintable ASCII codes. For example, `Chr(10)` returns a linefeed character. The normal range for *charcode* is 0--255. However, on DBCS systems, the actual range for *charcode* is -32768--65535. ::: info The **ChrB** function is used with byte data contained in a **String**. Instead of returning a character, which may be one or two bytes, **ChrB** always returns a single byte. The **ChrW** function returns a **String** containing the Unicode character. ::: The functions [**Asc**, **AscB**, and **AscW**](/en/official/Reference/VBA/Strings/Asc) are the opposite of **Chr**, **ChrB**, and **ChrW**. The **Asc** functions convert a string to an integer. ### Example This example uses the **Chr** function to return the character associated with the specified character code. ```vb Dim MyChar MyChar = Chr(65) ' Returns A. MyChar = Chr(97) ' Returns a. MyChar = Chr(62) ' Returns >. MyChar = Chr(37) ' Returns %. ``` ### See Also * [Asc](/en/official/Reference/VBA/Strings/Asc) function --- --- url: /zh/official/Reference/VBA/Strings/Chr.md --- # Chr, ChrB, ChrW 返回一个**String**,包含与指定字符代码相关联的字符。 语法: * **Chr$(** *charcode* **)**, **Chr(** *charcode* **)** * **ChrB$(** *charcode* **)**, **ChrB(** *charcode* **)** * **ChrW$(** *charcode* **)**, **ChrW(** *charcode* **)** *charcode* : *必需* 一个标识字符的**Long**。 带`$`后缀的形式返回**String**;不带后缀的形式返回**Variant**(**String**)。 0--31的数字与标准的不可打印ASCII码相同。例如,`Chr(10)`返回换行符。*charcode*的正常范围为0--255。但在DBCS系统上,*charcode*的实际范围为-32768--65535。 ::: info **ChrB**函数用于处理**String**中包含的字节数据。**ChrB**不返回可能是一个或两个字节的字符,而是始终返回单个字节。 **ChrW**函数返回包含Unicode字符的**String**。 ::: 函数[**Asc**、**AscB**和**AscW**](/official/Reference/VBA/Strings/Asc)与**Chr**、**ChrB**和**ChrW**互为相反。**Asc**函数将字符串转换为整数。 ### 示例 本示例使用**Chr**函数返回与指定字符代码相关联的字符。 ```vb Dim MyChar MyChar = Chr(65) ' Returns A. MyChar = Chr(97) ' Returns a. MyChar = Chr(62) ' Returns >. MyChar = Chr(37) ' Returns %. ``` ### 另请参阅 * [Asc](/official/Reference/VBA/Strings/Asc)函数 --- --- url: /en/official/Reference/VBA/Conversion/CInt.md --- # CInt Coerces an expression to an **Integer**. Syntax: **CInt(** *expression* **)** *expression* : *required* Any valid string or numeric expression in the range `-32,768` to `32,767`. Fractions are rounded. The return type is **Integer**. If *expression* is outside the range of an **Integer**, a run-time error occurs. When the fractional part is exactly `0.5`, **CInt** always rounds it to the nearest even number. For example, `0.5` rounds to `0`, and `1.5` rounds to `2`. **CInt** differs from the [**Fix**](/en/official/Reference/VBA/Conversion/Fix) and [**Int**](/en/official/Reference/VBA/Conversion/Int) functions, which truncate, rather than round, the fractional part of a number. Also, **Fix** and **Int** always return a value of the same type as is passed in. **CInt** is the internationally aware alternative to [**Val**](/en/official/Reference/VBA/Conversion/Val) for converting a string to a numeric type. ### Example This example uses the **CInt** function to convert a value to an **Integer**. ```vb Dim MyDouble, MyInt MyDouble = 2345.5678 ' MyDouble is a Double. MyInt = CInt(MyDouble) ' MyInt contains 2346. ``` ### See Also * [CBool](/en/official/Reference/VBA/Conversion/CBool), [CByte](/en/official/Reference/VBA/Conversion/CByte), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CLngLng](/en/official/Reference/VBA/Conversion/CLngLng), [CSng](/en/official/Reference/VBA/Conversion/CSng), [CStr](/en/official/Reference/VBA/Conversion/CStr), [CVar](/en/official/Reference/VBA/Conversion/CVar) functions * [Fix](/en/official/Reference/VBA/Conversion/Fix), [Int](/en/official/Reference/VBA/Conversion/Int) functions --- --- url: /zh/official/Reference/VBA/Conversion/CInt.md --- # CInt 将表达式强制转换为 **Integer**。 语法:**CInt(** *expression* **)** *expression* : *必需* 范围在 `-32,768` 到 `32,767` 之间的任何有效字符串或数值表达式。小数部分会四舍五入。 返回类型为 **Integer**。如果 *expression* 超出 **Integer** 的范围,将发生运行时错误。 当小数部分恰好为 `0.5` 时,**CInt** 始终舍入到最接近的偶数。例如,`0.5` 舍入为 `0`,`1.5` 舍入为 `2`。**CInt** 与 [**Fix**](/official/Reference/VBA/Conversion/Fix) 和 [**Int**](/official/Reference/VBA/Conversion/Int) 函数不同,后者截断而非舍入数字的小数部分。此外,**Fix** 和 **Int** 始终返回与传入值相同类型的值。 **CInt** 是替代 [**Val**](/official/Reference/VBA/Conversion/Val) 将字符串转换为数值类型的区域感知方案。 ### 示例 此示例使用 **CInt** 函数将值转换为 **Integer**。 ```vb Dim MyDouble, MyInt MyDouble = 2345.5678 ' MyDouble is a Double. MyInt = CInt(MyDouble) ' MyInt contains 2346. ``` ### 另请参阅 * [CBool](/official/Reference/VBA/Conversion/CBool)、[CByte](/official/Reference/VBA/Conversion/CByte)、[CLng](/official/Reference/VBA/Conversion/CLng)、[CLngLng](/official/Reference/VBA/Conversion/CLngLng)、[CSng](/official/Reference/VBA/Conversion/CSng)、[CStr](/official/Reference/VBA/Conversion/CStr)、[CVar](/official/Reference/VBA/Conversion/CVar) 函数 * [Fix](/official/Reference/VBA/Conversion/Fix)、[Int](/official/Reference/VBA/Conversion/Int) 函数 --- --- url: /en/official/Reference/Core/Class.md --- # Class Defines a class. Classes are templates from which objects are created --- classes are object types, as opposed to value types. Objects are held by reference and are reference-counted. The memory an object occupies is freed when there are no more references to it --- when no variables in the process refer to them. Syntax: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Class** *name* \[ **(** **Of** *typevars* **)** ]\ >     \[ **Inherits** *baseclass* ]\ >     \[ *classmember* ]\ >     \[ *classmember* ] ...\ > **End Class** *attributes* : *optional* One or more of:\ [ArrayBoundsChecks](/en/official/Reference/Attributes#arrayboundschecks), [ClassId](/en/official/Reference/Attributes#classid), [COMCreatable](/en/official/Reference/Attributes#comcreatable), [CustomControl](/en/official/Reference/Attributes#customcontrol), [Description](/en/official/Reference/Attributes#description), [FloatingPointErrorChecks](/en/official/Reference/Attributes#floatingpointerrorchecks), [FormDesignerId](/en/official/Reference/Attributes#formdesignerid), [Hidden](/en/official/Reference/Attributes#hidden), [IntegerOverflowChecks](/en/official/Reference/Attributes#integeroverflowchecks), [PredeclaredID](/en/official/Reference/Attributes#predeclaredid) **Public** : *optional* (twinBASIC) In an ActiveX project, marks the class as exported into the type library so that consumers in other projects can create and use it. **Private** : *optional* (twinBASIC) In an ActiveX project, withholds the class from the type library: it remains usable within the project but is not exported. The conventional pairing with [**CoClass**](/en/official/Reference/Core/CoClass) --- a public **CoClass** as the consumer-visible contract paired with a `Private Class` as the hidden implementation --- relies on this modifier. *name* : The identifier naming the class. **Of** *typevars* : *optional* (twinBASIC) One or more type variable names, separated by commas, that make the class a *generic class*. Each type variable can be referenced in member declarations as if it were a regular type. See [Generics](/en/official/Features/Language/Generics). **Inherits** *baseclass* : *optional* (twinBASIC) Names a single base class whose **Public** and [**Protected**](/en/official/Reference/Core/Protected) members are inherited by *name*. The **Inherits** line, when present, must appear immediately after the **Class** header and before any other member. **Inherits** enables [**Overridable**](/en/official/Reference/Core/Sub) / **Overrides** members, explicit `*baseclass*.New(...)` chained constructor calls from inside `Sub New`, and **Protected** member visibility. See [Inheritance](/en/official/Features/Language/Inheritance). *classmember* : *optional* Any of the following: * [constant](/en/official/Reference/Glossary#constant) defined using [**Const**](/en/official/Reference/Core/Const), * [variable](/en/official/Reference/Glossary#variable) defined using [**Public**](/en/official/Reference/Core/Public), [**Protected**](/en/official/Reference/Core/Protected), [**Private**](/en/official/Reference/Core/Private), or [**Dim**](/en/official/Reference/Core/Dim), * [procedure](/en/official/Reference/Glossary#procedure) defined using [**Sub**](/en/official/Reference/Core/Sub), [**Function**](/en/official/Reference/Core/Function), or [**Property**](/en/official/Reference/Core/Property) --- including the special instance constructor `Sub New(`*args*`)`, which the runtime invokes when the class is created with [**New**](/en/official/Reference/Core/New), * [user-defined type (UDTs)](/en/official/Reference/Glossary#user-defined-type) defined using [**Type**](/en/official/Reference/Core/Type), * (twinBASIC) [**Implements**](/en/official/Reference/Core/Implements) clauses, listing interfaces or classes whose members this class provides bodies for. In `.twin` files, a **Class** block may share a file with [**Interface**](/en/official/Reference/Core/Interface), [**CoClass**](/en/official/Reference/Core/CoClass), and [**Alias**](/en/official/Reference/Core/Alias) declarations (which appear *before* the **Class** block) and with a [**Module**](/en/official/Reference/Core/Module) block. In legacy `.cls` files the class is implicit and the **Class**/**End Class** keywords are not written. ### See Also * [**Module** statement](/en/official/Reference/Core/Module) * [**Interface** statement](/en/official/Reference/Core/Interface) * [**CoClass** statement](/en/official/Reference/Core/CoClass) * [**Implements** statement](/en/official/Reference/Core/Implements) * [**Protected** statement](/en/official/Reference/Core/Protected) * [**New** statement](/en/official/Reference/Core/New) * [Inheritance](/en/official/Features/Language/Inheritance) * [Generics](/en/official/Features/Language/Generics) --- --- url: /zh/official/Reference/Core/Class.md --- # Class 定义类。类是创建对象的模板——类是对象类型,与值类型相对。对象通过引用持有并采用引用计数。当不再有引用指向对象时——即进程中没有变量引用它们时——对象占用的内存会被释放。 语法: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Class** *name* \[ **(** **Of** *typevars* **)** ]\ >     \[ **Inherits** *baseclass* ]\ >     \[ *classmember* ]\ >     \[ *classmember* ] ...\ > **End Class** *attributes* : *可选* 以下一个或多个:\ [ArrayBoundsChecks](/official/Reference/Attributes#arrayboundschecks)、[ClassId](/official/Reference/Attributes#classid)、[COMCreatable](/official/Reference/Attributes#comcreatable)、[CustomControl](/official/Reference/Attributes#customcontrol)、[Description](/official/Reference/Attributes#description)、[FloatingPointErrorChecks](/official/Reference/Attributes#floatingpointerrorchecks)、[FormDesignerId](/official/Reference/Attributes#formdesignerid)、[Hidden](/official/Reference/Attributes#hidden)、[IntegerOverflowChecks](/official/Reference/Attributes#integeroverflowchecks)、[PredeclaredID](/official/Reference/Attributes#predeclaredid) **Public** : *可选* (twinBASIC) 在ActiveX项目中,将类标记为导出到类型库,使其他项目的使用者可以创建和使用它。 **Private** : *可选* (twinBASIC) 在ActiveX项目中,不将类导出到类型库:它在项目内仍可使用但不导出。与 [**CoClass**](/official/Reference/Core/CoClass) 的常规搭配——一个公共 **CoClass** 作为使用者可见的契约,配对一个 `Private Class` 作为隐藏的实现——依赖此修饰符。 *name* : 命名类的标识符。 **Of** *typevars* : *可选* (twinBASIC) 一个或多个用逗号分隔的类型变量名,使类成为*泛型类*。每个类型变量可以在成员声明中像常规类型一样被引用。参见[泛型](/official/Features/Language/Generics)。 **Inherits** *baseclass* : *可选* (twinBASIC) 指定一个基类,其 **Public** 和 [**Protected**](/official/Reference/Core/Protected) 成员被 *name* 继承。**Inherits** 行(如果存在)必须紧跟在 **Class** 头部之后、任何其他成员之前。**Inherits** 启用 [**Overridable**](/official/Reference/Core/Sub) / **Overrides** 成员、从 `Sub New` 内部的显式 `*baseclass*.New(...)` 链式构造函数调用,以及 **Protected** 成员可见性。参见[继承](/official/Features/Language/Inheritance)。 *classmember* : *可选* 以下任意项: * 使用 [**Const**](/official/Reference/Core/Const) 定义的[常量](/official/Reference/Glossary#constant), * 使用 [**Public**](/official/Reference/Core/Public)、[**Protected**](/official/Reference/Core/Protected)、[**Private**](/official/Reference/Core/Private) 或 [**Dim**](/official/Reference/Core/Dim) 定义的[变量](/official/Reference/Glossary#variable), * 使用 [**Sub**](/official/Reference/Core/Sub)、[**Function**](/official/Reference/Core/Function) 或 [**Property**](/official/Reference/Core/Property) 定义的[过程](/official/Reference/Glossary#procedure)——包括特殊的实例构造函数 `Sub New(`*args*`)`,当使用 [**New**](/official/Reference/Core/New) 创建类时运行时将调用它, * 使用 [**Type**](/official/Reference/Core/Type) 定义的[用户自定义类型(UDT)](/official/Reference/Glossary#user-defined-type), * (twinBASIC) [**Implements**](/official/Reference/Core/Implements) 子句,列出了此类提供实现的接口或类的成员。 在 `.twin` 文件中,**Class** 块可以与 [**Interface**](/official/Reference/Core/Interface)、[**CoClass**](/official/Reference/Core/CoClass) 和 [**Alias**](/official/Reference/Core/Alias) 声明(出现在 **Class** 块*之前*)以及 [**Module**](/official/Reference/Core/Module) 块共享同一文件。在传统 `.cls` 文件中,类是隐式的,不写 **Class**/**End Class** 关键字。 ### 另请参阅 * [**Module** 语句](/official/Reference/Core/Module) * [**Interface** 语句](/official/Reference/Core/Interface) * [**CoClass** 语句](/official/Reference/Core/CoClass) * [**Implements** 语句](/official/Reference/Core/Implements) * [**Protected** 语句](/official/Reference/Core/Protected) * [**New** 语句](/official/Reference/Core/New) * [继承](/official/Features/Language/Inheritance) * [泛型](/official/Features/Language/Generics) --- --- url: /en/official/Features/Advanced/Classes-and-Modules.md --- # Class and Module Enhancements twinBASIC provides several enhancements for classes and modules. ## Parameterized Class Constructors Classes now support a `New` sub with ability to add arguments, called as the class is constructed prior to the `Class_Initialize` event. ### Example For example a class can have: ```vb [ComCreatable(False)] Class MyClass Private MyClassVar As Long Sub New(Value As Long) MyClassVar = Value End Sub End Class ``` then created by `Dim mc As MyClass = New MyClass(123)` which sets `MyClassVar` on create. Note: Classes using this must be private, have the `[ComCreatable(False)]` attribute, or also contain `Class_Initialize()`. `Class_Initialize()` will replace `New` in callers of a compiled OCX. Within the project, only `New` will be used if present. ## Private/Public Modifiers for Modules and Classes A private module or class won't have its members entered into the type library in an ActiveX project. ## ReadOnly Variables In a class, module-level variables can be declared as `ReadOnly`, e.g. `Private ReadOnly mStartDate As Date`. This allows more complex constant assignments: you can use a function return to set it inline, `Private ReadOnly mStartDate As Date = Now()`, or `ReadOnly` constants can be set in `Class_Initialize` or `Sub New(...)` (see parameterized class constructors above), but everywhere else, they can only be read, not changed. ## Exported Functions and Variables It's possible to export a function or variable from standard modules, including with CDecl. ### Examples ```vb [DllExport] Public Const MyExportedSymbol As Long = &H00000001 [DllExport] Public Function MyExportedFunction(ByVal arg As Long) As Long [DllExport] Public Function MyCDeclExport CDecl(ByVal arg As Long) ``` This is primarily used to create Standard DLLs (see [Project Types](/en/official/Features/Project-Configuration/Project-Types)), but this functionality is also available in Standard EXE and other compiled project types. ## Create classes without `IDispatch` By default, the compiler creates a default implementation of `IDispatch` in all VBx/twinBASIC classes. This allows late-binding and other features. Sometimes however you want a more limited class that only implements `IUnknown`. This is possible in twinBASIC via the `NotDispatchable` keyword, used like this: ```vb NotDispatchable Class MyClass '... End Class ``` With the above, `MyClass` will not implement `IDispatch`. This means it will not be available for late-binding-- i.e. you cannot use it with a variable declared `As Object`. If you attempt to `Set` an `Object` (or `IDispatch`) variable to such a class, it will raise an `E_NOINTERFACE` error. --- --- url: /en/official/Reference/VBA/Collection/Clear.md --- # Clear Removes all elements from a **Collection** object. After **Clear** returns, the collection's [**Count**](/en/official/Reference/VBA/Collection/Count) is zero. Syntax: *object*.**Clear** *object* : *required* An object expression that evaluates to a **Collection** object. ::: info **Clear** is a twinBASIC extension; the classic VBA **Collection** object has no **Clear** method. The same effect in VBA requires repeatedly removing the first item until the collection is empty. ::: **Clear** resets a **Collection** to its initial, empty state --- useful when the object is to be reused without creating a new instance. ### Example ```vb Dim MyClasses As New Collection MyClasses.Add "first" MyClasses.Add "second" MyClasses.Add "third" Debug.Print MyClasses.Count ' Prints 3. MyClasses.Clear Debug.Print MyClasses.Count ' Prints 0. ``` ### See Also * [Count](/en/official/Reference/VBA/Collection/Count) property * [Remove](/en/official/Reference/VBA/Collection/Remove) method --- --- url: /en/official/Reference/VBA/ErrObject/Clear.md --- # Clear Clears all property settings of the **Err** object --- [**Number**](/en/official/Reference/VBA/ErrObject/Number) is reset to **0**, the string properties to zero-length strings, and [**HelpContext**](/en/official/Reference/VBA/ErrObject/HelpContext) to **0**. Syntax: **Err**.**Clear** Use **Clear** to explicitly reset the **Err** object after an error has been handled, for example when using deferred error handling with **On Error Resume Next**. **Clear** is also called automatically whenever any of the following statements is executed: * Any form of **Resume** * **Exit Sub**, **Exit Function**, **Exit Property** * Any **On Error** statement ::: info The **On Error Resume Next** construct may be preferable to **On Error GoTo** when handling errors generated during access to other objects. Checking **Err** after each interaction with an object removes ambiguity about which object the error came from --- both the object that placed the code in [**Err.Number**](/en/official/Reference/VBA/ErrObject/Number) and the object that originally generated the error (specified in [**Err.Source**](/en/official/Reference/VBA/ErrObject/Source)) can be identified, and they may be distinct. ::: ### Example This example uses **Err.Clear** to reset the **Err** object's numeric properties to zero and its string properties to zero-length strings between iterations of a loop. If **Clear** were omitted, the error message dialog box would be displayed on every iteration after an error first occurred --- whether or not the next calculation actually generated an error. ```vb Dim result(10) As Integer ' Declare an array whose elements ' will overflow. Dim idx As Long On Error Resume Next ' Defer error trapping. Do Until idx = 10 ' Generate an occasional error, or store the result if no error. result(idx) = Rnd * idx * 20000 If Err.Number <> 0 Then MsgBox Err, , "Error generated: ", Err.HelpFile, Err.HelpContext Err.Clear ' Clear Err object properties. End If idx = idx + 1 Loop ``` ### See Also * [Number](/en/official/Reference/VBA/ErrObject/Number) property * [Description](/en/official/Reference/VBA/ErrObject/Description) property * [Source](/en/official/Reference/VBA/ErrObject/Source) property * [Raise](/en/official/Reference/VBA/ErrObject/Raise) method --- --- url: /en/official/Reference/VBRUN/DataObject/Clear.md --- # Clear Removes every value and format from the **DataObject**, returning it to the empty state it had immediately after **New**. Syntax: *object*.**Clear** *object* : *required* An object expression that evaluates to a **DataObject**. After **Clear** returns, [**GetFormat**](/en/official/Reference/VBRUN/DataObject/GetFormat) reports **False** for every format and [**AvailableFormats**](/en/official/Reference/VBRUN/DataObject/AvailableFormats) is empty. Use **Clear** when reusing a single **DataObject** for several operations, so that values from the previous operation cannot leak into the next one. ### Example ```vb Dim Data As New DataObject Data.SetData "First payload", vbCFText ' ... use Data ... Data.Clear Data.SetData "Second payload", vbCFText ``` ### See Also * [SetData](/en/official/Reference/VBRUN/DataObject/SetData) method * [AvailableFormats](/en/official/Reference/VBRUN/DataObject/AvailableFormats) method --- --- url: /zh/official/Reference/VBA/ErrObject/Clear.md --- # Clear 清除 **Err** 对象的所有属性设置——[**Number**](/official/Reference/VBA/ErrObject/Number) 重置为 **0**,字符串属性重置为零长度字符串,[**HelpContext**](/official/Reference/VBA/ErrObject/HelpContext) 重置为 **0**。 语法:**Err**.**Clear** 在处理错误后使用 **Clear** 显式重置 **Err** 对象,例如在使用 **On Error Resume Next** 进行延迟错误处理时。在执行以下任一语句时,也会自动调用 **Clear**: * 任何形式的 **Resume** * **Exit Sub**、**Exit Function**、**Exit Property** * 任何 **On Error** 语句 ::: info 当处理访问其他对象时产生的错误时,**On Error Resume Next** 构造可能比 **On Error GoTo** 更可取。在与对象每次交互后检查 **Err** 可消除错误来源的歧义——将代码放入 [**Err.Number**](/official/Reference/VBA/ErrObject/Number) 的对象和最初生成错误的对象(在 [**Err.Source**](/official/Reference/VBA/ErrObject/Source) 中指定)都可以被识别,它们可能是不同的。 ::: ### 示例 此示例使用 **Err.Clear** 在循环的每次迭代之间将 **Err** 对象的数值属性重置为零,字符串属性重置为零长度字符串。如果省略 **Clear**,则在首次发生错误后的每次迭代中都会显示错误消息对话框——无论下一次计算是否实际产生了错误。 ```vb Dim result(10) As Integer ' Declare an array whose elements ' will overflow. Dim idx As Long On Error Resume Next ' Defer error trapping. Do Until idx = 10 ' Generate an occasional error, or store the result if no error. result(idx) = Rnd * idx * 20000 If Err.Number <> 0 Then MsgBox Err, , "Error generated: ", Err.HelpFile, Err.HelpContext Err.Clear ' Clear Err object properties. End If idx = idx + 1 Loop ``` ### 另请参阅 * [Number](/official/Reference/VBA/ErrObject/Number) 属性 * [Description](/official/Reference/VBA/ErrObject/Description) 属性 * [Source](/official/Reference/VBA/ErrObject/Source) 属性 * [Raise](/official/Reference/VBA/ErrObject/Raise) 方法 --- --- url: /zh/official/Reference/VBRUN/DataObject/Clear.md --- # Clear 从**DataObject**中移除所有值和格式,将其恢复到**New**后的初始空状态。 语法:*object*.**Clear** *object* : *必需* 求值为**DataObject**的对象表达式。 **Clear**返回后,[**GetFormat**](/official/Reference/VBRUN/DataObject/GetFormat)对每种格式报告**False**,[**AvailableFormats**](/official/Reference/VBRUN/DataObject/AvailableFormats)为空。在重用单个**DataObject**进行多次操作时使用**Clear**,以防止前一次操作的值泄漏到下一次。 ### 示例 ```vb Dim Data As New DataObject Data.SetData "First payload", vbCFText ' ... 使用Data ... Data.Clear Data.SetData "Second payload", vbCFText ``` ### 另见 * [SetData](/official/Reference/VBRUN/DataObject/SetData) 方法 * [AvailableFormats](/official/Reference/VBRUN/DataObject/AvailableFormats) 方法 --- --- url: /zh/official/Reference/VBA/Collection/Clear.md --- # Clear 移除 **Collection** 对象中的所有元素。**Clear** 返回后,集合的 [**Count**](/official/Reference/VBA/Collection/Count) 为零。 语法:*object*.**Clear** *object* : *必需* 一个计算结果为 **Collection** 对象的对象表达式。 ::: info **Clear** 是 twinBASIC 扩展;经典 VBA 的 **Collection** 对象没有 **Clear** 方法。在 VBA 中要实现相同效果,需要反复移除第一项,直到集合为空。 ::: **Clear** 将 **Collection** 重置为初始的空状态——当需要重用对象而不创建新实例时非常有用。 ### 示例 ```vb Dim MyClasses As New Collection MyClasses.Add "first" MyClasses.Add "second" MyClasses.Add "third" Debug.Print MyClasses.Count ' Prints 3. MyClasses.Clear Debug.Print MyClasses.Count ' Prints 0. ``` ### 另请参阅 * [Count](/official/Reference/VBA/Collection/Count) 属性 * [Remove](/official/Reference/VBA/Collection/Remove) 方法 --- --- url: /en/official/Reference/VB/Clipboard.md --- # Clipboard class The **Clipboard** class wraps the system clipboard --- the Win32 inter-application copy-and-paste API --- and exposes it as a singleton object. Code reads and writes text, queries which formats are currently available, and (eventually --- see [the picture caveat](#picture-data)) reads and writes pictures. **Clipboard** is not creatable: there is exactly one instance per process, owned by the runtime and exposed through the [**Clipboard**](/en/official/Reference/VB/Global/#clipboard) property on the [**Global**](/en/official/Reference/VB/Global/) app-object. Code reaches it without qualification: ```vb ' Copy Clipboard.Clear Clipboard.SetText "Hello, world!" ' Paste If Clipboard.GetFormat(vbCFText) Then txtEditor.Text = Clipboard.GetText() End If ``` ## Formats Clipboard contents are tagged with a *format* --- text, bitmap, files, rich text, and so on. The [**ClipboardConstants**](/en/official/Reference/VBRUN/Constants/ClipboardConstants) enum lists the predefined formats: | Constant | Value | Meaning | |-----------------------|-------|------------------------------------------------| | **vbCFText** | 1 | ANSI plain text. | | **vbCFBitmap** | 2 | DDB (device-dependent bitmap). | | **vbCFMetafile** | 3 | Windows metafile (`WMF`). | | **vbCFDIB** | 8 | DIB (device-independent bitmap). | | **vbCFPalette** | 9 | Colour palette. | | **vbCFUnicodeText** | 13 | UTF-16 plain text. | | **vbCFEMetafile** | 14 | Enhanced metafile (`EMF`). | | **vbCFFiles** | 15 | A list of file paths (`CF_HDROP`). | | **vbCFLink** | `&HFFFFBF00` | DDE link (legacy OLE-1 link source). | | **vbCFRTF** | `&HFFFFBF01` | Rich Text Format. | The [**GetText**](#gettext) / [**SetText**](#settext) methods take an optional *Format* argument constrained to the text-shaped subset (**vbCFText**, **vbCFUnicodeText**, **vbCFRTF**, **vbCFLink**). The [**GetData**](#getdata) / [**SetData**](#setdata) methods handle pictures, restricted to the bitmap and metafile formats. ## Picture data The picture methods --- [**GetData**](#getdata) and [**SetData**](#setdata) --- are declared but not yet connected. ::: info [**GetData**](#getdata) and [**SetData**](#setdata) are reserved for compatibility with VB6; they are not currently implemented in twinBASIC. For picture-clipboard interop, use the Win32 clipboard API (`OpenClipboard`, `GetClipboardData`, `SetClipboardData`, `CloseClipboard`) directly until the implementation lands. ::: [**Clear**](#clear), [**GetText**](#gettext), [**SetText**](#settext), and [**GetFormat**](#getformat) are all fully functional. ## Methods ### Clear Empties the clipboard, removing every format currently on it. Syntax: *object*.**Clear** ### GetData Reads picture data from the clipboard. Returns the result as a **stdole.StdPicture**. Syntax: *object*.**GetData**( \[ *Format* ] ) *Format* : *optional* A member of [**ClipboardConstants**](/en/official/Reference/VBRUN/Constants/ClipboardConstants) selecting which picture format to retrieve (**vbCFBitmap**, **vbCFDIB**, **vbCFMetafile**, **vbCFEMetafile**, or **vbCFPalette**). When omitted, the implementation picks the most descriptive format the clipboard currently holds. ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### GetFormat Tests whether the clipboard currently contains data in the given format. Returns **True** if it does, **False** otherwise. Syntax: *object*.**GetFormat**( *Format* ) *Format* : *required* A member of [**ClipboardConstants**](/en/official/Reference/VBRUN/Constants/ClipboardConstants) --- the format to probe for. ```vb If Clipboard.GetFormat(vbCFFiles) Then ' The clipboard holds a file list (e.g. from Explorer copy) End If ``` ### GetText Reads text data from the clipboard. Returns a **String**; returns an empty string if the clipboard does not currently hold data in the requested format. Syntax: *object*.**GetText**( \[ *Format* ] ) *Format* : *optional* A member of [**ClipboardConstants**](/en/official/Reference/VBRUN/Constants/ClipboardConstants) selecting which text format to retrieve: **vbCFText** (default), **vbCFUnicodeText**, **vbCFRTF**, or **vbCFLink**. ```vb Dim s As String s = Clipboard.GetText() ' plain text Dim rtf As String rtf = Clipboard.GetText(vbCFRTF) ' RTF, if available ``` ### SetData Places picture data onto the clipboard. Syntax: *object*.**SetData** *Picture* \[, *Format* ] *Picture* : *required* A **stdole.StdPicture** holding the picture to copy. *Format* : *optional* A member of [**ClipboardConstants**](/en/official/Reference/VBRUN/Constants/ClipboardConstants) --- which picture format to publish. When omitted, the format is inferred from the picture's underlying type. ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### SetText Places text data onto the clipboard. Note that **SetText** does *not* implicitly clear the clipboard first --- call [**Clear**](#clear) explicitly to ensure that no stale data of other formats survives alongside the new value. Syntax: *object*.**SetText** *Str* \[, *Format* ] *Str* : *required* The **String** to publish. *Format* : *optional* A member of [**ClipboardConstants**](/en/official/Reference/VBRUN/Constants/ClipboardConstants) --- **vbCFText** (default), **vbCFUnicodeText**, **vbCFRTF**, or **vbCFLink**. ```vb Clipboard.Clear Clipboard.SetText "Plain text" Clipboard.SetText "{\rtf1 \b Bold \b0 plain.}", vbCFRTF ' add an RTF alternative ``` --- --- url: /zh/official/Reference/VB/Clipboard.md --- # Clipboard 类 **Clipboard** 类封装了系统剪贴板——即 Win32 进程间复制粘贴API——并将其作为单例对象公开。代码通过它可以读写文本、查询当前可用的格式,以及(最终——参见[图片数据注意事项](#picture-data))读写图片。 **Clipboard** 不可创建:每个进程只有一个实例,由运行时拥有,并通过[**Global**](/official/Reference/VB/Global/)应用对象的[**Clipboard**](/official/Reference/VB/Global/#clipboard)属性公开。代码无需限定即可访问: ```vb ' Copy Clipboard.Clear Clipboard.SetText "Hello, world!" ' Paste If Clipboard.GetFormat(vbCFText) Then txtEditor.Text = Clipboard.GetText() End If ``` ## 格式 剪贴板内容以*格式*标记——文本、位图、文件、富文本等。[**ClipboardConstants**](/official/Reference/VBRUN/Constants/ClipboardConstants)枚举列出了预定义的格式: | 常量 | 值 | 含义 | |-----------------------|-------------|--------------------------------------------| | **vbCFText** | 1 | ANSI纯文本。 | | **vbCFBitmap** | 2 | DDB(设备相关位图)。 | | **vbCFMetafile** | 3 | Windows图元文件(`WMF`)。 | | **vbCFDIB** | 8 | DIB(设备无关位图)。 | | **vbCFPalette** | 9 | 调色板。 | | **vbCFUnicodeText** | 13 | UTF-16纯文本。 | | **vbCFEMetafile** | 14 | 增强型图元文件(`EMF`)。 | | **vbCFFiles** | 15 | 文件路径列表(`CF_HDROP`)。 | | **vbCFLink** | `&HFFFFBF00` | DDE链接(旧版OLE-1链接源)。 | | **vbCFRTF** | `&HFFFFBF01` | 富文本格式。 | [**GetText**](#gettext) / [**SetText**](#settext)方法接受一个可选的*Format*参数,限制为文本类子集(**vbCFText**、**vbCFUnicodeText**、**vbCFRTF**、**vbCFLink**)。[**GetData**](#getdata) / [**SetData**](#setdata)方法处理图片,仅限于位图和图元文件格式。 ## 图片数据 图片方法——[**GetData**](#getdata)和[**SetData**](#setdata)——已声明但尚未连接。 ::: info [**GetData**](#getdata)和[**SetData**](#setdata)保留用于与VB6兼容;目前在twinBASIC中尚未实现。对于图片-剪贴板互操作,请直接使用Win32剪贴板API(`OpenClipboard`、`GetClipboardData`、`SetClipboardData`、`CloseClipboard`),直到该实现落地。 ::: [**Clear**](#clear)、[**GetText**](#gettext)、[**SetText**](#settext)和[**GetFormat**](#getformat)均已完全可用。 ## 方法 ### Clear 清空剪贴板,移除其上当前的所有格式。 语法:*object*.**Clear** ### GetData 从剪贴板读取图片数据。返回结果为**stdole.StdPicture**。 语法:*object*.**GetData**( \[ *Format* ] ) *Format* : *可选* [**ClipboardConstants**](/official/Reference/VBRUN/Constants/ClipboardConstants)的成员,选择要检索的图片格式(**vbCFBitmap**、**vbCFDIB**、**vbCFMetafile**、**vbCFEMetafile**或**vbCFPalette**)。省略时,实现会选择剪贴板当前持有的最具描述性的格式。 ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: ### GetFormat 测试剪贴板当前是否包含给定格式的数据。如果包含则返回**True**,否则返回**False**。 语法:*object*.**GetFormat**( *Format* ) *Format* : *必需* [**ClipboardConstants**](/official/Reference/VBRUN/Constants/ClipboardConstants)的成员——要探测的格式。 ```vb If Clipboard.GetFormat(vbCFFiles) Then ' The clipboard holds a file list (e.g. from Explorer copy) End If ``` ### GetText 从剪贴板读取文本数据。返回**String**;如果剪贴板当前不包含所请求格式的数据,则返回空字符串。 语法:*object*.**GetText**( \[ *Format* ] ) *Format* : *可选* [**ClipboardConstants**](/official/Reference/VBRUN/Constants/ClipboardConstants)的成员,选择要检索的文本格式:**vbCFText**(默认)、**vbCFUnicodeText**、**vbCFRTF**或**vbCFLink**。 ```vb Dim s As String s = Clipboard.GetText() ' plain text Dim rtf As String rtf = Clipboard.GetText(vbCFRTF) ' RTF, if available ``` ### SetData 将图片数据放到剪贴板上。 语法:*object*.**SetData** *Picture* \[, *Format* ] *Picture* : *必需* 持有要复制的图片的**stdole.StdPicture**。 *Format* : *可选* [**ClipboardConstants**](/official/Reference/VBRUN/Constants/ClipboardConstants)的成员——要发布的图片格式。省略时,格式从图片的基础类型推断。 ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: ### SetText 将文本数据放到剪贴板上。注意,**SetText** *不会*隐式地先清空剪贴板——需显式调用[**Clear**](#clear)以确保不会在新值旁边残留其他格式的过期数据。 语法:*object*.**SetText** *Str* \[, *Format* ] *Str* : *必需* 要发布的**String**。 *Format* : *可选* [**ClipboardConstants**](/official/Reference/VBRUN/Constants/ClipboardConstants)的成员——**vbCFText**(默认)、**vbCFUnicodeText**、**vbCFRTF**或**vbCFLink**。 ```vb Clipboard.Clear Clipboard.SetText "Plain text" Clipboard.SetText "{\rtf1 \b Bold \b0 plain.}", vbCFRTF ' add an RTF alternative ``` --- --- url: /en/official/Reference/VBRUN/Constants/ClipboardConstants.md --- # ClipboardConstants Standard clipboard format identifiers used by the [**DataObject**](/en/official/Reference/VBRUN/DataObject/) and **Clipboard** objects to choose how a value is stored or retrieved. | Constant | Value | Description | |----------|-------|-------------| | **vbCFText** | 1 | ANSI text. | | **vbCFBitmap** | 2 | Device-dependent bitmap (`HBITMAP`). | | **vbCFMetafile** | 3 | Windows metafile. | | **vbCFDIB** | 8 | Device-independent bitmap. | | **vbCFPalette** | 9 | Colour palette. | | **vbCFUnicodeText** | 13 | Unicode (UTF-16) text. | | **vbCFEMetafile** | 14 | Enhanced metafile. | | **vbCFFiles** | 15 | A list of file paths (typically from a Windows shell drag-drop). | | **vbCFLink** | \&HFFFFBF00 | A DDE link reference. | | **vbCFRTF** | \&HFFFFBF01 | Rich Text Format. | --- --- url: /zh/official/Reference/VBRUN/Constants/ClipboardConstants.md --- # ClipboardConstants [**DataObject**](/official/Reference/VBRUN/DataObject/)和**Clipboard**对象使用的标准剪贴板格式标识符,用于选择值的存储或检索方式。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbCFText** | 1 | ANSI文本。 | | **vbCFBitmap** | 2 | 设备相关位图(`HBITMAP`)。 | | **vbCFMetafile** | 3 | Windows元文件。 | | **vbCFDIB** | 8 | 设备无关位图。 | | **vbCFPalette** | 9 | 调色板。 | | **vbCFUnicodeText** | 13 | Unicode(UTF-16)文本。 | | **vbCFEMetafile** | 14 | 增强元文件。 | | **vbCFFiles** | 15 | 文件路径列表(通常来自Windows外壳拖放)。 | | **vbCFLink** | \&HFFFFBF00 | DDE链接引用。 | | **vbCFRTF** | \&HFFFFBF01 | 富文本格式。 | --- --- url: /en/official/Reference/VBA/Conversion/CLng.md --- # CLng Coerces an expression to a **Long**. Syntax: **CLng(** *expression* **)** *expression* : *required* Any valid string or numeric expression in the range `-2,147,483,648` to `2,147,483,647`. Fractions are rounded. The return type is **Long**. If *expression* is outside the range of a **Long**, a run-time error occurs. When the fractional part is exactly `0.5`, **CLng** always rounds it to the nearest even number. For example, `0.5` rounds to `0`, and `1.5` rounds to `2`. **CLng** differs from the [**Fix**](/en/official/Reference/VBA/Conversion/Fix) and [**Int**](/en/official/Reference/VBA/Conversion/Int) functions, which truncate, rather than round, the fractional part of a number. ### Example This example uses the **CLng** function to convert values to a **Long**. ```vb Dim MyVal1, MyVal2, MyLong1, MyLong2 MyVal1 = 25427.45: MyVal2 = 25427.55 ' MyVal1, MyVal2 are Doubles. MyLong1 = CLng(MyVal1) ' MyLong1 contains 25427. MyLong2 = CLng(MyVal2) ' MyLong2 contains 25428. ``` ### See Also * [CBool](/en/official/Reference/VBA/Conversion/CBool), [CByte](/en/official/Reference/VBA/Conversion/CByte), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLngLng](/en/official/Reference/VBA/Conversion/CLngLng), [CLngPtr](/en/official/Reference/VBA/Conversion/CLngPtr), [CSng](/en/official/Reference/VBA/Conversion/CSng), [CStr](/en/official/Reference/VBA/Conversion/CStr), [CVar](/en/official/Reference/VBA/Conversion/CVar) functions * [Fix](/en/official/Reference/VBA/Conversion/Fix), [Int](/en/official/Reference/VBA/Conversion/Int) functions --- --- url: /zh/official/Reference/VBA/Conversion/CLng.md --- # CLng 将表达式强制转换为 **Long**。 语法:**CLng(** *expression* **)** *expression* : *必需* 范围在 `-2,147,483,648` 到 `2,147,483,647` 之间的任何有效字符串或数值表达式。小数部分会四舍五入。 返回类型为 **Long**。如果 *expression* 超出 **Long** 的范围,将发生运行时错误。 当小数部分恰好为 `0.5` 时,**CLng** 始终舍入到最接近的偶数。例如,`0.5` 舍入为 `0`,`1.5` 舍入为 `2`。**CLng** 与 [**Fix**](/official/Reference/VBA/Conversion/Fix) 和 [**Int**](/official/Reference/VBA/Conversion/Int) 函数不同,后者截断而非舍入数字的小数部分。 ### 示例 此示例使用 **CLng** 函数将值转换为 **Long**。 ```vb Dim MyVal1, MyVal2, MyLong1, MyLong2 MyVal1 = 25427.45: MyVal2 = 25427.55 ' MyVal1, MyVal2 are Doubles. MyLong1 = CLng(MyVal1) ' MyLong1 contains 25427. MyLong2 = CLng(MyVal2) ' MyLong2 contains 25428. ``` ### 另请参阅 * [CBool](/official/Reference/VBA/Conversion/CBool)、[CByte](/official/Reference/VBA/Conversion/CByte)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLngLng](/official/Reference/VBA/Conversion/CLngLng)、[CLngPtr](/official/Reference/VBA/Conversion/CLngPtr)、[CSng](/official/Reference/VBA/Conversion/CSng)、[CStr](/official/Reference/VBA/Conversion/CStr)、[CVar](/official/Reference/VBA/Conversion/CVar) 函数 * [Fix](/official/Reference/VBA/Conversion/Fix)、[Int](/official/Reference/VBA/Conversion/Int) 函数 --- --- url: /en/official/Reference/VBA/Conversion/CLngLng.md --- # CLngLng Coerces an expression to a **LongLong**. Syntax: **CLngLng(** *expression* **)** *expression* : *required* Any valid string or numeric expression in the range `-9,223,372,036,854,775,808` to `9,223,372,036,854,775,807`. Fractions are rounded. The return type is **LongLong**. If *expression* is outside the range of a **LongLong**, a run-time error occurs. When the fractional part is exactly `0.5`, **CLngLng** always rounds it to the nearest even number. For example, `0.5` rounds to `0`, and `1.5` rounds to `2`. **CLngLng** differs from the [**Fix**](/en/official/Reference/VBA/Conversion/Fix) and [**Int**](/en/official/Reference/VBA/Conversion/Int) functions, which truncate, rather than round, the fractional part of a number. ::: info Conversion functions must be used to explicitly assign **LongLong** to smaller integral types. Implicit conversions of **LongLong** to smaller integrals are not allowed. ::: ::: info In VBA, **LongLong** (and therefore **CLngLng**) is restricted to 64-bit hosts. twinBASIC supports **LongLong** in both 32-bit and 64-bit modes --- see [Data Types](/en/official/Features/Language/Data-Types). ::: ### Example This example uses the **CLngLng** function to convert an expression to a **LongLong**. ```vb Dim someValue As Variant someValue = 9223372036854775807 Dim longLongValue As LongLong longLongValue = CLngLng(someValue) MsgBox "The LongLong representation is: " & longLongValue ``` ### See Also * [CBool](/en/official/Reference/VBA/Conversion/CBool), [CByte](/en/official/Reference/VBA/Conversion/CByte), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CLngPtr](/en/official/Reference/VBA/Conversion/CLngPtr), [CSng](/en/official/Reference/VBA/Conversion/CSng), [CStr](/en/official/Reference/VBA/Conversion/CStr), [CVar](/en/official/Reference/VBA/Conversion/CVar) functions --- --- url: /zh/official/Reference/VBA/Conversion/CLngLng.md --- # CLngLng 将表达式强制转换为 **LongLong**。 语法:**CLngLng(** *expression* **)** *expression* : *必需* 范围在 `-9,223,372,036,854,775,808` 到 `9,223,372,036,854,775,807` 之间的任何有效字符串或数值表达式。小数部分会四舍五入。 返回类型为 **LongLong**。如果 *expression* 超出 **LongLong** 的范围,将发生运行时错误。 当小数部分恰好为 `0.5` 时,**CLngLng** 始终舍入到最接近的偶数。例如,`0.5` 舍入为 `0`,`1.5` 舍入为 `2`。**CLngLng** 与 [**Fix**](/official/Reference/VBA/Conversion/Fix) 和 [**Int**](/official/Reference/VBA/Conversion/Int) 函数不同,后者截断而非舍入数字的小数部分。 ::: info 必须使用转换函数显式将 **LongLong** 赋值给较小的整数类型。不允许 **LongLong** 到较小整数类型的隐式转换。 ::: ::: info 在 VBA 中,**LongLong**(以及因此 **CLngLng**)仅限于 64 位宿主。twinBASIC 在 32 位和 64 位模式下都支持 **LongLong**——参见[数据类型](/official/Features/Language/Data-Types)。 ::: ### 示例 此示例使用 **CLngLng** 函数将表达式转换为 **LongLong**。 ```vb Dim someValue As Variant someValue = 9223372036854775807 Dim longLongValue As LongLong longLongValue = CLngLng(someValue) MsgBox "The LongLong representation is: " & longLongValue ``` ### 另请参阅 * [CBool](/official/Reference/VBA/Conversion/CBool)、[CByte](/official/Reference/VBA/Conversion/CByte)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLng](/official/Reference/VBA/Conversion/CLng)、[CLngPtr](/official/Reference/VBA/Conversion/CLngPtr)、[CSng](/official/Reference/VBA/Conversion/CSng)、[CStr](/official/Reference/VBA/Conversion/CStr)、[CVar](/official/Reference/VBA/Conversion/CVar) 函数 --- --- url: /en/official/Reference/VBA/Conversion/CLngPtr.md --- # CLngPtr Coerces an expression to a **LongPtr**. Syntax: **CLngPtr(** *expression* **)** *expression* : *required* Any valid string or numeric expression. The acceptable range is `-2,147,483,648` to `2,147,483,647` on 32-bit systems, and `-9,223,372,036,854,775,808` to `9,223,372,036,854,775,807` on 64-bit systems. Fractions are rounded. The return type is **LongPtr**, which is a **Long** on 32-bit systems and a **LongLong** on 64-bit systems. If *expression* is outside the valid range, a run-time error occurs. When the fractional part is exactly `0.5`, **CLngPtr** always rounds it to the nearest even number. **CLngPtr** differs from the [**Fix**](/en/official/Reference/VBA/Conversion/Fix) and [**Int**](/en/official/Reference/VBA/Conversion/Int) functions, which truncate, rather than round, the fractional part of a number. **LongPtr** is intended primarily for holding pointer values returned from API calls. See [Data Types](/en/official/Features/Language/Data-Types) for details. ### Example This example uses the **CLngPtr** function to convert an expression to a **LongPtr**. ```vb Dim num As Variant num = 1234567890 MsgBox "LongPtr value of " & num & " is " & CLngPtr(num) ``` ### See Also * [CBool](/en/official/Reference/VBA/Conversion/CBool), [CByte](/en/official/Reference/VBA/Conversion/CByte), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CLngLng](/en/official/Reference/VBA/Conversion/CLngLng), [CSng](/en/official/Reference/VBA/Conversion/CSng), [CStr](/en/official/Reference/VBA/Conversion/CStr), [CVar](/en/official/Reference/VBA/Conversion/CVar) functions --- --- url: /zh/official/Reference/VBA/Conversion/CLngPtr.md --- # CLngPtr 将表达式强制转换为 **LongPtr**。 语法:**CLngPtr(** *expression* **)** *expression* : *必需* 任何有效的字符串或数值表达式。可接受范围在 32 位系统上为 `-2,147,483,648` 到 `2,147,483,647`,在 64 位系统上为 `-9,223,372,036,854,775,808` 到 `9,223,372,036,854,775,807`。小数部分会四舍五入。 返回类型为 **LongPtr**,在 32 位系统上为 **Long**,在 64 位系统上为 **LongLong**。如果 *expression* 超出有效范围,将发生运行时错误。 当小数部分恰好为 `0.5` 时,**CLngPtr** 始终舍入到最接近的偶数。**CLngPtr** 与 [**Fix**](/official/Reference/VBA/Conversion/Fix) 和 [**Int**](/official/Reference/VBA/Conversion/Int) 函数不同,后者截断而非舍入数字的小数部分。 **LongPtr** 主要用于保存 API 调用返回的指针值。详见[数据类型](/official/Features/Language/Data-Types)。 ### 示例 此示例使用 **CLngPtr** 函数将表达式转换为 **LongPtr**。 ```vb Dim num As Variant num = 1234567890 MsgBox "LongPtr value of " & num & " is " & CLngPtr(num) ``` ### 另请参阅 * [CBool](/official/Reference/VBA/Conversion/CBool)、[CByte](/official/Reference/VBA/Conversion/CByte)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLng](/official/Reference/VBA/Conversion/CLng)、[CLngLng](/official/Reference/VBA/Conversion/CLngLng)、[CSng](/official/Reference/VBA/Conversion/CSng)、[CStr](/official/Reference/VBA/Conversion/CStr)、[CVar](/official/Reference/VBA/Conversion/CVar) 函数 --- --- url: /en/official/Reference/Core/Close.md --- # Close Concludes input/output (I/O) to a file opened using the **Open** statement. Syntax: * **Close** \[\[ **#** ] *filenumber1* ] \[ **,** \[ **#** ] *filenumber2* ] *. . .*\ The *filenumber* is any valid file number, given as an expression evaluating to an integer. The file numbers do not have to be constant. The **#** prefixes are optional. * **Close**\ When the *filenumber* list is omitted, all active files opened by the **Open** statement are closed. ::: warning The parameterless form should be used only when shutting down/exiting the program, since it closes *all* open files that were opened elsewhere in the program. ::: When files opened for **Output** or **Append** are closed, the final buffer of output is written to the operating system buffer for that file. All buffer space associated with the closed file is released. When the **Close** statement is executed, the association of a file with its file number ends. ### Example This example uses the **Close** statement to close the three files opened for **Output**. ```vb Dim I%, FileName$, FileNumber%(1 To 3) For I = 1 To 3 ' Loop 3 times FileName = "TEST" & I ' Create file name FileNumber(I) = FreeFile() Open FileName For Output As #FileNumber(I) ' Open file Print #FileNumber(I), "This is a test." ' Write string to file Next I Close #FileNumber(1), #FileNumber(2), #FileNumber(3) ' Close the 3 open files. ``` ### See Also * [Open](/en/official/Reference/Core/Open) statement * [FreeFile](/en/official/Reference/VBA/FileSystem/) function --- --- url: /zh/official/Reference/Core/Close.md --- # Close 结束对使用 **Open** 语句打开的文件的输入/输出(I/O)。 语法: * **Close** \[\[ **#** ] *filenumber1* ] \[ **,** \[ **#** ] *filenumber2* ] *. . .*\ *filenumber* 是任何有效的文件号,以求值为整数的表达式给出。文件号不必是常量。**#** 前缀可选。 * **Close**\ 省略 *filenumber* 列表时,由 **Open** 语句打开的所有活动文件都将被关闭。 ::: warning 无参数形式应仅在关闭/退出程序时使用,因为它会关闭程序中其他地方打开的*所有*文件。 ::: 当以 **Output** 或 **Append** 模式打开的文件被关闭时,最后的输出缓冲区会写入该文件的操作系统缓冲区。与已关闭文件关联的所有缓冲区空间都会被释放。 执行 **Close** 语句时,文件与其文件号的关联终止。 ### 示例 本示例使用 **Close** 语句关闭为 **Output** 打开的三个文件。 ```vb Dim I%, FileName$, FileNumber%(1 To 3) For I = 1 To 3 ' Loop 3 times FileName = "TEST" & I ' Create file name FileNumber(I) = FreeFile() Open FileName For Output As #FileNumber(I) ' Open file Print #FileNumber(I), "This is a test." ' Write string to file Next I Close #FileNumber(1), #FileNumber(2), #FileNumber(3) ' Close the 3 open files. ``` ### 另请参阅 * [Open](/official/Reference/Core/Open) 语句 * [FreeFile](/official/Reference/VBA/FileSystem/) 函数 --- --- url: /en/official/Reference/Core/CoClass.md --- # CoClass Defines a creatable COM class as a contract: a public name and identity, paired with one or more [**Interface**](/en/official/Reference/Core/Interface) blocks that the class will expose. The actual implementation lives in a separate [**Class**](/en/official/Reference/Core/Class) (typically `Private`) that uses [**Implements**](/en/official/Reference/Core/Implements). ::: info The **CoClass** block is a twinBASIC extension. In classic VBA, coclasses could only be defined indirectly via a referenced type library (IDL/C++). ::: Syntax: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **CoClass** *name*\ >      \[ *member-attributes* ] **Interface** *interfacename*\ >      ...\ > **End CoClass** *attributes* : *optional* Coclass-level attributes. See [Available attributes](#available-attributes) below. *name* : The identifier naming the coclass. *interfacename* : An [**Interface**](/en/official/Reference/Core/Interface) defined in the project (or imported from a referenced type library) that the coclass exposes. A coclass must list at least one interface and may list several. *member-attributes* : *optional* Per-interface markers, principally: * `[Default]` --- marks an interface as the default interface of the coclass. It is conventional and highly recommended to mark exactly one interface as `[Default]`. * `[Source]` --- marks an interface as a source interface (an outgoing/event interface). Combine with `[Default]` (`[Default, Source]`) to mark the default event interface. **CoClass** blocks are valid only in `.twin` source files (not legacy `.bas` or `.cls` files), and must appear *before* the [**Class**](/en/official/Reference/Core/Class) or [**Module**](/en/official/Reference/Core/Module) statement in the file. ### Available attributes * `[CoClassId("...")]` --- fixes the CLSID for the coclass (a string GUID). Set this on any public/exported coclass so consumers in other projects bind to a stable identity. * `[Description("text")]` --- exposed as the `helpstring` in the type library. * `[ComCreatable(True/False)]` --- indicates whether the coclass can be created with **New**. `True` by default. * `[AppObject]` --- marks the class as part of the global namespace. Use only when the implications are fully understood. * `[Hidden]` --- hides the coclass from IntelliSense and similar lists. * `[CoClassCustomConstructor("ModuleName.FunctionName")]` --- names a factory function (returning `HRESULT` and producing the new instance via an out parameter) used in place of the default `New` behavior. The factory may construct any private class that implements the coclass's interfaces. ### Example A simple coclass exposing two interfaces, with `IFoo` marked as the default: ```vb [CoClassId("52112FA1-FBE4-11CA-B5DD-0020AFE7292D")] CoClass Foo [Default] Interface IFoo Interface IBar End CoClass ``` A more complete example showing a custom-constructor coclass paired with a private implementing class. The coclass `Foo` is what consumers see and instantiate; the actual implementation `FooImpl` is hidden: ```vb [InterfaceId("016BC30A-A8E0-4AAF-93AE-13BD838A149E")] Public Interface IFoo Sub Foo() End Interface [InterfaceId("2A20E655-30A4-4534-86BC-6A7E281C425D")] Public Interface IBar Sub Bar() End Interface [CoClassId("7980D953-10BF-478C-93BB-DD0093315D96")] [CoClassCustomConstructor("FooFactory.CreateFoo")] [ComCreatable(True)] Public CoClass Foo [Default] Interface IFoo Interface IBar End CoClass ' The implementation does not have to be exposed. Private Class FooImpl Implements IFoo Implements IBar Public Sub Foo() Implements IFoo.Foo Debug.Print "Foo ran" End Sub Public Sub Bar() Implements IBar.Bar Debug.Print "Bar ran" End Sub End Class Public Module FooFactory ' The signature must be "preserved", returning an HRESULT ' and the new instance via the "out" parameter. Public Function CreateFoo(ByRef RHS As Foo) As Long Set RHS = New FooImpl Return 0 ' S_OK End Function End Module Public Module Test Public Sub DoIt() Dim MyFoo As Foo Set MyFoo = New Foo ' Implicitly calls FooFactory.CreateFoo. MyFoo.Foo End Sub End Module ``` ### See Also * [**Interface** statement](/en/official/Reference/Core/Interface) * [**Implements** statement](/en/official/Reference/Core/Implements) * [**Class** statement](/en/official/Reference/Core/Class) * [Interfaces and CoClasses](/en/official/Features/Language/Interfaces-CoClasses) --- --- url: /zh/official/Reference/Core/CoClass.md --- # CoClass 将可创建的COM类定义为契约:一个公共名称和标识,配合一个或多个类将公开的 [**Interface**](/official/Reference/Core/Interface) 块。实际实现位于使用 [**Implements**](/official/Reference/Core/Implements) 的单独 [**Class**](/official/Reference/Core/Class)(通常为 `Private`)中。 ::: info **CoClass** 块是twinBASIC扩展。在经典VBA中,coclass只能通过引用的类型库(IDL/C++)间接定义。 ::: 语法: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **CoClass** *name*\ >      \[ *member-attributes* ] **Interface** *interfacename*\ >      ...\ > **End CoClass** *attributes* : *可选* Coclass级别的属性。参见下文[可用属性](#available-attributes)。 *name* : 命名coclass的标识符。 *interfacename* : 项目中定义的(或从引用的类型库导入的)coclass公开的 [**Interface**](/official/Reference/Core/Interface)。coclass必须列出至少一个接口,可以列出多个。 *member-attributes* : *可选* 每个接口的标记,主要包括: * `[Default]`——将接口标记为coclass的默认接口。惯例上强烈建议恰好标记一个接口为 `[Default]`。 * `[Source]`——将接口标记为源接口(出/事件接口)。与 `[Default]` 组合使用(`[Default, Source]`)以标记默认事件接口。 **CoClass** 块仅在 `.twin` 源文件中有效(不支持传统 `.bas` 或 `.cls` 文件),且必须出现在文件中 [**Class**](/official/Reference/Core/Class) 或 [**Module**](/official/Reference/Core/Module) 语句*之前*。 ### 可用属性 * `[CoClassId("...")]`——固定coclass的CLSID(字符串GUID)。在任何公共/导出的coclass上设置此项,以便其他项目的使用者绑定到稳定的标识。 * `[Description("text")]`——在类型库中作为 `helpstring` 公开。 * `[ComCreatable(True/False)]`——指示coclass是否可以用 **New** 创建。默认为 `True`。 * `[AppObject]`——将类标记为全局命名空间的一部分。仅在完全理解其影响时使用。 * `[Hidden]`——从IntelliSense和类似列表中隐藏coclass。 * `[CoClassCustomConstructor("ModuleName.FunctionName")]`——指定工厂函数(返回 `HRESULT` 并通过out参数产生新实例),用于替代默认的 `New` 行为。工厂可以构造任何实现了coclass接口的私有类。 ### 示例 一个简单的coclass公开两个接口,`IFoo` 标记为默认接口: ```vb [CoClassId("52112FA1-FBE4-11CA-B5DD-0020AFE7292D")] CoClass Foo [Default] Interface IFoo Interface IBar End CoClass ``` 一个更完整的示例,展示自定义构造函数coclass与私有实现类的搭配。coclass `Foo` 是使用者看到并实例化的内容;实际实现 `FooImpl` 是隐藏的: ```vb [InterfaceId("016BC30A-A8E0-4AAF-93AE-13BD838A149E")] Public Interface IFoo Sub Foo() End Interface [InterfaceId("2A20E655-30A4-4534-86BC-6A7E281C425D")] Public Interface IBar Sub Bar() End Interface [CoClassId("7980D953-10BF-478C-93BB-DD0093315D96")] [CoClassCustomConstructor("FooFactory.CreateFoo")] [ComCreatable(True)] Public CoClass Foo [Default] Interface IFoo Interface IBar End CoClass ' The implementation does not have to be exposed. Private Class FooImpl Implements IFoo Implements IBar Public Sub Foo() Implements IFoo.Foo Debug.Print "Foo ran" End Sub Public Sub Bar() Implements IBar.Bar Debug.Print "Bar ran" End Sub End Class Public Module FooFactory ' The signature must be "preserved", returning an HRESULT ' and the new instance via the "out" parameter. Public Function CreateFoo(ByRef RHS As Foo) As Long Set RHS = New FooImpl Return 0 ' S_OK End Function End Module Public Module Test Public Sub DoIt() Dim MyFoo As Foo Set MyFoo = New Foo ' Implicitly calls FooFactory.CreateFoo. MyFoo.Foo End Sub End Module ``` ### 另请参阅 * [**Interface** 语句](/official/Reference/Core/Interface) * [**Implements** 语句](/official/Reference/Core/Implements) * [**Class** 语句](/official/Reference/Core/Class) * [接口与CoClass](/official/Features/Language/Interfaces-CoClasses) --- --- url: /en/official/Reference/tbIDE/CodeEditor.md --- # CodeEditor class A code-pane editor --- the specific [**Editor**](/en/official/Reference/tbIDE/Editor) kind the IDE returns when the active editor is a source-code pane. Adds selection / text / scrolling control, an inline-widget API, and a raw passthrough into the underlying Monaco editor that powers code panes. A **CodeEditor** is reached by casting an [**Editor**](/en/official/Reference/tbIDE/Editor) --- `Host.ActiveEditors(0)` returns an [**Editor**](/en/official/Reference/tbIDE/Editor) that, for a code pane, is also a **CodeEditor**: ```vb If TypeOf Host.ActiveEditors(0) Is CodeEditor Then Dim codeEditor As CodeEditor = Host.ActiveEditors(0) codeEditor.SelectedText = "' commented out by an addin" & vbCrLf & codeEditor.SelectedText End If ``` **CodeEditor** inherits every base [**Editor**](/en/official/Reference/tbIDE/Editor) member ([**Path**](/en/official/Reference/tbIDE/Editor#path), [**Type**](/en/official/Reference/tbIDE/Editor#type), [**SetFocus**](/en/official/Reference/tbIDE/Editor#setfocus), [**Close**](/en/official/Reference/tbIDE/Editor#close), [**Save**](/en/official/Reference/tbIDE/Editor#save), [**IsDirty**](/en/official/Reference/tbIDE/Editor#isdirty)) and adds the members listed below. ## Properties ### SelectedText The currently-selected text. Reading returns the selection as a **String** (empty string when nothing is selected). Assigning replaces the current selection with the supplied text. Read / write. Syntax: *codeEditor*.**SelectedText** \[ = *value* ] ### Text The full text of the code pane. Reading returns the entire document; assigning replaces every line with the supplied text. Read / write. Syntax: *codeEditor*.**Text** \[ = *value* ] Replacing the entire text is heavy --- both for the editor (it has to rebuild every Monaco data structure) and for the user (the undo stack collapses to a single step). For targeted edits, prefer [**SelectedText**](#selectedtext) over [**Text**](#text). ## Methods ### AddMonacoWidget Attaches an inline HTML overlay to a specific position in the editor --- Monaco's *content widget* mechanism, exposed as a familiar [**HtmlElement**](/en/official/Reference/tbIDE/HtmlElement). Syntax: *codeEditor*.**AddMonacoWidget**( *LineNumber*, *ColumnNumber*, *Html* \[, *Css* ] ) **As** [**HtmlElement**](/en/official/Reference/tbIDE/HtmlElement) *LineNumber* : *required* One-based line number to attach the widget to. **Long**. *ColumnNumber* : *required* One-based column number on that line, **or zero**. **Long**. When the column number is zero, the widget is rendered *below* the line and the editor inserts vertical space so the widget does not overlap the next line. Pass a non-zero column to render the widget inline at that column. *Html* : *required* The widget's HTML content. **String**. *Css* : *optional* Per-widget CSS as a **String**. Use this for widget-local styles that should not bleed into the rest of the code pane. The returned [**HtmlElement**](/en/official/Reference/tbIDE/HtmlElement) has the same dynamic-DOM properties as elements inside a tool window --- see [Dynamic DOM property resolution](/en/official/Reference/tbIDE/#dynamic-dom-property-resolution) on the package overview. Call [**HtmlElement.Remove**](/en/official/Reference/tbIDE/HtmlElement#remove) on the returned object to remove the widget. ### ExecuteMonacoCommand Sends a direct command to the underlying Monaco editor instance. Useful for triggering Monaco's built-in commands (Find, Go-to-Line, Format, Toggle Comment, …) without writing the equivalent twinBASIC code. Syntax: *codeEditor*.**ExecuteMonacoCommand** *Command* \[, *Arg1*, *Arg2*, … ] *Command* : *required* The Monaco command ID. **String**. Common values include `"actions.find"` (open the Find widget), `"closeFindWidget"` (close it), `"editor.action.formatDocument"`, and `"editor.action.commentLine"`. *Args* : *optional* A **ParamArray** of command-specific arguments. **Variant**. Forwarded verbatim to Monaco. The reference does not enumerate Monaco's command set --- refer to Monaco's documentation for the full list and their per-command argument shapes. ```vb codeEditor.ExecuteMonacoCommand "actions.find" ' open Find widget codeEditor.ExecuteMonacoCommand "closeFindWidget" ' close it ``` ### GetSelectionInfo Reports the start and end positions of the current selection. All four output arguments are filled even when nothing is selected --- start and end positions then coincide on the caret's current position. Syntax: *codeEditor*.**GetSelectionInfo** *StartLine*, *StartColumn*, *EndLine*, *EndColumn* *StartLine*, *StartColumn*, *EndLine*, *EndColumn* : **ByRef Long** --- output parameters, all one-based. ### RevealRange Scrolls the editor to bring a range into view, optionally animating the scroll and positioning the range at a specific spot in the viewport. Syntax: *codeEditor*.**RevealRange** *StartLine*, *StartColumn*, *EndLine*, *EndColumn* \[, *SmoothScroll* ] \[, *Area* ] *StartLine*, *StartColumn*, *EndLine*, *EndColumn* : *required* The range to reveal. **Long**, one-based. *SmoothScroll* : *optional* **Boolean** --- animate the scroll. Default **True**. *Area* : *optional* A [**RevealArea**](#revealarea) value controlling where in the viewport the range lands. Default [**Any**](#RevealArea_Any). ### SetSelectionInfo Sets the start and end positions of the selection. The inverse of [**GetSelectionInfo**](#getselectioninfo). Syntax: *codeEditor*.**SetSelectionInfo** *StartLine*, *StartColumn*, *EndLine*, *EndColumn* *StartLine*, *StartColumn*, *EndLine*, *EndColumn* : *required* One-based line and column positions. **Long**. To position the caret without selecting any text, use the same line / column for both ends. ## RevealArea Controls where in the viewport [**RevealRange**](#revealrange) places the requested range. | Constant | Value | Description | |----------|-------|-------------| | **Any** | 0 | Scroll vertically or horizontally only as much as necessary to make the range visible. Cheapest scroll. | | **Top** | 1 | Scroll so the range sits at the top of the viewport. | | **Center** | 2 | Scroll so the range is vertically centred in the viewport. | | **CenterIfNotVisible** | 3 | Centre vertically, but only if the range currently lies outside the viewport --- otherwise do nothing. | | **NearTop** | 4 | Scroll so the range sits close to the top, with some context above --- Monaco's "view a code definition" preset. | | **NearTopIfNotVisible** | 5 | Same as [**NearTop**](#RevealArea_NearTop), but only if the range is currently outside the viewport. | --- --- url: /zh/official/Reference/tbIDE/CodeEditor.md --- # CodeEditor 类 一个代码窗格编辑器——当活动编辑器是源代码窗格时 IDE 返回的特定 [**Editor**](/official/Reference/tbIDE/Editor) 类型。增加了选择/文本/滚动控制、行内控件 API,以及直接透传到驱动代码窗格的底层 Monaco 编辑器。 通过转换一个 [**Editor**](/official/Reference/tbIDE/Editor) 来获取 **CodeEditor**——`Host.ActiveEditors(0)` 返回一个 [**Editor**](/official/Reference/tbIDE/Editor),对于代码窗格,它也是一个 **CodeEditor**: ```vb If TypeOf Host.ActiveEditors(0) Is CodeEditor Then Dim codeEditor As CodeEditor = Host.ActiveEditors(0) codeEditor.SelectedText = "' commented out by an addin" & vbCrLf & codeEditor.SelectedText End If ``` **CodeEditor** 继承了所有基础 [**Editor**](/official/Reference/tbIDE/Editor) 成员([**Path**](/official/Reference/tbIDE/Editor#path)、[**Type**](/official/Reference/tbIDE/Editor#type)、[**SetFocus**](/official/Reference/tbIDE/Editor#setfocus)、[**Close**](/official/Reference/tbIDE/Editor#close)、[**Save**](/official/Reference/tbIDE/Editor#save)、[**IsDirty**](/official/Reference/tbIDE/Editor#isdirty)),并添加了以下成员。 ## 属性 ### SelectedText 当前选中的文本。读取时将选择内容作为 **String** 返回(未选中任何内容时返回空字符串)。赋值时用提供的文本替换当前选择。可读/写。 语法:*codeEditor*.**SelectedText** \[ = *value* ] ### Text 代码窗格的完整文本。读取时返回整个文档;赋值时用提供的文本替换所有行。可读/写。 语法:*codeEditor*.**Text** \[ = *value* ] 替换整个文本开销较大——对编辑器而言(它必须重建每个 Monaco 数据结构),对用户亦然(撤销栈会折叠为单步)。对于针对性编辑,优先使用 [**SelectedText**](#selectedtext) 而非 [**Text**](#text)。 ## 方法 ### AddMonacoWidget 在编辑器的特定位置附加一个行内 HTML 覆盖层——Monaco 的*内容控件*机制,以熟悉的 [**HtmlElement**](/official/Reference/tbIDE/HtmlElement) 形式暴露。 语法:*codeEditor*.**AddMonacoWidget**( *LineNumber*, *ColumnNumber*, *Html* \[, *Css* ] ) **As** [**HtmlElement**](/official/Reference/tbIDE/HtmlElement) *LineNumber* : *必需* 要附加控件的基于 1 的行号。**Long**。 *ColumnNumber* : *必需* 该行上基于 1 的列号,**或零**。**Long**。当列号为零时,控件渲染在该行*下方*,编辑器插入垂直空间以使控件不会与下一行重叠。传入非零列号以在该列处行内渲染控件。 *Html* : *必需* 控件的 HTML 内容。**String**。 *Css* : *可选* 每个控件的 CSS,为 **String**。用于不应渗入代码窗格其余部分的控件局部样式。 返回的 [**HtmlElement**](/official/Reference/tbIDE/HtmlElement) 具有与工具窗口内元素相同的动态 DOM 属性——参见包概述中的[动态 DOM 属性解析](/official/Reference/tbIDE/#动态-dom-属性解析)。对返回对象调用 [**HtmlElement.Remove**](/official/Reference/tbIDE/HtmlElement#remove) 以移除控件。 ### ExecuteMonacoCommand 向底层 Monaco 编辑器实例发送直接命令。适用于触发 Monaco 内置命令(查找、跳转到行、格式化、切换注释等),而无需编写等效的 twinBASIC 代码。 语法:*codeEditor*.**ExecuteMonacoCommand** *Command* \[, *Arg1*, *Arg2*, … ] *Command* : *必需* Monaco 命令 ID。**String**。常用值包括 `"actions.find"`(打开查找控件)、`"closeFindWidget"`(关闭它)、`"editor.action.formatDocument"` 和 `"editor.action.commentLine"`。 *Args* : *可选* 命令特有参数的 **ParamArray**。**Variant**。原样转发给 Monaco。 参考文档不列举 Monaco 的命令集——完整列表及每个命令的参数形态请参阅 Monaco 文档。 ```vb codeEditor.ExecuteMonacoCommand "actions.find" ' 打开查找控件 codeEditor.ExecuteMonacoCommand "closeFindWidget" ' 关闭它 ``` ### GetSelectionInfo 报告当前选择的起止位置。即使未选中任何内容,所有四个输出参数也会被填充——起止位置重合于插入符的当前位置。 语法:*codeEditor*.**GetSelectionInfo** *StartLine*, *StartColumn*, *EndLine*, *EndColumn* *StartLine*, *StartColumn*, *EndLine*, *EndColumn* : **ByRef Long** —— 输出参数,全部基于 1。 ### RevealRange 滚动编辑器使指定范围可见,可选地动画滚动并将范围定位到视口中的特定位置。 语法:*codeEditor*.**RevealRange** *StartLine*, *StartColumn*, *EndLine*, *EndColumn* \[, *SmoothScroll* ] \[, *Area* ] *StartLine*, *StartColumn*, *EndLine*, *EndColumn* : *必需* 要显示的范围。**Long**,基于 1。 *SmoothScroll* : *可选* **Boolean** —— 动画滚动。默认 **True**。 *Area* : *可选* 一个 [**RevealArea**](#revealarea) 值,控制范围在视口中的落地位置。默认 [**Any**](#RevealArea_Any)。 ### SetSelectionInfo 设置选择的起止位置。[**GetSelectionInfo**](#getselectioninfo) 的逆操作。 语法:*codeEditor*.**SetSelectionInfo** *StartLine*, *StartColumn*, *EndLine*, *EndColumn* *StartLine*, *StartColumn*, *EndLine*, *EndColumn* : *必需* 基于 1 的行和列位置。**Long**。要在不选择任何文本的情况下定位插入符,两端使用相同的行/列。 ## RevealArea 控制 [**RevealRange**](#revealrange) 将请求的范围放置在视口中的何处。 | 常量 | 值 | 描述 | |------|-----|------| | **Any** | 0 | 仅在必要时垂直或水平滚动以使范围可见。最小滚动量。 | | **Top** | 1 | 滚动使范围位于视口顶部。 | | **Center** | 2 | 滚动使范围在视口中垂直居中。 | | **CenterIfNotVisible** | 3 | 垂直居中,但仅当范围当前在视口外时——否则不做任何操作。 | | **NearTop** | 4 | 滚动使范围靠近顶部,上方保留一些上下文——Monaco 的"查看代码定义"预设。 | | **NearTopIfNotVisible** | 5 | 与 [**NearTop**](#RevealArea_NearTop) 相同,但仅当范围当前在视口外时。 | --- --- url: /en/official/Features/Compiler-IDE/CodeLens.md --- # Run Subs from the IDE The CodeLens feature allows running Subs and Functions, with no arguments and in modules (but not classes/Forms/UserControls) right from the editor without starting the full program. It has full access to your code; it can access constants, call other functions both intrinsic and user-defined, call APIs, and print to the Debug Console. Methods eligible to run with CodeLens (when enabled), have a bar above them that you can click to run: ![image](/assets/351d0147-cad3-4e16-89e5-0a9e43496740.CYyypF76.png) ### Example A no-argument `Public Sub` in a module is eligible for CodeLens: ```vb Public Sub RunTest() Debug.Print "Hello from CodeLens" End Sub ``` --- --- url: /zh/official/Features/Compiler-IDE/CodeLens.md --- # 从 IDE 运行 Sub CodeLens 功能允许直接在编辑器中运行无参数的 Sub 和 Function(限模块中,不包括类/窗体/UserControl),而无需启动完整程序。它可以完全访问你的代码;可以访问常量、调用内置函数和自定义函数、调用 API,以及输出到调试控制台。 符合 CodeLens 运行条件的方法(启用时),上方会显示一个可点击的运行栏: ![image](/assets/351d0147-cad3-4e16-89e5-0a9e43496740.CYyypF76.png) ### 示例 模块中无参数的 `Public Sub` 符合 CodeLens 条件: ```vb Public Sub RunTest() Debug.Print "Hello from CodeLens" End Sub ``` --- --- url: /en/official/Reference/VBA/Collection.md --- # Collection class A **Collection** is an ordered set of items that can be referred to as a unit. The members of a collection do not have to share a data type --- any value or object reference is acceptable. Items are accessed by their one-based numeric position in the collection or, if they were added with a key, by that key. ## Creating, populating, and disposing of a collection A collection is created with **New**, populated with [**Add**](/en/official/Reference/VBA/Collection/Add), and reduced with [**Remove**](/en/official/Reference/VBA/Collection/Remove) (one item at a time) or [**Clear**](/en/official/Reference/VBA/Collection/Clear) (every item at once). When the variable referring to the collection goes out of scope, or is set to **Nothing**, the collection --- together with any object references it holds --- is released. ```vb Sub Demo() Dim Cars As Collection Set Cars = New Collection Cars.Add "Polestar 2", Key:="EV" ' Add with a key. Cars.Add "Volvo XC40", Key:="ICE" Cars.Add "Toyota Mirai" ' Add without a key. Debug.Print Cars.Count ' 3 Debug.Print Cars("EV") ' "Polestar 2" — Item is the default member. Debug.Print Cars(3) ' "Toyota Mirai" — indexes are 1-based. Cars.Remove "ICE" ' Remove the Volvo XC40 by key. Cars.Remove 1 ' Remove the Polestar 2 by index. Set Cars = Nothing ' Release the collection. End Sub ``` ## Iterating over a collection A **Collection** can be iterated with the [**For Each...Next**](/en/official/Reference/Core/For-Each-Next) statement, which yields each item in turn in insertion order, regardless of whether the item was added with a key. To iterate over the keys instead, fetch them with [**Keys**](/en/official/Reference/VBA/Collection/Keys); to take a snapshot of the values as an array (for example, when the collection may be modified during iteration), use [**Items**](/en/official/Reference/VBA/Collection/Items). ```vb Dim Numbers As New Collection Numbers.Add 10 Numbers.Add 20 Numbers.Add 30 Dim n As Variant For Each n In Numbers Debug.Print n ' Prints 10, then 20, then 30. Next n ``` ## Members * [Add](/en/official/Reference/VBA/Collection/Add) -- adds an element to the collection * [Clear](/en/official/Reference/VBA/Collection/Clear) -- removes all elements from the collection * [Count](/en/official/Reference/VBA/Collection/Count) -- returns the number of elements in the collection * [Exists](/en/official/Reference/VBA/Collection/Exists) -- returns whether an element with a specific key exists in the collection * [Item](/en/official/Reference/VBA/Collection/Item) -- returns an element from the collection by index or key (default member) * [Items](/en/official/Reference/VBA/Collection/Items) -- returns a **Variant** array of all elements in the collection * [KeyCompareMode](/en/official/Reference/VBA/Collection/KeyCompareMode) -- returns or sets the text comparison mode used for keys * [KeyCountHint](/en/official/Reference/VBA/Collection/KeyCountHint) -- returns or sets a hint for the expected number of keyed items * [Keys](/en/official/Reference/VBA/Collection/Keys) -- returns a **String** array of all keys in the collection * [Remove](/en/official/Reference/VBA/Collection/Remove) -- removes an element from the collection by index or key --- --- url: /zh/official/Reference/VBA/Collection.md --- # Collection 类 **Collection** 是一个有序的项集合,可以作为一个整体来引用。集合的成员不必共享相同的数据类型——任何值或对象引用都是可接受的。可以通过项在集合中从 1 开始的数字位置访问,或者在添加时指定了键的情况下,通过该键访问。 ## 创建、填充和释放集合 集合使用 **New** 创建,使用 [**Add**](/official/Reference/VBA/Collection/Add) 填充,使用 [**Remove**](/official/Reference/VBA/Collection/Remove)(一次移除一项)或 [**Clear**](/official/Reference/VBA/Collection/Clear)(一次移除所有项)缩减。当引用集合的变量超出作用域或被设置为 **Nothing** 时,集合及其持有的所有对象引用将被释放。 ```vb Sub Demo() Dim Cars As Collection Set Cars = New Collection Cars.Add "Polestar 2", Key:="EV" ' Add with a key. Cars.Add "Volvo XC40", Key:="ICE" Cars.Add "Toyota Mirai" ' Add without a key. Debug.Print Cars.Count ' 3 Debug.Print Cars("EV") ' "Polestar 2" — Item is the default member. Debug.Print Cars(3) ' "Toyota Mirai" — indexes are 1-based. Cars.Remove "ICE" ' Remove the Volvo XC40 by key. Cars.Remove 1 ' Remove the Polestar 2 by index. Set Cars = Nothing ' Release the collection. End Sub ``` ## 遍历集合 可以使用 [**For Each...Next**](/official/Reference/Core/For-Each-Next) 语句遍历 **Collection**,该语句按插入顺序依次产出每个项,无论项是否使用键添加。如果要遍历键,请使用 [**Keys**](/official/Reference/VBA/Collection/Keys) 获取;若要将值的快照作为数组获取(例如在迭代期间集合可能被修改时),请使用 [**Items**](/official/Reference/VBA/Collection/Items)。 ```vb Dim Numbers As New Collection Numbers.Add 10 Numbers.Add 20 Numbers.Add 30 Dim n As Variant For Each n In Numbers Debug.Print n ' Prints 10, then 20, then 30. Next n ``` ## 成员 * [Add](/official/Reference/VBA/Collection/Add) -- 向集合添加一个元素 * [Clear](/official/Reference/VBA/Collection/Clear) -- 移除集合中的所有元素 * [Count](/official/Reference/VBA/Collection/Count) -- 返回集合中的元素数量 * [Exists](/official/Reference/VBA/Collection/Exists) -- 返回集合中是否存在具有特定键的元素 * [Item](/official/Reference/VBA/Collection/Item) -- 按索引或键返回集合中的一个元素(默认成员) * [Items](/official/Reference/VBA/Collection/Items) -- 返回集合中所有元素的 **Variant** 数组 * [KeyCompareMode](/official/Reference/VBA/Collection/KeyCompareMode) -- 返回或设置用于键的文本比较模式 * [KeyCountHint](/official/Reference/VBA/Collection/KeyCountHint) -- 返回或设置预期键控项数量的提示 * [Keys](/official/Reference/VBA/Collection/Keys) -- 返回集合中所有键的 **String** 数组 * [Remove](/official/Reference/VBA/Collection/Remove) -- 按索引或键移除集合中的一个元素 --- --- url: /en/official/Reference/VBRUN/Constants/ColorConstants.md --- # ColorConstants Common named RGB colour values, suitable wherever a colour is supplied as a **Long** or **OLE\_COLOR**. The numeric values follow the GDI byte order --- `&H00BBGGRR`. | Constant | Value | Description | |----------|-------|-------------| | **vbBlack** | 0 | Black. | | **vbRed** | 255 | Red. | | **vbGreen** | 65280 | Green. | | **vbYellow** | 65535 | Yellow. | | **vbBlue** | 16711680 | Blue. | | **vbMagenta** | 16711935 | Magenta. | | **vbCyan** | 16776960 | Cyan. | | **vbWhite** | 16777215 | White. | --- --- url: /zh/official/Reference/VBRUN/Constants/ColorConstants.md --- # ColorConstants 常用命名RGB颜色值,适用于以**Long**或**OLE\_COLOR**提供颜色的任何场合。数值遵循GDI字节顺序 --- `&H00BBGGRR`。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbBlack** | 0 | 黑色。 | | **vbRed** | 255 | 红色。 | | **vbGreen** | 65280 | 绿色。 | | **vbYellow** | 65535 | 黄色。 | | **vbBlue** | 16711680 | 蓝色。 | | **vbMagenta** | 16711935 | 品红色。 | | **vbCyan** | 16776960 | 青色。 | | **vbWhite** | 16777215 | 白色。 | --- --- url: /en/official/Reference/CustomControls/Enumerations/ColorRGBA.md --- # ColorRGBA A **Long**-compatible type alias used wherever a 32-bit ABGR colour value is expected. The high byte is the alpha channel --- `&HFF000000` is fully opaque, `&H00000000` is fully transparent --- and the low three bytes follow the standard `vbBlue`/`vbGreen`/`vbRed` order used by the [**ColorConstants**](/en/official/Reference/VBRUN/Constants/ColorConstants) `Long`-coloured constants. Used by [**FillColorPoint.Color**](/en/official/Reference/CustomControls/Styles/Fill#color) and by the **RGBA** parameter of [**FillColorPoints.SetSolidColorRGBA**](/en/official/Reference/CustomControls/Styles/Fill#setsolidcolorrgba) / [**Borders.SetSimpleBorderRGBA**](/en/official/Reference/CustomControls/Styles/Borders#setsimpleborderrgba). ::: info **ColorRGBA** is declared as an empty `Enum` block (with a placeholder `[_MAX] = 0` member) only because twinBASIC has not yet exposed a type-alias syntax such as `Type ColorRGBA = Long`. The source has a `FIXME` comment noting the stand-in. **ColorRGBA** should be used as a **Long**-compatible type alias rather than as an enumeration with named members; when alias syntax becomes available, the enum stand-in will be replaced. ::: To write a fully-opaque colour, OR-in the opaque alpha mask: `&HFF000000 Or vbBlue`. The convenience setters [**FillColorPoints.SetSolidColor**](/en/official/Reference/CustomControls/Styles/Fill#setsolidcolor) and [**Borders.SetSimpleBorder**](/en/official/Reference/CustomControls/Styles/Borders#setsimpleborder) take a normal three-byte **Long** colour and apply the opaque mask automatically; only the `*RGBA` variants take a raw **ColorRGBA**. ```vb Dim translucentRed As ColorRGBA = &H800000FF& ' 50% alpha, full red ``` --- --- url: /zh/official/Reference/CustomControls/Enumerations/ColorRGBA.md --- # ColorRGBA **Long** 兼容类型别名,用于任何需要 32 位 ABGR 颜色值的地方。高字节是 alpha 通道——`&HFF000000` 为完全不透明,`&H00000000` 为完全透明——低三个字节遵循 [**ColorConstants**](/official/Reference/VBRUN/Constants/ColorConstants) `Long` 颜色常量使用的标准 `vbBlue`/`vbGreen`/`vbRed` 顺序。由 [**FillColorPoint.Color**](/official/Reference/CustomControls/Styles/Fill#color) 和 [**FillColorPoints.SetSolidColorRGBA**](/official/Reference/CustomControls/Styles/Fill#setsolidcolorrgba) / [**Borders.SetSimpleBorderRGBA**](/official/Reference/CustomControls/Styles/Borders#setsimpleborderrgba) 的 **RGBA** 参数使用。 ::: info **ColorRGBA** 仅作为空 `Enum` 块声明(带有占位 `[_MAX] = 0` 成员),因为 twinBASIC 尚未暴露类型别名语法如 `Type ColorRGBA = Long`。源码中有 `FIXME` 注释说明了此替代。**ColorRGBA** 应作为 **Long** 兼容类型别名使用,而非带有命名成员的枚举;当别名语法可用时,枚举替代将被替换。 ::: 要写入完全不透明颜色,OR 进不透明 alpha 掩码:`&HFF000000 Or vbBlue`。便捷设置器 [**FillColorPoints.SetSolidColor**](/official/Reference/CustomControls/Styles/Fill#setsolidcolor) 和 [**Borders.SetSimpleBorder**](/official/Reference/CustomControls/Styles/Borders#setsimpleborder) 接受普通三字节 **Long** 颜色并自动应用不透明掩码;只有 `*RGBA` 变体接受原始 **ColorRGBA**。 ```vb Dim translucentRed As ColorRGBA = &H800000FF& ' 50% alpha, full red ``` --- --- url: /en/official/Reference/CustomControls/WaynesGrid/Column.md --- # Column class One column of a [**WaynesGrid**](/en/official/Reference/CustomControls/WaynesGrid/). Has a [**Caption**](#caption) that is shown in the column-header row and a [**Width**](#width) that the user can drag at run time. Elements of [**WaynesGrid.Columns**](/en/official/Reference/CustomControls/WaynesGrid/#columns). ```vb ReDim Grid1.Columns(2) Set Grid1.Columns(0) = New Column Grid1.Columns(0).Caption = "ID" Grid1.Columns(0).Width = 80 ``` ## Properties ### Caption The text shown in the column-header cell. **String**. Default: `"Column"`. ### Width The column's width in pixels (unscaled by DPI). [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount). Default: 100. Editable by the user at run time by dragging the resizer bar on the column's right edge; assignments at run time update the grid immediately. ## Events ### OnChanged Raised when [**Caption**](#caption) or [**Width**](#width) is assigned. The parent [**WaynesGrid**](/en/official/Reference/CustomControls/WaynesGrid/) listens for this and requests a repaint. --- --- url: /zh/official/Reference/CustomControls/WaynesGrid/Column.md --- # Column 类 [**WaynesGrid**](/official/Reference/CustomControls/WaynesGrid/) 的一列。具有显示在列标题行中的 [**Caption**](#caption) 和用户可在运行时拖动的 [**Width**](#width)。[**WaynesGrid.Columns**](/official/Reference/CustomControls/WaynesGrid/#columns) 的元素。 ```vb ReDim Grid1.Columns(2) Set Grid1.Columns(0) = New Column Grid1.Columns(0).Caption = "ID" Grid1.Columns(0).Width = 80 ``` ## 属性 ### Caption 列标题单元格中显示的文本。**String**。默认:`"Column"`。 ### Width 列的宽度(像素,未经 DPI 缩放)。[**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount)。默认:100。用户可在运行时通过拖动列右边缘的调整条编辑;运行时赋值立即更新网格。 ## 事件 ### OnChanged [**Caption**](#caption) 或 [**Width**](#width) 被赋值时触发。父 [**WaynesGrid**](/official/Reference/CustomControls/WaynesGrid/) 监听此事件并请求重绘。 --- --- url: /en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader.md --- # ColumnHeader class A **ColumnHeader** represents a single column in a [**ListView**](/en/official/Reference/WinNativeCommonCtls/ListView/) running in **lvwReport** view. Returned from [**ColumnHeaders.Add**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders#add) and from [**ColumnHeaders.Item**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders#item). The class is tagged `[COMCreatable(False)]` --- user code accesses **ColumnHeader** instances through the parent [**ListView**](/en/official/Reference/WinNativeCommonCtls/ListView/)'s [**ColumnHeaders**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders) collection. ```vb With ListView1.ColumnHeaders .Add , "name", "Name", 150 .Add , "size", "Size", 80, lvwColumnRight .Add , "date", "Date", 100, lvwColumnCenter End With ``` ## Properties ### Alignment The horizontal alignment of the column's text. A member of [**ListColumnAlignmentConstants**](#listcolumnalignmentconstants). Default: **lvwColumnLeft**. ::: info The first column in a ListView must be left-aligned. Attempting to add a non-left-aligned column at position 1 raises run-time error 5. ::: ### Icon The icon rendered in the header. **Variant** --- either a 1-based **Long** index into [**ListView.ColumnHeaderIcons**](/en/official/Reference/WinNativeCommonCtls/ListView/#columnheadericons), or a **String** key. Assignment validates against the bound image list. ### Index The 1-based position of the column in the parent collection. **Long**, read-only. Attempting to assign raises run-time error 383. ### Key The string key the column was added under. **String**, read/write. ### Left The column's horizontal pixel position in the listview, computed as the sum of preceding columns' widths. **Single**, read-only. ### Position The column's visual position. **Long**, read/write. Distinct from [**Index**](#index) --- when [**ListView.AllowColumnReorder**](/en/official/Reference/WinNativeCommonCtls/ListView/#allowcolumnreorder) is **True**, the user can drag columns to reorder them, in which case **Index** stays fixed but **Position** changes. Assigning a value outside `1..Count` raises run-time error 380. ### SubItemIndex The 0-based sub-item index this column displays. **Long**, read-only. Maps the column to a [**ListItem.SubItems**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem#subitemsindex)(*index*) value. Returns `0` for the first column (which shows [**ListItem.Text**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem#text)). ### Tag Arbitrary data the application can attach to the column. **Variant**. ### Text The column header text. **String**, read/write. The default member. ### Width The column's pixel width. **Single**, read/write. ## ListColumnAlignmentConstants Determines the horizontal alignment of a column's text. Declared on the **ColumnHeader** class. | Member | Value | Description | |---------------------------|-------|-------------------| | **lvwColumnLeft** | 0 | Left-aligned text. | | **lvwColumnRight** | 1 | Right-aligned text. | | **lvwColumnCenter** | 2 | Centered text. | ## See Also * [ListView](/en/official/Reference/WinNativeCommonCtls/ListView/) -- the parent control * [ColumnHeaders](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders) -- the collection holding **ColumnHeader** instances * [ListItem](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem) -- a row, whose [**SubItems**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem#subitemsindex) align with columns --- --- url: /zh/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader.md --- # ColumnHeader 类 **ColumnHeader** 表示在 **lvwReport** 视图中运行的 [**ListView**](/official/Reference/WinNativeCommonCtls/ListView/) 中的单个列。从 [**ColumnHeaders.Add**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders#add) 和 [**ColumnHeaders.Item**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders#item) 返回。 该类标记为 `[COMCreatable(False)]` --- 用户代码通过父级 [**ListView**](/official/Reference/WinNativeCommonCtls/ListView/) 的 [**ColumnHeaders**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders) 集合访问 **ColumnHeader** 实例。 ```vb With ListView1.ColumnHeaders .Add , "name", "Name", 150 .Add , "size", "Size", 80, lvwColumnRight .Add , "date", "Date", 100, lvwColumnCenter End With ``` ## 属性 ### Alignment 列文本的水平对齐方式。[**ListColumnAlignmentConstants**](#listcolumnalignmentconstants) 的成员。默认:**lvwColumnLeft**。 ::: info ListView 中的第一列必须左对齐。尝试在位置1添加非左对齐的列会引发运行时错误 5。 ::: ### Icon 在标题中渲染的图标。**Variant** --- 可以是基于1的 **Long** 索引指向 [**ListView.ColumnHeaderIcons**](/official/Reference/WinNativeCommonCtls/ListView/#columnheadericons),或 **String** 键。赋值对照绑定图像列表验证。 ### Index 此列在父集合中基于1的位置。**Long**,只读。尝试赋值引发运行时错误 383。 ### Key 此列添加时的字符串键。**String**,读/写。 ### Left 列在列表视图中的水平像素位置,计算为前面列宽度之和。**Single**,只读。 ### Position 列的视觉位置。**Long**,读/写。与 [**Index**](#index) 不同 --- 当 [**ListView.AllowColumnReorder**](/official/Reference/WinNativeCommonCtls/ListView/#allowcolumnreorder) 为 **True** 时,用户可拖动列重新排序,此时 **Index** 保持不变但 **Position** 改变。 赋值超出 `1..Count` 范围引发运行时错误 380。 ### SubItemIndex 此列显示的基于0的子项索引。**Long**,只读。将列映射到 [**ListItem.SubItems**](/official/Reference/WinNativeCommonCtls/ListView/ListItem#subitemsindex)(*index*) 值。第一列返回 `0`(显示 [**ListItem.Text**](/official/Reference/WinNativeCommonCtls/ListView/ListItem#text))。 ### Tag 应用程序可附加到此列的任意数据。**Variant**。 ### Text 列标题文本。**String**,读/写。默认成员。 ### Width 列的像素宽度。**Single**,读/写。 ## ListColumnAlignmentConstants 确定列文本的水平对齐方式。在 **ColumnHeader** 类上声明。 | 成员 | 值 | 描述 | |---------------------------|-------|-------------------| | **lvwColumnLeft** | 0 | 左对齐文本。 | | **lvwColumnRight** | 1 | 右对齐文本。 | | **lvwColumnCenter** | 2 | 居中文本。 | ## 另见 * [ListView](/official/Reference/WinNativeCommonCtls/ListView/) --- 父控件 * [ColumnHeaders](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders) --- 持有 **ColumnHeader** 实例的集合 * [ListItem](/official/Reference/WinNativeCommonCtls/ListView/ListItem) --- 行,其 [**SubItems**](/official/Reference/WinNativeCommonCtls/ListView/ListItem#subitemsindex) 与列对齐 --- --- url: /en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders.md --- # ColumnHeaders class The **ColumnHeaders** collection is the entry point for managing the columns of a [**ListView**](/en/official/Reference/WinNativeCommonCtls/ListView/) in **lvwReport** view. Accessed as `<listView>.ColumnHeaders`; supports adding, removing, indexed access, and `For Each` iteration. The class is tagged `[COMCreatable(False)]` --- user code accesses **ColumnHeaders** through the parent [**ListView**](/en/official/Reference/WinNativeCommonCtls/ListView/) control's [**ColumnHeaders**](/en/official/Reference/WinNativeCommonCtls/ListView/#columnheaders) property. ```vb With ListView1.ColumnHeaders .Add , "name", "Name", 150 .Add , "size", "Size", 80, lvwColumnRight .Add , "date", "Date", 100, lvwColumnCenter End With ``` ## Properties ### Count The number of columns in the collection. **Long**, read-only. ### Item Returns the [**ColumnHeader**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader) at the given index or with the given key. The default member, so `ListView1.ColumnHeaders("name")` works without writing `.Item("name")`. Syntax: *object*.**Item** ( *Index* ) **As ColumnHeader** *Index* : A **Variant** --- either a 1-based **Long** position or a **String** key. ## Methods ### Add Adds a column to the listview. Syntax: *object*.**Add** ( \[ *Index* ] \[, *Key* ] \[, *Text* ] \[, *Width* ] \[, *Alignment* ] \[, *Icon* ] ) **As ColumnHeader** *Index* : *optional* A **Long** giving the 1-based position at which to insert the new column. When omitted, the column is appended. *Key* : *optional* A **String** name under which the column can be looked up. Keys must be unique within the collection (otherwise run-time error 35602). *Text* : *optional* A **String** giving the column header label. *Width* : *optional* A **Variant** giving the column's pixel width. When omitted, defaults to 96 pixels (scaled). *Alignment* : *optional* A member of [**ListColumnAlignmentConstants**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader#listcolumnalignmentconstants). Default: **lvwColumnLeft**. Attempting to add a non-left-aligned column at position `1` raises run-time error 5. *Icon* : *optional* A **Variant** identifying the header icon --- either a 1-based **Long** index into [**ListView.ColumnHeaderIcons**](/en/official/Reference/WinNativeCommonCtls/ListView/#columnheadericons), or a **String** key. Returns the newly-created [**ColumnHeader**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader). ### Clear Removes every column from the listview. Syntax: *object*.**Clear** ### Remove Removes a column from the listview. Syntax: *object*.**Remove** ( *Index* ) *Index* : A **Variant** --- either a 1-based **Long** position or a **String** key. ### \_NewEnum Returns the enumerator used by `For Each col In listView.ColumnHeaders`. Iterates columns in **Index** order. Syntax: *object*.**\_NewEnum** **As stdole.IUnknown** ## See Also * [ListView](/en/official/Reference/WinNativeCommonCtls/ListView/) -- the parent control * [ColumnHeader](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader) -- a single column header * [ListColumnAlignmentConstants](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader#listcolumnalignmentconstants) -- the **Alignment** values --- --- url: /zh/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders.md --- # ColumnHeaders 类 **ColumnHeaders** 集合是管理 **lvwReport** 视图中 [**ListView**](/official/Reference/WinNativeCommonCtls/ListView/) 列的入口。通过 `<listView>.ColumnHeaders` 访问;支持添加、删除、索引访问和 `For Each` 迭代。 该类标记为 `[COMCreatable(False)]` —— 用户代码通过父级 [**ListView**](/official/Reference/WinNativeCommonCtls/ListView/) 控件的 [**ColumnHeaders**](/official/Reference/WinNativeCommonCtls/ListView/#columnheaders) 属性访问 **ColumnHeaders**。 ```vb With ListView1.ColumnHeaders .Add , "name", "Name", 150 .Add , "size", "Size", 80, lvwColumnRight .Add , "date", "Date", 100, lvwColumnCenter End With ``` ## 属性 ### Count 集合中的列数。**Long**,只读。 ### Item 返回给定索引或给定键对应的 [**ColumnHeader**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader)。这是默认成员,因此 `ListView1.ColumnHeaders("name")` 无需写 `.Item("name")` 即可工作。 语法:*对象*.**Item** ( *Index* ) **As ColumnHeader** *Index* : **Variant** —— 可以是从1开始的 **Long** 位置或 **String** 键。 ## 方法 ### Add 向列表视图添加一列。 语法:*对象*.**Add** ( \[ *Index* ] \[, *Key* ] \[, *Text* ] \[, *Width* ] \[, *Alignment* ] \[, *Icon* ] ) **As ColumnHeader** *Index* : *可选* **Long**,指定插入新列的从1开始的位置。省略时,列被追加到末尾。 *Key* : *可选* **String**,用于查找列的名称。键在集合内必须唯一(否则将引发运行时错误35602)。 *Text* : *可选* **String**,指定列标题标签。 *Width* : *可选* **Variant**,指定列的像素宽度。省略时默认为96像素(经过缩放)。 *Alignment* : *可选* [**ListColumnAlignmentConstants**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader#listcolumnalignmentconstants) 的成员。默认:**lvwColumnLeft**。尝试在位置 `1` 添加非左对齐的列将引发运行时错误5。 *Icon* : *可选* **Variant**,标识标题图标 —— 可以是 [**ListView.ColumnHeaderIcons**](/official/Reference/WinNativeCommonCtls/ListView/#columnheadericons) 中从1开始的 **Long** 索引,或 **String** 键。 返回新创建的 [**ColumnHeader**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader)。 ### Clear 从列表视图中移除所有列。 语法:*对象*.**Clear** ### Remove 从列表视图中移除一列。 语法:*对象*.**Remove** ( *Index* ) *Index* : **Variant** —— 可以是从1开始的 **Long** 位置或 **String** 键。 ### \_NewEnum 返回 `For Each col In listView.ColumnHeaders` 使用的枚举器。按 **Index** 顺序迭代列。 语法:*对象*.**\_NewEnum** **As stdole.IUnknown** ## 另见 * [ListView](/official/Reference/WinNativeCommonCtls/ListView/) —— 父控件 * [ColumnHeader](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader) —— 单个列标题 * [ListColumnAlignmentConstants](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader#listcolumnalignmentconstants) —— **Alignment** 取值 --- --- url: /en/official/Reference/VB/ComboBox.md --- # ComboBox class A **ComboBox** is a Win32 native control that combines an edit field with a drop-down list of items, letting the user either type a value or pick one from the list. The control is normally placed on a **Form** or **UserControl** at design time. The default property is [**Text**](#text) and the default event is [**Change**](#change). ```vb Private Sub Form_Load() With Combo1 .AddItem "Apple" .AddItem "Banana" .AddItem "Cherry" .ListIndex = 0 End With End Sub Private Sub Combo1_Click() Debug.Print "Picked: " & Combo1.Text End Sub ``` ## Style [**Style**](#style) selects one of three Win32 combo-box variants ([**ComboBoxConstants**](/en/official/Reference/VBRUN/Constants/ComboBoxConstants)): | Constant | Value | Layout | |---------------------------|-------|--------------------------------------------------------------------------| | **vbComboDropdown** | 0 | Editable text + drop-down button + drop-down list. The default. | | **vbComboSimple** | 1 | Editable text + a permanently visible list (no drop-down button). | | **vbComboDropdownList** | 2 | Drop-down list only --- the user must pick a value; typing is disabled. | Changing **Style** at run time recreates the underlying window (the existing list contents and selection are preserved). [**Sorted**](#sorted) and [**IntegralHeight**](#integralheight) recreate the window the same way. ## Editing the list Items are held inside the OS combo-box control; the [**List**](#list) and [**ItemData**](#itemdata) arrays are projections onto that storage. Items are added with [**AddItem**](#additem), removed with [**RemoveItem**](#removeitem), and the whole list is cleared with [**Clear**](#clear). After each [**AddItem**](#additem) call, [**NewIndex**](#newindex) reports the position the item was inserted at --- useful when [**Sorted**](#sorted) is **True** and the position is not predictable from the call. ```vb Combo1.Sorted = True Combo1.AddItem "Cherry" Combo1.AddItem "Apple" ' Inserted at index 0 — Combo1.NewIndex = 0 Combo1.ItemData(Combo1.NewIndex) = 42 ``` ## Selection and text [**ListIndex**](#listindex) is the index of the selected item, or `-1` when nothing is selected. Setting it from code highlights the corresponding item and raises [**Click**](#click) (only if the value actually changes). [**TopIndex**](#topindex) controls which item appears at the top of the drop-down portion when it is open. [**Text**](#text) reads or writes the editable area, except in **vbComboDropdownList** mode where there is no edit field --- there, assigning a string searches the list with an exact, case-insensitive match and selects that item if found, doing nothing otherwise. Reading **Text** in any mode returns the current display text. For the styles that have an edit area (**vbComboDropdown** and **vbComboSimple**), [**SelStart**](#selstart), [**SelLength**](#sellength), and [**SelText**](#seltext) reflect or modify the user's text selection. Reading or writing any of these in **vbComboDropdownList** mode raises run-time error 380. ## OLE drag-and-drop [**OLEDragMode**](#oledragmode) controls source-side drags (only meaningful for the styles with an edit area --- when set to **vbOLEDragAutomatic**, dragging selected text in the edit area starts an OLE drag with that text as the data). [**OLEDropMode**](#oledropmode) controls drop-target behaviour and is restricted to **vbOLEDropNone** or **vbOLEDropManual**. ## Properties ### Appearance Determines how the control's border is drawn by the OS. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). ### BackColor The colour of the edit area and the list background, as an **OLE\_COLOR**. Defaults to the system window-background colour. ### BorderStyle A member of [**ControlBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants): **vbNoBorder** (0) or **vbFixedSingleBorder** (1, default). Changing it at run time re-syncs the border without recreating the window. ### CausesValidation Determines whether the previously focused control's [**Validate**](#validate) event runs before this control receives the focus. **Boolean**, default **True**. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a combo box. Always **vbComboBox**. ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the control accepts user input. A disabled combo box shows its current text but is dimmed and ignores keyboard and mouse interaction. **Boolean**, default **True**. ### Font The **StdFont** used to render text in the edit area and the drop-down list. The convenience properties **FontName**, **FontSize**, **FontBold**, **FontItalic**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. Changing the font may resize the control vertically when [**IntegralHeight**](#integralheight) is **True**. ### ForeColor The text colour, as an **OLE\_COLOR**. Defaults to the system window-text colour. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). For **vbComboDropdown** and **vbComboDropdownList** this is the height of the closed control (the drop-down portion is sized separately --- see [**MaxDropDownItems**](#maxdropdownitems)). For **vbComboSimple** it is the total height including the always-visible list. **Single**. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the control has focus. ### hWnd The Win32 window handle for the underlying combo box, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Read-only at run time. ### IntegralHeight When **True** (default), the OS adjusts the control's height so that the visible portion of the list shows whole items rather than partial ones. When **False**, the control honours [**Height**](#height) exactly. **Boolean**. Changing this at run time recreates the underlying window. ### ItemData A **LongPtr** that the application can associate with each item. Indexed by the same zero-based position used by [**List**](#list). Syntax: *object*.**ItemData**( *Index* ) \[ = *value* ] *Index* : *required* A **Long** zero-based item position. ```vb Combo1.AddItem "Apple" Combo1.ItemData(Combo1.NewIndex) = customerID ``` ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Single**. ### List The text of an item, indexed by zero-based position. Setting **List(*Index*)** removes the existing item at that position and reinserts the new value at the same index --- note that this can change the resulting position when [**Sorted**](#sorted) is **True**. Syntax: *object*.**List**( *Index* ) \[ = *string* ] ### ListCount The number of items in the list, as a **Long**. Read-only. ### ListIndex The zero-based index of the selected item, or `-1` if nothing is selected. **Long**. Assigning a value that differs from the current one selects that item and raises [**Click**](#click). ### Locked When **True**, the user can scroll and select within the control but cannot type into the edit area or change the selection with the keyboard or mouse wheel. **Boolean**, default **False**. Has no effect when [**Style**](#style) is **vbComboDropdownList** (where there is no edit area to lock). ### MaxDropDownItems The maximum number of items shown in the drop-down portion when the user opens it. **Long**, default `0` --- when zero, the OS chooses a height (typically eight items). ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### NewIndex The zero-based index at which the most recent [**AddItem**](#additem) call inserted its item, or `-1` if no item has been added since the control was created. Particularly useful when [**Sorted**](#sorted) is **True** and the resulting position cannot be predicted from the call. **Long**, read-only. ### OLEDragMode Whether the control's edit area can act as an automatic OLE drag source. A member of [**OLEDragConstants**](/en/official/Reference/VBRUN/Constants/OLEDragConstants): **vbOLEDragManual** (0, default --- call [**OLEDrag**](#oledrag) from code) or **vbOLEDragAutomatic** (1 --- dragging selected text in the edit area starts an OLE drag with that text as the data, and the drop effect **vbDropEffectMove** clears the selection). ### OLEDropMode How the control responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on a ComboBox. ### Opacity The control's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Requires Windows 8 or later for child controls. ### Parent A reference to the **Form** (or **UserControl**) that contains this control. Read-only. ### RightToLeft ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### SelLength The number of characters selected in the edit area. **Long**. Reading or writing this property when [**Style**](#style) is **vbComboDropdownList** raises run-time error 380. ### SelStart The zero-based position of the first selected character in the edit area, or the caret position when no text is selected. **Long**. Reading or writing this property when [**Style**](#style) is **vbComboDropdownList** raises run-time error 380. ### SelText The text currently selected in the edit area. Assigning a string replaces the selection with that string and positions the caret immediately after the inserted text. **String**. Reading or writing this property when [**Style**](#style) is **vbComboDropdownList** raises run-time error 380. ### Sorted When **True**, items added with [**AddItem**](#additem) are inserted in alphabetical order regardless of the *Index* argument; when **False** (default), they are inserted at the requested position (or appended). **Boolean**. Changing this at run time recreates the underlying window with the existing items re-added. ### Style Selects one of the three combo-box variants. A member of [**ComboBoxConstants**](/en/official/Reference/VBRUN/Constants/ComboBoxConstants): **vbComboDropdown** (0, default), **vbComboSimple** (1), or **vbComboDropdownList** (2). See [Style](#style) above for the layout differences. Changing **Style** at run time recreates the underlying window. ### TabIndex The position of the control in the form's TAB-key navigation order. **Long**. ### TabStop Whether the user can reach the control by pressing the **TAB** key. **Boolean**, default **True**. A disabled control is skipped regardless of this setting. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### Text The text shown in the edit area, or the text of the selected item when [**Style**](#style) is **vbComboDropdownList**. **Default property.** Syntax: *object*.**Text** \[ = *string* ] For **vbComboDropdown** and **vbComboSimple**, assigning a value writes it directly to the edit area and raises [**Change**](#change) if the new value differs from the current one. For **vbComboDropdownList**, assigning a value searches the list (case-insensitive, exact match) and selects the matching item if found; if no item matches, the assignment has no visible effect. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the control. ### Top The vertical distance from the top of the container to the top of the control. **Single**. ### TopIndex The zero-based index of the item shown at the top of the drop-down (or always-visible) list. Assigning a value scrolls the list so that item is at the top. **Long**. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered control. Default `-1` disables the effect. Requires Windows 8 or later for child controls. ### Visible Whether the control is shown. **Boolean**, default **True**. ### VisualStyles Whether the OS theme engine should be used when drawing the control. **Boolean**, default **True**. ### WhatsThisHelpID A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### WheelScrollEvent When **True** (default), mouse-wheel notifications over the drop-down list raise the [**Scroll**](#scroll) event; when **False**, the wheel still scrolls the list but [**Scroll**](#scroll) is suppressed. **Boolean**. VB6 never raised **Scroll** for wheel events; set this to **False** to match that behaviour exactly. ### Width The control's width. **Single**. ## Methods ### AddItem Inserts a new item into the list and stores the resulting position in [**NewIndex**](#newindex). Syntax: *object*.**AddItem** *Value* \[, *Index* ] *Value* : *required* A **String** giving the text of the new item. *Index* : *optional* A **Long** zero-based position to insert at. Omit to append to the end. Ignored when [**Sorted**](#sorted) is **True**. ### Clear Removes every item from the list and clears [**ListIndex**](#listindex). Syntax: *object*.**Clear** ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the control, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Forces an immediate repaint of the control. Syntax: *object*.**Refresh** ### RemoveItem Removes the item at the given zero-based position. Items below it shift up by one. Syntax: *object*.**RemoveItem** *Index* *Index* : *required* A **Long** zero-based position. ### SetFocus Moves the input focus to the control. The control must be both [**Visible**](#visible) and [**Enabled**](#enabled), or run-time error 5 (*Invalid procedure call or argument*) is raised. Syntax: *object*.**SetFocus** ### ShowWhatsThis Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Change Raised when the text in the edit area changes --- whether the user typed into it or code assigned a different value to [**Text**](#text). Not raised in **vbComboDropdownList** mode (where there is no edit area). **Default event.** Syntax: *object*\_**Change**( ) ### Click Raised after [**ListIndex**](#listindex) changes --- whether the user picked an item from the list or code assigned a different value to [**ListIndex**](#listindex). Assigning the current value again does not raise **Click**. Syntax: *object*\_**Click**( ) ### CloseUp Raised when the drop-down portion closes --- either because the user picked an item, clicked elsewhere, or pressed **Esc**. Not raised in **vbComboSimple** mode (the list is always visible). Syntax: *object*\_**CloseUp**( ) ### DblClick Raised when the user double-clicks an item in the always-visible list (**vbComboSimple** mode). Syntax: *object*\_**DblClick**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### DropDown Raised when the user opens the drop-down portion. Not raised in **vbComboSimple** mode (the list is always visible). Syntax: *object*\_**DropDown**( ) ### GotFocus Raised when the control receives the input focus. Syntax: *object*\_**GotFocus**( ) ### KeyDown Raised when the user presses any key while the control has focus. Syntax: *object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress Raised when the user types a character that produces an ANSI keystroke. Syntax: *object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp Raised when the user releases a key while the control has focus. Syntax: *object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus Raised when the control loses the input focus. Syntax: *object*\_**LostFocus**( ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Scroll Raised when the drop-down (or always-visible) list is scrolled --- by the scroll bar, the keyboard, or the mouse wheel. Wheel-driven scrolling can be silenced by setting [**WheelScrollEvent**](#wheelscrollevent) to **False**. Syntax: *object*\_**Scroll**( ) ### Validate Raised when the focus is moving to another control whose [**CausesValidation**](#causesvalidation) is **True**. Setting *Cancel* to **True** keeps the focus on this control. Syntax: *object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /zh/official/Reference/VB/ComboBox.md --- # ComboBox 类 **ComboBox**是一个Win32原生控件,将编辑字段与下拉列表组合在一起,允许用户键入值或从列表中选择。该控件通常在设计时放置在**Form**或**UserControl**上。默认属性是[**Text**](#text),默认事件是[**Change**](#change)。 ```vb Private Sub Form_Load() With Combo1 .AddItem "Apple" .AddItem "Banana" .AddItem "Cherry" .ListIndex = 0 End With End Sub Private Sub Combo1_Click() Debug.Print "Picked: " & Combo1.Text End Sub ``` ## 样式 [**Style**](#style)选择三种Win32组合框变体之一([**ComboBoxConstants**](/official/Reference/VBRUN/Constants/ComboBoxConstants)): | 常量 | 值 | 布局 | |---------------------------|-----|------------------------------------------------------------------------| | **vbComboDropdown** | 0 | 可编辑文本+下拉按钮+下拉列表。默认值。 | | **vbComboSimple** | 1 | 可编辑文本+永久可见列表(无下拉按钮)。 | | **vbComboDropdownList** | 2 | 仅下拉列表——用户必须选择一个值;禁止键入。 | 在运行时更改**Style**会重新创建底层窗口(现有列表内容和选择被保留)。[**Sorted**](#sorted)和[**IntegralHeight**](#integralheight)以相同方式重新创建窗口。 ## 编辑列表 条目保存在操作系统组合框控件内部;[**List**](#list)和[**ItemData**](#itemdata)数组是对该存储的映射。条目通过[**AddItem**](#additem)添加,通过[**RemoveItem**](#removeitem)移除,整个列表通过[**Clear**](#clear)清空。每次[**AddItem**](#additem)调用后,[**NewIndex**](#newindex)报告条目插入的位置——当[**Sorted**](#sorted)为**True**且位置无法从调用预测时非常有用。 ```vb Combo1.Sorted = True Combo1.AddItem "Cherry" Combo1.AddItem "Apple" ' 插入到索引0 — Combo1.NewIndex = 0 Combo1.ItemData(Combo1.NewIndex) = 42 ``` ## 选择和文本 [**ListIndex**](#listindex)是选中条目的索引,无选中时为`-1`。从代码设置它会高亮对应条目并引发[**Click**](#click)(仅当值实际更改时)。[**TopIndex**](#topindex)控制下拉部分打开时哪个条目出现在顶部。 [**Text**](#text)读取或写入可编辑区域,但在**vbComboDropdownList**模式下没有编辑字段——此时赋值字符串会以不区分大小写的精确匹配搜索列表,找到则选中该条目,否则不做任何操作。任何模式下读取**Text**都返回当前显示文本。 对于有编辑区域的样式(**vbComboDropdown**和**vbComboSimple**),[**SelStart**](#selstart)、[**SelLength**](#sellength)和[**SelText**](#seltext)反映或修改用户的文本选择。在**vbComboDropdownList**模式下读写这些属性会引发运行时错误380。 ## OLE拖放 [**OLEDragMode**](#oledragmode)控制源端拖动(仅对有编辑区域的样式有意义——当设置为**vbOLEDragAutomatic**时,在编辑区域拖动选中文本会以该文本为数据启动OLE拖动)。[**OLEDropMode**](#oledropmode)控制放置目标行为,仅限于**vbOLEDropNone**或**vbOLEDropManual**。 ## 属性 ### Appearance 确定操作系统如何绘制控件的边框。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。 ### BackColor 编辑区域和列表背景的颜色,类型为**OLE\_COLOR**。默认为系统窗口背景色。 ### BorderStyle [**ControlBorderStyleConstants**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants)的成员:**vbNoBorder** (0)或**vbFixedSingleBorder** (1,默认)。在运行时更改会重新同步边框而不重新创建窗口。 ### CausesValidation 确定先前获得焦点的控件的[**Validate**](#validate)事件是否在此控件获得焦点之前运行。**Boolean**,默认**True**。 ### ControlType 只读的[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值,将此控件标识为组合框。始终为**vbComboBox**。 ### DragIcon 控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自动拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual** (0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic** (1)。 ### Enabled 确定控件是否接受用户输入。禁用的组合框显示当前文本但变暗并忽略键盘和鼠标交互。**Boolean**,默认**True**。 ### Font 用于渲染编辑区域和下拉列表中文本的**StdFont**。便捷属性**FontName**、**FontSize**、**FontBold**、**FontItalic**、**FontStrikethru**和**FontUnderline**读写此对象的相应成员。当[**IntegralHeight**](#integralheight)为**True**时,更改字体可能会垂直调整控件大小。 ### ForeColor 文本颜色,类型为**OLE\_COLOR**。默认为系统窗口文本色。 ### Height 控件的高度,默认以缇为单位(或使用容器的**ScaleMode**单位)。对于**vbComboDropdown**和**vbComboDropdownList**,这是关闭状态的控件高度(下拉部分的大小单独控制——参见[**MaxDropDownItems**](#maxdropdownitems))。对于**vbComboSimple**,这是包括始终可见列表在内的总高度。**Single**。 ### HelpContextID 标识应用程序帮助文件中主题的**Long**值,当用户在控件具有焦点时按**F1**时检索。 ### hWnd 底层组合框的Win32窗口句柄,类型为**LongPtr**。只读。可用于传递给API函数。 ### Index 当控件是控件数组的一部分时,此实例在数组中的从零开始的**Long**索引。运行时只读。 ### IntegralHeight 当为**True**(默认)时,操作系统调整控件高度使列表可见部分显示完整条目而非部分条目。当为**False**时,控件精确遵循[**Height**](#height)。**Boolean**。在运行时更改此属性会重新创建底层窗口。 ### ItemData 应用程序可关联到每个条目的**LongPtr**。使用与[**List**](#list)相同的从零开始的位置索引。 语法:*object*.**ItemData**( *Index* ) \[ = *value* ] *Index* : *必需* 从零开始的**Long**条目位置。 ```vb Combo1.AddItem "Apple" Combo1.ItemData(Combo1.NewIndex) = customerID ``` ### Left 从容器的左边缘到控件左边缘的水平距离。**Single**。 ### List 条目的文本,按从零开始的位置索引。设置**List(*Index*)**会移除该位置的现有条目并在同一索引重新插入新值——注意当[**Sorted**](#sorted)为**True**时这可能改变最终位置。 语法:*object*.**List**( *Index* ) \[ = *string* ] ### ListCount 列表中的条目数,类型为**Long**。只读。 ### ListIndex 选中条目的从零开始的索引,无选中时为`-1`。**Long**。赋值与当前值不同的值会选中该条目并引发[**Click**](#click)。 ### Locked 当为**True**时,用户可以在控件中滚动和选择,但不能在编辑区域键入或用键盘或鼠标滚轮更改选择。**Boolean**,默认**False**。当[**Style**](#style)为**vbComboDropdownList**时无效(没有可锁定的编辑区域)。 ### MaxDropDownItems 用户打开下拉部分时显示的最大条目数。**Long**,默认`0`——为零时由操作系统选择高度(通常为8个条目)。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针位于控件上时用作鼠标光标的**StdPicture**。 ### MousePointer 指针位于控件上时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### NewIndex 最近一次[**AddItem**](#additem)调用插入条目的从零开始的索引,如果自控件创建以来未添加条目则为`-1`。当[**Sorted**](#sorted)为**True**且最终位置无法从调用预测时特别有用。**Long**,只读。 ### OLEDragMode 控件的编辑区域是否可作为自动OLE拖动源。[**OLEDragConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的成员:**vbOLEDragManual** (0,默认——从代码调用[**OLEDrag**](#oledrag))或**vbOLEDragAutomatic** (1——在编辑区域拖动选中文本会以该文本为数据启动OLE拖动,且放置效果**vbDropEffectMove**会清除选择)。 ### OLEDropMode 控件如何响应OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**或**vbOLEDropManual**。ComboBox不支持自动放置模式。 ### Opacity 控件的不透明度百分比(0--100,默认100)。超出范围的值在**Initialize**时被钳制。子控件需要Windows 8或更高版本。 ### Parent 对包含此控件的**Form**(或**UserControl**)的引用。只读。 ### RightToLeft ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: ### SelLength 编辑区域中选中的字符数。**Long**。当[**Style**](#style)为**vbComboDropdownList**时读写此属性会引发运行时错误380。 ### SelStart 编辑区域中第一个选中字符的从零开始的位置,或无文本选中时的插入点位置。**Long**。当[**Style**](#style)为**vbComboDropdownList**时读写此属性会引发运行时错误380。 ### SelText 编辑区域中当前选中的文本。赋值字符串会用该字符串替换选择并将插入点定位在插入文本之后。**String**。当[**Style**](#style)为**vbComboDropdownList**时读写此属性会引发运行时错误380。 ### Sorted 当为**True**时,通过[**AddItem**](#additem)添加的条目按字母顺序插入,不考虑*Index*参数;当为**False**(默认)时,条目插入到请求的位置(或追加到末尾)。**Boolean**。在运行时更改此属性会重新创建底层窗口并重新添加现有条目。 ### Style 选择三种组合框变体之一。[**ComboBoxConstants**](/official/Reference/VBRUN/Constants/ComboBoxConstants)的成员:**vbComboDropdown** (0,默认)、**vbComboSimple** (1)或**vbComboDropdownList** (2)。参见上方的[样式](#style)部分了解布局差异。在运行时更改**Style**会重新创建底层窗口。 ### TabIndex 控件在窗体TAB键导航顺序中的位置。**Long**。 ### TabStop 用户是否可以通过按**TAB**键到达控件。**Boolean**,默认**True**。禁用的控件无论此设置如何都会被跳过。 ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### Text 编辑区域中显示的文本,或当[**Style**](#style)为**vbComboDropdownList**时选中条目的文本。**默认属性。** 语法:*object*.**Text** \[ = *string* ] 对于**vbComboDropdown**和**vbComboSimple**,赋值会直接写入编辑区域,如果新值与当前值不同则引发[**Change**](#change)。对于**vbComboDropdownList**,赋值会搜索列表(不区分大小写,精确匹配),如果找到匹配项则选中;如果无匹配项,赋值无可见效果。 ### ToolTipText 当用户将鼠标悬停在控件上时作为工具提示显示的多行**String**。 ### Top 从容器顶部到控件顶部的垂直距离。**Single**。 ### TopIndex 下拉(或始终可见)列表顶部显示条目的从零开始的索引。赋值会滚动列表使该条目位于顶部。**Long**。 ### TransparencyKey 一个**OLE\_COLOR**值,设置后在渲染的控件中变为完全透明。默认`-1`禁用此效果。子控件需要Windows 8或更高版本。 ### Visible 控件是否显示。**Boolean**,默认**True**。 ### VisualStyles 绘制控件时是否使用操作系统主题引擎。**Boolean**,默认**True**。 ### WhatsThisHelpID 标识应用程序帮助文件中"这是什么?"弹出帮助主题的**Long**值。参见[**ShowWhatsThis**](#showwhatsthis)。 ### WheelScrollEvent 当为**True**(默认)时,下拉列表上的鼠标滚轮通知引发[**Scroll**](#scroll)事件;当为**False**时,滚轮仍会滚动列表但[**Scroll**](#scroll)被抑制。**Boolean**。VB6从不为滚轮事件引发**Scroll**;将此设置为**False**可完全匹配该行为。 ### Width 控件的宽度。**Single**。 ## 方法 ### AddItem 向列表插入新条目并将结果位置存储在[**NewIndex**](#newindex)中。 语法:*object*.**AddItem** *Value* \[, *Index* ] *Value* : *必需* 新条目文本的**String**。 *Index* : *可选* 要插入的从零开始的**Long**位置。省略则追加到末尾。当[**Sorted**](#sorted)为**True**时忽略。 ### Clear 移除列表中的所有条目并清除[**ListIndex**](#listindex)。 语法:*object*.**Clear** ### Drag 开始、完成或取消手动拖放操作。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel** (0)、**vbBeginDrag** (1,默认)或**vbEndDrag** (2)。 ### Move 在单次调用中重新定位并可选地调整控件大小。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**值。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从控件发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### Refresh 强制控件立即重绘。 语法:*object*.**Refresh** ### RemoveItem 移除给定从零开始位置处的条目。其下方的条目上移一位。 语法:*object*.**RemoveItem** *Index* *Index* : *必需* 从零开始的**Long**位置。 ### SetFocus 将输入焦点移至控件。控件必须同时[**Visible**](#visible)和[**Enabled**](#enabled),否则引发运行时错误5(*Invalid procedure call or argument*)。 语法:*object*.**SetFocus** ### ShowWhatsThis 以"这是什么?"弹出的方式显示由[**WhatsThisHelpID**](#whatsthishelpid)标识的主题。 语法:*object*.**ShowWhatsThis** ### ZOrder 将控件置于其同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront** (0,默认)或**vbSendToBack** (1)。 ## 事件 ### Change 编辑区域文本更改时引发——无论用户在其中键入还是代码赋值了不同的[**Text**](#text)值。在**vbComboDropdownList**模式下不引发(没有编辑区域)。**默认事件。** 语法:*object*\_**Change**( ) ### Click [**ListIndex**](#listindex)更改后引发——无论用户从列表中选择了条目还是代码赋值了不同的[**ListIndex**](#listindex)值。再次赋值当前值不会引发**Click**。 语法:*object*\_**Click**( ) ### CloseUp 下拉部分关闭时引发——因为用户选择了条目、点击了其他地方或按了**Esc**。在**vbComboSimple**模式下不引发(列表始终可见)。 语法:*object*\_**CloseUp**( ) ### DblClick 用户双击始终可见列表中的条目时引发(**vbComboSimple**模式)。 语法:*object*\_**DblClick**( ) ### DragDrop 手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### DropDown 用户打开下拉部分时引发。在**vbComboSimple**模式下不引发(列表始终可见)。 语法:*object*\_**DropDown**( ) ### GotFocus 控件获得输入焦点时引发。 语法:*object*\_**GotFocus**( ) ### KeyDown 用户在控件具有焦点时按下任意键引发。 语法:*object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress 用户键入产生ANSI击键的字符时引发。 语法:*object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp 用户在控件具有焦点时释放键引发。 语法:*object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus 控件失去输入焦点时引发。 语法:*object*\_**LostFocus**( ) ### OLECompleteDrag OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 用户将数据放置到目标控件上时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的数据格式时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Scroll 下拉(或始终可见)列表滚动时引发——通过滚动条、键盘或鼠标滚轮。通过将[**WheelScrollEvent**](#wheelscrollevent)设置为**False**可抑制滚轮驱动的滚动事件。 语法:*object*\_**Scroll**( ) ### Validate 焦点移动到另一个[**CausesValidation**](#causesvalidation)为**True**的控件时引发。将*Cancel*设置为**True**可使焦点保留在此控件上。 语法:*object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /en/official/Reference/VBRUN/Constants/ComboBoxConstants.md --- # ComboBoxConstants Style values for the **Style** property of a combo-box control. | Constant | Value | Description | |----------|-------|-------------| | **vbComboDropdown** | 0 | A drop-down combo box: the user can type a value or select one from the list. | | **vbComboSimple** | 1 | A simple combo box: the list is always visible and the user can also type a value. | | **vbComboDropdownList** | 2 | A drop-down list: the user must pick a value from the list. | --- --- url: /zh/official/Reference/VBRUN/Constants/ComboBoxConstants.md --- # ComboBoxConstants 组合框控件的**Style**属性的样式值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbComboDropdown** | 0 | 下拉组合框:用户可以输入值或从列表中选择。 | | **vbComboSimple** | 1 | 简单组合框:列表始终可见,用户也可以输入值。 | | **vbComboDropdownList** | 2 | 下拉列表:用户必须从列表中选择值。 | --- --- url: /en/packages/vbccr/lists/comboboxw.md description: >- ComboBoxW Control - VBCCR Development Manual, complete API reference based on source code --- # ComboBoxW Control Enhanced combo box control with support for visual styles, owner-draw, character casing control, and cue banner text. ## Enumerations ### CboStyleConstants | Constant | Value | Description | |----------|-------|-------------| | CboStyleDropDownCombo | 0 | Drop-down combo box | | CboStyleSimpleCombo | 1 | Simple combo box | | CboStyleDropDownList | 2 | Drop-down list | ### CboCharacterCasingConstants | Constant | Value | Description | |----------|-------|-------------| | CboCharacterCasingNormal | 0 | Normal casing | | CboCharacterCasingUpper | 1 | Uppercase | | CboCharacterCasingLower | 2 | Lowercase | ### CboDrawModeConstants | Constant | Value | Description | |----------|-------|-------------| | CboDrawModeNormal | 0 | Normal mode | | CboDrawModeOwnerDrawFixed | 1 | Owner-draw fixed height | | CboDrawModeOwnerDrawVariable | 2 | Owner-draw variable height | ## Properties ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` Whether to enable visual styles. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` Foreground color. ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE drag-drop mode. See common enumerations. ### Redraw ```vb Property Get Redraw() As Boolean Property Let Redraw(ByVal Value As Boolean) ``` Whether to allow redrawing. ### Style ```vb Property Get Style() As CboStyleConstants Property Let Style(ByVal Value As CboStyleConstants) ``` Combo box style. ### Locked ```vb Property Get Locked() As Boolean Property Let Locked(ByVal Value As Boolean) ``` Whether the control is locked (not editable). ### Text ```vb Property Get Text() As String Property Let Text(ByVal Value As String) ``` Edit box text. ### ExtendedUI ```vb Property Get ExtendedUI() As Boolean Property Let ExtendedUI(ByVal Value As Boolean) ``` Extended user interface mode. ### MaxDropDownItems ```vb Property Get MaxDropDownItems() As Long Property Let MaxDropDownItems(ByVal Value As Long) ``` Maximum number of items displayed in the drop-down list. ### IntegralHeight ```vb Property Get IntegralHeight() As Boolean Property Let IntegralHeight(ByVal Value As Boolean) ``` Whether to resize the list to fit complete items only. ### MaxLength ```vb Property Get MaxLength() As Long Property Let MaxLength(ByVal Value As Long) ``` Maximum number of characters in the edit box. ### CueBanner ```vb Property Get CueBanner() As String Property Let CueBanner(ByVal Value As String) ``` Cue banner text (displayed when the edit box is empty). ### UseListBackColor ```vb Property Get UseListBackColor() As Boolean Property Let UseListBackColor(ByVal Value As Boolean) ``` Whether to use a custom list background color. ### ListBackColor ```vb Property Get ListBackColor() As OLE_COLOR Property Let ListBackColor(ByVal Value As OLE_COLOR) ``` Drop-down list background color. ### UseListForeColor ```vb Property Get UseListForeColor() As Boolean Property Let UseListForeColor(ByVal Value As Boolean) ``` Whether to use a custom list foreground color. ### ListForeColor ```vb Property Get ListForeColor() As OLE_COLOR Property Let ListForeColor(ByVal Value As OLE_COLOR) ``` Drop-down list foreground color. ### Sorted ```vb Property Get Sorted() As Boolean Property Let Sorted(ByVal Value As Boolean) ``` Whether to automatically sort items. ### HorizontalExtent ```vb Property Get HorizontalExtent() As Long Property Let HorizontalExtent(ByVal Value As Long) ``` Horizontal scroll range of the drop-down list. ### DisableNoScroll ```vb Property Get DisableNoScroll() As Boolean Property Let DisableNoScroll(ByVal Value As Boolean) ``` Whether to disable the scroll bar instead of hiding it when items do not fill the list. ### CharacterCasing ```vb Property Get CharacterCasing() As CboCharacterCasingConstants Property Let CharacterCasing(ByVal Value As CboCharacterCasingConstants) ``` Character casing mode. ### DrawMode ```vb Property Get DrawMode() As CboDrawModeConstants Property Let DrawMode(ByVal Value As CboDrawModeConstants) ``` Drawing mode. ### IMEMode ```vb Property Get IMEMode() As CCIMEModeConstants Property Let IMEMode(ByVal Value As CCIMEModeConstants) ``` Input method editor mode. See common enumerations. ### ScrollTrack ```vb Property Get ScrollTrack() As Boolean Property Let ScrollTrack(ByVal Value As Boolean) ``` Whether to enable scroll tracking. ### AutoSelect ```vb Property Get AutoSelect() As Boolean Property Let AutoSelect(ByVal Value As Boolean) ``` Whether to automatically select matching items. ### AlwaysFindExact ```vb Property Get AlwaysFindExact() As Boolean Property Let AlwaysFindExact(ByVal Value As Boolean) ``` Whether to always perform exact find. ### ListCount ```vb Property Get ListCount() As Long ``` Number of list items. Read-only. ### List ```vb Property Get List(ByVal Index As Long) As String Property Let List(ByVal Index As Long, ByVal Value As String) ``` Access list items by index. ### ListIndex ```vb Property Get ListIndex() As Long Property Let ListIndex(ByVal Value As Long) ``` Index of the currently selected item. ### ItemData ```vb Property Get ItemData(ByVal Index As Long) As Long Property Let ItemData(ByVal Index As Long, ByVal Value As Long) ``` Item-associated data. ### NewIndex ```vb Property Get NewIndex() As Long ``` Index of the most recently added item. Read-only. ### TopIndex ```vb Property Get TopIndex() As Long Property Let TopIndex(ByVal Value As Long) ``` Index of the top visible item in the list. ### SelStart ```vb Property Get SelStart() As Long Property Let SelStart(ByVal Value As Long) ``` Starting position of selected text. ### SelLength ```vb Property Get SelLength() As Long Property Let SelLength(ByVal Value As Long) ``` Length of selected text. ### SelText ```vb Property Get SelText() As String Property Let SelText(ByVal Value As String) ``` Selected text. ### ItemHeight ```vb Property Get ItemHeight() As Single Property Let ItemHeight(ByVal Value As Single) ``` List item height. ### FieldHeight ```vb Property Get FieldHeight() As Single ``` Edit box height. Read-only. ### DroppedDown ```vb Property Get DroppedDown() As Boolean Property Let DroppedDown(ByVal Value As Boolean) ``` Whether the drop-down list is expanded. ### DropDownWidth ```vb Property Get DropDownWidth() As Long Property Let DropDownWidth(ByVal Value As Long) ``` Drop-down list width. ### DropDownHeight ```vb Property Get DropDownHeight() As Long Property Let DropDownHeight(ByVal Value As Long) ``` Drop-down list height. ### hWndEdit ```vb Property Get hWndEdit() As LongPtr ``` Edit box window handle. Read-only. ### hWndList ```vb Property Get hWndList() As LongPtr ``` List box window handle. Read-only. ### hWnd / hWndUserControl / Font / Enabled / MousePointer / MouseIcon / MouseTrack See common properties. ### Name / Tag / Parent / Container / Left / Top / Width / Height / Visible / ToolTipText / HelpContextID / WhatsThisHelpID / DragIcon / DragMode See standard extender properties. ## Methods ### AddItem ```vb Public Sub AddItem(ByVal Item As String, Optional ByVal Index As Variant) ``` Adds a list item. ### RemoveItem ```vb Public Sub RemoveItem(ByVal Index As Long) ``` Removes a list item. ### Clear ```vb Public Sub Clear() ``` Clears all list items. ### Refresh ```vb Public Sub Refresh() ``` Forces a redraw. ### FindItem ```vb Public Function FindItem(ByVal SearchString As String, Optional ByVal StartIndex As Long, Optional ByVal FindMode As Long) As Long ``` Finds a list item and returns its index. ### GetIdealHorizontalExtent ```vb Public Function GetIdealHorizontalExtent() As Long ``` Gets the ideal horizontal scroll range. ### SelectItem ```vb Public Sub SelectItem(ByVal SearchString As String) ``` Selects a matching list item. ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag-drop operation. ### Drag / ZOrder / SetFocus / Move See standard methods. ## Events ### Click ```vb Public Event Click() ``` ### DblClick ```vb Public Event DblClick() ``` ### Scroll ```vb Public Event Scroll() ``` Fired when the list scrolls. ### Change ```vb Public Event Change() ``` Fired when the text content changes. ### ContextMenu ```vb Public Event ContextMenu() ``` Context menu event. ### DropDown ```vb Public Event DropDown() ``` Drop-down list is expanding. ### CloseUp ```vb Public Event CloseUp() ``` Drop-down list is closing. ### ItemMeasure ```vb Public Event ItemMeasure(ByVal Index As Long, ByVal ItemWidth As Long, ByVal ItemHeight As Long) ``` Owner-draw measure event. ### ItemDraw ```vb Public Event ItemDraw(ByVal Index As Long, ByVal ItemState As Long, ByVal hDC As LongPtr, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` Owner-draw paint event. ### KeyDown / KeyUp / KeyPress ### MouseDown / MouseMove / MouseUp / MouseEnter / MouseLeave ### OLECompleteDrag / OLEDragDrop / OLEDragOver / OLEGiveFeedback / OLESetData / OLEStartDrag ## Code Examples ### Basic Usage ```vb ' Add items ComboBoxW1.AddItem "Apple" ComboBoxW1.AddItem "Banana" ComboBoxW1.ListIndex = 0 ' Set cue banner ComboBoxW1.CueBanner = "Please select a fruit..." ' Uppercase mode ComboBoxW1.CharacterCasing = CboCharacterCasingUpper ' Owner-draw mode ComboBoxW1.DrawMode = CboDrawModeOwnerDrawFixed ``` ### Owner-Draw Example ```vb Private Sub ComboBoxW1_ItemDraw(ByVal Index As Long, ByVal ItemState As Long, _ ByVal hDC As LongPtr, ByVal Left As Long, ByVal Top As Long, _ ByVal Right As Long, ByVal Bottom As Long) ' Draw custom list item End Sub ``` --- --- url: /en/official/Reference/VBA/Interaction/Command.md --- # Command, Command$ Returns the argument portion of the command line used to launch the program. Syntax: * **Command$()** * **Command()** The `$`-suffixed form returns a **String**; the unsuffixed form returns a **Variant** (**String**). For applications compiled to an executable, **Command** returns any arguments that appear after the name of the application on the command line. For example, with the command line: ``` MyApp /switch arg1 arg2 ``` **Command** returns `"/switch arg1 arg2"`. ### Example This example uses **Command** to retrieve the command-line arguments and split them into an array. ```vb Function GetCommandLine(Optional MaxArgs As Variant) As Variant Dim Ch As String, CmdLine As String, CmdLnLen As Long Dim InArg As Boolean, I As Long, NumArgs As Long If IsMissing(MaxArgs) Then MaxArgs = 10 ReDim ArgArray(MaxArgs) NumArgs = 0 InArg = False CmdLine = Command() CmdLnLen = Len(CmdLine) For I = 1 To CmdLnLen Ch = Mid(CmdLine, I, 1) If Ch <> " " And Ch <> vbTab Then If Not InArg Then If NumArgs = MaxArgs Then Exit For NumArgs = NumArgs + 1 InArg = True End If ArgArray(NumArgs) = ArgArray(NumArgs) & Ch Else InArg = False End If Next I ReDim Preserve ArgArray(NumArgs) GetCommandLine = ArgArray() End Function ``` ### See Also * [Shell](/en/official/Reference/VBA/Interaction/Shell) function * [Environ](/en/official/Reference/VBA/Interaction/Environ) function --- --- url: /zh/official/Reference/VBA/Interaction/Command.md --- # Command, Command$ 返回用于启动程序的命令行参数部分。 语法: * **Command$()** * **Command()** 带`$`后缀的形式返回**String**;不带后缀的形式返回**Variant**(**String**)。 对于编译为可执行文件的应用程序,**Command**返回命令行中应用程序名称之后出现的任何参数。例如,命令行: ``` MyApp /switch arg1 arg2 ``` **Command**返回`"/switch arg1 arg2"`。 ### 示例 本示例使用**Command**检索命令行参数并将其拆分为数组。 ```vb Function GetCommandLine(Optional MaxArgs As Variant) As Variant Dim Ch As String, CmdLine As String, CmdLnLen As Long Dim InArg As Boolean, I As Long, NumArgs As Long If IsMissing(MaxArgs) Then MaxArgs = 10 ReDim ArgArray(MaxArgs) NumArgs = 0 InArg = False CmdLine = Command() CmdLnLen = Len(CmdLine) For I = 1 To CmdLnLen Ch = Mid(CmdLine, I, 1) If Ch <> " " And Ch <> vbTab Then If Not InArg Then If NumArgs = MaxArgs Then Exit For NumArgs = NumArgs + 1 InArg = True End If ArgArray(NumArgs) = ArgArray(NumArgs) & Ch Else InArg = False End If Next I ReDim Preserve ArgArray(NumArgs) GetCommandLine = ArgArray() End Function ``` ### 另请参阅 * [Shell](/official/Reference/VBA/Interaction/Shell)函数 * [Environ](/official/Reference/VBA/Interaction/Environ)函数 --- --- url: /en/official/Reference/VB/CommandButton.md --- # CommandButton class A **CommandButton** is a Win32 native push-button control used to trigger an action --- a click-handler runs every time the user presses it. The control is normally placed on a **Form** or **UserControl** at design time. The default property is [**Value**](#value) and the default event is [**Click**](#click). ```vb Private Sub Form_Load() cmdOK.Caption = "&OK" cmdOK.Default = True ' Enter triggers it cmdCancel.Caption = "Cancel" cmdCancel.Cancel = True ' Esc triggers it End Sub Private Sub cmdOK_Click() Unload Me End Sub ``` ## Triggering a click A **CommandButton** raises [**Click**](#click) every time the user presses it --- by left-clicking, by pressing **Space** or **Enter** while it has focus, by typing the **Alt+** access key marked in the [**Caption**](#caption), by pressing **Esc** when [**Cancel**](#cancel) is **True**, or by pressing **Enter** anywhere on the form when [**Default**](#default) is **True**. Code can fire the same event by assigning **True** to [**Value**](#value): ```vb cmdOK.Value = True ' raises cmdOK_Click ``` [**Value**](#value) is reset to **False** immediately after the click handler returns, so reading it almost always returns **False**. ## Cancel and Default [**Cancel**](#cancel) and [**Default**](#default) are mutually-form-exclusive --- at most one button on a form can have either set to **True**. Assigning **True** to **Cancel** or **Default** on one button automatically clears the same property on whatever button held it before. Setting **Default = True** also gives the button the bold "default push-button" border. ## Caption and mnemonics The text on the button face comes from [**Caption**](#caption). An ampersand in the caption marks the next character as a keyboard mnemonic: pressing **Alt+** that character moves the focus to the button and raises [**Click**](#click) (provided no other control on the form competes for the same access key). Use `&&` to display a literal ampersand. ```vb cmdSave.Caption = "&Save && Close" ' renders as: Save & Close ``` ## Graphical style When [**Style**](#style) is **vbButtonGraphical**, the button is owner-drawn and displays the bitmaps assigned to [**Picture**](#picture), [**DownPicture**](#downpicture), and [**DisabledPicture**](#disabledpicture) alongside the caption. [**PictureAlignment**](#picturealignment), [**Padding**](#padding), and [**PictureDpiScaling**](#picturedpiscaling) control how the picture is positioned. Changing **Style** at run time recreates the underlying window. ## Properties ### Appearance Determines how the control's border is drawn by the OS. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). ### BackColor The background colour, as an **OLE\_COLOR**. Defaults to the system 3-D face colour. Honoured only when [**Style**](#style) is **vbButtonGraphical** --- the standard Win32 button always paints with the theme colour. ### Cancel When **True**, this button is fired by the **Esc** key from anywhere on its form. **Boolean**, default **False**. Only one **CommandButton** on a form can hold this property --- assigning **True** to a second button automatically clears it on the previous one. ### Caption The text displayed on the button. An ampersand marks the next character as a mnemonic; `&&` produces a literal ampersand. The string is read directly from the underlying window --- assigning to **Caption** is reflected immediately. Syntax: *object*.**Caption** \[ = *string* ] ### CausesValidation Determines whether the previously focused control's **Validate** event runs before this control receives the focus. **Boolean**, default **True**. **CommandButton** itself does not raise **Validate**. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a command button. Always **vbCommandButton**. ### Default When **True**, this button is fired by the **Enter** key from anywhere on its form (unless another control is currently consuming **Enter**). The button also displays the bold "default push-button" border. **Boolean**, default **False**. Only one **CommandButton** on a form can hold this property --- assigning **True** to a second button automatically clears it on the previous one. ### DisabledPicture A **StdPicture** drawn instead of [**Picture**](#picture) when the control is disabled and [**Style**](#style) is **vbButtonGraphical**. ### DownPicture A **StdPicture** drawn instead of [**Picture**](#picture) while the control is in the depressed state, when [**Style**](#style) is **vbButtonGraphical**. ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the control accepts user input. A disabled button shows its caption but is dimmed and ignores keyboard and mouse interaction (including its mnemonic and any **Cancel**/**Default** behaviour). **Boolean**, default **True**. ### Font The **StdFont** used to render [**Caption**](#caption). The convenience properties **FontName**, **FontSize**, **FontBold**, **FontItalic**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. ### ForeColor The text colour for the caption, as an **OLE\_COLOR**. Defaults to the system button-text colour. Honoured only when [**Style**](#style) is **vbButtonGraphical**. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). **Single**. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the control has focus. ### hWnd The Win32 window handle for the underlying button, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Read-only at run time. ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Single**. ### MaskColor ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### OLEDropMode How the control responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on a CommandButton. ### Opacity The control's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Requires Windows 8 or later for child controls. ### Padding The number of pixels of empty space inserted between the picture and the caption (when [**PictureAlignment**](#picturealignment) is **vbAlignLeft** or **vbAlignRight**) or between the caption and the corresponding edge (when **vbAlignTop** or **vbAlignBottom**). **Long**, default 2. Only meaningful when [**Style**](#style) is **vbButtonGraphical**. ### Parent A reference to the **Form** (or **UserControl**) that contains this control. Read-only. ### Picture A **StdPicture** drawn on the button when [**Style**](#style) is **vbButtonGraphical**. Assigning **Nothing** restores an empty picture rather than removing the bitmap surface. ### PictureAlignment How [**Picture**](#picture) is positioned relative to the caption when [**Style**](#style) is **vbButtonGraphical**. A member of [**AlignConstants**](/en/official/Reference/VBRUN/Constants/AlignConstants): **vbAlignNone**, **vbAlignTop** (default), **vbAlignBottom**, **vbAlignLeft**, **vbAlignRight**. ### PictureDpiScaling When **True**, scales [**Picture**](#picture), [**DownPicture**](#downpicture), and [**DisabledPicture**](#disabledpicture) by the current DPI factor before drawing. **Boolean**, default **False**. ### RightToLeft ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### Style Selects between the standard Win32 push-button appearance and an owner-drawn graphical button. A member of [**ButtonConstants**](/en/official/Reference/VBRUN/Constants/ButtonConstants): **vbButtonStandard** (0, default) or **vbButtonGraphical** (1). Changing **Style** at run time recreates the underlying window. ### TabIndex The position of the control in the form's TAB-key navigation order. **Long**. ### TabStop Whether the user can reach the control by pressing the **TAB** key. **Boolean**, default **True**. A disabled control is skipped regardless of this setting. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the control. ### Top The vertical distance from the top of the container to the top of the control. **Single**. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered control. Default `-1` disables the effect. Requires Windows 8 or later for child controls. ### UseMaskColor ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### Value A trigger for raising [**Click**](#click) from code. **Default property.** Syntax: *object*.**Value** \[ = *boolean* ] Assigning **True** raises [**Click**](#click) and resets **Value** to **False** immediately after the handler returns; assigning **False** does nothing. Reading **Value** therefore returns **False** in almost every situation. ```vb cmdOK.Value = True ' equivalent to a user click ``` ### Visible Whether the control is shown. **Boolean**, default **True**. ### VisualStyles Whether the OS theme engine should be used when drawing the control. **Boolean**, default **True**. ### WhatsThisHelpID A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### Width The control's width. **Single**. ## Methods ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Typically called from a [**MouseDown**](#mousedown) handler when [**DragMode**](#dragmode) is **vbManual**. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the control, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Forces an immediate repaint of the control. Syntax: *object*.**Refresh** ### SetFocus Moves the input focus to the control. The control must be both [**Visible**](#visible) and [**Enabled**](#enabled), or run-time error 5 (*Invalid procedure call or argument*) is raised. Syntax: *object*.**SetFocus** ### ShowWhatsThis Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Click Raised every time the button is pressed --- by mouse click, by **Space** or **Enter** while focused, by the **Alt+** access key in the [**Caption**](#caption), by **Esc** when [**Cancel**](#cancel) is **True**, by **Enter** when [**Default**](#default) is **True**, or by an assignment of **True** to [**Value**](#value). **Default event.** Syntax: *object*\_**Click**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus Raised when the control receives the input focus. Syntax: *object*\_**GotFocus**( ) ### KeyDown Raised when the user presses any key while the control has focus. Syntax: *object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress Raised when the user types a character that produces an ANSI keystroke. Syntax: *object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp Raised when the user releases a key while the control has focus. Syntax: *object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus Raised when the control loses the input focus. Syntax: *object*\_**LostFocus**( ) ### MouseDown Raised when the user presses any mouse button over the control. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the control. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the control. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) --- --- url: /zh/official/Reference/VB/CommandButton.md --- # CommandButton 类 **CommandButton**是Win32原生按钮控件,用于触发操作——每次用户按下时运行点击处理程序。控件通常在设计时放置在**Form**或**UserControl**上。默认属性是[**Value**](#value),默认事件是[**Click**](#click)。 ```vb Private Sub Form_Load() cmdOK.Caption = "&OK" cmdOK.Default = True ' Enter triggers it cmdCancel.Caption = "Cancel" cmdCancel.Cancel = True ' Esc triggers it End Sub Private Sub cmdOK_Click() Unload Me End Sub ``` ## 触发点击 **CommandButton**每次用户按下时引发[**Click**](#click)——通过左键点击、在有焦点时按**Space**或**Enter**、输入[**Caption**](#caption)中标记的**Alt+**访问键、当[**Cancel**](#cancel)为**True**时按**Esc**、或当[**Default**](#default)为**True**时在窗体任意位置按**Enter**。代码可以通过赋值**True**给[**Value**](#value)来触发相同事件: ```vb cmdOK.Value = True ' raises cmdOK_Click ``` [**Value**](#value)在点击处理程序返回后立即重置为**False**,因此读取它几乎总是返回**False**。 ## Cancel 和 Default [**Cancel**](#cancel)和[**Default**](#default)是窗体互斥的——窗体上最多只有一个按钮可以将其中一个设为**True**。在一个按钮上赋值**True**给**Cancel**或**Default**会自动清除之前持有该属性的按钮上的相同属性。设置**Default = True**还会给按钮加粗"默认按钮"边框。 ## 标题和助记符 按钮面上的文本来自[**Caption**](#caption)。标题中的和号将下一个字符标记为键盘助记符:按\*\*Alt+\*\*该字符将焦点移到按钮并引发[**Click**](#click)(前提是窗体上没有其他控件竞争同一访问键)。使用`&&`显示字面和号。 ```vb cmdSave.Caption = "&Save && Close" ' renders as: Save & Close ``` ## 图形样式 当[**Style**](#style)为**vbButtonGraphical**时,按钮为所有者绘制,显示赋给[**Picture**](#picture)、[**DownPicture**](#downpicture)和[**DisabledPicture**](#disabledpicture)的位图以及标题。[**PictureAlignment**](#picturealignment)、[**Padding**](#padding)和[**PictureDpiScaling**](#picturedpiscaling)控制图片的定位方式。在运行时更改**Style**会重新创建底层窗口。 ## 属性 ### Appearance 决定操作系统绘制控件边框的方式。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。 ### BackColor 背景色,作为**OLE\_COLOR**。默认为系统3D表面颜色。仅在[**Style**](#style)为**vbButtonGraphical**时有效——标准Win32按钮始终使用主题颜色绘制。 ### Cancel 当**True**时,此按钮可从窗体任意位置由**Esc**键触发。**Boolean**,默认**False**。窗体上只能有一个**CommandButton**持有此属性——在第二个按钮上赋值**True**会自动清除前一个按钮上的该属性。 ### Caption 按钮上显示的文本。和号将下一个字符标记为助记符;`&&`产生字面和号。字符串直接从底层窗口读取——赋值给**Caption**会立即反映。 语法:*object*.**Caption** \[ = *string* ] ### CausesValidation 决定先前聚焦控件的**Validate**事件是否在此控件获得焦点之前运行。**Boolean**,默认**True**。**CommandButton**自身不引发**Validate**。 ### ControlType 标识此控件为命令按钮的只读[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值。始终为**vbCommandButton**。 ### Default 当**True**时,此按钮可从窗体任意位置由**Enter**键触发(除非另一个控件当前正在消费**Enter**)。按钮还显示粗体"默认按钮"边框。**Boolean**,默认**False**。窗体上只能有一个**CommandButton**持有此属性——在第二个按钮上赋值**True**会自动清除前一个按钮上的该属性。 ### DisabledPicture 当控件禁用且[**Style**](#style)为**vbButtonGraphical**时,替代[**Picture**](#picture)绘制的**StdPicture**。 ### DownPicture 当控件处于按下状态且[**Style**](#style)为**vbButtonGraphical**时,替代[**Picture**](#picture)绘制的**StdPicture**。 ### DragIcon 在控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自行拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual**(0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic**(1)。 ### Enabled 决定控件是否接受用户输入。禁用的按钮显示其标题但变暗,忽略键盘和鼠标交互(包括其助记符和任何**Cancel**/**Default**行为)。**Boolean**,默认**True**。 ### Font 用于渲染[**Caption**](#caption)的**StdFont**。便捷属性**FontName**、**FontSize**、**FontBold**、**FontItalic**、**FontStrikethru**和**FontUnderline**读写此对象的对应成员。 ### ForeColor 标题的文本颜色,作为**OLE\_COLOR**。默认为系统按钮文本颜色。仅在[**Style**](#style)为**vbButtonGraphical**时有效。 ### Height 控件的高度,默认以缇为单位(或以容器的**ScaleMode**单位)。**Single**。 ### HelpContextID 标识应用程序帮助文件中主题的**Long**,当用户在控件有焦点时按**F1**时检索。 ### hWnd 底层按钮的Win32窗口句柄,作为**LongPtr**。只读。适用于传递给API函数。 ### Index 当控件是控件数组的一部分时,此实例在数组中的**Long**零基索引。运行时只读。 ### Left 从容器左边缘到控件左边缘的水平距离。**Single**。 ### MaskColor ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针在控件上方时用作鼠标光标的**StdPicture**。 ### MousePointer 指针在控件上方时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### OLEDropMode 控件如何响应OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**或**vbOLEDropManual**。CommandButton不支持自动放置模式。 ### Opacity 控件的不透明度百分比(0--100,默认100)。超出范围的值在**Initialize**时被钳制。子控件需要Windows 8或更高版本。 ### Padding 在图片和标题之间插入的空像素数(当[**PictureAlignment**](#picturealignment)为**vbAlignLeft**或**vbAlignRight**时)或在标题和对应边缘之间(当**vbAlignTop**或**vbAlignBottom**时)。**Long**,默认2。仅在[**Style**](#style)为**vbButtonGraphical**时有意义。 ### Parent 对包含此控件的**Form**(或**UserControl**)的引用。只读。 ### Picture 当[**Style**](#style)为**vbButtonGraphical**时绘制在按钮上的**StdPicture**。赋值**Nothing**恢复空图片而非移除位图表面。 ### PictureAlignment 当[**Style**](#style)为**vbButtonGraphical**时[**Picture**](#picture)相对于标题的定位方式。[**AlignConstants**](/official/Reference/VBRUN/Constants/AlignConstants)的成员:**vbAlignNone**、**vbAlignTop**(默认)、**vbAlignBottom**、**vbAlignLeft**、**vbAlignRight**。 ### PictureDpiScaling 当**True**时,绘制前按当前DPI因子缩放[**Picture**](#picture)、[**DownPicture**](#downpicture)和[**DisabledPicture**](#disabledpicture)。**Boolean**,默认**False**。 ### RightToLeft ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: ### Style 在标准Win32按钮外观和所有者绘制图形按钮之间选择。[**ButtonConstants**](/official/Reference/VBRUN/Constants/ButtonConstants)的成员:**vbButtonStandard**(0,默认)或**vbButtonGraphical**(1)。在运行时更改**Style**会重新创建底层窗口。 ### TabIndex 控件在窗体TAB键导航顺序中的位置。**Long**。 ### TabStop 用户是否可以通过按**TAB**键到达控件。**Boolean**,默认**True**。禁用的控件无论此设置如何都会被跳过。 ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### ToolTipText 用户悬停在控件上方时作为工具提示显示的多行**String**。 ### Top 从容器顶部到控件顶部的垂直距离。**Single**。 ### TransparencyKey 设置后成为渲染控件中完全透明的**OLE\_COLOR**。默认`-1`禁用效果。子控件需要Windows 8或更高版本。 ### UseMaskColor ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: ### Value 从代码引发[**Click**](#click)的触发器。**默认属性。** 语法:*object*.**Value** \[ = *boolean* ] 赋值**True**引发[**Click**](#click)并在处理程序返回后立即将**Value**重置为**False**;赋值**False**不做任何事。因此读取**Value**在几乎所有情况下返回**False**。 ```vb cmdOK.Value = True ' equivalent to a user click ``` ### Visible 控件是否显示。**Boolean**,默认**True**。 ### VisualStyles 绘制控件时是否使用操作系统主题引擎。**Boolean**,默认**True**。 ### WhatsThisHelpID 标识应用程序帮助文件中"这是什么?"帮助弹出主题的**Long**。参见[**ShowWhatsThis**](#showwhatsthis)。 ### Width 控件的宽度。**Single**。 ## 方法 ### Drag 开始、完成或取消手动拖放操作。通常在[**DragMode**](#dragmode)为**vbManual**时从[**MouseDown**](#mousedown)处理程序调用。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel**(0)、**vbBeginDrag**(1,默认)或**vbEndDrag**(2)。 ### Move 在单次调用中重新定位并可选地调整控件的尺寸。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从控件发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### Refresh 强制立即重绘控件。 语法:*object*.**Refresh** ### SetFocus 将输入焦点移到控件。控件必须同时[**Visible**](#visible)和[**Enabled**](#enabled),否则引发运行时错误5(*无效的过程调用或参数*)。 语法:*object*.**SetFocus** ### ShowWhatsThis 以"这是什么?"弹窗形式显示由[**WhatsThisHelpID**](#whatsthishelpid)标识的主题。 语法:*object*.**ShowWhatsThis** ### ZOrder 将控件带到同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront**(0,默认)或**vbSendToBack**(1)。 ## 事件 ### Click 每次按钮被按下时引发——通过鼠标点击、有焦点时按**Space**或**Enter**、[**Caption**](#caption)中的**Alt+**访问键、[**Cancel**](#cancel)为**True**时按**Esc**、[**Default**](#default)为**True**时按**Enter**、或赋值**True**给[**Value**](#value)。**默认事件。** 语法:*object*\_**Click**( ) ### DragDrop 当手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 当手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus 当控件获得输入焦点时引发。 语法:*object*\_**GotFocus**( ) ### KeyDown 当控件有焦点时用户按下任意键时引发。 语法:*object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress 当用户输入产生ANSI按键的字符时引发。 语法:*object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp 当控件有焦点时用户释放键时引发。 语法:*object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus 当控件失去输入焦点时引发。 语法:*object*\_**LostFocus**( ) ### MouseDown 当用户在控件上方按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 当光标在控件上方移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 当用户在控件上方释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag 当OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 当用户在目标控件上放置数据时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver 当OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 在拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的格式的数据时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag 在OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) --- --- url: /en/packages/vbccr/buttons/commandbuttonw.md description: >- CommandButtonW Control - VBCCR Development Manual, complete API reference based on source code --- # CommandButtonW Control Enhanced CommandButton control with support for visual styles, split button, owner-draw, and coexistence of picture and caption. ## Enumerations ### CmdImageListAlignmentConstants | Constant | Value | Description | |----------|-------|-------------| | CmdImageListAlignmentLeft | 0 | Left alignment | | CmdImageListAlignmentRight | 1 | Right alignment | | CmdImageListAlignmentTop | 2 | Top alignment | | CmdImageListAlignmentBottom | 3 | Bottom alignment | | CmdImageListAlignmentCenter | 4 | Center alignment | ### CmdDrawModeConstants | Constant | Value | Description | |----------|-------|-------------| | CmdDrawModeNormal | 0 | Normal mode | | CmdDrawModeOwnerDraw | 1 | Owner-draw mode | ## Properties ### Default ```vb Property Get Default() As Boolean Property Let Default(ByVal Value As Boolean) ``` Whether this is the default button (triggered by Enter key). ### Cancel ```vb Property Get Cancel() As Boolean Property Let Cancel(ByVal Value As Boolean) ``` Whether this is the cancel button (triggered by Esc key). ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` Whether to enable visual styles. ### Appearance ```vb Property Get Appearance() As CCAppearanceConstants Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` Appearance style. See Common Enumerations. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` Foreground color. ### ImageList ```vb Property Get ImageList() As Variant Property Let ImageList(ByVal Value As Variant) Property Set ImageList(ByVal Value As Variant) ``` Associated ImageList control. ### ImageListAlignment ```vb Property Get ImageListAlignment() As CmdImageListAlignmentConstants Property Let ImageListAlignment(ByVal Value As CmdImageListAlignmentConstants) ``` ImageList icon alignment. ### ImageListMargin ```vb Property Get ImageListMargin() As Single Property Let ImageListMargin(ByVal Value As Single) ``` ImageList icon margin. ### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` Caption text. ### Alignment ```vb Property Get Alignment() As VBRUN.AlignmentConstants Property Let Alignment(ByVal Value As VBRUN.AlignmentConstants) ``` Horizontal text alignment. ### VerticalAlignment ```vb Property Get VerticalAlignment() As CCVerticalAlignmentConstants Property Let VerticalAlignment(ByVal Value As CCVerticalAlignmentConstants) ``` Vertical text alignment. See Common Enumerations. ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` Picture. ### PictureAndCaption ```vb Property Get PictureAndCaption() As Boolean Property Let PictureAndCaption(ByVal Value As Boolean) ``` Whether to display both picture and caption simultaneously. Requires comctl32.dll 6.1 or later. ### WordWrap ```vb Property Get WordWrap() As Boolean Property Let WordWrap(ByVal Value As Boolean) ``` Whether to enable word wrap. ### Transparent ```vb Property Get Transparent() As Boolean Property Let Transparent(ByVal Value As Boolean) ``` Whether to use a transparent background (effective at run time). ### SplitButton ```vb Property Get SplitButton() As Boolean Property Let SplitButton(ByVal Value As Boolean) ``` Whether to display as a split button. Requires comctl32.dll 6.1 or later. ### SplitButtonAlignment ```vb Property Get SplitButtonAlignment() As CCLeftRightAlignmentConstants Property Let SplitButtonAlignment(ByVal Value As CCLeftRightAlignmentConstants) ``` Split button alignment. See Common Enumerations. ### SplitButtonNoSplit ```vb Property Get SplitButtonNoSplit() As Boolean Property Let SplitButtonNoSplit(ByVal Value As Boolean) ``` Whether the split button hides the split line. ### SplitButtonGlyph ```vb Property Get SplitButtonGlyph() As IPictureDisp Property Let SplitButtonGlyph(ByVal Value As IPictureDisp) Property Set SplitButtonGlyph(ByVal Value As IPictureDisp) ``` Drop-down arrow icon for the split button. ### Style ```vb Property Get Style() As VBRUN.ButtonConstants Property Let Style(ByVal Value As VBRUN.ButtonConstants) ``` Button style (standard or graphical). ### DisabledPicture ```vb Property Get DisabledPicture() As IPictureDisp Property Let DisabledPicture(ByVal Value As IPictureDisp) Property Set DisabledPicture(ByVal Value As IPictureDisp) ``` Disabled state picture. ### DownPicture ```vb Property Get DownPicture() As IPictureDisp Property Let DownPicture(ByVal Value As IPictureDisp) Property Set DownPicture(ByVal Value As IPictureDisp) ``` Pressed state picture. ### UseMaskColor ```vb Property Get UseMaskColor() As Boolean Property Let UseMaskColor(ByVal Value As Boolean) ``` Whether to use mask color. ### MaskColor ```vb Property Get MaskColor() As OLE_COLOR Property Let MaskColor(ByVal Value As OLE_COLOR) ``` Mask color. ### DrawMode ```vb Property Get DrawMode() As CmdDrawModeConstants Property Let DrawMode(ByVal Value As CmdDrawModeConstants) ``` Draw mode. ### Value ```vb Property Get Value() As Boolean Property Let Value(ByVal NewValue As Boolean) ``` Button value; setting to True triggers the Click event. ### Pushed ```vb Property Get Pushed() As Boolean Property Let Pushed(ByVal Value As Boolean) ``` Whether the control is in a pressed state. ### Hot ```vb Property Get Hot() As Boolean ``` Whether the control is in a hot state. Read-only. ### DroppedDown ```vb Property Get DroppedDown() As Boolean Property Let DroppedDown(ByVal Value As Boolean) ``` Whether the split button is dropped down. ### hWnd / hWndUserControl / Font / Enabled / OLEDropMode / MousePointer / MouseIcon / MouseTrack / RightToLeft / RightToLeftLayout / RightToLeftMode See common properties. ### Name / Tag / Parent / Container / Left / Top / Width / Height / Visible / ToolTipText / HelpContextID / WhatsThisHelpID / DragIcon / DragMode See standard extender properties. ## Methods ### Refresh ```vb Public Sub Refresh() ``` Forces a repaint. ### PerformClick ```vb Public Sub PerformClick() ``` Simulates a user clicking the button. ### SetShield ```vb Public Function SetShield(ByVal State As Boolean) As Long ``` Sets the UAC shield icon. Returns 1 on success. Requires comctl32.dll 6.1 or later. ### GetIdealSize ```vb Public Sub GetIdealSize(ByRef Width As Single, ByRef Height As Single) ``` Gets the ideal size for the button. Requires comctl32.dll 6.0 or later. ### OLEDrag ```vb Public Sub OLEDrag() ``` ### Drag / ZOrder / SetFocus / Move See standard methods. ## Events ### Click ```vb Public Event Click() ``` Single click. ### DblClick ```vb Public Event DblClick() ``` Double click. ### HotChanged ```vb Public Event HotChanged() ``` Hot state changed. ### DropDown ```vb Public Event DropDown() ``` Fired when the split button drops down. ### OwnerDraw ```vb Public Event OwnerDraw(ByVal DisplayAsDefault As Boolean, ByVal ItemAction As Long, ByVal ItemState As Long, ByVal hDC As LongPtr, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` Owner-draw event. ### KeyDown / KeyUp / KeyPress ### MouseDown / MouseMove / MouseUp / MouseEnter / MouseLeave ### OLECompleteDrag / OLEDragDrop / OLEDragOver / OLEGiveFeedback / OLESetData / OLEStartDrag ## Code Examples ### Basic Usage ```vb ' Set as default button CommandButtonW1.Default = True CommandButtonW1.Caption = "OK" ' Graphical button CommandButtonW1.Style = vbButtonGraphical Set CommandButtonW1.Picture = LoadPicture("ok.bmp") ' Picture and caption coexistence CommandButtonW1.PictureAndCaption = True ``` ### Split Button ```vb CommandButtonW1.SplitButton = True Private Sub CommandButtonW1_DropDown() ' Display context menu PopupMenu mnuOptions End Sub ``` ### UAC Shield Icon ```vb CommandButtonW1.SetShield True ``` ### Get Ideal Size ```vb Dim w As Single, h As Single CommandButtonW1.GetIdealSize w, h CommandButtonW1.Width = w CommandButtonW1.Height = h ``` --- --- url: /en/packages/vbccr/buttons/commandlink.md description: >- CommandLink Control - VBCCR Development Manual, complete API reference based on source code --- # CommandLink Control Windows CommandLink button control that displays a caption, hint text, and an optional icon. ## Enumerations No control-specific enumerations. ## Properties ### Default ```vb Property Get Default() As Boolean Property Let Default(ByVal Value As Boolean) ``` Whether this is the default button. ### Cancel ```vb Property Get Cancel() As Boolean Property Let Cancel(ByVal Value As Boolean) ``` Whether this is the cancel button. ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` Whether to enable visual styles. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### ImageList ```vb Property Get ImageList() As Variant Property Let ImageList(ByVal Value As Variant) Property Set ImageList(ByVal Value As Variant) ``` Associated ImageList control. ### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` Caption text. ### Hint ```vb Property Get Hint() As String Property Let Hint(ByVal Value As String) ``` Hint text (description text below the caption). ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` Icon. ### Transparent ```vb Property Get Transparent() As Boolean Property Let Transparent(ByVal Value As Boolean) ``` Transparent background (effective at run time). ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` Right-to-left display. ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` Right-to-left mirrored layout. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` Right-to-left mode. See Common Enumerations. ### Value ```vb Property Get Value() As Boolean Property Let Value(ByVal NewValue As Boolean) ``` Button value; setting to True triggers the Click event. ### Pushed ```vb Property Get Pushed() As Boolean Property Let Pushed(ByVal Value As Boolean) ``` Whether the control is in a pressed state. ### Hot ```vb Property Get Hot() As Boolean ``` Whether the control is in a hot state. Read-only. ### hWnd / hWndUserControl / Font / Enabled / OLEDropMode / MousePointer / MouseIcon / MouseTrack See common properties. ### Name / Tag / Parent / Container / Left / Top / Width / Height / Visible / ToolTipText / HelpContextID / WhatsThisHelpID / DragIcon / DragMode See standard extender properties. ## Methods ### Refresh ```vb Public Sub Refresh() ``` Forces a repaint. ### PerformClick ```vb Public Sub PerformClick() ``` Simulates a user click. ### SetShield ```vb Public Function SetShield(ByVal State As Boolean) As Long ``` Sets the UAC shield icon. Returns 1 on success. ### GetIdealHeight ```vb Public Function GetIdealHeight() As Single ``` Gets the ideal height for the control. ### OLEDrag ```vb Public Sub OLEDrag() ``` ### Drag / ZOrder / SetFocus / Move See standard methods. ## Events ### Click ```vb Public Event Click() ``` Single click. ### DblClick ```vb Public Event DblClick() ``` Double click. ### HotChanged ```vb Public Event HotChanged() ``` Hot state changed. ### KeyDown / KeyUp / KeyPress ### MouseDown / MouseMove / MouseUp / MouseEnter / MouseLeave ### OLECompleteDrag / OLEDragDrop / OLEDragOver / OLEGiveFeedback / OLESetData / OLEStartDrag ## Code Examples ### Basic Usage ```vb ' Set up a CommandLink CommandLink1.Caption = "Save File" CommandLink1.Hint = "Save the current document to disk" CommandLink1.Default = True ' Set UAC shield icon CommandLink1.SetShield True ' Get ideal height and adjust CommandLink1.Height = CommandLink1.GetIdealHeight ``` ### Responding to Clicks ```vb Private Sub CommandLink1_Click() MsgBox "You clicked: " & CommandLink1.Caption End Sub ``` --- --- url: /en/official/Features/Language/Comments.md --- # New Comment Syntax ## Block and Inline Comments You can now use `/* */` syntax. For example, `Sub Foo(bar As Long /* out */)` or: ```c /* Everything here is a comment until: */ ``` ### Example ```vb ' Single-line comment using the apostrophe Sub Greet(ByVal name As String /* in */) Debug.Print "Hello, " & name ' inline comment /* This block comment spans multiple lines. */ End Sub ``` --- --- url: /en/packages/vbccr/author.md description: >- Official documentation for VBCCR - VB Common Controls Replacement library, covering StdEXE/OCX usage guide, OCX2StdEXE tool, compilation options and version history. --- # Common Controls Replacement **\[official document]** This page is a translation of the official documentation written by the original author. The original Word document was converted to Markdown using AI by woeoio. ## Utility Note- This document accompanies version 3.3 of the StdEXE utility. The changelog of the utility is in a table at the end of this document. Version 3.3 adds the capability of using VBCCRxx.OCX up to version 1.7 and VBFLXGRDxx.OCX up to the new version 1.6. Since November 2012, a VBForums user named Krool has been developing a set of replacements for the Windows Common Controls. Replacing these controls has been discussed by many and successfully done by none, until now. Krool has been working on this primarily by himself with lots of debugging and feedback within the forum. In the middle of 2017 Krool took on the task of addressing a replacement for the MSFlexGrid control. He decided to do this development in a separate set of threads on the forum although it is very similar to the other replacement controls. This package hopefully will offer you some tips on how to set up and use these controls in your program and guide you to reduce or eliminate dependencies on any files other than your code. Krool’s controls will show up in your Toolbox similar to what is shown below. They function just like other controls that are built-in to VB6. Just drop them onto forms or onto other controls. Those that you can add are shown below. What can these new controls do for you and programs you write or maintain? * They use Unicode. If you look on the Internet you will find a control here and a control there which use Unicode but Krool’s two packages allow you to do 34 Windows common controls in one cohesive package. * They have enhancements beyond what is found in the common controls VB6 and VBA programmers have been using for years. * They can use themes, a complicated set of things made simpler here so that each of your programs can have a modern look and not look like it came out of Windows 95. * The controls can be embedded into your code so that your final EXE file has no dependencies and is just the one executable file that does not require registration or installation (e.g., you could run it from a thumb drive). Alternatively, it can use the traditional control versions (using .OCX files) but with ’side-by-side’ so that the .OCX files don’t have to be registered on the end-user’s PC but rather reside in your program’s folder. These two techniques enable you to have truly portable solutions for your users. * Krool’s code gets more stable all the time but users and the author are available to help with troubleshooting, inserting new features, etc. all the time. * I have included in this package a user guide, not to each of the controls themselves but the packages in their entirety (this document). * A utility named OCX2StdEXE is included that helps you keep up-to-date on the latest controls but also to enable you to use the OCX versions for your program development but use the StdEXE version to make the compiled code program. * The EXE file is totally self-contained and has no external dependencies. It does not need an installer on the end-user’s PC and it does not need to be distributed with an .OCX control file that needs t be registered on the end-user’s PC. * Using Krool’s StdEXE controls (not the traditional .OCX control file) in the IDE is not completely safe although he has worked hard to minimize the crashes in the IDE. Developing in the IDE with the .ocx version is safer and much faster and this utility enables you to have this benefit while at the same time producing you final code with all of the controls embedded in the program, requiring no dependencies. * Using the StdEXE versions of the controls in the IDE not only has some stability risks but it causes the controls code to be re-compiled every time you compile your program (on my PC using the .ocx version causes compile on a typical program to be less than 3 seconds but with the StdEXE controls it takes 25 seconds. Doing this once is okay but gets really cumbersome to do this over and over during development. With the OCX2StdEXE utility you develop using the .ocx version (speed and stability) and then finally compile with the StdEXE to get the file size and no-dependency benefits. ## User Guide Krool has a package of routines that do an incredible number of things but there are many things the programmer should understand to fully utilize these packages. Items addressed include: * Installation * The two different approaches, compiled .OCX controls and controls embedded into your program that get compiled each time with your code. How to choose which version to use and why? Can or should you use both of them? * Set-up * How to set up for the frequent updates to minimize the hassles of frequent updates as bugs are fixed and features are added. * Required type libraries. * What else do you need to use these control packages? * What are visual themes and should I use them? How? * What does ’side-by-side mean? Should I use this and how? * What are manifests, should I use them and how should I use them? ## Introduction VB6 controls come in two versions. The simplest is when the source code for the control is in your program and when your code is compiled the code for the control is compiled with it. The compiled code for the control becomes part of your program. Your program is standalone and does not rely on any external files other than those included with Windows in order to run nor do any files need to be copied to or registered on the users’ PC’s. The disadvantage of this method is that the control’s code must be compiled every time you compile your code as you are developing the program. Also, most companies who author controls do not want to give away their code so they won’t distribute the source code for each control. Thus, this method of making controls is not very common. The other way to do controls is to compile one or more controls into a file that has an OCX extension, (which stands for OLE Control eXtension or just ActiveX controls). The programmer who uses the OCX file never sees the source code and the code doesn’t need to be compiled over and over. One of the disadvantages of this type of control package is that the controls are not a part of the program and must be sent to each end-user and, for reasons well beyond this document, the OCX file must be registered on each user’s computer (we’ll get to side-by-side later). Krool produced the first version of the Common Controls Replacement in late 2012. These were the un-compiled versions of source code that you would include in your code. He calls this version the StdEXE which presumably means that the standard versions of these controls get compiled into your EXE file. A bit over 5 years later (January 2017) he started providing the same controls but in the pre-compiled OCX version. So now we programmers have the same controls available in both forms. There is no user guide for how to use each of the controls but since each of the controls is an enhanced replacement for other common controls it can be argued that such handholding is not needed for the largely very veteran VB6 programmers. However, there are several other aspects of these control sets that without some support makes them more difficult to fully use than they have to be. Hopefully this document addresses some of those points. Well after Krool developed his controls package of common controls he decided to add another one that had been left out of his package, a replacement for the MSFlexGrid control. He decided that although there is a lot of commonality with the first package, it is a separate package and use of it with the original package can be done but it can be confusing. When using the StdEXE version of either set of controls, you need a type library, ’OLEGuids and interface definitions’, while you are in the IDE. Also, when using the StdEXE version of the FlexGrid control, another type library is required. OCX versions do not require type libraries because in essence they are included in the OCX file. One of the major advantages of Krool’s controls is that they are designed with the capability of using ’visual styles’ so that your programs don’t look like they came out of Windows 95. However, in order to use these styles you need to now how to turn this feature on and for many of us this is not intuitively obvious. Once it is turned on, though, it is really impressive. If you use the OCX version of the controls you have to distribute the OCX file to your users with your program. Up until when VB6 came out Windows was designed such that these pre-compiled controls, dynamic link libraries, device drivers, etc. would all be registered on each user’s system and only one version (ostensibly the latest one) would be one each user’s system so that once installed and registered, many programs could make use of the same registered code. This was designed to save space on the hard drive, reduce memory usage, etc. but it caused many more problems than it solved. By the time VB6 came out, a new system had been designed and was being implemented to enable programs to use the centrally-registered files or for a program to have its own support files of its own, not copied to the central repository (the Windows System folder) and registered but instead included ’side by side’ with the program. If you use the StdEXE version of the controls you don’t need this (at least for these controls) because all of the code is compiled into yours but if you use the OCX version this side-by-side solution may be desirable because it enables you to distribute programs that don’t need to be installed and that don’t have components that must be installed and registered. If you use the StdEXE version of the controls there are no ’versions’ and when Krool issues an update you just copy the new files over the old ones and keep going. However, the OCX version does have versions (like all pre-compiled code, see the long paragraph above) and it is not a trivial matter to modify each of your programs to use the newer version. My utility takes care of this for you. Since Krool provides both the OCX and the StdEXE versions of the controls, it is possible to improve your programming experience by enabling you to use the OCX version during development (easier to use and much shorter compile time) but then do the final compile with the StdEXE version to get all of the control code included in the program such that there is no OCX file to include with the program and you don’t have to deal with the side-by-side complications. My utility takes care of this for you as well. ## Overview There are two versions of each control set; one is a single file with the extension of OCX that contains the pre-compiled version of the controls. This would need to be registered on your (programmer) computer. It is available [here](https://www.vbforums.com/showthread.php?698563-CommonControls-\(Replacement-of-the-MS-common-controls\)) on VBForums. You reference this in your program and then you have access to all of the controls. This is simple from a programmer’s perspective but when you distribute your finished EXE or DLL file you have to include the OCX file. Further, this file either needs to be part of a ’side-by-side’ solution or it needs to be copied to and registered on the user’s PC. The other approach Krool calls the StdEXE version. In this one has all of the code in a large group of files (162 currently in 38 folders) that are all un-compiled and have to be added as modules to your program. The latest version of this package is available [here](https://www.vbforums.com/showthread.php?698563-CommonControls-\(Replacement-of-the-MS-common-controls\)) on VBForums. Each time you compile your program all of these controls get compiled too. There is a major hassle of even knowing which files to include in your program for which controls, some of the names of subs, functions and variables can conflict with names you use and compiling each time of all of this control code takes a long time. I have a fairly fast PC and just compiling the ComCtlsDemo program Krool provides takes over 25 seconds. I compile a lot in VB6 as I code, partly just to check syntax and logic errors, and a compile time of 25+ seconds is very irritating especially when I know I can get the same code to compile in the OCX version in under 3 seconds. I love the fact that there are no external dependencies in the final executable but I hate the compile time. If only there was a way to use the OCX version with its fast compile times during development but a final compile using the internal controls to eliminate the need to have a separate OCX file to distribute with the program. My utility does that. Also, there are many updates to these controls. The un-compiled files (the StdEXE version) really don’t have version numbers and as long as you copy the latest files over the earlier ones in the same location you won’t have any issues. However, this is not true of the OCX version. I put mine in C:\Windows\SysWOW64 and as long as we have the same version we can just copy the new OCX file over the old one. But there have been new features added over time so we have had versions 1.1, 1.2, 1.3, 1.4, 1.5, 1.6 and now 1.7. If you developed a program using version 1.6 controls you will have a problem using version 1.7 controls because changes have to be made to each project file, each control file in that project that uses Krool’s controls and the manifest if you use one. My utility takes care of that, allowing you to switch from any OCX version to any other OCX version of the CommonControls that are installed on your PC (including the standalone FlexGrid controls). ## Controls Included Below is a list of controls found in Krool’s packages. All are in the Common Controls replacement package except for VBFlexGrid which is in the VBFlexGrid Control package. | | | | | | -------------- | ---------- | ------------- | --------------- | | Animation | FrameW | MCIWnd | SysInfo | | CheckBoxW | HotKey | MonthView | TabStrip | | ComboBoxW | ImageCombo | OptionButtonW | TextBoxW | | CommandButtonW | ImageList | Pager | ToolBar | | CommandLink | IPAddress | ProgressBar | TreeView | | CommonDialog | LabelW | RichTextBox | UpDown | | CoolBar | LinkLabel | Slider | VirtualBoxCombo | | DTPicker | ListBoxW | SpinBox | VListBox | | FontCombo | ListView | StatusBar | VBFlexGrid | If you have any programming experience, you have undoubtedly seen and used many of these controls. Once you get Krool’s system installed, usage is quite easy since the controls behave very similarly to existing controls. We will mainly cover how to get each of the systems installed and set-up to use. ## Terminology Krool’s controls are wonderful but many of the terms used within and around his packages can be very confusing (to me at least). Here are my interpretations of some of the terms. **ActiveX** - Wikipedia [article](https://en.wikipedia.org/wiki/ActiveX). This is a software framework instituted by Microsoft in 1996 using the earlier OLE and COM technologies. For this document we will consider ActiveX as the basis of our controls. **Control** - A component represented by an icon in your Toolbox that can be placed on a form. Most are visible but some, such as a Timer, are not. The simplest ones in VB6 are included in the as-installed VB6 program package. Others, such as Krool’s controls and many others from Microsoft and other vendors, must be added. For amore information on making your own controls please see [this](https://pages.cpsc.ucalgary.ca/~saul/vb_examples/index.html) web page and especially tutorial #10. **OCX** - Often, all of us use controls that are pre-compiled into files having an extension of .OCX (which stands for OLE Control eXtension or just ActiveX controls). These files have to be registered on the developer’s PC and they have to be distributed and registered on each user of the developer’s program(s). One .OCX file can contain multiple controls. The programmer (you) needs to have an OCX installed and registered on his system but the user needs to have the OCX file on his system too, generally registered but sometimes ’side-by-side’ with the compiled program that is being run which uses the OCX control(s). **StdEXE** - Krool uses this term to designate the other method of including ActiveX controls in a program. There are a number of source code files including standard and class modules, property page files etc. that get compiled into an OCX control. Alternatively, all of these can be distributed by the author and put into each of our programs as source code. Normally the authors of a controls package do not want to distribute the source code for their controls for a variety of reasons but Krool has elected to do that with his packages. The advantage of doing this is that your program has all of the control code compiled within it and thus no files need to be distributed or registered for your program to work. Everything is self-contained in your compiled code. A drawback of this from the programmer’s perspective is that all of the controls code gets compiled over and over as you develop your program and compile it over and over. **VBCCRxx** - VBCCR stands for Visual Basic Common Controls Replacement and ’xx’ refers to the OCX version which at present can be 1.1 (xx=11), 1.2, 1.3, 1.4, 1.5 or 1.6 (xx=16). As code that is distributed in compiled form gets modified and expanded over time, the author (Krool) has to issue different versions and each must be on the user’s PC (and the programmer’s PC). For example, suppose you write a program that uses VBCCR16.ocx and you send it to a colleague who has VBCCR13.ocx installed but not VBCCR16.ocx. It won’t run because it is looking fro the other ocx file when it starts up. That’s a disadvantage of OCX files. If you use the StdEXE version, the code is compiled directly into your code and you don’t have to distribute, install or register any external file to use the controls. The main advantages of the OCX version over the StdExE versions are a) compile time for your programs is almost 10x faster because the form code doesn’t need to be re-compiled each time and b) all of the various .BAS, .CTL, .PAG files that make up each control don’t clutter up the programmers list of files to manage. **ComCtlsDemo** - This is a sample program that shows each of Krool’s controls. This file is updated regularly and is always found at the bottom of the first post in [this](http://www.vbforums.com/showthread.php?698563-CommonControls-\(Replacement-of-the-MS-common-controls\)) thread on VBForums. This package uses the StdEXE concept of compiling the code for all of the controls into the executable. This is much more than just a sample file. The source code in this file is all there is for his package and you will use it (or most of it) when you make your own programs that use his controls. It doesn’t have (or need) version numbers like the OCX version since there are no files to register on the developer or user’s PC’s (it is source code that gets embedded ina program each time the program is compiled). I download most every update and to avoid confusion I rename each of the .zip files to a file on my hard drive with the date of the file in the name of the .zip file. Because of VBForum size limitations, he posts the file with a Word extension of .docx but it is really a .zip file so when you download it you do a Save As and then cut the .docx off of the filename. At the time of this writing, the latest one Krool posted is 11 November 2018 (look at the small italics line at the very bottom of the post below the download link) and the file to download is named ComCtlsDemo.zip.docx so when I downloaded that file I renamed it to ComCtlsDemo 2018-11-11.zip on my hard drive. **VBCCR OCX Version** - After about 4? years of having just the StdEXE version, Krool released a pre-compiled version called VBCCRxx.OCX where xx is the version number. The earliest one is version 1.1 so the first file was VBCCR11.ocx. As of this writing, the latest version is 1.6.13 so the file is VBCCR16.ocx. The latest version is always at the bottom of the 1st post in [this](http://www.vbforums.com/showthread.php?841929-VB6-ActiveX-CommonControls-%28Replacement-of-the-MS-common-controls%29\&p=5129155#post5129155) thread on VBForums. The .zip file online contains the .ocx file as well as some resource files (discussed below) related to ’side-by-side’ execution of the programmer’s EXE file and also making your programs themed so that what you display on-screen doesn’t look like it came out of Windows 95. I save the .zip file with it renamed to include the version number. For example, the latest one which is called ’VBCCR16.OCX.rar.docx’ was copied to my hard drive with the name ’VBCCR.OCX v1.6.13.rar’ (see above note for why the file is available with the .docx extension). In addition to containing the .ocx file, the zip file has all of the code in case you wanted to put make your own .ocx file (not recommended) or just to learn from what Krool has done. Copy the .ocx file to you Windows system folder. If you run 32-bit Windows this will typically be C:\Wnidows\System32 but if you run 64-bit Windows then your 32-bit folder for these types of files is C:\Windows\SysWOW64. (In the unlikely event that you put Windows somewhere other then C:\Window then use that path instead). Since you are copying to a system folder you will need elevated permission. It is okay to copy over a previous version if the xx is the same (in my example the xx is 16 so I can copy over the 1.6.12 or 1.6.11 versions) and if the xx is a new one (like for version 1.6.0) then there is no overwrite but you should use regsvr32 to register this control with your system. This .OCX file is loaded into your project using Ctrl-T in the VB6 IDE (or Project|Components) and selecting the appropriate control. For version 1.6 you would select ’VB Common Controls Replacement 1.6 Library’ by clicking the check mark next to it. With the reference to this OCX, all of the controls with show up in your toolbox for use like any other controls you can put on your forms. Because the .OCX version of the controls is pre-compiled, the controls aren’t compiled every time you compile your program like has to happen with the StdEXE version where the controls are embedded into your code. On the other hand, a drawback is that the .OCX file ahs to accompany your EXE or DLL file when you distribute it because it was not compiled into it. **Type Library** - To get Krool’s VBCCR and VBFlexGrid controls in the StdEXE versions (not the OCX versions) to work you need to use a type library he has provided called ’OLEGuids.tlb’ which is in the ’OLDGuids’ folder he distributes with each of the control packages. I copied oleguids.tlb into my system directory and then I can use Project|References to specify it by clicking on the check box next to ’OLE Guid and interface definitions’. The file he is currently distributing has a date stamp of 9 June 2017 so it hasn’t changed in some time. This file is only needed while you are developing your code if you use the StdEXE version. It does not need to be distributed with the final compiled program. (Note-If you use Krool’s controls with VBA you do ***not*** need this file because you have to use the OCX version which already has this type library compiled into it.) **Visual Styles (Themes)** - This started in XP but didn’t really didn’t see much use until Vista and alter. With visual styles you can get more modern-looking forms but since these came into vogue after VB6 came out, there is no simple method of using these in your VB6 programs. Krool’s code is set up to use these visual styles but without a couple of interesting steps you won’t get them. In any event his code provides Unicode and some enhanced features compared to the original controls but to get visual styles you have to specify this in a manifest and then embed the manifest into a resource file referenced by your program. It sounds harder than it is and I will cover how to do that later. 9Note- VBA doesn’t do styles **Side-by-Side Assemblies** - If your program requires a DLL or an OCX file to run, it can use one if it already exists on the user’s system, has been registered and is the right version. Starting around the time when VB6 came out, there was a movement to get away from this system to avoid what many call ’DLL Hell’ (Google that for some fun). To make a long story short, Windows allows programs to run without having to register support files as long as the support files are located along side the EXE or DLL file (or in a sub-folder of it). A lot of corporate users have their PC’s set to not allow any new programs to be installed by blocking registration of thee support files and this is one way around that. In order to specify that the support files are side-by-side you have to specify this in a manifest (see below). It used to be that it was okay to have the manifest in the same folder as the executable file or embed into the file but later versions of Windows strongly prefer the manifest file to be included in a resource file. All of this sound crazy but Krool provides some support for all of the compelxities and my utility (hopefully) takes the pain out of the rest. **Manifest File** - A manifest file is XML-based and can specify many things for Windows to do to control the program. An example is that you can specify in a manifest that the program needs to run with elevated privileges. For our situation, though, the manifest file is of use to use for 2 reasons: 1) we can tell Windows that we want to use version 6.0 f Microsoft’s CommonContrls dll file which is the one that give us the visual styles with Krool’s code and 2) we can tell give it information such that the .OCX file (if you use that instead of the StdEXE one) is side-by-side with the executable you will be making. This by itself is bad enough but Windows now wants this manifest file included in the program’s resource file. **Resource File** - You can put many things into a VB6 resource file (extension .RES) including icons, graphics images, international strings, etc. You can also put a manifest file and you will do exactly that to get the visual styles and/or the side-by-side stuff going. Krool provides two resource files with the OCX version, one for just side-by-side and one for side-by-side plus visual styles. In the StdEXE package there is a resource file in the Resources folder that provides for visual styles (don’t need side-by-side if you don’t use the .OCX version). A user named LaVolpe has a utility on VBForums ([here](http://www.vbforums.com/showthread.php?845909-VB6-Manifest-Creator-II)) that enables you to pull out the manifest information from a resource file, edit it and then put it back in. Hopefully you won’t have to use that utility (I use a part of LaVolpe’s code in my utility as discussed later). The point of defining it here is to ensure that the programmer knows that side-by-side and visual styles need to specify a resource file and that the resource file needs to specify these internally. **Windows System Folder** - The Windows system folder holds many system-related files including DLL’s, type libraries, registered controls etc. For 32-bit VB6 and 32-bit VBA, this folder can be one of two things. If you are using a 32-bit operating system this folder will be ’C:\Windows\System32’. Unfortunately if you are using a 64-bit Windows operating system, all of its 64-bit DLL’s, type libraries and controls go into the system32 folder (?) so Microsoft puts all of the 32-bit files like this into a folder named ’SysWOW64’ (**W**indows 32-bit **O**n **W**indows **64**-bit). All of the 32-bit files go into ’C:\Windows\SysWOW64’. If you are using all of this in 64-bit VBA you will only deal with the 64-bit Windows folder which is always ’C:\Windows\System32’. **VBFlexGrid** - Krool’s original controls include 35 controls but not a replacement for the MSFlexGrid control (Microsoft provides a file MSFLXGRD.OCX which Krool’s package upgrades and replaces). The approach he has taken is very similar to what he has done with the other controls. There are separate versions that are standalone like the VBCCR ComCtlsDemo package, this one called VBFlexGridDemo found [here](http://www.vbforums.com/showthread.php?848839-VBFlexGrid-Control-\(Replacement-of-the-MSFlexGrid-control\)), and the corresponding OCX version of it, VBFLXGRD12.OCX, found [here](http://www.vbforums.com/showthread.php?855931-VB6-ActiveX-VBFlexGrid-%28Replacement-of-the-MSFlexGrid-control%29\&p=5236525#post5236525). Both of these versions are independent of the VBCCRxx controls. My utility deals with these and the VBCCR controls as if they are all part of the same package. ## User Guide for the Programmer Below is a discussion of usage for each version. After that is a discussion of my recommended use which is a simple hybrid of each option that (hopefully) takes advantage of the best features of each option and then some. VBCCR - Two versions exist for this set of 33 controls (all of the ones in the previous table except the last one). Until now, programmers have had to decide whether to use either the StdEXE or OCX versions; there has been no way to use both of them. After the user guides for the two versions I will show you another, hopefully better, way of using these controls so you can take advantage of the easier and faster OCX version for development yet produce a final executable with the code for the controls in your control with the StdEXE version. ### VBCCR - StdEXE Version This is the version in which all of the control code is compiled into your program. You will include the appropriate source code in your program and when you compile the controls become part of your program. Getting the latest version - You might be tempted to think that there is a download available that has all of the controls, a user guide, etc. but that’s not the case. Krool has a demonstration project on the VBForums web site and from that you get access to all of his controls (interesting approach but it works’). Krools’ demo project with all of the controls has been [here](http://www.vbforums.com/showthread.php?698563-CommonControls-\(Replacement-of-the-MS-common-controls\)) since 10 Nov 2012. There are over 78 pages of comments and discussion in the thread. Most deal with various bugs and user questions and feature addition requests as Krool has worked the package for the past 9 years. The important thing is that at the bottom of the first post is a downloadable file named ’**ComCtlsDemo.zip.docx**’ which is always the latest version to download. It has the .DOCX extension because VBForums has a lower size limit on .ZIP files than .DOCX files and this file exceeds the file size limit for .ZIP files. It really is a .ZIP file so as you download it (or after) rename it by knocking off the .DOCX part of the name, leaving the file ComCtlsDemo.zip. The name of this file on the web site is always the same. I recommend that you look at the last line in this first post and note the date and then put the date in the filename. For example, I am looking at the first post and at the bottom it says that it was last edited by Krool on November 11, 2018 so when I right-click on the link I tell it to save it into a set of folders where I keep all of my downloaded archive files and I save it with the name ’**ComCtlsDemo 2018-11-11.zip**’ so I can differentiate it from prior copies I have downloaded. Now here is an important observation. ComCtlsDemo contain all of the files for the controls and these files are not supposed to be altered so you can put these files into a central location that all of your programs will access (a library). This location doesn’t need to change and you can always delete the existing files and put the newest version’s files in the same folders. Also, all of your programs access all of these files where they are so you don’t need to copy all of these files into your individual project folders. That greatly simplifies usage and updating for newer versions. Where to put the downloaded files when unzipping - I have a library folder into which I put all sorts of files for use in my programs. I do not put files into here that will change. This contains files I can use in all or my programs without modifications. In my Library folder I have a sub-folder for Controls & Forms. Within that I have a folder for Krool’s controls named VBCCR and in that I have made a sub-folder called ’Current’. Whenever I download the latest update from Krool, I first delete all the files and folders in Current and then I unzip the new files into Current. This is important because programs I am working on that already that use these controls will continue to find these controls in the same places and won’t even know they are the new versions. Fortunately Krool keeps the names of his files and folders the same as he debugs and adds features to the controls. So now that we have the files on our PC in a location where we can use them for all of our programs, we can just start using them. Right? Well, sort of. There are some additional steps to take in order to use his controls. Follow the steps below for any new or modified program you create. Type library - You need to be able to access a type library named ’OLEGuids.tlb’ that is included with Krool’s sample program. This file is in a sub-folder of Current named ’OLEGuids’. You will need this file during your editing and compiling but your compiled program doesn’t need it and you don’t distribute it with your executable. I put mine into my Windows System folder so I always know where it is and I register it in Windows 10 with regsvr32. Fortunately this type library file doesn’t change very often so you don’t have to do this step often. OLEGuids.tlb is dated 9 June 2017 so it hasn’t changed in 18 months. In VB6 you will use the commands Project | References to select this type library. If you have registered this file using regsvr32 then you can find it in the list of Available References with the name ’OLE Guid and interface definitions’ but if you haven’t registered it yet you can click on ’Browse’’ and go find it. Visual Styles - In order to use visual styles (themes) in your programs so they don’t look like old Windows programs you have to specify the use of Windows’ Common Controls library version 6.0 because it has support for visual styles. The way to do that is to include the specification for this in a manifest file. It used to be that you made a file including the name of your executable that had a ’.Manifest’ extension and when you distributed your program you included this file in the same folder as your executable file. Later versions of Windows discourage this but recommend that you include the manifest in the EXE file as part of an embedded resource file. VB6 can use resource files to hold a number of different things such as internationalization strings, icons, etc. in addition to manifests. So we have to get the visual style specification into a manifest and then get the manifest file inside of a VB6 resource file. In Krool’s package look in Current\Resources to find a file named ’Resources.res’ which is a resource file Krool made that contains the directions to enable visual styles (or theming). If you are not using a resource file for anything else you can simply copy this Resources.res file to wherever you project file (.VBP) resides. I will show you in a minute how to embed that in your project. But for now let’s consider what to do if you already have a resource file and we want to add our manifest information to that resource file (whether it already has manifest information in it or not). Please note that the VB6 IDE was not designed to use visual styles. [Here](http://www.vbforums.com/showthread.php?693111-VB6-IDE-solving-UAC-and-Visual-Style-issues\&highlight=) is a VBForums post by Krool that shows how to get a resource file with embedded manifest that will run VB6 with elevated UAC as well as incorporating visual styles. You don’t need this to use Krool’s controls but if you want to see the ’prettier’ forms then this may be worth it to you. Note that it involves using another utility called ResourceHacker to get the resource file into the VB6.EXE file. An easier approach is to get the file vb6.exe.manifest from [here](http://www.vbaccelerator.com/home/VB/Code/Libraries/XP_Visual_Styles/Using_XP_Visual_Styles_in_VB/article.asp) and put it into the same folder where you have vb6 (typically C:\Program Files (x86)\Microsoft Visual Studio\VB98). As far as using visual styles in your programs, I find it strange that the instructions to use visual styles are part of a manifest file which we have to embed into a resource file which is then embedded within our executable files. Krool supplies a resource file with visual styles in the Resources folder under Current that you can copy to your project and embed. Advanced resource/manifest/visual styles note - You may want other things in your resource file in addition to the visual styles setting. It is not a trivial thing to work with these files. The manifest part is XML and it is contained in a non-XML resource file. I have found another utility on VBForums by a user named LaVolpe ([here](http://www.vbforums.com/showthread.php?845909-VB6-Manifest-Creator-II)) that lets us make or edit a manifest from scratch or from a manifest file or extracted from a resource file so that we can edit it and then we can specify that it is put into a resource file. Below is a screenshot of LaVolpe’s utility running with Resources.res loaded. I highlighted the section that specifies Windows Common Controls version 6.0.0.0 to be used. This is what specifies visual styles. In general for a new program you should be able to just copy the Resources.res to your project folder and use it without having to edit it. BTW, you don’t *need* this file but you won’t get any of the modern looking controls in your program without it. So now you have a resource file that specifies using visual styles. How do we get it into our project? In VB6, go to AddIns | AddIn Manager’ and you will see something like the following. Select ’VB6 Resource Editor’ and ensure that ’Loaded/Unloaded’ and ’Load On Startup’ are both checked. Then, back in your main project go to Project | Add New Resource File’ and then select your .res file from the dialog box that pops up. Now your resource file should show up in the navigator pane under Related Documents. Side-by-Side - One reason for using the StdEXE version is that unless you use some other specialized controls or other files, your executable has no dependencies so there is no reason to be concerned about side-by-side. I will discuss it more in the user guide for the OCX version of Krool’s controls. Files to Include in Your Project - Each of the controls has a number of files specific to the control which need to be inserted into your project as shown below. | **Control** | **Files in Current Folder** | | -------------------------------------- | --------------------------------------------------------------------------- | | Animation | Builds\Animation\Animation.ctl | | | Builds\Animation\PPAnimationGeneral.pag | | CheckBoxW | Builds\CheckBoxW\CheckBoxW.ctl | | ComboBoxW | Builds\ComboBoxW\ComboBoxW.ctl | | CommandButtonW | Builds\CommandButtonW\CommandButtonW.ctl | | CommandLink | Builds\CommandLink\CommandLink.ctl | | | Builds\CommandLink\PPCommandLinkGeneral.pag | | CoolBar | Builds\CoolBar\CbrBand.cls | | | Builds\CoolBar\CbrBandProperties.cls | | | Builds\CoolBar\CbrBands.cls | | | Builds\CoolBar\CoolBar.ctl | | | Builds\CoolBar\PPCoolBarBands.pag | | | Builds\CoolBar\PPCoolBarGeneral.pag | | DTPicker | Builds\DTPicker\DTPicker.ctl | | | Builds\DTPicker\PPDTPickerGeneral.pag | | FontCombo | Builds\FontCombo\FontCombo.ctl | | FrameW | Builds\FrameW\FrameW.ctl | | HotKey | Builds\HotKey\HotKey.ctl | | ImageCombo | Builds\ImageCombo\ImageCombo.ctl | | | Builds\ImageCombo\ImcComboItem.cls | | | Builds\ImageCombo\ImcComboItems.cls | | | Builds\ImageCombo\PPImageComboGeneral.pag | | ImageList | Builds\ImageList\ImageList.ctl | | | Builds\ImageList\ImlListImage.cls | | | Builds\ImageList\ImlListImages.cls | | | Builds\ImageList\PPImageListGeneral.pag | | | Builds\ImageList\PPImageListImages.pag | | IPAddress | Builds\IPAddress\IPAddress.ctl | | LabelW | Builds\LabelW\LabelW.ctl | | LinkLabel | Builds\LinkLabel\LinkLabel.ctl | | | Builds\LinkLabel\LlbLink.cls | | | Builds\LinkLabel\LlbLinks.cls | | | Builds\LinkLabel\PPLinkLabelGeneral.pag | | ListBoxW | Builds\ListBoxW\ListBoxW.ctl | | ListView | Builds\ListView\ListView.ctl | | | Builds\ListView\LvwColumnHeader.cls | | | Builds\ListView\LvwColumnHeaders.cls | | | Builds\ListView\LvwGroup.cls | | | Builds\ListView\LvwGroups.cls | | | Builds\ListView\LvwListItem.cls | | | Builds\ListView\LvwListItems.cls | | | Builds\ListView\LvwListSubItem.cls | | | Builds\ListView\LvwListSubItems.cls | | | Builds\ListView\LvwVirtualListItem.cls | | | Builds\ListView\LvwVirtualListItems.cls | | | Builds\ListView\PPListViewGeneral.pag | | | Builds\ListView\PPListViewImageLists.pag | | | Builds\ListView\PPListViewSorting.pag | | MCIWnd | Builds\MCIWnd\MCIWnd.ctl | | MonthView | Builds\MonthView\MonthView.ctl | | | Builds\MonthView\PPMonthViewGeneral.pag | | OptionButtonW | Builds\OptionButtonW\OptionButtonW.ctl | | Pager | Builds\Pager\Pager.ctl | | | Builds\Pager\PPPagerGeneral.pag | | ProgressBar | Builds\ProgressBar\PPProgressBarGeneral.pag | | | Builds\ProgressBar\ProgressBar.ctl | | RichTextBox | Builds\RichTextBox\PPRichTextBoxGeneral.pag | | | Builds\RichTextBox\RichTextBox.ctl | | | Builds\RichTextBox\RichTextBoxBase.bas | | Slider | Builds\Slider\PPSliderAppearance.pag | | | Builds\Slider\PPSliderGeneral.pag | | | Builds\Slider\Slider.ctl | | SpinBox | Builds\SpinBox\PPSpinBoxGeneral.pag | | | Builds\SpinBox\SpinBox.ctl | | StatusBar | Builds\StatusBar\PPStatusBarGeneral.pag | | | Builds\StatusBar\PPStatusBarPanels.pag | | | Builds\StatusBar\SbrPanel.cls | | | Builds\StatusBar\SbrPanelProperties.cls | | | Builds\StatusBar\SbrPanels.cls | | | Builds\StatusBar\StatusBar.ctl | | SysInfo | Builds\SysInfo\SysInfo.ctl | | TabStrip | Builds\TabStrip\PPTabStripGeneral.pag | | | Builds\TabStrip\PPTabStripTabs.pag | | | Builds\TabStrip\TabStrip.ctl | | | Builds\TabStrip\TbsTab.cls | | | Builds\TabStrip\TbsTabs.cls | | TextBoxW | Builds\TextBoxW\PPTextBoxWText.pag | | | Builds\TextBoxW\TextBoxW.ctl | | ToolBar | Builds\ToolBar\PPToolBarButtons.pag | | | Builds\ToolBar\PPToolBarGeneral.pag | | | Builds\ToolBar\TbrButton.cls | | | Builds\ToolBar\TbrButtonMenu.cls | | | Builds\ToolBar\TbrButtonMenus.cls | | | Builds\ToolBar\TbrButtonProperties.cls | | | Builds\ToolBar\TbrButtons.cls | | | Builds\ToolBar\ToolBar.ctl | | TreeView | Builds\TreeView\PPTreeViewGeneral.pag | | | Builds\TreeView\TreeView.ctl | | | Builds\TreeView\TvwNode.cls | | | Builds\TreeView\TvwNodes.cls | | UpDown | Builds\UpDown\PPUpDownGeneral.pag | | | Builds\UpDown\UpDown.ctl | | VirtualCombo (on or after 15 Aug 2020) | Builds\VirtualCombo.ctl Builds\VirtualCombo.ctx Builds\VirtualComboBase.bas | | VListBox (on or after 15 Aug 2020) | Builds\VListBox\VListBox.ctl Buids\VListBox\VListBox.ctx | If you want any individual control to be available in your project, from within the IDE, press Ctrl-D and then navigate to the appropriate folder and highlight all of the files in the folder to import and press Enter. A challenge is that Krool’s package includes all of the controls and it is unlikely you will need all of them. The demo program utilizes all of them and the EXE file resulting from this is 4.2 MB so if you include all of the controls in your program you will add about 4 MB to the file size. In these days of multi-gigabyte RAM and hard drives this may not be the consideration that it once was. There are also some files that have to be present whether you use one control or all of them. These are: | | | ------------------------------------------------- | | Builds\ComCtlsBase.bas | | Builds\VTableHandle.bas | | Builds\VTableSubclass.cls (only until 5 Jan 2020) | | Builds\ISubclass.cls | | Common\Common.bas | | Common\VisualStyles.bas | Finally, if you use the control MCIWnd.ctl or property pages for CoolBar, Imagelist, RichTextBox or StatusBar you must also include the file ’Builds\CommonDialog.cls’ in your project. You may be tempted to not include code for controls you are not using. You do save some size in your final executable file but just know that the control(s) left out do not appear in your toolbox for even possible use without including the above code for the individual controls. If you are sure you won’t use a given control it is okay to leave it out. Each of the controls is independent of the others. There is one more file in Krool’s ComCtlsDemo package, Common\Startup.bas, which is really for the demo program. You don’t need this file but there are some concepts in that file that need to be part of your program. Sub Main - Krool’s controls rely on some Microsoft code that needs to run before any forms are loaded or shown. To use the new controls you must specify the Startup Object as Sub Main instead of any Form and you must have the correct start-up code in Sub main before you reference any control. This is set in Project | Properties on the General tab. If you don’t have a start-up routine in a Sub named Main you need to put one in your program. You need to have a call to one of Krool’s routines to provide protection for callbacks etc. built into his programs so that you don’t crash in the IDE. Also, there is some start-up code required for your program to use the visual styles enabled by using Microsoft’s Common Controls 6.0. Thus, the first two lines in your Sub Main should be: ```vb Call ComCtlsInitIDEStopProtection ' in Builds\ComCtlsBase.bas ' above is only needed if you are using Krool’s package before 13 Aug 2020) Call InitVisualStyles ' in Common\VisualStyles.bas ``` Now you can put the rest of your code to show Forms, do calculations etc. Unless you use other .OCX control files, your final executable will contain all of the code including the controls so the executable is standalone and does not need anything other than the standard VB6 support files included with Windows by Microsoft. You may have some issues with names of subroutines and variables being the same as ones that you use. If you use the .OCX version of the controls, most of that is hidden and is not a concern. However, when you include all of the various files for the controls to be compiled within your program, you now have 153 new files and you may have some naming conflicts. If you decide to keep your names and change Krool’s, just know that every time you download and use and update your will have to edit his files to rename these (not just the name of the subroutine but every other routine that calls it). I reluctantly decided to change some conflicting names in my code so I wouldn’t have to keep updating his files with new downloads. I don’t like this but it is a small price to pay for these controls. Note - I don’t use the above approach because I don’t like the long compile times although I do like a fully self-contained executable. That’s part of the reason I wrote the utility I will discuss later. It allows you to develop using the .OCX version (compiles so much faster) and then do the final compile through my utility with the StdEXE version so you have the self-contained executable. ### VBCCR OCX Version Guide Krool has the equivalent of the StdEXE package for VBCCR in a pre-compiled form as a more typical single controls file with an OCX extension found [here](http://www.vbforums.com/showthread.php?841929-VB6-ActiveX-CommonControls-%28Replacement-of-the-MS-common-controls%29\&p=5129155#post5129155). Advantages versus the StdEXE-based controls are: 1) simpler to use as it needs one .OCX file instead of 153 individual files to include in each of your programs, 2) compile times for your program are faster since the OCX file is already compiled and 3) programmers are used to OCX systems available from Microsoft and other vendors. Disadvantages are: 1) the OCX file has to accompany the executable to the users, 2) the OCX file must either be registered on the user’s PC or employ a more-complicated side-by-side solution. Getting the latest version - From [this site](http://www.vbforums.com/showthread.php?841929-VB6-ActiveX-CommonControls-%28Replacement-of-the-MS-common-controls%29\&p=5129155#post5129155) download the file at the bottom of the first post. We are now in version 1.6 of the OCX version of the controls so the file is listed for download as ’VBCCR16.OCX.rar.docx’. It has the .docx extension due to size limitations of other types of files on VBForums. It is really a RAR file. I include the current version in the filename when I download the file so I can keep track of the various downloads. The first post says the current version if 1.6.13 so when I downloaded this file is used SaveAs and I named it ’VBCCR16.OCX v1.6.13.rar’ (I drop the .docx extension and add the new version number). Inside this file is the .OCX file and a zip file containing the source code if you wanted to generate your own version of the .OCX (I don’t recommend this because it will now be a separate package from Krool’s; it basically has the same files that the StdEXE version has). Use of the files in your program - Now in your new program you will use all of these files. Press Ctrl-T or do Project|Compenents and select ’VB Common Controls Replacement 1.6 Library’ (that’s file vbccr16.ocx). To get these into a VBA project do Tools | Additional Controls’ in the VBA IDE. Finally, you need to set the resource file that contains the manifest to enable visual styles and optionally side-by-side (VB6 only; not applicable for VBA). There are also 2 VB6 resource files in the first post on VBForums: ’VBCCR16SideBySide.res’ and ’VBCCR16SideBySideAndVisualStyles.res’ which are for exactly what they say in the title. These are not zipped but instead are the actual resource files so you should just save the links as files and use them. I will cover how to use one of these in just a bit. Setting up your project - Just like with the StdEXE version you cannot start your program with a Form; you must have a Sub Main and start it first so you can run some code that is required to be run before your first form is called or referenced. The easiest thing to do is to include the standard module VisualStyles.bas from the StdEXE version and then in your program, make sure in the General tab of Project | Properties is set to use Sub Main and in your Sub Main you should have the following line of code before loading, referencing or showing any forms: InitVisualStyles Now you are ready to go. All of the controls will show up in your Toolbox for use in your forms. Note - In the StdEXE version there is some code Krool has included to provide crash protection when you use the controls in the IDE. You need the same protections with the OCX version but thy have been compiled into the OCX so you don’t need to call the IDE protection code. Compiling your code - Nothing special here other than using that procedure discussed above in Sub Main. Krool says his code is IDE-safe and that has been my experience as well. You have an option of using a manifest file to specify two things that may be of interest to you. First, I think you will want to take advantage of themes/visual styles since this capability is built into Krool’s code and is relatively easily accessed. Also, the manifest can specify that you want a ’side-by-side’ assembly. Normally you have to include separate controls and ActiveX DLL’s with your program and they must be registered on the user’s system in the Windows System folder. Some organizations don’t allow this so they can’t even use a program with external dependencies such as the VBCCRxx.OCX controls file discussed here. Around the time VB6 came out there was a move to get away from this and to allow something else. In theory, having the latest version of controls (.OCX’s) and DLL’s in your system folder is efficient because many programs can access that one file instead of each program having its own OCX’s or DLL’s. In practice this caused a lot of problems (for fun, Google ’DLL Hell’ sometime). So with the right manifest you can specify that the OCX and/or DLL files your program uses can be with your programs and they don’t have to be registered with the user’s system. It is not quite as slick as including the code inside the program (like with the StdEXE version of Krool’s code) but it is the next best thing. Manifests can include other things but for purposes of this user guide we will focus only on the two that can affect Krool’s package. ’Back in the day’ you used to be able to put the manifest file next to the EXE when you distributed your package to your users but recent versions of Windows really want you to include the manifest in the program. There really isn’t a way to do that so the manifest gets included inside a resource file which can be and is used by many programming languages including VB6. Manifests are in XML and are strange because the file size must be exactly a multiple of 4 bytes. Fortunately Krool has provided two resource files that I discussed 2 pages back that can just be included into your program. One is for side-by-side and the other is for enabling visual styles plus side-by-side. Suppose you have downloaded from Krool’s web site the file ’VBCCR16SideBySideAndVisualStyles.res’ and want to use it. Obviously this is the one that provides both visual styles and side-by-side. You do not need to edit this file but you do need to reference it. Note - The resource file can be left in a common location as a library file used by multiple of your programs. Note though if you add to it or modify the file as you centrally use it, these changes will show up in all programs using that resource file. If you are concerned about this, simply copy the resource file to your project folder (same on that holds your .vbp file) and reference it separately for your project. So how do you get this resource file into your project? In VB6, go to AddIns | AddIn Manager’ and you will see something like the following: Select ’VB6 Resource Editor’ and ensure that ’Loaded/Unloaded’ and ’Load On Startup’ are both checked. Then, back in your main project go to Project | Add New Resource File’ and then select your .res file from the dialog box that pops up. Now your resource file should show up in the navigator pane under Related Documents which is listed below all of the forms, standard and class modules. Now you are ready to go and to use your compiled program. Using the EXE or DLL - You do not need a manifest to be included with the files you distribute since by including it in the resource file it is now part of your executable. You do need to include VBCCRxx.OCX with your program. If you use the side-by-side approach you can include it in the same folder or a sub-folder of the folder you put the executable file in. Please note that if you do use side-by-side, Windows looks for this OCX file in the executable’s folder even on your PC or anyone else’s even though you may have copied it to the System folder and registered it (at least that’s my experience). So I recommend that you do not move the OCX file out of the system folder but rather make a copy of it in the same folder where you have your EXE file on your PC. Please check my utility before you decide to do side-by-side. I have a solution whereby you use the OCX version of the controls during development then use the utility to do a commandline compile with the StdEXE version of the controls so you don’t need any side-by-side solutions since the code is all embedded in the executable (at least for Krool’s controls; if you use someone else’s OCX files you may still want to do side-by-side for their controls). If you don’t specify side-by-side you won’t need to do anything on your PC since you already have it registered but you need to have your installation program install it to the user’s system directory and register it. ### VBFlexGrid User Guide The MSFlexgrid replacement package from Krool is almost identical to what we have discussed above for the other 33 Common Control replacements Krool has done. This one came much later than the others so Krool decided to keep it separate. Perhaps at some point these two packages get merged but for now just think of VBFLXGRD as just like VBCCR except it has one control instead of 33. You can download the StdEXE version from VBForums [here](http://www.vbforums.com/showthread.php?848839-VBFlexGrid-Control-\(Replacement-of-the-MSFlexGrid-control\)) and the OCX version [here](http://www.vbforums.com/showthread.php?855931-VB6-ActiveX-VBFlexGrid-%28Replacement-of-the-MSFlexGrid-control%29\&p=5236525#post5236525). All of the issues relating to the VBCCR counterpart are the same with the FlexGrid control. My utility will help you manage both of these seamlessly. ### VBA Usage The StdEXE version of the VBCCR and VBFLXGRD controls will not work in VBA because VBA does not allow you to have controls embedded into the code. Any controls in addition to the ones built-in to VBA must be ActiveX controls (i.e., the OCX version). The OCX versions do work in VBA. The type library is not required since it is effectively compiled into the OCX file. Each user have the OCX file registered and referenced in his VBA project on whatever PC’s are running the code. Also, there are no styles in VBA so this feature is not available. If your VBA forms are ugly this code won’t help that. These controls do give the VBA user access to Unicode versions of the controls although many VBA controls in recent years display Unicode characters anyway (don’t allow Unicode text in properties at design-time though). It does not enable Unicode in the IDE code editor; the editor remains ANSI with or without these controls. Finally, many of Krool’s controls are enhanced versus what Microsoft provides so this could be an advantage. ## OCX2StdExe Utility I have used these for a while and have thought about how to manage these to not drive myself crazy and to get an efficient coding environment. Things I don’t like are: * The StdEXE versions enable a standalone executable file with no dependencies which is great but the compile times are a killer. * The OCX versions compile much more quickly but now you have an OCX to distribute and possibly register for each executable you make. * Updates to the OCX packages are great because they have a lot of bug fixes and feature additions but it is a real pain when a new version comes out. For each of your programs you have to find which forms use the controls from the text in the project file, manually change the references to the new name of VBCCRxx.OCX and/or VBFLXGRDxx.OCX in each form manually with a text editor, if you use a manifold with side-by-side you have to replace all of the names and GUID strings in the manifest part of the resource file and lastly you have to manually edit the project file (.vbp) to reference the new ocx file(s). Once is an experience and many times is nuts. * Since Krool’s OCX version doesn’t come with a sample file it is not entirely straightforward how to get the OCX version to use visual styles even though it might be referenced in the manifest/resource file. There is some initialization code that is required that is not included in the OCX package. You can make one from the StdEXE version but it takes parts of several standard modules. * I have a lot of other initialization code and I don’t want my code to get mixed up with Krool’s code. So I wrote a VB6 utility that manages these issues and more: * You set up your development program to use the OCX version(s) because it is simpler (1 file instead of 153) and your project compiles much faster than the StdEXE version during development. * You can use VBCCRxx.OCX or VBFLXGRDxx.OCX or both. I am trying to treat these two control packages as if they are one and the same (I have no inside knowledge but my expectation is that Krool will combine these in the not-too-distant future anyway). * Whenever a new version of VBCCRxx.OCX or VBFLxGRDxx.OCX comes out, you download it and copy it to your system folder and register it. If you have1.7.13 which is in VBCCR17.OCX and your overwrite the version 1.7.12 copy that was already registered and in the system folder you don’t have to do anything extra but it you have a program that is using version 1.6 and you now download version 1.7.xx you can use my utility to specify that your existing program that had been using VBCCR16.OCX should be upgraded to VBCCR17.OCX. the utility takes care of making the appropriate changes to your project file (.vbp), all form files (.frm and .frx) and even to the data in the resource file (.res) that references the old file for visual styles and/or side-by-side. All of your existing files are saved so you can easily restore them if for some reason you wanted to regress to an earlier version (not recommended). In fact, the utility can take projects using any version and switch to an earlier version. So you could go from version 1.7 down to 1.1 (why you would want to do this I don’t know but you could). * You can develop and maintain your project as you normally do with other projects when you use OCX controls. At some point, though, you likely will want to switch the compile to use the StdEXE version so you can get the single file, no dependency program and you don’t mind the compile time just this once. You can easily do this and not change any of your existing files. You just get a new self-contained executable file. * Your compiled code is smaller with the StdEXE commandline compilation because it includes only those controls that are actually used in the project. Your original files are not modified. I make temporary files that contain references to the StdEXE controls (the 153 files) instead of the one OCX. You have the option of retaining the temporary files (have different names than the files for the OCX version) so you can recompile the new StdEXE version again if you need or want to. Also, the property pages are optionally not included in the StdExE version reducing the executable file size because the commandline compile does not make use of property pages anyway (IDE does). * An option which has been added is to have the utility make a folder beneath your project folder called StdExe. The utility is (hopefully) easy to use. This document covers the version of the utility written for VB6; there is an almost identical version written for Excel if you prefer to do that. The Excel version is included in the package along with the VB6 version. Below is a screen shot of the VB6 version. At the top of the form is the VB6 project file to be updated or compiled. You can enter the path in the text box or click on the button to the left to search for it. The project file needs to be a project that uses the OCX versions of Krool’s controls (either or both). The OCX versions have versions and it is not trivial to change from one of the versions to a newer one because references to the OCX file to be used is embedded in code for the forms that use the controls, the resource file if it has an embedded manifest and the project file itself. If you specify a project file for a project that either doesn’t use Krool’s controls or uses the StdEXE version then you won’t be able to do either the OCX upgrade or the commandline compile. **Update OCX References** Our form advises you what current version of either VBCCRxx.OCX and/or VBFLXGRD.OCX you are using in the project. The sample above shows that the specified project is using VBCCR15.OCX and VBFLXGRD12.OCX. It also shows the versions of each that you have installed on the PC running this utility, defaulting to the most recent. In the sample above, it is showing VBCCR17.OCX and VBFLXGRD14.OCX which are the latest available at the time of this document. Although you can’t see it from the picture, the drop-downs include some earlier versions as well. You have an option to keep or delete the old version files after the upgrade. In general you won’t need to keep the old files but if you choose to keep them, you can find them in the same folder(s) as the new ones but with the extensions added not the names of the old OCX version numbers. For example, if you used Krool’s controls on ’myForm.frm’ when it is converted to version 16 from 15, the old file can be retained and if it is it would be named ’myForm.frm.ocxCCR15ocxFlex12’ so you can clearly identify it as the old file left behind after an upgrade. I recommend that once you develop trust in this utility that it won’t delete files it shouldn’t, there really is no reason to save the old versions so you can click on the choice to delete the old files. You can actually go to earlier versions of the controls that the current one if the older OCX file(s) is registered on your PC. In general, newer versions have more features but more importantly they also have bug fixes so I discourage going back to an earlier version. Another item to consider is that VBCCR16 added a new control (ComboFont) and VBCCR17 added VirtualCombo and VListBox that don’t exist in earlier versions so if you specify going from version 1.6 or later to version 1.5 or earlier, references to these controls have to be cut out which is likely not what you want (assuming you have used it). Once you have chosen the version(s) to go to and whether or not to save the old files, you just click on ’Update .OCX References’ to get your project changed. All of the controls will have the same settings as before you upgraded to the new version. **Note** - This utility does not use any of Krool’s controls so a) it is only ANSI and b) it doesn’t matter which versions of the OCX you have installed on your PC. **Compile Without the OCX Files** This choice from the main menu allows you to compile your program with the StdEXE files embedded into your program such that after the compilation you will not need the OCX file any more. It does not change any of your files that you have been using for development using the OCX versions of the controls. This option should be used *after* you get your program to compile and run with the OCX version. It is much easier and more productive to develop the program using the OCX version and then use the StdEXE version to make an executable file that can be distributed. Note that all of this presumes that you have downloaded and registered the OCX version(s) of VBCCR and VBFlexGrid and also have downloaded and unzipped the equivalent versions of the StdEXE version(s) as well. If you click on the Options button on the Main form, you will see the following: At the top of the form are options for which of Krool’s support files that are not part of each of the controls you wish to include. Some of these are general files used by many of the individual controls and some are just general support files. For example, the Common.bas is a general purpose module whose routines are used by many of the controls. I always leave this one checked because it is so core to all of the functions. On the other hand, VisualStyles.bas contains code that I have already incorporated into my core module so I don’t use it in the options above. The class module CommonDialog.cls is interesting. Only one control uses it (MCIWnd.ctl) and 4 of the .pag files that are used in the IDE use it (CoolBar, ImageList, RichTextBox and StatusBar). I have code that looks to see if any of these are used and if not it is automatically excluded so my suggestion is that unless you specifically have included CommonDialog.cls in your code for other uses, just leave it checked above. Note that there is an option for a module named VTableSubClass.bas but if you use a version of ComCtrlsDemo on or after 5 Jan 2020 this option is not needed and is not shown. In the middle of the form are choices for file locations for the compile. The utility will not affect your existing project files but it does need to modify them to change the references from the .OCX controls to the StdEXE controls. You have two choices of doing this: 1) make copies of all of the affected files and put an XXX in front of the name of the newly copied file or 2) copy all of the project files to a separate folder where you can make the appropriate changes for the compile. I recommend the option of copying to a separate folder because you dn’t leave XXX files scattered all over your programming system. **Copy all files into a StdEXE sub-folder and then compile that** - If you choose this option, all of the files associated with your project are copied into a sub-folder named StdEXE of the folder where the project file is located. A copy of the project file is put into this sub-folder and all of the references are adjusted to the files now in this sub-folder. After the compile, the EXE file will be located in this folder. This project will differ from the parent project in that the OCX references are gone, replaced by references to the StdEXE control files. However, in addition to the project being fed to the commandline VB6 compiler, it can also be opened like a normal project in the VB6 IDE. If/when you ever want to get rid of this project just delete the contents of the sub-folder. Note- Krool’s control files are treated as a library and so are not changed in any way for a compile so they are not copied into the StdEXE folder. They are referenced rom wherever you have put them on. **Rename all support files with XXX prefix before compile and then’** - When you select this option, you get 3 sub-options below it. To protect the original project, we make copies of all of the changed files by putting ’XXX\_’ in front of the name, including the EXE generated from the commandline compiler. You can tell the program to delete these support files after the compile; you can save these XXX\_ files so that later you can re-compile the new project file (which also has XXX\_ prepr=ended to its name); or you can choose to keep all of the support files for all of Krool’s controls, even those that are not used in your project. (Note - If you use the Excel version of this utility the prefix is YYY\_ instead of XXX\_.) Note - If you elect to save the support files so you can open the StdEXE version in the VB6 IDE, there are some modifications I have to make that are transparent to you but are important to note so you aren’t surprised. For example, I do not include any control property page files (.pag extension) since these are only used within the IDE and we skip the IDE with the commandline compile. However, if you want to save the support files so you can later open this in the IDE then we need to make sure that we adjust your project file to reference the appropriate .PAG files so you can open it in the IDE. So after the commandline compile, references to the .PAG files are placed into the .VBP project file. Until early August 2020, Krool had a mechanism built in to the StdEXE set of files that tried to ensure safety of using these controls in the IDE. After 13 Aug 2020 he removed these safeguards. If you are still using a StdEXE version before then (highly not recommended) then we have some code in place that will help you put this attempted safeguard into you code post-compile it isn’t needed in the.OCX version but is in the earlier StdEXE versions. **Which controls are included** When you do a commandline compile, only the controls you actually used are included in the compiled code. This makes the resulting .EXE file be the smallest possible because you do not include references to unused controls. However, if you want to later edit this StdEXE version it could be that you want the option of adding more or all of the controls you aren’t using now into the project. There is a choice on the Options form to specify inclusion of all of the controls into the new project or you can click on ’Special’ and include specific ones. In general I recommend against this because it is easier to just keep using the original project that refrences the .OCX file where you have all of the controls available and then just re-run this utility when you want to generate the .EXE file with the controls included in the .EXE. There is a special case where you have to use the ’Special’ button. If you define a control at run-time and the name of the control is in a variable, my utility cannot see that and it would get extremely complicated to track down all possible assignments to the string. Since you write the programming code you should know which controls you are adding at run-time so you wan specify which additional controls to include, if any. If you already use a specific control in your program you don’t even need this since that use already makes that control be included in the compile. **Base File Locations** At the bottom of the Compile Options form is a section for ’Base File Locations’. In order to do a commandline compile we need to know where VB6 is located and also where Krool’s control files are located. If you are going to compile the project by swapping the OCX version for a temporary StdEXE version then you need to know where VB6.EXE is because this utility will execute it later when you click on ’Compile w/o .OCX’s’ in the main form. When you click on the VB6.EXE’ button, we will try to locate VB6 automatically for you. If we don’t find it, you can navigate to it or manually enter it. There are two locations towards the bottom of the form to specify the locations of Krool’s StdEXE versions (ComCtlsDemo and VBFlexGridDemo) for you to specify. You do not need these to specify an update to the OCX versions but you do need to specify these if you wish to do a commandline compilation with the StdExE controls instead of the OCX version of the controls. These files do not ever get modified so I put them in my library and I always keep the latest versions in a folder called ’Current’. You don’t need to call the folder by that name but you do need somewhere to put the new files downloaded for VBCCRxx and/or VBFLXGRDxx After you make whatever changes you want to this Compile Options form, if you click on ’Accept changes & return’ your entries will all be saved in an INI file for re-use the next time you run the StdEXE utility. The INI file is saved in the same folder where you keep the StdEXE utility. I am assuming as a programmer you will not install this into ’Program Files’ so it is more convenient to keep your settings with the program since you won’t have to worry about trying to save to ’Program Files’ requiring a UAC elevation. **Compiling** When you click on the ’Compile w/o .OCX’s’ button on the main form, the utility will look through your project file, all of your controls, modules and the manifest/resource file for references to the OCX controls and it changes them to the StdEXE controls and the references to the StdEXE controls are put in the .vbp file which is then compiled using the VB6.EXE program from a commandline (we shell out to an elevated command prompt). None of your original project files are modified. **NOTE** - Please know that the first few times you use this utility to do a commandline compilation you are likely to get some naming conflicts. The names of all of the control, page property, class files etc. (basically everything inside of the Builds folder) are ’hidden’ in the OCX but all of the file names and all of the public variables, types, procedures enums, etc. are all visible when you have your program compile with all of these controls included with your program. At this point you get to decide whether to rename your code or Krool's. I would like to have kept mine and renamed Krool's (I had 2 conflicts) but I did not because I didn’t want to track down each use of his and because I didn’t want to go through the renaming hassle every time I downloaded and update. But either way will work. Below are two screen shots, one of a successful compile and one that failed. ### Running OCX2StdEXE with Commandline Options There is now a commandline version of the utility that can do either OCX version upgrade or OCX compile using the StdEXE version just like described above but without the input form. Note that in both cases if the full path to your project has any spaces in it that the full path must be in quotes. **Compiling via the Commandline** OCX2StdExe ProjectPathAndName \[/s\[1]\[2]\[3]] \[/A\[-]\[+]] This means do a compile of the project that uses the OCX version with the StdEXE version to embed the code in the executable. If you specify /S then no files are saved after the compile other than the executable (assuming a successful compile). If you specify /S1 then the support files for the used controls are saved and if you specify /S2 then all support files for all controls are saved regardless of whether the controls are used in the project. Specifying /S3 means make a copy of the whole project in a StdEXE sub-folder and then compile that one. If you do not specify a /S switch then whatever value was saved from the last time you used the program with the dialog box is re-used. You can also specify whether or not all of the StdEXE controls are used in the commandline compile (this is different from whether any of the files are saved after the compile). Specifying /A or /A+ says use all controls and /A- means do not use all controls. If you do not specify the /A switch then whatever the currently saved value for /A is from you last run is used. Switch case does not matter. /S is the same as /s. The compiled version of the program (if successful compile) will be found in one of 2 places. If you specify /S3 then the StdEXE sub-fodler will contain not only copies of all the project files but also the compiled .EXE file. On the other hand, using any of the other SaveControls options will make the compiled EXE in the same folder as the original project file and the executable will have ’XXX\_’ appended to the front of the file name. **Updating the .OCX version in a project** OCX2StdExe ProjectPathAndName /u \[/CCRxx] \[/FLEXxx] \[/d] This causes the specified project to have its OCX controls changed to the values specified in /CCRxx or /FLExxx switches. The ’xx’ specifies the version to use (must be registered on this PC first). If no ’xx’ is specified then the latest version registered on the PC running the utility is used. As with the regular version of OCX2STDExe, the old files are saved with a new extension. Specifying /d or /D causes all of those old files containing the old OCX references to be deleted. ## How I Manage Krool’s System As you probably have figured out, I use Krool’s OCX versions of the controls during development and then use my utility to switch to a compile using Krool’s StdEXE version so I have a self-contained executable to distribute. There are a few techniques I have learned that will hopefully make this whole process very simple. * OCX Version of the Controls * I always use the latest version of the OCX files found [here](http://www.vbforums.com/showthread.php?841929-VB6-ActiveX-CommonControls-%28Replacement-of-the-MS-common-controls%29\&p=5129155#post5129155) for VBCCRxx and [here](http://www.vbforums.com/showthread.php?855931-VB6-ActiveX-VBFlexGrid-%28Replacement-of-the-MSFlexGrid-control%29\&p=5236525#post5236525) for VBFLXGRDxx. The latest versions are at the end of post #1. When you save the VBCCRxx file note that you do a Save As and drop the .docx extension since it is a trick Krool does to avoid a file size limit on VBForums for zip files. I recommend putting the file on your hard drive with the current version as part of the name. The current VBCCRxx file is version 1.7.0 so I save the file ’VBCCR17.OCX.rar.docx’ as ’VBCCR16.OCX v1.7.0.rar’. the latest VBFLXGRDxx version is 1.4.27 at least for now the file size is small enough that is still ahs the .zip extension. I would save this file which is ’VBFLXGRD14.OCX.zip’ as ’VBFLXGRD12.OCX v1.4.27.zip’. While you are on the web page getting the OCX files you should also get the .RES files (resource files) because those will be helpful a bit later. * Now you have to get the OCX files that are inside the .RAR and .ZIP files into your System folder to use them. If you are using a 32-bit version of Windows you will want to get the OCX files into C:\Windows\System32 and if you are using a 64-bit version of Windows, put them in C:\Windows\SysWOW64. Note that the OCX file doesn’t have the minor version in the file name. For example, two recent VBCCRxx.OCX versions are 1.7.12 and 1.7.13 but each is a file named VBCCR17.OCX. If an older version is already in your system folder you can just overwrite it. Note that with any operating system after XP you will have to use an elevated CMD prompt or a file manager such as Directory Opus (my favorite) that takes care of elevation for you. You don’t have to put the OCX file in the system folder but I always do that if for no other reason than I know where it is. * If you haven’t used Krool’s OCX controls at all or you have an updated version (say 1.7 instead of 1.5) then you will need to register the OCX file using regsver32 from an elevated command prompt (don’t need if you just overwrote an older file of the same name). * If you have updated OCX versions (e.g. from 1.5 to 1.7) then you will want to run my utility for each of your projects that use the earlier version and update to the most recent OCX version. * StdEXE Version of the Controls * One confusing aspect of the StdEXE version of the controls is that there are no version numbers like for the .OCX version of the controls. When Krool updates his StdEXE controls I download that package and put the date of the issue in the download file name. Then I extract the files into the same folder structure I used from before so that I always have the latest version of the controls available. Krool has cautioned against developing with these controls because they are not IDE-safe but by using this compile utility you can develop with the stable .OCX version and then commandline compile with the stdEXE version to include the controls you use into your EXE file so that you don’t need the .OCX file to distribute with your .EXE program. * You need to look into the OLEGuids folder of either VBCCRxx or VBFLXGRDxx and copy the type library OLEGuids.tlb to you system folder and register it. Fortunately this file doesn’t change very often (current version is dated 15 April 2020) but it is worth checking every now and then to make sure you aren’t using an out-of-date type library. Note that tis type library is not required for the .OCX version because it is effectively compiled into the .OCX file but it is needed for the StdEXE version. * In your program you must reference the type library in the IDE via Project | References and put a check mark by ’OLE Guid and interface definitions’. Again, this is only needed fro the StdEXE version. I take care of this for you when you use this utility and it is modifying a copy of your project that uses the OCX version to instead use the StdEXE version. * Enable the controls in the IDE via Project | Components (or Ctrl-T) and then select the appropriate controls files. For VBCCR version 1.7 you would put a check mark by ’VB Common Controls Replacement 1.7 Library’. For VBFLXGRD version 1.4 you would put a check mark by ’VB FlexGrid Control 1.4’. All of the controls should now show up in your toolbox in the IDE. * The default start action in a VB6 program is to load and display a form. You can’t do this with these controls because there is some initialization code that needs to run before any form is referenced, loaded or displayed. First you need to have Sub Main in a standard module in your project. Then you need to change the setting in Project | Properties on the General tab to make the Startup Object be a call to Sub Main instead of any forms. Then within Sub Main you need some initialization code so that you don’t crash when you call the first form. There are 2 ways to do this. * The first is to use Krool’s code directly, albeit in a strange way. The OCX control package doesn’t contain any guides or code on how to use it (it does have some code in later versions that would enable you to make your own OCX file from source code but that isn’t the same as a go-by for use). If you download the StdEXE version you will find a folder called ’Common’ and inside that are files ’Common.bas’ and ’VisualStyles.bas’. There is a sub in VisualStyles.bas called ’InitVisualStyles’ which is what you need to run before calling a form but if you just include VisualStyles.bas in your program you will find that it needs some routines from Common.bas so you have to load it too. So if you include these two files in your project, your first line in your Sub Main would be a call to InitVisualStyles and then you can call your forms. * The route I use (as you can see in the source code for my utility), I have a general standard module in my library called mVB6Core.bas in which I put enough of the code from Common.bas and VisualStyles.bas so that I can run the sub InitVisualStyles and I can do a lot of other stuff I always do (checking whether we are in the IDE or running compiled code, the current Windows version, etc.). Below is the code I have in my general initialization routine called UCCoreInit (line 1971): ```vb If OSVer >= Vista Then Dim ICC As InitCC If App.LogMode <> 0 Then Call InitReleaseVisualStyles(AddressOf ReleaseVisualStyles) ICC.dwSize = LenB(ICC) ICC.dwICC = &H4000& InitCommonControlsEx ICC Else InitCommonControls End If ``` * You would think you are good to go. Not quite yet. We have to setup visual styles for each control on each form when they are loaded. Somewhere in the initialization code for each form you need to call SetupVisualStyles and pass the form to the sub. This code is in VisualStyles.bas and it is also part of my mVB6Core.bas library. This sub SetupVisualStyles makes sure that all of the controls on the form are able to use visual styles. So you either put this call in the Form\_Load sub for each form you use. My method is close to this. I always have my forms use my class library clResizer.cls and even if I turn resizing off for a form I still have in the initialization code for my form a call to this class module which in turn calls the sub SetupVisualStyles. This way I didn’t have to make that call be a part of the code for each new form since my class library handles it. But either way works just as well. * On to manifest and resource files. Krool’s controls have nothing to do with resource files per se other than being a container for a manifest file. You are not required to use a manifest or a resource file but if you want to take advantage of visual styles, side-by-side or high DPI monitors then you must use a manifest and embed it into a resource file and then load that resource file into your executable. If you are planning to continue to use the OCX version and not do the final compile with the StdEXE version of the controls then you will likely want to use the side-by-side option. I do ***not*** do this. There is no advantage to specifying side-by-side on your development PC and in fact it causes a hassle because when you make the EXE file on your PC with the OCX version, if you have specified side-by-side on your own PC you have to have the OCX file in the same folder as your EXE to run the EXE even if it also resides and is registered in your Windows system folder. Instead, I use a resource file named OCX2StdEXE.res for all new projects (included with my utility) that specifies the use of visual styles and high DPI monitors but does not specify the use of side-by-side. If there are other files you need to have side-by-side it is okay to put them in the resource file, just don’t bother putting Krool’s OCX controls in there. Note - Even if you specify side-by-side and then decide to use my utility for compilation nothing bad will happen. My utility will strip out the side-by-side specification from inside the resource file since it is not needed or wanted when all of the code for the controls is included in the executable. As usual, your original files (the ones you have been using to develop with the OCX version) are unchanged by this. * Now it is time to plan a bit for later. If you are using a version of the StdExe controls as part of Krool’s ComCtrlDemo project that is later than 13 Aug 2020 the discussion below can be skipped because of changes Krool made to his code that makes the following only applicable to older versions. Since his controls are free it doesn’t seem to make sense why you would want to use the older versions anyway. * We are using the OCX controls for development. We do not need to worry about using these in the IDE and crashing it because Krool has taken that into account in his OCX. When you do a commandline compile I handle that as well. An issue arises when we take code that does not need it (the OCX controls themselves plus your code) and you specify that you want a commandline compile but you want to save the support files so you can open it later in the IDE. Krool controls the IDE Stop protection code via a conditional compilation constant called ’ImplementIDEStopProtection’. In his demo for the StdEXE version there is a file named ComCtlsBase and on line 3 is this conditional compilation constant set to True which later in that module cause the IDE stop protection code to be compiled. We don’t want that to happen in the commandline compile so for the commandline compile I use a copy of ComCtlsBas.bas with the conditional compilation constant commented out. In the post-commandline compile not only do you want this constant set True for all modules you want to call the sub ’ComCtlsInitIDEStopProtection’ which turns on the IDE Stop protection when you run your/his code in the IDE. I account for this in the library standard module I include with the utility called mVB6Core.bas. If you look on line 1980 you will see the following code: ```vb #If ImplementIDEStopProtection = True Then ' If you use Krool's controls, the OCX version does not need IDE protection ' but the StdEXE version does. If you are using the OCX version and then compile using ' this utility (commandline with switch to StdEXE) and elect to keep the files you will ' need to execute the following sub. At the end of the compile part of my utility I add ' ImplementIDEStopProtection = True to the list of compilation constants in the new ' .vbp project file (the one that now references the individual controls not the OCX. ' The following sub is in ComCtlsBase.bas ComCtlsInitIDEStopProtection ' constant set to False for commandline compile of Krool's controls #End If ``` Since normally the conditional compilation constant is 0 (it is not a visible part of the OCX version of the controls) then the call above to ComCtlsInitIDEStopProtection does not occur (and it shouldn’t) but if you specify to save support files in the utility, the saved project file sill have an additional conditional compilation constant ImplementIDEStopProtection set to -1 (True). The only time the procedure ComCtlsInitIDEStopProtection is even present is in this post-commandline compile situation with the saved support files so the above code does nothing outside of that situation. If you use your own initialization code you need something like this in your code if you want to be able to open the post-commandline compile support file version. Note that this is not really necessary. If you are able to compile your program with the OCX version of the controls then it is extremely likely that the commandline compile of your code with the StdEXE version of the controls will be successful and you will never need to even look at the support files (and will likely not even keep them). * So now you can develop your program. You will be using the OCX version of the controls. You can use the VBCCRxx.OCX &/or the VBFLXGRDxx.OCX packages. * If a new version of the OCX controls comes out ([here](http://www.vbforums.com/showthread.php?841929-VB6-ActiveX-CommonControls-%28Replacement-of-the-MS-common-controls%29\&p=5129155#post5129155) for VBCCRxx and [here](http://www.vbforums.com/showthread.php?855931-VB6-ActiveX-VBFlexGrid-%28Replacement-of-the-MSFlexGrid-control%29\&p=5236525#post5236525) for VBFLXGRDxx) that has the same main version as the one you are using (say you have 1.7.10 installed and 1.7.13 comes out) just copy the OCX file over the existing one. If a new main version comes out (current is 1.7 so 1.8 will be the next one) simply copy the OCX to your system folder and use regsvr32.exe to register it and then use my utility to adjust each of your programs that use the older version to the new version. * Also keep track of the StdEXE releases as part of Krool’s ComCtlsDemo ([here](http://www.vbforums.com/showthread.php?698563-CommonControls-\(Replacement-of-the-MS-common-controls\))) and the VBFlexGridDemo ([here](http://www.vbforums.com/showthread.php?848839-VBFlexGrid-Control-\(Replacement-of-the-MSFlexGrid-control\))). There are no versions per se but the most recent version on the web site corresponds very closely (if not exactly) with the latest OCX version. There used to be some differences (OCX version tended to lag a bit behind in terms of bug fixes and additional features) but for the past couple of years Krool has done a very good job of keeping the two the same. * Whenever you want to send out a version of your executable, run my utility and select the option to compile without the .OCX’s. * When doing a commandline compile you will need files for each control. The utility determines which ones are needed and includes them. However, there are some general files in the Common and Builds folder of ComCtlsDemo that may or may not be included. Whatever values you set for these in the Options form of my utility will be re-l As the developer I give you the choice of including any of them or not. You will find these in the Function DoCompile in the module zVBandVBA starting on line 191. My values are shown below. ```vb Public IncludeStartupbas As Boolean Public IncludeCommonbas As Boolean Public IncludeVisualStylesbas As Boolean Public IncludeISubclasscls As Boolean Public IncludeVTableHandlebas As Boolean Public IncludeVTableSubclasscls As Boolean Public IncludeCommonDialogcls As Boolean ``` I do not include Startup.bas in my programs because it is specific to Krool’s demo program although I have used bits of his routine in my own. I do not include VisualStyles.bas because I have incorporated that code into my initialization routine for both the OCX and StdEXE versions. VisuaStyles requires some functions and subs from Common.bas but I only took a part of them along with VisualStyles and made them Private so that for the commandline compile I can bring in the whole of Common.bas. Finally, specify that CommonDialog.bas can be included. Note that it is not automatically included. It is only included if/when the control MCIWnd.ctl is used or one or more of the property pages for CoolBar, ImageList, RichtextBox or StatusBar are used. Property pages are not used in the commandline compile option but if you elect to save the support files for later re-compiling then the property page files are included. ## Version History | **Version** | **Date** | **Comments** | | ----------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | 0.9.0 | 2 Jul 2017 | \* Initial VB6 & Excel releases for beta test. | | 0.9.1 | 4 Jul 2017 | \_ Works with no controls but 1 or more references to CommonDialog \_ Comparisons within the .vbp file are done uppercase \* Does not include reference to stdol2.tlb if the .vbp file already has that reference. | | 0.9.2 | 9 Jul 2017 | \* Correctly handles situation where no controls are used but CommonDialog is called in a Form (used to just check for this in class and standard modules). | | 0.9.3 | 31 Jul 2017 | \* Fixed path error for forms in new .vbp file | | 0.9.4 | 23 Aug 2017 | \* Reworked some relative path stuff | | 0.9.6 | 11 Jul 2018 | \* Adjusted to function name change in mUCCore of myQuickOpen to FileCreateOrOpen. | | 0.9.7 | 1 Oct 2018 | \_ Add support for VBCCR16 \_ Broke out VB6 core code into own mVB6Core.bas, parallel with mUCCore for VBA | | 0.9.8 | 24 Nov 2018 | \* Many, many changes | | 0.9.9 | 1 Dec 2018 | \_ Add support for VBFLXGRD.OCX and VBFlexGridDemo.vbp (StdEXE) \_ Combined all input onto 1 form in VB6 version \_ Made 3 option buttons for amount of post-compile support file saves (none, controls used, all controls) \_ Modified logic to include or exclude various modules from Common and Builds in compile \_ Modified logic around conditional compilation constant ImplementIDEStopProtection especially for post-compile re-use \_ New logic for include or exclude of CommonDialog.cls in compile &/or post-compile support file save. \_ Use enums to help manage code around whether VBCCRxx &/or VBFLXGRDxx are used in a given project. \_ Added commandline option for Upgrade or Compile. | | 0.9.10 | 11 Dec 2018 | \_ Fixed bug in DoCompile if VBCCRxx or VBFLXGRDxx was not installed/registered \_ Fixed bug in DoCompile on extracting manifest from resource file when resource file had no embedded manifest | | 0.9.11 | 12 Dec 2018 | \_ In DoCompile look in class and standard modules for references to VBCCRxx and/or VBFLXGRDxx (had done forms and the resource file but not .bas and .cls files) \_ On fmInput, cbutProjFile defaulted to this program's path even when a current file was already in the dialog box. Now, goes to that file's folder. | | 0.9.12 | 13 Dec 2018 | \* New check box on fmInput for DoCompile to force the use of all of StdEXE controls in the compile which is not mornally needed but if someone puts a reference to a property of a control in the OCX-based project we can see it as part of VBCCRxx but without going through each of the properties for each control we wouldn't know which control it is connected to. I don't think this is a normal occurrence so I put it there just in case someone did this in their OCX-based code. | | 0.9.13 | 19 Dec 2018 | \_ Code clean-up \_ Moved all compile options to 2nd form | | 2.0.0 | 1 Jul 2020 | \_ VBFlexGrid OCX version 1.4 is covered. \_ Krool’s controls have been replaced with standard VB6 controls. This sounds counterproductive but an update utility should not rely on a given version of the controls during the update. A small part of the change is that the manifest and side-by-side compilation has been removed. \_ It seems that Krool is close to issuing major updates to VBCCR.OCX to version1.7 and VBFlexGrid to 1.5 and this utility is now set-up to quickly add the capability to update ot these new versions. \_ The utility uses a new class module called clINI.cls that saves and restores settings between various runs of the utility in an INI file. The previous version saved settings to the registry. That is still an option but I have moved away from using the registry at all for a variety of reasons so it would require some code modification. Presently the utility will save the INI file into the same folder where the program files are copied. \* Incorporated a tooltips module by The Trick on VBForums. | | 2.1.0 | 2 Jul 2020 | \* Miscellaneous bug fixes. | | 2.1.1 | 3 Jul 2020 | \* Uploaded version did not have local version of the tooltips module. | | 2.2.0 | 20 Aug 2020 | \_ Different method for new tooltips included in clResize.cls & old one removed from VB6Core.bas \_ Works with VBCCR17.OCX. \* Slight improvements in registry reading in a couple of spots. | | 2.3.0 | 28 Aug 2020 | \_ Now includes an option to first copy the project file (& all of its modules etc.) to a sub-folder of your project called StdEXE for potential later use. \_ Lots of minor bug fixes. | | 2.3.1 | 31 Aug 2020 | \* Bug Fix - If you had your own UserControl &/or PropertyPage in your project (not Krool's controls; your own), these would not get copied into the StdExe folder for that self-contained project compile. Fixed now. | | 3.0.0 | 27 Mar 2021 | \_ You can specify individual controls to be included in a compile with the StdExe. This feature was added because of the example in post #34 where he wanted to add a control in a standard module with the control name in a variable. I didn't want to have to chase down variable assignments in your code so there is now a feature to deal with that (you should know what controls you add like this so you can turn on those controls to be included in the EXE file). Previously this was an all or nothing proposition. \_ StdExe compilation option includes looking inside all project files for references to Krool's controls including .BAS files. \_ Bug fixes in StdExe compilation section \_ VirtualCombo and VirtualListbox had been effectively ignored. \_ CommonDialog.cls was left out even if specified to be in. \_ Conditional compilation constants from user project file sometimes were left out. \_ The .PAG files were not referenced in the final .VBP file in the Copy to a sub-folder option. \_ Handling of the commandline compile output from the MS compiler/linker was improved. \* Base file locations are now required before a compile with StdExe options from the commandline. If you have not entered these file location values, you will be prompted for them before you can continue. | | 3.1.0 | 17 Nov 2021 | \_ Handles VBCCR17.OCX version 1.1 (previously only handles 1.0) \_ Set\_xx\_CCR and Set\_xx\_Flex are now only called once \* Arrays GUIDxxCCR() and GUIDccFlex() are now Public (were embedded into Set\_xx\_CCR & Set\_xx\_Flex) | | 3.2.0 | 20 Dec 2021 | \* Handles VBCCRxx.OCX up through version 1.7. Handles all VBFLXGRDxx.OCX versions including the just-released v1.5. | | 3.3.0 | 24 Jun 2023 | \_ Now works with VBFleGrd16 \_ Each OCX version is independent. VBCCR16.OCX is totally separate from VBCCR17.OCX etc. It is unusual for any of these to have multiple versions so there is as version 1.0, 1.2 and now 1.2. This version number shows up in the VBP file and also each of the .FRM files. I had assumed that version 1.0 was the version number for each .OCS because all of them only had 1,0 but now VBCCR17.OCX has 1.0, 1.1 and 1.2. Failing to recognize versions greater than 1.0 caused some problem. It is now fixed. \* Trivia- VBCCR11.OCX had a version 1.1 but that was in 2015 and I am fairly certain nobody uses that one any more. | --- --- url: /en/packages/vbccr/system/commondialog.md description: >- CommonDialog Control - VBCCR Development Manual, Complete API Reference Based on Source Code --- # CommonDialog Control Provides a wrapper class for Windows standard dialogs (Open, Save, Color, Font, Print, Help, Page Setup, Folder Browser, Find, Replace). ## Enumerations ### CdlErrorConstants | Constant | Value | Description | |------|-----|------| | CdlCancel | 32755 | User selected "Cancel" | | CdlBufferTooSmall | 20476 | File name buffer is too small | | CdlInvalidFileName | 20477 | Invalid file name | | CdlSubclassFailure | 20478 | Subclassing failed | | CdlMaxLessThanMin | 24573 | Minimum value is greater than maximum | | CdlNoFonts | 24574 | No fonts available | | CdlPrinterNotFound | 28660 | Printer not found | | CdlCreateICFailure | 28661 | Failed to create information context | | CdlDndmMismatch | 28662 | DEVMODE mismatch | | CdlNoDefaultPrn | 28663 | No default printer | | CdlNoDevices | 28664 | No print devices | | CdlInitFailure | 28665 | Print dialog initialization failed | | CdlGetDevModeFail | 28666 | Failed to get DEVMODE | | CdlLoadDrvFailure | 28667 | Failed to load printer driver | | CdlRetDefFailure | 28668 | Failed to return default DEVMODE | | CdlParseFailure | 28669 | Parse failure | | CdlHelp | 32751 | Help request | | CdlBufferLengthZero | 36848 | Buffer length is zero | ### CdlPRORConstants | Constant | Value | Description | |------|-----|------| | CdlPRORPortrait | vbPRORPortrait | Portrait orientation | | CdlPRORLandscape | vbPRORLandscape | Landscape orientation | ### CdlPRPSConstants | Constant | Value | Description | |------|-----|------| | CdlPRPSLetter | vbPRPSLetter | Letter | | CdlPRPSLetterSmall | vbPRPSLetterSmall | Letter Small | | CdlPRPSTabloid | vbPRPSTabloid | Tabloid | | CdlPRPSLedger | vbPRPSLedger | Ledger | | CdlPRPSLegal | vbPRPSLegal | Legal | | CdlPRPSStatement | vbPRPSStatement | Statement | | CdlPRPSExecutive | vbPRPSExecutive | Executive | | CdlPRPSA3 | vbPRPSA3 | A3 | | CdlPRPSA4 | vbPRPSA4 | A4 | | CdlPRPSA4Small | vbPRPSA4Small | A4 Small | | CdlPRPSA5 | vbPRPSA5 | A5 | | CdlPRPSB4 | vbPRPSB4 | B4 | | CdlPRPSB5 | vbPRPSB5 | B5 | | CdlPRPSFolio | vbPRPSFolio | Folio | | CdlPRPSQuarto | vbPRPSQuarto | Quarto | | CdlPRPS10x14 | vbPRPS10x14 | 10x14 | | CdlPRPS11x17 | vbPRPS11x17 | 11x17 | | CdlPRPSNote | vbPRPSNote | Note | | CdlPRPSEnv9 | vbPRPSEnv9 | Envelope #9 | | CdlPRPSEnv10 | vbPRPSEnv10 | Envelope #10 | | CdlPRPSEnv11 | vbPRPSEnv11 | Envelope #11 | | CdlPRPSEnv12 | vbPRPSEnv12 | Envelope #12 | | CdlPRPSEnv14 | vbPRPSEnv14 | Envelope #14 | | CdlPRPSCSheet | vbPRPSCSheet | C Sheet | | CdlPRPSDSheet | vbPRPSDSheet | D Sheet | | CdlPRPSESheet | vbPRPSESheet | E Sheet | | CdlPRPSEnvDL | vbPRPSEnvDL | Envelope DL | | CdlPRPSEnvC5 | vbPRPSEnvC5 | Envelope C5 | | CdlPRPSEnvC3 | vbPRPSEnvC3 | Envelope C3 | | CdlPRPSEnvC4 | vbPRPSEnvC4 | Envelope C4 | | CdlPRPSEnvC6 | vbPRPSEnvC6 | Envelope C6 | | CdlPRPSEnvC65 | vbPRPSEnvC65 | Envelope C65 | | CdlPRPSEnvB4 | vbPRPSEnvB4 | Envelope B4 | | CdlPRPSEnvB5 | vbPRPSEnvB5 | Envelope B5 | | CdlPRPSEnvB6 | vbPRPSEnvB6 | Envelope B6 | | CdlPRPSEnvItaly | vbPRPSEnvItaly | Envelope Italy | | CdlPRPSEnvMonarch | vbPRPSEnvMonarch | Envelope Monarch | | CdlPRPSEnvPersonal | vbPRPSEnvPersonal | Envelope Personal | | CdlPRPSFanfoldUS | vbPRPSFanfoldUS | Fanfold US | | CdlPRPSFanfoldStdGerman | vbPRPSFanfoldStdGerman | Fanfold Std German | | CdlPRPSFanfoldLglGerman | vbPRPSFanfoldLglGerman | Fanfold Lgl German | | CdlPRPSUser | vbPRPSUser | User-defined | ### CdlPRBNConstants | Constant | Value | Description | |------|-----|------| | CdlPRBNUpper | vbPRBNUpper | Upper paper bin | | CdlPRBNLower | vbPRBNLower | Lower paper bin | | CdlPRBNMiddle | vbPRBNMiddle | Middle paper bin | | CdlPRBNManual | vbPRBNManual | Manual paper feed | | CdlPRBNEnvelope | vbPRBNEnvelope | Envelope bin | | CdlPRBNEnvManual | vbPRBNEnvManual | Envelope manual feed | | CdlPRBNAuto | vbPRBNAuto | Auto feed | | CdlPRBNTractor | vbPRBNTractor | Tractor feed | | CdlPRBNSmallFmt | vbPRBNSmallFmt | Small format bin | | CdlPRBNLargeFmt | vbPRBNLargeFmt | Large format bin | | CdlPRBNLargeCapacity | vbPRBNLargeCapacity | Large capacity bin | | CdlPRBNCassette | vbPRBNCassette | Cassette bin | ### CdlPRPQConstants | Constant | Value | Description | |------|-----|------| | CdlPRPQHigh | vbPRPQHigh | High quality | | CdlPRPQMedium | vbPRPQMedium | Medium quality | | CdlPRPQLow | vbPRPQLow | Low quality | | CdlPRPQDraft | vbPRPQDraft | Draft quality | ### CdlPRCMConstants | Constant | Value | Description | |------|-----|------| | CdlPRCMMonochrome | vbPRCMMonochrome | Monochrome printing | | CdlPRCMColor | vbPRCMColor | Color printing | ### CdlPRDPConstants | Constant | Value | Description | |------|-----|------| | CdlPRDPSimplex | vbPRDPSimplex | Single-sided printing | | CdlPRDPHorizontal | vbPRDPHorizontal | Double-sided horizontal flip | | CdlPRDPVertical | vbPRDPVertical | Double-sided vertical flip | ### CdlOFNConstants | Constant | Value | Description | |------|-----|------| | CdlOFNReadOnly | \&H1 | Show read-only checkbox | | CdlOFNOverwritePrompt | \&H2 | Prompt before overwriting file | | CdlOFNHideReadOnly | \&H4 | Hide read-only checkbox | | CdlOFNNoChangeDir | \&H8 | Do not change current directory | | CdlOFNHelpButton | \&H10 | Show help button | | CdlOFNNoValidate | \&H100 | Do not validate file name | | CdlOFNAllowMultiSelect | \&H200 | Allow multiple selections | | CdlOFNExtensionDifferent | \&H400 | Extension is different | | CdlOFNPathMustExist | \&H800 | Path must exist | | CdlOFNFileMustExist | \&H1000 | File must exist | | CdlOFNCreatePrompt | \&H2000 | Prompt to create file | | CdlOFNShareAware | \&H4000 | Ignore sharing errors | | CdlOFNNoReadOnlyReturn | \&H8000& | Do not return read-only files | | CdlOFNNoNetworkButton | \&H20000 | Hide network button | | CdlOFNExplorer | \&H80000 | Use Explorer-style dialog | | CdlOFNNoDereferenceLinks | \&H100000 | Do not dereference shortcuts | | CdlOFNDontAddToRecent | \&H2000000 | Do not add to recent files | | CdlOFNForcesShowHidden | \&H10000000 | Show hidden files | ### CdlOFNShareViResultConstants | Constant | Value | Description | |------|-----|------| | CdlOFNShareViResultWarn | \&H0 | Warn on sharing violation | | CdlOFNShareViResultNoWarn | \&H1 | Do not warn on sharing violation | | CdlOFNShareViResultFallThrough | \&H2 | Ignore sharing violation | ### CdlCCConstants | Constant | Value | Description | |------|-----|------| | CdlCCRGBInit | \&H1 | Use initial color | | CdlCCFullOpen | \&H2 | Fully open the dialog | | CdlCCPreventFullOpen | \&H4 | Prevent full open | | CdlCCHelpButton | \&H8 | Show help button | | CdlCCSolidColor | \&H80 | Solid colors only | | CdlCCAnyColor | \&H100 | Any color | ### CdlCFConstants | Constant | Value | Description | |------|-----|------| | CdlCFScreenFonts | \&H1 | Screen fonts | | CdlCFPrinterFonts | \&H2 | Printer fonts | | CdlCFHelpButton | \&H4 | Show help button | | CdlCFEffects | \&H100 | Enable effects options | | CdlCFApply | \&H200 | Enable Apply button | | CdlCFScriptsOnly | \&H400 | Script fonts only | | CdlCFNoVectorFonts | \&H800 | Exclude vector fonts | | CdlCFLimitSize | \&H2000 | Limit font size | | CdlCFFixedPitchOnly | \&H4000 | Fixed-pitch fonts only | | CdlCFForceFontExist | \&H10000 | Font must exist | | CdlCFScalableOnly | \&H20000 | Scalable fonts only | | CdlCFTTOnly | \&H40000 | TrueType fonts only | | CdlCFNoFaceSel | \&H80000 | No font name selected | | CdlCFNoStyleSel | \&H100000 | No style selected | | CdlCFNoSizeSel | \&H200000 | No size selected | | CdlCFSelectScript | \&H400000 | Select script | | CdlCFNoScriptSel | \&H800000 | No script selected | | CdlCFNoVertFonts | \&H1000000 | Exclude vertical fonts | ### CdlPDConstants | Constant | Value | Description | |------|-----|------| | CdlPDAllPages | \&H0 | All pages | | CdlPDSelection | \&H1 | Selection | | CdlPDPageNums | \&H2 | Page range | | CdlPDNoSelection | \&H4 | Disable selection | | CdlPDNoPageNums | \&H8 | Disable page range | | CdlPDCollate | \&H10 | Collate copies | | CdlPDPrintToFile | \&H20 | Print to file | | CdlPDPrintSetup | \&H40 | Show print setup | | CdlPDNoWarning | \&H80 | No warning | | CdlPDReturnDC | \&H100 | Return device context | | CdlPDReturnIC | \&H200 | Return information context | | CdlPDReturnDefault | \&H400 | Return default printer | | CdlPDHelpButton | \&H800 | Show help button | | CdlPDUseDevModeCopies | \&H40000 | Use DEVMODE copy count | | CdlPDUseDevModeCopiesAndCollate | \&H40000 | Use DEVMODE copies and collate | | CdlPDDisablePrintToFile | \&H80000 | Disable print to file | | CdlPDCurrentPage | \&H400000 | Current page | | CdlPDHidePrintToFile | \&H100000 | Hide print to file | | CdlPDNoNetworkButton | \&H200000 | Hide network button | | CdlPDNoCurrentPage | \&H800000 | Disable current page | ### CdlPDResultConstants | Constant | Value | Description | |------|-----|------| | CdlPDResultCancel | \&H0 | User cancelled | | CdlPDResultPrint | \&H1 | User chose print | | CdlPDResultApply | \&H2 | User chose apply | ### CdlHelpConstants | Constant | Value | Description | |------|-----|------| | CdlHelpContext | \&H1 | Context help | | CdlHelpQuit | \&H2 | Quit help | | CdlHelpIndex | \&H3 | Help index | | CdlHelpContents | \&H3 | Help contents | | CdlHelpHelpOnHelp | \&H4 | Help on help | | CdlHelpSetIndex | \&H5 | Set help index | | CdlHelpSetContents | \&H5 | Set help contents | | CdlHelpContextPopup | \&H8 | Context popup help | | CdlHelpForceFile | \&H9 | Force help file | | CdlHelpKey | \&H101 | Keyword help | | CdlHelpCommandHelp | \&H102 | Command help | | CdlHelpPartialKey | \&H105 | Partial keyword help | ### CdlPSDConstants | Constant | Value | Description | |------|-----|------| | CdlPSDDefaultMinMargins | \&H0 | Default minimum margins | | CdlPSDMinMargins | \&H1 | Allow setting minimum margins | | CdlPSDMargins | \&H2 | Allow setting margins | | CdlPSDInThousandthsOfInches | \&H4 | In thousandths of inches | | CdlPSDInHundredthsOfMillimeters | \&H8 | In hundredths of millimeters | | CdlPSDDisableMargins | \&H10 | Disable margins | | CdlPSDDisablePrinter | \&H20 | Disable printer button | | CdlPSDNoWarning | \&H80 | No warning | | CdlPSDDisableOrientation | \&H100 | Disable orientation | | CdlPSDDisablePaper | \&H200 | Disable paper | | CdlPSDReturnDefault | \&H400 | Return default settings | | CdlPSDHelpButton | \&H800 | Show help button | | CdlPSDDisablePagePainting | \&H80000 | Disable page painting | | CdlPSDNoNetworkButton | \&H200000 | Hide network button | ### CdlBIFConstants | Constant | Value | Description | |------|-----|------| | CdlBIFReturnOnlyFSDirs | \&H1 | Return file system directories only | | CdlBIFDontGoBelowDomain | \&H2 | Do not go below domain | | CdlBIFStatusText | \&H4 | Include status text | | CdlBIFReturnFSAncestors | \&H8 | Return file system ancestors | | CdlBIFEditBox | \&H10 | Include edit box | | CdlBIFValidate | \&H20 | Validate input | | CdlBIFNewDialogStyle | \&H40 | New dialog style | | CdlBIFBrowseIncludeURLs | \&H80 | Include URLs | | CdlBIFUseNewUI | \&H50 | Use new UI | | CdlBIFUAHint | \&H100 | User hint | | CdlBIFNoNewFolderButton | \&H200 | Hide new folder button | | CdlBIFNoTranslateTargets | \&H400 | Do not translate targets | | CdlBIFBrowseForComputer | \&H1000 | Browse for computer only | | CdlBIFBrowseForPrinter | \&H2000 | Browse for printer only | | CdlBIFBrowseIncludeFiles | \&H4000 | Include files | | CdlBIFShareable | \&H8000& | Shareable | | CdlBIFBrowseFileJunctions | \&H10000 | Browse file junctions | ### CdlFRConstants | Constant | Value | Description | |------|-----|------| | CdlFRDown | \&H1 | Search downward | | CdlFRWholeWord | \&H2 | Match whole word | | CdlFRMatchCase | \&H4 | Case-sensitive | | CdlFRFindNext | \&H8 | Find next | | CdlFRReplace | \&H10 | Replace | | CdlFRReplaceAll | \&H20 | Replace all | | CdlFRHelpButton | \&H80 | Show help button | | CdlFRNoUpDown | \&H400 | Disable direction selection | | CdlFRNoMatchCase | \&H800 | Disable case selection | | CdlFRNoWholeWord | \&H1000 | Disable whole word selection | | CdlFRHideUpDown | \&H4000 | Hide direction selection | | CdlFRHideMatchCase | \&H8000& | Hide case selection | | CdlFRHideWholeWord | \&H10000 | Hide whole word selection | ## Properties ### Object ```vb Property Get Object() As Object ``` Returns the instance of the object itself. ### CancelError ```vb Property Get/Let CancelError() As Boolean ``` Indicates whether an error is raised when the user selects "Cancel". ### HookEvents ```vb Property Get/Let HookEvents() As Boolean ``` Indicates whether the dialog can raise events that require hook callbacks. ### Tag ```vb Property Get/Let Tag() As String ``` Stores additional data needed by the program. ### hDC ```vb Property Get hDC() As LongPtr ``` Returns the device context handle (read-only). ### Flags ```vb Property Get/Let Flags() As Long ``` Returns/sets the dialog option flags. ### DialogTitle ```vb Property Get/Let DialogTitle() As String ``` Sets the string displayed in the dialog title bar. ### MaxFileSize ```vb Property Get/Let MaxFileSize() As Long ``` Returns/sets the maximum size of the open file name. ### FileName ```vb Property Get/Let FileName() As String ``` Returns/sets the path and file name of the selected file. ### FileTitle ```vb Property Get FileTitle() As String ``` Returns the file name of the selected file (without path, read-only). ### FileOffset ```vb Property Get FileOffset() As Integer ``` Returns the zero-based offset from the beginning of the path to the file name (read-only). ### Filter ```vb Property Get/Let Filter() As String ``` Returns/sets the filter displayed in the dialog type list box. ### FilterIndex ```vb Property Get/Let FilterIndex() As Long ``` Returns/sets the default filter index. ### InitDir ```vb Property Get/Let InitDir() As String ``` Returns/sets the initial file directory. ### DefaultExt ```vb Property Get/Let DefaultExt() As String ``` Returns/sets the default file extension. ### Color ```vb Property Get/Let Color() As Long ``` Returns/sets the selected color. ### CustomColors ```vb Property Get/Let CustomColors() As Variant ``` Returns/sets the custom colors available for user selection. ### FontName ```vb Property Get/Let FontName() As String ``` Returns/sets the font name. ### FontSize ```vb Property Get/Let FontSize() As Single ``` Returns/sets the font size (in points). ### FontBold ```vb Property Get/Let FontBold() As Boolean ``` Returns/sets the bold font style. ### FontItalic ```vb Property Get/Let FontItalic() As Boolean ``` Returns/sets the italic font style. ### FontStrikethru ```vb Property Get/Let FontStrikethru() As Boolean ``` Returns/sets the strikethrough font style. ### FontUnderline ```vb Property Get/Let FontUnderline() As Boolean ``` Returns/sets the underline font style. ### FontCharset ```vb Property Get/Let FontCharset() As Integer ``` Returns/sets the font character set. ### FontWeight ```vb Property Get/Let FontWeight() As Integer ``` Returns/sets the font weight (0=Don'tCare, 100=Thin, 200=ExtraLight, 300=Light, 400=Normal, 500=Medium, 600=SemiBold, 700=Bold, 800=ExtraBold, 900=Heavy). ### Min ```vb Property Get/Let Min() As Long ``` Returns/sets the minimum font size (Font dialog) or minimum print page range (Print dialog). ### Max ```vb Property Get/Let Max() As Long ``` Returns/sets the maximum font size (Font dialog) or maximum print page range (Print dialog). ### FromPage ```vb Property Get/Let FromPage() As Long ``` Returns/sets the starting print page. ### ToPage ```vb Property Get/Let ToPage() As Long ``` Returns/sets the ending print page. ### Orientation ```vb Property Get/Let Orientation() As CdlPRORConstants ``` Returns/sets the print orientation. ### PaperSize ```vb Property Get/Let PaperSize() As CdlPRPSConstants ``` Returns/sets the print paper size. ### Copies ```vb Property Get/Let Copies() As Integer ``` Returns/sets the number of print copies. ### PaperBin ```vb Property Get/Let PaperBin() As CdlPRBNConstants ``` Returns/sets the default paper bin. ### PrintQuality ```vb Property Get/Let PrintQuality() As CdlPRPQConstants ``` Returns/sets the print resolution. ### ColorMode ```vb Property Get/Let ColorMode() As CdlPRCMConstants ``` Returns/sets the printer color mode. ### Duplex ```vb Property Get/Let Duplex() As CdlPRDPConstants ``` Returns/sets the duplex printing mode. ### PrinterDefault ```vb Property Get/Let PrinterDefault() As Boolean ``` Returns/sets whether the user selection changes the default printer. ### PrinterDefaultInit ```vb Property Get/Let PrinterDefaultInit() As Boolean ``` Returns/sets whether to always initialize the default printer. ### PrinterDriver ```vb Property Get/Let PrinterDriver() As String ``` Returns/sets the non-default printer driver name. ### PrinterName ```vb Property Get/Let PrinterName() As String ``` Returns/sets the non-default printer device name. ### PrinterPort ```vb Property Get/Let PrinterPort() As String ``` Returns/sets the non-default printer port name. ### HelpFile ```vb Property Get/Let HelpFile() As String ``` Returns/sets the help file name associated with the project. ### HelpCommand ```vb Property Get/Let HelpCommand() As CdlHelpConstants ``` Returns/sets the online help type. ### HelpContext ```vb Property Get/Let HelpContext() As LongPtr ``` Returns/sets the context ID for the help topic. ### HelpKey ```vb Property Get/Let HelpKey() As String ``` Returns/sets the keyword that identifies the help topic. ### PageLeftMargin ```vb Property Get/Let PageLeftMargin() As Long ``` Returns/sets the left margin of the paper (device units). ### PageTopMargin ```vb Property Get/Let PageTopMargin() As Long ``` Returns/sets the top margin of the paper (device units). ### PageRightMargin ```vb Property Get/Let PageRightMargin() As Long ``` Returns/sets the right margin of the paper (device units). ### PageBottomMargin ```vb Property Get/Let PageBottomMargin() As Long ``` Returns/sets the bottom margin of the paper (device units). ### PageLeftMinMargin ```vb Property Get/Let PageLeftMinMargin() As Long ``` Returns/sets the minimum left margin of the paper (device units). ### PageTopMinMargin ```vb Property Get/Let PageTopMinMargin() As Long ``` Returns/sets the minimum top margin of the paper (device units). ### PageRightMinMargin ```vb Property Get/Let PageRightMinMargin() As Long ``` Returns/sets the minimum right margin of the paper (device units). ### PageBottomMinMargin ```vb Property Get/Let PageBottomMinMargin() As Long ``` Returns/sets the minimum bottom margin of the paper (device units). ### RootFolder ```vb Property Get/Let RootFolder() As Variant ``` Returns/sets the root folder for the folder browser dialog. ### FindWhat ```vb Property Get/Let FindWhat() As String ``` Returns/sets the search string for the Find dialog. ### ReplaceWith ```vb Property Get/Let ReplaceWith() As String ``` Returns/sets the replacement string for the Replace dialog. ### Action ```vb Property Let Action() As Integer ``` Sets the type of dialog to display (write-only, 1=Open, 2=Save, 3=Color, 4=Font, 5=Print, 6=Help, 7=Page Setup, 8=Folder Browser, 9=Find, 10=Replace). ## Methods ### ShowOpen ```vb Public Function ShowOpen() As Boolean ``` Displays the Open dialog. Returns True on success. ### ShowSave ```vb Public Function ShowSave() As Boolean ``` Displays the Save dialog. Returns True on success. ### ShowColor ```vb Public Function ShowColor() As Boolean ``` Displays the Color dialog. Returns True on success. ### ShowFont ```vb Public Function ShowFont() As Boolean ``` Displays the Font dialog. Returns True on success. ### ShowPrinter ```vb Public Function ShowPrinter() As Boolean ``` Displays the Print dialog. Returns True on success. ### ShowPrinterEx ```vb Public Function ShowPrinterEx() As Boolean ``` Displays the extended Print dialog (PrintDlgEx). Returns True on success. ### ShowHelp ```vb Public Sub ShowHelp() ``` Displays help. ### ShowPageSetup ```vb Public Function ShowPageSetup() As Boolean ``` Displays the Page Setup dialog. Returns True on success. ### ShowFolderBrowser ```vb Public Function ShowFolderBrowser() As Boolean ``` Displays the Folder Browser dialog. Returns True on success. ### ShowFind ```vb Public Function ShowFind() As Boolean ``` Displays the Find dialog. Returns True on success. ### ShowReplace ```vb Public Function ShowReplace() As Boolean ``` Displays the Replace dialog. Returns True on success. ## Events ### InitDialog ```vb Public Event InitDialog(ByVal Action As Integer, ByVal hDlg As Long) ``` Occurs when the dialog has completed initialization. ### Help ```vb Public Event Help(ByRef Handled As Boolean, ByVal Action As Integer, ByVal hDlg As Long) ``` Occurs when the user clicks the help button in the dialog. ### FileShareViolation ```vb Public Event FileShareViolation(ByVal FileName As String, ByRef Result As CdlOFNShareViResultConstants, ByVal hDlg As Long) ``` Occurs when the user clicks OK in the Open or Save dialog and a network sharing violation occurs. ### FileValidate ```vb Public Event FileValidate(ByVal FileName As String, ByVal FileTitle As String, ByVal FileOffset As Integer, ByRef Cancel As Boolean, ByVal hDlg As Long) ``` Occurs when the user clicks OK in the Open or Save dialog. ### ColorValidate ```vb Public Event ColorValidate(ByRef RGBColor As Long, ByRef Cancel As Boolean, ByVal hDlg As Long) ``` Occurs when the user clicks OK in the Color dialog. ### FontApply ```vb Public Event FontApply(ByVal Flags As Long, ByVal FontName As String, ByVal FontSize As Single, ByVal FontBold As Boolean, ByVal FontItalic As Boolean, ByVal FontStrikethru As Boolean, ByVal FontUnderline As Boolean, ByVal FontCharset As Integer, ByVal RGBColor As Long, ByVal hDlg As Long) ``` Occurs when the user clicks the "Apply" button in the Font dialog. ### FolderBrowserValidateFailed ```vb Public Event FolderBrowserValidateFailed(ByVal Text As String, ByRef Cancel As Boolean, ByVal hDlg As Long) ``` Occurs when the user enters an invalid name in the Folder Browser dialog. ### FindNext ```vb Public Event FindNext() ``` Occurs when the user clicks the "Find Next" button in the Find or Replace dialog. ### Replace ```vb Public Event Replace() ``` Occurs when the user clicks the "Replace" button in the Replace dialog. ### ReplaceAll ```vb Public Event ReplaceAll() ``` Occurs when the user clicks the "Replace All" button in the Replace dialog. ## Code Examples ### Basic Usage ```vb Private Sub cmdOpen_Click() Dim dlg As CommonDialog Set dlg = New CommonDialog dlg.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*" dlg.FilterIndex = 1 dlg.CancelError = True On Error GoTo Cancelled If dlg.ShowOpen() Then MsgBox "Selected: " & dlg.FileName End If Exit Sub Cancelled: If Err.Number = CdlCancel Then Exit Sub MsgBox "Error: " & Err.Description End Sub ``` ### Using Event Hooks ```vb Private WithEvents dlg As CommonDialog Private Sub cmdFont_Click() Set dlg = New CommonDialog dlg.HookEvents = True dlg.Flags = CdlCFScreenFonts Or CdlCFEffects Or CdlCFLimitSize dlg.Min = 8 dlg.Max = 72 dlg.ShowFont End Sub Private Sub dlg_FontApply(ByVal Flags As Long, ByVal FontName As String, _ ByVal FontSize As Single, ByVal FontBold As Boolean, ByVal FontItalic As Boolean, _ ByVal FontStrikethru As Boolean, ByVal FontUnderline As Boolean, _ ByVal FontCharset As Integer, ByVal RGBColor As Long, ByVal hDlg As Long) Me.Font.Name = FontName Me.Font.Size = FontSize Me.Font.Bold = FontBold Me.Font.Italic = FontItalic End Sub ``` --- --- url: /en/official/IDE/AddIns/Community.md --- ::: warning AddIns are a compiled executable and therefore should be treated with the same security measures you would with any application you haven't written yourself.\ Be sure to take the necessary precautions needed. ::: See **Sample 10. twinBASIC IDE Addin** to get started writing your own, then be sure to add it back here. --- --- url: /en/official/Reference/Core/Comparison-Operators.md --- # Comparison operators Used to compare expressions and return a **Boolean** result. Syntax: > *result* **=** *expression1* *comparisonoperator* *expression2*\ > *result* **=** *object1* **Is** *object2*\ > *result* **=** *string* **Like** *pattern* *result* : Any numeric variable. *expression* : Any expression. *comparisonoperator* : Any of `<`, `<=`, `>`, `>=`, `=`, `<>`. *object* : Any object reference. *string* : Any string expression. *pattern* : Any string expression or range of characters. The following table lists the comparison operators and the conditions that determine whether *result* is **True**, **False**, or **Null**: | Operator | **True** if | **False** if | **Null** if | |:----------------------------------|:---------------------------|:---------------------------|:-----------------------------------------| | `<` (Less than) | *expression1* < *expression2* | *expression1* >= *expression2* | *expression1* or *expression2* = **Null** | | `<=` (Less than or equal to) | *expression1* <= *expression2* | *expression1* > *expression2* | *expression1* or *expression2* = **Null** | | `>` (Greater than) | *expression1* > *expression2* | *expression1* <= *expression2* | *expression1* or *expression2* = **Null** | | `>=` (Greater than or equal to) | *expression1* >= *expression2* | *expression1* < *expression2* | *expression1* or *expression2* = **Null** | | `=` (Equal to) | *expression1* = *expression2* | *expression1* <> *expression2* | *expression1* or *expression2* = **Null** | | `<>` (Not equal to) | *expression1* <> *expression2* | *expression1* = *expression2* | *expression1* or *expression2* = **Null** | ::: info The [**Is**](/en/official/Reference/Core/Is) and [**Like**](/en/official/Reference/Core/Like) operators have their own dedicated comparison semantics and are documented separately. ::: The `=` symbol is also the assignment operator (`*variable* = *expression*`). The context --- whether `=` appears in an expression or at the top of a statement --- determines which meaning applies; no explicit choice between them is required. When comparing two expressions, determining whether they are being compared as numbers or as strings can be non-obvious. The following table shows how the expressions are compared, or the result when either expression is not a **Variant**: | If | Then | |:-----------------------------------------------------------------------------------------|:------------------------------------------------------| | Both expressions are numeric (**Byte**, **Boolean**, **Integer**, **Long**, **LongLong**, **Single**, **Double**, **Date**, **Currency**) | Perform a numeric comparison. | | Both expressions are **String** | Perform a string comparison. | | One expression is numeric and the other is a **Variant** that is, or can be, a number | Perform a numeric comparison. | | One expression is numeric and the other is a string **Variant** that can't be converted to a number | A `Type Mismatch` error occurs. | | One expression is a **String** and the other is any **Variant** except a **Null** | Perform a string comparison. | | One expression is **Empty** and the other is a numeric data type | Perform a numeric comparison, using 0 as the **Empty** expression. | | One expression is **Empty** and the other is a **String** | Perform a string comparison, using `""` as the **Empty** expression. | If *expression1* and *expression2* are both **Variant** expressions, their underlying type determines how they are compared: | If | Then | |:--------------------------------------------------------------------|:------------------------------------------------------| | Both **Variant** expressions are numeric | Perform a numeric comparison. | | Both **Variant** expressions are strings | Perform a string comparison. | | One **Variant** expression is numeric and the other is a string | The numeric expression is less than the string expression. | | One **Variant** expression is **Empty** and the other is numeric | Perform a numeric comparison, using 0 as the **Empty** expression. | | One **Variant** expression is **Empty** and the other is a string | Perform a string comparison, using `""` as the **Empty** expression. | | Both **Variant** expressions are **Empty** | The expressions are equal. | When a **Single** is compared to a **Double**, the **Double** is rounded to the precision of the **Single**. If a **Currency** is compared with a **Single** or **Double**, the **Single** or **Double** is converted to a **Currency**. For **Currency**, any fractional value less than `.0001` may be lost, which can cause two values to compare as equal when they are not. String comparisons are governed by the module's [**Option Compare**](/en/official/Reference/Core/Option) setting --- **Binary** (the default; case-sensitive, ordinal) or **Text** (case-insensitive, locale-sensitive). ### Example ```vb Dim MyResult, Var1, Var2 MyResult = (45 < 35) ' Returns False. MyResult = (45 = 45) ' Returns True. MyResult = (4 <> 3) ' Returns True. MyResult = ("5" > "4") ' Returns True. Var1 = "5": Var2 = 4 ' Initialize variables. MyResult = (Var1 > Var2) ' Returns True (string compared as string). Var1 = 5: Var2 = Empty MyResult = (Var1 > Var2) ' Returns True (Empty treated as 0). Var1 = 0: Var2 = Empty MyResult = (Var1 = Var2) ' Returns True. ``` ### See Also * [**Is** operator](/en/official/Reference/Core/Is) * [**IsNot** operator](/en/official/Reference/Core/IsNot) * [**Like** operator](/en/official/Reference/Core/Like) * [**Option** statement](/en/official/Reference/Core/Option) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/VBA/Compilation.md --- # Compilation 模块 **Compilation** 模块汇集了报告运行中代码的构建方式和来源的内部函数。其大多数成员是*编译时*内部函数:它们在运行时不查找任何内容,而是在调用点将字面值嵌入到编译后的代码中,记录编译器运行时的项目、组件、过程或源文件。 ## 构建标识 [**CompilerVersion**](/official/Reference/VBA/Compilation/CompilerVersion) 返回生成运行中代码的 twinBASIC 编译器的构建号,[**ProcessorArchitecture**](/official/Reference/VBA/Compilation/ProcessorArchitecture) 返回一个 [**VbArchitecture**](/official/Reference/VBA/Constants/VbArchitecture) 常量——**vbArchWin32** 或 **vbArchWin64**——标识二进制文件是为 32 位还是 64 位执行而构建的。两者共同描述了是*哪个*编译器生成了运行中的代码,以及它运行在*什么类型*的进程中。 ```vb Debug.Print "twinBASIC build #" & CompilerVersion() If ProcessorArchitecture() = vbArchWin64 Then Debug.Print "64-bit process" Else Debug.Print "32-bit process" End If ``` ## 词法上下文 `Current...` 系列函数将调用点的源位置记录为字面字符串,在源代码编译时捕获。[**CurrentProjectName**](/official/Reference/VBA/Compilation/CurrentProjectName) 命名拥有该调用的项目(可执行文件或库),[**CurrentComponentName**](/official/Reference/VBA/Compilation/CurrentComponentName) 命名包含调用的模块、类或窗体,[**CurrentProcedureName**](/official/Reference/VBA/Compilation/CurrentProcedureName) 命名包含调用的 **Sub**、**Function** 或 **Property**,[**CurrentSourceFile**](/official/Reference/VBA/Compilation/CurrentSourceFile) 返回源文件在构建机器上的完整路径。对于 COM 类,[**CurrentComponentCLSID**](/official/Reference/VBA/Compilation/CurrentComponentCLSID) 返回由类的 [`[ClassId(...)]`](/official/Reference/Core/Attributes#classid) 属性提供的 GUID,未设置时返回全零 GUID。 由于每个值在编译时固定,将调用包装在辅助函数中会记录*辅助函数的*名称而非其调用者的名称。这些内部函数在诊断输出(日志、跟踪、断言)中最有用,它们可以替代硬编码的标识符字符串,避免代码重命名时产生不一致。 ```vb Public Sub Log(Message As String) Debug.Print CurrentProjectName() & "!" & _ CurrentComponentName() & "." & _ CurrentProcedureName() & ": " & Message End Sub ``` ## 成员 * [CompilerVersion](/official/Reference/VBA/Compilation/CompilerVersion) -- 返回 twinBASIC 编译器版本号 * [CurrentComponentCLSID](/official/Reference/VBA/Compilation/CurrentComponentCLSID) -- 返回当前类的 Class ID (CLSID) * [CurrentComponentName](/official/Reference/VBA/Compilation/CurrentComponentName) -- 返回当前组件(模块或类)的名称 * [CurrentProcedureName](/official/Reference/VBA/Compilation/CurrentProcedureName) -- 返回函数被调用时所在过程的名称 * [CurrentProjectName](/official/Reference/VBA/Compilation/CurrentProjectName) -- 返回当前项目的名称 * [CurrentSourceFile](/official/Reference/VBA/Compilation/CurrentSourceFile) -- 返回当前源文件的完整路径 * [ProcessorArchitecture](/official/Reference/VBA/Compilation/ProcessorArchitecture) -- 返回运行中应用程序的处理器架构 --- --- url: /en/official/Reference/VBA/Compilation.md --- # Compilation module The **Compilation** module groups together intrinsics that report on how --- and from where --- the running code was built. Most of its members are *compile-time* intrinsics: they do not look anything up at run time but instead embed a literal value into the compiled code at the point of the call, recording the surrounding project, component, procedure, or source file as it stood when the compiler ran. ## Build identity [**CompilerVersion**](/en/official/Reference/VBA/Compilation/CompilerVersion) returns the build number of the twinBASIC compiler that produced the running code, and [**ProcessorArchitecture**](/en/official/Reference/VBA/Compilation/ProcessorArchitecture) returns a [**VbArchitecture**](/en/official/Reference/VBA/Constants/VbArchitecture) constant --- **vbArchWin32** or **vbArchWin64** --- identifying whether the binary was built for 32-bit or 64-bit execution. Together they characterise *which* compiler emitted the running code and *what kind* of process it is running in. ```vb Debug.Print "twinBASIC build #" & CompilerVersion() If ProcessorArchitecture() = vbArchWin64 Then Debug.Print "64-bit process" Else Debug.Print "32-bit process" End If ``` ## Lexical context The `Current...` family records the source location of the call site as a literal string, captured when the source is compiled. [**CurrentProjectName**](/en/official/Reference/VBA/Compilation/CurrentProjectName) names the project (executable or library) that owns the call, [**CurrentComponentName**](/en/official/Reference/VBA/Compilation/CurrentComponentName) names the enclosing module, class, or form, [**CurrentProcedureName**](/en/official/Reference/VBA/Compilation/CurrentProcedureName) names the surrounding **Sub**, **Function**, or **Property**, and [**CurrentSourceFile**](/en/official/Reference/VBA/Compilation/CurrentSourceFile) returns the full path of the source file as it was on the build machine. For COM classes, [**CurrentComponentCLSID**](/en/official/Reference/VBA/Compilation/CurrentComponentCLSID) returns the GUID supplied by the class's [`[ClassId(...)]`](/en/official/Reference/Core/Attributes#classid) attribute, or the all-zero GUID when none is set. Because each value is fixed at compile time, wrapping a call in a helper records the *helper's* name rather than its caller's. These intrinsics are most useful in diagnostic output --- logging, tracing, assertions --- where they replace hard-coded identifier strings that would otherwise drift as code is renamed. ```vb Public Sub Log(Message As String) Debug.Print CurrentProjectName() & "!" & _ CurrentComponentName() & "." & _ CurrentProcedureName() & ": " & Message End Sub ``` ## Members * [CompilerVersion](/en/official/Reference/VBA/Compilation/CompilerVersion) -- returns the twinBASIC compiler version number * [CurrentComponentCLSID](/en/official/Reference/VBA/Compilation/CurrentComponentCLSID) -- returns the Class ID (CLSID) of the current class * [CurrentComponentName](/en/official/Reference/VBA/Compilation/CurrentComponentName) -- returns the name of the current component (module or class) * [CurrentProcedureName](/en/official/Reference/VBA/Compilation/CurrentProcedureName) -- returns the name of the procedure in which the function is called * [CurrentProjectName](/en/official/Reference/VBA/Compilation/CurrentProjectName) -- returns the name of the current project * [CurrentSourceFile](/en/official/Reference/VBA/Compilation/CurrentSourceFile) -- returns the full path of the current source file * [ProcessorArchitecture](/en/official/Reference/VBA/Compilation/ProcessorArchitecture) -- returns the processor architecture of the running application --- --- url: /en/official/Reference/VBA/TbExpressionService/Compile.md --- # Compile Parses an expression string and returns it as a compiled **ITbExpression**. Syntax: *service*.**Compile(** *expression* **)** *service* : *required* An object expression that evaluates to a **TbExpressionService** object. *expression* : *required* A **String** containing a twinBASIC-syntax expression --- for example, `"Sqr(2) + 1"` or `"UCase(FirstName) & "" "" & UCase(LastName)"`. The return value is an [**ITbExpression**](./#itbexpression-interface). Calling [**Evaluate**](/en/official/Reference/VBA/TbExpressionService/Evaluate) on it runs the expression and produces the current value; the same instance can be evaluated as many times as needed. Symbols referenced in *expression* --- function names, object members, properties --- are resolved against the binders registered with *service* at the time of the call. At least one binder must be registered before **Compile** is called; the most common starting point is [**AddStdLibraryBinder**](/en/official/Reference/VBA/TbExpressionService/AddStdLibraryBinder), which exposes the standard runtime library. Compilation is the relatively expensive step; evaluation reuses the compiled form. When a piece of source text will be used for repeated evaluation --- a formula column refreshed every row, a watch expression sampled in a debugger --- compile it once and keep the **ITbExpression** around. If *expression* is malformed, or references a symbol that no registered binder can resolve, **Compile** raises a run-time error. ### Example ```vb Dim Service As TbExpressionService = New TbExpressionService Service.AddStdLibraryBinder() Dim Square As ITbExpression = Service.Compile("Sqr(2)") Debug.Print Square.Evaluate() ' 1.4142135623731 Debug.Print Square.Evaluate() ' Same compiled instance, evaluated again. ``` ### See Also * [Evaluate](/en/official/Reference/VBA/TbExpressionService/Evaluate) method * [AddStdLibraryBinder](/en/official/Reference/VBA/TbExpressionService/AddStdLibraryBinder) method * [AddCustomBinderObject](/en/official/Reference/VBA/TbExpressionService/AddCustomBinderObject) method * [AddCustomBinder](/en/official/Reference/VBA/TbExpressionService/AddCustomBinder) method --- --- url: /zh/official/Reference/VBA/TbExpressionService/Compile.md --- # Compile 解析表达式字符串并返回编译后的 **ITbExpression**。 语法:*service*.**Compile(** *expression* **)** *service* : *必需* 计算结果为 **TbExpressionService** 对象的对象表达式。 *expression* : *必需* 包含 twinBASIC 语法表达式的 **String**——例如,`"Sqr(2) + 1"` 或 `"UCase(FirstName) & "" "" & UCase(LastName)"`。 返回值是一个 [**ITbExpression**](./#itbexpression-interface)。对其调用 [**Evaluate**](/official/Reference/VBA/TbExpressionService/Evaluate) 会运行表达式并产生当前值;同一实例可以根据需要求值任意次数。 *expression* 中引用的符号——函数名、对象成员、属性——在调用时根据 *service* 注册的绑定器解析。在调用 **Compile** 之前必须至少注册一个绑定器;最常见的起点是 [**AddStdLibraryBinder**](/official/Reference/VBA/TbExpressionService/AddStdLibraryBinder),它暴露标准运行时库。 编译是相对耗费资源的步骤;求值重用编译后的形式。当一段源文本将用于重复求值时——每行刷新的公式列、调试器中采样的监视表达式——编译一次并保留 **ITbExpression**。 如果 *expression* 格式错误,或引用了没有注册绑定器能解析的符号,**Compile** 将引发运行时错误。 ### 示例 ```vb Dim Service As TbExpressionService = New TbExpressionService Service.AddStdLibraryBinder() Dim Square As ITbExpression = Service.Compile("Sqr(2)") Debug.Print Square.Evaluate() ' 1.4142135623731 Debug.Print Square.Evaluate() ' Same compiled instance, evaluated again. ``` ### 另请参阅 * [Evaluate](/official/Reference/VBA/TbExpressionService/Evaluate) 方法 * [AddStdLibraryBinder](/official/Reference/VBA/TbExpressionService/AddStdLibraryBinder) 方法 * [AddCustomBinderObject](/official/Reference/VBA/TbExpressionService/AddCustomBinderObject) 方法 * [AddCustomBinder](/official/Reference/VBA/TbExpressionService/AddCustomBinder) 方法 --- --- url: /en/official/Features/Compiler-IDE.md --- # Design Experience and Compiler Features twinBASIC includes many compiler features and IDE enhancements to improve the development experience. ## Topics * [Compiler Warnings](/en/official/Features/Compiler-IDE/Compiler-Warnings) - Compiler warnings and strict mode * [Debugging](/en/official/Features/Compiler-IDE/Debugging) - Debug trace logger and stale pointer detection * [CodeLens](/en/official/Features/Compiler-IDE/CodeLens) - Run Subs from the IDE * [IDE Features](/en/official/Features/Compiler-IDE/IDE-Features) - Modern IDE capabilities * [Package Server](/en/official/Features/Compiler-IDE/Package-Server) - Package management system --- --- url: /en/official/Reference/Compiler-Constants.md --- This is a guide to the built in compiler constants in twinBASIC. It includes the constants listed for VBA in its documentation even if they're not defined, as an undefined compiler constant can always be used, but will be 0. ## `Win16` **Purpose:** Indicates a 16-bit Windows compatible platform.\ **Value:** Always 0 (False); 16 bit Windows is not supported. ## `Win32` **Purpose:** Indicates a 32bit compatible Windows platform\ **Value:** Always 1 (True) on supported Windows platforms, for both 32bit and 64bit. ## `Win64` **Purpose:** Indicates a 64bit Windows AMD64 platform.\ **Value:** 0 (False) when the compiler is in 32bit mode, 1 (True) when in 64bit mode. ## `VBA6` **Purpose:** Indicates compatibility with VBA6 syntax.\ **Value:** Always 1 (True). ## `VBA7` **Purpose:** Indicates compatibility with VBA7 syntax.\ **Value:** Always 1 (True). ## `MAC` **Purpose:** Indicates running on a MacOS platform.\ **Value:** Always 0 (False). Mac is not currently supported, although this will change in the future. ## `TWINBASIC` **Purpose:** Indicates compatibility with twinBASIC syntax.\ **Value:** Always 1 (True). ## `TWINBASIC_BUILD` **Purpose:** Provides a `Long` value giving the current twinBASIC Build Number.\ **Value:** Currently this is the same as the "BETA" number, e.g. for Beta 610 it will have a value of 610. ## `TWINBASIC_BUILD_TYPE` **Purpose:** Allows conditional compilation based on whether the project is an exe, dll, or ocx.\ **Value:** A `String` that can be one of "Standard EXE", "Standard DLL", "ActiveX DLL", or "ActiveX Control", determined by the "Build Type" option in Project Settings. # Usage Usage of these follows the standard syntax of using a hashtag before the standard `If/Else/ElseIf` conditionals. For example, to differentiate between 32bit and 64bit VBA vs 64bit twinBASIC, ```vb #If VBA7 Then 'We're in either VBA7 or twinBASIC #If Win64 Then 'We're in either 64bit VBA7 or 64bit twinBASIC #If TWINBASIC Then 'We're in 64bit twinBASIC #If TWINBASIC_BUILD_TYPE = "ActiveX Control" Then 'And we're building an OCX #End If #Else 'We're in 64bit VBA7 #End If #Else 'We're in either 32bit VBA7 or 32bit twinBASIC #If TWINBASIC Then 'We're in 32bit twinBASIC #Else 'We're in 32bit VBA7 #End If #End If #Else 'We're in VB6 or VBA6. Win64 will always be False by default. TWINBASIC will always be False by default. #End If ``` Or more simply, to determine whether to use `PtrSafe` then `DeclareWide` or other tB features: ```vb #If VBA7 Then #If TWINBASIC Then 'PtrSafe DeclareWide declares, if desired, also inline comments and `[ TypeHint() ]`, and function attributes. #Else 'PtrSafe declares not using DeclareWide or any new syntax #End If #Else 'Classic VB6/VBA6 declares without PtrSafe or other new syntax #End If ``` ::: warning Reminder: Compiler Constants are not `Boolean` values, so you shouuldn't use syntax like `#If Not Win64 Then` as the result may not be desired, for instance that example evaluates to `True` for both 32bit and 64bit modes when you likely used it expecting `False` under 64bit to use 32bit-only code.\ ::: If you wish to treat these as `Boolean`, you can use the `CBool()` function, e.g. `#If Not CBool(Win64) Then`. # Appearance The tB editor has the helpful feature of showing you in real time which compiler constants are active. Code in `#If` blocks is inactive and will appear grayed out if it will not execute under current settings. Note that unlike VBx, inactive code is not evaluated for errors. For example, in 32bit mode:\ ![image](/assets/oHpCiV1.rjQ32Q75.png) Then switching to 64bit mode:\ ![image](/assets/TYizrRW.B6FJyjA6.png) *** *VB6, VBA, VBA6, and VBA7 are trademarks of the Microsoft Corporation.*\ *MacOS is a trademark of Apple, Inc.* --- --- url: /en/official/Features/Project-Configuration/Compiler-Options.md --- # Compiler Options twinBASIC provides several compiler options to control how your code is compiled and optimized. ## COM Initialization You can specify the call used by the hidden entry point with the following options: `CoInitialize STA`, `CoInitializeEx MTA`, `OleInitialize STA`. If you don't know the difference, don't change it from the default. ## Symbol Table Parameters You can adjust the following parameters: Max Size Raw, Max Size Lookup, and Data Type Lookup. These options allow for compiling very large projects that would otherwise have issues, and the compiler will notify you if these values need to be increased. ## Boolean Type Sanitization Internally, a Boolean is a 2-byte type. With memory APIs, or when receiving these from outside code, it's possible to store values other than the ones representing `True` and `False`. This option validates Booleans from external sources, e.g. COM objects and APIs, to ensure only the two supported values are stored. ## Additional Options * **LARGEADDRESSAWARE**: Projects can be marked `LARGEADDRESSAWARE`. * **Base Address**: A manual base address can be specified. * **PE Relocation Symbols**: Option to strip PE relocation symbols. ## Exploit Mitigation You can enable the following security features: * **Data execution prevention (DEP)** * **Address-space layout randomization (ASLR)** --- --- url: /en/official/Features/Compiler-IDE/Compiler-Warnings.md --- # Compiler Warnings twinBASIC provides compiler warnings during design time for common bad practices or likely oversights. ## Available Warnings ### Warnings for Likely Incorrect Hex Literals Non-explicit values are coerced into the lowest possible type first. So if you declare a constant as `&H8000`, the compiler sees it as an -32,768 `Integer`, and when you're putting that into a `Long` you almost certainly do not want -32,768, you want **positive** 32,768, which requires you to instead use `&H8000&`. This warning is supplied for `&H8000`-`&HFFFF` and `&H80000000`-`&HFFFFFFFF`. ### Warnings for Implicit Variable Creation with ReDim When you use `ReDim myArray(1)`, the `myArray` variable is created for you, when it's good practice to declare all variables first. ### Warnings for Use of DefType This feature is discouraged for it making code difficult to read and prone to difficult to debug errors. The full list can be found in your project's Settings page: ![image](/assets/017bd6f8-4b35-43a9-b6be-84cba69daf64.DNFSosgo.png) ## Adjusting Warnings Each warning has the ability to set them to ignore or turn them into an error both project-wide via the Settings page, and per-module/class, and per-procedure with `[IgnoreWarnings(TB___)]`, `[EnforceWarnings(TB____)]`, and `[EnforceErrors(TB____)]` attributes, where the underscores are replaced with the **full** number, e.g. `[IgnoreWarnings(TB0001)]`; the leading zeroes must be included. ## Strict Mode twinBASIC has added the following warning messages to support something similar to .NET's Strict Mode, where certain implicit conversions are not allowed and must be made explicit. By default, these are all set to be ignored, and must be enabled in the "Compiler Warnings" section of Project Settings or per-module/procedure with `[EnforceWarnings()]`. All of these can be configured individually and ignored for procedure/module scope with `[IgnoreWarnings()]` ### TB0018: Implicit Narrowing Conversion Such as converting a Long to Integer; if you have `Dim i As Integer, l As Long` then `i = l` will trigger the warning, and `i = CInt(l)` would be required to avoid it. ### TB0019: Implicit Enumeration Conversion When assigning a member of one Enum to a variable typed as another, such as `Dim day As VbDayOfWeek: day = vbBlack`. The `CType(Of <type>)` operator whose use in pointers was described in the previous section is also used to specify an explicit type conversion in this case; the warning would not be triggered by `day = CType(Of VbDayOfWeek)(vbBlack)`. ### TB0020: Suspicious Interface Conversion If a declared coclass doesn't explicitly name an interface as supported, converting to it will trigger this warning, e.g.: ```vb Dim myPic As StdPicture Dim myFont As StdFont Set myFont = myPic ``` You'd use `Set myFont = CType(OfStdFont)(myPic)` to avoid this warning. ### TB0021: Implicit Enumeration Conversion to/from Numeric Triggered by assigning a numeric literal to a variable typed as an Enum, such as `Dim day As VbDayOfWeek: day = 1`. To avoid it you'd use `day = CType(Of VbDayOfWeek)(1)`. --- --- url: /en/official/Reference/VBA/Compilation/CompilerVersion.md --- # CompilerVersion Returns the twinBASIC compiler version number. Syntax: **CompilerVersion** \[ **()** ] The return value is a **Long** identifying the compiler that produced the running code. ### Example ```vb Debug.Print "Built with twinBASIC compiler build #" & CompilerVersion() ``` ### See Also * [ProcessorArchitecture](/en/official/Reference/VBA/Compilation/ProcessorArchitecture) function --- --- url: /zh/official/Reference/VBA/Compilation/CompilerVersion.md --- # CompilerVersion 返回 twinBASIC 编译器版本号。 语法:**CompilerVersion** \[ **()** ] 返回值是一个 **Long**,标识生成运行中代码的编译器。 ### 示例 ```vb Debug.Print "Built with twinBASIC compiler build #" & CompilerVersion() ``` ### 另请参阅 * [ProcessorArchitecture](/official/Reference/VBA/Compilation/ProcessorArchitecture) 函数 --- --- url: /en/official/Reference/Core/Const.md --- # Const Declares constants for use in place of literal values. Syntax: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Const** *constname* \[ **As** *type* ] **=** *expression* *attributes* : *optional* One or more of:\ [Description](/en/official/Reference/Attributes#description) **Public** : *optional* Keyword used at the module level to declare constants that are available to all procedures in all modules. Not allowed in procedures. **Private** : *optional* Keyword used at the class or module level to declare constants that are available only within the class or module where the declaration is made. Not allowed in procedures. *constname* : *required* Name of the constant; follows standard variable naming conventions. *type* : *optional* The data type of the constant; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal, Date, String, or Variant. Use a separate **As** *type* clause for each constant being declared. *expression* : *required* Literal, other constant, or any combination that includes all arithmetic or logical operators except **Is**. Constants are private by default. Within procedures, constants are always private; their visibility can't be changed. In standard modules, the **Public** keyword can change the default visibility of module-level constants. In class modules, constants are always private; the **Public** keyword has no effect. To combine several constant declarations on the same line, separate each constant assignment with a comma. When constant declarations are combined in this way, the **Public** or **Private** keyword, if used, applies to all of them. Variables, user-defined functions, and intrinsic Visual Basic functions (such as **Chr**) cannot be used in expressions assigned to constants. Constants can make programs self-documenting and easy to modify. Unlike variables, constants can't be inadvertently changed while the program is running. When the constant type is not explicitly declared by using **As** *type*, the constant has the data type that is most appropriate for *expression*. Constants declared in a **Sub**, **Function**, or **Property** procedure are local to that procedure. A constant declared outside a procedure is defined throughout the module in which it is declared. Constants can be used anywhere an expression is allowed. ### Example This example uses the **Const** statement to declare constants for use in place of literal values. **Public** constants are declared in the General section of a standard module, rather than a class module. **Private** constants are declared in the General section of any type of module. ```vb ' Constants are Private by default. Const MyVar = 459 ' Declare Public constant. Public Const MyString = "HELP" ' Declare Private Integer constant. Private Const MyInt As Integer = 5 ' Declare multiple constants on same line. Const MyStr = "Hello", MyDouble As Double = 3.4567 ``` --- --- url: /zh/official/Reference/Core/Const.md --- # Const 声明常量以替代字面值使用。 语法: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Const** *constname* \[ **As** *type* ] **=** *expression* *attributes* : *可选* 以下一个或多个:\ [Description](/official/Reference/Attributes#description) **Public** : *可选* 在模块级别使用的关键字,用于声明对所有模块中所有过程可用的常量。不允许在过程中使用。 **Private** : *可选* 在类或模块级别使用的关键字,用于声明仅在声明所在的类或模块内可用的常量。不允许在过程中使用。 *constname* : *必填* 常量的名称;遵循标准变量命名约定。 *type* : *可选* 常量的数据类型;可以是Byte、Boolean、Integer、Long、Currency、Single、Double、Decimal、Date、String或Variant。对每个声明的常量使用单独的 **As** *type* 子句。 *expression* : *必填* 字面值、其他常量或包含除 **Is** 外的所有算术或逻辑运算符的任意组合。 常量默认为私有。在过程中,常量始终为私有;其可见性无法更改。在标准模块中,**Public** 关键字可以更改模块级常量的默认可见性。在类模块中,常量始终为私有;**Public** 关键字无效。 要在同一行合并多个常量声明,用逗号分隔每个常量赋值。以此方式合并常量声明时,如果使用 **Public** 或 **Private** 关键字,则适用于所有常量。 变量、用户自定义函数和内部Visual Basic函数(如 **Chr**)不能用于赋给常量的表达式中。 常量可以使程序自文档化且易于修改。与变量不同,常量在程序运行时不会被意外更改。 当未使用 **As** *type* 显式声明常量类型时,常量具有最适合 *expression* 的数据类型。 在 **Sub**、**Function** 或 **Property** 过程中声明的常量是该过程的局部常量。在过程外声明的常量定义于声明它的整个模块中。常量可以在允许使用表达式的任何地方使用。 ### 示例 本示例使用 **Const** 语句声明常量以替代字面值使用。**Public** 常量在标准模块的通用部分中声明,而非类模块。**Private** 常量可以在任何类型模块的通用部分中声明。 ```vb ' Constants are Private by default. Const MyVar = 459 ' Declare Public constant. Public Const MyString = "HELP" ' Declare Private Integer constant. Private Const MyInt As Integer = 5 ' Declare multiple constants on same line. Const MyStr = "Hello", MyDouble As Double = 3.4567 ``` --- --- url: /zh/official/Reference/VBA/Constants.md --- # Constants 模块 ## 常量 **vbBack** : 退格字符——**Chr(8)**。 **vbCr** : 回车字符——**Chr(13)**。 **vbCrLf** : 回车+换行组合——**Chr(13) & Chr(10)**。 **vbFormFeed** : 换页字符——**Chr(12)**。 **vbLf** : 换行字符——**Chr(10)**。 **vbNewLine** : 平台适用的换行字符。在 twinBASIC 中,与 **vbCrLf** 相同。 **vbNullChar** : 空字符——**Chr(0)**。 **vbNullPtr** : **LongPtr** 类型的空指针(零),用于接受指针或句柄参数的 API 声明。 **vbNullString** : 空字符串指针。与零长度字符串 `""` 不同;用于调用需要区分空指针和空字符串的外部过程。 **vbObjectError** : 用户自定义错误号的基础值——**\&H80040000** (-2147221504)。用户自定义错误号应大于此值;例如 `Err.Raise vbObjectError + 1000`。 **vbTab** : 制表符——**Chr(9)**。 **vbVerticalTab** : 垂直制表符——**Chr(11)**。 ## 枚举 * [VbAppWinStyle](/official/Reference/VBA/Constants/VbAppWinStyle) -- **Shell** 函数的窗口样式值 * [VbArchitecture](/official/Reference/VBA/Constants/VbArchitecture) -- 处理器架构标识符 * [VbCalendar](/official/Reference/VBA/Constants/VbCalendar) -- 日历类型值(公历或回历) * [VbCallType](/official/Reference/VBA/Constants/VbCallType) -- **CallByName** 的过程调用类型值 * [VbCompareMethod](/official/Reference/VBA/Constants/VbCompareMethod) -- 字符串函数的文本比较模式 * [VbDateTimeFormat](/official/Reference/VBA/Constants/VbDateTimeFormat) -- **FormatDateTime** 的格式代码 * [VbDayOfWeek](/official/Reference/VBA/Constants/VbDayOfWeek) -- 日期函数的星期常量 * [VbFileAttribute](/official/Reference/VBA/Constants/VbFileAttribute) -- **Dir**、**GetAttr** 和 **SetAttr** 的文件属性标志 * [VbFirstWeekOfYear](/official/Reference/VBA/Constants/VbFirstWeekOfYear) -- 日期函数的年份首周选择器 * [VbIMEStatus](/official/Reference/VBA/Constants/VbIMEStatus) -- 输入法编辑器状态值 * [VbMsgBoxResult](/official/Reference/VBA/Constants/VbMsgBoxResult) -- **MsgBox** 返回的值 * [VbMsgBoxStyle](/official/Reference/VBA/Constants/VbMsgBoxStyle) -- **MsgBox** 的按钮、图标和行为标志 * [VbStrConv](/official/Reference/VBA/Constants/VbStrConv) -- **StrConv** 的转换类型标志 * [VbTriState](/official/Reference/VBA/Constants/VbTriState) -- 用于替代 **Boolean** 参数的三态值 * [VbVarType](/official/Reference/VBA/Constants/VbVarType) -- **VarType** 返回的变体子类型代码 --- --- url: /en/official/Reference/VBA/Constants.md --- # Constants module ## Constants **vbBack** : The backspace character --- **Chr(8)**. **vbCr** : The carriage return character --- **Chr(13)**. **vbCrLf** : The carriage return + linefeed pair --- **Chr(13) & Chr(10)**. **vbFormFeed** : The form feed character --- **Chr(12)**. **vbLf** : The linefeed character --- **Chr(10)**. **vbNewLine** : The platform-appropriate newline character. In twinBASIC, identical to **vbCrLf**. **vbNullChar** : The null character --- **Chr(0)**. **vbNullPtr** : A null pointer of type **LongPtr** (zero), for use with API declarations that take a pointer or handle argument. **vbNullString** : A null string pointer. Distinct from the zero-length string `""`; used when calling external procedures that differentiate between a null pointer and an empty string. **vbObjectError** : The base value for user-defined error numbers --- **\&H80040000** (-2147221504). User-defined error numbers should be greater than this; for example, `Err.Raise vbObjectError + 1000`. **vbTab** : The tab character --- **Chr(9)**. **vbVerticalTab** : The vertical tab character --- **Chr(11)**. ## Enumerations * [VbAppWinStyle](/en/official/Reference/VBA/Constants/VbAppWinStyle) -- window style values for the **Shell** function * [VbArchitecture](/en/official/Reference/VBA/Constants/VbArchitecture) -- processor architecture identifiers * [VbCalendar](/en/official/Reference/VBA/Constants/VbCalendar) -- calendar type values (Gregorian or Hijri) * [VbCallType](/en/official/Reference/VBA/Constants/VbCallType) -- procedure call type values for **CallByName** * [VbCompareMethod](/en/official/Reference/VBA/Constants/VbCompareMethod) -- text comparison modes for string functions * [VbDateTimeFormat](/en/official/Reference/VBA/Constants/VbDateTimeFormat) -- format codes for **FormatDateTime** * [VbDayOfWeek](/en/official/Reference/VBA/Constants/VbDayOfWeek) -- day-of-week constants for date functions * [VbFileAttribute](/en/official/Reference/VBA/Constants/VbFileAttribute) -- file attribute flags for **Dir**, **GetAttr**, and **SetAttr** * [VbFirstWeekOfYear](/en/official/Reference/VBA/Constants/VbFirstWeekOfYear) -- first-week-of-year selectors for date functions * [VbIMEStatus](/en/official/Reference/VBA/Constants/VbIMEStatus) -- Input Method Editor status values * [VbMsgBoxResult](/en/official/Reference/VBA/Constants/VbMsgBoxResult) -- the values returned by **MsgBox** * [VbMsgBoxStyle](/en/official/Reference/VBA/Constants/VbMsgBoxStyle) -- buttons, icons, and behaviour flags for **MsgBox** * [VbStrConv](/en/official/Reference/VBA/Constants/VbStrConv) -- conversion type flags for **StrConv** * [VbTriState](/en/official/Reference/VBA/Constants/VbTriState) -- three-state values used in place of **Boolean** arguments * [VbVarType](/en/official/Reference/VBA/Constants/VbVarType) -- variant subtype codes returned by **VarType** --- --- url: /en/official/Reference/VBRUN/Constants.md --- # Constants module The VBRUN **Constants** module collects the named-integer enumerations that classic VB6 forms, intrinsic controls, and runtime services use to spell out their option values --- colours, mouse pointers, key codes, drag/drop states, OLE container behaviour, printer setup values, and so on. There are no standalone constants in this module; everything is grouped into an enumeration so that **IntelliSense** can offer the right options at each property or argument. Some enumerations are tagged **\[MustBeQualified]** in the source --- their members must be referenced through the enum name (e.g. `ControlBorderStyleConstantsCustom.vbCustomBorder`) to avoid clashing with members of similarly named enumerations. This is noted on those enum's pages. ## Enumerations * [AlignConstants](/en/official/Reference/VBRUN/Constants/AlignConstants) -- alignment values for the **Align** property (none, top, bottom, left, right) * [AlignmentConstants](/en/official/Reference/VBRUN/Constants/AlignmentConstants) -- text alignment values (left, right, centred) * [AlignmentConstantsNoCenter](/en/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter) -- text alignment values without a centred option * [AppearanceConstants](/en/official/Reference/VBRUN/Constants/AppearanceConstants) -- flat or 3-D drawing style for controls * [ApplicationStartConstants](/en/official/Reference/VBRUN/Constants/ApplicationStartConstants) -- whether the application was started standalone or via Automation * [AspectTypeConstants](/en/official/Reference/VBRUN/Constants/AspectTypeConstants) -- rendering aspects of an OLE object (content, thumbnail, icon, print) * [AsyncReadConstants](/en/official/Reference/VBRUN/Constants/AsyncReadConstants) -- flags for **UserControl.AsyncRead** * [AsyncStatusCodeConstants](/en/official/Reference/VBRUN/Constants/AsyncStatusCodeConstants) -- status codes reported by the **AsyncReadProgress** event * [AsyncTypeConstants](/en/official/Reference/VBRUN/Constants/AsyncTypeConstants) -- the kind of data being read in **UserControl.AsyncRead** * [BackFillStyleConstants](/en/official/Reference/VBRUN/Constants/BackFillStyleConstants) -- whether a control's background fill is opaque or transparent * [BorderStyleConstants](/en/official/Reference/VBRUN/Constants/BorderStyleConstants) -- line style for drawn shapes (solid, dashed, dotted, transparent, ...) * [ButtonConstants](/en/official/Reference/VBRUN/Constants/ButtonConstants) -- standard or graphical button style * [CheckBoxConstants](/en/official/Reference/VBRUN/Constants/CheckBoxConstants) -- state of a check box (unchecked, checked, grayed) * [ClipboardConstants](/en/official/Reference/VBRUN/Constants/ClipboardConstants) -- clipboard format identifiers (`vbCFText`, `vbCFBitmap`, ...) * [ColorConstants](/en/official/Reference/VBRUN/Constants/ColorConstants) -- common named colours (`vbBlack`, `vbBlue`, `vbRed`, ...) * [ComboBoxConstants](/en/official/Reference/VBRUN/Constants/ComboBoxConstants) -- combo-box style (drop-down, simple, drop-down list) * [ControlBorderStyleConstants](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants) -- single-border style (none or fixed single) * [ControlBorderStyleConstantsCustom](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstantsCustom) -- single-border style with a custom-drawn option * [ControlTypeConstants](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) -- identifiers for the standard intrinsic control types * [DataBOFconstants](/en/official/Reference/VBRUN/Constants/DataBOFconstants) -- action when a Data control reaches the start of a recordset * [DataEOFConstants](/en/official/Reference/VBRUN/Constants/DataEOFConstants) -- action when a Data control reaches the end of a recordset * [DataErrorConstants](/en/official/Reference/VBRUN/Constants/DataErrorConstants) -- response to an error from a data binding operation * [DataValidateConstants](/en/official/Reference/VBRUN/Constants/DataValidateConstants) -- actions reported in a Data control's **Validate** event * [DatabaseTypeConstants](/en/official/Reference/VBRUN/Constants/DatabaseTypeConstants) -- database engine to use with the Data control (ODBC, Jet, ACE) * [DefaultCursorTypeConstants](/en/official/Reference/VBRUN/Constants/DefaultCursorTypeConstants) -- cursor type for a Data control connection * [DockModeConstants](/en/official/Reference/VBRUN/Constants/DockModeConstants) -- dock-edge values for forms and toolbars * [DragConstants](/en/official/Reference/VBRUN/Constants/DragConstants) -- states reported by **DragDrop**/**DragOver** * [DragModeConstants](/en/official/Reference/VBRUN/Constants/DragModeConstants) -- automatic or manual drag mode * [DragOverConstants](/en/official/Reference/VBRUN/Constants/DragOverConstants) -- enter/leave/over state values during a drag-over event * [DrawModeConstants](/en/official/Reference/VBRUN/Constants/DrawModeConstants) -- raster operation for **PSet**/**Line**/**Circle** drawing * [DrawStyleConstants](/en/official/Reference/VBRUN/Constants/DrawStyleConstants) -- line style for drawn lines and shape outlines * [FillStyleConstants](/en/official/Reference/VBRUN/Constants/FillStyleConstants) -- fill pattern for filled shapes * [FillStyleConstantsEx](/en/official/Reference/VBRUN/Constants/FillStyleConstantsEx) -- fill pattern with twinBASIC gradient extensions * [FormArrangeConstants](/en/official/Reference/VBRUN/Constants/FormArrangeConstants) -- MDI child arrangement modes (cascade, tile, ...) * [FormBorderStyleConstants](/en/official/Reference/VBRUN/Constants/FormBorderStyleConstants) -- form window border style (sizable, fixed dialog, tool window, ...) * [FormShowConstants](/en/official/Reference/VBRUN/Constants/FormShowConstants) -- whether a form is shown modal or modeless * [FormWindowStateConstants](/en/official/Reference/VBRUN/Constants/FormWindowStateConstants) -- normal, minimised, or maximised window state * [HitResultConstants](/en/official/Reference/VBRUN/Constants/HitResultConstants) -- return values from a **UserControl** **HitTest** event * [KeyCodeConstants](/en/official/Reference/VBRUN/Constants/KeyCodeConstants) -- virtual-key code values for **KeyDown**/**KeyUp** * [LinkModeConstants](/en/official/Reference/VBRUN/Constants/LinkModeConstants) -- DDE link mode (none, automatic, manual, notify) * [ListBoxConstants](/en/official/Reference/VBRUN/Constants/ListBoxConstants) -- list-box style (standard, check-box, colour swatch) * [LoadPictureColorConstants](/en/official/Reference/VBRUN/Constants/LoadPictureColorConstants) -- colour-depth flag for **LoadPicture** * [LoadPictureSizeConstants](/en/official/Reference/VBRUN/Constants/LoadPictureSizeConstants) -- size selector for **LoadPicture** * [LoadResConstants](/en/official/Reference/VBRUN/Constants/LoadResConstants) -- resource type for **LoadResPicture** * [LogEventTypeConstants](/en/official/Reference/VBRUN/Constants/LogEventTypeConstants) -- severity for **LogEvent** (error, warning, information) * [LogModeConstants](/en/official/Reference/VBRUN/Constants/LogModeConstants) -- destination and behaviour flags for the application log * [MenuAccelConstants](/en/official/Reference/VBRUN/Constants/MenuAccelConstants) -- keyboard-accelerator codes for menu items * [MenuControlConstants](/en/official/Reference/VBRUN/Constants/MenuControlConstants) -- alignment and triggering options for popup menus * [MouseButtonConstants](/en/official/Reference/VBRUN/Constants/MouseButtonConstants) -- bit flags for the pressed mouse buttons (left, right, middle) * [MousePointerConstants](/en/official/Reference/VBRUN/Constants/MousePointerConstants) -- cursor shape for the **MousePointer** property * [MultiSelectConstants](/en/official/Reference/VBRUN/Constants/MultiSelectConstants) -- multi-selection mode for a list box * [NegotiatePositionConstants](/en/official/Reference/VBRUN/Constants/NegotiatePositionConstants) -- positioning of OLE-negotiated menus * [OLEContainerActivateConstants](/en/official/Reference/VBRUN/Constants/OLEContainerActivateConstants) -- when the **OLE** container activates its embedded object * [OLEContainerConstants](/en/official/Reference/VBRUN/Constants/OLEContainerConstants) -- combined enumeration of all **OLE** container option values * [OLEContainerDisplayTypeConstants](/en/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants) -- whether to show content or icon * [OLEContainerSizeModeConstants](/en/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants) -- sizing rule for an embedded **OLE** object * [OLEContainerTypesAllowedConstants](/en/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants) -- linked, embedded, or either object types * [OLEContainerUpdateOptionsConstants](/en/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants) -- update mode for an **OLE**-linked object * [OLEDragConstants](/en/official/Reference/VBRUN/Constants/OLEDragConstants) -- automatic or manual **OLE** drag * [OLEDropConstants](/en/official/Reference/VBRUN/Constants/OLEDropConstants) -- none/manual/automatic **OLE** drop targets * [OLEDropEffectConstants](/en/official/Reference/VBRUN/Constants/OLEDropEffectConstants) -- effect of an **OLE** drop (copy, move, link, scroll) * [OldLinkModeConstants](/en/official/Reference/VBRUN/Constants/OldLinkModeConstants) -- legacy DDE link modes (hot, cold, server) * [PaletteModeConstants](/en/official/Reference/VBRUN/Constants/PaletteModeConstants) -- palette source for forms and controls * [ParentControlsType](/en/official/Reference/VBRUN/Constants/ParentControlsType) -- whether [**ParentControls**](/en/official/Reference/VBRUN/ParentControls/) wraps items in their **Extender** * [PictureTypeConstants](/en/official/Reference/VBRUN/Constants/PictureTypeConstants) -- the type of a **StdPicture** (bitmap, icon, metafile, enhanced metafile) * [PrinterObjectConstants](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants) -- combined enumeration of all printer setup values * [PrinterObjectConstants\_ColorMode](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_ColorMode) -- colour or monochrome printing * [PrinterObjectConstants\_Duplex](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_Duplex) -- one-sided or two-sided printing mode * [PrinterObjectConstants\_Orientation](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_Orientation) -- portrait or landscape paper orientation * [PrinterObjectConstants\_PaperBin](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperBin) -- paper-source identifiers for the printer * [PrinterObjectConstants\_PaperSize](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperSize) -- paper-size identifiers for the printer * [PrinterObjectConstants\_PrintQuality](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_PrintQuality) -- draft / low / medium / high print quality * [QueryUnloadConstants](/en/official/Reference/VBRUN/Constants/QueryUnloadConstants) -- reason codes reported in a form's **QueryUnload** event * [RasterOpConstants](/en/official/Reference/VBRUN/Constants/RasterOpConstants) -- raster-operation codes for **PaintPicture** * [RecordsetTypeConstants](/en/official/Reference/VBRUN/Constants/RecordsetTypeConstants) -- table / dynaset / snapshot recordset types * [ScaleModeConstants](/en/official/Reference/VBRUN/Constants/ScaleModeConstants) -- measurement units for a form's or container's **Scale** properties * [ScrollBarConstants](/en/official/Reference/VBRUN/Constants/ScrollBarConstants) -- which scrollbars a control should display (none, horizontal, vertical, both) * [ShapeConstants](/en/official/Reference/VBRUN/Constants/ShapeConstants) -- geometric shape selectors for the **Shape** control * [ShiftConstants](/en/official/Reference/VBRUN/Constants/ShiftConstants) -- bit flags for **Shift**, **Ctrl**, and **Alt** in mouse and key events * [ShortcutConstants](/en/official/Reference/VBRUN/Constants/ShortcutConstants) -- shortcut-key identifiers for menu items * [StartUpPositionConstants](/en/official/Reference/VBRUN/Constants/StartUpPositionConstants) -- initial position of a form (manual, owner, screen, default) * [StorageTypeContants](/en/official/Reference/VBRUN/Constants/StorageTypeContants) -- **OLE** data storage medium (`HGLOBAL`, file, `IStream`, `IStorage`, ...) * [SystemColorConstants](/en/official/Reference/VBRUN/Constants/SystemColorConstants) -- high values referring to system palette entries * [VariantTypeConstants](/en/official/Reference/VBRUN/Constants/VariantTypeConstants) -- DAO field-type tags (legacy) * [VerticalAlignmentConstants](/en/official/Reference/VBRUN/Constants/VerticalAlignmentConstants) -- vertical text alignment (top, middle, bottom) * [ZOrderConstants](/en/official/Reference/VBRUN/Constants/ZOrderConstants) -- selectors for **BringToFront** / **SendToBack** ::: info The enumeration name `StorageTypeContants` (note the missing `s`) is preserved here exactly as the runtime exposes it; the misspelling is a long-standing VB6 holdover. ::: --- --- url: /en/official/Reference/VBRUN/ContainedControls.md --- # ContainedControls class The **ContainedControls** object is a collection that exposes the controls placed inside an instance of a **UserControl** that has been set up as a control container. The author of the **UserControl** uses this collection to enumerate or inspect those constituent controls at run time. The author of the **UserControl** sees only what the consumer added --- controls placed on the **UserControl** at design time by the author themselves are not part of this collection. The collection is read-only: items cannot be added or removed through it, and the indexer returns existing controls only. To use it, the **UserControl**'s **ControlContainer** property must have been set to **True** at design time. ```vb ' Inside the UserControl that hosts other controls. Private Sub UserControl_Resize() Dim ctl As Object For Each ctl In UserControl.ContainedControls ' Lay each consumer-placed control out within the UserControl. Next ctl End Sub ``` ## Members ### Count Returns the number of controls in the collection. Syntax: *object*.**Count** *object* : *required* An object expression that evaluates to a **ContainedControls** object. The value is a **Long**. Valid indexes for [**Item**](#item) run from `1` to **Count**. ### Item Returns a single control from the collection by its one-based position. Syntax: *object*.**Item(** *index* **)** *object* : *required* An object expression that evaluates to a **ContainedControls** object. *index* : *required* A **Long** giving the one-based position of the control to return. Must be between `1` and [**Count**](#count); otherwise an error occurs. **Item** is the default member of **ContainedControls**, so the following lines are equivalent: ```vb Set ctl = UserControl.ContainedControls.Item(1) Set ctl = UserControl.ContainedControls(1) ``` The result is typed as **Object** because the consumer may have placed any kind of control inside the **UserControl**. Use [**TypeName**](/en/official/Reference/VBA/Information/TypeName) or **TypeOf** to discover the concrete type before binding to a specific control's properties. ### For Each iteration A **ContainedControls** object can be iterated with the [**For Each...Next**](/en/official/Reference/Core/For-Each-Next) statement, which yields each control in turn, in the order the consumer added them. The hidden `_NewEnum` member supplies the enumerator and is not called directly from user code. ```vb Dim ctl As Object For Each ctl In UserControl.ContainedControls Debug.Print TypeName(ctl) Next ctl ``` --- --- url: /zh/official/Reference/VBRUN/ContainedControls.md --- # ContainedControls 类 **ContainedControls**对象是一个集合,公开放置在设置为控件容器的**UserControl**实例内部的控件。**UserControl**的作者使用此集合在运行时枚举或检查这些组成控件。**UserControl**的作者只能看到消费者添加的内容——作者本人在设计时放置在**UserControl**上的控件不属于此集合。 此集合为只读:不能通过它添加或移除项,索引器仅返回现有控件。要使用它,**UserControl**的**ControlContainer**属性必须已设计时设置为**True**。 ```vb ' 在承载其他控件的UserControl内部。 Private Sub UserControl_Resize() Dim ctl As Object For Each ctl In UserControl.ContainedControls ' 在UserControl中布局每个消费者放置的控件。 Next ctl End Sub ``` ## 成员 ### Count 返回集合中的控件数量。 语法:*object*.**Count** *object* : *必需* 求值为**ContainedControls**对象的对象表达式。 值为**Long**。[**Item**](#item)的有效索引范围从1到**Count**。 ### Item 按从一开始的位置从集合中返回单个控件。 语法:*object*.**Item(** *index* **)** *object* : *必需* 求值为**ContainedControls**对象的对象表达式。 *index* : *必需* 给出要返回的控件从一开始位置的**Long**。必须在1和[**Count**](#count)之间;否则将发生错误。 **Item**是**ContainedControls**的默认成员,因此以下两行等效: ```vb Set ctl = UserControl.ContainedControls.Item(1) Set ctl = UserControl.ContainedControls(1) ``` 结果类型为**Object**,因为消费者可能放置了任何类型的控件。使用[**TypeName**](/official/Reference/VBA/Information/TypeName)或**TypeOf**在绑定到特定控件属性前发现具体类型。 ### For Each 迭代 **ContainedControls**对象可以使用[**For Each...Next**](/official/Reference/Core/For-Each-Next)语句进行迭代,按消费者添加的顺序依次产生每个控件。隐藏的\_NewEnum成员提供枚举器,不从用户代码直接调用。 ```vb Dim ctl As Object For Each ctl In UserControl.ContainedControls Debug.Print TypeName(ctl) Next ctl ``` --- --- url: /en/official/Reference/Core/Continue.md --- # Continue Immediately begins the next iteration of the enclosing loop. Syntax: **Continue** \[ **Do** | **For** | **While** ] Do : Used within a [Do](/en/official/Reference/Core/Do-Loop) loop. For : Used within a [For](/en/official/Reference/Core/For-Next) loop. While : Used within a [While](/en/official/Reference/Core/While-Wend) loop ::: info **Continue** is a twinBASIC extension. Classic VBA has no skip-iteration form for any loop construct --- the closest equivalent is a forward [**GoTo**](/en/official/Reference/Core/GoTo) to a label placed just before the loop's terminator. ::: ### Example This example uses **Continue For** to skip processing of certain characters of the string. ```vb Dim i%, ch$, text$ For i = 1 To 10 ch = Mid$(text, i, 1) If ch = " " Then Continue For ' Process a non-space character here Next i ``` --- --- url: /zh/official/Reference/Core/Continue.md --- # Continue 立即开始外层循环的下一次迭代。 语法:**Continue** \[ **Do** | **For** | **While** ] Do : 在 [Do](/official/Reference/Core/Do-Loop) 循环中使用。 For : 在 [For](/official/Reference/Core/For-Next) 循环中使用。 While : 在 [While](/official/Reference/Core/While-Wend) 循环中使用 ::: info **Continue** 是twinBASIC扩展。经典VBA中任何循环结构都没有跳过迭代的形式——最接近的等价方式是使用 [**GoTo**](/official/Reference/Core/GoTo) 前向跳转到放置在循环终止符之前的标签。 ::: ### 示例 本示例使用 **Continue For** 跳过字符串中某些字符的处理。 ```vb Dim i%, ch$, text$ For i = 1 To 10 ch = Mid$(text, i, 1) If ch = " " Then Continue For ' Process a non-space character here Next i ``` --- --- url: /en/official/Features/GUI-Components/Anchoring-Docking.md --- # Anchoring One of the new form designer features you see in twinBASIC is the 'Anchors' property: ![image](/assets/b26da59b-4e98-40b7-b97b-bb3cef4ca1d0.BcGaGtE1.png) Clicking the arrow on the left expands it to provide 4 options: ![image](/assets/d5dff8f5-c5fa-4620-ba11-430d06276b27.DcyU1nFU.png) These control whether the position of each point relative to the borders of their parent form or control container are maintained when the form is resized. By default it behaves in the expected manner; the top and left stay the same, and the control is not resized or moved with the form unless you do this manually with code, typically in the `Form_Resize` event. These provide an alternative to handle sizing and moving automatically. If a control is anchored at all 4 positions, it will be resized in both dimensions along with the form: ![image](/assets/fddbffa9-2b71-47f5-b925-e67fc66b9e5c.CQlTnV3s.png) As you can see, all anchor points were kept a constant distant from the edge, resulting in the control being resized. If you anchored only the Top, Left, and Bottom, it will be resized vertically, but not horizontally: ![image](/assets/3fa1cf2b-0af5-44ae-ae6a-3c0662f51f57.DUy7S04c.png) Right was not anchored to the edge, so it didn't move with the edge. If you remove the anchors to the Top and Left (False) but maintain the Right and Bottom anchors (True), the control will move with the Bottom and Right: ![image](/assets/0aeb25f6-d864-4ebb-a9f5-bbd7b5d242e8.Cy_MY7WO.png) The control stayed the same size, and because the Right and Bottom were anchored to the edge, they moved with the form, resulting in the whole control moving. ### Control Containers The above examples illustrate how this works with controls directly on a Form. But what if they're inside a Frame or other control container? The anchors are relative to their parent, so resizing a Form won't resize or move a control inside a Frame unless the Frame is also anchored in a way that changes its size/position. For example, if a TextBox is anchored at all 4 points, inside a Frame anchored at all 4 points, then it will resize along with the Frame: ![image](/assets/4829696d-788b-40ee-bebd-5afa44477460.BfumJ117.png) If we remove the Bottom anchor from the TextBox, but not the Frame, the Frame will be resize along the bottom, but the TextBox will not: ![image](/assets/bc9f3756-a14b-4ee7-b819-6822497b640a.DIvlgSnZ.png) Using these 4 points you can automatically maintain a relative size, position, or both, without having to manually code any of it. ::: tip Reminder, twinBASIC also adds `MinWidth`, `MinHeight`, `MaxWidth`, and `MaxHeight` properties to a Form, so those can also be automatically managed in combination with control anchors. You may want to set a minimum size so that controls do not disappear. ::: # Docking Similar to anchoring but slightly different, tB also offers a 'Dock' property: ![image](/assets/4c8b881e-1216-4819-a558-d2ce20f47fcd.CdPMi0EK.png) You might already be familiar with how a StatusBar control locks itself to the bottom of a form; that's the kind of positioning this property controls. A control can be docked on any side, and it will stay sized to the full width or height, and move with, that side of the Form or parent container. For example, a CommandButton with `vbDockBottom`: ![image](/assets/599a66ad-31d5-449f-bbf5-00963fe9aa2a.DRatQz3A.png) Besides the four sides, there's a final option: `vbDockFill`. This will have the control fill its entire parent area. This is most useful when used with a container such as a PictureBox or Frame control-- it will fill only that container when its a child of it, not the whole form. `vbDockFill` will exclude other docked controls, so you could for instance have one control with `vbDockRight` and another with `vbDockFill` that covers the rest of the Form or container while the first control stays in position on the right. ### Multiple Controls As the end of the last section suggests, it's possible to dock more than one control to the same location, such as a CommandButton and TextBox docked to the bottom. The following example also shows a PictureBox control with the `vbDockRight` + `vbDockFill` example from above: ![image](/assets/80185a8d-2952-415f-bc02-ec3ddea89568.BG4-i5TH.png) ::: tip The order of two (or more) controls docked in the same position is determined by which was set first. Currently they can't be dragged to rearranged, but you can set the Dock property back to none, and re-do them in the desired order. ::: --- --- url: /en/official/Features/GUI-Components/Modernization.md --- # Control Modernization tB will eventually replace all built in controls that you're used to, for now the ones available are: CommandButton, TextBox, ComboBox, CheckBox, OptionButton, Label, Frame, PictureBox, Line, Shape, VScrollBar, HScrollBar, Timer, DriveListBox, DirListBox, FileListBox, Image, and Data from the basic set; then, ListView, TreeView, ProgressBar, DTPicker, MonthView, Slider, and UpDown from the Common Controls. ## Key Modernization Features * **64-bit Support**: Every control can be compiled both as 32bit and 64bit without changing anything. * **DPI Aware**: They will automatically size correctly when dpi awareness is enabled for your app. * **Visual Styles**: Controls support Visual Styles per-control. Comctl6 styles can be applied, or not, on a control-by-control basis with the `.VisualStyles` property. ## Alternatives for Unimplemented Controls The best option is Krool's VBCCR and VBFlexGrid projects. These are now available [from the Package Server](/en/official/Features/Packages/Importing-a-package-from-TWINSERV) in x64-compatible form, and are also DPI aware and support Visual Styles. Additionally, the original OCX controls provided by Microsoft will work fine; however, they're mostly 32-bit only. The x64 version of `MSComCtl.ocx` doesn't come with Windows and isn't legally redistributable but if you have Office 64bit, it works in tB. --- --- url: /en/official/Features/GUI-Components/Control-Properties.md --- # Control Property Enhancements ## TextBox Enhancements * `TextBox.NumbersOnly` property: Restricts input to 0-9 by setting the `ES_NUMBER` style on the underlying control. * `TextBox.TextHint` property: Sets the light gray hint text in an empty TextBox (`EM_SETCUEBANNER`). ## Label Enhancements * `Label.VerticalAlignment` property: Defaults to Top. * `Label.LineSpacing` property (in twips, default is 0) * `Label.Angle` property (in degrees, rotates the label text) * `Label.BorderCustom` property (has suboptions to set size, padding and color of borders independently for each side). ## Timer Enhancements `Timer.Interval` can now be set to any positive `Long` instead of being limited to 65,535. ## Example ```vb TextBox1.TextHint = "Enter your name" TextBox1.NumbersOnly = True Label1.Angle = 45 Label1.LineSpacing = 30 Timer1.Interval = 120000 ' 2 minutes; not limited to 65,535 ms ``` --- --- url: /en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants.md --- # ControlBorderStyleConstants Border-style values for the **BorderStyle** property of intrinsic controls such as text boxes, picture boxes, and labels. | Constant | Value | Description | |----------|-------|-------------| | **vbNoBorder** | 0 | No border is drawn. | | **vbFixedSingleBorder** | 1 | A single, non-resizable border. | --- --- url: /zh/official/Reference/VBRUN/Constants/ControlBorderStyleConstants.md --- # ControlBorderStyleConstants 文本框、图片框和标签等内在控件的**BorderStyle**属性的边框样式值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbNoBorder** | 0 | 不绘制边框。 | | **vbFixedSingleBorder** | 1 | 固定单线边框,不可调整大小。 | --- --- url: /en/official/Reference/VBRUN/Constants/ControlBorderStyleConstantsCustom.md --- # ControlBorderStyleConstantsCustom Border-style values for controls that support a custom-drawn border in addition to the standard options. The enumeration is tagged **\[MustBeQualified]**, so members must be referenced through the enum name (`ControlBorderStyleConstantsCustom.vbCustomBorder`) to avoid clashing with the similarly named values in [**ControlBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants). | Constant | Value | Description | |----------|-------|-------------| | **vbNoBorder** | 0 | No border is drawn. | | **vbFixedSingleBorder** | 1 | A single, non-resizable border. | | **vbCustomBorder** | 2 | The control raises the events that let user code paint the border itself. | --- --- url: /zh/official/Reference/VBRUN/Constants/ControlBorderStyleConstantsCustom.md --- # ControlBorderStyleConstantsCustom 除标准选项外还支持自定义绘制边框的控件的边框样式值。该枚举标记为\*\*\[MustBeQualified]\*\*,因此成员必须通过枚举名引用(`ControlBorderStyleConstantsCustom.vbCustomBorder`),以避免与[**ControlBorderStyleConstants**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants)中类似命名的值冲突。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbNoBorder** | 0 | 不绘制边框。 | | **vbFixedSingleBorder** | 1 | 固定单线边框,不可调整大小。 | | **vbCustomBorder** | 2 | 控件引发允许用户代码自行绘制边框的事件。 | --- --- url: /en/official/Reference/Controls.md --- # Controls The standard set of UI control classes that ship with twinBASIC lives in the **VB** built-in package --- see [VB Package](/en/official/Reference/VB/) for the package landing page. The classes below are grouped by purpose; each entry links to the per-class reference. ## Forms and host classes These classes are *containers* rather than controls in the strict sense --- they host other controls and back the form/control designer in the IDE. * [Form](/en/official/Reference/VB/Form/) -- top-level window hosting controls, menus, and a drawing surface. * [MDIForm](/en/official/Reference/VB/MDIForm/) -- top-level MDI parent that hosts MDI-child [Form](/en/official/Reference/VB/Form/) instances inside a recessed client area. * [UserControl](/en/official/Reference/VB/UserControl/) -- base class for designing a reusable ActiveX control in twinBASIC. * [PropertyPage](/en/official/Reference/VB/PropertyPage/) -- container backing a single tab of a COM property-page dialog (the **(Custom)** popup on an ActiveX control's property browser). * [Report](/en/official/Reference/VB/Report/) -- top-level window specialised for banded report layout, print preview, and printing. ## Buttons and toggles * [CommandButton](/en/official/Reference/VB/CommandButton/) -- push-button used to trigger an action. * [CheckBox](/en/official/Reference/VB/CheckBox/) -- two- or three-state check box with an optional text caption. * [CheckMark](/en/official/Reference/VB/CheckMark/) -- windowless check glyph that scales to fill its rectangle; no caption, no focus. * [OptionButton](/en/official/Reference/VB/OptionButton/) -- radio-button; option buttons sharing a container form a mutually-exclusive group. ## Text and value input * [TextBox](/en/official/Reference/VB/TextBox/) -- single-line or multi-line edit control, with optional password masking and digit-only input. * [ComboBox](/en/official/Reference/VB/ComboBox/) -- edit field combined with a drop-down list of items. * [ListBox](/en/official/Reference/VB/ListBox/) -- vertically-scrolling list of items, optionally multi-column and multi-select. * [HScrollBar](/en/official/Reference/VB/HScrollBar/) -- stand-alone horizontal scroll bar. * [VScrollBar](/en/official/Reference/VB/VScrollBar/) -- stand-alone vertical scroll bar. ## File-system browsing These three controls are normally connected together to build a complete file picker. * DriveListBox --- drive picker. *Not yet documented.* * [DirListBox](/en/official/Reference/VB/DirListBox/) -- directory-tree picker for a single path. * [FileListBox](/en/official/Reference/VB/FileListBox/) -- file list for a single directory, filtered by wildcard and file-attribute toggles. ## Containers * [Frame](/en/official/Reference/VB/Frame/) -- captioned container that groups related controls and scopes [OptionButton](/en/official/Reference/VB/OptionButton/) groups. * [MultiFrame](/en/official/Reference/VB/MultiFrame/) -- layout container that arranges a set of [Frame](/en/official/Reference/VB/Frame/) controls in a horizontal or vertical strip. * [PictureBox](/en/official/Reference/VB/PictureBox/) -- Win32 native control combining picture display, a drawing surface, and a child-control container. ## Display-only * [Label](/en/official/Reference/VB/Label/) -- windowless lightweight read-only text display, used for captions, status text, and keyboard mnemonics. * [Image](/en/official/Reference/VB/Image/) -- windowless lightweight picture display; the small, efficient alternative to [PictureBox](/en/official/Reference/VB/PictureBox/). * [Line](/en/official/Reference/VB/Line/) -- windowless single straight line between two endpoints. * [Shape](/en/official/Reference/VB/Shape/) -- windowless geometric primitive (rectangle, oval, circle, star, arrow, …) with configurable border, fill, and rotation. * [QRCode](/en/official/Reference/VB/QRCode/) -- windowless QR-code renderer populated from a text or byte-array payload. ## Menus * [Menu](/en/official/Reference/VB/Menu/) -- item in a Win32 native menu --- top-level entry on a [Form](/en/official/Reference/VB/Form/)'s or [MDIForm](/en/official/Reference/VB/MDIForm/)'s menu bar, a drop-down entry, or a separator. ## Data and external content * [Data](/en/official/Reference/VB/Data/) -- Win32 native control that opens a DAO recordset and exposes record-navigation buttons for bound controls. * [OLE](/en/official/Reference/VB/OLE/) -- OLE container hosting a linked or embedded OLE Automation object (Word document, Excel sheet, …). * [Timer](/en/official/Reference/VB/Timer/) -- non-visual control that raises a periodic event at a programmable interval. --- --- url: /en/official/Reference/VBRUN/Constants/ControlTypeConstants.md --- # ControlTypeConstants Identifiers for the standard intrinsic and bundled control types, used by runtime introspection --- for example by code that inspects the contents of a form's **Controls** collection. | Constant | Value | Description | |----------|-------|-------------| | **vbCommandButton** | 0 | A command-button control. | | **vbListBox** | 1 | A list-box control. | | **vbComboBox** | 2 | A combo-box control. | | **vbOptionButton** | 3 | An option-button (radio button) control. | | **vbCheckBox** | 4 | A check-box control. | | **vbFrame** | 5 | A frame control. | | **vbLabel** | 6 | A label control. | | **vbPictureBox** | 7 | A picture-box control. | | **vbTextBox** | 8 | A text-box control. | | **vbTimer** | 9 | A timer control. | | **vbUserControl** | 10 | An ActiveX user control. | | **vbHScrollBar** | 11 | A horizontal scrollbar. | | **vbVScrollBar** | 12 | A vertical scrollbar. | | **vbImage** | 13 | An image control. | | **vbDirListBox** | 14 | A directory list-box. | | **vbDriveListBox** | 15 | A drive list-box. | | **vbFileListBox** | 16 | A file list-box. | | **vbForm** | 17 | A form. | | **vbWebView2** | 18 | A [**WebView2**](/en/official/Reference/WebView2/WebView2/) control. | | **vbActiveXExtender** | 19 | An ActiveX extender wrapper. | | **vbShape** | 20 | A shape control. | | **vbProgressBar** | 21 | A progress-bar control. | | **vbTreeView** | 22 | A tree-view control. | | **vbOLEControl** | 23 | An OLE container control. | | **vbDataControl** | 24 | A data control. | | **vbMenuControl** | 25 | A menu item. | | **vbSlider** | 26 | A slider (track-bar) control. | | **vbUpDown** | 27 | An up-down (spin) control. | | **vbDTPicker** | 28 | A date-time picker control. | | **vbMonthView** | 29 | A month-view (calendar) control. | | **vbListView** | 30 | A list-view control. | | **vbImageList** | 31 | An image-list control. | | **vbPropertyPage** | 32 | A property-page surface. | | **vbHwndControl** | 33 | A control hosted by an `HWND`. | | **vbReport** | 34 | A report (data-report) control. | | **vbCheckMark** | 35 | A check-mark control. | | **vbTwinBridge** | 36 | A TwinBridge interop wrapper (twinBASIC). | | **vbCefBrowser** | 37 | A [**CefBrowser**](/en/official/Reference/CEF/CefBrowser/) control. | --- --- url: /zh/official/Reference/VBRUN/Constants/ControlTypeConstants.md --- # ControlTypeConstants 标准内在和捆绑控件类型的标识符,由运行时自省使用 --- 例如检查窗体**Controls**集合内容的代码。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbCommandButton** | 0 | 命令按钮控件。 | | **vbListBox** | 1 | 列表框控件。 | | **vbComboBox** | 2 | 组合框控件。 | | **vbOptionButton** | 3 | 选项按钮(单选按钮)控件。 | | **vbCheckBox** | 4 | 复选框控件。 | | **vbFrame** | 5 | 框架控件。 | | **vbLabel** | 6 | 标签控件。 | | **vbPictureBox** | 7 | 图片框控件。 | | **vbTextBox** | 8 | 文本框控件。 | | **vbTimer** | 9 | 定时器控件。 | | **vbUserControl** | 10 | ActiveX用户控件。 | | **vbHScrollBar** | 11 | 水平滚动条。 | | **vbVScrollBar** | 12 | 垂直滚动条。 | | **vbImage** | 13 | 图像控件。 | | **vbDirListBox** | 14 | 目录列表框。 | | **vbDriveListBox** | 15 | 驱动器列表框。 | | **vbFileListBox** | 16 | 文件列表框。 | | **vbForm** | 17 | 窗体。 | | **vbWebView2** | 18 | [**WebView2**](/official/Reference/WebView2/WebView2/)控件。 | | **vbActiveXExtender** | 19 | ActiveX扩展器包装。 | | **vbShape** | 20 | 形状控件。 | | **vbProgressBar** | 21 | 进度条控件。 | | **vbTreeView** | 22 | 树视图控件。 | | **vbOLEControl** | 23 | OLE容器控件。 | | **vbDataControl** | 24 | 数据控件。 | | **vbMenuControl** | 25 | 菜单项。 | | **vbSlider** | 26 | 滑块(跟踪条)控件。 | | **vbUpDown** | 27 | 上下调整(微调)控件。 | | **vbDTPicker** | 28 | 日期时间选择器控件。 | | **vbMonthView** | 29 | 月视图(日历)控件。 | | **vbListView** | 30 | 列表视图控件。 | | **vbImageList** | 31 | 图像列表控件。 | | **vbPropertyPage** | 32 | 属性页面。 | | **vbHwndControl** | 33 | 由`HWND`承载的控件。 | | **vbReport** | 34 | 报表(数据报表)控件。 | | **vbCheckMark** | 35 | 勾选标记控件。 | | **vbTwinBridge** | 36 | TwinBridge互操作包装(twinBASIC)。 | | **vbCefBrowser** | 37 | [**CefBrowser**](/official/Reference/CEF/CefBrowser/)控件。 | --- --- url: /zh/official/Reference/VBA/Conversion.md --- # Conversion 模块 **Conversion** 模块汇集了从一种类型的值生成另一种类型的值的过程——在内部数值类型之间强制转换、从字符串解析数字、将数字格式化为字符串,以及处理 **Null**、错误值和替代数字基数的相关工具。 ## 强制转换为特定类型 最大的一组是 **C** 前缀函数系列,每种内部数据类型一个。每个函数接受任何有效表达式并生成指定类型的值,如果无法转换则引发运行时错误:[**CBool**](/official/Reference/VBA/Conversion/CBool)、[**CByte**](/official/Reference/VBA/Conversion/CByte)、[**CCur**](/official/Reference/VBA/Conversion/CCur)、[**CDate**](/official/Reference/VBA/Conversion/CDate)、[**CDbl**](/official/Reference/VBA/Conversion/CDbl)、[**CDec**](/official/Reference/VBA/Conversion/CDec)、[**CInt**](/official/Reference/VBA/Conversion/CInt)、[**CLng**](/official/Reference/VBA/Conversion/CLng)、[**CLngLng**](/official/Reference/VBA/Conversion/CLngLng)、[**CLngPtr**](/official/Reference/VBA/Conversion/CLngPtr)、[**CSng**](/official/Reference/VBA/Conversion/CSng)、[**CStr**](/official/Reference/VBA/Conversion/CStr) 和 [**CVar**](/official/Reference/VBA/Conversion/CVar)。 除了其缩窄或扩展行为外,C 前缀函数是*区域设置感知*的——它们遵循当前的小数分隔符和短日期格式——这使它们成为解析源自用户输入的值的正确选择。它们还起到文档作用:编写 `CLng(x)` 可以明确中间结果的预期类型,即使在周围上下文会隐式强制转换 *x* 的情况下也是如此。 ```vb Dim Amount As Currency Amount = CCur("1,234.56") ' parses with the local decimal separator ``` 另外两个构造函数返回子类型固定的 **Variant**:[**CVDate**](/official/Reference/VBA/Conversion/CVDate) 构建子类型为 **Date** 的 **Variant**(保留用于与 **Date** 成为内部类型之前编写的代码兼容),[**CVErr**](/official/Reference/VBA/Conversion/CVErr) 构建子类型为 **Error** 且包含选定错误号的 **Variant**——这是返回 **Variant** 的函数在不引发运行时错误的情况下表示"此调用失败并返回此错误代码"的规范方式。 ## 泛型转换 [**CType**](/official/Reference/VBA/Conversion/CType) 是 twinBASIC 扩展,它以泛型参数接收目标类型,写作 `CType(Of `*type*`)(`*value*`)`。它与 C 前缀函数扮演相同的角色,但适用于编译器已知的任何类型,这使其成为没有固定名称函数的 **Enum** 值、接口和用户自定义类型的标准转换方式。**CType** 还可以用作指针到 UDT 的转换——参见[增强指针功能](/official/Features/Language/Pointers#ctypeof-type)。 ```vb Dim day As VbDayOfWeek day = CType(Of VbDayOfWeek)(1) ``` ## 截断为整数 [**Int**](/official/Reference/VBA/Conversion/Int) 和 [**Fix**](/official/Reference/VBA/Conversion/Fix) 都丢弃数字的小数部分,但对于负数输入,它们的舍入方向相反。**Int** 向负无穷舍入,因此 `Int(-8.4)` 为 `-9`;**Fix** 向零截断,因此 `Fix(-8.4)` 为 `-8`。对于正值,两者相同。两者都不改变其参数的数据类型,这与 [**CInt**](/official/Reference/VBA/Conversion/CInt) 和 [**CLng**](/official/Reference/VBA/Conversion/CLng) 不同,后者既舍入又缩窄到特定的整数类型。 ```vb Debug.Print Int(-8.4) ' -9 Debug.Print Fix(-8.4) ' -8 ``` ## 数字、字符串和进制 [**Str**](/official/Reference/VBA/Conversion/Str)、[**Hex**](/official/Reference/VBA/Conversion/Hex) 和 [**Oct**](/official/Reference/VBA/Conversion/Oct) 都返回数字的可打印字符串表示——**Str** 为十进制,**Hex** 为十六进制,**Oct** 为八进制。反过来,[**Val**](/official/Reference/VBA/Conversion/Val) 和 [**ValDec**](/official/Reference/VBA/Conversion/ValDec) 从字符串中解析前导数字,分别返回 **Double** 或 **Decimal**;两者都在第一个无法识别的字符处停止,并且都识别十六进制和八进制字面量的 `&H` 和 `&O` 基数前缀。 这五个函数是*区域性不变*的——它们始终使用句点(`.`)作为小数分隔符,且从不读取或写入千位分隔符——这使它们适合在固定文件格式或通信协议中往返使用。对于区域设置感知的文本转换,请改用 [**CStr**](/official/Reference/VBA/Conversion/CStr) 和 [**CDbl**](/official/Reference/VBA/Conversion/CDbl)(或 [**CDec**](/official/Reference/VBA/Conversion/CDec))。 ```vb Debug.Print Hex(255) ' "FF" Debug.Print Oct(8) ' "10" Debug.Print Val("&HFF") ' 255 ``` ## 处理 Null 和错误值 [**Nz**](/official/Reference/VBA/Conversion/Nz) 在其参数为 **Null** 时返回替代值,其他值保持不变。它最常用于从数据库记录集读取可为空的列,其中直接将该字段与另一个值进行拼接或算术组合会导致 **Null** 传播到表达式的其余部分。 [**Error**](/official/Reference/VBA/Conversion/Error) 返回与错误号关联的描述性文本——与使用该错误号引发的 [**ErrObject**](/official/Reference/VBA/ErrObject/) 的 **Description** 中显示的文本相同。它是同名 [**Error** 语句](/official/Reference/Core/Error)的函数对应形式——语句*引发*运行时错误,而非描述错误。 ## Macintosh 兼容性 [**MacID**](/official/Reference/VBA/Conversion/MacID) 将四字符的 Macintosh 资源类型或应用程序签名打包为 **Long**,用于 [**Dir**](/official/Reference/VBA/FileSystem/Dir)、[**Kill**](/official/Reference/VBA/FileSystem/Kill)、**Shell** 或 [**AppActivate**](/official/Reference/VBA/Interaction/AppActivate)。twinBASIC 目前面向 Windows,在这些函数中该值没有特殊含义;提供 **MacID** 是为了与最初为经典 Mac 编写的 VBA 代码保持源代码兼容性。 ## 成员 * [CBool](/official/Reference/VBA/Conversion/CBool) -- 将表达式转换为 **Boolean** * [CByte](/official/Reference/VBA/Conversion/CByte) -- 将表达式转换为 **Byte** * [CCur](/official/Reference/VBA/Conversion/CCur) -- 将表达式转换为 **Currency** * [CDate](/official/Reference/VBA/Conversion/CDate) -- 将日期/时间表达式转换为 **Date** * [CDbl](/official/Reference/VBA/Conversion/CDbl) -- 将表达式转换为 **Double** * [CDec](/official/Reference/VBA/Conversion/CDec) -- 将表达式转换为 **Decimal** * [CInt](/official/Reference/VBA/Conversion/CInt) -- 将表达式转换为 **Integer** * [CLng](/official/Reference/VBA/Conversion/CLng) -- 将表达式转换为 **Long** * [CLngLng](/official/Reference/VBA/Conversion/CLngLng) -- 将表达式转换为 **LongLong** * [CLngPtr](/official/Reference/VBA/Conversion/CLngPtr) -- 将表达式转换为 **LongPtr** * [CSng](/official/Reference/VBA/Conversion/CSng) -- 将表达式转换为 **Single** * [CStr](/official/Reference/VBA/Conversion/CStr) -- 将表达式转换为 **String** * [CType](/official/Reference/VBA/Conversion/CType) -- 泛型类型转换,支持 **CType(Of *type*)** 转换运算符 * [CVar](/official/Reference/VBA/Conversion/CVar) -- 将表达式转换为 **Variant** * [CVDate](/official/Reference/VBA/Conversion/CVDate) -- 将日期/时间表达式转换为子类型为 **Date** 的 **Variant** * [CVErr](/official/Reference/VBA/Conversion/CVErr) -- 将数值表达式转换为子类型为 **Error** 的 **Variant** * [Error](/official/Reference/VBA/Conversion/Error) -- 返回与给定错误号对应的错误消息 * [Fix](/official/Reference/VBA/Conversion/Fix) -- 返回数字的整数部分,向零截断 * [Hex](/official/Reference/VBA/Conversion/Hex) -- 返回数字的十六进制字符串表示 * [Int](/official/Reference/VBA/Conversion/Int) -- 返回数字的整数部分,向负无穷舍入 * [MacID](/official/Reference/VBA/Conversion/MacID) -- 在 Macintosh 上,将 4 字符常量转换为可供 **Dir**、**Kill**、**Shell** 或 **AppActivate** 使用的值 * [Nz](/official/Reference/VBA/Conversion/Nz) -- 用指定的替换值替代 **Null** 值 * [Oct](/official/Reference/VBA/Conversion/Oct) -- 返回数字的八进制字符串表示 * [Str](/official/Reference/VBA/Conversion/Str) -- 返回数字的字符串表示 * [Val](/official/Reference/VBA/Conversion/Val) -- 将字符串解析为 **Double** * [ValDec](/official/Reference/VBA/Conversion/ValDec) -- 将字符串解析为 **Decimal** --- --- url: /en/official/Reference/VBA/Conversion.md --- # Conversion module The **Conversion** module groups together the procedures that produce a value of one type from a value of another --- coercing between the intrinsic numeric types, parsing numbers out of strings, formatting numbers as strings, and a handful of related utilities for handling **Null**, error values, and alternate numeric bases. ## Coercing to a specific type The largest group is the family of **C**-prefixed functions, one per intrinsic data type. Each accepts any valid expression and produces a value of the named type, raising a run-time error if the conversion is not possible: [**CBool**](/en/official/Reference/VBA/Conversion/CBool), [**CByte**](/en/official/Reference/VBA/Conversion/CByte), [**CCur**](/en/official/Reference/VBA/Conversion/CCur), [**CDate**](/en/official/Reference/VBA/Conversion/CDate), [**CDbl**](/en/official/Reference/VBA/Conversion/CDbl), [**CDec**](/en/official/Reference/VBA/Conversion/CDec), [**CInt**](/en/official/Reference/VBA/Conversion/CInt), [**CLng**](/en/official/Reference/VBA/Conversion/CLng), [**CLngLng**](/en/official/Reference/VBA/Conversion/CLngLng), [**CLngPtr**](/en/official/Reference/VBA/Conversion/CLngPtr), [**CSng**](/en/official/Reference/VBA/Conversion/CSng), [**CStr**](/en/official/Reference/VBA/Conversion/CStr), and [**CVar**](/en/official/Reference/VBA/Conversion/CVar). Beyond their narrowing or widening behaviour, the C-prefix functions are *locale-aware* --- they honour the current decimal separator and short date format --- which makes them the right choice for parsing values that originated as user input. They also serve as documentation: writing `CLng(x)` makes the intended type of an intermediate result explicit even where the surrounding context would coerce *x* implicitly. ```vb Dim Amount As Currency Amount = CCur("1,234.56") ' parses with the local decimal separator ``` Two further constructors return a **Variant** whose subtype is fixed: [**CVDate**](/en/official/Reference/VBA/Conversion/CVDate) builds a **Variant** of subtype **Date** (kept for compatibility with code written before **Date** became an intrinsic type), and [**CVErr**](/en/official/Reference/VBA/Conversion/CVErr) builds a **Variant** of subtype **Error** containing a chosen error number --- the canonical way for a **Variant**-returning function to signal "this call failed with this error code" without raising a run-time error. ## Generic conversion [**CType**](/en/official/Reference/VBA/Conversion/CType) is a twinBASIC extension that takes its target type as a generic parameter, written `CType(Of `*type*`)(`*value*`)`. It plays the same role as the C-prefix functions but for any type known to the compiler, which makes it the standard cast for **Enum** values, interfaces, and user-defined types where no fixed-name function exists. **CType** doubles as a pointer-to-UDT cast --- see [Enhanced Pointer Functionality](/en/official/Features/Language/Pointers#ctypeof-type). ```vb Dim day As VbDayOfWeek day = CType(Of VbDayOfWeek)(1) ``` ## Truncating to an integer [**Int**](/en/official/Reference/VBA/Conversion/Int) and [**Fix**](/en/official/Reference/VBA/Conversion/Fix) both discard the fractional part of a number, but they round in opposite directions for negative input. **Int** rounds toward negative infinity, so `Int(-8.4)` is `-9`; **Fix** truncates toward zero, so `Fix(-8.4)` is `-8`. For positive values the two coincide. Neither changes the data type of its argument, in contrast to [**CInt**](/en/official/Reference/VBA/Conversion/CInt) and [**CLng**](/en/official/Reference/VBA/Conversion/CLng), which both round and narrow to a specific integer type. ```vb Debug.Print Int(-8.4) ' -9 Debug.Print Fix(-8.4) ' -8 ``` ## Numbers, strings, and bases [**Str**](/en/official/Reference/VBA/Conversion/Str), [**Hex**](/en/official/Reference/VBA/Conversion/Hex), and [**Oct**](/en/official/Reference/VBA/Conversion/Oct) all return a printable string representation of a number --- **Str** in decimal, **Hex** in base 16, and **Oct** in base 8. Going the other way, [**Val**](/en/official/Reference/VBA/Conversion/Val) and [**ValDec**](/en/official/Reference/VBA/Conversion/ValDec) parse leading digits out of a string, returning a **Double** or **Decimal** respectively; both stop at the first unrecognised character and both honour the `&H` and `&O` radix prefixes for hexadecimal and octal literals. These five functions are *culture-invariant* --- they always use the period (`.`) as the decimal separator and never read or write a thousands separator --- which makes them appropriate for round-tripping through a fixed file format or wire protocol. For locale-aware conversion to and from text, use [**CStr**](/en/official/Reference/VBA/Conversion/CStr) and [**CDbl**](/en/official/Reference/VBA/Conversion/CDbl) (or [**CDec**](/en/official/Reference/VBA/Conversion/CDec)) instead. ```vb Debug.Print Hex(255) ' "FF" Debug.Print Oct(8) ' "10" Debug.Print Val("&HFF") ' 255 ``` ## Working with Null and error values [**Nz**](/en/official/Reference/VBA/Conversion/Nz) returns a substitute value when its argument is **Null**, leaving any other value unchanged. It is most useful for reading nullable columns from a database recordset, where directly concatenating or arithmetically combining the field with another value would otherwise propagate **Null** through the rest of the expression. [**Error**](/en/official/Reference/VBA/Conversion/Error) returns the descriptive text associated with an error number --- the same text that would appear as the **Description** of an [**ErrObject**](/en/official/Reference/VBA/ErrObject/) raised with that number. It is the function counterpart to the same-named [**Error** statement](/en/official/Reference/Core/Error), which *raises* a run-time error rather than describing one. ## Macintosh compatibility [**MacID**](/en/official/Reference/VBA/Conversion/MacID) packs a four-character Macintosh resource type or application signature into a **Long** for use with [**Dir**](/en/official/Reference/VBA/FileSystem/Dir), [**Kill**](/en/official/Reference/VBA/FileSystem/Kill), **Shell**, or [**AppActivate**](/en/official/Reference/VBA/Interaction/AppActivate). twinBASIC currently targets Windows, where the value has no special meaning to those functions; **MacID** is provided for source compatibility with VBA code originally written for the classic Mac. ## Members * [CBool](/en/official/Reference/VBA/Conversion/CBool) -- converts an expression to a **Boolean** * [CByte](/en/official/Reference/VBA/Conversion/CByte) -- converts an expression to a **Byte** * [CCur](/en/official/Reference/VBA/Conversion/CCur) -- converts an expression to a **Currency** * [CDate](/en/official/Reference/VBA/Conversion/CDate) -- converts a date/time expression to a **Date** * [CDbl](/en/official/Reference/VBA/Conversion/CDbl) -- converts an expression to a **Double** * [CDec](/en/official/Reference/VBA/Conversion/CDec) -- converts an expression to a **Decimal** * [CInt](/en/official/Reference/VBA/Conversion/CInt) -- converts an expression to an **Integer** * [CLng](/en/official/Reference/VBA/Conversion/CLng) -- converts an expression to a **Long** * [CLngLng](/en/official/Reference/VBA/Conversion/CLngLng) -- converts an expression to a **LongLong** * [CLngPtr](/en/official/Reference/VBA/Conversion/CLngPtr) -- converts an expression to a **LongPtr** * [CSng](/en/official/Reference/VBA/Conversion/CSng) -- converts an expression to a **Single** * [CStr](/en/official/Reference/VBA/Conversion/CStr) -- converts an expression to a **String** * [CType](/en/official/Reference/VBA/Conversion/CType) -- generic type conversion supporting the **CType(Of *type*)** cast operator * [CVar](/en/official/Reference/VBA/Conversion/CVar) -- converts an expression to a **Variant** * [CVDate](/en/official/Reference/VBA/Conversion/CVDate) -- converts a date/time expression to a **Variant** of subtype **Date** * [CVErr](/en/official/Reference/VBA/Conversion/CVErr) -- converts a numeric expression to a **Variant** of subtype **Error** * [Error](/en/official/Reference/VBA/Conversion/Error) -- returns the error message that corresponds to a given error number * [Fix](/en/official/Reference/VBA/Conversion/Fix) -- returns the integer portion of a number, truncating toward zero * [Hex](/en/official/Reference/VBA/Conversion/Hex) -- returns the hexadecimal representation of a number as a string * [Int](/en/official/Reference/VBA/Conversion/Int) -- returns the integer portion of a number, rounding toward negative infinity * [MacID](/en/official/Reference/VBA/Conversion/MacID) -- on the Macintosh, converts a 4-character constant to a value usable by **Dir**, **Kill**, **Shell**, or **AppActivate** * [Nz](/en/official/Reference/VBA/Conversion/Nz) -- replaces a **Null** value with a specified replacement value * [Oct](/en/official/Reference/VBA/Conversion/Oct) -- returns the octal representation of a number as a string * [Str](/en/official/Reference/VBA/Conversion/Str) -- returns the string representation of a number * [Val](/en/official/Reference/VBA/Conversion/Val) -- parses a string into a **Double** * [ValDec](/en/official/Reference/VBA/Conversion/ValDec) -- parses a string into a **Decimal** --- --- url: /en/official/Reference/VBA/HiddenModule/ConvertIconToBitmap.md --- # ConvertIconToBitmap Converts an icon picture into a bitmap picture. Syntax: **ConvertIconToBitmap(** *IconPicture* \[ **,** *BackColor* ] **)** **As Object** *IconPicture* : *required* **Object**. An **stdole.StdPicture** holding an icon (`vbPicTypeIcon`) or cursor (`vbPicTypeIcon`). *BackColor* : *optional* **Variant**. The background colour to flatten transparent pixels onto, given as an OLE colour value. If omitted, the system **Window** colour is used. The returned picture is a fresh bitmap-typed **stdole.StdPicture** with the icon rasterised on top of the chosen background. The original icon picture is unchanged. ### Example ```vb Dim Bmp As StdPicture Set Bmp = ConvertIconToBitmap(MyIconPicture, RGB(255, 255, 255)) Set Picture1.Picture = Bmp ``` ### See Also * [CreateStdPictureFromHandle](/en/official/Reference/VBA/HiddenModule/CreateStdPictureFromHandle) function * [PictureToByteArray](/en/official/Reference/VBA/HiddenModule/PictureToByteArray) function --- --- url: /zh/official/Reference/VBA/HiddenModule/ConvertIconToBitmap.md --- # ConvertIconToBitmap 将图标图片转换为位图图片。 语法:**ConvertIconToBitmap(** *IconPicture* \[ **,** *BackColor* ] **)** **As Object** *IconPicture* : *必需* **Object**。一个持有图标(`vbPicTypeIcon`)或光标(`vbPicTypeIcon`)的**stdole.StdPicture**。 *BackColor* : *可选* **Variant**。将透明像素展平到的背景颜色,以OLE颜色值给出。如果省略,则使用系统**Window**颜色。 返回的图片是一个全新的位图类型**stdole.StdPicture**,图标栅格化在所选背景之上。原始图标图片保持不变。 ### 示例 ```vb Dim Bmp As StdPicture Set Bmp = ConvertIconToBitmap(MyIconPicture, RGB(255, 255, 255)) Set Picture1.Picture = Bmp ``` ### 另请参阅 * [CreateStdPictureFromHandle](/official/Reference/VBA/HiddenModule/CreateStdPictureFromHandle)函数 * [PictureToByteArray](/official/Reference/VBA/HiddenModule/PictureToByteArray)函数 --- --- url: /en/packages/vbccr/bars/coolbar.md description: >- CoolBar Control - VBCCR Developer Reference, complete API documentation based on source code --- # CoolBar Control Wraps the ReBar system control, providing a draggable, resizable band container bar. ## Enumerations ### CbrOrientationConstants | Constant | Value | Description | |----------|-------|-------------| | CbrOrientationHorizontal | 0 | Horizontal orientation | | CbrOrientationVertical | 1 | Vertical orientation | ### CbrBandStyleConstants | Constant | Value | Description | |----------|-------|-------------| | CbrBandStyleNormal | 0 | Normal style, resizable | | CbrBandStyleFixedSize | 1 | Fixed size | ### CbrBandGripperConstants | Constant | Value | Description | |----------|-------|-------------| | CbrBandGripperNormal | 0 | Default gripper | | CbrBandGripperAlways | 1 | Always show gripper | | CbrBandGripperNever | 2 | Never show gripper | ### CbrHitResultConstants | Constant | Value | Description | |----------|-------|-------------| | CbrHitResultNoWhere | 0 | Empty area | | CbrHitResultCaption | 1 | Caption area | | CbrHitResultClient | 2 | Client area | | CbrHitResultGrabber | 3 | Gripper bar | | CbrHitResultChevron | 4 | Chevron arrow | | CbrHitResultSplitter | 5 | Splitter bar | ## Properties ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` Whether visual styles are enabled. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE drag-and-drop mode. See common enumerations. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` Mouse pointer. See common enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` Custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Mouse enter/leave tracking. ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` Right-to-left display. ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` Right-to-left mirrored layout. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` Right-to-left mode. See common enumerations. ### ImageList ```vb Property Get ImageList() As Variant Property Let ImageList(ByVal Value As Variant) Property Set ImageList(ByVal Value As Variant) ``` Associated ImageList control. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` Foreground color. ### BorderStyle ```vb Property Get BorderStyle() As Integer Property Let BorderStyle(ByVal Value As Integer) ``` Border style (0 - no border, 1 - fixed single). ### Orientation ```vb Property Get Orientation() As CbrOrientationConstants Property Let Orientation(ByVal Value As CbrOrientationConstants) ``` Orientation. ### BandBorders ```vb Property Get BandBorders() As Boolean Property Let BandBorders(ByVal Value As Boolean) ``` Whether separator lines are displayed between bands. ### FixedOrder ```vb Property Get FixedOrder() As Boolean Property Let FixedOrder(ByVal Value As Boolean) ``` Whether the user is prevented from reordering bands. ### VariantHeight ```vb Property Get VariantHeight() As Boolean Property Let VariantHeight(ByVal Value As Boolean) ``` Whether bands are allowed to have different heights. ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` Background picture. ### DblClickToggle ```vb Property Get DblClickToggle() As Boolean Property Let DblClickToggle(ByVal Value As Boolean) ``` Whether double-click toggles maximize/minimize. ### VerticalGripper ```vb Property Get VerticalGripper() As Boolean Property Let VerticalGripper(ByVal Value As Boolean) ``` Whether a vertical gripper is used in vertical orientation. ### ShowTips ```vb Property Get ShowTips() As Boolean Property Let ShowTips(ByVal Value As Boolean) ``` Whether tooltips are displayed. ### DoubleBuffer ```vb Property Get DoubleBuffer() As Boolean Property Let DoubleBuffer(ByVal Value As Boolean) ``` Whether double buffering is enabled to reduce flicker. ### Bands ```vb Property Get Bands() As CbrBands ``` Bands collection. ### ContainedControls ```vb Property Get ContainedControls() As VBRUN.ContainedControls ``` Contained controls collection. Read-only. ### RowCount ```vb Property Get RowCount() As Long ``` Row count. Read-only. ### hWnd / hWndUserControl / Font See common properties. ### Name / Tag / Parent / Container / Left / Top / Width / Height / Visible / ToolTipText / WhatsThisHelpID / Align / DragIcon / DragMode See standard extender properties. ## Methods ### Refresh ```vb Public Sub Refresh() ``` Forces a redraw. ### HitTest ```vb Public Function HitTest(ByVal X As Single, ByVal Y As Single, Optional ByRef HitResult As CbrHitResultConstants) As CbrBand ``` Hit test; returns the band object at the specified coordinates. ### OLEDrag ```vb Public Sub OLEDrag() ``` ### Drag / ZOrder See standard methods. ## Events ### Click ```vb Public Event Click() ``` Click. ### DblClick ```vb Public Event DblClick() ``` Double-click. ### Resize ```vb Public Event Resize() ``` Size changed. ### HeightChanged ```vb Public Event HeightChanged(ByVal NewHeight As Single) ``` Height changed. ### LayoutChanged ```vb Public Event LayoutChanged() ``` Layout changed. ### MinMax ```vb Public Event MinMax(ByRef Cancel As Boolean) ``` A band is about to be maximized or minimized; can be canceled. ### BandBeforeDrag ```vb Public Event BandBeforeDrag(ByVal Band As CbrBand, ByRef Cancel As Boolean) ``` A band is about to be dragged; can be canceled. ### BandAfterDrag ```vb Public Event BandAfterDrag(ByVal Band As CbrBand, ByVal NewPosition As Long) ``` Band drag completed. ### BandChevronPushed ```vb Public Event BandChevronPushed(ByVal Band As CbrBand, ByVal Left As Single, ByVal Top As Single, ByVal Width As Single, ByVal Height As Single) ``` Chevron arrow clicked. ### BandMouseEnter ```vb Public Event BandMouseEnter(ByVal Band As CbrBand) ``` Mouse entered a band. ### BandMouseLeave ```vb Public Event BandMouseLeave(ByVal Band As CbrBand) ``` Mouse left a band. ### MouseDown / MouseMove / MouseUp / MouseEnter / MouseLeave ### OLECompleteDrag / OLEDragDrop / OLEDragOver / OLEGiveFeedback / OLESetData / OLEStartDrag ## CbrBand Object Band properties and methods. ### Properties #### Index ```vb Property Get Index() As Long ``` Band index in the collection. Read-only. #### Key ```vb Property Get Key() As String Property Let Key(ByVal Value As String) ``` Band key. #### Tag ```vb Property Get Tag() As Variant Property Let Tag(ByVal Value As Variant) Property Set Tag(ByVal Value As Variant) ``` Custom data. #### ID ```vb Property Get ID() As Long ``` Internal identifier. Read-only. #### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` Band caption. #### Child ```vb Property Get Child() As Object Property Let Child(ByVal Value As Object) Property Set Child(ByVal Value As Object) ``` Child control contained in the band. #### Style ```vb Property Get Style() As CbrBandStyleConstants Property Let Style(ByVal Value As CbrBandStyleConstants) ``` Band style. #### Image ```vb Property Get Image() As Variant Property Let Image(ByVal Value As Variant) ``` Image index or key in the ImageList. #### ImageIndex ```vb Property Get ImageIndex() As Long ``` Image index. Read-only. #### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` Band width. Read-only when Style is FixedSize. #### Height ```vb Property Get Height() As Single ``` Band height. Read-only. #### MinWidth ```vb Property Get MinWidth() As Single Property Let MinWidth(ByVal Value As Single) ``` Minimum width. #### MinHeight ```vb Property Get MinHeight() As Single Property Let MinHeight(ByVal Value As Single) ``` Minimum height. #### IdealWidth ```vb Property Get IdealWidth() As Single Property Let IdealWidth(ByVal Value As Single) ``` Ideal width. #### Gripper ```vb Property Get Gripper() As CbrBandGripperConstants Property Let Gripper(ByVal Value As CbrBandGripperConstants) ``` Gripper style. #### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` ToolTip text. Requires ShowTips to be True. #### UseCoolBarPicture ```vb Property Get UseCoolBarPicture() As Boolean Property Let UseCoolBarPicture(ByVal Value As Boolean) ``` Whether the CoolBar's background picture is used. #### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` Band background picture. #### UseCoolBarColors ```vb Property Get UseCoolBarColors() As Boolean Property Let UseCoolBarColors(ByVal Value As Boolean) ``` Whether the CoolBar's foreground/background colors are used. #### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Band background color. #### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` Band foreground color. #### NewRow ```vb Property Get NewRow() As Boolean Property Let NewRow(ByVal Value As Boolean) ``` Whether the band starts on a new row. #### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` Whether visible. #### ChildEdge ```vb Property Get ChildEdge() As Boolean Property Let ChildEdge(ByVal Value As Boolean) ``` Whether an edge is displayed around the child control. #### UseChevron ```vb Property Get UseChevron() As Boolean Property Let UseChevron(ByVal Value As Boolean) ``` Whether a chevron arrow is displayed when the band width is less than the ideal width. #### HideCaption ```vb Property Get HideCaption() As Boolean Property Let HideCaption(ByVal Value As Boolean) ``` Whether the caption is hidden. #### FixedBackground ```vb Property Get FixedBackground() As Boolean Property Let FixedBackground(ByVal Value As Boolean) ``` Whether the background picture is fixed in place. #### Position ```vb Property Get Position() As Long Property Let Position(ByVal Value As Long) ``` Band position. ### Methods #### Maximize ```vb Public Sub Maximize() ``` Maximizes the band. #### Minimize ```vb Public Sub Minimize() ``` Minimizes the band. #### PushChevron ```vb Public Sub PushChevron() ``` Programmatically clicks the chevron arrow. ## CbrBands Collection Bands collection object. ### Properties #### Item ```vb Property Get Item(ByVal Index As Variant) As CbrBand ``` Gets a band by index or key. #### ItemFromPosition ```vb Property Get ItemFromPosition(ByVal Position As Long) As CbrBand ``` Gets a band by position. #### Count ```vb Property Get Count() As Long ``` Band count. ### Methods #### Add ```vb Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Caption As String, Optional ByVal Image As Variant, Optional ByVal NewRow As Boolean, Optional ByVal Child As Variant, Optional ByVal Visible As Boolean = True) As CbrBand ``` Adds a new band. #### Remove ```vb Public Sub Remove(ByVal Index As Variant) ``` Removes a band. #### Clear ```vb Public Sub Clear() ``` Clears all bands. #### Exists ```vb Public Function Exists(ByVal Index As Variant) As Boolean ``` Checks if a band exists. ## CbrBandProperties Object Auxiliary object for band color properties. ### Properties #### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. #### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` Foreground color. ## Code Examples ### Basic Usage ```vb ' Add bands With CoolBar1.Bands .Add Key:="Band1", Caption:="Toolbar", NewRow:=True .Add Key:="Band2", Caption:="Format Bar" End With ' Set child control Set CoolBar1.Bands("Band1").Child = Toolbar1 ' Set band properties CoolBar1.Bands(1).UseChevron = True CoolBar1.Bands(1).IdealWidth = 500 ``` ### Hit Test ```vb Private Sub CoolBar1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) Dim HitResult As CbrHitResultConstants Dim Band As CbrBand Set Band = CoolBar1.HitTest(X, Y, HitResult) If Not Band Is Nothing Then Debug.Print "Clicked: " & Band.Caption End If End Sub ``` ### Chevron Event ```vb Private Sub CoolBar1_BandChevronPushed(ByVal Band As CbrBand, _ ByVal Left As Single, ByVal Top As Single, _ ByVal Width As Single, ByVal Height As Single) ' Display menu at chevron position PopupMenu mnuToolbar, , Left, Top + Height End Sub ``` --- --- url: /en/official/Reference/WebView2/Types/COREWEBVIEW2_PHYSICAL_KEY_STATUS.md --- # COREWEBVIEW2\_PHYSICAL\_KEY\_STATUS The bit-fields the Win32 `WM_KEYDOWN` / `WM_KEYUP` message family packs into its `lParam`, decoded into a record. The control reads the runtime's `COREWEBVIEW2_PHYSICAL_KEY_STATUS` structure on each accelerator keystroke and distributes it across individual arguments of the [**AcceleratorKeyPressed**](/en/official/Reference/WebView2/WebView2/#acceleratorkeypressed) event --- application code does not normally create instances of this type directly. ```vb Public Type COREWEBVIEW2_PHYSICAL_KEY_STATUS RepeatCount As Long ScanCode As Long IsExtendedKey As Long IsMenuKeyDown As Long WasKeyDown As Long IsKeyReleased As Long End Type ``` ## Members *RepeatCount* : How many times the keystroke is auto-repeated as the message is held in the queue. *ScanCode* : The hardware scan code of the pressed key. *IsExtendedKey* : Non-zero when the key is one of the *extended* keys --- right-hand **Alt** / **Ctrl**, the arrow / **Home** / **End** / **Page Up** / **Page Down** / **Insert** / **Delete** block, **NumLock**, and the numeric-keypad **Enter** and **/**. *IsMenuKeyDown* : Non-zero when **Alt** was held while the message was generated. *WasKeyDown* : Non-zero when the key was already down before this message --- distinguishes the initial keystroke from subsequent auto-repeats. *IsKeyReleased* : Non-zero on the transition message reporting the key going up; zero on key-down messages. ### See Also * [AcceleratorKeyPressed](/en/official/Reference/WebView2/WebView2/#acceleratorkeypressed) * [wv2KeyEventKind](/en/official/Reference/WebView2/Enumerations/wv2KeyEventKind) --- --- url: /zh/official/Reference/WebView2/Types/COREWEBVIEW2_PHYSICAL_KEY_STATUS.md --- # COREWEBVIEW2\_PHYSICAL\_KEY\_STATUS Win32 `WM_KEYDOWN` / `WM_KEYUP` 消息族打包到其 `lParam` 中的位字段,解码为记录。控件在每次快捷键击键时读取运行时的 `COREWEBVIEW2_PHYSICAL_KEY_STATUS` 结构,并将其分发到 [**AcceleratorKeyPressed**](/official/Reference/WebView2/WebView2/#acceleratorkeypressed) 事件的各个参数——应用程序代码通常不直接创建此类型的实例。 ```vb Public Type COREWEBVIEW2_PHYSICAL_KEY_STATUS RepeatCount As Long ScanCode As Long IsExtendedKey As Long IsMenuKeyDown As Long WasKeyDown As Long IsKeyReleased As Long End Type ``` ## 成员 *RepeatCount* : 击键在消息保持在队列中时自动重复的次数。 *ScanCode* : 所按键的硬件扫描码。 *IsExtendedKey* : 当键是*扩展*键时非零——右侧 **Alt** / **Ctrl**、方向键 / **Home** / **End** / **Page Up** / **Page Down** / **Insert** / **Delete** 区、**NumLock**,以及数字小键盘的 **Enter** 和 **/**。 *IsMenuKeyDown* : 生成消息时 **Alt** 被按住时非零。 *WasKeyDown* : 在此消息之前键已经按下时非零——区分初次击键和后续自动重复。 *IsKeyReleased* : 在报告键抬起的转换消息上非零;在键按下消息上为零。 ### 另见 * [AcceleratorKeyPressed](/official/Reference/WebView2/WebView2/#acceleratorkeypressed) * [wv2KeyEventKind](/official/Reference/WebView2/Enumerations/wv2KeyEventKind) --- --- url: /en/official/Reference/CustomControls/Styles/Corners.md --- # Corners class The four corners of a rendered region. Each corner is an independent [**Corner**](#corner-class) sub-object --- the shape and radius can vary corner by corner --- letting a control round one corner while notching another. Accessed as `<state>.Corners`, [**CellRenderingOptions.Corners**](/en/official/Reference/CustomControls/WaynesGrid/CellRenderingOptions#corners), and the slider's `<sliderState>.BackgroundCorners` / `BlockCorners`. ```vb With btnGo.NormalState.Corners .SetAll tbCurve, 12 ' all four corners 12px rounded .TopRight.Shape = tbNotched End With ``` The three [**CornerShape**](/en/official/Reference/CustomControls/Enumerations/CornerShape) values can mix on a single control. Setting [**TopLeft**](#topleft), [**TopRight**](#topright), [**BottomLeft**](#bottomleft), and [**BottomRight**](#bottomright) individually gives full control over the silhouette: ```vb With btnTab.NormalState.Corners .TopLeft.Shape = tbCurve : .TopLeft.Radius = 12 .TopRight.Shape = tbCurve : .TopRight.Radius = 12 .BottomLeft.Shape = tbNotched : .BottomLeft.Radius = 0 .BottomRight.Shape = tbNotched : .BottomRight.Radius = 0 End With ``` A circular control is just a square one with all four corners set to [**tbCurve**](/en/official/Reference/CustomControls/Enumerations/CornerShape#tbCurve) and a radius greater than or equal to half the control's smaller dimension --- that is what the `Circle` button in the package's sample forms uses. ## Properties ### BottomLeft The [**Corner**](#corner-class) sub-object that controls the bottom-left corner. ### BottomRight The [**Corner**](#corner-class) sub-object that controls the bottom-right corner. ### TopLeft The [**Corner**](#corner-class) sub-object that controls the top-left corner. ### TopRight The [**Corner**](#corner-class) sub-object that controls the top-right corner. ## Methods ### SetAll Sets all four corners to the same shape and radius in a single call. Equivalent to assigning the same values to each of [**TopLeft**](#topleft), [**TopRight**](#topright), [**BottomLeft**](#bottomleft), and [**BottomRight**](#bottomright). Syntax: *object*.**SetAll** *Shape*, *Radius* *Shape* : *required* A member of [**CornerShape**](/en/official/Reference/CustomControls/Enumerations/CornerShape). *Radius* : *required* A [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount) giving the curve / notch / cut-out radius. ## Events ### OnChanged Raised whenever any of the four corner sub-objects changes --- either through a direct property set on the **Corners** object or through a propagated **OnChanged** from one of the **Corner** sub-objects. ## Corner class A single corner of a [**Corners**](#) object. Has a [**Shape**](#shape) (curve, notch, or cut-out) and a [**Radius**](#radius) (in pixels). ### Radius The corner's radius in pixels. The interpretation depends on [**Shape**](#shape): for **tbCurve** it is the radius of the quarter-circle, for **tbNotched** the cut depth, and for **tbCutOut** the depth of the carved-out region. [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount). Default: 0 (a sharp 90° corner regardless of **Shape**). ### Shape How the corner is drawn. A member of [**CornerShape**](/en/official/Reference/CustomControls/Enumerations/CornerShape): **tbCurve** (default), **tbNotched**, or **tbCutOut**. ### OnChanged Raised when either [**Shape**](#shape) or [**Radius**](#radius) is assigned. The parent [**Corners**](#) listens for this event and re-raises its own. --- --- url: /zh/official/Reference/CustomControls/Styles/Corners.md --- # Corners 类 渲染区域的四个角。每个角是独立的 [**Corner**](#corner-class) 子对象——形状和半径可以逐角不同——使控件可以圆化一个角同时凹口另一个角。通过 `<state>.Corners`、[**CellRenderingOptions.Corners**](/official/Reference/CustomControls/WaynesGrid/CellRenderingOptions#corners) 以及滑块的 `<sliderState>.BackgroundCorners` / `BlockCorners` 访问。 ```vb With btnGo.NormalState.Corners .SetAll tbCurve, 12 ' all four corners 12px rounded .TopRight.Shape = tbNotched End With ``` 三个 [**CornerShape**](/official/Reference/CustomControls/Enumerations/CornerShape) 值可以在单个控件上混合使用。单独设置 [**TopLeft**](#topleft)、[**TopRight**](#topright)、[**BottomLeft**](#bottomleft) 和 [**BottomRight**](#bottomright) 可完全控制轮廓: ```vb With btnTab.NormalState.Corners .TopLeft.Shape = tbCurve : .TopLeft.Radius = 12 .TopRight.Shape = tbCurve : .TopRight.Radius = 12 .BottomLeft.Shape = tbNotched : .BottomLeft.Radius = 0 .BottomRight.Shape = tbNotched : .BottomRight.Radius = 0 End With ``` 圆形控件就是将所有四个角设为 [**tbCurve**](/official/Reference/CustomControls/Enumerations/CornerShape#tbCurve) 且半径大于等于控件较小维度一半的方形控件——包示例窗体中的 `Circle` 按钮正是如此。 ## 属性 ### BottomLeft 控制左下角的 [**Corner**](#corner-class) 子对象。 ### BottomRight 控制右下角的 [**Corner**](#corner-class) 子对象。 ### TopLeft 控制左上角的 [**Corner**](#corner-class) 子对象。 ### TopRight 控制右上角的 [**Corner**](#corner-class) 子对象。 ## 方法 ### SetAll 在单次调用中将所有四个角设为相同的形状和半径。等同于为 [**TopLeft**](#topleft)、[**TopRight**](#topright)、[**BottomLeft**](#bottomleft) 和 [**BottomRight**](#bottomright) 各赋相同的值。 语法:*object*.**SetAll** *Shape*, *Radius* *Shape* : *必需* [**CornerShape**](/official/Reference/CustomControls/Enumerations/CornerShape) 的成员。 *Radius* : *必需* [**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount),给出曲线/凹口/切角的半径。 ## 事件 ### OnChanged 四个角子对象中任一个更改时触发——无论是通过 **Corners** 对象上的直接属性设置还是通过 **Corner** 子对象传播的 **OnChanged**。 ## Corner 类 [**Corners**](#) 对象的单个角。具有 [**Shape**](#shape)(曲线、凹口或切角)和 [**Radius**](#radius)(像素)。 ### Radius 角的半径(像素)。含义取决于 [**Shape**](#shape):对于 **tbCurve** 是四分之一圆的半径,对于 **tbNotched** 是切割深度,对于 **tbCutOut** 是挖空区域的深度。[**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount)。默认:0(无论 **Shape** 如何都是直角 90° 角)。 ### Shape 角的绘制方式。[**CornerShape**](/official/Reference/CustomControls/Enumerations/CornerShape) 的成员:**tbCurve**(默认)、**tbNotched** 或 **tbCutOut**。 ### OnChanged [**Shape**](#shape) 或 [**Radius**](#radius) 被赋值时触发。父 [**Corners**](#) 监听此事件并重新触发自身的。 --- --- url: /en/official/Reference/CustomControls/Enumerations/CornerShape.md --- # CornerShape Determines how a single corner of a control is shaped. Used by [**Corner.Shape**](/en/official/Reference/CustomControls/Styles/Corners#shape), which is set independently for each of the four corners of any control that exposes a [**Corners**](/en/official/Reference/CustomControls/Styles/Corners) style object. The numeric value of the radius is supplied separately by [**Corner.Radius**](/en/official/Reference/CustomControls/Styles/Corners#radius). | Constant | Value | Description | |----------|-------|-------------| | **tbCurve** | 0 | Quarter-circle round corner; the radius gives the curve. | | **tbNotched** | 1 | Diagonal notch across the corner; the radius gives the cut depth. | | **tbCutOut** | 2 | Inverse round-corner --- the corner area is carved *out* of the control. | [**Corners.SetAll**](/en/official/Reference/CustomControls/Styles/Corners#setall) applies one shape to every corner at once; setting [**TopLeft**](/en/official/Reference/CustomControls/Styles/Corners#topleft) / [**TopRight**](/en/official/Reference/CustomControls/Styles/Corners#topright) / [**BottomLeft**](/en/official/Reference/CustomControls/Styles/Corners#bottomleft) / [**BottomRight**](/en/official/Reference/CustomControls/Styles/Corners#bottomright) individually lets the shapes mix: ```vb With btnDemo.NormalState.Corners .TopLeft.Shape = tbCurve : .TopLeft.Radius = 16 ' rounded .TopRight.Shape = tbNotched : .TopRight.Radius = 16 ' diagonal cut .BottomLeft.Shape = tbCutOut : .BottomLeft.Radius = 16 ' carved-out .BottomRight.Shape = tbCurve : .BottomRight.Radius = 0 ' sharp 90° End With ``` A [**Radius**](/en/official/Reference/CustomControls/Styles/Corners#radius) of 0 produces a sharp 90° corner regardless of [**Shape**](/en/official/Reference/CustomControls/Styles/Corners#shape); a radius greater than or equal to half the control's smaller dimension turns a [**tbCurve**](#tbCurve) corner into a quarter-circle that touches the centreline, which is the technique the package's `Circle` sample button uses to render a full circle from a rectangular control. --- --- url: /zh/official/Reference/CustomControls/Enumerations/CornerShape.md --- # CornerShape 决定控件单个角的形状。由 [**Corner.Shape**](/official/Reference/CustomControls/Styles/Corners#shape) 使用,对暴露 [**Corners**](/official/Reference/CustomControls/Styles/Corners) 样式对象的任何控件的四个角独立设置。半径数值由 [**Corner.Radius**](/official/Reference/CustomControls/Styles/Corners#radius) 单独提供。 | 常量 | 值 | 说明 | |------|----|------| | **tbCurve** | 0 | 四分之一圆圆角;半径给出曲线。 | | **tbNotched** | 1 | 对角凹口;半径给出切割深度。 | | **tbCutOut** | 2 | 反向圆角——角区域从控件中*挖空*。 | [**Corners.SetAll**](/official/Reference/CustomControls/Styles/Corners#setall) 一次性将一种形状应用到每个角;单独设置 [**TopLeft**](/official/Reference/CustomControls/Styles/Corners#topleft) / [**TopRight**](/official/Reference/CustomControls/Styles/Corners#topright) / [**BottomLeft**](/official/Reference/CustomControls/Styles/Corners#bottomleft) / [**BottomRight**](/official/Reference/CustomControls/Styles/Corners#bottomright) 可以混合形状: ```vb With btnDemo.NormalState.Corners .TopLeft.Shape = tbCurve : .TopLeft.Radius = 16 ' rounded .TopRight.Shape = tbNotched : .TopRight.Radius = 16 ' diagonal cut .BottomLeft.Shape = tbCutOut : .BottomLeft.Radius = 16 ' carved-out .BottomRight.Shape = tbCurve : .BottomRight.Radius = 0 ' sharp 90° End With ``` [**Radius**](/official/Reference/CustomControls/Styles/Corners#radius) 为 0 时无论 [**Shape**](/official/Reference/CustomControls/Styles/Corners#shape) 如何都产生直角 90° 角;半径大于等于控件较小维度的一半时 [**tbCurve**](#tbCurve) 角变成触及中线的四分之一圆,这是包的 `Circle` 示例按钮将矩形控件渲染为完整圆形的技术。 --- --- url: /en/official/Reference/VBA/Math/Cos.md --- # Cos Returns a **Double** specifying the cosine of an angle. Syntax: **Cos(** *number* **)** *number* : *required* A **Double** or any valid numeric expression that expresses an angle in radians. The **Cos** function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse. The result lies in the range -1 to 1. To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi. ### Example This example uses the **Cos** function to return the cosine of an angle. ```vb Dim MyAngle, MySecant MyAngle = 1.3 ' Define angle in radians. MySecant = 1 / Cos(MyAngle) ' Calculate secant. ``` ### See Also * [Atn](/en/official/Reference/VBA/Math/Atn), [Sin](/en/official/Reference/VBA/Math/Sin), [Tan](/en/official/Reference/VBA/Math/Tan) functions --- --- url: /zh/official/Reference/VBA/Math/Cos.md --- # Cos 返回一个 **Double**,指定角度的余弦值。 语法:**Cos(** *number* **)** *number* : *必需* **Double** 或任何表示弧度角的有效数值表达式。 **Cos** 函数取一个角度,返回直角三角形两边的比值。该比值是邻边长度除以斜边长度。结果范围为 -1 到 1。 要将角度转换为弧度,将角度乘以 pi/180。要将弧度转换为角度,将弧度乘以 180/pi。 ### 示例 此示例使用 **Cos** 函数返回角度的余弦值。 ```vb Dim MyAngle, MySecant MyAngle = 1.3 ' Define angle in radians. MySecant = 1 / Cos(MyAngle) ' Calculate secant. ``` ### 另请参阅 * [Atn](/official/Reference/VBA/Math/Atn)、[Sin](/official/Reference/VBA/Math/Sin)、[Tan](/official/Reference/VBA/Math/Tan) 函数 --- --- url: /en/official/Reference/VBA/Collection/Count.md --- # Count Returns a **Long** containing the number of items in a **Collection** object. Read-only. Syntax: *object*.**Count** *object* : *required* An object expression that evaluates to a **Collection** object. ### Example This example uses the **Collection** object's **Count** property to specify how many iterations are required to remove all the elements of the collection called `MyClasses`. Collection numeric indexes start at 1 by default. Because collections are reindexed automatically when a removal is made, the following code removes the first member on each iteration. ```vb Dim Num As Long, MyClasses As Collection Set MyClasses = New Collection ' ... assume MyClasses has been populated ... For Num = 1 To MyClasses.Count ' Default collection numeric indexes MyClasses.Remove 1 ' begin at 1. Next ``` ### See Also * [Add](/en/official/Reference/VBA/Collection/Add) method * [Item](/en/official/Reference/VBA/Collection/Item) method * [Remove](/en/official/Reference/VBA/Collection/Remove) method * [Clear](/en/official/Reference/VBA/Collection/Clear) method --- --- url: /zh/official/Reference/VBA/Collection/Count.md --- # Count 返回一个 **Long**,包含 **Collection** 对象中的项数。只读。 语法:*object*.**Count** *object* : *必需* 一个计算结果为 **Collection** 对象的对象表达式。 ### 示例 此示例使用 **Collection** 对象的 **Count** 属性来指定移除名为 `MyClasses` 的集合中所有元素所需的迭代次数。集合的数值索引默认从 1 开始。由于集合在移除元素后会自动重新索引,以下代码在每次迭代中移除第一个成员。 ```vb Dim Num As Long, MyClasses As Collection Set MyClasses = New Collection ' ... assume MyClasses has been populated ... For Num = 1 To MyClasses.Count ' Default collection numeric indexes MyClasses.Remove 1 ' begin at 1. Next ``` ### 另请参阅 * [Add](/official/Reference/VBA/Collection/Add) 方法 * [Item](/official/Reference/VBA/Collection/Item) 方法 * [Remove](/official/Reference/VBA/Collection/Remove) 方法 * [Clear](/official/Reference/VBA/Collection/Clear) 方法 --- --- url: /en/official/Challenges/create-a-game.md --- # 🎮 twinBASIC Monthly Challenge #2 - February **Create a Game** Build **any game you like** using twinBASIC. This can be a simple card game, arcade game, puzzle, or something more experimental. Creativity is encouraged - there is no "right" genre or style. ## 📦 Submission Rules * Built using twinBASIC * Full source code must be provided, but licence choice is unrestricted * Submission must be a *single* `.twinproj` file (external image and music resource files allowed if necessary) * Produces a **single Windows EXE** * Runs on **Windows 10 and later** * Game may be windowed or fullscreen * Music is optional * ❌ Not a direct or near-direct port of an existing VB6 game ## 🎵 Bonus Points * Inclusion of music or sound effects * Inclusion of controller support (e.g. XInput) * Use of **GDI+ package** ⁠[GDI+ Package](https://discord.com/channels/927638153546829845/1460777854714515728) * Use of **OpenGL** ⁠[twinBASIC + WinDevLib OpenGL De…](https://discord.com/channels/927638153546829845/1464785863702610053) * Clever or efficient rendering techniques * Use of newer twinBASIC features (e.g. delegates, generics) * Clean architecture and well-documented code * Polished UI, UX, or game feel * Interesting technical tricks (collision detection, AI, etc.) ## 🎁 Prize **£100 twinBASIC account credit** * Non-transferable * No cash alternative * Can only be used towards future twinBASIC licences ## 🏆 Judging Entries will be judged across multiple categories, including: * Originality and creativity * Technical execution * Performance * Visual presentation * Code quality and structure * Overall polish and fun factor Bonus points may be awarded at the discretion of the twinBASIC team. **Winner selected at the sole discretion of the twinBASIC team within 7 days after the entry deadline.** ## ⏰ Deadline Entries must be received by: 🗓️ 1st March --- 12:00 PM (GMT) Submissions will be locked after the deadline. 🔗: <https://discord.com/channels/927638153546829845/1467429513456783498> --- --- url: /en/official/Reference/VBA/HiddenModule/CreateGUID.md --- # CreateGUID Generates a fresh GUID and returns it as a registry-formatted string. Syntax: **CreateGUID()** **As String** The result is a fresh, unique GUID in the form `{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}` --- the same format used by **InterfaceId**, **ClassId**, and the like. Each call returns a different value. This is a thin wrapper over the operating system's GUID generator (`CoCreateGuid` on Windows). The resulting GUID is suitable for use as an interface or class identifier; it is not, however, a cryptographically random number --- do not use it where unpredictability matters. ### Example ```vb Debug.Print CreateGUID() ' {2A1B6F2C-4D9F-4D5E-9C8A-EE9C8B5F3DCE} ``` ### See Also * [vbaCastObj](/en/official/Reference/VBA/HiddenModule/vbaCastObj) function --- --- url: /zh/official/Reference/VBA/HiddenModule/CreateGUID.md --- # CreateGUID 生成一个新的GUID并以注册表格式字符串返回。 语法:**CreateGUID()** **As String** 结果是一个新的唯一GUID,格式为`{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}`——与**InterfaceId**、**ClassId**等使用的格式相同。每次调用返回不同的值。 这是对操作系统GUID生成器(Windows上的`CoCreateGuid`)的轻量封装。生成的GUID适合用作接口或类标识符;但它不是加密随机数——不要在需要不可预测性的场合使用。 ### 示例 ```vb Debug.Print CreateGUID() ' {2A1B6F2C-4D9F-4D5E-9C8A-EE9C8B5F3DCE} ``` ### 另请参阅 * [vbaCastObj](/official/Reference/VBA/HiddenModule/vbaCastObj)函数 --- --- url: /en/official/Reference/VBA/Interaction/CreateObject.md --- # CreateObject Creates and returns a reference to a new instance of a COM/Automation object. Syntax: **CreateObject(** *class* \[ **,** *servername* ] **)** *class* : *required* **Variant** (**String**). The application name and class of the object to create, in the form *appname*.*objecttype* --- for example, `"Excel.Application"`. A CLSID may also be supplied in the form `"new:{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"`. *servername* : *optional* **Variant** (**String**). The name of the network server on which to create the object --- the same as the *Machine Name* portion of a UNC share name. For a share named `\\MyServer\Public`, *servername* is `"MyServer"`. If *servername* is omitted or supplied as a zero-length string (`""`), the object is created on the local machine. To use the returned object, assign it to an object variable. Declaring the variable `As Object` causes late binding (binding occurs at run time); declaring it with a specific class type produces early binding (binding occurs at compile time), which is faster and gives access to IntelliSense for the object's members but limits the variable to that one type. ```vb Dim ExcelApp As Object Set ExcelApp = CreateObject("Excel.Application") ExcelApp.Visible = True ``` If a remote *servername* is supplied but the remote machine doesn't exist or is unreachable, a run-time error occurs. If an object has registered itself as single-instance, only one instance is ever created, no matter how many times **CreateObject** is invoked. ::: info **CreateObject** obtains a new instance of the object. [**GetObject**](/en/official/Reference/VBA/Interaction/GetObject) attaches to an *already-running* instance --- or starts the object's application with a particular file loaded. ::: ### Example This example creates a Microsoft Excel **Application** object, makes it visible, and then closes it via **Quit**, releasing the reference at the end. ```vb Dim XlApp As Object Set XlApp = CreateObject("Excel.Application") XlApp.Visible = True ' ... work with Excel through XlApp ... XlApp.Quit Set XlApp = Nothing ``` ### See Also * [GetObject](/en/official/Reference/VBA/Interaction/GetObject) function --- --- url: /zh/official/Reference/VBA/Interaction/CreateObject.md --- # CreateObject 创建并返回对COM/Automation对象新实例的引用。 语法:**CreateObject(** *class* \[ **,** *servername* ] **)** *class* : *必需* **Variant**(**String**)。要创建的对象的应用程序名称和类,格式为*appname*.*objecttype*——例如`"Excel.Application"`。也可以CLSID形式提供,格式为`"new:{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"`。 *servername* : *可选* **Variant**(**String**)。要在其上创建对象的网络服务器名称——与UNC共享名的*Machine Name*部分相同。对于名为`\\MyServer\Public`的共享,*servername*为`"MyServer"`。如果省略*servername*或提供为零长度字符串(`""`),则在本地机器上创建对象。 要使用返回的对象,请将其赋给对象变量。将变量声明为`As Object`会导致后期绑定(绑定在运行时发生);使用特定类类型声明会产生早期绑定(绑定在编译时发生),速度更快并且可以访问对象成员的IntelliSense,但将变量限制为该一种类型。 ```vb Dim ExcelApp As Object Set ExcelApp = CreateObject("Excel.Application") ExcelApp.Visible = True ``` 如果提供了远程*servername*但远程机器不存在或不可达,则会产生运行时错误。如果对象注册为单实例,则无论调用**CreateObject**多少次,都只会创建一个实例。 ::: info **CreateObject**获取对象的新实例。[**GetObject**](/official/Reference/VBA/Interaction/GetObject)附加到*已运行的*实例——或启动对象的应用程序并加载特定文件。 ::: ### 示例 本示例创建Microsoft Excel **Application**对象,使其可见,然后通过**Quit**关闭它,最后释放引用。 ```vb Dim XlApp As Object Set XlApp = CreateObject("Excel.Application") XlApp.Visible = True ' ... work with Excel through XlApp ... XlApp.Quit Set XlApp = Nothing ``` ### 另请参阅 * [GetObject](/official/Reference/VBA/Interaction/GetObject)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/CreateStdPictureFromHandle.md --- # CreateStdPictureFromHandle Wraps a GDI handle in an **stdole.StdPicture** so it can be assigned to a control's **Picture** property or passed to any other **IPicture** consumer. Syntax: **CreateStdPictureFromHandle(** *Handle* **,** *Type* **,** *TakeOwnership* **)** **As Object** *Handle* : *required* **LongPtr**. The GDI handle to wrap --- typically an `HBITMAP`, `HICON`, `HCURSOR`, `HENHMETAFILE`, or `HMETAFILE`. *Type* : *required* **Long**. The picture type. Pass one of the **PictureTypeConstants** values (`vbPicTypeBitmap`, `vbPicTypeIcon`, `vbPicTypeMetafile`, `vbPicTypeEnhMetafile`) corresponding to *Handle*'s flavour. *TakeOwnership* : *required* **Boolean**. If **True**, the returned picture takes ownership of *Handle* and frees it when released. If **False**, the caller remains responsible for the handle's lifetime. The result is a regular **stdole.StdPicture** equivalent to one returned by **LoadPicture**, suitable for assignment to a **Picture** property. ### See Also * [PictureToByteArray](/en/official/Reference/VBA/HiddenModule/PictureToByteArray) function * [ConvertIconToBitmap](/en/official/Reference/VBA/HiddenModule/ConvertIconToBitmap) function --- --- url: /zh/official/Reference/VBA/HiddenModule/CreateStdPictureFromHandle.md --- # CreateStdPictureFromHandle 将GDI句柄包装在**stdole.StdPicture**中,以便可以将其赋值给控件的**Picture**属性或传递给任何其他**IPicture**消费者。 语法:**CreateStdPictureFromHandle(** *Handle* **,** *Type* **,** *TakeOwnership* **)** **As Object** *Handle* : *必需* **LongPtr**。要包装的GDI句柄——通常是`HBITMAP`、`HICON`、`HCURSOR`、`HENHMETAFILE`或`HMETAFILE`。 *Type* : *必需* **Long**。图片类型。传递与*Handle*类型对应的**PictureTypeConstants**值之一(`vbPicTypeBitmap`、`vbPicTypeIcon`、`vbPicTypeMetafile`、`vbPicTypeEnhMetafile`)。 *TakeOwnership* : *必需* **Boolean**。如果为**True**,返回的图片获取*Handle*的所有权并在释放时释放它。如果为**False**,调用者仍负责句柄的生命周期。 结果是一个常规的**stdole.StdPicture**,等效于**LoadPicture**返回的对象,适合赋值给**Picture**属性。 ### 另请参阅 * [PictureToByteArray](/official/Reference/VBA/HiddenModule/PictureToByteArray)函数 * [ConvertIconToBitmap](/official/Reference/VBA/HiddenModule/ConvertIconToBitmap)函数 --- --- url: /en/official/Features/Packages/Creating-a-TWINPACK-package.md --- # Creating a TWINPACK package To create a new TWINPACK package, navigate to the twinBASIC New Project dialog, and under the 'Samples' tab, choose the option labelled 'Package': ![image](/assets/6ad7a172-0e1b-4276-ac89-042681552507.CUsDUXoA.png) Once you've created the project, you should find the extra 'PACKAGE PUBLISHING' panel as a popup: ![image](/assets/9eeffbcf-d73e-4a92-bce5-811ed60aba98.DcWbVPkf.png) You should now edit the Namespace, Description, Licence and Visibility properties appropriately by using the package manager 'EDIT' links, which will take you to the individual settings in the `Settings` file. Once you've edited them, remember to close (and save) the `Settings` file in order for your changes to be reflected in the package manager panel. * **Namespace:** this is the symbol that will be used to group your components in projects that reference your package. For example, a package that provides a series of different dialog classes might use the namespace `Dialogs`. * **Description:** this is the descriptive text that will appear in the `Settings`->`References` list. If you plan to share this package, think carefully about the description so that others can discover your package through TWINSERV. * **Licence:** this short text appears in the `Settings`->`References` list, alongside the Description. If you plan to share this package, it is important that you enter this field, and the value you enter here should appropriately match the content of the LICENCE.md file (e.g. 'MIT', 'LGPL' etc). * **Visibility:** determines whether the package is visible to only you (PRIVATE) or everyone (PUBLIC). The value set here only takes effect when you use the 'PUBLISH THIS PACKAGE' button to publish your package in the package manager service, TWINSERV. *If you don't plan to publish your package on TWINSERV, then you don't need to fill in the **Licence** or **Visibility** fields.* You can now create components (Class, Module, Interface) in your project as normal, and when you are finished, it's time to finalize the package. You have two options; ## OPTION 1 - Finalize the package into a TWINPACK file Use this option if you want to just create a local TWINPACK file that you can use in other projects. For this, the build process is the same as any ordinary twinBASIC build... just hit the Build button in the TWINBASIC toolbar: ![image](/assets/4d90f313-35d5-426d-8fc3-852ca03382fa.C14PwK_T.png) ![image](/assets/8d74d820-9907-4e76-ac42-71d0233187f1.CSUZ5DI5.png) You'll see the build output notification in the `DEBUG CONSOLE`, as seen above. Job done. See [Importing a package from a TWINPACK file](/en/official/Features/Packages/Importing-a-package-from-a-TWINPACK-file) for referencing and using the TWINPACK file in other twinBASIC projects. ## OPTION 2 - Publish the package directly to the package manager service (TWINSERV) If you're publishing your package onto TWINSERV, you don't need to create the TWINPACK file manually. Just use the 'PUBLISH THIS PACKAGE' button: ![Create Package](/assets/packPublishButton.BMiVB8Mz.png){style="width:45%; height:auto;"} ***Publishing packages onto TWINSERV requires you to first create a publisher account. If you haven't done so, you'll be prompted to do so at this stage.*** You will then be prompted to confirm the package details: ![Create Package](/assets/packPublishPackage1.DgsLjXIA.png){style="width:65%; height:auto;"} After pressing `YES`, the package will be uploaded to TWINSERV. Check the `DEBUG CONSOLE` for completion notices: ![Create Package](/assets/packPublishComplete1.DFxBYuMc.png){style="width:85%; height:auto;"} If the package got uploaded successfully, it should be available via TWINSERV within a few moments. If you've created a `PUBLIC` package, others will be able to see and download it at this point. See [Importing a package from TWINSERV](/en/official/Features/Packages/Importing-a-package-from-TWINSERV) for referencing and using the uploaded packages. ## Special files LICENCE.md and CHANGELOG.md When you create a new package project, you'll see two additional files created for you in the project filesystem: ![Create Package](/assets/packLicenceFiles.DCs-krDV.png){style="width:55%; height:auto;"} If you're publishing a `PUBLIC` package to the package manager service, it is important that you edit these two files before publishing. These are both markdown files, and will in future become more accessible to users that are considering using your package from TWINSERV. --- --- url: /en/official/Reference/VBA/Conversion/CSng.md --- # CSng Coerces an expression to a **Single**. Syntax: **CSng(** *expression* **)** *expression* : *required* Any valid string or numeric expression in the **Single** range --- `-3.402823E38` to `-1.401298E-45` for negative values, and `1.401298E-45` to `3.402823E38` for positive values. The return type is **Single**. If *expression* is outside the range of a **Single**, a run-time error occurs. **CSng** is the internationally aware alternative to [**Val**](/en/official/Reference/VBA/Conversion/Val) for converting a string to a numeric type. ### Example This example uses the **CSng** function to convert values to a **Single**. ```vb Dim MyDouble1, MyDouble2, MySingle1, MySingle2 ' MyDouble1, MyDouble2 are Doubles. MyDouble1 = 75.3421115: MyDouble2 = 75.3421555 MySingle1 = CSng(MyDouble1) ' MySingle1 contains 75.34211. MySingle2 = CSng(MyDouble2) ' MySingle2 contains 75.34216. ``` ### See Also * [CBool](/en/official/Reference/VBA/Conversion/CBool), [CByte](/en/official/Reference/VBA/Conversion/CByte), [CCur](/en/official/Reference/VBA/Conversion/CCur), [CDbl](/en/official/Reference/VBA/Conversion/CDbl), [CDec](/en/official/Reference/VBA/Conversion/CDec), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CStr](/en/official/Reference/VBA/Conversion/CStr), [CVar](/en/official/Reference/VBA/Conversion/CVar) functions --- --- url: /zh/official/Reference/VBA/Conversion/CSng.md --- # CSng 将表达式强制转换为 **Single**。 语法:**CSng(** *expression* **)** *expression* : *必需* **Single** 范围内的任何有效字符串或数值表达式——负值为 `-3.402823E38` 到 `-1.401298E-45`,正值为 `1.401298E-45` 到 `3.402823E38`。 返回类型为 **Single**。如果 *expression* 超出 **Single** 的范围,将发生运行时错误。 **CSng** 是替代 [**Val**](/official/Reference/VBA/Conversion/Val) 将字符串转换为数值类型的区域感知方案。 ### 示例 此示例使用 **CSng** 函数将值转换为 **Single**。 ```vb Dim MyDouble1, MyDouble2, MySingle1, MySingle2 ' MyDouble1, MyDouble2 are Doubles. MyDouble1 = 75.3421115: MyDouble2 = 75.3421555 MySingle1 = CSng(MyDouble1) ' MySingle1 contains 75.34211. MySingle2 = CSng(MyDouble2) ' MySingle2 contains 75.34216. ``` ### 另请参阅 * [CBool](/official/Reference/VBA/Conversion/CBool)、[CByte](/official/Reference/VBA/Conversion/CByte)、[CCur](/official/Reference/VBA/Conversion/CCur)、[CDbl](/official/Reference/VBA/Conversion/CDbl)、[CDec](/official/Reference/VBA/Conversion/CDec)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLng](/official/Reference/VBA/Conversion/CLng)、[CStr](/official/Reference/VBA/Conversion/CStr)、[CVar](/official/Reference/VBA/Conversion/CVar) 函数 --- --- url: /en/official/Reference/VBA/Conversion/CStr.md --- # CStr Coerces an expression to a **String**. Syntax: **CStr(** *expression* **)** *expression* : *required* Any valid expression. The return type is **String**. The result depends on the type of *expression*: | If *expression* is | CStr returns | |--------------------|---------------------------------------------------------------| | **Boolean** | A string containing `"True"` or `"False"`. | | **Date** | A string containing a date in the system's short date format. | | **Empty** | A zero-length string (`""`). | | **Error** | A string containing the word `Error` followed by the error number. | | **Null** | A run-time error. | | Other numeric | A string containing the number. | **CStr** is the internationally aware alternative to [**Str**](/en/official/Reference/VBA/Conversion/Str) for converting a number to a string. **CStr** recognizes different decimal separators properly, depending on the system's locale setting. ### Example This example uses the **CStr** function to convert a numeric value to a **String**. ```vb Dim MyDouble, MyString MyDouble = 437.324 ' MyDouble is a Double. MyString = CStr(MyDouble) ' MyString contains "437.324". ``` ### See Also * [CBool](/en/official/Reference/VBA/Conversion/CBool), [CByte](/en/official/Reference/VBA/Conversion/CByte), [CCur](/en/official/Reference/VBA/Conversion/CCur), [CDbl](/en/official/Reference/VBA/Conversion/CDbl), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CSng](/en/official/Reference/VBA/Conversion/CSng), [CVar](/en/official/Reference/VBA/Conversion/CVar) functions * [Str](/en/official/Reference/VBA/Conversion/Str), [Format](/en/official/Reference/VBA/Strings/Format) functions --- --- url: /zh/official/Reference/VBA/Conversion/CStr.md --- # CStr 将表达式强制转换为 **String**。 语法:**CStr(** *expression* **)** *expression* : *必需* 任何有效的表达式。 返回类型为 **String**。结果取决于 *expression* 的类型: | 如果 *expression* 为 | CStr 返回 | |----------------------|-----------| | **Boolean** | 包含 `"True"` 或 `"False"` 的字符串。 | | **Date** | 包含系统短日期格式日期的字符串。 | | **Empty** | 零长度字符串(`""`)。 | | **Error** | 包含单词 `Error` 后跟错误号的字符串。 | | **Null** | 运行时错误。 | | 其他数值 | 包含该数字的字符串。 | **CStr** 是替代 [**Str**](/official/Reference/VBA/Conversion/Str) 将数字转换为字符串的区域感知方案。**CStr** 根据系统的区域设置正确识别不同的小数分隔符。 ### 示例 此示例使用 **CStr** 函数将数值转换为 **String**。 ```vb Dim MyDouble, MyString MyDouble = 437.324 ' MyDouble is a Double. MyString = CStr(MyDouble) ' MyString contains "437.324". ``` ### 另请参阅 * [CBool](/official/Reference/VBA/Conversion/CBool)、[CByte](/official/Reference/VBA/Conversion/CByte)、[CCur](/official/Reference/VBA/Conversion/CCur)、[CDbl](/official/Reference/VBA/Conversion/CDbl)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLng](/official/Reference/VBA/Conversion/CLng)、[CSng](/official/Reference/VBA/Conversion/CSng)、[CVar](/official/Reference/VBA/Conversion/CVar) 函数 * [Str](/official/Reference/VBA/Conversion/Str)、[Format](/official/Reference/VBA/Strings/Format) 函数 --- --- url: /en/official/Reference/VBA/Conversion/CType.md --- # CType Performs an explicit type conversion to a type chosen by the caller. Syntax: **CType(Of** *type* **)** **(** *value* **)** *type* : *required* The type to convert *value* to. Any type known to the compiler is accepted, including built-in types, **Enum** types, classes, interfaces, and user-defined types. *value* : *required* The expression being converted. The return type matches *type*. ::: info **CType** is a twinBASIC extension; VBA has no equivalent. ::: **CType** has two roles: 1. **As an explicit cast**, used wherever an implicit conversion would either be disallowed or produce a compiler warning. It conveys the same intent as [**CInt**](/en/official/Reference/VBA/Conversion/CInt), [**CLng**](/en/official/Reference/VBA/Conversion/CLng), and the rest of the C-prefix functions, but for any target type --- most usefully when the target is an **Enum** or an interface. For example, assigning a numeric literal or another **Enum** member to an **Enum**-typed variable triggers a compiler warning that **CType** silences: ```vb Dim day As VbDayOfWeek day = CType(Of VbDayOfWeek)(1) ``` 2. **As a pointer-to-UDT cast**, used to view the memory pointed to by a **LongPtr** as a particular user-defined type without copying it. See [Enhanced Pointer Functionality](/en/official/Features/Language/Pointers#ctypeof-type) for the canonical examples. In both roles **CType** is an operator-like form recognized by the compiler; it isn't called like a regular function and the unparameterized name `CType` cannot be assigned to a function reference. ### See Also * [Enhanced Pointer Functionality](/en/official/Features/Language/Pointers#ctypeof-type) * [Generics](/en/official/Features/Language/Generics) * [Compiler Warnings](/en/official/Features/Compiler-IDE/Compiler-Warnings) * [CBool](/en/official/Reference/VBA/Conversion/CBool), [CByte](/en/official/Reference/VBA/Conversion/CByte), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CDbl](/en/official/Reference/VBA/Conversion/CDbl), [CStr](/en/official/Reference/VBA/Conversion/CStr), [CVar](/en/official/Reference/VBA/Conversion/CVar) functions --- --- url: /zh/official/Reference/VBA/Conversion/CType.md --- # CType 执行到由调用者选择的类型的显式类型转换。 语法:**CType(Of** *type* **)** **(** *value* **)** *type* : *必需* 要将 *value* 转换为的类型。接受编译器已知的任何类型,包括内置类型、**Enum** 类型、类、接口和用户自定义类型。 *value* : *必需* 要转换的表达式。 返回类型与 *type* 匹配。 ::: info **CType** 是 twinBASIC 扩展;VBA 没有等效项。 ::: **CType** 有两个作用: 1. **作为显式转换**,在任何隐式转换会被禁止或产生编译器警告的地方使用。它表达了与 [**CInt**](/official/Reference/VBA/Conversion/CInt)、[**CLng**](/official/Reference/VBA/Conversion/CLng) 和其余 C 前缀函数相同的意图,但适用于任何目标类型——最常用的是目标为 **Enum** 或接口的情况。例如,将数值字面量或另一个 **Enum** 成员赋值给 **Enum** 类型的变量会触发编译器警告,而 **CType** 可以消除此警告: ```vb Dim day As VbDayOfWeek day = CType(Of VbDayOfWeek)(1) ``` 2. **作为指针到 UDT 的转换**,用于将 **LongPtr** 指向的内存视为特定的用户自定义类型而不进行复制。参见[增强指针功能](/official/Features/Language/Pointers#ctypeof-type)中的规范示例。 在这两种角色中,**CType** 都是编译器识别的类似运算符的形式;它不像常规函数那样被调用,未参数化的名称 `CType` 不能赋值给函数引用。 ### 另请参阅 * [增强指针功能](/official/Features/Language/Pointers#ctypeof-type) * [泛型](/official/Features/Language/Generics) * [编译器警告](/official/Features/Compiler-IDE/Compiler-Warnings) * [CBool](/official/Reference/VBA/Conversion/CBool)、[CByte](/official/Reference/VBA/Conversion/CByte)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLng](/official/Reference/VBA/Conversion/CLng)、[CDbl](/official/Reference/VBA/Conversion/CDbl)、[CStr](/official/Reference/VBA/Conversion/CStr)、[CVar](/official/Reference/VBA/Conversion/CVar) 函数 --- --- url: /en/official/Reference/VBA/FileSystem/CurDir.md --- # CurDir Returns the current path. ## CurDir Function Returns a **Variant** (**String**) representing the current path. Syntax: **CurDir** \[ **(** *drive* **)** ] *drive* : *optional* String expression that specifies an existing drive. If no drive is specified or if *drive* is a zero-length string (`""`), **CurDir** returns the path for the current drive. ### Example This example uses the **CurDir** function to return the current path. ```vb ' Assume current path on C drive is "C:\WINDOWS\SYSTEM". ' Assume current path on D drive is "D:\EXCEL". ' Assume C is the current drive. Dim MyPath MyPath = CurDir ' Returns "C:\WINDOWS\SYSTEM". MyPath = CurDir("C") ' Returns "C:\WINDOWS\SYSTEM". MyPath = CurDir("D") ' Returns "D:\EXCEL". ``` ## CurDir$ Function Returns a **String** representing the current path. Syntax: **CurDir$** \[ **(** *drive* **)** ] *drive* : *optional* String expression that specifies an existing drive. If no drive is specified or if *drive* is a zero-length string (`""`), **CurDir$** returns the path for the current drive. ### Example This example uses the **CurDir$** function to return the current path. ```vb ' Assume current path on C drive is "C:\WINDOWS\SYSTEM". ' Assume current path on D drive is "D:\EXCEL". ' Assume C is the current drive. Dim MyPath As String MyPath = CurDir$ ' Returns "C:\WINDOWS\SYSTEM". MyPath = CurDir$("C") ' Returns "C:\WINDOWS\SYSTEM". MyPath = CurDir$("D") ' Returns "D:\EXCEL". ``` ### See Also * [ChDir](/en/official/Reference/VBA/FileSystem/ChDir), [ChDrive](/en/official/Reference/VBA/FileSystem/ChDrive) statements * [Dir](/en/official/Reference/VBA/FileSystem/Dir) function --- --- url: /zh/official/Reference/VBA/FileSystem/CurDir.md --- # CurDir 返回当前路径。 ## CurDir函数 返回一个表示当前路径的**Variant**(**String**)。 语法:**CurDir** \[ **(** *drive* **)** ] *drive* : *可选* 字符串表达式,指定一个现有的驱动器。如果未指定驱动器或*drive*为零长度字符串(`""`),**CurDir**返回当前驱动器的路径。 ### 示例 本示例使用**CurDir**函数返回当前路径。 ```vb ' Assume current path on C drive is "C:\WINDOWS\SYSTEM". ' Assume current path on D drive is "D:\EXCEL". ' Assume C is the current drive. Dim MyPath MyPath = CurDir ' Returns "C:\WINDOWS\SYSTEM". MyPath = CurDir("C") ' Returns "C:\WINDOWS\SYSTEM". MyPath = CurDir("D") ' Returns "D:\EXCEL". ``` ## CurDir$函数 返回一个表示当前路径的**String**。 语法:**CurDir$** \[ **(** *drive* **)** ] *drive* : *可选* 字符串表达式,指定一个现有的驱动器。如果未指定驱动器或*drive*为零长度字符串(`""`),\*\*CurDir$\*\*返回当前驱动器的路径。 ### 示例 本示例使用\*\*CurDir$\*\*函数返回当前路径。 ```vb ' Assume current path on C drive is "C:\WINDOWS\SYSTEM". ' Assume current path on D drive is "D:\EXCEL". ' Assume C is the current drive. Dim MyPath As String MyPath = CurDir$ ' Returns "C:\WINDOWS\SYSTEM". MyPath = CurDir$("C") ' Returns "C:\WINDOWS\SYSTEM". MyPath = CurDir$("D") ' Returns "D:\EXCEL". ``` ### 另请参阅 * [ChDir](/official/Reference/VBA/FileSystem/ChDir)、[ChDrive](/official/Reference/VBA/FileSystem/ChDrive)语句 * [Dir](/official/Reference/VBA/FileSystem/Dir)函数 --- --- url: /zh/official/Reference/Core/CurDir.md --- # CurDir 函数 curdir 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/CurDir.md --- # CurDir Function Documentation for the curdir keyword is not yet available. --- --- url: /en/official/Reference/VBA/Compilation/CurrentComponentCLSID.md --- # CurrentComponentCLSID Returns the Class ID (CLSID) of the current class as a **String**. Syntax: **CurrentComponentCLSID** \[ **()** ] The value is the GUID assigned to the enclosing class by its [`[ClassId(...)]`](/en/official/Reference/Core/Attributes#classid) attribute. If no **ClassId** is set, the function returns the all-zero GUID. ::: info **CurrentComponentCLSID** is a compile-time intrinsic --- the CLSID is read from the class's attributes when the source is compiled, not looked up from the COM registry at run time. It uses special internal bindings and may not behave like an ordinary function. ::: ### Example ```vb [ClassId("12345678-1234-1234-1234-123456789ABC")] Class CFoo Public Sub PrintId() Debug.Print CurrentComponentCLSID() End Sub End Class ``` ### See Also * [CurrentComponentName](/en/official/Reference/VBA/Compilation/CurrentComponentName) function * [ClassId](/en/official/Reference/Core/Attributes#classid) attribute --- --- url: /zh/official/Reference/VBA/Compilation/CurrentComponentCLSID.md --- # CurrentComponentCLSID 以 **String** 形式返回当前类的 Class ID (CLSID)。 语法:**CurrentComponentCLSID** \[ **()** ] 该值是由类的 [`[ClassId(...)]`](/official/Reference/Core/Attributes#classid) 属性分配给包含类的 GUID。如果未设置 **ClassId**,函数返回全零 GUID。 ::: info **CurrentComponentCLSID** 是编译时内部函数——CLSID 在源代码编译时从类的属性中读取,而非在运行时从 COM 注册表查找。它使用特殊的内部绑定,可能不像普通函数那样运作。 ::: ### 示例 ```vb [ClassId("12345678-1234-1234-1234-123456789ABC")] Class CFoo Public Sub PrintId() Debug.Print CurrentComponentCLSID() End Sub End Class ``` ### 另请参阅 * [CurrentComponentName](/official/Reference/VBA/Compilation/CurrentComponentName) 函数 * [ClassId](/official/Reference/Core/Attributes#classid) 属性 --- --- url: /en/official/Reference/VBA/Compilation/CurrentComponentName.md --- # CurrentComponentName Returns the name of the current component (module or class) as a literal **String**. Syntax: **CurrentComponentName** \[ **()** ] The value identifies the source unit --- the **Module**, **Class**, **Form**, or other component --- that lexically contains the call site. ::: info **CurrentComponentName** is a compile-time intrinsic: the literal string is embedded in the compiled code at the point of the call. It does not change at run time, even when the call is reached through a forwarded or inherited member. ::: ### Example ```vb Public Sub Log(Message As String) Debug.Print CurrentComponentName() & ": " & Message End Sub ``` ### See Also * [CurrentComponentCLSID](/en/official/Reference/VBA/Compilation/CurrentComponentCLSID) function * [CurrentProcedureName](/en/official/Reference/VBA/Compilation/CurrentProcedureName) function * [CurrentProjectName](/en/official/Reference/VBA/Compilation/CurrentProjectName) function * [CurrentSourceFile](/en/official/Reference/VBA/Compilation/CurrentSourceFile) function --- --- url: /zh/official/Reference/VBA/Compilation/CurrentComponentName.md --- # CurrentComponentName 以字面 **String** 形式返回当前组件(模块或类)的名称。 语法:**CurrentComponentName** \[ **()** ] 该值标识词汇上包含调用点的源单元——**Module**、**Class**、**Form** 或其他组件。 ::: info **CurrentComponentName** 是编译时内部函数:字面字符串在调用点嵌入到编译后的代码中。它在运行时不会改变,即使调用是通过转发或继承的成员到达的。 ::: ### 示例 ```vb Public Sub Log(Message As String) Debug.Print CurrentComponentName() & ": " & Message End Sub ``` ### 另请参阅 * [CurrentComponentCLSID](/official/Reference/VBA/Compilation/CurrentComponentCLSID) 函数 * [CurrentProcedureName](/official/Reference/VBA/Compilation/CurrentProcedureName) 函数 * [CurrentProjectName](/official/Reference/VBA/Compilation/CurrentProjectName) 函数 * [CurrentSourceFile](/official/Reference/VBA/Compilation/CurrentSourceFile) 函数 --- --- url: /en/official/Reference/VBA/Compilation/CurrentProcedureName.md --- # CurrentProcedureName Returns the name of the procedure in which the function is called, as a literal **String**. Syntax: **CurrentProcedureName** \[ **()** ] The value is the name of the **Sub**, **Function**, or **Property** that lexically contains the call. ::: info **CurrentProcedureName** is a compile-time intrinsic: the literal string is determined when the source is compiled, from the procedure that surrounds the call. It is not derived from the runtime call stack --- wrapping the call in a helper records the helper's name, not the original caller's. ::: ### Example ```vb Public Sub DoWork() Debug.Print CurrentProcedureName() ' Prints "DoWork" End Sub ``` ### See Also * [CurrentComponentName](/en/official/Reference/VBA/Compilation/CurrentComponentName) function * [CurrentProjectName](/en/official/Reference/VBA/Compilation/CurrentProjectName) function * [CurrentSourceFile](/en/official/Reference/VBA/Compilation/CurrentSourceFile) function --- --- url: /zh/official/Reference/VBA/Compilation/CurrentProcedureName.md --- # CurrentProcedureName 以字面 **String** 形式返回函数被调用时所在过程的名称。 语法:**CurrentProcedureName** \[ **()** ] 该值是词汇上包含调用的 **Sub**、**Function** 或 **Property** 的名称。 ::: info **CurrentProcedureName** 是编译时内部函数:字面字符串在源代码编译时确定,来自包围调用的过程。它不是从运行时调用栈派生的——将调用包装在辅助函数中会记录辅助函数的名称,而非原始调用者的名称。 ::: ### 示例 ```vb Public Sub DoWork() Debug.Print CurrentProcedureName() ' Prints "DoWork" End Sub ``` ### 另请参阅 * [CurrentComponentName](/official/Reference/VBA/Compilation/CurrentComponentName) 函数 * [CurrentProjectName](/official/Reference/VBA/Compilation/CurrentProjectName) 函数 * [CurrentSourceFile](/official/Reference/VBA/Compilation/CurrentSourceFile) 函数 --- --- url: /en/official/Reference/VBA/Compilation/CurrentProjectName.md --- # CurrentProjectName Returns the name of the current project as a literal **String**. Syntax: **CurrentProjectName** \[ **()** ] The value is the name of the project (executable or library) that owns the call site. ::: info **CurrentProjectName** is a compile-time intrinsic --- the literal string is embedded in the compiled code from the project's metadata at the point of the call. ::: ### Example ```vb Dim ProjectName As String ProjectName = CurrentProjectName() Debug.Print "Running in project: " & ProjectName ``` ### See Also * [CurrentComponentName](/en/official/Reference/VBA/Compilation/CurrentComponentName) function * [CurrentProcedureName](/en/official/Reference/VBA/Compilation/CurrentProcedureName) function * [CurrentSourceFile](/en/official/Reference/VBA/Compilation/CurrentSourceFile) function --- --- url: /zh/official/Reference/VBA/Compilation/CurrentProjectName.md --- # CurrentProjectName 以字面 **String** 形式返回当前项目的名称。 语法:**CurrentProjectName** \[ **()** ] 该值是拥有调用点的项目(可执行文件或库)的名称。 ::: info **CurrentProjectName** 是编译时内部函数——字面字符串在调用点从项目的元数据嵌入到编译后的代码中。 ::: ### 示例 ```vb Dim ProjectName As String ProjectName = CurrentProjectName() Debug.Print "Running in project: " & ProjectName ``` ### 另请参阅 * [CurrentComponentName](/official/Reference/VBA/Compilation/CurrentComponentName) 函数 * [CurrentProcedureName](/official/Reference/VBA/Compilation/CurrentProcedureName) 函数 * [CurrentSourceFile](/official/Reference/VBA/Compilation/CurrentSourceFile) 函数 --- --- url: /en/official/Reference/VBA/Compilation/CurrentSourceFile.md --- # CurrentSourceFile Returns the full path of the source file in which the function is called, as a **String**. Syntax: **CurrentSourceFile** \[ **()** ] The value is the absolute path of the source file that lexically contains the call. ::: info **CurrentSourceFile** is a compile-time intrinsic: the path is captured when the source is compiled. It reflects where the file lived on the build machine and may not correspond to any path that exists at run time. ::: ### Example ```vb Public Sub TraceHere() Debug.Print "Trace from " & CurrentSourceFile() & " in " & CurrentProcedureName() End Sub ``` ### See Also * [CurrentComponentName](/en/official/Reference/VBA/Compilation/CurrentComponentName) function * [CurrentProcedureName](/en/official/Reference/VBA/Compilation/CurrentProcedureName) function * [CurrentProjectName](/en/official/Reference/VBA/Compilation/CurrentProjectName) function --- --- url: /zh/official/Reference/VBA/Compilation/CurrentSourceFile.md --- # CurrentSourceFile 以 **String** 形式返回函数被调用时所在源文件的完整路径。 语法:**CurrentSourceFile** \[ **()** ] 该值是词汇上包含调用的源文件的绝对路径。 ::: info **CurrentSourceFile** 是编译时内部函数:路径在源代码编译时捕获。它反映的是文件在构建机器上的位置,可能与运行时存在的任何路径不一致。 ::: ### 示例 ```vb Public Sub TraceHere() Debug.Print "Trace from " & CurrentSourceFile() & " in " & CurrentProcedureName() End Sub ``` ### 另请参阅 * [CurrentComponentName](/official/Reference/VBA/Compilation/CurrentComponentName) 函数 * [CurrentProcedureName](/official/Reference/VBA/Compilation/CurrentProcedureName) 函数 * [CurrentProjectName](/official/Reference/VBA/Compilation/CurrentProjectName) 函数 --- --- url: /en/official/Reference/CustomControls/Framework/CustomControlContext.md --- # CustomControlContext class The callback object passed to a custom control's [**Initialize**](/en/official/Reference/CustomControls/Framework/ICustomControl#initialize). Holds the connection back into the framework --- used to deserialize designer-set property values, request repaints, create timers, and move the keyboard focus between elements the control has drawn. Custom controls store the **CustomControlContext** in a private field (typically called **ControlContext**) so that they can call back into the framework at any point after **Initialize** has returned. The form-class counterpart [**CustomFormContext**](/en/official/Reference/CustomControls/Framework/CustomFormContext) extends this with **Show** and **Close**. ```vb Private Sub OnInitialize(ByVal Ctx As CustomControls.CustomControlContext) _ Implements CustomControls.ICustomControl.Initialize ' Load any serialized property values If Not Ctx.GetSerializer.RuntimeUISrzDeserialize(Me, False) Then InitializeDefaultValues End If ' Remember the context for later Set Me.ControlContext = Ctx End Sub ``` ## Methods ### ChangeFocusedElement Asks the framework to move the keyboard focus to a particular `ElementTabIndex` value, as if the user had pressed **TAB** until reaching that point. Used by [**WaynesGrid**](/en/official/Reference/CustomControls/WaynesGrid/) when a cell is selected programmatically --- the grid changes its **SelectedCellX** / **SelectedCellY** and then calls this method so that the form-level focus tracking matches. Syntax: *object*.**ChangeFocusedElement** *ElementTabIndex* *ElementTabIndex* : *required* A **Long** matching the **ElementTabIndex** of an element that was added to the canvas in the most recent paint pass. ### CreateTimer Returns a new [**CustomControlTimer**](/en/official/Reference/CustomControls/Framework/CustomControlTimer) bound to this control's lifetime. The timer is **Disabled** on creation; the caller sets [**Interval**](/en/official/Reference/CustomControls/Framework/CustomControlTimer#interval), subscribes to the timer's **OnTimer** event, and sets [**Enabled**](/en/official/Reference/CustomControls/Framework/CustomControlTimer#enabled) to **True** to start it. Syntax: *object*.**CreateTimer** ( ) **As stdole.IUnknown** The framework returns the timer typed as **stdole.IUnknown**; cast with `CType(Of CustomControlTimer)(…)` to get a strongly-typed reference. [**WaynesTimer**](/en/official/Reference/CustomControls/WaynesTimer) and [**WaynesSlider**](/en/official/Reference/CustomControls/WaynesSlider/) both use this pattern. ### GetSerializer Returns the [**SerializeInfo**](/en/official/Reference/CustomControls/Framework/SerializeInfo) handle for this control instance. The serializer exposes the deserialization entry point and the run-time / design-time mode flags. Syntax: *object*.**GetSerializer** ( ) **As SerializeInfo** ### Repaint Tells the framework that the control's appearance has changed and that the canvas should be repainted at the next opportunity. The framework eventually calls back into [**ICustomControl.Paint**](/en/official/Reference/CustomControls/Framework/ICustomControl#paint); calling **Repaint** multiple times in quick succession produces at most one paint. Syntax: *object*.**Repaint** ( ) Every concrete `Waynes…` control hooks the **OnChanged** events on its state and style sub-objects, and calls **Repaint** from the handler --- so a runtime assignment like `btn.NormalState.BackgroundFill.ColorPoints.SetSolidColor vbBlue` triggers an automatic redraw. --- --- url: /zh/official/Reference/CustomControls/Framework/CustomControlContext.md --- # CustomControlContext 类 传递给自定义控件 [**Initialize**](/official/Reference/CustomControls/Framework/ICustomControl#initialize) 的回调对象。保持回到框架的连接——用于反序列化设计器设置的属性值、请求重绘、创建定时器以及在控件绘制的元素之间移动键盘焦点。 自定义控件将 **CustomControlContext** 存储在私有字段中(通常名为 **ControlContext**),以便在 **Initialize** 返回后的任何时刻回调框架。窗体类对应类 [**CustomFormContext**](/official/Reference/CustomControls/Framework/CustomFormContext) 扩展了 **Show** 和 **Close**。 ```vb Private Sub OnInitialize(ByVal Ctx As CustomControls.CustomControlContext) _ Implements CustomControls.ICustomControl.Initialize ' Load any serialized property values If Not Ctx.GetSerializer.RuntimeUISrzDeserialize(Me, False) Then InitializeDefaultValues End If ' Remember the context for later Set Me.ControlContext = Ctx End Sub ``` ## 方法 ### ChangeFocusedElement 请求框架将键盘焦点移至特定 `ElementTabIndex` 值,如同用户按 **TAB** 直至到达该位置。[**WaynesGrid**](/official/Reference/CustomControls/WaynesGrid/) 在以编程方式选择单元格时使用此方法——网格更改其 **SelectedCellX** / **SelectedCellY** 然后调用此方法,使窗体级焦点跟踪与之匹配。 语法:*object*.**ChangeFocusedElement** *ElementTabIndex* *ElementTabIndex* : *必需* **Long**,匹配最近一次绘制过程中添加到画布的元素的 **ElementTabIndex**。 ### CreateTimer 返回一个新的 [**CustomControlTimer**](/official/Reference/CustomControls/Framework/CustomControlTimer),绑定到此控件的生命周期。定时器创建时为**禁用**状态;调用者设置 [**Interval**](/official/Reference/CustomControls/Framework/CustomControlTimer#interval),订阅定时器的 **OnTimer** 事件,并将 [**Enabled**](/official/Reference/CustomControls/Framework/CustomControlTimer#enabled) 设为 **True** 以启动。 语法:*object*.**CreateTimer** ( ) **As stdole.IUnknown** 框架以 **stdole.IUnknown** 类型返回定时器;用 `CType(Of CustomControlTimer)(…)` 转换以获取强类型引用。[**WaynesTimer**](/official/Reference/CustomControls/WaynesTimer) 和 [**WaynesSlider**](/official/Reference/CustomControls/WaynesSlider/) 都使用此模式。 ### GetSerializer 返回此控件实例的 [**SerializeInfo**](/official/Reference/CustomControls/Framework/SerializeInfo) 句柄。序列化器暴露反序列化入口点和运行时/设计时模式标志。 语法:*object*.**GetSerializer** ( ) **As SerializeInfo** ### Repaint 通知框架控件外观已更改,画布应在下次机会时重绘。框架最终回调 [**ICustomControl.Paint**](/official/Reference/CustomControls/Framework/ICustomControl#paint);快速连续多次调用 **Repaint** 最多只产生一次绘制。 语法:*object*.**Repaint** ( ) 每个具体 `Waynes…` 控件都挂钩其状态和样式子对象上的 **OnChanged** 事件,并从处理程序中调用 **Repaint**——因此运行时赋值如 `btn.NormalState.BackgroundFill.ColorPoints.SetSolidColor vbBlue` 会触发自动重绘。 --- --- url: /en/official/Tutorials/CustomControls.md --- # CustomControls twinBASIC now offers experimental support for CustomControls. CustomControls are implemented using the BASIC language, allowing implementers to design controls directly from the twinBASIC environment. A few highlights; * completely custom drawn controls, with no external or third-party dependencies (tiny footprint) * support 32-bit RGBA for full alpha-transparency * support high-DPI modes (per-monitor), requiring little thought whilst designing new controls * full debugging support via the usual twinBASIC integrated debugger * designed for efficiency to support complex controls with hundreds of elements (e.g. a DataGrid with 100's of cells) * designed for flexibility, allowing for curved corners, multiple borders, background gradients and much more * the form engine supports anchoring and docking without any considerations needed for CustomControl implementers * simple property sheet synchronization via the built-in form designer ## See also * [CustomControls package reference](/en/official/Reference/CustomControls/) -- the full reference for the built-in `Waynes…` controls and the framework they are built on, including [`ICustomControl`](/en/official/Reference/CustomControls/Framework/ICustomControl), [`Canvas`](/en/official/Reference/CustomControls/Framework/Canvas), and the style helpers ([`Fill`](/en/official/Reference/CustomControls/Styles/Fill), [`Corners`](/en/official/Reference/CustomControls/Styles/Corners), [`Borders`](/en/official/Reference/CustomControls/Styles/Borders), [`TextRendering`](/en/official/Reference/CustomControls/Styles/TextRendering), …) --- --- url: /zh/official/Tutorials/CustomControls.md --- # CustomControls twinBASIC现在提供对CustomControls的实验性支持。CustomControls使用BASIC语言实现,允许开发者直接从twinBASIC环境中设计控件。 主要亮点: * 完全自绘控件,无外部或第三方依赖(极小体积) * 支持32位RGBA实现完全Alpha透明 * 支持高DPI模式(每显示器),设计新控件时几乎无需额外考虑 * 通过twinBASIC集成调试器提供完整调试支持 * 针对效率设计,支持包含数百个元素的复杂控件(如具有数百单元格的DataGrid) * 针对灵活性设计,支持圆角、多重边框、背景渐变等 * 窗体引擎支持锚定和停靠,CustomControl开发者无需任何额外考虑 * 通过内置窗体设计器进行简单的属性表同步 ## 另见 * [CustomControls包参考](/official/Reference/CustomControls/) —— 内置 `Waynes…` 控件及其构建框架的完整参考,包括[`ICustomControl`](/official/Reference/CustomControls/Framework/ICustomControl)、[`Canvas`](/official/Reference/CustomControls/Framework/Canvas)和样式辅助工具([`Fill`](/official/Reference/CustomControls/Styles/Fill)、[`Corners`](/official/Reference/CustomControls/Styles/Corners)、[`Borders`](/official/Reference/CustomControls/Styles/Borders)、[`TextRendering`](/official/Reference/CustomControls/Styles/TextRendering)、……) > AI生成 --- --- url: /zh/official/Reference/CustomControls.md --- # CustomControls 包 **CustomControls** 内置包提供一组完全自绘控件——按钮、窗体、框架、网格、标签、滑块、文本框和定时器——以及它们所基于的框架。每个可见像素都由包自身渲染而非 Windows,因此外观在不同系统上完全一致,且完全通过少量样式对象([**Fill**](/official/Reference/CustomControls/Styles/Fill)、[**Borders**](/official/Reference/CustomControls/Styles/Borders)、[**Corners**](/official/Reference/CustomControls/Styles/Corners)、[**TextRendering**](/official/Reference/CustomControls/Styles/TextRendering) 等)进行配置,而非通过切换主题标志。 该包以两个配对组件的形式发布:一个 **CustomControls DESIGNER** 库——框架部分,源码侧项目 `CustomControls`——定义了渲染表面和每个自定义控件实现的接口;以及 **Custom Controls** 包——源码侧项目 `CustomControlsPackage`——提供八个具体的 `Waynes…` 控件。两者与 twinBASIC 同版本发布,始终一起发布;均为 MIT 许可。 除了提供即用控件外,该包同时也可作为编写新自定义控件的工作示例。`Waynes…` 类实现了与手写控件相同的 [**ICustomControl**](/official/Reference/CustomControls/Framework/ICustomControl) 接口,使用相同的 [**CustomControlContext**](/official/Reference/CustomControls/Framework/CustomControlContext) 回调对象和 [**Canvas**](/official/Reference/CustomControls/Framework/Canvas) 绘图表面——参见 [Framework](/official/Reference/CustomControls/Framework/) 页面了解宿主侧契约。 ```vb Private Sub Form_Load() btnGo.Caption = "Continue" btnGo.NormalState.BackgroundFill.ColorPoints.SetSolidColor vbBlue btnGo.NormalState.Corners.SetAll tbCurve, 12 txtName.Value = "" End Sub Private Sub btnGo_Click() MsgBox "Hello, " & txtName.Value End Sub ``` ## 控件 * [WaynesButton](/official/Reference/CustomControls/WaynesButton/) —— 自绘按钮,具有正常、悬停、焦点和按下等独立的视觉状态 * [WaynesForm](/official/Reference/CustomControls/WaynesForm/) —— 用于承载自定义控件的顶级窗体;暴露控制 Win32 框架的 **WindowsOptions** 子对象 * [WaynesFrame](/official/Reference/CustomControls/WaynesFrame) —— 矩形容器,以可配置背景填充其区域 * [WaynesGrid](/official/Reference/CustomControls/WaynesGrid/) —— 表格数据显示,具有列标题、行标题、悬停/选择状态和可调整列宽 * [WaynesLabel](/official/Reference/CustomControls/WaynesLabel) —— 静态文本显示,具有填充、文本渲染和标题 * [WaynesSlider](/official/Reference/CustomControls/WaynesSlider/) —— 水平或垂直值滑块,具有悬停/焦点状态和可拖动滑块 * [WaynesTextBox](/official/Reference/CustomControls/WaynesTextBox/) —— 单行可编辑文本字段,具有选择、插入符、代理对感知和内联文本装饰器 * [WaynesTimer](/official/Reference/CustomControls/WaynesTimer) —— 非可视定时器,以可编程间隔触发 **Timer** 事件 每个具体控件都实现了 [**ICustomControl**](/official/Reference/CustomControls/Framework/ICustomControl) 并从内部基类继承少量布局和名称成员: * 所有控件都暴露 **Name**、**Left**、**Top**、**Width**、**Height**、**Anchors**、**Dock** 和 **Visible**。 * 可以获取键盘焦点的控件([**WaynesButton**](/official/Reference/CustomControls/WaynesButton/)、[**WaynesGrid**](/official/Reference/CustomControls/WaynesGrid/)、[**WaynesSlider**](/official/Reference/CustomControls/WaynesSlider/)、[**WaynesTextBox**](/official/Reference/CustomControls/WaynesTextBox/))还暴露 **TabIndex** 和 **TabStop**。 * [**WaynesForm**](/official/Reference/CustomControls/WaynesForm/) 则暴露窗体级成员:**FormDesignerId**、**Name**、位置/大小以及 **Controls** 集合。 这些成员列在每个控件自己的页面上;它们的定义相同,不会单独重复。 ## 样式对象 每个控件的视觉风格由少量小型辅助类控制,通过 `Public WithEvents …` 属性自动实例化。它们可以任意嵌套——[**TextRendering**](/official/Reference/CustomControls/Styles/TextRendering) 包含一个 [**Fill**](/official/Reference/CustomControls/Styles/Fill) 用于文本颜色,其中包含 `Granularity` 和 `FillColorPoint` 渐变 stops 数组;[**Border**](/official/Reference/CustomControls/Styles/Borders#border-class) 对象数组描述控件轮廓的绘制方式;等等。 * [Anchors](/official/Reference/CustomControls/Styles/Anchors) —— 容器调整大小时控件的哪些边附着到容器 * [Borders](/official/Reference/CustomControls/Styles/Borders) —— 绘制在控件周围的一个或多个边框笔触(包括单笔触 `Border` 子对象) * [Corners](/official/Reference/CustomControls/Styles/Corners) —— 控件的四个角形状和半径(包括逐角 `Corner` 子对象) * [Fill](/official/Reference/CustomControls/Styles/Fill) —— 绘制区域的颜色或渐变(包括 `FillColorPoint` / `FillColorPoints` 渐变 stop 子对象) * [Line](/official/Reference/CustomControls/Styles/Line) —— 单条网格线或调整条笔触;比完整边框更细的形状 * [Padding](/official/Reference/CustomControls/Styles/Padding) —— [**TextRendering**](/official/Reference/CustomControls/Styles/TextRendering) 内文本的逐侧内边距 * [TextRendering](/official/Reference/CustomControls/Styles/TextRendering) —— 控件内绘制文本的字体、内边距、填充、轮廓、对齐和溢出(包括 `FontStyle` 子对象) 每个样式对象在设置其任意字段时都会触发 **OnChanged** 事件,承载它的控件在每次变更时请求重绘——在运行时赋值样式属性会立即触发重绘。 ## 框架 用于编写新自定义控件或窗体,包的 **CustomControls DESIGNER** 部分提供: * [ICustomControl](/official/Reference/CustomControls/Framework/ICustomControl) —— 每个自定义控件实现的接口:**Initialize**、**Destroy**、**Paint** * [ICustomForm](/official/Reference/CustomControls/Framework/ICustomForm) —— 自定义窗体类的相应接口 * [CustomControlContext](/official/Reference/CustomControls/Framework/CustomControlContext) —— 传递给 **Initialize** 的回调对象;提供序列化器访问、重绘请求、定时器创建和焦点变更 * [CustomFormContext](/official/Reference/CustomControls/Framework/CustomFormContext) —— 扩展了 **CustomControlContext** 的 **Show** 和 **Close** 的窗体类控件回调 * [CustomControlTimer](/official/Reference/CustomControls/Framework/CustomControlTimer) —— 由 **CustomControlContext.CreateTimer** 返回的定时器;具有 **Interval**、**Enabled** 和 **OnTimer** 事件 * [CustomControlsCollection](/official/Reference/CustomControls/Framework/CustomControlsCollection) —— 窗体上的 **Controls** 集合 * [Canvas](/official/Reference/CustomControls/Framework/Canvas) —— 传递给 **Paint** 的绘图表面;向自定义控件输出像素的唯一方式 * [SerializeInfo](/official/Reference/CustomControls/Framework/SerializeInfo) —— 由 **CustomControlContext.GetSerializer** 返回的每实例序列化器;用于反序列化设计器设置的属性值和查询运行时模式 ## 枚举 * [BorderStyle](/official/Reference/CustomControls/Enumerations/BorderStyle) —— 传递给 [**WindowsFormOptions.BorderStyle**](/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#borderstyle) 的窗体框架样式 * [ColorRGBA](/official/Reference/CustomControls/Enumerations/ColorRGBA) —— 32 位 ABGR 颜色值的 `Long` 兼容类型别名 * [CornerShape](/official/Reference/CustomControls/Enumerations/CornerShape) —— 控件单个角的形状:曲线、凹口或切角 * [Customtate](/official/Reference/CustomControls/Enumerations/Customtate) —— [**WindowState**](/official/Reference/CustomControls/Enumerations/WindowState) 的副本;保留 * [DockMode](/official/Reference/CustomControls/Enumerations/DockMode) —— 控件在其容器内的停靠方式 * [FillPattern](/official/Reference/CustomControls/Enumerations/FillPattern) —— [**Fill**](/official/Reference/CustomControls/Styles/Fill) 使用的渐变或填充模式 * [FontWeight](/official/Reference/CustomControls/Enumerations/FontWeight) —— 从 **tbThin** 到 **tbHeavy** 的字体粗细,映射 OpenType `wght` 刻度 * [PixelCount](/official/Reference/CustomControls/Enumerations/PixelCount) —— 以像素表示的测量值的 `Long` 兼容类型别名 * [PointSize](/official/Reference/CustomControls/Enumerations/PointSize) —— 以磅表示的字体大小的 `Long` 兼容类型别名 * [StartupPosition](/official/Reference/CustomControls/Enumerations/StartupPosition) —— 窗体首次显示时的初始位置 * [TextAlignment](/official/Reference/CustomControls/Enumerations/TextAlignment) —— [**TextRendering**](/official/Reference/CustomControls/Styles/TextRendering) 内文本的水平和垂直对齐 * [TextOverflowMode](/official/Reference/CustomControls/Enumerations/TextOverflowMode) —— 超出可用区域的文本如何截断 * [WindowState](/official/Reference/CustomControls/Enumerations/WindowState) —— 窗体的最小化/正常/最大化窗口状态 --- --- url: /en/official/Reference/CustomControls.md --- # CustomControls Package The **CustomControls** built-in package supplies a set of fully owner-drawn controls --- buttons, a form, a frame, a grid, a label, a slider, a textbox, and a timer --- together with the framework on which they are built. Every visible pixel is rendered by the package itself rather than by Windows, so the look and feel is identical across systems and is configured entirely through a small vocabulary of style objects ([**Fill**](/en/official/Reference/CustomControls/Styles/Fill), [**Borders**](/en/official/Reference/CustomControls/Styles/Borders), [**Corners**](/en/official/Reference/CustomControls/Styles/Corners), [**TextRendering**](/en/official/Reference/CustomControls/Styles/TextRendering), …) rather than by toggling theme flags. The package ships as two paired components: a **CustomControls DESIGNER** library --- the framework half, source-side project `CustomControls` --- that defines the rendering surface and the interface every custom control implements; and the **Custom Controls** package --- source-side project `CustomControlsPackage` --- that supplies the eight concrete `Waynes…` controls. The two are co-versioned with twinBASIC and always ship together; both are MIT-licensed. Beyond providing ready-to-use controls, the package doubles as a worked example for authoring new custom controls. The `Waynes…` classes implement the same [**ICustomControl**](/en/official/Reference/CustomControls/Framework/ICustomControl) interface that a hand-written control would, against the same [**CustomControlContext**](/en/official/Reference/CustomControls/Framework/CustomControlContext) callback object and [**Canvas**](/en/official/Reference/CustomControls/Framework/Canvas) drawing surface --- see the [Framework](/en/official/Reference/CustomControls/Framework/) page for the host-side contract. ```vb Private Sub Form_Load() btnGo.Caption = "Continue" btnGo.NormalState.BackgroundFill.ColorPoints.SetSolidColor vbBlue btnGo.NormalState.Corners.SetAll tbCurve, 12 txtName.Value = "" End Sub Private Sub btnGo_Click() MsgBox "Hello, " & txtName.Value End Sub ``` ## Controls * [WaynesButton](/en/official/Reference/CustomControls/WaynesButton/) -- owner-drawn push-button with separate visual states for normal, hover, focused, and pressed * [WaynesForm](/en/official/Reference/CustomControls/WaynesForm/) -- top-level form for hosting custom controls; exposes the **WindowsOptions** sub-object that controls the Win32 frame * [WaynesFrame](/en/official/Reference/CustomControls/WaynesFrame) -- rectangular container that fills its area with a configurable background * [WaynesGrid](/en/official/Reference/CustomControls/WaynesGrid/) -- tabular data display with column headers, row headers, hover / selection states, and resizable columns * [WaynesLabel](/en/official/Reference/CustomControls/WaynesLabel) -- static text display with fill, text rendering, and caption * [WaynesSlider](/en/official/Reference/CustomControls/WaynesSlider/) -- horizontal or vertical value slider with hover / focused states and a draggable block * [WaynesTextBox](/en/official/Reference/CustomControls/WaynesTextBox/) -- single-line editable text field with selection, caret, surrogate-pair awareness, and inline text decorators * [WaynesTimer](/en/official/Reference/CustomControls/WaynesTimer) -- non-visual timer that raises a **Timer** event at a programmable interval Every concrete control implements [**ICustomControl**](/en/official/Reference/CustomControls/Framework/ICustomControl) and inherits a small set of layout-and-name members from an internal base class: * All controls expose **Name**, **Left**, **Top**, **Width**, **Height**, **Anchors**, **Dock**, and **Visible**. * Controls that can take keyboard focus ([**WaynesButton**](/en/official/Reference/CustomControls/WaynesButton/), [**WaynesGrid**](/en/official/Reference/CustomControls/WaynesGrid/), [**WaynesSlider**](/en/official/Reference/CustomControls/WaynesSlider/), [**WaynesTextBox**](/en/official/Reference/CustomControls/WaynesTextBox/)) additionally expose **TabIndex** and **TabStop**. * [**WaynesForm**](/en/official/Reference/CustomControls/WaynesForm/) instead exposes form-level members: **FormDesignerId**, **Name**, position / size, and the **Controls** collection. These members are listed on each control's own page; their definitions are identical and are not repeated separately. ## Style objects The visual style of every control is controlled by a few small helper classes, instantiated automatically through `Public WithEvents …` properties. They are nested arbitrarily --- a [**TextRendering**](/en/official/Reference/CustomControls/Styles/TextRendering) contains a [**Fill**](/en/official/Reference/CustomControls/Styles/Fill) for the text colour, which contains a `Granularity` and an array of `FillColorPoint` gradient stops; an array of [**Border**](/en/official/Reference/CustomControls/Styles/Borders#border-class) objects describes how the outline of a control is stroked; and so on. * [Anchors](/en/official/Reference/CustomControls/Styles/Anchors) -- which sides of a control are attached to its container when the container is resized * [Borders](/en/official/Reference/CustomControls/Styles/Borders) -- one or more border strokes drawn around a control (including the single-stroke `Border` sub-object) * [Corners](/en/official/Reference/CustomControls/Styles/Corners) -- the four corner shapes and radii of a control (including the per-corner `Corner` sub-object) * [Fill](/en/official/Reference/CustomControls/Styles/Fill) -- the colour or gradient that paints a region (including the `FillColorPoint` / `FillColorPoints` gradient-stop sub-objects) * [Line](/en/official/Reference/CustomControls/Styles/Line) -- a single grid-line or resizer-bar stroke; thinner shape than a full border * [Padding](/en/official/Reference/CustomControls/Styles/Padding) -- per-side padding around text inside a [**TextRendering**](/en/official/Reference/CustomControls/Styles/TextRendering) * [TextRendering](/en/official/Reference/CustomControls/Styles/TextRendering) -- font, padding, fill, outlines, alignment, and overflow for the text drawn inside a control (including the `FontStyle` sub-object) Every style object raises an **OnChanged** event whenever one of its fields is set, and the control that hosts it requests a repaint on each change --- assigning style values at runtime triggers an immediate redraw. ## Framework For authoring new custom controls or forms, the **CustomControls DESIGNER** half of the package supplies: * [ICustomControl](/en/official/Reference/CustomControls/Framework/ICustomControl) -- the interface every custom control implements: **Initialize**, **Destroy**, **Paint** * [ICustomForm](/en/official/Reference/CustomControls/Framework/ICustomForm) -- the analogous interface for custom form classes * [CustomControlContext](/en/official/Reference/CustomControls/Framework/CustomControlContext) -- callback object passed to **Initialize**; offers serializer access, repaint requests, timer creation, and focus changes * [CustomFormContext](/en/official/Reference/CustomControls/Framework/CustomFormContext) -- a **CustomControlContext** extended with **Show** and **Close** for form-class controls * [CustomControlTimer](/en/official/Reference/CustomControls/Framework/CustomControlTimer) -- the timer returned by **CustomControlContext.CreateTimer**; has **Interval**, **Enabled**, and an **OnTimer** event * [CustomControlsCollection](/en/official/Reference/CustomControls/Framework/CustomControlsCollection) -- the **Controls** collection on a form * [Canvas](/en/official/Reference/CustomControls/Framework/Canvas) -- the drawing surface passed to **Paint**; the only way to put pixels into a custom control * [SerializeInfo](/en/official/Reference/CustomControls/Framework/SerializeInfo) -- the per-instance serializer returned by **CustomControlContext.GetSerializer**; used to deserialize designer-set property values and to query the runtime mode ## Enumerations * [BorderStyle](/en/official/Reference/CustomControls/Enumerations/BorderStyle) -- window-frame style passed to [**WindowsFormOptions.BorderStyle**](/en/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#borderstyle) * [ColorRGBA](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) -- `Long`-compatible type alias for 32-bit ABGR colour values * [CornerShape](/en/official/Reference/CustomControls/Enumerations/CornerShape) -- how a single corner of a control is shaped: curve, notch, or cut-out * [Customtate](/en/official/Reference/CustomControls/Enumerations/Customtate) -- duplicate of [**WindowState**](/en/official/Reference/CustomControls/Enumerations/WindowState); reserved * [DockMode](/en/official/Reference/CustomControls/Enumerations/DockMode) -- how a control is docked inside its container * [FillPattern](/en/official/Reference/CustomControls/Enumerations/FillPattern) -- the gradient or fill pattern used by a [**Fill**](/en/official/Reference/CustomControls/Styles/Fill) * [FontWeight](/en/official/Reference/CustomControls/Enumerations/FontWeight) -- font weights from **tbThin** through **tbHeavy**, mirroring the OpenType `wght` scale * [PixelCount](/en/official/Reference/CustomControls/Enumerations/PixelCount) -- `Long`-compatible type alias for measurements expressed in pixels * [PointSize](/en/official/Reference/CustomControls/Enumerations/PointSize) -- `Long`-compatible type alias for font sizes expressed in points * [StartupPosition](/en/official/Reference/CustomControls/Enumerations/StartupPosition) -- initial position of a form when it is first shown * [TextAlignment](/en/official/Reference/CustomControls/Enumerations/TextAlignment) -- horizontal and vertical alignment of text within a [**TextRendering**](/en/official/Reference/CustomControls/Styles/TextRendering) * [TextOverflowMode](/en/official/Reference/CustomControls/Enumerations/TextOverflowMode) -- how text longer than the available area is truncated * [WindowState](/en/official/Reference/CustomControls/Enumerations/WindowState) -- the minimized / normal / maximized window state of a form --- --- url: /en/official/Reference/CustomControls/Framework/CustomControlsCollection.md --- # CustomControlsCollection class The collection of controls hosted on a custom form. Accessed as the **Controls** property of a [**WaynesForm**](/en/official/Reference/CustomControls/WaynesForm/). Supports indexed access by integer or name, enumeration with **For Each**, and runtime add / remove of controls. ```vb Dim ctl As Object For Each ctl In MyForm.Controls Debug.Print ctl.Name Next ``` ## Properties ### Count The number of controls in the collection. **Long**. Read-only. Syntax: *object*.**Count** ### Item Returns the control at the given index or with the given name. The **Default property** --- the **Controls** ( *…* ) shorthand calls **Item**. Syntax: *object*.**Item** ( *IndexOrName* ) **As Object** *IndexOrName* : *required* A **Variant** that is either a **Long** zero-based index or a **String** matching the control's [**Name**](/en/official/Reference/CustomControls/#controls). ## Methods ### Add Adds a new control to the collection by class **ProgID**, gives it a name, and attaches it to a container. Syntax: *object*.**Add** ( *ProgId*, *ControlName*, *Container* ) **As Object** *ProgId* : *required* A **String** holding the class **ProgID** of the control to create. *ControlName* : *required* A **String** giving the **Name** to assign to the new control. *Container* : *required* An **Object** reference to the form, frame, or other container that will host the new control. The newly-created control is returned, typed as **Object**. ### Remove Removes the control at the given index or with the given name from the collection. Syntax: *object*.**Remove** *IndexOrName* *IndexOrName* : *required* A **Variant** that is either a **Long** zero-based index or a **String** matching the control's [**Name**](/en/official/Reference/CustomControls/#controls). ## Iteration A `For Each` loop over the collection produces every hosted control in turn: ```vb Dim ctl As Object For Each ctl In MyForm.Controls ' … Next ``` The hidden member that powers this is `_NewEnum`; application code does not call it directly. --- --- url: /zh/official/Reference/CustomControls/Framework/CustomControlsCollection.md --- # CustomControlsCollection 类 自定义窗体上承载的控件集合。作为 [**WaynesForm**](/official/Reference/CustomControls/WaynesForm/) 的 **Controls** 属性访问。支持按整数或名称的索引访问、**For Each** 枚举以及运行时添加/删除控件。 ```vb Dim ctl As Object For Each ctl In MyForm.Controls Debug.Print ctl.Name Next ``` ## 属性 ### Count 集合中的控件数量。**Long**。只读。 语法:*object*.**Count** ### Item 返回给定索引或给定名称的控件。**默认属性**——**Controls** ( *…* ) 简写调用 **Item**。 语法:*object*.**Item** ( *IndexOrName* ) **As Object** *IndexOrName* : *必需* **Variant**,为 **Long** 零基索引或与控件 [**Name**](/official/Reference/CustomControls/#controls) 匹配的 **String**。 ## 方法 ### Add 按类 **ProgID** 向集合添加新控件,为其命名并附加到容器。 语法:*object*.**Add** ( *ProgId*, *ControlName*, *Container* ) **As Object** *ProgId* : *必需* **String**,包含要创建控件的类 **ProgID**。 *ControlName* : *必需* **String**,分配给新控件的 **Name**。 *Container* : *必需* **Object** 引用,指向将承载新控件的窗体、框架或其他容器。 返回新创建的控件,类型为 **Object**。 ### Remove 从集合中移除给定索引或给定名称的控件。 语法:*object*.**Remove** *IndexOrName* *IndexOrName* : *必需* **Variant**,为 **Long** 零基索引或与控件 [**Name**](/official/Reference/CustomControls/#controls) 匹配的 **String**。 ## 迭代 对集合的 `For Each` 循环依次产生每个承载的控件: ```vb Dim ctl As Object For Each ctl In MyForm.Controls ' … Next ``` 支持此功能的隐藏成员是 `_NewEnum`;应用程序代码不会直接调用它。 --- --- url: /en/official/Reference/CustomControls/Framework/CustomControlTimer.md --- # CustomControlTimer class A timer created by [**CustomControlContext.CreateTimer**](/en/official/Reference/CustomControls/Framework/CustomControlContext#createtimer) and owned by the control that created it. The timer raises [**OnTimer**](#ontimer) at the rate given by [**Interval**](#interval), once it has been started by setting [**Enabled**](#enabled) to **True**. The framework returns timers typed as **stdole.IUnknown**; cast to **CustomControlTimer** with `CType(Of CustomControlTimer)(…)` before storing. The control should also declare the field with `WithEvents` so that the **OnTimer** event can be handled. ```vb Private WithEvents InternalTimer As CustomControlTimer Private Sub OnInitialize(ByVal Ctx As CustomControls.CustomControlContext) _ Implements CustomControls.ICustomControl.Initialize Set Me.ControlContext = Ctx Set Me.InternalTimer = CType(Of CustomControlTimer)(Ctx.CreateTimer()) Me.InternalTimer.Interval = 250 Me.InternalTimer.Enabled = True End Sub Private Sub OnTimer() Handles InternalTimer.OnTimer ' fire every 250ms End Sub ``` [**WaynesTimer**](/en/official/Reference/CustomControls/WaynesTimer) wraps a single **CustomControlTimer** and re-exposes its **Interval** / **Enabled** as designer-visible properties. [**WaynesSlider**](/en/official/Reference/CustomControls/WaynesSlider/) uses one as an internal mouse-down auto-repeat timer. ## Properties ### Enabled Whether the timer is currently running. Setting to **True** starts it; setting to **False** stops it. **Boolean**. Syntax: *object*.**Enabled** \[ = *value* ] ### Interval The number of milliseconds between successive [**OnTimer**](#ontimer) events. **Long**. A timer with an interval of 0 never fires. Syntax: *object*.**Interval** \[ = *value* ] Changing **Interval** while the timer is enabled takes effect on the next tick. ## Events ### OnTimer Raised every [**Interval**](#interval) milliseconds while the timer is enabled. Syntax: *object*\_**OnTimer**( ) --- --- url: /zh/official/Reference/CustomControls/Framework/CustomControlTimer.md --- # CustomControlTimer 类 由 [**CustomControlContext.CreateTimer**](/official/Reference/CustomControls/Framework/CustomControlContext#createtimer) 创建的定时器,由创建它的控件拥有。定时器以 [**Interval**](#interval) 指定的速率触发 [**OnTimer**](#ontimer),在将 [**Enabled**](#enabled) 设置为 **True** 启动后开始。 框架以 **stdole.IUnknown** 类型返回定时器;存储前需用 `CType(Of CustomControlTimer)(…)` 转换为 **CustomControlTimer**。控件还应使用 `WithEvents` 声明字段,以便处理 **OnTimer** 事件。 ```vb Private WithEvents InternalTimer As CustomControlTimer Private Sub OnInitialize(ByVal Ctx As CustomControls.CustomControlContext) _ Implements CustomControls.ICustomControl.Initialize Set Me.ControlContext = Ctx Set Me.InternalTimer = CType(Of CustomControlTimer)(Ctx.CreateTimer()) Me.InternalTimer.Interval = 250 Me.InternalTimer.Enabled = True End Sub Private Sub OnTimer() Handles InternalTimer.OnTimer ' fire every 250ms End Sub ``` [**WaynesTimer**](/official/Reference/CustomControls/WaynesTimer) 封装单个 **CustomControlTimer** 并将其 **Interval** / **Enabled** 作为设计器可见属性重新暴露。[**WaynesSlider**](/official/Reference/CustomControls/WaynesSlider/) 使用一个作为内部鼠标按下自动重复定时器。 ## 属性 ### Enabled 定时器当前是否正在运行。设置为 **True** 启动;设置为 **False** 停止。**Boolean**。 语法:*object*.**Enabled** \[ = *value* ] ### Interval 连续 [**OnTimer**](#ontimer) 事件之间的毫秒数。**Long**。间隔为 0 的定时器永不触发。 语法:*object*.**Interval** \[ = *value* ] 在定时器启用时更改 **Interval** 会在下一次计时生效。 ## 事件 ### OnTimer 在定时器启用时每隔 [**Interval**](#interval) 毫秒触发。 语法:*object*\_**OnTimer**( ) --- --- url: /en/official/Reference/CustomControls/Framework/CustomFormContext.md --- # CustomFormContext class The form-class counterpart to [**CustomControlContext**](/en/official/Reference/CustomControls/Framework/CustomControlContext). Extends the base context with **Show** and **Close** --- the operations a top-level form needs that an embedded control does not. [**WaynesForm**](/en/official/Reference/CustomControls/WaynesForm/) receives its context as a [**CustomControlContext**](/en/official/Reference/CustomControls/Framework/CustomControlContext) (because it implements [**ICustomControl**](/en/official/Reference/CustomControls/Framework/ICustomControl)) and casts it to **CustomFormContext** internally so that it can call **Show** from its own **Show** method and **Close** from its **Close** method. ```vb Private Sub OnInitialize(ByVal Ctx As CustomControls.CustomControlContext) _ Implements CustomControls.ICustomControl.Initialize Set Me.ControlContext = CType(Of CustomFormContext)(Ctx) End Sub ``` ## Inherited A **CustomFormContext** includes every member from [**CustomControlContext**](/en/official/Reference/CustomControls/Framework/CustomControlContext) --- [**ChangeFocusedElement**](/en/official/Reference/CustomControls/Framework/CustomControlContext#changefocusedelement), [**CreateTimer**](/en/official/Reference/CustomControls/Framework/CustomControlContext#createtimer), [**GetSerializer**](/en/official/Reference/CustomControls/Framework/CustomControlContext#getserializer), and [**Repaint**](/en/official/Reference/CustomControls/Framework/CustomControlContext#repaint) --- and adds the two form-specific members below. ## Methods ### Close Closes the underlying window. Equivalent to the user clicking the title-bar close button. Application code typically calls [**WaynesForm.Close**](/en/official/Reference/CustomControls/WaynesForm/#close), which in turn calls into this method. Syntax: *object*.**Close** ( ) ### Show Shows the underlying window. Application code typically calls [**WaynesForm.Show**](/en/official/Reference/CustomControls/WaynesForm/#show), which in turn calls into this method. Syntax: *object*.**Show** ( ) --- --- url: /zh/official/Reference/CustomControls/Framework/CustomFormContext.md --- # CustomFormContext 类 [**CustomControlContext**](/official/Reference/CustomControls/Framework/CustomControlContext) 的窗体类对应类。扩展了基上下文的 **Show** 和 **Close**——顶级窗体所需而嵌入控件不需要的操作。 [**WaynesForm**](/official/Reference/CustomControls/WaynesForm/) 作为 [**CustomControlContext**](/official/Reference/CustomControls/Framework/CustomControlContext) 接收其上下文(因为它实现了 [**ICustomControl**](/official/Reference/CustomControls/Framework/ICustomControl)),并在内部转换为 **CustomFormContext**,以便从自己的 **Show** 方法调用 **Show**,从 **Close** 方法调用 **Close**。 ```vb Private Sub OnInitialize(ByVal Ctx As CustomControls.CustomControlContext) _ Implements CustomControls.ICustomControl.Initialize Set Me.ControlContext = CType(Of CustomFormContext)(Ctx) End Sub ``` ## 继承 **CustomFormContext** 包含 [**CustomControlContext**](/official/Reference/CustomControls/Framework/CustomControlContext) 的每个成员——[**ChangeFocusedElement**](/official/Reference/CustomControls/Framework/CustomControlContext#changefocusedelement)、[**CreateTimer**](/official/Reference/CustomControls/Framework/CustomControlContext#createtimer)、[**GetSerializer**](/official/Reference/CustomControls/Framework/CustomControlContext#getserializer) 和 [**Repaint**](/official/Reference/CustomControls/Framework/CustomControlContext#repaint)——并添加以下两个窗体专用成员。 ## 方法 ### Close 关闭底层窗口。等同于用户点击标题栏关闭按钮。应用程序代码通常调用 [**WaynesForm.Close**](/official/Reference/CustomControls/WaynesForm/#close),后者再调用此方法。 语法:*object*.**Close** ( ) ### Show 显示底层窗口。应用程序代码通常调用 [**WaynesForm.Show**](/official/Reference/CustomControls/WaynesForm/#show),后者再调用此方法。 语法:*object*.**Show** ( ) --- --- url: /en/official/Tutorials/CEF/Customize-the-UserDataFolder.md --- # Customize the UserDataFolder At runtime, CEF needs a working folder for the user profile --- cache, cookies, history, local storage, password manager, and the per-instance lock file that prevents two browser processes from sharing the same profile. By default the runtime picks a folder under `%LocalAppData%\twinBASIC_CEF\<ProjectName>\instance-<N>\`, but that default is not always appropriate. A few situations where the default goes wrong: * **Office add-ins**, where the host process is `MSACCESS.EXE` or `EXCEL.EXE` --- the default per-process layout interferes with the host's own profile. * **Kiosk installations**, where the application runs under a low-privilege account that can't write under `%LocalAppData%`. * **Portable deployments**, where all state must live next to the executable on a USB stick or network share. * **Multi-user / hosted scenarios**, where each end-user needs an isolated profile. In every one of these, override the default by assigning [**EnvironmentOptions.UserDataFolder**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#userdatafolder) during the control's [**Create**](/en/official/Reference/CEF/CefBrowser/#create) event: ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.UserDataFolder = _ Environ$("APPDATA") & "\MyApp\CEF\" End Sub ``` The folder is created automatically if it doesn't exist. The path must be writable by the current user --- a read-only path raises the [**Error**](/en/official/Reference/CEF/CefBrowser/#error) event when the helper browser process tries to launch. ## Why the Create event CEF reads the environment options *once*, when the helper browser process is launched. The [**Create**](/en/official/Reference/CEF/CefBrowser/#create) event fires immediately before that launch, which makes it the right place to override the defaults. Assigning [**UserDataFolder**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#userdatafolder) any later (e.g. inside [**Ready**](/en/official/Reference/CEF/CefBrowser/#ready)) has no effect on the running browser. ## Sharing a folder across instances A single user-data folder cannot be opened by two CEF processes at once --- the runtime takes an exclusive lock on it for the lifetime of the browser process. Two **CefBrowser** controls in the *same* application share the helper process and therefore the same lock, so they cooperate fine; two *separate* applications pointing at the same folder collide. When a collision is detected and [**UserDataFolder**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#userdatafolder) is left at its default, the control automatically retries with the next `instance-N` sub-folder. When the host has explicitly set a path, the lock failure instead appears as a CEF initialisation error (*"CEF cache path already locked by another process"*) --- handle it in the [**Error**](/en/official/Reference/CEF/CefBrowser/#error) event: ```vb Private Sub CefBrowser1_Error(ByVal code As Long, ByVal msg As String) If InStr(msg, "already locked") > 0 Then MsgBox "Another copy of this application is already running. " & _ "Close it before opening another window.", _ vbExclamation End If End Sub ``` ## Logging the runtime's output Two related fields on [**EnvironmentOptions**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions) configure the CEF debug log, useful when investigating runtime issues: ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.UserDataFolder = _ Environ$("APPDATA") & "\MyApp\CEF\" CefBrowser1.EnvironmentOptions.LogFilePath = _ Environ$("APPDATA") & "\MyApp\CEF\debug.log" CefBrowser1.EnvironmentOptions.LogSeverity = CefLogWarning End Sub ``` [**LogFilePath**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#logfilepath) is appended to across runs --- rotate or delete it from your own code if it needs to be capped. [**LogSeverity**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#logseverity) controls the threshold; **CefLogDisable** (the default) writes nothing regardless of the path. ## See also * [CefEnvironmentOptions](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions) -- full reference for the pre-creation options. * [Customize the UserDataFolder (WebView2)](/en/official/Tutorials/WebView2/Customize-the-UserDataFolder) -- the same idea applied to the [**WebView2**](/en/official/Reference/WebView2/WebView2/) control. --- --- url: /en/official/Tutorials/WebView2/Customize-the-UserDataFolder.md --- # Customize the UserDataFolder At runtime, WebView2 needs a working folder for storing data used during the session.  By default, a folder will be created in the same folder as your executable file, called `<FileName>.WebView2` (e.g. `MyApp.Exe.WebView2`).  If this folder cannot be created, the WebView2 control will not work (you can catch the controls Error event to determine this at runtime). This default behaviour is not always appropriate.  For example, if you're creating an Addin for Microsoft Access, then you almost certainly will not be allowed to create a folder called `MSACCESS.EXE.WebView2` in the Office sub folder of your systems Program Files folder. It is HIGHLY recommended that you override the default behaviour, and instead provide a path that is considered to be safe to use for storing such data. To override the UserDataFolder path at runtime, handle the Create event of the WebView2 control.  See the example in `Sample 9. ActiveX Control WebView2 + Monaco` here, where we use the `%APPDATA%\Local` system path: ![Create Package](/assets/tbWebView2CreateEvent.DEpSZmxB.png){style="width:80%; height:auto;"} Set the `EnvironmentOptions.UserDataFolder` property to a string containing the output path to use (folder will be created if necessary). --- --- url: /en/official/Reference/CustomControls/Enumerations/Customtate.md --- # Customtate ::: info The name **Customtate** appears to be a typo for "CustomState" preserved from an early draft of the package. The enum is not referenced by any of the eight concrete `Waynes…` controls; the actual minimized / normal / maximized state of a [**WaynesForm**](/en/official/Reference/CustomControls/WaynesForm/) is controlled by the parallel [**WindowState**](/en/official/Reference/CustomControls/Enumerations/WindowState) enum, which has identical members. Treat **Customtate** as reserved. ::: A reserved enumeration with the same three members as [**WindowState**](/en/official/Reference/CustomControls/Enumerations/WindowState). Defined in `Module Constants` of the **CustomControls DESIGNER** library, exported as **Public**, but otherwise unused inside the package. | Constant | Value | Description | |----------|-------|-------------| | **tbNormal** | 0 | Same value as [**WindowState.tbNormal**](/en/official/Reference/CustomControls/Enumerations/WindowState#tbNormal). | | **tbMinimized** | 1 | Same value as [**WindowState.tbMinimized**](/en/official/Reference/CustomControls/Enumerations/WindowState#tbMinimized). | | **tbMaximized** | 2 | Same value as [**WindowState.tbMaximized**](/en/official/Reference/CustomControls/Enumerations/WindowState#tbMaximized). | --- --- url: /zh/official/Reference/CustomControls/Enumerations/Customtate.md --- # Customtate ::: info 名称 **Customtate** 看起来是 "CustomState" 的拼写错误,保留自包的早期草稿。该枚举未被八个具体 `Waynes…` 控件引用;[**WaynesForm**](/official/Reference/CustomControls/WaynesForm/) 的实际最小化/正常/最大化状态由并行的 [**WindowState**](/official/Reference/CustomControls/Enumerations/WindowState) 枚举控制,其成员相同。将 **Customtate** 视为保留。 ::: 与 [**WindowState**](/official/Reference/CustomControls/Enumerations/WindowState) 具有相同三个成员的保留枚举。定义在 **CustomControls DESIGNER** 库的 `Module Constants` 中,以 **Public** 导出,但在包内未被使用。 | 常量 | 值 | 说明 | |------|----|------| | **tbNormal** | 0 | 与 [**WindowState.tbNormal**](/official/Reference/CustomControls/Enumerations/WindowState#tbNormal) 值相同。 | | **tbMinimized** | 1 | 与 [**WindowState.tbMinimized**](/official/Reference/CustomControls/Enumerations/WindowState#tbMinimized) 值相同。 | | **tbMaximized** | 2 | 与 [**WindowState.tbMaximized**](/official/Reference/CustomControls/Enumerations/WindowState#tbMaximized) 值相同。 | --- --- url: /en/official/Reference/VBA/Conversion/CVar.md --- # CVar Coerces an expression to a **Variant**. Syntax: **CVar(** *expression* **)** *expression* : *required* Any valid expression. The acceptable range is the same as **Double** for numerics, and the same as **String** for non-numerics. The return type is **Variant**. ### Example This example uses the **CVar** function to convert an expression to a **Variant**. ```vb Dim MyInt, MyVar MyInt = 4534 ' MyInt is an Integer. MyVar = CVar(MyInt & 000) ' MyVar contains the string "4534000". ``` ### See Also * [CBool](/en/official/Reference/VBA/Conversion/CBool), [CByte](/en/official/Reference/VBA/Conversion/CByte), [CCur](/en/official/Reference/VBA/Conversion/CCur), [CDate](/en/official/Reference/VBA/Conversion/CDate), [CDbl](/en/official/Reference/VBA/Conversion/CDbl), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng), [CSng](/en/official/Reference/VBA/Conversion/CSng), [CStr](/en/official/Reference/VBA/Conversion/CStr) functions * [CVDate](/en/official/Reference/VBA/Conversion/CVDate), [CVErr](/en/official/Reference/VBA/Conversion/CVErr) functions --- --- url: /zh/official/Reference/VBA/Conversion/CVar.md --- # CVar 将表达式强制转换为 **Variant**。 语法:**CVar(** *expression* **)** *expression* : *必需* 任何有效的表达式。数值的可接受范围与 **Double** 相同,非数值的范围与 **String** 相同。 返回类型为 **Variant**。 ### 示例 此示例使用 **CVar** 函数将表达式转换为 **Variant**。 ```vb Dim MyInt, MyVar MyInt = 4534 ' MyInt is an Integer. MyVar = CVar(MyInt & 000) ' MyVar contains the string "4534000". ``` ### 另请参阅 * [CBool](/official/Reference/VBA/Conversion/CBool)、[CByte](/official/Reference/VBA/Conversion/CByte)、[CCur](/official/Reference/VBA/Conversion/CCur)、[CDate](/official/Reference/VBA/Conversion/CDate)、[CDbl](/official/Reference/VBA/Conversion/CDbl)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLng](/official/Reference/VBA/Conversion/CLng)、[CSng](/official/Reference/VBA/Conversion/CSng)、[CStr](/official/Reference/VBA/Conversion/CStr) 函数 * [CVDate](/official/Reference/VBA/Conversion/CVDate)、[CVErr](/official/Reference/VBA/Conversion/CVErr) 函数 --- --- url: /en/official/Reference/VBA/Conversion/CVDate.md --- # CVDate Converts a valid date and time expression to a **Variant** of subtype **Date**. Syntax: **CVDate(** *expression* **)** *expression* : *required* Any expression that can be converted to a date --- a date literal, a date/time string, or a number that falls within the range of acceptable dates. The return type is **Variant** (**Date**). An error occurs if *expression* cannot be converted to a date. **CVDate** is provided for compatibility with previous versions of Visual Basic. The syntax of **CVDate** is identical to [**CDate**](/en/official/Reference/VBA/Conversion/CDate); however, **CVDate** returns a **Variant** whose subtype is **Date** instead of an actual **Date** type. Since **Date** is now an intrinsic type, there is no further need for **CVDate** in new code. The same effect can be achieved by converting an expression to a **Date** with [**CDate**](/en/official/Reference/VBA/Conversion/CDate) and then assigning it to a **Variant**. ### Example ```vb Dim dateString As String dateString = "February 28, 1998" MsgBox "Date value of " & dateString & " is " & CVDate(dateString) ``` ### See Also * [CDate](/en/official/Reference/VBA/Conversion/CDate), [CVar](/en/official/Reference/VBA/Conversion/CVar), [CVErr](/en/official/Reference/VBA/Conversion/CVErr) functions --- --- url: /zh/official/Reference/VBA/Conversion/CVDate.md --- # CVDate 将有效的日期和时间表达式转换为子类型为 **Date** 的 **Variant**。 语法:**CVDate(** *expression* **)** *expression* : *必需* 任何可以转换为日期的表达式——日期字面量、日期/时间字符串,或在可接受日期范围内的数字。 返回类型为 **Variant** (**Date**)。如果 *expression* 无法转换为日期,将发生错误。 提供 **CVDate** 是为了与先前版本的 Visual Basic 兼容。**CVDate** 的语法与 [**CDate**](/official/Reference/VBA/Conversion/CDate) 相同;但是,**CVDate** 返回的是子类型为 **Date** 的 **Variant**,而非实际的 **Date** 类型。由于 **Date** 现在已是内部类型,新代码不再需要 **CVDate**。通过使用 [**CDate**](/official/Reference/VBA/Conversion/CDate) 将表达式转换为 **Date** 然后赋值给 **Variant**,可以达到相同效果。 ### 示例 ```vb Dim dateString As String dateString = "February 28, 1998" MsgBox "Date value of " & dateString & " is " & CVDate(dateString) ``` ### 另请参阅 * [CDate](/official/Reference/VBA/Conversion/CDate)、[CVar](/official/Reference/VBA/Conversion/CVar)、[CVErr](/official/Reference/VBA/Conversion/CVErr) 函数 --- --- url: /en/official/Reference/VBA/Conversion/CVErr.md --- # CVErr Returns a **Variant** of subtype **Error** containing an error number specified by the user. Syntax: **CVErr(** *errornumber* **)** *errornumber* : *required* Any valid error number. Use the **CVErr** function to create user-defined errors in user-created procedures. For example, a function that accepts several arguments and normally returns a string can evaluate the input arguments to ensure they are within an acceptable range. If they aren't, the function is unlikely to return the expected result. In this event, **CVErr** returns an error number that tells the caller what action to take. Note that implicit conversion of an **Error** is not allowed. For example, the return value of **CVErr** cannot be directly assigned to a variable that is not a **Variant**. An explicit conversion (using [**CInt**](/en/official/Reference/VBA/Conversion/CInt), [**CDbl**](/en/official/Reference/VBA/Conversion/CDbl), and so on) of the value returned by **CVErr** can be assigned to a variable of the appropriate data type. ### Example This example uses the **CVErr** function to return a **Variant** whose **VarType** is **vbError** (10). The user-defined function `CalculateDouble` returns an error if the argument passed to it isn't a number. Use **CVErr** to return user-defined errors from user-defined procedures or to defer handling of a run-time error. Use the **IsError** function to test whether the value represents an error. ```vb ' Call CalculateDouble with an error-producing argument. Sub Test() Debug.Print CalculateDouble("345.45robert") End Sub ' Define CalculateDouble Function procedure. Function CalculateDouble(Number) If IsNumeric(Number) Then CalculateDouble = Number * 2 ' Return result. Else CalculateDouble = CVErr(2001) ' Return a user-defined error number. End If End Function ``` ### See Also * [Error](/en/official/Reference/VBA/Conversion/Error) function --- --- url: /zh/official/Reference/VBA/Conversion/CVErr.md --- # CVErr 返回一个子类型为 **Error** 且包含用户指定错误号的 **Variant**。 语法:**CVErr(** *errornumber* **)** *errornumber* : *必需* 任何有效的错误号。 使用 **CVErr** 函数在用户创建的过程中创建用户自定义错误。例如,一个接受多个参数并通常返回字符串的函数可以评估输入参数以确保它们在可接受的范围内。如果不在范围内,函数不太可能返回预期结果。在这种情况下,**CVErr** 返回一个错误号,告诉调用者应该采取什么操作。 注意,不允许对 **Error** 进行隐式转换。例如,**CVErr** 的返回值不能直接赋值给非 **Variant** 的变量。可以使用显式转换(如 [**CInt**](/official/Reference/VBA/Conversion/CInt)、[**CDbl**](/official/Reference/VBA/Conversion/CDbl) 等)将 **CVErr** 返回的值赋给适当数据类型的变量。 ### 示例 此示例使用 **CVErr** 函数返回 **VarType** 为 **vbError** (10) 的 **Variant**。如果传递给用户自定义函数 `CalculateDouble` 的参数不是数字,则返回错误。使用 **CVErr** 从用户自定义过程返回用户自定义错误,或推迟处理运行时错误。使用 **IsError** 函数测试值是否表示错误。 ```vb ' Call CalculateDouble with an error-producing argument. Sub Test() Debug.Print CalculateDouble("345.45robert") End Sub ' Define CalculateDouble Function procedure. Function CalculateDouble(Number) If IsNumeric(Number) Then CalculateDouble = Number * 2 ' Return result. Else CalculateDouble = CVErr(2001) ' Return a user-defined error number. End If End Function ``` ### 另请参阅 * [Error](/official/Reference/VBA/Conversion/Error) 函数 --- --- url: /en/official/Reference/VB/Data.md --- # Data class A **Data** control is a Win32 native control that opens a DAO database and exposes a single recordset to other controls on the form through data binding. It draws a strip of four arrow-shaped buttons --- **Move-First**, **Move-Previous**, **Move-Next**, **Move-Last** --- with a centred [**Caption**](#caption) between them, and lets the user step through the recordset with the mouse. The control is normally placed on a **Form** or **UserControl** at design time. Setting [**DatabaseName**](#databasename) and [**RecordSource**](#recordsource) is enough to populate it; the recordset opens automatically the first time the control is created. The default event is [**Validate**](#validate); the control has no usable default property. ```vb Private Sub Form_Load() With Data1 .DatabaseName = App.Path & "\biblio.mdb" .RecordSource = "Authors" .Caption = "Authors" End With Set Text1.DataSource = Data1 Text1.DataField = "Author" End Sub Private Sub Data1_Reposition() Me.Caption = "Author " & (Data1.Recordset.AbsolutePosition + 1) End Sub ``` ## Connecting to a database [**DefaultType**](#defaulttype) selects the database engine ([**DatabaseTypeConstants**](/en/official/Reference/VBRUN/Constants/DatabaseTypeConstants)): | Constant | Value | Engine | |----------------|-------|------------------------------------------------------| | **vbUseJet** | 2 | Microsoft Jet (the classic VB6 default). | | **vbUseODBC** | 1 | An ODBC data source. | | **vbUseACE** | 3 | The Microsoft Access ACE engine. New in twinBASIC. | [**DatabaseName**](#databasename) gives the path to the database file (for Jet/ACE) or the DSN (for ODBC); [**Connect**](#connect) is the connection string. The Jet-flavoured default `"Access 2000;"` is rewritten to `"MS Access;"` before the database is opened, matching the VB6 behaviour. [**Exclusive**](#exclusive) and [**ReadOnly**](#readonly) are passed through to **OpenDatabase**, and [**Options**](#options) is the DAO option bit-mask. [**DefaultCursorType**](#defaultcursortype) is consulted only when **DefaultType** is **vbUseODBC**. [**RecordSource**](#recordsource) is the table name (or SQL statement) opened against the database, and [**RecordsetType**](#recordsettype) chooses between table, dynaset, and snapshot ([**RecordsetTypeConstants**](/en/official/Reference/VBRUN/Constants/RecordsetTypeConstants)). Calling [**Refresh**](#refresh) reopens the recordset using the current values of these properties --- typically after one of them is changed at run time. The opened objects are exposed read-only as [**Database**](#database) and read/write as [**Recordset**](#recordset). Assigning a new value to **Recordset** disconnects from the current database, adopts the new recordset, and re-binds every dependent control. ## Bound controls Other controls become *data-bound* by setting their **DataSource** to this **Data** control and their **DataField** to the name of a field in [**Recordset**](#recordset). A bound control reads its value from that field whenever the current record changes, and writes user edits back into the field as part of the next save. The **Data** control mediates both directions, raising [**Reposition**](#reposition) after the bound controls have re-synced and [**Validate**](#validate) before any operation that would discard pending edits. ```vb ' At design time these are normally set in the property sheet, ' but they can also be assigned in code: Set txtTitle.DataSource = Data1 txtTitle.DataField = "Title" Set chkInPrint.DataSource = Data1 chkInPrint.DataField = "InPrint" ``` ## Navigation and end-of-file behaviour The four buttons step through the recordset with **MoveFirst**, **MovePrevious**, **MoveNext**, and **MoveLast**. [**BOFAction**](#bofaction) controls what happens when the user moves past the first record ([**DataBOFconstants**](/en/official/Reference/VBRUN/Constants/DataBOFconstants)): **vbMoveFirst** (default) snaps back to the first record; **vbBOF** lets the recordset sit on the BOF marker. [**EOFAction**](#eofaction) controls what happens past the last record ([**DataEOFConstants**](/en/official/Reference/VBRUN/Constants/DataEOFConstants)): **vbMoveLast** (default), **vbEOF**, or **vbAddNew** --- which clears every bound control and starts a new record. ## The validate / save cycle Whenever the control is about to leave the current record --- through a navigation button, a programmatic move, **Refresh**, **Update**, **Delete**, or unloading the form --- it fires [**Validate**](#validate) with an *Action* argument from [**DataValidateConstants**](/en/official/Reference/VBRUN/Constants/DataValidateConstants) and a *Save* flag indicating whether bound controls hold unsaved edits. Setting *Action* to **vbDataActionCancel** (0) cancels the operation and keeps the current record. If *Save* is non-zero on return and the operation proceeds, the bound controls are flushed back into the recordset before the move occurs. [**Reposition**](#reposition) is raised after a successful move, with the bound controls already showing the new record. [**UpdateControls**](#updatecontrols) re-pulls the current record into the bound controls without firing **Reposition**, and [**UpdateRecord**](#updaterecord) is reserved for explicit save-without-move (currently unimplemented). ## Properties ### Appearance Determines how the control's border is drawn by the OS. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). ### BackColor The fill colour of the band behind the [**Caption**](#caption), as an **OLE\_COLOR**. Defaults to the system window-background colour. ### BOFAction Controls what happens when the user moves past the start of the recordset. A member of [**DataBOFconstants**](/en/official/Reference/VBRUN/Constants/DataBOFconstants): **vbMoveFirst** (0, default --- snap back to the first record) or **vbBOF** (1 --- let the recordset sit on the beginning-of-file marker, leaving bound controls cleared). ### Caption The text drawn in the band between the navigation buttons. **String**, default `"Data"`. The string is read directly from the underlying window --- assigning to **Caption** is reflected immediately. Syntax: *object*.**Caption** \[ = *string* ] ### CausesValidation Determines whether the previously focused control's **Validate** event runs before this control receives the focus. **Boolean**, default **True**. This refers to the *previous* control's validation; for the **Data** control's own [**Validate**](#validate) event, see the [validate / save cycle](#the-validate--save-cycle) section above. ### Connect The connection string passed to **OpenDatabase**. **String**, default `"Access 2000;"`. The default value is rewritten to `"MS Access;"` before the database is opened, matching the VB6 behaviour. Used together with [**DatabaseName**](#databasename), [**Exclusive**](#exclusive), [**ReadOnly**](#readonly), and [**Options**](#options). ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a Data control. Always **vbDataControl**. ### Database The currently open DAO database. Read-only --- assign to [**Recordset**](#recordset) or call [**Refresh**](#refresh) to change it. ### DatabaseName The path to the database file (for **vbUseJet** and **vbUseACE**) or the DSN (for **vbUseODBC**). **String**. Combined with [**Connect**](#connect), [**Exclusive**](#exclusive), [**ReadOnly**](#readonly), and [**Options**](#options) to open the database the first time the control is realised, or whenever [**Refresh**](#refresh) is called. ### DefaultCursorType The cursor driver to use when [**DefaultType**](#defaulttype) is **vbUseODBC**. A member of [**DefaultCursorTypeConstants**](/en/official/Reference/VBRUN/Constants/DefaultCursorTypeConstants): **vbUseDefaultCursor** (0, default), **vbUseODBCCursor** (1), or **vbUseServersideCursor** (2). Ignored for Jet and ACE connections. ### DefaultType The database engine to use. A member of [**DatabaseTypeConstants**](/en/official/Reference/VBRUN/Constants/DatabaseTypeConstants): **vbUseJet** (2, default), **vbUseODBC** (1), or **vbUseACE** (3 --- new in twinBASIC, uses the Access ACE engine). Read once when the recordset is opened. ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the control accepts user input. A disabled **Data** control still shows its caption but draws the navigation buttons dimmed and ignores keyboard and mouse interaction. **Boolean**, default **True**. ### EOFAction Controls what happens when the user moves past the end of the recordset. A member of [**DataEOFConstants**](/en/official/Reference/VBRUN/Constants/DataEOFConstants): **vbMoveLast** (0, default --- snap back to the last record), **vbEOF** (1 --- sit on the end-of-file marker), or **vbAddNew** (2 --- clear all bound controls and start a new record ready for editing). ### Exclusive When **True**, the database is opened with exclusive access (no other process or **Data** control can open it). **Boolean**, default **False**. ### Font The **StdFont** used to render [**Caption**](#caption). The convenience properties **FontName**, **FontSize**, **FontBold**, **FontItalic**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. ### ForeColor The text colour for the caption, as an **OLE\_COLOR**. Defaults to the system window-text colour. A disabled control draws the caption in the system grey-text colour instead. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). **Single**. ### hWnd The Win32 window handle for the underlying control, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Read-only at run time. ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Single**. ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### Negotiate ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### OLEDropMode How the control responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on a **Data** control. ### Options A bit-mask of DAO **OpenRecordset** options (e.g. `dbReadOnly`, `dbAppendOnly`, `dbDenyWrite`). **Long**, default `0`. Read once when the recordset is opened. ### Parent A reference to the **Form** (or **UserControl**) that contains this control. Read-only. ### ReadOnly When **True**, the database is opened read-only and edits to bound fields are prevented. **Boolean**, default **False**. Note that this is a reserved word in twinBASIC and must be referenced through a member access (`Data1.ReadOnly`) or escaped (`[ReadOnly]`) in declarations. ### Recordset The DAO recordset currently populating the bound controls. **Object** (a `DAO.Recordset` at run time). Syntax: *object*.**Recordset** \[ = *recordset* ] Reading **Recordset** returns the open recordset, or **Nothing** if the control has not yet connected. Setting **Recordset** with **Set** detaches from the current database, adopts the supplied recordset (and its parent database), copies its [**DatabaseName**](#databasename), [**Connect**](#connect), [**ReadOnly**](#readonly), [**RecordsetType**](#recordsettype), and [**RecordSource**](#recordsource) values back onto the control, re-binds every dependent field, and raises [**Reposition**](#reposition). ### RecordsetType The kind of recordset to open. A member of [**RecordsetTypeConstants**](/en/official/Reference/VBRUN/Constants/RecordsetTypeConstants): **vbRSTypeTable** (0), **vbRSTypeDynaset** (1, default), or **vbRSTypeSnapShot** (2). Read once when the recordset is opened. ### RecordSource The table name, query name, or SQL statement that supplies the recordset. **String**. Read once when the recordset is opened. ### RightToLeft ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### TabIndex The position of the control in the form's TAB-key navigation order. **Long**. ### TabStop Whether the user can reach the control by pressing the **TAB** key. **Boolean**, default **True**. A disabled control is skipped regardless of this setting. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the control. ### Top The vertical distance from the top of the container to the top of the control. **Single**. ### Visible Whether the control is shown. **Boolean**, default **True**. ### VisualStyles Whether the OS theme engine should be used when drawing the navigation buttons. **Boolean**, default **True**. ### WhatsThisHelpID A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### Width The control's width. **Single**. ## Methods ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Typically called from a [**MouseDown**](#mousedown) handler when [**DragMode**](#dragmode) is **vbManual**. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the control, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Saves any pending edits in bound controls, closes the current recordset, and reopens it from the current values of [**DatabaseName**](#databasename), [**Connect**](#connect), [**RecordSource**](#recordsource), [**RecordsetType**](#recordsettype), [**Exclusive**](#exclusive), [**ReadOnly**](#readonly), and [**Options**](#options). Bound controls are then re-synced and [**Reposition**](#reposition) is raised. Syntax: *object*.**Refresh** ### SetFocus Moves the input focus to the control. The control must be both [**Visible**](#visible) and [**Enabled**](#enabled), or run-time error 5 (*Invalid procedure call or argument*) is raised. Syntax: *object*.**SetFocus** ### ShowWhatsThis ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### UpdateControls Re-reads the values of the current record into every bound control, discarding any unsaved edits. Useful as a manual "revert" when validation has rejected an edit. Does not raise [**Reposition**](#reposition). Syntax: *object*.**UpdateControls** ### UpdateRecord ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. In VB6 this saves bound-control edits to the recordset without firing [**Validate**](#validate). Until it is implemented, force a save by calling **Recordset.Update** directly, or trigger a navigation/refresh that goes through the [validate / save cycle](#the-validate--save-cycle). ::: Syntax: *object*.**UpdateRecord** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### Error ::: info Reserved for compatibility with VB6; not currently raised in twinBASIC. In VB6 this event is raised when an asynchronous DAO operation fails outside of a code path the application can intercept; it is not needed for synchronous errors that arise through normal `On Error` handling. ::: Syntax: *object*\_**Error**( *DataErr* **As Integer**, *Response* **As Integer** ) ### Initialize Raised once, immediately after the underlying window is created and before the recordset is opened. Useful for setting [**DatabaseName**](#databasename), [**RecordSource**](#recordsource), or [**Connect**](#connect) from code in time for the first connection. New in twinBASIC --- VB6 had no equivalent on the **Data** control. Syntax: *object*\_**Initialize**( ) ### MouseDown Raised when the user presses any mouse button over the control. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the control. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the control. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseWheel Raised when the mouse wheel turns over the control. New in twinBASIC. Syntax: *object*\_**MouseWheel**( *Delta* **As Integer**, *Horizontal* **As Boolean** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Reposition Raised after the current record has changed --- through a navigation button, a programmatic move on [**Recordset**](#recordset), an assignment to **Recordset**, or [**Refresh**](#refresh) --- and after every bound control has been re-synced to the new record. The point at which to update derived UI such as a "Record *n* of *m*" caption. Syntax: *object*\_**Reposition**( ) ### Resize ::: info Reserved for compatibility with VB6; not currently raised in twinBASIC. ::: Syntax: *object*\_**Resize**( ) ### Validate Raised before any operation that would leave the current record --- a navigation button, a programmatic move, **Update**, **Delete**, **Refresh**, **Find**, an **AddNew**, an explicit close, or unloading the form. **Default event.** Syntax: *object*\_**Validate**( *Action* **As Integer**, *Save* **As Integer** ) *Action* : A member of [**DataValidateConstants**](/en/official/Reference/VBRUN/Constants/DataValidateConstants) identifying the operation that triggered validation. Setting *Action* to **vbDataActionCancel** (0) cancels the operation and keeps the current record. *Save* : Non-zero on entry when bound controls hold unsaved edits. Set it to zero before returning to discard those edits without writing them back; leave it non-zero to flush them into the recordset before the operation proceeds. --- --- url: /zh/official/Reference/VB/Data.md --- # Data 类 **Data**控件是一个Win32原生控件,用于打开DAO数据库并通过数据绑定向窗体上的其他控件公开单个记录集。它绘制一条包含四个箭头按钮的条——**Move-First**、**Move-Previous**、**Move-Next**、**Move-Last**——中间居中显示[**Caption**](#caption),允许用户用鼠标浏览记录集。该控件通常在设计时放置在**Form**或**UserControl**上。设置[**DatabaseName**](#databasename)和[**RecordSource**](#recordsource)即可填充控件;记录集在控件首次创建时自动打开。默认事件是[**Validate**](#validate);该控件没有可用的默认属性。 ```vb Private Sub Form_Load() With Data1 .DatabaseName = App.Path & "\biblio.mdb" .RecordSource = "Authors" .Caption = "Authors" End With Set Text1.DataSource = Data1 Text1.DataField = "Author" End Sub Private Sub Data1_Reposition() Me.Caption = "Author " & (Data1.Recordset.AbsolutePosition + 1) End Sub ``` ## 连接数据库 [**DefaultType**](#defaulttype)选择数据库引擎([**DatabaseTypeConstants**](/official/Reference/VBRUN/Constants/DatabaseTypeConstants)): | 常量 | 值 | 引擎 | |-----------------|-----|--------------------------------------------------| | **vbUseJet** | 2 | Microsoft Jet(经典VB6默认值)。 | | **vbUseODBC** | 1 | ODBC数据源。 | | **vbUseACE** | 3 | Microsoft Access ACE引擎。twinBASIC新增。 | [**DatabaseName**](#databasename)提供数据库文件路径(用于Jet/ACE)或DSN(用于ODBC);[**Connect**](#connect)是连接字符串。Jet风格的默认值`"Access 2000;"`在数据库打开前被改写为`"MS Access;"`,与VB6行为匹配。[**Exclusive**](#exclusive)和[**ReadOnly**](#readonly)传递给**OpenDatabase**,[**Options**](#options)是DAO选项位掩码。[**DefaultCursorType**](#defaultcursortype)仅在**DefaultType**为**vbUseODBC**时使用。 [**RecordSource**](#recordsource)是针对数据库打开的表名(或SQL语句),[**RecordsetType**](#recordsettype)在表、动态集和快照之间选择([**RecordsetTypeConstants**](/official/Reference/VBRUN/Constants/RecordsetTypeConstants))。调用[**Refresh**](#refresh)使用这些属性的当前值重新打开记录集——通常在运行时更改其中一个属性后调用。 打开的对象以只读方式通过[**Database**](#database)公开,以读写方式通过[**Recordset**](#recordset)公开。为**Recordset**赋新值会断开与当前数据库的连接,采用新的记录集,并重新绑定所有依赖控件。 ## 绑定控件 其他控件通过将其**DataSource**设置为此**Data**控件、将其**DataField**设置为[**Recordset**](#recordset)中的字段名来成为*数据绑定*控件。绑定控件在当前记录更改时从该字段读取值,并在下次保存时将用户编辑写回字段。**Data**控件调解双向操作,在绑定控件重新同步后引发[**Reposition**](#reposition),在丢弃未保存编辑的操作之前引发[**Validate**](#validate)。 ```vb ' 设计时这些通常在属性窗口中设置, ' 但也可以在代码中赋值: Set txtTitle.DataSource = Data1 txtTitle.DataField = "Title" Set chkInPrint.DataSource = Data1 chkInPrint.DataField = "InPrint" ``` ## 导航和文件末尾行为 四个按钮通过**MoveFirst**、**MovePrevious**、**MoveNext**和**MoveLast**浏览记录集。[**BOFAction**](#bofaction)控制用户移过第一条记录时发生什么([**DataBOFconstants**](/official/Reference/VBRUN/Constants/DataBOFconstants)):**vbMoveFirst**(默认)跳回第一条记录;**vbBOF**让记录集停留在BOF标记上。[**EOFAction**](#eofaction)控制移过最后一条记录时发生什么([**DataEOFConstants**](/official/Reference/VBRUN/Constants/DataEOFConstants)):**vbMoveLast**(默认)、**vbEOF**或**vbAddNew**——后者清除所有绑定控件并开始新记录。 ## 验证/保存周期 每当控件即将离开当前记录——通过导航按钮、编程移动、**Refresh**、**Update**、**Delete**或卸载窗体——它会引发[**Validate**](#validate),带有来自[**DataValidateConstants**](/official/Reference/VBRUN/Constants/DataValidateConstants)的*Action*参数和指示绑定控件是否持有未保存编辑的*Save*标志。将*Action*设置为**vbDataActionCancel** (0)取消操作并保留当前记录。如果返回时*Save*非零且操作继续执行,绑定控件会在移动发生前将数据写回记录集。 [**Reposition**](#reposition)在成功移动后引发,此时绑定控件已显示新记录。[**UpdateControls**](#updatecontrols)在不引发**Reposition**的情况下将当前记录重新拉取到绑定控件中,[**UpdateRecord**](#updaterecord)保留用于显式保存而不移动(当前未实现)。 ## 属性 ### Appearance 确定操作系统如何绘制控件的边框。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。 ### BackColor [**Caption**](#caption)后面条带的填充颜色,类型为**OLE\_COLOR**。默认为系统窗口背景色。 ### BOFAction 控制用户移过记录集开头时发生什么。[**DataBOFconstants**](/official/Reference/VBRUN/Constants/DataBOFconstants)的成员:**vbMoveFirst** (0,默认——跳回第一条记录)或**vbBOF** (1——让记录集停留在文件开头标记上,绑定控件保持清空)。 ### Caption 导航按钮之间条带中绘制的文本。**String**,默认`"Data"`。字符串直接从底层窗口读取——赋值给**Caption**会立即反映。 语法:*object*.**Caption** \[ = *string* ] ### CausesValidation 确定先前获得焦点的控件的**Validate**事件是否在此控件获得焦点之前运行。**Boolean**,默认**True**。这指的是*先前*控件的验证;关于**Data**控件自身的[**Validate**](#validate)事件,请参见上方的[验证/保存周期](#the-validate--save-cycle)部分。 ### Connect 传递给**OpenDatabase**的连接字符串。**String**,默认`"Access 2000;"`。默认值在数据库打开前被改写为`"MS Access;"`,与VB6行为匹配。与[**DatabaseName**](#databasename)、[**Exclusive**](#exclusive)、[**ReadOnly**](#readonly)和[**Options**](#options)一起使用。 ### ControlType 只读的[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值,将此控件标识为Data控件。始终为**vbDataControl**。 ### Database 当前打开的DAO数据库。只读——赋值给[**Recordset**](#recordset)或调用[**Refresh**](#refresh)来更改。 ### DatabaseName 数据库文件路径(用于**vbUseJet**和**vbUseACE**)或DSN(用于**vbUseODBC**)。**String**。与[**Connect**](#connect)、[**Exclusive**](#exclusive)、[**ReadOnly**](#readonly)和[**Options**](#options)组合使用,在控件首次实例化或调用[**Refresh**](#refresh)时打开数据库。 ### DefaultCursorType 当[**DefaultType**](#defaulttype)为**vbUseODBC**时使用的游标驱动程序。[**DefaultCursorTypeConstants**](/official/Reference/VBRUN/Constants/DefaultCursorTypeConstants)的成员:**vbUseDefaultCursor** (0,默认)、**vbUseODBCCursor** (1)或**vbUseServersideCursor** (2)。Jet和ACE连接忽略此属性。 ### DefaultType 要使用的数据库引擎。[**DatabaseTypeConstants**](/official/Reference/VBRUN/Constants/DatabaseTypeConstants)的成员:**vbUseJet** (2,默认)、**vbUseODBC** (1)或**vbUseACE** (3——twinBASIC新增,使用Access ACE引擎)。在记录集打开时读取一次。 ### DragIcon 控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自动拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual** (0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic** (1)。 ### Enabled 确定控件是否接受用户输入。禁用的**Data**控件仍显示标题,但将导航按钮绘制为变暗状态并忽略键盘和鼠标交互。**Boolean**,默认**True**。 ### EOFAction 控制用户移过记录集末尾时发生什么。[**DataEOFConstants**](/official/Reference/VBRUN/Constants/DataEOFConstants)的成员:**vbMoveLast** (0,默认——跳回最后一条记录)、**vbEOF** (1——停留在文件末尾标记上)或**vbAddNew** (2——清除所有绑定控件并开始新记录以便编辑)。 ### Exclusive 当为**True**时,数据库以独占方式打开(其他进程或**Data**控件无法打开它)。**Boolean**,默认**False**。 ### Font 用于渲染[**Caption**](#caption)的**StdFont**。便捷属性**FontName**、**FontSize**、**FontBold**、**FontItalic**、**FontStrikethru**和**FontUnderline**读写此对象的相应成员。 ### ForeColor 标题的文本颜色,类型为**OLE\_COLOR**。默认为系统窗口文本色。禁用的控件使用系统灰色文本色绘制标题。 ### Height 控件的高度,默认以缇为单位(或使用容器的**ScaleMode**单位)。**Single**。 ### hWnd 底层控件的Win32窗口句柄,类型为**LongPtr**。只读。可用于传递给API函数。 ### Index 当控件是控件数组的一部分时,此实例在数组中的从零开始的**Long**索引。运行时只读。 ### Left 从容器的左边缘到控件左边缘的水平距离。**Single**。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针位于控件上时用作鼠标光标的**StdPicture**。 ### MousePointer 指针位于控件上时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### Negotiate ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: ### OLEDropMode 控件如何响应OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**或**vbOLEDropManual**。**Data**控件不支持自动放置模式。 ### Options DAO **OpenRecordset**选项的位掩码(如`dbReadOnly`、`dbAppendOnly`、`dbDenyWrite`)。**Long**,默认`0`。在记录集打开时读取一次。 ### Parent 对包含此控件的**Form**(或**UserControl**)的引用。只读。 ### ReadOnly 当为**True**时,数据库以只读方式打开,阻止对绑定字段的编辑。**Boolean**,默认**False**。注意这是twinBASIC中的保留字,必须通过成员访问(`Data1.ReadOnly`)或在声明中转义(`[ReadOnly]`)来引用。 ### Recordset 当前填充绑定控件的DAO记录集。**Object**(运行时为`DAO.Recordset`)。 语法:*object*.**Recordset** \[ = *recordset* ] 读取**Recordset**返回打开的记录集,如果控件尚未连接则返回**Nothing**。使用**Set**设置**Recordset**会断开与当前数据库的连接,采用提供的记录集(及其父数据库),将其[**DatabaseName**](#databasename)、[**Connect**](#connect)、[**ReadOnly**](#readonly)、[**RecordsetType**](#recordsettype)和[**RecordSource**](#recordsource)值复制回控件,重新绑定所有依赖字段,并引发[**Reposition**](#reposition)。 ### RecordsetType 要打开的记录集类型。[**RecordsetTypeConstants**](/official/Reference/VBRUN/Constants/RecordsetTypeConstants)的成员:**vbRSTypeTable** (0)、**vbRSTypeDynaset** (1,默认)或**vbRSTypeSnapShot** (2)。在记录集打开时读取一次。 ### RecordSource 提供记录集的表名、查询名或SQL语句。**String**。在记录集打开时读取一次。 ### RightToLeft ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: ### TabIndex 控件在窗体TAB键导航顺序中的位置。**Long**。 ### TabStop 用户是否可以通过按**TAB**键到达控件。**Boolean**,默认**True**。禁用的控件无论此设置如何都会被跳过。 ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### ToolTipText 当用户将鼠标悬停在控件上时作为工具提示显示的多行**String**。 ### Top 从容器顶部到控件顶部的垂直距离。**Single**。 ### Visible 控件是否显示。**Boolean**,默认**True**。 ### VisualStyles 绘制导航按钮时是否使用操作系统主题引擎。**Boolean**,默认**True**。 ### WhatsThisHelpID 标识应用程序帮助文件中"这是什么?"弹出帮助主题的**Long**值。参见[**ShowWhatsThis**](#showwhatsthis)。 ### Width 控件的宽度。**Single**。 ## 方法 ### Drag 开始、完成或取消手动拖放操作。通常在[**DragMode**](#dragmode)为**vbManual**时从[**MouseDown**](#mousedown)处理程序中调用。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel** (0)、**vbBeginDrag** (1,默认)或**vbEndDrag** (2)。 ### Move 在单次调用中重新定位并可选地调整控件大小。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**值。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从控件发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### Refresh 保存绑定控件中所有未保存的编辑,关闭当前记录集,并使用[**DatabaseName**](#databasename)、[**Connect**](#connect)、[**RecordSource**](#recordsource)、[**RecordsetType**](#recordsettype)、[**Exclusive**](#exclusive)、[**ReadOnly**](#readonly)和[**Options**](#options)的当前值重新打开。绑定控件随后重新同步并引发[**Reposition**](#reposition)。 语法:*object*.**Refresh** ### SetFocus 将输入焦点移至控件。控件必须同时[**Visible**](#visible)和[**Enabled**](#enabled),否则引发运行时错误5(*Invalid procedure call or argument*)。 语法:*object*.**SetFocus** ### ShowWhatsThis ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: 以"这是什么?"弹出的方式显示由[**WhatsThisHelpID**](#whatsthishelpid)标识的主题。 语法:*object*.**ShowWhatsThis** ### UpdateControls 将当前记录的值重新读入所有绑定控件,丢弃任何未保存的编辑。当验证拒绝编辑时作为手动"还原"很有用。不引发[**Reposition**](#reposition)。 语法:*object*.**UpdateControls** ### UpdateRecord ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。在VB6中,这会将绑定控件的编辑保存到记录集而不引发[**Validate**](#validate)。在实现之前,可通过直接调用**Recordset.Update**强制保存,或触经过[验证/保存周期](#the-validate--save-cycle)的导航/刷新。 ::: 语法:*object*.**UpdateRecord** ### ZOrder 将控件置于其同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront** (0,默认)或**vbSendToBack** (1)。 ## 事件 ### DragDrop 手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### Error ::: info 保留用于与VB6兼容;目前在twinBASIC中不会引发。在VB6中,当异步DAO操作在应用程序可拦截的代码路径之外失败时引发此事件;通过正常的`On Error`处理产生的同步错误不需要此事件。 ::: 语法:*object*\_**Error**( *DataErr* **As Integer**, *Response* **As Integer** ) ### Initialize 在底层窗口创建后且记录集打开前立即引发一次。用于从代码及时设置[**DatabaseName**](#databasename)、[**RecordSource**](#recordsource)或[**Connect**](#connect)以进行首次连接。twinBASIC新增——VB6在**Data**控件上没有等效功能。 语法:*object*\_**Initialize**( ) ### MouseDown 用户在控件上按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 光标在控件上移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 用户在控件上释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseWheel 鼠标滚轮在控件上滚动时引发。twinBASIC新增。 语法:*object*\_**MouseWheel**( *Delta* **As Integer**, *Horizontal* **As Boolean** ) ### OLECompleteDrag OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 用户将数据放置到目标控件上时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的数据格式时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Reposition 在当前记录更改后引发——通过导航按钮、对[**Recordset**](#recordset)的编程移动、对**Recordset**的赋值或[**Refresh**](#refresh)——且每个绑定控件已重新同步到新记录之后。这是更新派生UI(如"第 *n* 条,共 *m* 条"标题)的时机。 语法:*object*\_**Reposition**( ) ### Resize ::: info 保留用于与VB6兼容;目前在twinBASIC中不会引发。 ::: 语法:*object*\_**Resize**( ) ### Validate 在任何将离开当前记录的操作之前引发——导航按钮、编程移动、**Update**、**Delete**、**Refresh**、**Find**、**AddNew**、显式关闭或卸载窗体。**默认事件。** 语法:*object*\_**Validate**( *Action* **As Integer**, *Save* **As Integer** ) *Action* : [**DataValidateConstants**](/official/Reference/VBRUN/Constants/DataValidateConstants)的成员,标识触发验证的操作。将*Action*设置为**vbDataActionCancel** (0)取消操作并保留当前记录。 *Save* : 进入时,当绑定控件持有未保存编辑时为非零。返回前将其设置为零可丢弃这些编辑而不写回;保持非零可在操作继续执行前将编辑写入记录集。 --- --- url: /en/official/Features/Language/Data-Types.md --- # New Data Types twinBASIC introduces several new data types to enhance your programming capabilities. ## LongPtr Meant primarily to handle pointers, `LongPtr` is a 4-byte (32 bits) signed integer in 32bit mode, and a signed 8-byte integer (64 bits) in 64bit mode. ## LongLong A signed 8-byte (64 bits) integer, ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Note that this type is available in both 32bit and 64bit mode (VBA restricts it to 64bit mode). ## Decimal In twinBASIC, `Decimal` is implemented as a full, regular data type, in addition to use within a `Variant`. This is a 16-byte (128 bits) type which holds a 12-byte (96 bits) integer with variable decimal point scaling and sign bit information. Values range from -79,228,162,514,264,337,593,543,950,335 to 79,228,162,514,264,337,593,543,950,335. ## Type Support All of the datatype management features also exist for these types: * `DefDec`/`DefLngLng`/`DefLongPtr` - Default type declarations * `CDec`/`CLngLng`/`CLongPtr` - Type conversion functions * `vbDecimal`/`vbLongLong`/`vbLongPtr` - Type check constants --- --- url: /en/official/Reference/Data-Types.md --- # Data Types twinBASIC supports fourteen intrinsic data types. They fall into four broad categories: numeric (integer and floating-point), text, date/time, and reference/generic. This page is the canonical lookup for storage size, value range, and the type-declaration suffix where one exists. For the twinBASIC-specific additions to this set --- **LongLong**, **LongPtr**, and **Decimal** as a standalone type --- see [Features → New Data Types](/en/official/Features/Language/Data-Types). *** ## Quick reference | Type | Suffix | Storage | Range | |------|--------|---------|-------| | **Boolean** | (none) | 2 bytes | `True` or `False` | | **Byte** | (none) | 1 byte | 0 to 255 | | **Integer** | `%` | 2 bytes | -32,768 to 32,767 | | **Long** | `&` | 4 bytes | -2,147,483,648 to 2,147,483,647 | | **LongLong** | `^` | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | | **LongPtr** | (none) | 4 bytes (32-bit) / 8 bytes (64-bit) | Same as **Long** or **LongLong** depending on target | | **Single** | `!` | 4 bytes | ±1.401298E-45 to ±3.402823E38 | | **Double** | `#` | 8 bytes | ±4.94065645841246E-324 to ±1.79769313486232E308 | | **Currency** | `@` | 8 bytes | -922,337,203,685,477.5808 to 922,337,203,685,477.5807 | | **Decimal** | (none) | 16 bytes | ±79,228,162,514,264,337,593,543,950,335 (up to 28 decimal places) | | **Date** | (none) | 8 bytes | January 1, 100 to December 31, 9999 | | **String** | `$` | variable | Up to ~2 billion characters | | **Variant** | (none) | 16 bytes (+ heap data) | Any of the above | | **Object** | (none) | 4 bytes (32-bit) / 8 bytes (64-bit) | A COM interface reference | The suffix column lists the character that can optionally follow a literal or identifier to force its type in source code --- for example, `42&` is a **Long** literal, `3.14#` is a **Double**, and `Total!` declares a **Single** variable in a type-implicit context. *** ## Integer types **Boolean** stores `True` (-1) or `False` (0). The runtime treats any non-zero value as `True` when a **Boolean** is expected; only -1 is the canonical `True`. Assigning any non-zero integer to a **Boolean** normalises it to -1. **Byte** is the only unsigned integer type. It holds values 0--255, which makes it the natural element type for byte arrays used in binary I/O and buffer operations. **Integer** holds small signed integers. In most code, **Long** is a better choice: it is no slower on 32-bit hardware and never overflows on values above 32,767. **Integer** is useful when interfacing with structures or APIs that declare 16-bit fields. **Long** is the most common integer type. It covers the full range of Win32 `DWORD` and `int` values and is the default type for index variables and counters. **LongLong** is an 8-byte signed integer available in both 32-bit and 64-bit builds. In VBA it is restricted to 64-bit targets; twinBASIC lifts that restriction and allows **LongLong** in 32-bit projects. Use it when a value can exceed 2,147,483,647 --- file sizes, tick counts, GUIDs, and 64-bit Win32 handles. The suffix `^` marks a **LongLong** literal: `9_000_000_000^`. **LongPtr** changes width with the compilation target: 4 bytes in a 32-bit build, 8 bytes in a 64-bit build. It is the correct type for Win32 handles, window handles (**HWND**), and pointers in `Declare` statements that must work in both modes. It has no literal suffix --- declare the variable with `Dim x As LongPtr` and assign it a numeric expression. Integer overflow raises a run-time error (error 6) by default. Overflow does not wrap silently. *** ## Floating-point types **Single** and **Double** follow the IEEE 754 standard for single-precision and double-precision floating-point respectively. Both can represent `NaN` and `Infinity` as bit patterns, though the VBA runtime raises an error on most operations that would produce them. **Double** is the default type of untyped numeric literals that contain a decimal point (`3.14` is a **Double**). It is accurate to approximately 15--16 significant decimal digits. Choose it for general-purpose floating-point arithmetic. **Single** is accurate to approximately 6--7 significant decimal digits. It is smaller and may be faster in tight loops, but the reduced precision makes it unsuitable for financial or scientific calculations where rounding error matters. **Currency** is a fixed-point type, stored internally as a 64-bit signed integer scaled by 10,000. It avoids the binary rounding errors of IEEE 754 types and carries exactly four decimal places. Use it for monetary values and any calculation where exact decimal rounding is required. *** ## Decimal **Decimal** is a 16-byte type using a 12-byte (96-bit) integer with a variable decimal-point scale and a sign bit. It provides up to 29 significant digits and up to 28 decimal places, making it the highest-precision numeric type available. ::: info In twinBASIC, **Decimal** is available both as a **Variant** subtype (as in VBA) and as a standalone declared type --- `Dim x As Decimal` compiles and runs. The conversion function [**CDec**](/en/official/Reference/VBA/Conversion/CDec) returns a **Decimal** value. ::: *** ## Date **Date** is stored as an IEEE 754 double: the integer part counts days from the epoch (December 30, 1899), and the fractional part represents the time of day (0.0 at midnight, 0.5 at noon). The representable range is January 1, 100 to December 31, 9999. The [**Date**](/en/official/Reference/Core/Date) and [**Time**](/en/official/Reference/Core/Time) properties return the current date and time. [**Now**](/en/official/Reference/VBA/DateTime/Now) returns both combined. Because **Date** is ultimately a **Double**, arithmetic on **Date** values works: adding 1 advances by one day, subtracting two dates gives the number of days between them. *** ## String **String** holds a sequence of Unicode characters, stored internally as a COM `BSTR` (a length-prefixed wide-character string). The length is measured in characters, not bytes; each character is 2 bytes wide (UTF-16 LE). A **String** can hold up to approximately 2 billion characters, limited in practice by available memory. A **String** variable initialises to `vbNullString` (a null `BSTR` pointer), which is distinct from a zero-length string (`""`). Most string operations treat both as empty, but the distinction matters when passing strings to APIs that distinguish a null pointer from an empty buffer. See [**StrPtr**](/en/official/Reference/VBA/Information/StrPtr) for the address of the underlying buffer. Fixed-length strings --- `Dim s As String * 20` --- occupy exactly the specified number of characters, padded with spaces on the right or truncated on assignment. They are useful for fixed-width binary file records. *** ## Variant **Variant** is a tagged union that can hold any of the types in the table above, plus `Null`, `Empty`, and arrays. Its 16-byte header stores a type tag ([**VbVarType**](/en/official/Reference/VBA/Constants/VbVarType)) followed by type-specific data. When the value is a **String**, **Object**, or array, the 8-byte data slot holds a pointer to heap-allocated storage. `Empty` is the default state of an uninitialised **Variant** --- it is distinct from `0`, `""`, `False`, and `Null`. Test for it with [**IsEmpty**](/en/official/Reference/VBA/Information/IsEmpty). `Null` propagates through arithmetic and comparison; use [**IsNull**](/en/official/Reference/VBA/Information/IsNull) to detect it. **Variant** is the required type for parameters and return values in late-bound COM calls, and for any function whose return type varies at runtime. It carries a small overhead on each operation compared to a typed variable because the runtime must check the tag. Prefer typed variables when the type is known at design time. *** ## Object **Object** holds a COM interface reference --- a pointer to a vtable. In a 32-bit build it occupies 4 bytes; in a 64-bit build, 8 bytes. The runtime calls `AddRef` on assignment and `Release` when the variable goes out of scope or is set to `Nothing`. `Nothing` is the zero-valued **Object** reference. Test for it with `If obj Is Nothing Then`. An **Object** variable can hold any COM-compatible object; the runtime resolves member calls through `IDispatch` (late binding). Declaring the variable with a specific class or interface type --- `Dim fs As FileSystemObject` --- enables early binding, which is faster and produces compile-time type checking. *** ### See Also * [New Data Types](/en/official/Features/Language/Data-Types) -- **LongLong**, **LongPtr**, and **Decimal** in depth * [Enumerations](/en/official/Reference/Enumerations) -- index of all enumeration types across all packages * [VbVarType](/en/official/Reference/VBA/Constants/VbVarType) -- **Variant** subtype tag constants * [CDec](/en/official/Reference/VBA/Conversion/CDec), [CLngLng](/en/official/Reference/VBA/Conversion/CLngLng), [CLngPtr](/en/official/Reference/VBA/Conversion/CLngPtr) -- conversion functions for the three extended numeric types --- --- url: /en/official/Reference/VBRUN/Constants/DatabaseTypeConstants.md --- # DatabaseTypeConstants Engine values for the **DefaultType** property of a Data control, choosing which database back-end the control should use. | Constant | Value | Description | |----------|-------|-------------| | **vbUseODBC** | 1 | Connect through ODBC. | | **vbUseJet** | 2 | Connect through the Jet (Access) engine. | | **vbUseACE** | 3 | Connect through the ACE (Access 2007+) engine. *(twinBASIC addition.)* | --- --- url: /zh/official/Reference/VBRUN/Constants/DatabaseTypeConstants.md --- # DatabaseTypeConstants Data控件**DefaultType**属性的引擎值,选择控件应使用的数据库后端。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbUseODBC** | 1 | 通过ODBC连接。 | | **vbUseJet** | 2 | 通过Jet(Access)引擎连接。 | | **vbUseACE** | 3 | 通过ACE(Access 2007+)引擎连接。*(twinBASIC新增)* | --- --- url: /en/official/Reference/VBRUN/Constants/DataBOFconstants.md --- # DataBOFconstants Action values for the **BOFAction** property of a Data control, controlling what happens when the user moves past the start of a recordset. | Constant | Value | Description | |----------|-------|-------------| | **vbMoveFirst** | 0 | Move back to the first record. | | **vbBOF** | 1 | The recordset is positioned at the beginning-of-file marker; navigation past it is disallowed. | --- --- url: /zh/official/Reference/VBRUN/Constants/DataBOFconstants.md --- # DataBOFconstants Data控件**BOFAction**属性的操作值,控制当用户移动到记录集开头之前时发生什么。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbMoveFirst** | 0 | 移回第一条记录。 | | **vbBOF** | 1 | 记录集定位在文件开头标记处;不允许继续向前导航。 | --- --- url: /en/official/Reference/VBRUN/Constants/DataEOFConstants.md --- # DataEOFConstants Action values for the **EOFAction** property of a Data control, controlling what happens when the user moves past the end of a recordset. | Constant | Value | Description | |----------|-------|-------------| | **vbMoveLast** | 0 | Move forward to the last record. | | **vbEOF** | 1 | The recordset is positioned at the end-of-file marker; navigation past it is disallowed. | | **vbAddNew** | 2 | A new record is automatically added so the user can continue past the last existing row. | --- --- url: /zh/official/Reference/VBRUN/Constants/DataEOFConstants.md --- # DataEOFConstants Data控件**EOFAction**属性的操作值,控制当用户移动到记录集末尾之后时发生什么。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbMoveLast** | 0 | 移到最后一条记录。 | | **vbEOF** | 1 | 记录集定位在文件末尾标记处;不允许继续向后导航。 | | **vbAddNew** | 2 | 自动添加新记录,以便用户可以继续越过最后一行。 | --- --- url: /en/official/Reference/VBRUN/Constants/DataErrorConstants.md --- # DataErrorConstants Response values returned from a Data control's **Error** event handler. | Constant | Value | Description | |----------|-------|-------------| | **vbDataErrContinue** | 0 | Continue execution as though no error had occurred. | | **vbDataErrDisplay** | 1 | Display the standard error dialog and let the runtime handle the error. | --- --- url: /zh/official/Reference/VBRUN/Constants/DataErrorConstants.md --- # DataErrorConstants Data控件**Error**事件处理程序返回的响应值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbDataErrContinue** | 0 | 继续执行,如同未发生错误。 | | **vbDataErrDisplay** | 1 | 显示标准错误对话框,让运行时处理错误。 | --- --- url: /en/official/Reference/VBRUN/DataMembers.md --- # DataMembers class The **DataMembers** object is a collection of names that a data source class advertises at design time, so that a consumer binding to the data source can choose which member to bind to. Each entry is a **String** --- the name of a data member the source can supply on request. The data source manages the list directly with [**Add**](#add), [**Remove**](#remove), and [**Clear**](#clear); the design-time environment reads it back through [**Count**](#count), [**Item**](#item), and **For Each** iteration to populate the data member picker. ```vb ' Inside a class whose DataSourceBehavior is set to make it a data source. Private Sub Class_Initialize() UserControl.DataMembers.Add "Customers" UserControl.DataMembers.Add "Orders" UserControl.DataMembers.Add "Invoices" End Sub ``` ## Members ### Add Adds a data member name to the collection. Syntax: *object*.**Add** *DataMember* *object* : *required* An object expression that evaluates to a **DataMembers** object. *DataMember* : *required* A **String** giving the name of the data member to add. Names are usually presented to the consumer verbatim, so they should be readable identifiers. ### Clear Removes every entry from the collection. Syntax: *object*.**Clear** *object* : *required* An object expression that evaluates to a **DataMembers** object. After **Clear**, [**Count**](#count) is `0`. Use this when the set of data members the source can supply changes wholesale --- for example, after the source is reconfigured. ### Count Returns the number of names in the collection. Syntax: *object*.**Count** *object* : *required* An object expression that evaluates to a **DataMembers** object. The value is a **Long**. Valid indexes for [**Item**](#item) run from `1` to **Count**. ### Item Returns a single data member name from the collection. Syntax: *object*.**Item(** *index* **)** *object* : *required* An object expression that evaluates to a **DataMembers** object. *index* : *required* A **Long** giving the one-based position of the name to return. Must be between `1` and [**Count**](#count); otherwise an error occurs. **Item** is the default member of **DataMembers**, so the following lines are equivalent: ```vb name = MyDataMembers.Item(1) name = MyDataMembers(1) ``` The result is a **String**. ### Remove Removes a single entry from the collection, identified either by position or by name. Syntax: *object*.**Remove** *index* *object* : *required* An object expression that evaluates to a **DataMembers** object. *index* : *required* A **Variant** identifying the entry to remove. If numeric, it is treated as a one-based position between `1` and [**Count**](#count). If a **String**, it is matched against the names previously passed to [**Add**](#add). If no entry matches, an error occurs. ### For Each iteration A **DataMembers** object can be iterated with the [**For Each...Next**](/en/official/Reference/Core/For-Each-Next) statement, which yields each name in turn, in the order it was added. The hidden `_NewEnum` member supplies the enumerator and is not called directly from user code. ```vb Dim Name As Variant For Each Name In MyDataMembers Debug.Print Name Next Name ``` --- --- url: /zh/official/Reference/VBRUN/DataMembers.md --- *** title: DataMembers parent: VBRUN Package nav\_order: 11 permalink: /tB/Packages/VBRUN/DataMembers/ ------------------------------------------ # DataMembers 类 **DataMembers**对象是数据源类在设计时公布的名称集合,使绑定到数据源的消费者可以选择要绑定的成员。每个条目是一个**String**——数据源可按需提供的数据成员名称。数据源通过[**Add**](#add)、[**Remove**](#remove)和[**Clear**](#clear)直接管理列表;设计时环境通过[**Count**](#count)、[**Item**](#item)和**For Each**迭代读回列表,以填充数据成员选择器。 `vb ' 在DataSourceBehavior设置为使其成为数据源的类内部。 Private Sub Class_Initialize() UserControl.DataMembers.Add "Customers" UserControl.DataMembers.Add "Orders" UserControl.DataMembers.Add "Invoices" End Sub ` ## 成员 ### Add 向集合添加数据成员名称。 语法:*object*.**Add** *DataMember* *object* : *必需* 求值为**DataMembers**对象的对象表达式。 *DataMember* : *必需* 给出要添加的数据成员名称的**String**。名称通常原样呈现给消费者,因此应为可读的标识符。 ### Clear 从集合中移除所有条目。 语法:*object*.**Clear** *object* : *必需* 求值为**DataMembers**对象的对象表达式。 调用**Clear**后,[**Count**](#count)为�。当数据源可提供的成员集合整体变化时使用——例如,在数据源重新配置后。 ### Count 返回集合中的名称数量。 语法:*object*.**Count** *object* : *必需* 求值为**DataMembers**对象的对象表达式。 值为**Long**。[**Item**](#item)的有效索引范围从1到**Count**。 ### Item 从集合中返回单个数据成员名称。 语法:*object*.**Item(** *index* **)** *object* : *必需* 求值为**DataMembers**对象的对象表达式。 *index* : *必需* 给出要返回的名称从一开始位置的**Long**。必须在1和[**Count**](#count)之间;否则将发生错误。 **Item**是**DataMembers**的默认成员,因此以下两行等效: `vb name = MyDataMembers.Item(1) name = MyDataMembers(1) ` 结果为**String**。 ### Remove 从集合中移除单个条目,按位置或名称标识。 语法:*object*.**Remove** *index* *object* : *必需* 求值为**DataMembers**对象的对象表达式。 *index* : *必需* 标识要移除条目的**Variant**。如果为数值,则视为1到[**Count**](#count)之间从一开始的位置。如果为**String**,则与先前传递给[**Add**](#add)的名称匹配。如果没有匹配的条目,将发生错误。 ### For Each 迭代 **DataMembers**对象可以使用[**For Each...Next**](/official/Reference/Core/For-Each-Next)语句进行迭代,按添加顺序依次产生每个名称。隐藏的\_NewEnum成员提供枚举器,不从用户代码直接调用。 `vb Dim Name As Variant For Each Name In MyDataMembers Debug.Print Name Next Name ` --- --- url: /en/official/Reference/VBRUN/DataObject.md --- # DataObject class A **DataObject** is a container for one piece of information held in one or more clipboard formats --- the same payload represented as plain text, Unicode text, RTF, a bitmap, a list of file paths, and so on. The runtime hands a **DataObject** to clipboard and OLE drag-and-drop operations: the source side fills it with [**SetData**](/en/official/Reference/VBRUN/DataObject/SetData), and the destination side inspects what's available with [**GetFormat**](/en/official/Reference/VBRUN/DataObject/GetFormat) (or [**AvailableFormats**](/en/official/Reference/VBRUN/DataObject/AvailableFormats)) and pulls the bytes out with [**GetData**](/en/official/Reference/VBRUN/DataObject/GetData). A new **DataObject** is created with **New** and starts out empty. ## Storing and retrieving data [**SetData**](/en/official/Reference/VBRUN/DataObject/SetData) places a value into the **DataObject** under a given clipboard format --- typically a value from the **ClipboardConstants** enumeration such as `vbCFText`, `vbCFUnicodeText`, or `vbCFBitmap`. A single object can hold the same logical payload under several formats at once, so consumers with different requirements can each find a representation they understand. ```vb Dim Data As New DataObject Data.SetData "Hello, world!", vbCFText Data.SetData StrConv("Hello, world!", vbUnicode), vbCFUnicodeText ``` [**GetData**](/en/official/Reference/VBRUN/DataObject/GetData) pulls the value back out for a chosen format. [**Clear**](/en/official/Reference/VBRUN/DataObject/Clear) removes every format and value at once --- useful when reusing a single **DataObject** for several operations. twinBASIC also accepts format names as plain strings: [**GetDataByName**](/en/official/Reference/VBRUN/DataObject/GetDataByName) is the string-keyed counterpart to [**GetData**](/en/official/Reference/VBRUN/DataObject/GetData), and is convenient for custom or registered formats whose numeric identifier is not known up front. ## Discovering what's there A consumer that did not place the data itself usually does not know which formats are present. [**GetFormat**](/en/official/Reference/VBRUN/DataObject/GetFormat) returns **True** if a given clipboard format is available, and [**GetFormatByName**](/en/official/Reference/VBRUN/DataObject/GetFormatByName) does the same for a named format. To discover the full set, [**AvailableFormats**](/en/official/Reference/VBRUN/DataObject/AvailableFormats) returns a [**DataObjectFormats**](/en/official/Reference/VBRUN/DataObject/DataObjectFormats) collection of [**DataObjectFormat**](/en/official/Reference/VBRUN/DataObject/DataObjectFormat) descriptors --- each with a `Name`, a `FormatType` from **ClipboardConstants**, and information about how the format is stored. ```vb Dim F As DataObjectFormat For Each F In Data.AvailableFormats Debug.Print F.Name, F.FormatType Next F ``` ::: info [**AvailableFormats**](/en/official/Reference/VBRUN/DataObject/AvailableFormats), [**GetFormatByName**](/en/official/Reference/VBRUN/DataObject/GetFormatByName), and [**GetDataByName**](/en/official/Reference/VBRUN/DataObject/GetDataByName) are twinBASIC additions; they have no equivalent in VB6. ::: ## Files When a **DataObject** contains a list of file paths --- for example, the payload of a Windows shell drag-and-drop --- [**Files**](/en/official/Reference/VBRUN/DataObject/Files) returns a [**DataObjectFiles**](/en/official/Reference/VBRUN/DataObject/DataObjectFiles) collection holding each path as a **String**. ```vb Dim Path As Variant For Each Path In Data.Files Debug.Print Path Next Path ``` ## Members * [AvailableFormats](/en/official/Reference/VBRUN/DataObject/AvailableFormats) -- returns the collection of formats currently held in the **DataObject** *(twinBASIC extension)* * [Clear](/en/official/Reference/VBRUN/DataObject/Clear) -- removes every format and value from the **DataObject** * [Files](/en/official/Reference/VBRUN/DataObject/Files) -- returns the collection of file paths held in the **DataObject** * [GetData](/en/official/Reference/VBRUN/DataObject/GetData) -- returns the value stored under a given clipboard format * [GetDataByName](/en/official/Reference/VBRUN/DataObject/GetDataByName) -- returns the value stored under a given named format *(twinBASIC extension)* * [GetFormat](/en/official/Reference/VBRUN/DataObject/GetFormat) -- returns whether the **DataObject** holds a value in a given clipboard format * [GetFormatByName](/en/official/Reference/VBRUN/DataObject/GetFormatByName) -- returns whether the **DataObject** holds a value in a given named format *(twinBASIC extension)* * [SetData](/en/official/Reference/VBRUN/DataObject/SetData) -- stores a value in the **DataObject** under a given clipboard format --- --- url: /zh/official/Reference/VBRUN/DataObject.md --- # DataObject 类 **DataObject**是一个容器,以一个或多个剪贴板格式保存一条信息——同一有效负载表示为纯文本、Unicode文本、RTF、位图、文件路径列表等。运行时将**DataObject**传递给剪贴板和OLE拖放操作:源端使用[**SetData**](/official/Reference/VBRUN/DataObject/SetData)填充数据,目标端使用[**GetFormat**](/official/Reference/VBRUN/DataObject/GetFormat)(或[**AvailableFormats**](/official/Reference/VBRUN/DataObject/AvailableFormats))检查可用格式,并使用[**GetData**](/official/Reference/VBRUN/DataObject/GetData)提取字节。 新的**DataObject**使用**New**创建,初始为空。 ## 存储和检索数据 [**SetData**](/official/Reference/VBRUN/DataObject/SetData)将值以给定剪贴板格式放入**DataObject**——通常为**ClipboardConstants**枚举中的值,如`vbCFText`、`vbCFUnicodeText`或`vbCFBitmap`。单个对象可以同时以多种格式保存相同的逻辑有效负载,使有不同需求的消费者都能找到其理解的表示。 ```vb Dim Data As New DataObject Data.SetData "Hello, world!", vbCFText Data.SetData StrConv("Hello, world!", vbUnicode), vbCFUnicodeText ``` [**GetData**](/official/Reference/VBRUN/DataObject/GetData)以选定格式取回值。[**Clear**](/official/Reference/VBRUN/DataObject/Clear)一次性移除所有格式和值——在重用单个**DataObject**进行多次操作时很有用。 twinBASIC还接受纯字符串作为格式名称:[**GetDataByName**](/official/Reference/VBRUN/DataObject/GetDataByName)是[**GetData**](/official/Reference/VBRUN/DataObject/GetData)的字符串键对应版本,适用于数字标识符未预先知道的自定义或注册格式。 ## 发现可用内容 未自行放置数据的消费者通常不知道存在哪些格式。[**GetFormat**](/official/Reference/VBRUN/DataObject/GetFormat)在给定剪贴板格式可用时返回**True**,[**GetFormatByName**](/official/Reference/VBRUN/DataObject/GetFormatByName)对命名的格式执行相同操作。要发现完整集合,[**AvailableFormats**](/official/Reference/VBRUN/DataObject/AvailableFormats)返回[**DataObjectFormats**](/official/Reference/VBRUN/DataObject/DataObjectFormats)集合,包含[**DataObjectFormat**](/official/Reference/VBRUN/DataObject/DataObjectFormat)描述符——每个描述符具有Name、来自**ClipboardConstants**的FormatType以及格式存储方式的信息。 ```vb Dim F As DataObjectFormat For Each F In Data.AvailableFormats Debug.Print F.Name, F.FormatType Next F ``` ::: info [**AvailableFormats**](/official/Reference/VBRUN/DataObject/AvailableFormats)、[**GetFormatByName**](/official/Reference/VBRUN/DataObject/GetFormatByName)和[**GetDataByName**](/official/Reference/VBRUN/DataObject/GetDataByName)是twinBASIC新增功能;VB6中没有对应功能。 ::: ## 文件 当**DataObject**包含文件路径列表时——例如Windows Shell拖放的有效负载——[**Files**](/official/Reference/VBRUN/DataObject/Files)返回[**DataObjectFiles**](/official/Reference/VBRUN/DataObject/DataObjectFiles)集合,以**String**形式保存每个路径。 ```vb Dim Path As Variant For Each Path In Data.Files Debug.Print Path Next Path ``` ## 成员 * [AvailableFormats](/official/Reference/VBRUN/DataObject/AvailableFormats) -- 返回**DataObject**中当前保存的格式集合 *(twinBASIC扩展)* * [Clear](/official/Reference/VBRUN/DataObject/Clear) -- 从**DataObject**中移除所有格式和值 * [Files](/official/Reference/VBRUN/DataObject/Files) -- 返回**DataObject**中保存的文件路径集合 * [GetData](/official/Reference/VBRUN/DataObject/GetData) -- 返回以给定剪贴板格式存储的值 * [GetDataByName](/official/Reference/VBRUN/DataObject/GetDataByName) -- 返回以给定命名格式存储的值 *(twinBASIC扩展)* * [GetFormat](/official/Reference/VBRUN/DataObject/GetFormat) -- 返回**DataObject**是否保存给定剪贴板格式的值 * [GetFormatByName](/official/Reference/VBRUN/DataObject/GetFormatByName) -- 返回**DataObject**是否保存给定命名格式的值 *(twinBASIC扩展)* * [SetData](/official/Reference/VBRUN/DataObject/SetData) -- 以给定剪贴板格式在**DataObject**中存储值 --- --- url: /en/official/Reference/VBRUN/DataObject/DataObjectFiles.md --- # DataObjectFiles A **DataObjectFiles** object is the collection of file paths held by a [**DataObject**](/en/official/Reference/VBRUN/DataObject/) --- typically the payload of a Windows shell drag-and-drop, which arrives under the `vbCFFiles` clipboard format. Each element is a fully qualified path stored as a **String**. The collection is reachable through the [**Files**](/en/official/Reference/VBRUN/DataObject/Files) property of the parent **DataObject**. The collection is mutable: the source side of a drag-and-drop or clipboard operation can build a list with [**Add**](#add), and the destination side reads it back with [**Item**](#item) or **For Each** iteration. ## Members ### Add Appends a file path to the collection. Syntax: *object*.**Add** *Filename* \[ **,** *Index* ] *object* : *required* An object expression that evaluates to a **DataObjectFiles** object. *Filename* : *required* A **String** giving the fully qualified path of the file to add. *Index* : *optional* A **Variant** identifying an existing entry. When supplied, the new path is inserted before that entry; if numeric, *Index* is a one-based position between `1` and [**Count**](#count). When omitted, the path is appended to the end. ### Clear Removes every entry from the collection. Syntax: *object*.**Clear** *object* : *required* An object expression that evaluates to a **DataObjectFiles** object. After **Clear**, [**Count**](#count) is `0`. ### Count Returns the number of paths in the collection. Syntax: *object*.**Count** *object* : *required* An object expression that evaluates to a **DataObjectFiles** object. The value is a **Long**. Valid indexes for [**Item**](#item) run from `1` to **Count**. ### Item Returns one path from the collection by its one-based position, as a **String**. Syntax: *object*.**Item(** *Index* **)** *object* : *required* An object expression that evaluates to a **DataObjectFiles** object. *Index* : *required* A **Long** giving the one-based position of the path to return. Must be between `1` and [**Count**](#count); otherwise an error occurs. **Item** is the default member of **DataObjectFiles**, so the following lines are equivalent: ```vb path = Data.Files.Item(1) path = Data.Files(1) ``` ### Remove Removes a single entry from the collection. Syntax: *object*.**Remove** *Index* *object* : *required* An object expression that evaluates to a **DataObjectFiles** object. *Index* : *required* A **Variant** identifying the entry to remove. Numeric values are treated as one-based positions between `1` and [**Count**](#count); string values are matched against the stored paths. If no entry matches, an error occurs. ### For Each iteration A **DataObjectFiles** object can be iterated with the [**For Each...Next**](/en/official/Reference/Core/For-Each-Next) statement, which yields each path in turn, in insertion order. The hidden `_NewEnum` member supplies the enumerator and is not called directly from user code. ```vb Dim Path As Variant For Each Path In Data.Files Debug.Print Path Next Path ``` ### Example This example iterates the file paths in a **DataObjectFiles** collection received from a shell drag-and-drop. ```vb Private Sub Form1_OLEDragDrop(Data As DataObject, Effect As Long, _ Button As Integer, Shift As Integer, _ X As Single, Y As Single) Dim path As Variant For Each path In Data.Files Debug.Print path Next path End Sub ``` ## See Also * [DataObject](/en/official/Reference/VBRUN/DataObject/) * [Files](/en/official/Reference/VBRUN/DataObject/Files) property --- --- url: /zh/official/Reference/VBRUN/DataObject/DataObjectFiles.md --- # DataObjectFiles **DataObjectFiles**对象是[**DataObject**](/official/Reference/VBRUN/DataObject/)保存的文件路径集合——通常是Windows Shell拖放的有效负载,以`vbCFFiles`剪贴板格式到达。每个元素是以**String**保存的完全限定路径。此集合可通过父**DataObject**的[**Files**](/official/Reference/VBRUN/DataObject/Files)属性获取。 此集合是可变的:拖放或剪贴板操作的源端可以使用[**Add**](#add)构建列表,目标端使用[**Item**](#item)或**For Each**迭代读回列表。 ## 成员 ### Add 向集合追加文件路径。 语法:*object*.**Add** *Filename* \[ **,** *Index* ] *object* : *必需* 求值为**DataObjectFiles**对象的对象表达式。 *Filename* : *必需* 给出要添加文件完全限定路径的**String**。 *Index* : *可选* 标识现有条目的**Variant**。提供时,新路径插入到该条目之前;如果为数值,*Index*是`1`到[**Count**](#count)之间从一开始的位置。省略时,路径追加到末尾。 ### Clear 从集合中移除所有条目。 语法:*object*.**Clear** *object* : *必需* 求值为**DataObjectFiles**对象的对象表达式。 调用**Clear**后,[**Count**](#count)为`0`。 ### Count 返回集合中的路径数量。 语法:*object*.**Count** *object* : *必需* 求值为**DataObjectFiles**对象的对象表达式。 值为**Long**。[**Item**](#item)的有效索引范围从`1`到**Count**。 ### Item 按从一开始的位置从集合中返回一个路径,类型为**String**。 语法:*object*.**Item(** *Index* **)** *object* : *必需* 求值为**DataObjectFiles**对象的对象表达式。 *Index* : *必需* 给出要返回路径从一开始位置的**Long**。必须在`1`和[**Count**](#count)之间;否则将发生错误。 **Item**是**DataObjectFiles**的默认成员,因此以下两行等效: ```vb path = Data.Files.Item(1) path = Data.Files(1) ``` ### Remove 从集合中移除单个条目。 语法:*object*.**Remove** *Index* *object* : *必需* 求值为**DataObjectFiles**对象的对象表达式。 *Index* : *必需* 标识要移除条目的**Variant**。数值被视为`1`到[**Count**](#count)之间从一开始的位置;字符串与存储的路径匹配。如果没有匹配的条目,将发生错误。 ### For Each 迭代 **DataObjectFiles**对象可以使用[**For Each...Next**](/official/Reference/Core/For-Each-Next)语句进行迭代,按插入顺序依次产生每个路径。隐藏的`_NewEnum`成员提供枚举器,不从用户代码直接调用。 ```vb Dim Path As Variant For Each Path In Data.Files Debug.Print Path Next Path ``` ### 示例 此示例迭代从Shell拖放接收的**DataObjectFiles**集合中的文件路径。 ```vb Private Sub Form1_OLEDragDrop(Data As DataObject, Effect As Long, _ Button As Integer, Shift As Integer, _ X As Single, Y As Single) Dim path As Variant For Each path In Data.Files Debug.Print path Next path End Sub ``` ## 另见 * [DataObject](/official/Reference/VBRUN/DataObject/) * [Files](/official/Reference/VBRUN/DataObject/Files) 属性 --- --- url: /en/official/Reference/VBRUN/DataObject/DataObjectFormat.md --- # DataObjectFormat A **DataObjectFormat** describes one of the formats a [**DataObject**](/en/official/Reference/VBRUN/DataObject/) holds a value in. The descriptor is the element type yielded when iterating a [**DataObjectFormats**](/en/official/Reference/VBRUN/DataObject/DataObjectFormats) collection, and exposes everything the runtime needs to negotiate a transfer: which clipboard format type the data is in, which aspect (rendering) of it is on offer, and how the bytes are stored. ## Members ### AspectIndex Returns or sets a one-based index into the chosen [**AspectType**](#aspecttype), as a **Long**. Syntax: *object*.**AspectIndex** \[ **=** *value* ] For aspects that have several pages or frames --- for example a multi-page metafile rendered with `dvaspect_Content` --- **AspectIndex** picks which one this descriptor refers to. For single-aspect formats, leave at the default. ### AspectType Returns or sets which rendering of the underlying data the descriptor refers to, as an **AspectTypeConstants** value. Syntax: *object*.**AspectType** \[ **=** *value* ] Common values are `dvaspect_Content` (the data itself), `dvaspect_Thumbnail` (a small preview), `dvaspect_Icon`, and `dvaspect_DocPrint` (a print-time rendering). Most formats only ever expose `dvaspect_Content`. ### FormatType Returns or sets the clipboard format type, as a **ClipboardConstants** value. Syntax: *object*.**FormatType** \[ **=** *value* ] Examples: `vbCFText`, `vbCFUnicodeText`, `vbCFBitmap`, `vbCFFiles`. The same numeric identifier can be passed to [**GetData**](/en/official/Reference/VBRUN/DataObject/GetData) or [**GetFormat**](/en/official/Reference/VBRUN/DataObject/GetFormat). ### Name Returns the human-readable name of the format, as a **String**. Read-only. Syntax: *object*.**Name** For built-in clipboard formats this is a stable label such as `"Text"` or `"Bitmap"`; for formats registered with `RegisterClipboardFormat`, this is the name they were registered under, which is also the key accepted by [**GetDataByName**](/en/official/Reference/VBRUN/DataObject/GetDataByName) and [**GetFormatByName**](/en/official/Reference/VBRUN/DataObject/GetFormatByName). ### StorageType Returns or sets how the data is stored, as a **StorageTypeConstants** value. Syntax: *object*.**StorageType** \[ **=** *value* ] Identifies the medium used to transfer the bytes --- a global memory handle, a file path, an `IStream`, an `IStorage`, a GDI handle, a metafile, or an enhanced metafile. The runtime normally negotiates this automatically; setting it directly is only needed when interoperating with another component that requires a specific medium. ### Example This example reads the name and type of the first available format on a **DataObject**. ```vb If Data.AvailableFormats.Count > 0 Then Dim fmt As DataObjectFormat Set fmt = Data.AvailableFormats.Item(1) Debug.Print fmt.Name & " (" & fmt.FormatType & ")" End If ``` ## See Also * [DataObject](/en/official/Reference/VBRUN/DataObject/) * [DataObjectFormats](/en/official/Reference/VBRUN/DataObject/DataObjectFormats) collection * [AvailableFormats](/en/official/Reference/VBRUN/DataObject/AvailableFormats) method --- --- url: /zh/official/Reference/VBRUN/DataObject/DataObjectFormat.md --- # DataObjectFormat **DataObjectFormat**描述[**DataObject**](/official/Reference/VBRUN/DataObject/)保存值的格式之一。此描述符是迭代[**DataObjectFormats**](/official/Reference/VBRUN/DataObject/DataObjectFormats)集合时产生的元素类型,公开了运行时协商传输所需的一切信息:数据所处的剪贴板格式类型、提供的数据方面(渲染)以及字节的存储方式。 ## 成员 ### AspectIndex 返回或设置所选[**AspectType**](#aspecttype)中从一开始的索引,类型为**Long**。 语法:*object*.**AspectIndex** \[ **=** *value* ] 对于具有多个页面或帧的方面——例如以`dvaspect_Content`渲染的多页图元文件——**AspectIndex**选择此描述符引用的页面或帧。对于单方面格式,保留默认值即可。 ### AspectType 返回或设置描述符引用的底层数据渲染方式,类型为**AspectTypeConstants**值。 语法:*object*.**AspectType** \[ **=** *value* ] 常见值为`dvaspect_Content`(数据本身)、`dvaspect_Thumbnail`(小预览)、`dvaspect_Icon`和`dvaspect_DocPrint`(打印时渲染)。大多数格式只公开`dvaspect_Content`。 ### FormatType 返回或设置剪贴板格式类型,类型为**ClipboardConstants**值。 语法:*object*.**FormatType** \[ **=** *value* ] 示例:`vbCFText`、`vbCFUnicodeText`、`vbCFBitmap`、`vbCFFiles`。同一数字标识符可传递给[**GetData**](/official/Reference/VBRUN/DataObject/GetData)或[**GetFormat**](/official/Reference/VBRUN/DataObject/GetFormat)。 ### Name 返回格式的人类可读名称,类型为**String**。只读。 语法:*object*.**Name** 对于内置剪贴板格式,这是稳定的标签,如`"Text"`或`"Bitmap"`;对于通过`RegisterClipboardFormat`注册的格式,这是注册时使用的名称,也是[**GetDataByName**](/official/Reference/VBRUN/DataObject/GetDataByName)和[**GetFormatByName**](/official/Reference/VBRUN/DataObject/GetFormatByName)接受的键。 ### StorageType 返回或设置数据的存储方式,类型为**StorageTypeConstants**值。 语法:*object*.**StorageType** \[ **=** *value* ] 标识用于传输字节的介质——全局内存句柄、文件路径、`IStream`、`IStorage`、GDI句柄、图元文件或增强型图元文件。运行时通常自动协商此值;仅在需要与要求特定介质的另一组件互操作时才需要直接设置。 ### 示例 此示例读取**DataObject**上第一个可用格式的名称和类型。 ```vb If Data.AvailableFormats.Count > 0 Then Dim fmt As DataObjectFormat Set fmt = Data.AvailableFormats.Item(1) Debug.Print fmt.Name & " (" & fmt.FormatType & ")" End If ``` ## 另见 * [DataObject](/official/Reference/VBRUN/DataObject/) * [DataObjectFormats](/official/Reference/VBRUN/DataObject/DataObjectFormats) 集合 * [AvailableFormats](/official/Reference/VBRUN/DataObject/AvailableFormats) 方法 --- --- url: /en/official/Reference/VBRUN/DataObject/DataObjectFormats.md --- # DataObjectFormats A **DataObjectFormats** object is the read-only collection of [**DataObjectFormat**](/en/official/Reference/VBRUN/DataObject/DataObjectFormat) descriptors a [**DataObject**](/en/official/Reference/VBRUN/DataObject/) currently exposes --- one element per clipboard format the object holds a value in. The collection is returned by the [**AvailableFormats**](/en/official/Reference/VBRUN/DataObject/AvailableFormats) method and is the only general way to discover, at run time, which formats a **DataObject** received from another application has on offer. ## Members ### Count Returns the number of formats in the collection. Syntax: *object*.**Count** *object* : *required* An object expression that evaluates to a **DataObjectFormats** object. The value is a **Long**. Valid indexes for [**Item**](#item) run from `1` to **Count**. ### Item Returns a single format descriptor from the collection by its one-based position. Syntax: *object*.**Item(** *Index* **)** *object* : *required* An object expression that evaluates to a **DataObjectFormats** object. *Index* : *required* A **Long** giving the one-based position of the descriptor to return. Must be between `1` and [**Count**](#count); otherwise an error occurs. The result is a [**DataObjectFormat**](/en/official/Reference/VBRUN/DataObject/DataObjectFormat). ### For Each iteration A **DataObjectFormats** object can be iterated with the [**For Each...Next**](/en/official/Reference/Core/For-Each-Next) statement, which yields each [**DataObjectFormat**](/en/official/Reference/VBRUN/DataObject/DataObjectFormat) in turn. The hidden `_NewEnum` member supplies the enumerator and is not called directly from user code. ```vb Dim F As DataObjectFormat For Each F In Data.AvailableFormats Debug.Print F.Name, F.FormatType Next F ``` ### Example This example lists the name and format type of every format a **DataObject** holds. ```vb Dim fmt As DataObjectFormat For Each fmt In Data.AvailableFormats Debug.Print fmt.Name & " (" & fmt.FormatType & ")" Next fmt ``` ## See Also * [DataObject](/en/official/Reference/VBRUN/DataObject/) * [DataObjectFormat](/en/official/Reference/VBRUN/DataObject/DataObjectFormat) * [AvailableFormats](/en/official/Reference/VBRUN/DataObject/AvailableFormats) method --- --- url: /zh/official/Reference/VBRUN/DataObject/DataObjectFormats.md --- # DataObjectFormats **DataObjectFormats**对象是[**DataObject**](/official/Reference/VBRUN/DataObject/)当前公开的[**DataObjectFormat**](/official/Reference/VBRUN/DataObject/DataObjectFormat)描述符的只读集合——每个元素对应对象保存值的一种剪贴板格式。此集合由[**AvailableFormats**](/official/Reference/VBRUN/DataObject/AvailableFormats)方法返回,是在运行时发现从其他应用程序接收的**DataObject**提供哪些格式的唯一通用方式。 ## 成员 ### Count 返回集合中的格式数量。 语法:*object*.**Count** *object* : *必需* 求值为**DataObjectFormats**对象的对象表达式。 值为**Long**。[**Item**](#item)的有效索引范围从`1`到**Count**。 ### Item 按从一开始的位置从集合中返回单个格式描述符。 语法:*object*.**Item(** *Index* **)** *object* : *必需* 求值为**DataObjectFormats**对象的对象表达式。 *Index* : *必需* 给出要返回描述符从一开始位置的**Long**。必须在`1`和[**Count**](#count)之间;否则将发生错误。 结果为[**DataObjectFormat**](/official/Reference/VBRUN/DataObject/DataObjectFormat)。 ### For Each 迭代 **DataObjectFormats**对象可以使用[**For Each...Next**](/official/Reference/Core/For-Each-Next)语句进行迭代,依次产生每个[**DataObjectFormat**](/official/Reference/VBRUN/DataObject/DataObjectFormat)。隐藏的`_NewEnum`成员提供枚举器,不从用户代码直接调用。 ```vb Dim F As DataObjectFormat For Each F In Data.AvailableFormats Debug.Print F.Name, F.FormatType Next F ``` ### 示例 此示例列出**DataObject**保存的每种格式的名称和格式类型。 ```vb Dim fmt As DataObjectFormat For Each fmt In Data.AvailableFormats Debug.Print fmt.Name & " (" & fmt.FormatType & ")" Next fmt ``` ## 另见 * [DataObject](/official/Reference/VBRUN/DataObject/) * [DataObjectFormat](/official/Reference/VBRUN/DataObject/DataObjectFormat) * [AvailableFormats](/official/Reference/VBRUN/DataObject/AvailableFormats) 方法 --- --- url: /en/official/Reference/VBRUN/Constants/DataValidateConstants.md --- # DataValidateConstants Action codes reported in the *Action* argument of a Data control's **Validate** event, identifying the operation that triggered validation. | Constant | Value | Description | |----------|-------|-------------| | **vbDataActionCancel** | 0 | The pending action is being cancelled. | | **vbDataActionMoveFirst** | 1 | The user is moving to the first record. | | **vbDataActionMovePrevious** | 2 | The user is moving to the previous record. | | **vbDataActionMoveNext** | 3 | The user is moving to the next record. | | **vbDataActionMoveLast** | 4 | The user is moving to the last record. | | **vbDataActionAddNew** | 5 | A new record is being added. | | **vbDataActionUpdate** | 6 | The current record is being updated. | | **vbDataActionDelete** | 7 | The current record is being deleted. | | **vbDataActionFind** | 8 | The user invoked a find operation. | | **vbDataActionBookmark** | 9 | The user is moving to a bookmarked record. | | **vbDataActionClose** | 10 | The recordset is being closed. | | **vbDataActionUnload** | 11 | The form is being unloaded. | --- --- url: /zh/official/Reference/VBRUN/Constants/DataValidateConstants.md --- # DataValidateConstants Data控件**Validate**事件的*Action*参数中报告的操作代码,标识触发验证的操作。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbDataActionCancel** | 0 | 待执行的操作正在被取消。 | | **vbDataActionMoveFirst** | 1 | 用户正在移到第一条记录。 | | **vbDataActionMovePrevious** | 2 | 用户正在移到上一条记录。 | | **vbDataActionMoveNext** | 3 | 用户正在移到下一条记录。 | | **vbDataActionMoveLast** | 4 | 用户正在移到最后一条记录。 | | **vbDataActionAddNew** | 5 | 正在添加新记录。 | | **vbDataActionUpdate** | 6 | 正在更新当前记录。 | | **vbDataActionDelete** | 7 | 正在删除当前记录。 | | **vbDataActionFind** | 8 | 用户调用了查找操作。 | | **vbDataActionBookmark** | 9 | 用户正在移到已添加书签的记录。 | | **vbDataActionClose** | 10 | 记录集正在关闭。 | | **vbDataActionUnload** | 11 | 窗体正在卸载。 | --- --- url: /en/official/Reference/VBA/DateTime/Date.md --- # Date ::: info In twinBASIC, **Date** and **Date$** are implemented as module-level properties, not as functions/statements like they were in VBx. This has no impact on their behavior. These properties still have the syntax and semantics of the Date and Date$ functions and statements in VBx. ::: ## Date Property The behavior of the **Date** property is unchanged by the [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property setting. ### Get Returns a **Variant** containing the current system date. Syntax: **Date** \[ **()** ] #### Example This example uses the **Date** property to return the current system date. ```vb Dim MyDate as Variant MyDate = Date ' MyDate contains the current system date. ``` ### Let Sets the current system date from a value with a Variant or Date type. Syntax: **Date** **=** *date* *date* : *required* For systems running Microsoft Windows 95, the *date* specification must be a date from January 1, 1980, through December 31, 2099. For systems running Microsoft Windows NT, *date* must be a date from January 1, 1980, through December 31, 2079. For the Macintosh, *date* must be a date from January 1, 1904, through February 5, 2040. ::: warning In some versions of Microsoft Windows, including Windows 10 and 11, setting the system date is a privileged operation that requires the process to have relevant permissions. Without those permissions, assignment to **Date** results in a Permission Denied runtime error. ::: #### Example This example uses the **Date** property to set the computer system date. In the development environment, the date literal is displayed in short date format by using the locale settings of the code. ```vb Dim MyDate As Date MyDate = #February 12, 1985# ' Assign a date to a variable. Date= MyDate ' Change system date. ``` ## Date$ Property The behavior of the **Date$** property relies on the [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property setting. If the calendar is Hijri, **Date$** returns or accepts a 10-character string of the form *mm-dd-yyyy*, where *mm* (01--12), *dd* (01--30) and *yyyy* (1400--1523) are the Hijri month, day, and year. The equivalent Gregorian range is Jan 1, 1980, through Dec 31, 2099. ### Get Returns a **String** containing the current system date. Syntax: **Date$** \[ **()** ] #### Example This example uses the **Date** property to return the current system date as a string. ```vb Dim MyDate$ MyDate = Date$ ' MyDate contains the current system date. ``` ### Let Sets the current system date from a string. Syntax: **Date$** **=** *date* *date* : *required* For systems running Microsoft Windows 95, the *date* specification must be a date from January 1, 1980, through December 31, 2099. For systems running Microsoft Windows NT, *date* must be a date from January 1, 1980, through December 31, 2079. For the Macintosh, *date* must be a date from January 1, 1904, through February 5, 2040. ::: warning In some versions of Microsoft Windows, including Windows 10 and 11, setting the system date is a privileged operation that requires the process to have relevant permissions. Without those permissions, assignment to **Date**$ results in a Permission Denied runtime error. ::: #### Example This example uses the **Date$** property to set the computer system date. In the development environment, the date literal is displayed in short date format by using the locale settings of the code. ```vb Dim MyDate$ MyDate = "02-12-1985" ' Assign a date to a variable. Date$ = MyDate ' Change the system date. ``` ### See Also * [Time](/en/official/Reference/VBA/DateTime/Time) property * [Format](/en/official/Reference/VBA/Strings/Format) function * [Now](/en/official/Reference/VBA/DateTime/Now) function --- --- url: /zh/official/Reference/VBA/DateTime/Date.md --- # Date ::: info 在 twinBASIC 中,**Date** 和 **Date$** 实现为模块级属性,而非 VBx 中的函数/语句。这对其行为没有影响。这些属性仍然具有 VBx 中 Date 和 Date$ 函数与语句的语法和语义。 ::: ## Date 属性 **Date** 属性的行为不受 [**Calendar**](/official/Reference/VBA/DateTime/Calendar) 属性设置的影响。 ### Get 返回一个包含当前系统日期的 **Variant**。 语法:**Date** \[ **()** ] #### 示例 此示例使用 **Date** 属性返回当前系统日期。 ```vb Dim MyDate as Variant MyDate = Date ' MyDate contains the current system date. ``` ### Let 从 Variant 或 Date 类型的值设置当前系统日期。 语法:**Date** **=** *date* *date* : *必需* 对于运行 Microsoft Windows 95 的系统,*date* 必须是从 1980 年 1 月 1 日到 2099 年 12 月 31 日的日期。对于运行 Microsoft Windows NT 的系统,*date* 必须是从 1980 年 1 月 1 日到 2079 年 12 月 31 日的日期。对于 Macintosh,*date* 必须是从 1904 年 1 月 1 日到 2040 年 2 月 5 日的日期。 ::: warning 在某些版本的 Microsoft Windows(包括 Windows 10 和 11)中,设置系统日期是一项特权操作,需要进程具有相关权限。如果没有这些权限,对 **Date** 的赋值会导致"权限被拒绝"运行时错误。 ::: #### 示例 此示例使用 **Date** 属性设置计算机系统日期。在开发环境中,日期字面量使用代码的区域设置以短日期格式显示。 ```vb Dim MyDate As Date MyDate = #February 12, 1985# ' Assign a date to a variable. Date= MyDate ' Change system date. ``` ## Date$ 属性 **Date$** 属性的行为依赖于 [**Calendar**](/official/Reference/VBA/DateTime/Calendar) 属性设置。如果日历为回历,**Date$** 返回或接受一个 10 字符的字符串,格式为 *mm-dd-yyyy*,其中 *mm* (01--12)、*dd* (01--30) 和 *yyyy* (1400--1523) 分别为回历月、日和年。等效的公历范围为 1980 年 1 月 1 日到 2099 年 12 月 31 日。 ### Get 返回一个包含当前系统日期的 **String**。 语法:**Date$** \[ **()** ] #### 示例 此示例使用 **Date** 属性以字符串形式返回当前系统日期。 ```vb Dim MyDate$ MyDate = Date$ ' MyDate contains the current system date. ``` ### Let 从字符串设置当前系统日期。 语法:**Date$** **=** *date* *date* : *必需* 对于运行 Microsoft Windows 95 的系统,*date* 必须是从 1980 年 1 月 1 日到 2099 年 12 月 31 日的日期。对于运行 Microsoft Windows NT 的系统,*date* 必须是从 1980 年 1 月 1 日到 2079 年 12 月 31 日的日期。对于 Macintosh,*date* 必须是从 1904 年 1 月 1 日到 2040 年 2 月 5 日的日期。 ::: warning 在某些版本的 Microsoft Windows(包括 Windows 10 和 11)中,设置系统日期是一项特权操作,需要进程具有相关权限。如果没有这些权限,对 **Date**$ 的赋值会导致"权限被拒绝"运行时错误。 ::: #### 示例 此示例使用 **Date$** 属性设置计算机系统日期。在开发环境中,日期字面量使用代码的区域设置以短日期格式显示。 ```vb Dim MyDate$ MyDate = "02-12-1985" ' Assign a date to a variable. Date$ = MyDate ' Change the system date. ``` ### 另请参阅 * [Time](/official/Reference/VBA/DateTime/Time) 属性 * [Format](/official/Reference/VBA/Strings/Format) 函数 * [Now](/official/Reference/VBA/DateTime/Now) 函数 --- --- url: /zh/official/Reference/Core/Date.md --- # Date 语句 date 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/Date.md --- # Date Statement Documentation for the date keyword is not yet available. --- --- url: /en/official/Reference/VBA/DateTime/DateAdd.md --- # DateAdd Returns a **Variant** (**Date**) containing a date to which a specified time interval has been added. Syntax: **DateAdd** ( *interval*, *number*, *date* ) *interval* : *required* String expression that is the interval of time to add. See [Interval settings](#interval-settings). *number* : *required* Numeric expression for the number of intervals to add. It can be positive (to get dates in the future) or negative (to get dates in the past). *date* : *required* **Variant** (**Date**) or literal representing the date to which the interval is added. ### Interval settings | Setting | Description | |----------|-------------| | **yyyy** | Year | | **q** | Quarter | | **m** | Month | | **y** | Day of year | | **d** | Day | | **w** | Weekday | | **ww** | Week | | **h** | Hour | | **n** | Minute | | **s** | Second | To add days to *date*, use Day of Year ("y"), Day ("d"), or Weekday ("w"). ::: info When the "w" interval is used to add days to a date, **DateAdd** adds the total number of days specified, not just workdays (Monday through Friday). ::: **DateAdd** won't return an invalid date. The following example adds one month to January 31: ```vb DateAdd("m", 1, "31-Jan-95") ``` In this case, **DateAdd** returns 28-Feb-95, not 31-Feb-95. If *date* is 31-Jan-96, it returns 29-Feb-96 because 1996 is a leap year. If the calculated date would precede the year 100, an error occurs. If *number* isn't a **Long** value, it is rounded to the nearest whole number before being evaluated. The format of the return value is determined by **Control Panel** settings, not by the format passed in the *date* argument. If the [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri. ### Example This example takes a date and, using the **DateAdd** function, displays a corresponding date a specified number of months in the future. ```vb Dim FirstDate As Date Dim IntervalType As String Dim Number As Integer IntervalType = "m" ' "m" specifies months as interval. FirstDate = InputBox("Enter a date") Number = InputBox("Enter number of months to add") MsgBox "New date: " & DateAdd(IntervalType, Number, FirstDate) ``` ### See Also * [DateDiff](/en/official/Reference/VBA/DateTime/DateDiff), [DatePart](/en/official/Reference/VBA/DateTime/DatePart) functions --- --- url: /zh/official/Reference/VBA/DateTime/DateAdd.md --- # DateAdd 返回一个 **Variant** (**Date**),包含添加了指定时间间隔的日期。 语法:**DateAdd** ( *interval*, *number*, *date* ) *interval* : *必需* 字符串表达式,表示要添加的时间间隔。参见[间隔设置](#interval-settings)。 *number* : *必需* 数值表达式,表示要添加的间隔数。可以为正(获取未来日期)或负(获取过去日期)。 *date* : *必需* **Variant** (**Date**) 或字面量,表示要添加间隔的日期。 ### 间隔设置 | 设置 | 描述 | |------|------| | **yyyy** | 年 | | **q** | 季度 | | **m** | 月 | | **y** | 一年中的天数 | | **d** | 日 | | **w** | 星期几 | | **ww** | 周 | | **h** | 小时 | | **n** | 分钟 | | **s** | 秒 | 要向 *date* 添加天数,请使用一年中的天数 ("y")、日 ("d") 或星期几 ("w")。 ::: info 当使用 "w" 间隔向日期添加天数时,**DateAdd** 添加指定的总天数,而不仅仅是工作日(周一至周五)。 ::: **DateAdd** 不会返回无效日期。以下示例向 1 月 31 日添加一个月: ```vb DateAdd("m", 1, "31-Jan-95") ``` 在这种情况下,**DateAdd** 返回 28-Feb-95,而非 31-Feb-95。如果 *date* 是 31-Jan-96,则返回 29-Feb-96,因为 1996 年是闰年。 如果计算出的日期早于 100 年,将发生错误。 如果 *number* 不是 **Long** 值,则在求值前四舍五入到最接近的整数。 返回值的格式由**控制面板**设置决定,而非 *date* 参数中传递的格式。 如果 [**Calendar**](/official/Reference/VBA/DateTime/Calendar) 属性设置为公历,则提供的日期必须为公历。如果日历为回历,则提供的日期必须为回历。 ### 示例 此示例取一个日期,并使用 **DateAdd** 函数显示指定月数后的对应日期。 ```vb Dim FirstDate As Date Dim IntervalType As String Dim Number As Integer IntervalType = "m" ' "m" specifies months as interval. FirstDate = InputBox("Enter a date") Number = InputBox("Enter number of months to add") MsgBox "New date: " & DateAdd(IntervalType, Number, FirstDate) ``` ### 另请参阅 * [DateDiff](/official/Reference/VBA/DateTime/DateDiff)、[DatePart](/official/Reference/VBA/DateTime/DatePart) 函数 --- --- url: /en/official/Reference/VBA/DateTime/DateDiff.md --- # DateDiff Returns a **Variant** (**Long**) specifying the number of time intervals between two specified dates. Syntax: **DateDiff** ( *interval*, *date1*, *date2* \[, *firstdayofweek* \[, *firstweekofyear* ]] ) *interval* : *required* String expression that is the interval of time used to calculate the difference between *date1* and *date2*. See [Interval settings](#interval-settings). *date1*, *date2* : *required* **Variant** (**Date**). Two dates to use in the calculation. *firstdayofweek* : *optional* A [**VbDayOfWeek**](#firstdayofweek-settings) constant specifying the first day of the week. Defaults to **vbSunday**. *firstweekofyear* : *optional* A [**VbFirstWeekOfYear**](#firstweekofyear-settings) constant specifying the first week of the year. Defaults to **vbFirstJan1**. ### Interval settings | Setting | Description | |----------|-------------| | **yyyy** | Year | | **q** | Quarter | | **m** | Month | | **y** | Day of year | | **d** | Day | | **w** | Weekday | | **ww** | Week | | **h** | Hour | | **n** | Minute | | **s** | Second | ### firstdayofweek settings | Constant | Value | Description | |------------------|-------|-------------------| | **vbUseSystem** | 0 | NLS API setting. | | **vbSunday** | 1 | Sunday (default). | | **vbMonday** | 2 | Monday. | | **vbTuesday** | 3 | Tuesday. | | **vbWednesday** | 4 | Wednesday. | | **vbThursday** | 5 | Thursday. | | **vbFriday** | 6 | Friday. | | **vbSaturday** | 7 | Saturday. | ### firstweekofyear settings | Constant | Value | Description | |---------------------|-------|-----------------------------------------------------------| | **vbUseSystem** | 0 | NLS API setting. | | **vbFirstJan1** | 1 | Week in which January 1 occurs (default). | | **vbFirstFourDays** | 2 | First week that has at least four days in the new year. | | **vbFirstFullWeek** | 3 | First full week of the year. | To calculate the number of days between *date1* and *date2*, use either Day of Year ("y") or Day ("d"). When *interval* is Weekday ("w"), **DateDiff** returns the number of weeks between the two dates. If *date1* falls on a Monday, **DateDiff** counts the number of Mondays until *date2*. It counts *date2* but not *date1*. If *interval* is Week ("ww"), however, **DateDiff** returns the number of calendar weeks between the two dates. It counts the number of Sundays between *date1* and *date2*. **DateDiff** counts *date2* if it falls on a Sunday, but it doesn't count *date1*, even if it does fall on a Sunday. If *date1* refers to a later point in time than *date2*, the function returns a negative number. The *firstdayofweek* argument affects calculations that use the "w" and "ww" interval symbols. If *date1* or *date2* is a date literal, the specified year becomes a permanent part of that date. If *date1* or *date2* is enclosed in double quotation marks and the year is omitted, the current year is inserted each time the expression is evaluated. When comparing December 31 to January 1 of the immediately succeeding year, **DateDiff** for Year ("yyyy") returns 1 even though only a day has elapsed. If the [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri. ### Example This example uses the **DateDiff** function to display the number of days between a given date and today. ```vb Dim TheDate As Date Dim Msg As String TheDate = InputBox("Enter a date") Msg = "Days from today: " & DateDiff("d", Now, TheDate) MsgBox Msg ``` ### See Also * [DateAdd](/en/official/Reference/VBA/DateTime/DateAdd), [DatePart](/en/official/Reference/VBA/DateTime/DatePart) functions --- --- url: /zh/official/Reference/VBA/DateTime/DateDiff.md --- # DateDiff 返回一个 **Variant** (**Long**),指定两个指定日期之间的时间间隔数。 语法:**DateDiff** ( *interval*, *date1*, *date2* \[, *firstdayofweek* \[, *firstweekofyear* ]] ) *interval* : *必需* 字符串表达式,表示用于计算 *date1* 和 *date2* 之间差值的时间间隔。参见[间隔设置](#interval-settings)。 *date1*, *date2* : *必需* **Variant** (**Date**)。用于计算的两个日期。 *firstdayofweek* : *可选* 一个 [**VbDayOfWeek**](#firstdayofweek-settings) 常量,指定一周的第一天。默认为 **vbSunday**。 *firstweekofyear* : *可选* 一个 [**VbFirstWeekOfYear**](#firstweekofyear-settings) 常量,指定一年的第一周。默认为 **vbFirstJan1**。 ### 间隔设置 | 设置 | 描述 | |------|------| | **yyyy** | 年 | | **q** | 季度 | | **m** | 月 | | **y** | 一年中的天数 | | **d** | 日 | | **w** | 星期几 | | **ww** | 周 | | **h** | 小时 | | **n** | 分钟 | | **s** | 秒 | ### firstdayofweek 设置 | 常量 | 值 | 描述 | |------|-----|------| | **vbUseSystem** | 0 | NLS API 设置。 | | **vbSunday** | 1 | 星期日(默认)。 | | **vbMonday** | 2 | 星期一。 | | **vbTuesday** | 3 | 星期二。 | | **vbWednesday** | 4 | 星期三。 | | **vbThursday** | 5 | 星期四。 | | **vbFriday** | 6 | 星期五。 | | **vbSaturday** | 7 | 星期六。 | ### firstweekofyear 设置 | 常量 | 值 | 描述 | |------|-----|------| | **vbUseSystem** | 0 | NLS API 设置。 | | **vbFirstJan1** | 1 | 包含 1 月 1 日的周(默认)。 | | **vbFirstFourDays** | 2 | 新年中至少有四天的第一周。 | | **vbFirstFullWeek** | 3 | 一年的第一个完整周。 | 要计算 *date1* 和 *date2* 之间的天数,请使用一年中的天数 ("y") 或日 ("d")。当 *interval* 为星期几 ("w") 时,**DateDiff** 返回两个日期之间的周数。如果 *date1* 是星期一,**DateDiff** 计算到 *date2* 之间的星期一数量。它计算 *date2* 但不计算 *date1*。 然而,如果 *interval* 为周 ("ww"),**DateDiff** 返回两个日期之间的日历周数。它计算 *date1* 和 *date2* 之间的星期日数量。如果 *date2* 是星期日,**DateDiff** 会将其计入,但不计算 *date1*,即使 *date1* 也是星期日。 如果 *date1* 引用的时间点晚于 *date2*,函数返回一个负数。*firstdayofweek* 参数影响使用 "w" 和 "ww" 间隔符号的计算。 如果 *date1* 或 *date2* 是日期字面量,指定的年份成为该日期的永久部分。如果 *date1* 或 *date2* 用双引号括起且省略了年份,则每次计算表达式时都会插入当前年份。 当比较 12 月 31 日与紧接着下一年的 1 月 1 日时,**DateDiff** 对于年 ("yyyy") 返回 1,即使只过了一天。 如果 [**Calendar**](/official/Reference/VBA/DateTime/Calendar) 属性设置为公历,则提供的日期必须为公历。如果日历为回历,则提供的日期必须为回历。 ### 示例 此示例使用 **DateDiff** 函数显示给定日期与今天之间的天数。 ```vb Dim TheDate As Date Dim Msg As String TheDate = InputBox("Enter a date") Msg = "Days from today: " & DateDiff("d", Now, TheDate) MsgBox Msg ``` ### 另请参阅 * [DateAdd](/official/Reference/VBA/DateTime/DateAdd)、[DatePart](/official/Reference/VBA/DateTime/DatePart) 函数 --- --- url: /en/official/Reference/VBA/DateTime/DatePart.md --- # DatePart Returns a **Variant** (**Integer**) containing the specified part of a given date. Syntax: **DatePart** ( *interval*, *date* \[, *firstdayofweek* \[, *firstweekofyear* ]] ) *interval* : *required* String expression that is the interval of time to return. See [Interval settings](#interval-settings). *date* : *required* **Variant** (**Date**) value to evaluate. *firstdayofweek* : *optional* A [**VbDayOfWeek**](#firstdayofweek-settings) constant specifying the first day of the week. Defaults to **vbSunday**. *firstweekofyear* : *optional* A [**VbFirstWeekOfYear**](#firstweekofyear-settings) constant specifying the first week of the year. Defaults to **vbFirstJan1**. ### Interval settings | Setting | Description | |----------|-------------| | **yyyy** | Year | | **q** | Quarter | | **m** | Month | | **y** | Day of year | | **d** | Day | | **w** | Weekday | | **ww** | Week | | **h** | Hour | | **n** | Minute | | **s** | Second | ### firstdayofweek settings | Constant | Value | Description | |------------------|-------|-------------------| | **vbUseSystem** | 0 | NLS API setting. | | **vbSunday** | 1 | Sunday (default). | | **vbMonday** | 2 | Monday. | | **vbTuesday** | 3 | Tuesday. | | **vbWednesday** | 4 | Wednesday. | | **vbThursday** | 5 | Thursday. | | **vbFriday** | 6 | Friday. | | **vbSaturday** | 7 | Saturday. | ### firstweekofyear settings | Constant | Value | Description | |---------------------|-------|-----------------------------------------------------------| | **vbUseSystem** | 0 | NLS API setting. | | **vbFirstJan1** | 1 | Week in which January 1 occurs (default). | | **vbFirstFourDays** | 2 | First week that has at least four days in the new year. | | **vbFirstFullWeek** | 3 | First full week of the year. | The *firstdayofweek* argument affects calculations that use the "w" and "ww" interval symbols. If *date* is a date literal, the specified year becomes a permanent part of that date. If *date* is enclosed in double quotation marks and the year is omitted, the current year is inserted each time the expression is evaluated. If the [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri. The returned date part is in the time period units of the current calendar. ### Example This example takes a date and, using the **DatePart** function, displays the quarter of the year in which it occurs. ```vb Dim TheDate As Date TheDate = InputBox("Enter a date:") MsgBox "Quarter: " & DatePart("q", TheDate) ``` ### See Also * [DateAdd](/en/official/Reference/VBA/DateTime/DateAdd), [DateDiff](/en/official/Reference/VBA/DateTime/DateDiff) functions --- --- url: /zh/official/Reference/VBA/DateTime/DatePart.md --- # DatePart 返回一个 **Variant** (**Integer**),包含给定日期的指定部分。 语法:**DatePart** ( *interval*, *date* \[, *firstdayofweek* \[, *firstweekofyear* ]] ) *interval* : *必需* 字符串表达式,表示要返回的时间间隔。参见[间隔设置](#interval-settings)。 *date* : *必需* 要计算的 **Variant** (**Date**) 值。 *firstdayofweek* : *可选* 一个 [**VbDayOfWeek**](#firstdayofweek-settings) 常量,指定一周的第一天。默认为 **vbSunday**。 *firstweekofyear* : *可选* 一个 [**VbFirstWeekOfYear**](#firstweekofyear-settings) 常量,指定一年的第一周。默认为 **vbFirstJan1**。 ### 间隔设置 | 设置 | 描述 | |------|------| | **yyyy** | 年 | | **q** | 季度 | | **m** | 月 | | **y** | 一年中的天数 | | **d** | 日 | | **w** | 星期几 | | **ww** | 周 | | **h** | 小时 | | **n** | 分钟 | | **s** | 秒 | ### firstdayofweek 设置 | 常量 | 值 | 描述 | |------|-----|------| | **vbUseSystem** | 0 | NLS API 设置。 | | **vbSunday** | 1 | 星期日(默认)。 | | **vbMonday** | 2 | 星期一。 | | **vbTuesday** | 3 | 星期二。 | | **vbWednesday** | 4 | 星期三。 | | **vbThursday** | 5 | 星期四。 | | **vbFriday** | 6 | 星期五。 | | **vbSaturday** | 7 | 星期六。 | ### firstweekofyear 设置 | 常量 | 值 | 描述 | |------|-----|------| | **vbUseSystem** | 0 | NLS API 设置。 | | **vbFirstJan1** | 1 | 包含 1 月 1 日的周(默认)。 | | **vbFirstFourDays** | 2 | 新年中至少有四天的第一周。 | | **vbFirstFullWeek** | 3 | 一年的第一个完整周。 | *firstdayofweek* 参数影响使用 "w" 和 "ww" 间隔符号的计算。 如果 *date* 是日期字面量,指定的年份成为该日期的永久部分。如果 *date* 用双引号括起且省略了年份,则每次计算表达式时都会插入当前年份。 如果 [**Calendar**](/official/Reference/VBA/DateTime/Calendar) 属性设置为公历,则提供的日期必须为公历。如果日历为回历,则提供的日期必须为回历。返回的日期部分以当前日历的时间段单位表示。 ### 示例 此示例取一个日期,并使用 **DatePart** 函数显示其所在的季度。 ```vb Dim TheDate As Date TheDate = InputBox("Enter a date:") MsgBox "Quarter: " & DatePart("q", TheDate) ``` ### 另请参阅 * [DateAdd](/official/Reference/VBA/DateTime/DateAdd)、[DateDiff](/official/Reference/VBA/DateTime/DateDiff) 函数 --- --- url: /en/official/Reference/VBA/DateTime/DateSerial.md --- # DateSerial Returns a **Variant** (**Date**) for a specified year, month, and day. Syntax: **DateSerial** ( *year*, *month*, *day* ) *year* : *required* **Integer**. Number between 100 and 9999, inclusive, or a numeric expression. *month* : *required* **Integer**. Any numeric expression. *day* : *required* **Integer**. Any numeric expression. To specify a date, such as December 31, 1991, the range of numbers for each **DateSerial** argument should be in the accepted range for the unit (1--31 for days, 1--12 for months). Relative dates can also be specified for each argument by using any numeric expression that represents some number of days, months, or years before or after a certain date. The following example uses numeric expressions instead of absolute date numbers. The **DateSerial** function returns a date that is the day before the first day (`1 - 1`), two months before August (`8 - 2`), 10 years before 1990 (`1990 - 10`) --- in other words, May 31, 1980. When any argument exceeds the accepted range, it increments to the next larger unit as appropriate. For example, 35 days is evaluated as one month and some number of days, depending on where in the year it is applied. If any single argument is outside the range -32,768 to 32,767, an error occurs. If the date specified by the three arguments falls outside the acceptable range of dates, an error occurs. Two-digit years for the *year* argument are interpreted based on user-defined machine settings. The default settings are that values between 0 and 29 are interpreted as the years 2000--2029, and values between 30 and 99 are interpreted as the years 1930--1999. For all other *year* arguments, use a four-digit year. If the [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property setting is Gregorian, the supplied value is assumed to be Gregorian. If the setting is Hijri, the supplied value is assumed to be Hijri, and two-digit *year* values between 0 and 99 are interpreted as the years 1400--1499. ### Example This example uses the **DateSerial** function to return the date for the specified year, month, and day. ```vb Dim MyDate MyDate = DateSerial(1969, 2, 12) ' Returns February 12, 1969. ``` ### See Also * [DateValue](/en/official/Reference/VBA/DateTime/DateValue), [Day](/en/official/Reference/VBA/DateTime/Day), [Month](/en/official/Reference/VBA/DateTime/Month), [Year](/en/official/Reference/VBA/DateTime/Year) functions --- --- url: /zh/official/Reference/VBA/DateTime/DateSerial.md --- # DateSerial 返回指定年、月、日的 **Variant** (**Date**)。 语法:**DateSerial** ( *year*, *month*, *day* ) *year* : *必需* **Integer**。100 到 9999 之间的数字(含),或数值表达式。 *month* : *必需* **Integer**。任何数值表达式。 *day* : *必需* **Integer**。任何数值表达式。 要指定日期(如 1991 年 12 月 31 日),每个 **DateSerial** 参数的数字范围应在单位的可接受范围内(日为 1--31,月为 1--12)。也可以通过使用表示某个日期之前或之后的天数、月数或年数的任何数值表达式来为每个参数指定相对日期。 以下示例使用数值表达式而非绝对日期数字。**DateSerial** 函数返回的日期是第一天之前的一天(`1 - 1`),8 月之前两个月(`8 - 2`),1990 年之前 10 年(`1990 - 10`)——即 1980 年 5 月 31 日。 当任何参数超出可接受范围时,会适当进位到下一个更大的单位。例如,35 天被计算为一个月加上若干天,具体取决于其在一年中的位置。如果任何单个参数超出 -32,768 到 32,767 的范围,将发生错误。如果三个参数指定的日期超出可接受的日期范围,也将发生错误。 *year* 参数的两位数年份根据用户定义的机器设置进行解释。默认设置为 0 到 29 之间的值被解释为 2000--2029 年,30 到 99 之间的值被解释为 1930--1999 年。对于所有其他 *year* 参数,请使用四位数年份。 如果 [**Calendar**](/official/Reference/VBA/DateTime/Calendar) 属性设置为公历,则提供的值假定为公历。如果设置为回历,则提供的值假定为回历,0 到 99 之间的两位数 *year* 值被解释为 1400--1499 年。 ### 示例 此示例使用 **DateSerial** 函数返回指定年、月、日的日期。 ```vb Dim MyDate MyDate = DateSerial(1969, 2, 12) ' Returns February 12, 1969. ``` ### 另请参阅 * [DateValue](/official/Reference/VBA/DateTime/DateValue)、[Day](/official/Reference/VBA/DateTime/Day)、[Month](/official/Reference/VBA/DateTime/Month)、[Year](/official/Reference/VBA/DateTime/Year) 函数 --- --- url: /zh/official/Reference/VBA/DateTime.md --- # DateTime 模块 **DateTime** 模块将读取系统时钟、从组件构建 **Date** 值、从字符串解析日期、将日期拆分为组件以及按指定单位向前或向后移动日期的过程组合在一起。一个设置项——[**Calendar**](/official/Reference/VBA/DateTime/Calendar) 属性——即可在整个模块中切换公历和回历。 ## 读取系统时钟 [**Now**](/official/Reference/VBA/DateTime/Now) 返回当前系统日期*和*时间,作为一个 **Date** 子类型的 **Variant**;[**Date**](/official/Reference/VBA/DateTime/Date) 仅返回日期部分,[**Time**](/official/Reference/VBA/DateTime/Time) 仅返回时间部分。后两者各有一个带 `$` 后缀的兄弟——**Date$** 和 **Time$**——它们以格式化的 **String** 而非 **Date** 返回相同的值。这四个属性也都是可写的:对它们赋值会更改系统时钟,但受操作系统权限要求限制。 ::: info 在 twinBASIC 中,**Date**、**Date$**、**Time** 和 **Time$** 被实现为模块级属性,而非 VBx 中的函数/语句。语法和语义保持不变。 ::: [**Timer**](/official/Reference/VBA/DateTime/Timer) 返回一个 **Single**,给出自午夜以来经过的秒数(含小数精度),是测量运行中经过时间的常用方法。 ```vb Dim Started As Single Started = Timer ' ... do some work ... Debug.Print "Elapsed: " & (Timer - Started) & " seconds" ``` ## 从组件构建日期和时间 [**DateSerial**](/official/Reference/VBA/DateTime/DateSerial) 从年、月、日参数构建一个 **Date**;[**TimeSerial**](/official/Reference/VBA/DateTime/TimeSerial) 从小时、分钟、秒构建。两者都支持超范围参数的进位——将 13 作为月份会进位到下一年,将 75 作为分钟会进位到下一小时——这使它们非常适合用组件的简单算术来表达相对日期。 ```vb Dim FirstOfNextMonth As Date FirstOfNextMonth = DateSerial(Year(Now), Month(Now) + 1, 1) ``` [**DateValue**](/official/Reference/VBA/DateTime/DateValue) 以系统短日期格式从字符串解析日期——可识别数字形式和明确的月份名称——并丢弃任何时间部分。[**TimeValue**](/official/Reference/VBA/DateTime/TimeValue) 是时间字符串的相应解析器;它丢弃任何日期部分。对于源自源代码中日期字面量的值,`#...#` 语法通常比任一解析器更合适。 ## 提取日期的部分 单组件访问器各自返回 **Date** 的一部分作为 **Integer**:[**Year**](/official/Reference/VBA/DateTime/Year)、[**Month**](/official/Reference/VBA/DateTime/Month)、[**Day**](/official/Reference/VBA/DateTime/Day)、[**Weekday**](/official/Reference/VBA/DateTime/Weekday)、[**Hour**](/official/Reference/VBA/DateTime/Hour)、[**Minute**](/official/Reference/VBA/DateTime/Minute) 和 [**Second**](/official/Reference/VBA/DateTime/Second)。[**DatePart**](/official/Reference/VBA/DateTime/DatePart) 泛化了相同的思路,以字符串间隔代码(`"yyyy"`、`"q"`、`"m"`、`"d"`、...)作为参数来选择要提取的部分——当单位本身是参数时很有用。 ```vb Dim D As Date D = #2/12/1969# Debug.Print Year(D) ' 1969 Debug.Print Month(D) ' 2 Debug.Print Day(D) ' 12 Debug.Print Weekday(D) ' 4 — Wednesday ``` ## 日期算术 [**DateAdd**](/official/Reference/VBA/DateTime/DateAdd) 将日期按选定的间隔数偏移——年、季度、月、周、日、小时、分钟或秒——考虑日历不规则性(月份长度不同、闰年),并在字面日值无效时钳制到目标月份的最后一天。[**DateDiff**](/official/Reference/VBA/DateTime/DateDiff) 执行逆操作:返回两个日期之间的完整间隔数。两者都使用与 **DatePart** 相同的字符串间隔代码。 ```vb Debug.Print DateAdd("m", 1, #1/31/2026#) ' 2/28/2026 — clamped to last day of February Debug.Print DateDiff("d", #1/1/2026#, #5/9/2026#) ' 128 ``` ## 日历选择 [**Calendar**](/official/Reference/VBA/DateTime/Calendar) 属性选择模块其余部分使用的日历——**vbCalGreg**(公历,默认)或 **vbCalHijri**(回历)。该设置控制 **Date$** 如何格式化系统日期、**DateSerial**、**DateValue**、**DateAdd** 和 **DateDiff** 的参数如何解释,以及 **DatePart**、**Year**、**Month**、**Day** 和 **Weekday** 返回的部分如何报告。 ## 成员 * [Calendar](/official/Reference/VBA/DateTime/Calendar) -- 返回或设置日历类型(公历或回历) * [Date](/official/Reference/VBA/DateTime/Date) -- 设置或返回当前系统日期 * [DateAdd](/official/Reference/VBA/DateTime/DateAdd) -- 向日期添加时间间隔 * [DateDiff](/official/Reference/VBA/DateTime/DateDiff) -- 返回两个日期之间的时间间隔数 * [DatePart](/official/Reference/VBA/DateTime/DatePart) -- 返回给定日期的指定部分 * [DateSerial](/official/Reference/VBA/DateTime/DateSerial) -- 返回指定年、月、日的日期 * [DateValue](/official/Reference/VBA/DateTime/DateValue) -- 将字符串转换为日期 * [Day](/official/Reference/VBA/DateTime/Day) -- 返回日期值中的月份中的日 * [Hour](/official/Reference/VBA/DateTime/Hour) -- 返回时间值中的小时 * [Minute](/official/Reference/VBA/DateTime/Minute) -- 返回时间值中的分钟 * [Month](/official/Reference/VBA/DateTime/Month) -- 返回日期值中的月份 * [Now](/official/Reference/VBA/DateTime/Now) -- 返回当前系统日期和时间 * [Second](/official/Reference/VBA/DateTime/Second) -- 返回时间值中的秒 * [Time](/official/Reference/VBA/DateTime/Time) -- 设置或返回当前系统时间 * [Timer](/official/Reference/VBA/DateTime/Timer) -- 返回自午夜以来经过的秒数 * [TimeSerial](/official/Reference/VBA/DateTime/TimeSerial) -- 返回指定小时、分钟和秒的时间 * [TimeValue](/official/Reference/VBA/DateTime/TimeValue) -- 将字符串转换为时间 * [Weekday](/official/Reference/VBA/DateTime/Weekday) -- 返回日期值中的星期几 * [Year](/official/Reference/VBA/DateTime/Year) -- 返回日期值中的年份 --- --- url: /en/official/Reference/VBA/DateTime.md --- # DateTime module The **DateTime** module groups together the procedures for reading the system clock, building **Date** values from their components, parsing them out of strings, taking them apart again, and shifting them forward or backward by a chosen unit. A single setting --- the [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property --- switches the whole module between the Gregorian and Hijri calendars. ## Reading the system clock [**Now**](/en/official/Reference/VBA/DateTime/Now) returns the current system date *and* time as a single **Variant** of subtype **Date**; [**Date**](/en/official/Reference/VBA/DateTime/Date) returns just the date portion and [**Time**](/en/official/Reference/VBA/DateTime/Time) just the time portion. Each of the latter two has a `$`-suffixed sibling --- **Date$** and **Time$** --- that returns the same value as a formatted **String** rather than a **Date**. All four are also writable: assigning to them changes the system clock, subject to the operating system's privilege requirements. ::: info In twinBASIC, **Date**, **Date$**, **Time**, and **Time$** are implemented as module-level properties rather than the functions/statements they were in VBx. The syntax and semantics are otherwise unchanged. ::: [**Timer**](/en/official/Reference/VBA/DateTime/Timer) returns a **Single** giving the number of seconds --- with fractional precision --- elapsed since midnight, and is the conventional way to measure elapsed time within a run. ```vb Dim Started As Single Started = Timer ' ... do some work ... Debug.Print "Elapsed: " & (Timer - Started) & " seconds" ``` ## Building dates and times from components [**DateSerial**](/en/official/Reference/VBA/DateTime/DateSerial) builds a **Date** from year, month, and day arguments; [**TimeSerial**](/en/official/Reference/VBA/DateTime/TimeSerial) builds one from hour, minute, and second. Both honour out-of-range arguments by carrying --- passing 13 as the month rolls into the next year, and passing 75 as the minute rolls into the next hour --- which makes them well-suited to expressing relative dates as plain arithmetic on the components. ```vb Dim FirstOfNextMonth As Date FirstOfNextMonth = DateSerial(Year(Now), Month(Now) + 1, 1) ``` [**DateValue**](/en/official/Reference/VBA/DateTime/DateValue) parses a date out of a string in the system's short date format --- recognising both numeric forms and unambiguous month names --- and discards any time portion. [**TimeValue**](/en/official/Reference/VBA/DateTime/TimeValue) is the corresponding parser for time strings; it discards any date portion. For values that originate as date literals in source code, the surrounding `#...#` syntax is usually a better fit than either parser. ## Extracting parts of a date The single-component accessors each return one part of a **Date** as an **Integer**: [**Year**](/en/official/Reference/VBA/DateTime/Year), [**Month**](/en/official/Reference/VBA/DateTime/Month), [**Day**](/en/official/Reference/VBA/DateTime/Day), [**Weekday**](/en/official/Reference/VBA/DateTime/Weekday), [**Hour**](/en/official/Reference/VBA/DateTime/Hour), [**Minute**](/en/official/Reference/VBA/DateTime/Minute), and [**Second**](/en/official/Reference/VBA/DateTime/Second). [**DatePart**](/en/official/Reference/VBA/DateTime/DatePart) generalises the same idea, taking the chosen part as a string interval code (`"yyyy"`, `"q"`, `"m"`, `"d"`, ...) --- useful when the unit itself is a parameter. ```vb Dim D As Date D = #2/12/1969# Debug.Print Year(D) ' 1969 Debug.Print Month(D) ' 2 Debug.Print Day(D) ' 12 Debug.Print Weekday(D) ' 4 — Wednesday ``` ## Date arithmetic [**DateAdd**](/en/official/Reference/VBA/DateTime/DateAdd) shifts a date by a chosen number of intervals --- years, quarters, months, weeks, days, hours, minutes, or seconds --- taking calendar irregularities (varying month lengths, leap years) into account, and clamping to the last day of the target month when a literal day-of-month would be invalid. [**DateDiff**](/en/official/Reference/VBA/DateTime/DateDiff) does the inverse: it returns the count of whole intervals between two dates. Both share the same string interval codes used by **DatePart**. ```vb Debug.Print DateAdd("m", 1, #1/31/2026#) ' 2/28/2026 — clamped to last day of February Debug.Print DateDiff("d", #1/1/2026#, #5/9/2026#) ' 128 ``` ## Calendar selection The [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property selects the calendar --- **vbCalGreg** (Gregorian, the default) or **vbCalHijri** (Hijri) --- used by the rest of the module. The setting controls how **Date$** formats the system date, how arguments to **DateSerial**, **DateValue**, **DateAdd**, and **DateDiff** are interpreted, and how the parts returned by **DatePart**, **Year**, **Month**, **Day**, and **Weekday** are reported. ## Members * [Calendar](/en/official/Reference/VBA/DateTime/Calendar) -- returns or sets the calendar type (Gregorian or Hijri) * [Date](/en/official/Reference/VBA/DateTime/Date) -- sets or returns the current system date * [DateAdd](/en/official/Reference/VBA/DateTime/DateAdd) -- adds a time interval to a date * [DateDiff](/en/official/Reference/VBA/DateTime/DateDiff) -- returns the number of time intervals between two dates * [DatePart](/en/official/Reference/VBA/DateTime/DatePart) -- returns a specified part of a given date * [DateSerial](/en/official/Reference/VBA/DateTime/DateSerial) -- returns a date for a specified year, month, and day * [DateValue](/en/official/Reference/VBA/DateTime/DateValue) -- converts a string to a date * [Day](/en/official/Reference/VBA/DateTime/Day) -- returns the day of the month from a date value * [Hour](/en/official/Reference/VBA/DateTime/Hour) -- returns the hour of the day from a time value * [Minute](/en/official/Reference/VBA/DateTime/Minute) -- returns the minute of the hour from a time value * [Month](/en/official/Reference/VBA/DateTime/Month) -- returns the month of the year from a date value * [Now](/en/official/Reference/VBA/DateTime/Now) -- returns the current system date and time * [Second](/en/official/Reference/VBA/DateTime/Second) -- returns the second of the minute from a time value * [Time](/en/official/Reference/VBA/DateTime/Time) -- sets or returns the current system time * [Timer](/en/official/Reference/VBA/DateTime/Timer) -- returns the number of seconds elapsed since midnight * [TimeSerial](/en/official/Reference/VBA/DateTime/TimeSerial) -- returns a time for a specific hour, minute, and second * [TimeValue](/en/official/Reference/VBA/DateTime/TimeValue) -- converts a string to a time * [Weekday](/en/official/Reference/VBA/DateTime/Weekday) -- returns the day of the week from a date value * [Year](/en/official/Reference/VBA/DateTime/Year) -- returns the year from a date value --- --- url: /en/official/Reference/VBA/DateTime/DateValue.md --- # DateValue Returns a **Variant** (**Date**) from a string expression representing a date. Syntax: **DateValue** ( *date* ) *date* : *required* String expression representing a date from January 1, 100, through December 31, 9999. However, *date* can also be any expression that can represent a date, a time, or both a date and time, in that range. If *date* is a string that includes only numbers separated by valid date separators, **DateValue** recognizes the order for month, day, and year according to the Short Date format specified by the system. **DateValue** also recognizes unambiguous dates that contain month names, either in long or abbreviated form. For example, in addition to recognizing 12/30/1991 and 12/30/91, **DateValue** also recognizes December 30, 1991 and Dec 30, 1991. If the year part of *date* is omitted, **DateValue** uses the current year from the system date. If the *date* argument includes time information, **DateValue** doesn't return it. However, if *date* includes invalid time information (such as "89:98"), an error occurs. If the [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri. ### Example This example uses the **DateValue** function to convert a string to a date. You can also use date literals to directly assign a date to a **Variant** or **Date** variable (for example, `MyDate = #2/12/69#`). ```vb Dim MyDate MyDate = DateValue("February 12, 1969") ' Returns a date. ``` ### See Also * [DateSerial](/en/official/Reference/VBA/DateTime/DateSerial) function --- --- url: /zh/official/Reference/VBA/DateTime/DateValue.md --- # DateValue 从表示日期的字符串表达式返回 **Variant** (**Date**)。 语法:**DateValue** ( *date* ) *date* : *必需* 表示从 100 年 1 月 1 日到 9999 年 12 月 31 日日期的字符串表达式。但是,*date* 也可以是该范围内任何可以表示日期、时间或同时表示日期和时间的表达式。 如果 *date* 是一个仅包含由有效日期分隔符分隔的数字的字符串,**DateValue** 根据系统指定的短日期格式识别月、日、年的顺序。**DateValue** 也识别包含月份名称(完整或缩写形式)的明确日期。例如,除了识别 12/30/1991 和 12/30/91 外,**DateValue** 还识别 December 30, 1991 和 Dec 30, 1991。 如果省略了 *date* 的年份部分,**DateValue** 使用系统日期中的当前年份。 如果 *date* 参数包含时间信息,**DateValue** 不返回时间。但如果 *date* 包含无效的时间信息(如 "89:98"),将发生错误。 如果 [**Calendar**](/official/Reference/VBA/DateTime/Calendar) 属性设置为公历,则提供的日期必须为公历。如果日历为回历,则提供的日期必须为回历。 ### 示例 此示例使用 **DateValue** 函数将字符串转换为日期。也可以使用日期字面量直接将日期赋值给 **Variant** 或 **Date** 变量(例如 `MyDate = #2/12/69#`)。 ```vb Dim MyDate MyDate = DateValue("February 12, 1969") ' Returns a date. ``` ### 另请参阅 * [DateSerial](/official/Reference/VBA/DateTime/DateSerial) 函数 --- --- url: /en/official/Reference/VBA/DateTime/Day.md --- # Day Returns a **Variant** (**Integer**) specifying a whole number between 1 and 31, inclusive, representing the day of the month. Syntax: **Day** ( *date* ) *date* : *required* Any **Variant**, numeric expression, string expression, or any combination that can represent a date. If *date* contains **Null**, **Null** is returned. ::: info If the [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property setting is Gregorian, the returned integer represents the Gregorian day of the month. If the calendar is Hijri, the returned integer represents the Hijri day of the month. ::: ### Example This example uses the **Day** function to obtain the day of the month from a specified date. ```vb Dim MyDate, MyDay MyDate = #February 12, 1969# ' Assign a date. MyDay = Day(MyDate) ' MyDay contains 12. ``` ### See Also * [Month](/en/official/Reference/VBA/DateTime/Month), [Year](/en/official/Reference/VBA/DateTime/Year), [DatePart](/en/official/Reference/VBA/DateTime/DatePart) functions --- --- url: /zh/official/Reference/VBA/DateTime/Day.md --- # Day 返回一个 **Variant** (**Integer**),指定 1 到 31 之间(含)的整数,表示月份中的日。 语法:**Day** ( *date* ) *date* : *必需* 任何可以表示日期的 **Variant**、数值表达式、字符串表达式或其组合。如果 *date* 包含 **Null**,则返回 **Null**。 ::: info 如果 [**Calendar**](/official/Reference/VBA/DateTime/Calendar) 属性设置为公历,则返回的整数表示公历月份中的日。如果日历为回历,则返回的整数表示回历月份中的日。 ::: ### 示例 此示例使用 **Day** 函数从指定日期获取月份中的日。 ```vb Dim MyDate, MyDay MyDate = #February 12, 1969# ' Assign a date. MyDay = Day(MyDate) ' MyDay contains 12. ``` ### 另请参阅 * [Month](/official/Reference/VBA/DateTime/Month)、[Year](/official/Reference/VBA/DateTime/Year)、[DatePart](/official/Reference/VBA/DateTime/DatePart) 函数 --- --- url: /en/official/Reference/VBA/Financial/DDB.md --- # DDB Returns a **Double** specifying the depreciation of an asset for a specific time period by using the double-declining balance method or another specified method. Syntax: **DDB(** *cost*, *salvage*, *life*, *period* \[ **,** *factor* ] **)** *cost* : *required* **Double** specifying the initial cost of the asset. *salvage* : *required* **Double** specifying the value of the asset at the end of its useful life. *life* : *required* **Double** specifying the length of useful life of the asset. *period* : *required* **Double** specifying the period for which asset depreciation is calculated. *factor* : *optional* **Variant** specifying the rate at which the balance declines. If omitted, 2 (double-declining method) is assumed. The double-declining balance method computes depreciation at an accelerated rate. Depreciation is highest in the first period and decreases in successive periods. The *life* and *period* arguments must be expressed in the same units. For example, if *life* is given in months, *period* must also be given in months. All arguments must be positive numbers. The **DDB** function uses the following formula to calculate depreciation for a given period: Depreciation / *period* = ((*cost* - *salvage*) \* *factor*) / *life* ### Example This example uses the **DDB** function to return the depreciation of an asset for a specified period given the initial cost (`InitCost`), the salvage value at the end of the asset's useful life (`SalvageVal`), the total life of the asset in years (`LifeTime`), and the period in years for which the depreciation is calculated (`Depr`). ```vb Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, DepYear, Depr Const YRMOS = 12 ' Number of months in a year. Fmt = "###,##0.00" InitCost = InputBox("What's the initial cost of the asset?") SalvageVal = InputBox("Enter the asset's value at end of its life.") MonthLife = InputBox("What's the asset's useful life in months?") Do While MonthLife < YRMOS ' Ensure period is >= 1 year. MsgBox "Asset life must be a year or more." MonthLife = InputBox("What's the asset's useful life in months?") Loop LifeTime = MonthLife / YRMOS ' Convert months to years. If LifeTime <> Int(MonthLife / YRMOS) Then LifeTime = Int(LifeTime + 1) ' Round up to nearest year. End If DepYear = CInt(InputBox("Enter year for depreciation calculation.")) Do While DepYear < 1 Or DepYear > LifeTime MsgBox "You must enter at least 1 but not more than " & LifeTime DepYear = InputBox("Enter year for depreciation calculation.") Loop Depr = DDB(InitCost, SalvageVal, LifeTime, DepYear) MsgBox "The depreciation for year " & DepYear & " is " & _ Format(Depr, Fmt) & "." ``` ### See Also * [SLN](/en/official/Reference/VBA/Financial/SLN), [SYD](/en/official/Reference/VBA/Financial/SYD) functions --- --- url: /zh/official/Reference/VBA/Financial/DDB.md --- # DDB 返回一个 **Double**,使用双倍余额递减法或其他指定方法指定资产在特定期间的折旧。 语法:**DDB(** *cost*, *salvage*, *life*, *period* \[ **,** *factor* ] **)** *cost* : *必需* **Double**,指定资产的初始成本。 *salvage* : *必需* **Double**,指定资产在使用寿命结束时的价值。 *life* : *必需* **Double**,指定资产使用寿命的长度。 *period* : *必需* **Double**,指定计算资产折旧的期间。 *factor* : *可选* **Variant**,指定余额递减率。如果省略,则假定为 2(双倍递减法)。 双倍余额递减法以加速率计算折旧。折旧在第一期间最高,在后续期间递减。 *life* 和 *period* 参数必须以相同单位表示。例如,如果 *life* 以月为单位,*period* 也必须以月为单位。所有参数必须为正数。 **DDB** 函数使用以下公式计算给定期间的折旧: 折旧 / *period* = ((*cost* - *salvage*) \* *factor*) / *life* ### 示例 此示例使用 **DDB** 函数返回资产在指定期间的折旧,给定初始成本(`InitCost`)、资产使用寿命结束时的残值(`SalvageVal`)、资产的总寿命年数(`LifeTime`)以及计算折旧的期间年数(`Depr`)。 ```vb Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, DepYear, Depr Const YRMOS = 12 ' Number of months in a year. Fmt = "###,##0.00" InitCost = InputBox("What's the initial cost of the asset?") SalvageVal = InputBox("Enter the asset's value at end of its life.") MonthLife = InputBox("What's the asset's useful life in months?") Do While MonthLife < YRMOS ' Ensure period is >= 1 year. MsgBox "Asset life must be a year or more." MonthLife = InputBox("What's the asset's useful life in months?") Loop LifeTime = MonthLife / YRMOS ' Convert months to years. If LifeTime <> Int(MonthLife / YRMOS) Then LifeTime = Int(LifeTime + 1) ' Round up to nearest year. End If DepYear = CInt(InputBox("Enter year for depreciation calculation.")) Do While DepYear < 1 Or DepYear > LifeTime MsgBox "You must enter at least 1 but not more than " & LifeTime DepYear = InputBox("Enter year for depreciation calculation.") Loop Depr = DDB(InitCost, SalvageVal, LifeTime, DepYear) MsgBox "The depreciation for year " & DepYear & " is " & _ Format(Depr, Fmt) & "." ``` ### 另请参阅 * [SLN](/official/Reference/VBA/Financial/SLN)、[SYD](/official/Reference/VBA/Financial/SYD) 函数 --- --- url: /en/official/IDE/Menu/Debug.md --- # Debug Menu ![Debug Menu](/assets/Menu_Debug.DmTsmZ4_.png "Debug Menu") * Step Into F8 / F11 * Step Over SHIFT + F8 / F10 *** * Add Watch... SHIFT + F9 * Clear Watches *** * Toggle Breakpoint F9 * Clear All Breakpoints CTRL + SHIFT + F9 *** * Set Next Statement (Jump To Line) CTRL + F9 *** * Debugger Options ## Debugger Options ![Debugger Options - Debug Menu](/assets/Menu_Debug_DebuggerOptions.aRq1DFjy.png "Debugger Options - Debug Menu") * Break On All Errors * ✔ Allow Breakpoints (Debuggable) ![Debugger Options - Debug Menu](Images/Menu_Debug_DebuggerOptions_2.png "Debugger Options - Debug Menu") --- --- url: /en/official/IDE/Debug-Console.md --- # Debug Console ![Debug Console](/assets/DebugConsole.Bt37Zf5d.png "Debug Console") The Debug Console captures output from `Debug.Print` statements and other debug-layer messages written at runtime, displaying them in a scrollable log. ## ![](Images/DebugConsole_AutoScroll.png) Auto Scroll ## ![](Images/DebugConsole_Clear.png) Clear Debug Console ## ![](Images/DebugConsole_Options.png) Options * Invert Output Direction * Show Timestamps ## ![](Images/DebugConsole_Input.png) Input --- --- url: /en/official/Reference/tbIDE/DebugConsole.md --- # DebugConsole class The IDE's DEBUG CONSOLE pane --- reached through [**Host.DebugConsole**](/en/official/Reference/tbIDE/Host#debugconsole). The canonical place for an addin to write diagnostic and log output. ```vb With Host.DebugConsole .PrintText "[MyAddIn] Project: " & Host.CurrentProject.Name .PrintText "[MyAddIn] Compiler: " & Host.CompilerVersion .PrintText "[MyAddIn] PID: " & Host.IDEProcessID End With ``` The pane is shared across the IDE's own output and every addin's output --- prefix log lines with an addin tag (e.g. `"[MyAddIn] "`) so users can distinguish the sources. ## Methods ### Clear Clears the entire content of the DEBUG CONSOLE pane. Syntax: *debugConsole*.**Clear** ### PrintText Prints one line of text to the pane. Syntax: *debugConsole*.**PrintText** *Prompt* \[, *ColorRGB* ] *Prompt* : *required* The text to print. **String**. *ColorRGB* : *optional* The text colour as an RGB **Long** (use the `RGB(r, g, b)` function to construct one). Default 0 --- the IDE's default DEBUG CONSOLE foreground colour. ```vb Host.DebugConsole.PrintText "Operation completed" ' default colour Host.DebugConsole.PrintText "Warning: something looks off", RGB(255, 128, 0) ' orange ``` ### SetFocus Gives keyboard focus to the DEBUG CONSOLE's text-entry point --- equivalent to the user clicking into the console. Syntax: *debugConsole*.**SetFocus** --- --- url: /zh/official/Reference/tbIDE/DebugConsole.md --- # DebugConsole 类 IDE 的调试控制台窗格——通过 [**Host.DebugConsole**](/official/Reference/tbIDE/Host#debugconsole) 访问。插件写入诊断和日志输出的规范位置。 ```vb With Host.DebugConsole .PrintText "[MyAddIn] Project: " & Host.CurrentProject.Name .PrintText "[MyAddIn] Compiler: " & Host.CompilerVersion .PrintText "[MyAddIn] PID: " & Host.IDEProcessID End With ``` 该窗格在 IDE 自身输出和每个插件的输出之间共享——用插件标签(例如 `"[MyAddIn] "`)作为日志行前缀,以便用户区分来源。 ## 方法 ### Clear 清除调试控制台窗格的全部内容。 语法:*debugConsole*.**Clear** ### PrintText 向窗格打印一行文本。 语法:*debugConsole*.**PrintText** *Prompt* \[, *ColorRGB* ] *Prompt* : *必需* 要打印的文本。**String**。 *ColorRGB* : *可选* 文本颜色,为 RGB **Long**(使用 `RGB(r, g, b)` 函数构造)。默认 0——IDE 的默认调试控制台前景色。 ```vb Host.DebugConsole.PrintText "Operation completed" ' 默认颜色 Host.DebugConsole.PrintText "Warning: something looks off", RGB(255, 128, 0) ' 橙色 ``` ### SetFocus 将键盘焦点给予调试控制台的文本输入点——等同于用户点击控制台。 语法:*debugConsole*.**SetFocus** --- --- url: /en/official/Features/Compiler-IDE/Debugging.md --- # Debugging Features twinBASIC includes several features to help with debugging. ## Debug Trace Logger New to the debugging experience is a trace logging feature that automatically creates detailed logs to either the debug console or a file. Messages can be output with `Debug.TracePrint`. The logger works both when running from the IDE and in compiled executables. ![image](/assets/4fc2bf99-2bec-4943-837d-21038d791574.DRG1F5be.png) ```vb Public Sub ProcessOrder(ByVal orderId As Long) Debug.TracePrint "ProcessOrder called, orderId=" & CStr(orderId) ' ... processing ... End Sub ``` ## Stale/Dangling Pointer Detection Bugs result from using Strings and Variants after they have been freed. It may not be noticed immediately if the memory has not been overwritten, but it's sometimes hard to detect and can cause issues like a String displaying it's previous value or garbage. This debugging option detects use-after-free, and replaces the data with a special symbol indicating the problem. Below shows an example where the ListView ColumnHeader text had been set by previously-freed string and detected by this feature: ![image](/assets/021f6cbf-acce-445d-ade7-3fcad0af4927.CZs18HD4.png) Previously, it had shown the same text for every column-- but only under certain circumstances, leading to the issue being overlooked for a long time. --- --- url: /en/official/Reference/Core/Declare.md --- # Declare Declares references to external procedures in a dynamic-link library (DLL) at the module level. ::: info **Declare** statements with the PtrSafe keyword is the recommended syntax. **Declare** statements that include **PtrSafe** work correctly in twinBASIC and VBA version 7 development environment on both 32-bit and 64-bit platforms only after all data types in the **Declare** statement (parameters and return values) that need to store 64-bit quantities are updated to use LongLong for 64-bit integrals or LongPtr for pointers and handles. ::: To ensure backwards compatibility with VBA version 6 and earlier, use the following construct: ```vb #If VBA7 Then Declare PtrSafe Sub... #Else Declare Sub... #EndIf ``` ::: info For code to run when built for 64-bit targets, all **Declare** statements must include the **PtrSafe** keyword, and all data types in the **Declare** statement (parameters and return values) that need to store 64-bit quantities must be updated to use **LongLong** for 64-bit integrals or **LongPtr** for pointers and handles. ::: Syntax: * > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Declare** \[ **PtrSafe** ] **Sub** *name* **Lib** "*libname*" \[ **(** \[ *arglist* ] **)** ] * > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Declare** \[ **PtrSafe** ] **Sub** *name* **Lib** "*libname*" **Alias** "*aliasname*" \[ **(** \[ *arglist* ] **)** ] * > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Declare** \[ **PtrSafe** ] **Function** *name* **Lib** "*libname*" \[ **(** \[ *arglist* ] **)** ] \[ **As** *type* ] * > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Declare** \[ **PtrSafe** ] **Function** *name* **Lib** "*libname*" **Alias** "*aliasname*" \[ **(** \[ *arglist* ] **)** ] \[ **As** *type* ] *attributes* : *optional* One or more of:\ [Description](/en/official/Reference/Attributes#description), [DLLStackCheck](/en/official/Reference/Attributes#dllstackcheck), [PreserveSig](/en/official/Reference/Attributes#preservesig), [SetDllDirectory](/en/official/Reference/Attributes#setdlldirectory), [UseGetLastError](/en/official/Reference/Attributes#usegetlasterror) **Public** : *optional* Used to declare procedures that are available to all other procedures in all modules. **Private** : *optional* Used to declare procedures that are available only within the module where the declaration is made. **PtrSafe** : *required in 64-bits* The PtrSafe keyword asserts that a Declare statement is safe to run in 64-bit versions of Microsoft Office. **Sub / Function** : Indicates whether the procedure returns a value (**Function**) or not (**Sub**). *name* : Any valid procedure name. Note that DLL entry points are case-sensitive. *libname* : Name of the DLL or code resource that contains the declared procedure. **Alias** *aliasname* : *optional* Indicates that the procedure being called has another name in the DLL. This is useful when the external procedure name is the same as a keyword. Alias also applies when a DLL procedure has the same name as a public variable, constant, or any other procedure in the same scope. Alias is also useful when any characters in the DLL procedure name aren't allowed by the DLL naming convention.\ *aliasname* names the procedure in the DLL or code resource. If the first character is not a number sign (**#**), *aliasname* is the name of the procedure's entry point in the DLL. If (**#**) is the first character, all characters that follow must indicate the ordinal number of the procedure's entry point. *arglist* : *optional* List of variables representing arguments that are passed to the procedure when it is called. *type* : *optional* Data type of the value returned by a **Function** procedure; may be Byte, Boolean, Integer, Long, LongLong, LongPtr, Currency, Single, Double, Decimal, Date, String (variable length only), Variant, a user-defined type (UDT), or an object type. **LongLong** is a valid declared type only on 64-bit platforms. ### arglist The *arglist* argument has the following syntax and parts: Syntax: \[ **Optional** ] \[ **ByVal** | **ByRef** ] \[ **ParamArray** ] *varname* \[ **( )** ] \[ **As** *type* ] **Optional** : *optional* Indicates that an argument is not required. If used, all subsequent arguments in *arglist* must also be optional and declared by using the **Optional** keyword. **Optional** can't be used for any argument if **ParamArray** is used. **ByVal** : *optional* Indicates that the argument is passed by value. **ByRef** : *optional* Indicates that the argument is passed by reference. **ByRef** is the default unlike in Visual Basic .NET. **ParamArray** : *optional* Used only as the last argument in arglist to indicate that the final argument is an **Optional** array of **Variant** elements. The **ParamArray** keyword permits passing an arbitrary number of arguments. The ParamArray keyword can't be used with **ByVal**, **ByRef**, or **Optional**. *varname* : Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions. **( )** : Required for array variables. Indicates that *varname* is an array. *type* : *optional* Data type of the argument passed to the procedure; may be **Byte**, **Boolean**, **Integer**, **Long**, **LongLong**, **LongPtr**, **Currency**, **Single**, **Double**, **Decimal**, **Date**, **String** (variable length only), **Object**, **Variant**, a user-defined type (UDT), or an object type. (**LongLong** is a valid declared type only on 64-bit platforms.) When an argument list is included, the number and type of arguments are checked each time the procedure is called. The First sub in the following example takes one **Long** argument, whereas the Second sub takes no arguments: ```vb Declare Sub First Lib "MyLib" (X As Long) Declare Sub Second Lib "MyLib" () ``` ::: info * Fixed-length strings cannot appear in the argument list of a **Declare** statement; only variable-length strings can be passed to procedures. Fixed-length strings can appear as procedure arguments, but they are converted to variable-length strings before being passed. * The **vbNullString** constant is used when calling external procedures, where the external procedure requires a string whose value is zero. This is not the same thing as a zero-length string (""). ::: ### Example This example shows how the **Declare** statement is used at the module level of a standard module to declare a reference to an external procedure in a dynamic-link library (DLL). **Declare** statements can be placed in class modules when they are **Private**. ```vb ' In 32-bit Microsoft Windows systems, specify the library USER32.DLL. Declare Sub MessageBeep Lib "User32" (ByVal N As Long) ' 64-bit Declare statement example: Declare PtrSafe Function GetActiveWindow Lib "User32" () As LongPtr ' Conditional Compilation Example #If Vba7 Then ' Code is running in 32-bit or 64-bit twinBASIC or VBA7 #If Win64 Then ' Code is running in 64-bit twinBASIC or VBA7. #Else ' Code is not running in 64-bit twinBASIC or VBA7. #End If #Else ' Code is NOT running in 32-bit or 64-bit twinBASIC or VBA7. #End If ``` --- --- url: /zh/official/Reference/Core/Declare.md --- # Declare 在模块级别声明对动态链接库(DLL)中外部过程的引用。 ::: info 带有PtrSafe关键字的 **Declare** 语句是推荐的语法。包含 **PtrSafe** 的 **Declare** 语句只有在将 **Declare** 语句中需要存储64位量的所有数据类型(参数和返回值)更新为对64位整数使用LongLong、对指针和句柄使用LongPtr之后,才能在twinBASIC和VBA版本7开发环境的32位和64位平台上正常工作。 ::: 为确保与VBA版本6及更早版本的向后兼容,请使用以下结构: ```vb #If VBA7 Then Declare PtrSafe Sub... #Else Declare Sub... #EndIf ``` ::: info 要在为64位目标构建时运行代码,所有 **Declare** 语句必须包含 **PtrSafe** 关键字,且 **Declare** 语句中需要存储64位量的所有数据类型(参数和返回值)必须更新为对64位整数使用 **LongLong**、对指针和句柄使用 **LongPtr**。 ::: 语法: * > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Declare** \[ **PtrSafe** ] **Sub** *name* **Lib** "*libname*" \[ **(** \[ *arglist* ] **)** ] * > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Declare** \[ **PtrSafe** ] **Sub** *name* **Lib** "*libname*" **Alias** "*aliasname*" \[ **(** \[ *arglist* ] **)** ] * > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Declare** \[ **PtrSafe** ] **Function** *name* **Lib** "*libname*" \[ **(** \[ *arglist* ] **)** ] \[ **As** *type* ] * > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Declare** \[ **PtrSafe** ] **Function** *name* **Lib** "*libname*" **Alias** "*aliasname*" \[ **(** \[ *arglist* ] **)** ] \[ **As** *type* ] *attributes* : *可选* 以下一个或多个:\ [Description](/official/Reference/Attributes#description)、[DLLStackCheck](/official/Reference/Attributes#dllstackcheck)、[PreserveSig](/official/Reference/Attributes#preservesig)、[SetDllDirectory](/official/Reference/Attributes#setdlldirectory)、[UseGetLastError](/official/Reference/Attributes#usegetlasterror) **Public** : *可选* 用于声明对所有模块中所有其他过程可用的过程。 **Private** : *可选* 用于声明仅在声明所在模块内可用的过程。 **PtrSafe** : *64位必填* PtrSafe关键字断言Declare语句可以在64位版本的Microsoft Office中安全运行。 **Sub / Function** : 指示过程是否返回值(**Function**)或不返回值(**Sub**)。 *name* : 任何有效的过程名称。注意DLL入口点区分大小写。 *libname* : 包含所声明过程的DLL或代码资源的名称。 **Alias** *aliasname* : *可选* 指示被调用的过程在DLL中有另一个名称。当外部过程名与关键字相同时很有用。当DLL过程与同一作用域中的公共变量、常量或任何其他过程同名时,Alias也适用。当DLL过程名中有不符合DLL命名约定的字符时,Alias也很有用。\ *aliasname* 命名DLL或代码资源中的过程。如果第一个字符不是数字符号(**#**),*aliasname* 是DLL中过程入口点的名称。如果第一个字符是(**#**),后续所有字符必须指示过程入口点的序号。 *arglist* : *可选* 表示调用过程时传递的参数的变量列表。 *type* : *可选* **Function** 过程返回值的数据类型;可以是Byte、Boolean、Integer、Long、LongLong、LongPtr、Currency、Single、Double、Decimal、Date、String(仅限变长)、Variant、用户自定义类型(UDT)或对象类型。**LongLong** 仅在64位平台上是有效的声明类型。 ### arglist *arglist* 参数的语法和组成部分如下: 语法:\[ **Optional** ] \[ **ByVal** | **ByRef** ] \[ **ParamArray** ] *varname* \[ **( )** ] \[ **As** *type* ] **Optional** : *可选* 指示参数不是必需的。如果使用,*arglist* 中所有后续参数也必须是可选的并使用 **Optional** 关键字声明。如果使用了 **ParamArray**,则不能对任何参数使用 **Optional**。 **ByVal** : *可选* 指示参数按值传递。 **ByRef** : *可选* 指示参数按引用传递。**ByRef** 是默认方式,与Visual Basic .NET不同。 **ParamArray** : *可选* 仅用作arglist中的最后一个参数,指示最后一个参数是 **Variant** 元素的 **Optional** 数组。**ParamArray** 关键字允许传递任意数量的参数。ParamArray关键字不能与 **ByVal**、**ByRef** 或 **Optional** 一起使用。 *varname* : 表示传递给过程的参数的变量名称;遵循标准变量命名约定。 **( )** : 数组变量必需。指示 *varname* 是数组。 *type* : *可选* 传递给过程的参数的数据类型;可以是 **Byte**、**Boolean**、**Integer**、**Long**、**LongLong**、**LongPtr**、**Currency**、**Single**、**Double**、**Decimal**、**Date**、**String**(仅限变长)、**Object**、**Variant**、用户自定义类型(UDT)或对象类型。(**LongLong** 仅在64位平台上是有效的声明类型。) 当包含参数列表时,每次调用过程时都会检查参数的数量和类型。以下示例中,第一个Sub接受一个 **Long** 参数,而第二个Sub不接受参数: ```vb Declare Sub First Lib "MyLib" (X As Long) Declare Sub Second Lib "MyLib" () ``` ::: info * 定长字符串不能出现在 **Declare** 语句的参数列表中;只能向过程传递变长字符串。定长字符串可以作为过程参数出现,但在传递之前会被转换为变长字符串。 * **vbNullString** 常量在调用外部过程时使用,当外部过程需要值为零的字符串时。这与零长度字符串("")不同。 ::: ### 示例 本示例展示如何在标准模块的模块级别使用 **Declare** 语句声明对动态链接库(DLL)中外部过程的引用。**Declare** 语句在为 **Private** 时可以放在类模块中。 ```vb ' In 32-bit Microsoft Windows systems, specify the library USER32.DLL. Declare Sub MessageBeep Lib "User32" (ByVal N As Long) ' 64-bit Declare statement example: Declare PtrSafe Function GetActiveWindow Lib "User32" () As LongPtr ' Conditional Compilation Example #If Vba7 Then ' Code is running in 32-bit or 64-bit twinBASIC or VBA7 #If Win64 Then ' Code is running in 64-bit twinBASIC or VBA7. #Else ' Code is not running in 64-bit twinBASIC or VBA7. #End If #Else ' Code is NOT running in 32-bit or 64-bit twinBASIC or VBA7. #End If ``` --- --- url: /en/official/Reference/VBRUN/Constants/DefaultCursorTypeConstants.md --- # DefaultCursorTypeConstants Cursor-driver values for a Data control's connection, controlling whether the database client or the server manages the recordset cursor. | Constant | Value | Description | |----------|-------|-------------| | **vbUseDefaultCursor** | 0 | Use the data source's default cursor driver. | | **vbUseODBCCursor** | 1 | Use the client-side ODBC cursor library. | | **vbUseServersideCursor** | 2 | Use a server-side cursor managed by the database engine. | --- --- url: /zh/official/Reference/VBRUN/Constants/DefaultCursorTypeConstants.md --- # DefaultCursorTypeConstants Data控件连接的游标驱动值,控制由数据库客户端还是服务器管理记录集游标。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbUseDefaultCursor** | 0 | 使用数据源的默认游标驱动。 | | **vbUseODBCCursor** | 1 | 使用客户端ODBC游标库。 | | **vbUseServersideCursor** | 2 | 使用由数据库引擎管理的服务器端游标。 | --- --- url: /en/official/Tutorials/CustomControls/Defining-a-CustomControl.md --- # Defining a CustomControl A CustomControl is simply an ordinary twinBASIC class, with a few extra attributes and requirements. ::: tip It is highly advisable to look at and experiment with the sample project provided with twinBASIC before trying to implement your own CustomControl. ::: ![Custom Control Sample Project](/assets/ccSampleProject.s4UMFguj.png) *** ## CustomControl() attribute ![CustomControl attribute](Images/ccCustomControlAttribute.png) This is a required attribute for all CustomControls. You must provide the relative path to an image file within your project that can be used to identify your control in the form designer toolbox. We recommend that you put the image file in the Miscellaneous folder in your project. ![CustomControl GridImage Folder](/assets/ccGridButtonImage.DUOdFAFA.png) *** ## ClassId() attribute ![CustomControl ClassId Attribute](Images/ccClassIdAttribute.png) This is a required attribute for all CustomControls. You must provide a unique CLSID (GUID) in order for the form engine to work with your control. ::: tip If you enter `[ ClassId () ]` twinBASIC helps you out - just press the 'insert a randomly generated GUID' text: ::: ![CustomControl ClassId auto-generate](Images/ccClassIdInsert.png) *** ## COMCreatable() attribute ![CustomControl COMCreatable attribute](/assets/ccCOMCreatable.Do5ABbox.png) This is an optional attribute, but it is usually advisable to set this attribute to False, as you don't need to instantiate CustomControls from external COM environments. *** ## Must implement ICustomControl ![CustomControl ICustomControl interface](/assets/ccICustomControl.Efdgn67o.png) All CustomControls *must* implement [`CustomControls.ICustomControl`](/en/official/Reference/CustomControls/Framework/ICustomControl). This interface currently has 3 methods that you must implement: ```vb Sub Initialize(ByVal Context As CustomControlContext) ``` This method is called when your control is attached to a form. You must store the provided Context object in a class field as it offers a `Repaint()` method for informing the form engine that something in your control has changed and needs to be repainted. ```vb Sub Destroy() ``` This method is called when your control is detached from a form. This allows an opportunity to break circular references so that your object instance can be destructed properly. The implementation for this can often be left empty provided you don't create circular references in objects. ```vb Sub Paint(ByVal Canvas As Canvas) ``` This is the most interesting part for a CustomControl. As such, it gets its own section, see [Painting / drawing to your control](/en/official/Tutorials/CustomControls/Painting-drawing-to-your-control) *** ## Minimum set of properties As twinBASIC doesn't yet support inheritance, you must expose a set of common properties (class fields) for all CustomControls: ```vb Public Name As String Public Left As CustomControls.PixelCount Public Top As CustomControls.PixelCount Public Width As CustomControls.PixelCount Public Height As CustomControls.PixelCount Public Anchors As Anchors = New Anchors Public Dock As CustomControls.DockMode Public Visible As Boolean ``` The form designer and the form engine work with these properties, so it is important to include them in your CustomControl class. The types used here are all defined in the framework: [`PixelCount`](/en/official/Reference/CustomControls/Enumerations/PixelCount), [`DockMode`](/en/official/Reference/CustomControls/Enumerations/DockMode), and the [`Anchors`](/en/official/Reference/CustomControls/Styles/Anchors) style object. Note that the form designer works with pixel values which are not DPI-scaled. So the Left/Top/Width/Height properties of your control do not reflect DPI scaling. For example, if your control has a width of 50 pixels, then at DPI 150%, then the actual drawing width is 75 pixels ( see [Painting / drawing to your control](/en/official/Tutorials/CustomControls/Painting-drawing-to-your-control)). *** ## Must have a serialization constructor CustomControls *must* offer a serialization constructor: ```vb Public Sub New(Serializer As SerializationInfo) ``` The passed in Serializer object offers a `Deserialize()` method that you call to load the properties that have been set for your control via the form designer. See [Property Sheet and Object Serialization](/en/official/Tutorials/CustomControls/Property-sheet-and-object-serialization) for further information. ::: info The current framework names the serializer type [`SerializeInfo`](/en/official/Reference/CustomControls/Framework/SerializeInfo) (not `SerializationInfo`), and `Deserialize()` is exposed as `RuntimeUISrzDeserialize()`. See the reference page for the current member names and the design-mode / runtime-mode flags also available on this object. ::: *** ## See also * [CustomControls package reference](/en/official/Reference/CustomControls/) -- the full reference for the framework half (interfaces, callback objects, the [`Canvas`](/en/official/Reference/CustomControls/Framework/Canvas) drawing surface, the [`SerializeInfo`](/en/official/Reference/CustomControls/Framework/SerializeInfo) serializer) and the built-in `Waynes…` controls built on it. --- --- url: /en/official/Reference/Core/Deftype.md --- # DefBool, DefByte, DefInt, DefLng, DefLngLng, DefLngPtr, DefCur, DefSng, DefDbl, DefDec, DefDate, DefStr, DefObj, DefVar Used at the module level to set the default data type for variables, arguments passed to procedures, and the return type for **Function** and **Property Get** procedures whose names start with the specified characters. ::: warning The **Def***type* family of statements is deprecated. They are supported for compatibility with legacy code, but new code should declare every variable, argument, and return type explicitly with **As** *type*. Combined with [**Option Explicit**](/en/official/Reference/Core/Option#Explicit), explicit declarations make code far easier to read and maintain. ::: Syntax: * > **DefBool** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefByte** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefInt** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefLng** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefLngLng** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefLngPtr** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefCur** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefSng** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefDbl** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefDec** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefDate** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefStr** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefObj** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefVar** *letterrange* \[ **,** *letterrange* ] **. . .** *letterrange* : A single letter, or a hyphenated range *letter1*-*letter2*. The letters specify the leading character of names that adopt the default type. Case is not significant. The statement name determines the data type: | Statement | Data type | |:----------|:----------| | **DefBool** | **Boolean** | | **DefByte** | **Byte** | | **DefInt** | **Integer** | | **DefLng** | **Long** | | **DefLngLng** | **LongLong** | | **DefLngPtr** | **LongPtr** | | **DefCur** | **Currency** | | **DefSng** | **Single** | | **DefDbl** | **Double** | | **DefDec** | **Decimal** | | **DefDate** | **Date** | | **DefStr** | **String** | | **DefObj** | **Object** | | **DefVar** | **Variant** | For example, in the following fragment, `Message` is a **String** variable: ```vb DefStr A-Q . . . Message = "Out of stack space." ``` A **Def***type* statement affects only the module where it is used. The default data type for variables, arguments, and return types of items not declared explicitly and not covered by a **Def***type* statement is **Variant**. A letter range usually defines the data type for variables that begin with letters in the first 128 characters of the character set. However, the range A-Z sets the default to the specified data type for *all* names, including those starting with characters from the extended part of the character set (128-255). After the range A-Z has been specified, subranges cannot be further redefined by using **Def***type* statements. Once a range has been specified, including a previously defined letter in another **Def***type* statement is an error. The data type of any variable --- defined or not --- can still be explicitly specified by using a [**Dim**](/en/official/Reference/Core/Dim) statement with an **As** *type* clause: ```vb DefInt A-Z Dim TaxRate As Double ' explicit declaration overrides the default ``` **Def***type* statements don't affect elements of user-defined types --- those must be explicitly declared. ### See Also * [**Dim** statement](/en/official/Reference/Core/Dim) * [**Option** statement](/en/official/Reference/Core/Option) (for **Option Explicit**) * [**Type** statement](/en/official/Reference/Core/Type) --- --- url: /zh/official/Reference/Core/Deftype.md --- # DefBool、DefByte、DefInt、DefLng、DefLngLng、DefLngPtr、DefCur、DefSng、DefDbl、DefDec、DefDate、DefStr、DefObj、DefVar 在模块级别用于为名称以指定字符开头的变量、传递给过程的参数以及 **Function** 和 **Property Get** 过程的返回类型设置默认数据类型。 ::: warning **Def***type* 系列语句已弃用。它们仅为与遗留代码兼容而受支持,新代码应使用 **As** *type* 显式声明每个变量、参数和返回类型。结合 [**Option Explicit**](/official/Reference/Core/Option#Explicit),显式声明使代码更易于阅读和维护。 ::: 语法: * > **DefBool** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefByte** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefInt** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefLng** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefLngLng** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefLngPtr** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefCur** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefSng** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefDbl** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefDec** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefDate** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefStr** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefObj** *letterrange* \[ **,** *letterrange* ] **. . .** * > **DefVar** *letterrange* \[ **,** *letterrange* ] **. . .** *letterrange* : 单个字母,或连字符范围 *letter1*-*letter2*。字母指定采用默认类型的名称的首字母。不区分大小写。 语句名决定数据类型: | 语句 | 数据类型 | |:----------|:----------| | **DefBool** | **Boolean** | | **DefByte** | **Byte** | | **DefInt** | **Integer** | | **DefLng** | **Long** | | **DefLngLng** | **LongLong** | | **DefLngPtr** | **LongPtr** | | **DefCur** | **Currency** | | **DefSng** | **Single** | | **DefDbl** | **Double** | | **DefDec** | **Decimal** | | **DefDate** | **Date** | | **DefStr** | **String** | | **DefObj** | **Object** | | **DefVar** | **Variant** | 例如,在以下片段中,`Message` 是 **String** 变量: ```vb DefStr A-Q . . . Message = "Out of stack space." ``` **Def***type* 语句仅影响使用它的模块。未显式声明且未被 **Def***type* 语句覆盖的变量、参数和返回类型的默认数据类型为 **Variant**。 字母范围通常为字符集前128个字符中以这些字母开头的变量定义数据类型。但是,范围A-Z为*所有*名称设置指定的数据类型,包括以字符集扩展部分(128-255)的字符开头的名称。 指定范围A-Z后,子范围不能再使用 **Def***type* 语句重新定义。一旦指定了范围,在另一个 **Def***type* 语句中包含先前定义的字母将产生错误。任何变量——无论是否已定义——的数据类型仍可以通过使用带 **As** *type* 子句的 [**Dim**](/official/Reference/Core/Dim) 语句显式指定: ```vb DefInt A-Z Dim TaxRate As Double ' explicit declaration overrides the default ``` **Def***type* 语句不影响用户自定义类型的元素——那些必须显式声明。 ### 另请参阅 * [**Dim** 语句](/official/Reference/Core/Dim) * [**Option** 语句](/official/Reference/Core/Option)(关于 **Option Explicit**) * [**Type** 语句](/official/Reference/Core/Type) --- --- url: /en/official/Reference/Core/Delegate.md --- # Delegate Declares a function-pointer type --- a named signature that variables, parameters, and UDT members can hold a *reference* to a callable matching. A delegate value is bit-compatible with **LongPtr**, but adds compile-time signature checking when it is assigned, passed, or called. ::: info The **Delegate** statement is a twinBASIC extension. In classic VBA, function pointers are untyped **LongPtr** values produced by **AddressOf** and called indirectly through custom mechanisms (`DispCallFunc`, `CallWindowProc` shims, etc.). ::: Syntax: > \[ **Public** | **Private** ] **Delegate Function** *name* \[ **CDecl** ] **(** \[ *arglist* ] **)** **As** *type* **Public** : *optional* In an ActiveX project, exports the delegate type to the type library so consumers in other projects see *name*. **Private** : *optional* Withholds the delegate from the type library; usable only within the project. *name* : The identifier naming the delegate type. Must be a valid twinBASIC identifier. **CDecl** : *optional* Marks the delegate as using the C calling convention (`cdecl` --- caller cleans the stack), used to model callbacks expected by C-runtime APIs such as `qsort`. The default is `stdcall`. See [API Declarations](/en/official/Features/Advanced/API-Declarations#cdecl-callbacks). *arglist* : *optional* Parameter signature, written exactly as for a [**Sub**](/en/official/Reference/Core/Sub) or [**Function**](/en/official/Reference/Core/Function) --- comma-separated `[ ByVal | ByRef ] [ Optional ] *varname* [ As *type* ]` parts. *type* : Return type of the delegate's signature. After the declaration, *name* may be used wherever a type is allowed: to declare variables and parameters of function-pointer type, as the type of a member of a [**Type**](/en/official/Reference/Core/Type) (UDT), or as a parameter type in a [**Declare**](/en/official/Reference/Core/Declare) statement or an [**Interface**](/en/official/Reference/Core/Interface) member. A delegate value is normally produced by **AddressOf**, which yields a delegate-typed reference to a regular procedure with a matching signature. For backwards compatibility, a delegate variable can also be assigned a plain **LongPtr** address obtained by other means --- the value passes through unchecked. A delegate variable is called like a function: `result = myDelegate(arg1, arg2)`. ### Example A basic delegate, declared, assigned, and called: ```vb Private Delegate Function Operation (ByVal A As Long, ByVal B As Long) As Long Public Function Addition(ByVal A As Long, ByVal B As Long) As Long Return A + B End Function Private Sub Command1_Click() Dim op As Operation = AddressOf Addition MsgBox "Answer: " & op(5, 6) End Sub ``` A delegate used as a UDT member, modelling the `lpfnHook` field of the Windows `CHOOSECOLOR` struct. Existing code that assigns a **Long**/**LongPtr** to `lpfnHook` continues to work; new code can assign **AddressOf** *Handler* directly and have the signature checked at compile time: ```vb Public Delegate Function CCHookProc (ByVal hwnd As LongPtr, ByVal uMsg As Long, _ ByVal wParam As LongPtr, ByVal lParam As LongPtr) As LongPtr Public Type CHOOSECOLOR lStructSize As Long hwndOwner As LongPtr hInstance As LongPtr rgbResult As Long lpCustColors As LongPtr Flags As ChooseColorFlags lCustData As LongPtr lpfnHook As CCHookProc ' Typed function pointer instead of LongPtr. lpTemplateName As LongPtr End Type Dim tCC As CHOOSECOLOR tCC.lpfnHook = AddressOf ChooseColorHookProc ``` A **CDecl** delegate, used as the comparator parameter of the C-runtime `qsort` API: ```vb Private Delegate Function LongComparator CDecl ( _ ByRef a As Long, _ ByRef b As Long _ ) As Long Private Declare PtrSafe Sub qsort CDecl Lib "msvcrt" ( _ ByRef pFirst As Any, _ ByVal lNumber As Long, _ ByVal lSize As Long, _ ByVal pfnComparator As LongComparator _ ) ``` ### See Also * [**Declare** statement](/en/official/Reference/Core/Declare) * [**Type** statement](/en/official/Reference/Core/Type) * [**Interface** statement](/en/official/Reference/Core/Interface) * [**Alias** statement](/en/official/Reference/Core/Alias) * [Delegate Types](/en/official/Features/Language/Delegates) * [API Declarations](/en/official/Features/Advanced/API-Declarations) * [Enhanced Pointer Functionality](/en/official/Features/Language/Pointers) --- --- url: /zh/official/Reference/Core/Delegate.md --- # Delegate 声明函数指针类型——一种命名的签名,变量、参数和UDT成员可以持有对匹配的可调用对象的*引用*。委托值在位级别与 **LongPtr** 兼容,但在赋值、传递或调用时增加了编译时签名检查。 ::: info **Delegate** 语句是twinBASIC扩展。在经典VBA中,函数指针是由 **AddressOf** 产生的无类型 **LongPtr** 值,通过自定义机制(`DispCallFunc`、`CallWindowProc` 垫片等)间接调用。 ::: 语法: > \[ **Public** | **Private** ] **Delegate Function** *name* \[ **CDecl** ] **(** \[ *arglist* ] **)** **As** *type* **Public** : *可选* 在ActiveX项目中,将委托类型导出到类型库,使其他项目的使用者可以看到 *name*。 **Private** : *可选* 不将委托导出到类型库;仅在项目内可用。 *name* : 命名委托类型的标识符。必须是有效的twinBASIC标识符。 **CDecl** : *可选* 将委托标记为使用C调用约定(`cdecl`——调用者清理栈),用于建模C运行时API(如 `qsort`)所期望的回调。默认为 `stdcall`。参见[API声明](/official/Features/Advanced/API-Declarations#cdecl-callbacks)。 *arglist* : *可选* 参数签名,与 [**Sub**](/official/Reference/Core/Sub) 或 [**Function**](/official/Reference/Core/Function) 的写法完全相同——逗号分隔的 `[ ByVal | ByRef ] [ Optional ] *varname* [ As *type* ]` 部分。 *type* : 委托签名的返回类型。 声明之后,*name* 可在允许类型的任何地方使用:声明函数指针类型的变量和参数、作为 [**Type**](/official/Reference/Core/Type)(UDT)成员的类型、或作为 [**Declare**](/official/Reference/Core/Declare) 语句或 [**Interface**](/official/Reference/Core/Interface) 成员的参数类型。 委托值通常由 **AddressOf** 产生,它产生一个对具有匹配签名的常规过程的委托类型引用。为向后兼容,委托变量也可以接受通过其他方式获得的普通 **LongPtr** 地址——该值不经检查直接通过。委托变量的调用方式与函数相同:`result = myDelegate(arg1, arg2)`。 ### 示例 一个基本委托,声明、赋值并调用: ```vb Private Delegate Function Operation (ByVal A As Long, ByVal B As Long) As Long Public Function Addition(ByVal A As Long, ByVal B As Long) As Long Return A + B End Function Private Sub Command1_Click() Dim op As Operation = AddressOf Addition MsgBox "Answer: " & op(5, 6) End Sub ``` 委托用作UDT成员,建模Windows `CHOOSECOLOR` 结构的 `lpfnHook` 字段。将 **Long**/**LongPtr** 赋值给 `lpfnHook` 的现有代码继续工作;新代码可以直接赋值 **AddressOf** *Handler* 并在编译时检查签名: ```vb Public Delegate Function CCHookProc (ByVal hwnd As LongPtr, ByVal uMsg As Long, _ ByVal wParam As LongPtr, ByVal lParam As LongPtr) As LongPtr Public Type CHOOSECOLOR lStructSize As Long hwndOwner As LongPtr hInstance As LongPtr rgbResult As Long lpCustColors As LongPtr Flags As ChooseColorFlags lCustData As LongPtr lpfnHook As CCHookProc ' Typed function pointer instead of LongPtr. lpTemplateName As LongPtr End Type Dim tCC As CHOOSECOLOR tCC.lpfnHook = AddressOf ChooseColorHookProc ``` **CDecl** 委托,用作C运行时 `qsort` API的比较器参数: ```vb Private Delegate Function LongComparator CDecl ( _ ByRef a As Long, _ ByRef b As Long _ ) As Long Private Declare PtrSafe Sub qsort CDecl Lib "msvcrt" ( _ ByRef pFirst As Any, _ ByVal lNumber As Long, _ ByVal lSize As Long, _ ByVal pfnComparator As LongComparator _ ) ``` ### 另请参阅 * [**Declare** 语句](/official/Reference/Core/Declare) * [**Type** 语句](/official/Reference/Core/Type) * [**Interface** 语句](/official/Reference/Core/Interface) * [**Alias** 语句](/official/Reference/Core/Alias) * [委托类型](/official/Features/Language/Delegates) * [API声明](/official/Features/Advanced/API-Declarations) * [增强指针功能](/official/Features/Language/Pointers) --- --- url: /en/official/Features/Language/Delegates.md --- # Delegate Types for Indirect Calls There is native support for calling a function by pointer, by way of `Delegate` syntax. A delegate in twinBASIC is a function pointer type that's compatible with LongPtr. `AddressOf` returns a delegate type, that's also backwards compatible with `LongPtr`. ## Basic Usage The syntax looks like this: ```vb Private Delegate Function Delegate1 (ByVal A As Long, ByVal B As Long) As Long Private Sub Command1_Click() Dim myDelegate As Delegate1 = AddressOf Addition MsgBox "Answer: " & myDelegate(5, 6) End Sub Public Function Addition(ByVal A As Long, ByVal B As Long) As Long Return A + B End Function ``` ## Advanced Usage The delegate type can also be used in interface/API declarations and as members of a User-defined type. For example, the `ChooseColor` API: ```vb Public Delegate Function CCHookProc (ByVal hwnd As LongPtr, ByVal uMsg As Long, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As LongPtr Public Type CHOOSECOLOR lStructSize As Long hwndOwner As LongPtr hInstance As LongPtr rgbResult As Long lpCustColors As LongPtr Flags As ChooseColorFlags lCustData As LongPtr lpfnHook As CCHookProc 'Delegate function pointer type instead of LongPtr lpTemplateName As LongPtr End Type ``` If you already have code assigning a `Long`/`LongPtr` to the `lpfnHook` member, it will continue to work normally, but now you can also have the type safety benefits of setting it to a method matching the Delegate: ```vb Dim tCC As CHOOSECOLOR tCC.lpfnHook = AddressOf ChooseColorHookProc '... Public Function ChooseColorHookProc(ByVal hwnd As LongPtr, ByVal uMsg As Long, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As LongPtr End Function ``` --- --- url: /en/official/Reference/VBA/Interaction/DeleteSetting.md --- # DeleteSetting Deletes a section or key setting from an application's entry in the Windows registry. Syntax: **DeleteSetting** *appname*, *section*, \[ *key* ] *appname* : The name of the application or project whose registry settings are to be deleted. *section* : *optional* The name of the section within the *appname* entry. If omitted, the entire *appname* section, including all keys within, is deleted. *key* : *optional* The name of the key to delete within the specified *section*. If omitted, the entire **section** and all keys within are deleted. A run-time error occurs when **DeleteSetting** is called for a non-existent *appname*, *section*, or *key*. The root of these registry settings is: `Computer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings`. ## Example The following example first uses the [**SaveSetting**](/en/official/Reference/VBA/Interaction/SaveSetting) statement to make entries in the Windows registry for the application, and then uses the **DeleteSetting** statement to remove them. Because no *key* argument is specified, the whole section is deleted, including the section name and all its keys. ```vb ' Place some settings in the registry. SaveSetting appname := "MyApp", section := "Startup", _ key := "Top", setting := 75 SaveSetting "MyApp", "Startup", "Left", 50 ' Remove section and all its settings from registry. DeleteSetting "MyApp", "Startup" ``` --- --- url: /zh/official/Reference/VBA/Interaction/DeleteSetting.md --- # DeleteSetting 从Windows注册表中应用程序条目删除节或键设置。 语法:**DeleteSetting** *appname*, *section*, \[ *key* ] *appname* : 要删除其注册表设置的应用程序或项目的名称。 *section* : *可选* *appname*条目中节的名称。如果省略,则删除整个*appname*节,包括其中的所有键。 *key* : *可选* 要在指定*section*中删除的键的名称。如果省略,则删除整个**section**及其中的所有键。 对不存在的*appname*、*section*或*key*调用**DeleteSetting**时会产生运行时错误。 这些注册表设置的根路径为:`Computer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings`。 ## 示例 以下示例首先使用[**SaveSetting**](/official/Reference/VBA/Interaction/SaveSetting)语句在Windows注册表中为应用程序创建条目,然后使用**DeleteSetting**语句将其删除。由于未指定*key*参数,整个节被删除,包括节名称及其所有键。 ```vb ' Place some settings in the registry. SaveSetting appname := "MyApp", section := "Startup", _ key := "Top", setting := 75 SaveSetting "MyApp", "Startup", "Left", 50 ' Remove section and all its settings from registry. DeleteSetting "MyApp", "Startup" ``` --- --- url: /zh/official/Reference/Core/DeleteSetting.md --- # DeleteSetting 语句 deletesetting 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/DeleteSetting.md --- # DeleteSetting Statement Documentation for the deletesetting keyword is not yet available. --- --- url: /en/official/Reference/VBA/ErrObject/Description.md --- # Description Returns or sets a **String** containing a descriptive message associated with the active error. Read/write. Syntax: * **Err**.**Description** * **Err**.**Description** **=** *errorDescription* *errorDescription* : A **String** describing the error. When read, **Description** returns the descriptive text for the active error, or a zero-length string if no error is active. The **Description** setting consists of a short description of the error. Use this property to alert the user to an error that the code cannot or does not handle. When generating a user-defined error, assign a short description of the error to the **Description** property. If **Description** isn't filled in and the value of [**Number**](/en/official/Reference/VBA/ErrObject/Number) corresponds to a built-in run-time error, the string returned by the [**Error**](/en/official/Reference/VBA/Conversion/Error) function is placed in **Description** when the error is generated. ### Example This example assigns a user-defined message to the **Description** property of the **Err** object. ```vb Err.Description = "It was not possible to access an object necessary " _ & "for this operation." ``` ### See Also * [Number](/en/official/Reference/VBA/ErrObject/Number) property * [Source](/en/official/Reference/VBA/ErrObject/Source) property * [Raise](/en/official/Reference/VBA/ErrObject/Raise) method * [Clear](/en/official/Reference/VBA/ErrObject/Clear) method --- --- url: /zh/official/Reference/VBA/ErrObject/Description.md --- # Description 返回或设置一个 **String**,包含与活动错误关联的描述性消息。可读/写。 语法: * **Err**.**Description** * **Err**.**Description** **=** *errorDescription* *errorDescription* : 描述错误的 **String**。读取时,**Description** 返回活动错误的描述文本,如果没有活动错误则返回零长度字符串。 **Description** 设置由错误的简短描述组成。使用此属性向用户提示代码无法或未处理的错误。 当生成用户定义的错误时,将错误的简短描述赋给 **Description** 属性。如果未填写 **Description** 且 [**Number**](/official/Reference/VBA/ErrObject/Number) 的值对应于内置运行时错误,则在生成错误时,[**Error**](/official/Reference/VBA/Conversion/Error) 函数返回的字符串将被放入 **Description**。 ### 示例 此示例将用户定义的消息赋给 **Err** 对象的 **Description** 属性。 ```vb Err.Description = "It was not possible to access an object necessary " _ & "for this operation." ``` ### 另请参阅 * [Number](/official/Reference/VBA/ErrObject/Number) 属性 * [Source](/official/Reference/VBA/ErrObject/Source) 属性 * [Raise](/official/Reference/VBA/ErrObject/Raise) 方法 * [Clear](/official/Reference/VBA/ErrObject/Clear) 方法 --- --- url: /en.md --- ::: info ℹ️ About This Site This is a **community mirror site** for twinBASIC documentation, created because the official website is sometimes inaccessible in certain regions. * 🌐 Official Website: <https://twinbasic.com> * 📖 Official Docs: <https://docs.twinbasic.com> * 💬 Join Discord: <https://discord.gg/UaW9GgKKuE> ::: # Development ## Core Features ✨ ### Perfect Compatibility 🤝 * 100% backward compatible with existing VB6/VBA codebases * Fully based on COM technology, consistent with classic Visual Basic versions * Simulates all known VB6 features and behaviors ### Modern Development Environment 💻 * Lightweight, modern dedicated IDE * Monaco-based code editor * Support for dark and light themes * Code folding capability * Real-time code hints * Syntax highlighting * Real-time project error diagnostics ### Powerful Compiler Features 🔧 * Native 32-bit and 64-bit compilation support * Complete Unicode support * Generates standalone executables without runtime libraries * Multi-threaded compilation process for excellent performance * Planned support for Mac, Linux, and Android platforms ### Enhanced Language Features 🌟 * Bit-shift operators support * Class instance AddressOf * Inheritance support * Inline assembly * Procedure overloading * Multi-threading syntax (coming soon) * Generics support (similar to VB.NET but more flexible) * New data types: LongLong, LongPtr, Decimal * New operators: AndAlso, OrElse, <<, >> * New assignment operators: +=, -=, \*=, etc. ### Built-in Debugger 🔍 * Multi-thread debugging support * Call stack window * Variables window * Watch window * Debug console ### New Built-in Controls 🎮 * FlexGrid support * QRCode generator * Support for more custom controls ## Package Management Features 📦 * Built-in package server * TWINPACK package format support * Convenient package import and update mechanism ## Why Choose twinBasic? 🤔 * Seamless upgrade path for existing VB6/VBA projects * Modern development experience * Active community support * Continuous updates and improvements * No runtime dependencies * Professional technical support ## Join the Community 👥 * Join the Discord community <https://discord.gg/UaW9GgKKuE> * Follow official updates * Participate in GitHub issue tracking * Become a VIP Gold member for additional support * Join to QQ group [788160802](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027\&k=c9Pkw_KrA0V0VYNhHq1bQ3ury6s85ZmM\&authKey=QJ4ZvpFfXPivXHgvfpcnbPg%2F99jOQOqvHArXoPz5VIvFX%2Bn%2BV0CBf8uQf%2F14aLrn\&noverify=0\&group_code=788160802) > Note: twinBasic is under active development with daily updates being the norm. It's recommended to follow official channels for the latest updates. --- --- url: /en/official/IDE/Diagnostics.md --- # Diagnostics ![Diagnostics](/assets/Diagnostics.D_TiNJxY.png) ![Diagnostics](/assets/Diagnostics_Toggles.DBEs0SQw.png) ![Diagnostics](/assets/Diagnostics_Totals.D0b1V0ny.png) ## Categories * 🟥 Error * 🟨 Warning * 🟩 Hints * 🟦 Info --- --- url: /en/official/Reference/Core/Dim.md --- # Dim Declares variables and allocates storage space. Syntax: **Dim** \[ **WithEvents** ] *varname* \[ **(** \[ *subscripts* ] **)** ] \[ **As** \[ **New** ] *type* ] \[ **=** *expression* ] \[ **,** \[ **WithEvents** ] *varname* \[ **(** \[ *subscripts* ] **)** ] \[ **As** \[ **New** ] *type* ] \[ **=** *expression* ] ] **. . .** **WithEvents** : *optional* Keyword that specifies that *varname* is an object variable used to respond to events triggered by an ActiveX object. **WithEvents** is valid only in class modules. Any number of individual variables may be declared by using **WithEvents**, but arrays cannot be declared with **WithEvents**. **New** cannot be combined with **WithEvents**. *varname* : Name of the variable; follows standard variable naming conventions. *subscripts* : *optional* Dimensions of an array variable; up to 60 multiple dimensions may be declared. The *subscripts* argument uses the following syntax: \[ *lower* **To** ] *upper* \[ , \[ *lower* **To** ] *upper* ] **. . .**. When not explicitly stated in *lower*, the lower bound of an array is controlled by the [**Option Base**](/en/official/Reference/Core/Option#Base) statement. The lower bound is zero if no **Option Base** statement is present. **New** : *optional* Keyword that enables implicit creation of an object. When **New** is used to declare the object variable, a new instance of the object is created on first reference to it, so the **Set** statement is not required to assign the object reference. The **New** keyword can't be used to declare variables of any intrinsic data type or to declare instances of dependent objects, and it can't be used with **WithEvents**. *type* : *optional*. Data type of the variable; may be **Byte**, **Boolean**, **Integer**, **Long**, **LongLong**, **LongPtr**, **Currency**, **Single**, **Double**, **Decimal**, **Date**, **String** (for variable-length strings), **String** *length* (for fixed-length strings), **Object**, **Variant**, a user-defined type (UDT), an object type, or **Any** (twinBASIC; type is inferred from *expression* --- see [Type Inference](/en/official/Features/Language/Type-Inference)). Use a separate **As** *type* clause for each declared variable. *expression* : *optional*. (twinBASIC) Initial value assigned to the variable at declaration. Equivalent to a separate assignment statement immediately after the **Dim** --- `Dim i As Long = 1` is the same as `Dim i As Long: i = 1`. For object types, `= New *type* ( *args* )` constructs an instance (and may pass custom-constructor arguments). When *type* is **Any**, *expression* is required and determines the inferred type. See [Inline Variable Initialization](/en/official/Features/Language/Inline-Initialization). Variables declared with **Dim** at the module level are available to all procedures within the module. At the procedure level, variables are available only within the procedure. Use the **Dim** statement at the module or procedure level to declare the data type of a variable. For example, the following statement declares a variable as an **Integer**. ```vb Dim NumberOfEmployees As Integer ``` Also use a **Dim** statement to declare the object type of a variable. The following declares a variable for a new instance of a worksheet. ```vb Dim X As New Worksheet ``` If the **New** keyword is not used when declaring an object variable, the variable that refers to the object must be assigned an existing object by using the **Set** statement before it can be used. Until it is assigned an object, the declared object variable has the special value **Nothing**, which indicates that it doesn't refer to any particular instance of an object. The **Dim** statement with empty parentheses also declares a dynamic array. After declaring a dynamic array, use the [**ReDim**](/en/official/Reference/Core/ReDim) statement within a procedure to define the number of dimensions and elements in the array. Redeclaring a dimension for an array variable whose size was explicitly specified in a [**Private**](/en/official/Reference/Core/Private), [**Public**](/en/official/Reference/Core/Public), or **Dim** statement raises an error. When no data type or object type is specified, and there is no [**Deftype**](/en/official/Reference/Core/Deftype) statement in the module, the variable is **Variant** by default. When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros. **Variant** variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable. By convention, a **Dim** statement inside a procedure is placed at the beginning of the procedure. ### Example This example shows the **Dim** statement used to declare variables. It also shows the **Dim** statement used to declare arrays. The default lower bound for array subscripts is 0 and can be overridden at the module level by using the **Option Base** statement. ```vb ' AnyValue and MyValue are declared as Variant by default with values ' set to Empty. Dim AnyValue, MyValue ' Explicitly declare a variable of type Integer. Dim Number As Integer ' Multiple declarations on a single line. AnotherVar is of type Variant ' because its type is omitted. Dim AnotherVar, Choice As Boolean, BirthDate As Date ' DayArray is an array of Variants with 51 elements indexed, from ' 0 thru 50, assuming Option Base is set to 0 (default) for ' the current module. Dim DayArray(50) ' Matrix is a two-dimensional array of integers. Dim Matrix(3, 4) As Integer ' MyMatrix is a three-dimensional array of doubles with explicit ' bounds. Dim MyMatrix(1 To 5, 4 To 9, 3 To 5) As Double ' BirthDay is an array of dates with indexes from 1 to 10. Dim BirthDay(1 To 10) As Date ' MyArray is a dynamic array of variants. Dim MyArray() ``` --- --- url: /zh/official/Reference/Core/Dim.md --- # Dim 声明变量并分配存储空间。 语法:**Dim** \[ **WithEvents** ] *varname* \[ **(** \[ *subscripts* ] **)** ] \[ **As** \[ **New** ] *type* ] \[ **=** *expression* ] \[ **,** \[ **WithEvents** ] *varname* \[ **(** \[ *subscripts* ] **)** ] \[ **As** \[ **New** ] *type* ] \[ **=** *expression* ] ] **. . .** **WithEvents** : *可选* 关键字,指定 *varname* 是用于响应ActiveX对象触发事件的对象变量。**WithEvents** 仅在类模块中有效。可以使用 **WithEvents** 声明任意数量的单独变量,但不能用 **WithEvents** 声明数组。**New** 不能与 **WithEvents** 组合使用。 *varname* : 变量的名称;遵循标准变量命名约定。 *subscripts* : *可选* 数组变量的维度;最多可声明60个多维维度。*subscripts* 参数使用以下语法:\[ *lower* **To** ] *upper* \[ , \[ *lower* **To** ] *upper* ] **. . .**。当未在 *lower* 中显式指定时,数组的下界由 [**Option Base**](/official/Reference/Core/Option#Base) 语句控制。如果没有 **Option Base** 语句,下界为零。 **New** : *可选* 关键字,启用对象的隐式创建。当使用 **New** 声明对象变量时,在首次引用时创建对象的新实例,因此不需要使用 **Set** 语句来分配对象引用。**New** 关键字不能用于声明任何内部数据类型的变量或依赖对象的实例,也不能与 **WithEvents** 一起使用。 *type* : *可选*。变量的数据类型;可以是 **Byte**、**Boolean**、**Integer**、**Long**、**LongLong**、**LongPtr**、**Currency**、**Single**、**Double**、**Decimal**、**Date**、**String**(变长字符串)、**String** *length*(定长字符串)、**Object**、**Variant**、用户自定义类型(UDT)、对象类型或 **Any**(twinBASIC;类型从 *expression* 推断——参见[类型推断](/official/Features/Language/Type-Inference))。对每个声明的变量使用单独的 **As** *type* 子句。 *expression* : *可选*。(twinBASIC) 声明时赋给变量的初始值。等效于紧接在 **Dim** 之后的单独赋值语句——`Dim i As Long = 1` 与 `Dim i As Long: i = 1` 相同。对于对象类型,`= New *type* ( *args* )` 构造一个实例(并可传递自定义构造函数参数)。当 *type* 为 **Any** 时,*expression* 是必需的并决定推断的类型。参见[内联变量初始化](/official/Features/Language/Inline-Initialization)。 在模块级别使用 **Dim** 声明的变量对该模块内所有过程可用。在过程级别,变量仅在该过程内可用。 在模块或过程级别使用 **Dim** 语句声明变量的数据类型。例如,以下语句声明一个 **Integer** 类型的变量。 ```vb Dim NumberOfEmployees As Integer ``` 也可以使用 **Dim** 语句声明变量的对象类型。以下声明一个工作表新实例的变量。 ```vb Dim X As New Worksheet ``` 如果声明对象变量时未使用 **New** 关键字,则必须在可以使用之前使用 **Set** 语句为引用该对象的变量分配现有对象。在分配对象之前,声明的对象变量具有特殊值 **Nothing**,表示它不引用任何特定对象实例。 带有空括号的 **Dim** 语句也声明动态数组。声明动态数组之后,在过程中使用 [**ReDim**](/official/Reference/Core/ReDim) 语句定义数组的维度和元素数。在 [**Private**](/official/Reference/Core/Private)、[**Public**](/official/Reference/Core/Public) 或 **Dim** 语句中显式指定了大小的数组变量重新声明维度会引发错误。 当未指定数据类型或对象类型,且模块中没有 [**Deftype**](/official/Reference/Core/Deftype) 语句时,变量默认为 **Variant**。变量初始化时,数值变量初始化为0,变长字符串初始化为零长度字符串(""),定长字符串用零填充。**Variant** 变量初始化为Empty。用户自定义类型变量的每个元素像单独变量一样初始化。 按照惯例,过程中的 **Dim** 语句放在过程的开头。 ### 示例 本示例展示使用 **Dim** 语句声明变量。也展示了使用 **Dim** 语句声明数组。数组下标的默认下界为0,可以通过模块级别的 **Option Base** 语句覆盖。 ```vb ' AnyValue and MyValue are declared as Variant by default with values ' set to Empty. Dim AnyValue, MyValue ' Explicitly declare a variable of type Integer. Dim Number As Integer ' Multiple declarations on a single line. AnotherVar is of type Variant ' because its type is omitted. Dim AnotherVar, Choice As Boolean, BirthDate As Date ' DayArray is an array of Variants with 51 elements indexed, from ' 0 thru 50, assuming Option Base is set to 0 (default) for ' the current module. Dim DayArray(50) ' Matrix is a two-dimensional array of integers. Dim Matrix(3, 4) As Integer ' MyMatrix is a three-dimensional array of doubles with explicit ' bounds. Dim MyMatrix(1 To 5, 4 To 9, 3 To 5) As Double ' BirthDay is an array of dates with indexes from 1 to 10. Dim BirthDay(1 To 10) As Date ' MyArray is a dynamic array of variants. Dim MyArray() ``` --- --- url: /en/official/Reference/VBA/FileSystem/Dir.md --- # Dir Returns a **String** representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive. Syntax: **Dir** \[ **(** *pathname* \[ **,** *attributes* ] **)** ] *pathname* : *optional* String expression that specifies a file name; may include directory or folder, and drive. A zero-length string (`""`) is returned if *pathname* is not found. *attributes* : *optional* Constant or numeric expression, whose sum specifies file attributes. If omitted, returns files that match *pathname* but have no attributes. The *attributes* argument settings are: | Constant | Value | Description | |-----------------|-------|------------------------------------------------------------------------------------------| | **vbNormal** | 0 | (Default) Specifies files with no attributes. | | **vbReadOnly** | 1 | Specifies read-only files in addition to files with no attributes. | | **vbHidden** | 2 | Specifies hidden files in addition to files with no attributes. | | **vbSystem** | 4 | Specifies system files in addition to files with no attributes. | | **vbVolume** | 8 | Specifies volume label; if any other attribute is specified, **vbVolume** is ignored. | | **vbDirectory** | 16 | Specifies directories or folders in addition to files with no attributes. | **Dir** supports the use of multiple-character (`*`) and single-character (`?`) wildcards to specify multiple files. The first call to **Dir** must specify *pathname*, or an error occurs. When file attributes are also specified, *pathname* must be included. **Dir** returns the first file name that matches *pathname*. To get any additional file names that match *pathname*, call **Dir** again with no arguments. When no more file names match, **Dir** returns a zero-length string (`""`). After a zero-length string is returned, subsequent calls must specify *pathname*, or an error occurs. A new *pathname* can be specified without first retrieving all of the file names that match the current *pathname*. However, **Dir** cannot be called recursively. Calling **Dir** with the **vbDirectory** attribute does not continually return subdirectories. ::: tip Because file names are retrieved in case-insensitive order on Windows, consider storing returned file names in an array and sorting the array. ::: ### See Also * [ChDir](/en/official/Reference/VBA/FileSystem/ChDir), [ChDrive](/en/official/Reference/VBA/FileSystem/ChDrive), [MkDir](/en/official/Reference/VBA/FileSystem/MkDir), [RmDir](/en/official/Reference/VBA/FileSystem/RmDir) statements * [CurDir](/en/official/Reference/VBA/FileSystem/CurDir) function ### Example This example uses the **Dir** function to check whether certain files and directories exist, and to enumerate files in a folder. ```vb Dim MyFile, MyPath, MyName ' Returns "WIN.INI" (on Microsoft Windows) if it exists. MyFile = Dir("C:\WINDOWS\WIN.INI") ' Returns filename with specified extension. If more than one *.ini ' file exists, the first file found is returned. MyFile = Dir("C:\WINDOWS\*.INI") ' Call Dir again without arguments to return the next *.ini file in ' the same directory. MyFile = Dir ' Return first *.txt file, including files with a set hidden attribute. MyFile = Dir("*.TXT", vbHidden) ' Display the names in C:\ that represent directories. MyPath = "c:\" ' Set the path. MyName = Dir(MyPath, vbDirectory) ' Retrieve the first entry. Do While MyName <> "" ' Start the loop. ' Ignore the current directory and the encompassing directory. If MyName <> "." And MyName <> ".." Then ' Use bitwise comparison to make sure MyName is a directory. If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then Debug.Print MyName ' Display entry only if it End If ' represents a directory. End If MyName = Dir ' Get next entry. Loop ``` --- --- url: /zh/official/Reference/VBA/FileSystem/Dir.md --- # Dir 返回一个**String**,表示与指定模式或文件属性匹配的文件、目录或文件夹的名称,或驱动器的卷标。 语法:**Dir** \[ **(** *pathname* \[ **,** *attributes* ] **)** ] *pathname* : *可选* 字符串表达式,指定文件名;可以包含目录或文件夹以及驱动器。如果未找到*pathname*,则返回零长度字符串(`""`)。 *attributes* : *可选* 常量或数值表达式,其和指定文件属性。如果省略,返回与*pathname*匹配但无属性的文件。 *attributes*参数设置如下: | 常量 | 值 | 描述 | |-----------------|-----|-------------------------------------------------------------------------| | **vbNormal** | 0 | (默认)指定无属性的文件。 | | **vbReadOnly** | 1 | 指定只读文件以及无属性的文件。 | | **vbHidden** | 2 | 指定隐藏文件以及无属性的文件。 | | **vbSystem** | 4 | 指定系统文件以及无属性的文件。 | | **vbVolume** | 8 | 指定卷标;如果指定了任何其他属性,**vbVolume**将被忽略。 | | **vbDirectory** | 16 | 指定目录或文件夹以及无属性的文件。 | **Dir**支持使用多字符(`*`)和单字符(`?`)通配符指定多个文件。 第一次调用**Dir**必须指定*pathname*,否则会产生错误。当同时指定文件属性时,必须包含*pathname*。 **Dir**返回与*pathname*匹配的第一个文件名。要获取与*pathname*匹配的其他文件名,请不带参数再次调用**Dir**。当没有更多文件名匹配时,**Dir**返回零长度字符串(`""`)。返回零长度字符串后,后续调用必须指定*pathname*,否则会产生错误。 可以在不先检索当前*pathname*的所有匹配文件名的情况下指定新的*pathname*。但是,**Dir**不能递归调用。使用**vbDirectory**属性调用**Dir**不会持续返回子目录。 ::: tip 由于Windows上文件名按不区分大小写的顺序检索,建议将返回的文件名存储在数组中并对数组排序。 ::: ### 另请参阅 * [ChDir](/official/Reference/VBA/FileSystem/ChDir)、[ChDrive](/official/Reference/VBA/FileSystem/ChDrive)、[MkDir](/official/Reference/VBA/FileSystem/MkDir)、[RmDir](/official/Reference/VBA/FileSystem/RmDir)语句 * [CurDir](/official/Reference/VBA/FileSystem/CurDir)函数 ### 示例 本示例使用**Dir**函数检查某些文件和目录是否存在,以及枚举文件夹中的文件。 ```vb Dim MyFile, MyPath, MyName ' Returns "WIN.INI" (on Microsoft Windows) if it exists. MyFile = Dir("C:\WINDOWS\WIN.INI") ' Returns filename with specified extension. If more than one *.ini ' file exists, the first file found is returned. MyFile = Dir("C:\WINDOWS\*.INI") ' Call Dir again without arguments to return the next *.ini file in ' the same directory. MyFile = Dir ' Return first *.txt file, including files with a set hidden attribute. MyFile = Dir("*.TXT", vbHidden) ' Display the names in C:\ that represent directories. MyPath = "c:\" ' Set the path. MyName = Dir(MyPath, vbDirectory) ' Retrieve the first entry. Do While MyName <> "" ' Start the loop. ' Ignore the current directory and the encompassing directory. If MyName <> "." And MyName <> ".." Then ' Use bitwise comparison to make sure MyName is a directory. If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then Debug.Print MyName ' Display entry only if it End If ' represents a directory. End If MyName = Dir ' Get next entry. Loop ``` --- --- url: /zh/official/Reference/Core/Dir.md --- # Dir 函数 dir 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/Dir.md --- # Dir Function Documentation for the dir keyword is not yet available. --- --- url: /en/official/Features/Advanced/Assembly.md --- # Emit() and Naked Functions Raw bytecode can be inserted into a binary with tB's `Emit()` function. To support this, functions can be marked as `Naked` to remove hidden tB code. ## Example For example, the following is an implementation of the InterlockedIncrement compiler intrinsic that replaces the API in Microsoft C/C++ (adds one to `Addend` and returns the result, as an atomic operation which isn't guaranteed with regular code): ```vb Public Function InlineInterlockedIncrement CDecl Naked(Addend As Long) As Long #If Win64 Then Emit(&Hb8, &H01, &H00, &H00, &H00) ' mov eax,0x1 Emit(&Hf0, &H0f, &Hc1, &H41, &H00) ' lock xadd DWORD PTR [rcx+0x4],eax Emit(&Hff, &Hc0) ' inc eax Emit(&Hc3) ' ret #Else Emit(&H8b, &H4c, &H24, &H04) ' mov ecx, DWORD PTR _Addend$[esp-4] Emit(&Hb8, &H01, &H00, &H00, &H00) ' mov eax, 1 Emit(&Hf0, &H0f, &Hc1, &H01) ' lock xadd DWORD PTR [ecx], eax Emit(&H40) ' inc eax Emit(&Hc3) ' ret 0 #End If End Function ``` (Note: The `CDecl` calling convention is optional; you can write x86 assembly using `_stdcall` and simply omit the notation.) --- --- url: /en/official/Reference/VB/DirListBox.md --- # DirListBox class A **DirListBox** is a Win32 native list control that displays the directory tree for a single path: the ancestors of the current folder are shown above (each with a closed-folder icon, indented by depth), and the immediate subdirectories of the current folder appear below (each with an open-folder icon at full indent). Double-clicking an entry navigates into it, raising a [**Change**](#change) event. The control is normally placed on a **Form** or **UserControl** at design time alongside a [**DriveListBox**](/en/official/Reference/VB/DriveListBox/) and a [**FileListBox**](/en/official/Reference/VB/FileListBox/), connecting their **Change** events together to build a complete file picker. The default property is [**Path**](#path) and the default event is [**Change**](#change). ```vb Private Sub Form_Load() Drive1.Drive = "C:\" Dir1.Path = Drive1.Drive File1.Path = Dir1.Path End Sub Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub ``` ## Path, ListIndex, and PathSelected The control is built around three closely-related properties: * [**Path**](#path) -- the absolute path of the *current* directory. Set it from code (or by double-clicking an entry) to navigate the list. Defaults to [**App.Path**](/en/official/Reference/VB/App/#path) when the control is first created. * [**ListIndex**](#listindex) -- which entry the user has *selected*. `-1` selects the current folder itself (the deepest of the ancestor entries); `0` and up select successive subdirectories. Selecting an entry is independent of navigating to it --- the selection just moves the highlight. * [**PathSelected**](#pathselected) -- the absolute path that would become **Path** if the selected entry were activated. For an ancestor entry it traverses back up the tree; for a subdirectory it concatenates **Path** and the entry's name. Activating an entry --- by double-clicking, or by an external caller assigning **Path** --- runs the navigation, repopulates the list, and raises [**Change**](#change). Setting **Path** to its current value is a no-op (no event). ## List, ListCount, and NewIndex [**ListCount**](#listcount) is the number of subdirectories of the current folder (it does *not* include the ancestor entries shown above). [**List**](#list) is indexed from zero through `ListCount - 1` and returns the *full path* of the corresponding subdirectory --- convenient when iterating from code: ```vb Dim i As Long For i = 0 To Dir1.ListCount - 1 Debug.Print Dir1.List(i) Next ``` [**NewIndex**](#newindex) tracks the position the most recent entry (ancestor or subdirectory) was inserted at while the list was being populated; it is rarely useful at run time but is read by some compatibility code. [**TopIndex**](#topindex) controls vertical scrolling within the subdirectory portion of the list. Wheel and scroll-bar interactions raise [**Scroll**](#scroll) when [**WheelScrollEvent**](#wheelscrollevent) is **True**. ## Properties ### Appearance Determines how the control's border is drawn by the OS. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). Combined with [**BorderStyle**](#borderstyle) to choose between a flat single-line border and a sunken client edge. ### BackColor The background colour, as an **OLE\_COLOR**. Defaults to the system window-background colour. Used as the fill behind every list item except the selected one (which paints with the system highlight colour). ### BorderStyle A member of [**ControlBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants): **vbNoBorder** (0) or **vbFixedSingleBorder** (1, default). Combined with [**Appearance**](#appearance): a 3-D appearance plus single border yields the standard sunken client edge; flat appearance plus single border yields a one-pixel outline. ### CausesValidation Determines whether the previously focused control's [**Validate**](#validate) event runs before this control receives the focus. **Boolean**, default **True**. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a directory list box. Always **vbDirListBox**. ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the control accepts user input. A disabled directory list box still shows its contents but is dimmed and ignores keyboard and mouse interaction. **Boolean**, default **True**. ### Font The **StdFont** used to render directory names. The convenience properties **FontName**, **FontSize**, **FontBold**, **FontItalic**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. Changing the font rescales each item's row height when [**IntegralHeight**](#integralheight) is **True**. ### ForeColor The text colour for entries that are not currently selected, as an **OLE\_COLOR**. Defaults to the system window-text colour. Disabled entries draw in the system grey-text colour, and selected entries draw in the system highlight-text colour, regardless of this setting. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). When [**IntegralHeight**](#integralheight) is **True**, the OS quantises this to a whole number of rows. **Single**. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the control has focus. ### hWnd The Win32 window handle for the underlying list box, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Read-only at run time. ### IntegralHeight When **True** (default), the OS adjusts the control's height so that the visible portion shows whole rows rather than partial ones. When **False**, the control honours [**Height**](#height) exactly. **Boolean**. Changing this at run time recreates the underlying window. ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Single**. ### List The full path of the subdirectory at the given index. Read-only. Syntax: *object*.**List**( *Index* ) *Index* : *required* A **Long** zero-based position, from `0` to `ListCount - 1`. The ancestor entries shown above the current folder are not addressable through **List**. ### ListCount The number of subdirectories of the current [**Path**](#path), as a **Long**. Read-only. The ancestor entries shown above the current folder are not counted. ### ListIndex The zero-based index of the selected entry within the subdirectory portion of the list, or `-1` to select the current folder itself. Reading or writing values below `-1` shifts further up the ancestor stack. **Long**. Assigning a value that differs from the current one selects that entry and raises [**Click**](#click). ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### NewIndex The zero-based index at which the most recent list-population step inserted an entry, or `-1` if the list is empty. **Long**, read-only. ### OLEDragMode ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. (VB6's own implementation of automatic drag was non-functional on this control.) ::: ### OLEDropMode How the control responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on a DirListBox. ### Opacity The control's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Requires Windows 8 or later for child controls. ### Parent A reference to the **Form** (or **UserControl**) that contains this control. Read-only. ### Path The absolute path of the current directory. **Default property.** Syntax: *object*.**Path** \[ = *string* ] Reading **Path** returns the path the list is currently displaying --- drive plus joined ancestor names. Setting **Path** repopulates the list to show the new directory and its subdirectories, raising [**Change**](#change) if the new value differs from the current one. Assigning a path that does not exist (or is not a directory) raises run-time error 76 (*Path not found*). The **DriveListBox** and **DirListBox** controls accept each other's "drive \[volume label]" formatting at this property --- `Dir1.Path = Drive1.Drive` does the right thing without manual stripping. ### PathSelected The absolute path that the currently-selected entry refers to. **String**, read-only. For [**ListIndex**](#listindex) `-1` (the current folder) this is the same as [**Path**](#path); for an ancestor entry it traverses back up the tree; for a subdirectory it returns **Path** plus the subdirectory's name. This is the value the control assigns to **Path** when the user double-clicks the selected entry. ### TabIndex The position of the control in the form's TAB-key navigation order. **Long**. ### TabStop Whether the user can reach the control by pressing the **TAB** key. **Boolean**, default **True**. A disabled control is skipped regardless of this setting. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the control. ### Top The vertical distance from the top of the container to the top of the control. **Single**. ### TopIndex The zero-based index of the subdirectory shown at the top of the visible area. Assigning a value scrolls the list so that subdirectory is at the top, and raises [**Scroll**](#scroll) when the value actually changes. **Long**. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered control. Default `-1` disables the effect. Requires Windows 8 or later for child controls. ### Visible Whether the control is shown. **Boolean**, default **True**. ### VisualStyles Whether the OS theme engine should be used when drawing the control. **Boolean**, default **True**. ### WhatsThisHelpID A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### WheelScrollEvent When **True** (default), mouse-wheel notifications over the control raise the [**Scroll**](#scroll) event; when **False**, the wheel still scrolls the list but [**Scroll**](#scroll) is suppressed. **Boolean**. VB6 never raised **Scroll** for wheel events; set this to **False** to match that behaviour exactly. ### Width The control's width. **Single**. ## Methods ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Typically called from a [**MouseDown**](#mousedown) handler when [**DragMode**](#dragmode) is **vbManual**. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the control, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Re-reads the contents of the current [**Path**](#path) from disk and repaints the control. Useful when the directory has been modified outside the application --- the control does not watch the file system on its own. Does not raise [**Change**](#change). Syntax: *object*.**Refresh** ### SetFocus Moves the input focus to the control. The control must be both [**Visible**](#visible) and [**Enabled**](#enabled), or run-time error 5 (*Invalid procedure call or argument*) is raised. Syntax: *object*.**SetFocus** ### ShowWhatsThis Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Change Raised after [**Path**](#path) has changed --- whether the user double-clicked an entry or code assigned a different value to **Path**. Not raised for assignments that match the current value, and not raised during the initial population that occurs before [**Initialize**](#initialize). **Default event.** Syntax: *object*\_**Change**( ) ### Click Raised after [**ListIndex**](#listindex) changes --- whether the user clicked a different entry, used the keyboard to move the selection, or code assigned a different value to [**ListIndex**](#listindex). Also raised when the selection is cancelled (e.g. by clicking the empty area below the last entry). Syntax: *object*\_**Click**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus Raised when the control receives the input focus. Syntax: *object*\_**GotFocus**( ) ### Initialize Raised once, immediately after the underlying window is created and the initial path ([**App.Path**](/en/official/Reference/VB/App/#path)) has been loaded. New in twinBASIC --- VB6 had no equivalent on this control. Syntax: *object*\_**Initialize**( ) ### KeyDown Raised when the user presses any key while the control has focus. Syntax: *object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress Raised when the user types a character that produces an ANSI keystroke. Syntax: *object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp Raised when the user releases a key while the control has focus. Syntax: *object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus Raised when the control loses the input focus. Syntax: *object*\_**LostFocus**( ) ### MouseDown Raised when the user presses any mouse button over the control. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the control. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the control. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Scroll Raised when the visible portion of the list scrolls --- by the scroll bar, the keyboard, or (when [**WheelScrollEvent**](#wheelscrollevent) is **True**) the mouse wheel. The new offset can be read from [**TopIndex**](#topindex). Syntax: *object*\_**Scroll**( ) ### Validate Raised when the focus is moving to another control whose [**CausesValidation**](#causesvalidation) is **True**. Setting *Cancel* to **True** keeps the focus on this control. Syntax: *object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /zh/official/Reference/VB/DirListBox.md --- # DirListBox 类 **DirListBox**是一个Win32原生列表控件,用于显示单个路径的目录树:当前文件夹的祖先目录显示在上方(每个带有关闭文件夹图标,按深度缩进),当前文件夹的直接子目录显示在下方(每个带有打开文件夹图标,全缩进)。双击某个条目会导航到该目录,并引发[**Change**](#change)事件。该控件通常在设计时放置在**Form**或**UserControl**上,与[**DriveListBox**](/official/Reference/VB/DriveListBox/)和[**FileListBox**](/official/Reference/VB/FileListBox/)一起使用,通过连接它们的**Change**事件来构建完整的文件选择器。默认属性是[**Path**](#path),默认事件是[**Change**](#change)。 ```vb Private Sub Form_Load() Drive1.Drive = "C:\" Dir1.Path = Drive1.Drive File1.Path = Dir1.Path End Sub Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub ``` ## Path、ListIndex 和 PathSelected 该控件围绕三个密切相关的属性构建: * [**Path**](#path) -- *当前*目录的绝对路径。通过代码(或双击某个条目)设置它来导航列表。控件首次创建时默认为[**App.Path**](/official/Reference/VB/App/#path)。 * [**ListIndex**](#listindex) -- 用户*选中*的条目索引。`-1`选择当前文件夹本身(祖先条目中最深的一个);`0`及以上选择依次的子目录。选择条目与导航到该条目是独立的操作——选择只是移动高亮显示。 * [**PathSelected**](#pathselected) -- 如果激活当前选中条目将成为**Path**的绝对路径。对于祖先条目,它会沿目录树向上回溯;对于子目录,它会拼接**Path**和条目名称。 激活条目——通过双击,或由外部调用者赋值**Path**——会执行导航、重新填充列表并引发[**Change**](#change)。将**Path**设置为当前值是空操作(不引发事件)。 ## List、ListCount 和 NewIndex [**ListCount**](#listcount)是当前文件夹的子目录数量(*不*包括上方显示的祖先条目)。[**List**](#list)从零索引到`ListCount - 1`,返回对应子目录的*完整路径*——从代码中迭代时很方便: ```vb Dim i As Long For i = 0 To Dir1.ListCount - 1 Debug.Print Dir1.List(i) Next ``` [**NewIndex**](#newindex)跟踪列表填充过程中最近条目(祖先或子目录)插入的位置;它在运行时很少使用,但某些兼容性代码会读取它。 [**TopIndex**](#topindex)控制列表子目录部分的垂直滚动。当[**WheelScrollEvent**](#wheelscrollevent)为**True**时,鼠标滚轮和滚动条交互会引发[**Scroll**](#scroll)。 ## 属性 ### Appearance 确定操作系统如何绘制控件的边框。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。与[**BorderStyle**](#borderstyle)组合使用,可选平面单线边框或凹陷的客户端边缘。 ### BackColor 背景颜色,类型为**OLE\_COLOR**。默认为系统窗口背景色。用作除选中项之外所有列表项的填充色(选中项使用系统高亮色绘制)。 ### BorderStyle [**ControlBorderStyleConstants**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants)的成员:**vbNoBorder** (0)或**vbFixedSingleBorder** (1,默认)。与[**Appearance**](#appearance)组合使用:3D外观加单线边框产生标准的凹陷客户端边缘;平面外观加单线边框产生一像素轮廓线。 ### CausesValidation 确定先前获得焦点的控件的[**Validate**](#validate)事件是否在此控件获得焦点之前运行。**Boolean**,默认**True**。 ### ControlType 只读的[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值,将此控件标识为目录列表框。始终为**vbDirListBox**。 ### DragIcon 控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自动拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual** (0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic** (1)。 ### Enabled 确定控件是否接受用户输入。禁用的目录列表框仍显示其内容,但变暗并忽略键盘和鼠标交互。**Boolean**,默认**True**。 ### Font 用于渲染目录名的**StdFont**。便捷属性**FontName**、**FontSize**、**FontBold**、**FontItalic**、**FontStrikethru**和**FontUnderline**读写此对象的相应成员。当[**IntegralHeight**](#integralheight)为**True**时,更改字体会重新缩放每项的行高。 ### ForeColor 未选中条目的文本颜色,类型为**OLE\_COLOR**。默认为系统窗口文本色。禁用条目使用系统灰色文本色绘制,选中条目使用系统高亮文本色绘制,不受此设置影响。 ### Height 控件的高度,默认以缇为单位(或使用容器的**ScaleMode**单位)。当[**IntegralHeight**](#integralheight)为**True**时,操作系统将其量化为整行数。**Single**。 ### HelpContextID 标识应用程序帮助文件中主题的**Long**值,当用户在控件具有焦点时按**F1**时检索。 ### hWnd 底层列表框的Win32窗口句柄,类型为**LongPtr**。只读。可用于传递给API函数。 ### Index 当控件是控件数组的一部分时,此实例在数组中的从零开始的**Long**索引。运行时只读。 ### IntegralHeight 当为**True**(默认)时,操作系统调整控件高度,使可见部分显示完整行而非部分行。当为**False**时,控件精确遵循[**Height**](#height)。**Boolean**。在运行时更改此属性会重新创建底层窗口。 ### Left 从容器的左边缘到控件左边缘的水平距离。**Single**。 ### List 给定索引处子目录的完整路径。只读。 语法:*object*.**List**( *Index* ) *Index* : *必需* 从零开始的**Long**位置,从`0`到`ListCount - 1`。当前文件夹上方显示的祖先条目不能通过**List**访问。 ### ListCount 当前[**Path**](#path)的子目录数量,类型为**Long**。只读。当前文件夹上方显示的祖先条目不计入。 ### ListIndex 列表子目录部分中选中条目的从零开始的索引,或`-1`选择当前文件夹本身。读取或写入低于`-1`的值会沿祖先栈进一步上移。**Long**。赋值与当前值不同的值会选中该条目并引发[**Click**](#click)。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针位于控件上时用作鼠标光标的**StdPicture**。 ### MousePointer 指针位于控件上时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### NewIndex 最近列表填充步骤插入条目的从零开始的索引,如果列表为空则为`-1`。**Long**,只读。 ### OLEDragMode ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。(VB6本身对此控件的自动拖动实现也是不可用的。) ::: ### OLEDropMode 控件如何响应OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**或**vbOLEDropManual**。DirListBox不支持自动放置模式。 ### Opacity 控件的不透明度百分比(0--100,默认100)。超出范围的值在**Initialize**时被钳制。子控件需要Windows 8或更高版本。 ### Parent 对包含此控件的**Form**(或**UserControl**)的引用。只读。 ### Path 当前目录的绝对路径。**默认属性。** 语法:*object*.**Path** \[ = *string* ] 读取**Path**返回列表当前显示的路径——驱动器加连接的祖先名称。设置**Path**会重新填充列表以显示新目录及其子目录,如果新值与当前值不同则引发[**Change**](#change)。赋值不存在的路径(或非目录路径)会引发运行时错误76(*Path not found*)。 **DriveListBox**和**DirListBox**控件在此属性上接受彼此的"驱动器 \[卷标]"格式——`Dir1.Path = Drive1.Drive`无需手动剥离即可正常工作。 ### PathSelected 当前选中条目引用的绝对路径。**String**,只读。对于[**ListIndex**](#listindex)为`-1`(当前文件夹),这与[**Path**](#path)相同;对于祖先条目,沿目录树向上回溯;对于子目录,返回**Path**加上子目录名称。这是用户双击选中条目时控件赋给**Path**的值。 ### TabIndex 控件在窗体TAB键导航顺序中的位置。**Long**。 ### TabStop 用户是否可以通过按**TAB**键到达控件。**Boolean**,默认**True**。禁用的控件无论此设置如何都会被跳过。 ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### ToolTipText 当用户将鼠标悬停在控件上时作为工具提示显示的多行**String**。 ### Top 从容器顶部到控件顶部的垂直距离。**Single**。 ### TopIndex 可见区域顶部显示的子目录的从零开始的索引。赋值会滚动列表使该子目录位于顶部,当值实际改变时引发[**Scroll**](#scroll)。**Long**。 ### TransparencyKey 一个**OLE\_COLOR**值,设置后在渲染的控件中变为完全透明。默认`-1`禁用此效果。子控件需要Windows 8或更高版本。 ### Visible 控件是否显示。**Boolean**,默认**True**。 ### VisualStyles 绘制控件时是否使用操作系统主题引擎。**Boolean**,默认**True**。 ### WhatsThisHelpID 标识应用程序帮助文件中"这是什么?"弹出帮助主题的**Long**值。参见[**ShowWhatsThis**](#showwhatsthis)。 ### WheelScrollEvent 当为**True**(默认)时,控件上的鼠标滚轮通知引发[**Scroll**](#scroll)事件;当为**False**时,滚轮仍会滚动列表但[**Scroll**](#scroll)被抑制。**Boolean**。VB6从不为滚轮事件引发**Scroll**;将此设置为**False**可完全匹配该行为。 ### Width 控件的宽度。**Single**。 ## 方法 ### Drag 开始、完成或取消手动拖放操作。通常在[**DragMode**](#dragmode)为**vbManual**时从[**MouseDown**](#mousedown)处理程序中调用。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel** (0)、**vbBeginDrag** (1,默认)或**vbEndDrag** (2)。 ### Move 在单次调用中重新定位并可选地调整控件大小。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**值。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从控件发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### Refresh 从磁盘重新读取当前[**Path**](#path)的内容并重绘控件。当目录在应用程序外部被修改时很有用——控件不会自行监视文件系统。不引发[**Change**](#change)。 语法:*object*.**Refresh** ### SetFocus 将输入焦点移至控件。控件必须同时[**Visible**](#visible)和[**Enabled**](#enabled),否则引发运行时错误5(*Invalid procedure call or argument*)。 语法:*object*.**SetFocus** ### ShowWhatsThis 以"这是什么?"弹出的方式显示由[**WhatsThisHelpID**](#whatsthishelpid)标识的主题。 语法:*object*.**ShowWhatsThis** ### ZOrder 将控件置于其同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront** (0,默认)或**vbSendToBack** (1)。 ## 事件 ### Change 在[**Path**](#path)更改后引发——无论用户双击了条目还是代码赋值了不同的**Path**值。对于与当前值相同的赋值不引发,在[**Initialize**](#initialize)之前发生的初始填充期间也不引发。**默认事件。** 语法:*object*\_**Change**( ) ### Click 在[**ListIndex**](#listindex)更改后引发——无论用户点击了不同的条目、使用键盘移动选择,还是代码赋值了不同的[**ListIndex**](#listindex)值。当选择被取消时也会引发(例如点击最后一个条目下方的空白区域)。 语法:*object*\_**Click**( ) ### DragDrop 手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus 控件获得输入焦点时引发。 语法:*object*\_**GotFocus**( ) ### Initialize 在底层窗口创建且初始路径([**App.Path**](/official/Reference/VB/App/#path))加载后立即引发一次。twinBASIC新增——VB6在此控件上没有等效功能。 语法:*object*\_**Initialize**( ) ### KeyDown 用户在控件具有焦点时按下任意键引发。 语法:*object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress 用户键入产生ANSI击键的字符时引发。 语法:*object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp 用户在控件具有焦点时释放键引发。 语法:*object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus 控件失去输入焦点时引发。 语法:*object*\_**LostFocus**( ) ### MouseDown 用户在控件上按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 光标在控件上移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 用户在控件上释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 用户将数据放置到目标控件上时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的数据格式时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Scroll 列表的可见部分滚动时引发——通过滚动条、键盘或(当[**WheelScrollEvent**](#wheelscrollevent)为**True**时)鼠标滚轮。新偏移量可从[**TopIndex**](#topindex)读取。 语法:*object*\_**Scroll**( ) ### Validate 焦点移动到另一个[**CausesValidation**](#causesvalidation)为**True**的控件时引发。将*Cancel*设置为**True**可使焦点保留在此控件上。 语法:*object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /en/official/Reference/VBRUN/AmbientProperties/DisplayAsDefault.md --- # DisplayAsDefault Returns whether the container is treating this control as its default control, as a **Boolean**. Read-only. Syntax: *object*.**DisplayAsDefault** *object* : *required* An object expression that evaluates to an **AmbientProperties** object. The default control on a form is the one activated when the user presses **Enter** without first giving focus to another control --- most often a command button. A control that wants to advertise its default-button status should paint itself with the heavier border or other distinguishing visual when **DisplayAsDefault** is **True**. ### Example This example responds to a **DisplayAsDefault** change and triggers a repaint to update the button border. ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "DisplayAsDefault" UserControl.Refresh ' repaint to show or remove the default-button border End Select End Sub ``` ### See Also * [ShowGrabHandles](/en/official/Reference/VBRUN/AmbientProperties/ShowGrabHandles) property * [ShowHatching](/en/official/Reference/VBRUN/AmbientProperties/ShowHatching) property * [SupportsMnemonics](/en/official/Reference/VBRUN/AmbientProperties/SupportsMnemonics) property --- --- url: /zh/official/Reference/VBRUN/AmbientProperties/DisplayAsDefault.md --- # DisplayAsDefault 返回容器是否将此控件视为其默认控件,类型为**Boolean**。只读。 语法:*object*.**DisplayAsDefault** *object* : *必需* 求值为**AmbientProperties**对象的对象表达式。 窗体上的默认控件是用户按下**Enter**键而未先将焦点给予其他控件时激活的控件——通常是命令按钮。希望宣传其默认按钮状态的控件应在**DisplayAsDefault**为**True**时以更粗的边框或其他区分性视觉效果绘制自身。 ### 示例 此示例响应**DisplayAsDefault**更改并触发重绘以更新按钮边框。 ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "DisplayAsDefault" UserControl.Refresh ' 重绘以显示或移除默认按钮边框 End Select End Sub ``` ### 另见 * [ShowGrabHandles](/official/Reference/VBRUN/AmbientProperties/ShowGrabHandles) 属性 * [ShowHatching](/official/Reference/VBRUN/AmbientProperties/ShowHatching) 属性 * [SupportsMnemonics](/official/Reference/VBRUN/AmbientProperties/SupportsMnemonics) 属性 --- --- url: /en/official/Reference/VBRUN/AmbientProperties/DisplayName.md --- # DisplayName Returns the name the container has assigned to the control, as a **String**. Read-only. Syntax: *object*.**DisplayName** *object* : *required* An object expression that evaluates to an **AmbientProperties** object. The host typically returns the name by which the user identifies the control --- for example `"Form1!Command1"` in a designer, or whatever label has been chosen at run time. A control can include this string in error messages, log entries, or property browsers so that the user can tell which instance the message refers to. ### Example This example responds to a **DisplayName** change and updates the control's tooltip. ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "DisplayName" ToolTipText = Ambient.DisplayName End Select End Sub ``` ### See Also * [LocaleID](/en/official/Reference/VBRUN/AmbientProperties/LocaleID) property * [UserMode](/en/official/Reference/VBRUN/AmbientProperties/UserMode) property --- --- url: /zh/official/Reference/VBRUN/AmbientProperties/DisplayName.md --- # DisplayName 返回容器分配给控件的名称,类型为**String**。只读。 语法:*object*.**DisplayName** *object* : *必需* 求值为**AmbientProperties**对象的对象表达式。 宿主通常返回用户标识控件的名称——例如设计器中的`"Form1!Command1"`,或运行时选择的任何标签。控件可将此字符串包含在错误消息、日志条目或属性浏览器中,使用户能够知道消息指向哪个实例。 ### 示例 此示例响应**DisplayName**更改并更新控件的工具提示。 ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "DisplayName" ToolTipText = Ambient.DisplayName End Select End Sub ``` ### 另见 * [LocaleID](/official/Reference/VBRUN/AmbientProperties/LocaleID) 属性 * [UserMode](/official/Reference/VBRUN/AmbientProperties/UserMode) 属性 --- --- url: /en/official/Reference/Core/Do-Loop.md --- # Do...Loop Repeats a block of statements while a condition is **True** or until a condition becomes **True**. Syntax: * > **Do** \[{ **While** | **Until** } *condition* ]\ >     \[ *statements* ]\ >     \[ **Exit Do** | **Continue Do** ]\ >     \[ *statements* ] ...\ > **Loop** * > **Do**\ >     \[ *statements* ]\ >     \[ **Exit Do** | **Continue Do** ]\ >     \[ *statements* ] ...\ > **Loop** \[{ **While** | **Until** } *condition* ] *condition* : *optional* Numeric expression or string expression that is **True** or **False**. If *condition* is Null, *condition* is treated as **False**. *statements* : One or more statements that are repeated while, or until, *condition* is **True**. Any number of [**Exit Do**](/en/official/Reference/Core/Exit) statements may be placed anywhere in the **Do…Loop** as an alternate way to exit a **Do…Loop**. **Exit Do** is often used after evaluating some condition, for example, **If…Then**, in which case the **Exit Do** statement transfers control to the statement immediately following the **Loop**. When used within nested **Do…Loop** statements, **Exit Do** transfers control to the loop that is one nested level above the loop where **Exit Do** occurs. Any number of [**Continue Do**](/en/official/Reference/Core/Continue) statements may be placed anywhere in the **Do…Loop** to skip the rest of the statements and proceed with a new iteration. ### Example This example shows how **Do...Loop** statements can be used. The inner **Do...Loop** statement loops 10 times, asks the user if it should keep going, sets the value of the flag to **False** when they select **No**, and exits prematurely by using the **Exit Do** statement. The outer loop exits immediately upon checking the value of the flag. ```vb Public Sub LoopExample() Dim Check As Boolean, Counter As Long, Total As Long Check = True: Counter = 0: Total = 0 ' Initialize variables. Do ' Outer loop. Do While Counter < 20 ' Inner Loop Counter = Counter + 1 ' Increment Counter. If Counter Mod 10 = 0 Then ' Check in with the user on every multiple of 10. Check = (MsgBox("Keep going?", vbYesNo) = vbYes) ' Stop when user click's on No If Not Check Then Exit Do ' Exit inner loop. End If Loop Total = Total + Counter ' Exit Do Lands here. Counter = 0 Loop Until Check = False ' Exit outer loop immediately. MsgBox "Counted to: " & Total End Sub ``` ## Using Do...Loop statements Use **Do...Loop** statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is **True** or until a condition becomes **True**. ### Repeating statements while a condition is True There are two ways to use the **While** keyword to check a condition in a **Do...Loop** statement. The condition can be checked before entering the loop, or after the loop has run at least once. In the following `ChkFirstWhile` procedure, the condition is checked before entering the loop. If `myNum` is set to 9 instead of 20, the statements inside the loop will never run. In the `ChkLastWhile` procedure, the statements inside the loop run only once before the condition becomes **False**. ```vb Sub ChkFirstWhile() counter = 0 myNum = 20 Do While myNum > 10 myNum = myNum - 1 counter = counter + 1 Loop MsgBox "The loop made " & counter & " repetitions." End Sub Sub ChkLastWhile() counter = 0 myNum = 9 Do myNum = myNum - 1 counter = counter + 1 Loop While myNum > 10 MsgBox "The loop made " & counter & " repetitions." End Sub ``` ### Repeating statements until a condition becomes True There are two ways to use the **Until** keyword to check a condition in a **Do...Loop** statement. The condition can be checked before entering the loop (as shown in the `ChkFirstUntil` procedure), or after the loop has run at least once (as shown in the `ChkLastUntil` procedure). Looping continues while the condition remains **False**. ```vb Sub ChkFirstUntil() counter = 0 myNum = 20 Do Until myNum = 10 myNum = myNum - 1 counter = counter + 1 Loop MsgBox "The loop made " & counter & " repetitions." End Sub Sub ChkLastUntil() counter = 0 myNum = 1 Do myNum = myNum + 1 counter = counter + 1 Loop Until myNum = 10 MsgBox "The loop made " & counter & " repetitions." End Sub ``` ### Exiting a Do...Loop statement from inside the loop The [**Exit Do**](/en/official/Reference/Core/Exit) statement exits a **Do...Loop** from inside. For example, to exit an endless loop, use the **Exit Do** statement in the **True** statement block of either an [**If...Then...Else**](/en/official/Reference/Core/If-Then-Else) statement or a [**Select Case**](/en/official/Reference/Core/Select-Case) statement. If the condition is **False**, the loop will run as usual. In the following example `myNum` is assigned a value that creates an endless loop. The **If...Then...Else** statement checks for this condition, and then exits, preventing endless looping. ```vb Sub ExitExample() counter = 0 myNum = 9 Do Until myNum = 10 myNum = myNum - 1 counter = counter + 1 If myNum < 10 Then Exit Do Loop MsgBox "The loop made " & counter & " repetitions." End Sub ``` ::: info To stop an endless loop, press ESC or CTRL+BREAK. ::: --- --- url: /zh/official/Reference/Core/Do-Loop.md --- # Do...Loop 当条件为 **True** 时或直到条件变为 **True** 时重复执行语句块。 语法: * > **Do** \[{ **While** | **Until** } *condition* ]\ >     \[ *statements* ]\ >     \[ **Exit Do** | **Continue Do** ]\ >     \[ *statements* ] ...\ > **Loop** * > **Do**\ >     \[ *statements* ]\ >     \[ **Exit Do** | **Continue Do** ]\ >     \[ *statements* ] ...\ > **Loop** \[{ **While** | **Until** } *condition* ] *condition* : *可选* 求值为 **True** 或 **False** 的数值表达式或字符串表达式。如果 *condition* 为Null,则 *condition* 被视为 **False**。 *statements* : 当条件为 **True** 时或直到条件变为 **True** 时重复执行的一条或多条语句。 可以在 **Do…Loop** 中任意位置放置任意数量的 [**Exit Do**](/official/Reference/Core/Exit) 语句作为退出 **Do…Loop** 的替代方式。**Exit Do** 通常在评估某个条件后使用,例如 **If…Then**,此时 **Exit Do** 语句将控制权转移到紧接在 **Loop** 之后的语句。 在嵌套的 **Do…Loop** 语句中使用时,**Exit Do** 将控制权转移到比出现 **Exit Do** 的循环高一层嵌套的循环。 可以在 **Do…Loop** 中任意位置放置任意数量的 [**Continue Do**](/official/Reference/Core/Continue) 语句,以跳过剩余语句并开始新的迭代。 ### 示例 本示例展示如何使用 **Do...Loop** 语句。内部 **Do...Loop** 语句循环10次,询问用户是否继续,当用户选择 **No** 时将标志值设为 **False**,并通过 **Exit Do** 语句提前退出。外层循环在检查标志值后立即退出。 ```vb Public Sub LoopExample() Dim Check As Boolean, Counter As Long, Total As Long Check = True: Counter = 0: Total = 0 ' Initialize variables. Do ' Outer loop. Do While Counter < 20 ' Inner Loop Counter = Counter + 1 ' Increment Counter. If Counter Mod 10 = 0 Then ' Check in with the user on every multiple of 10. Check = (MsgBox("Keep going?", vbYesNo) = vbYes) ' Stop when user click's on No If Not Check Then Exit Do ' Exit inner loop. End If Loop Total = Total + Counter ' Exit Do Lands here. Counter = 0 Loop Until Check = False ' Exit outer loop immediately. MsgBox "Counted to: " & Total End Sub ``` ## 使用 Do...Loop 语句 使用 **Do...Loop** 语句可以不限次数地运行语句块。语句在条件为 **True** 时或直到条件变为 **True** 时重复执行。 ### 当条件为 True 时重复语句 有两种方式使用 **While** 关键字在 **Do...Loop** 语句中检查条件。可以在进入循环之前检查条件,或在循环至少运行一次之后检查条件。 在以下 `ChkFirstWhile` 过程中,条件在进入循环之前检查。如果 `myNum` 设为9而非20,循环内的语句将永远不会执行。在 `ChkLastWhile` 过程中,循环内的语句在条件变为 **False** 之前只执行一次。 ```vb Sub ChkFirstWhile() counter = 0 myNum = 20 Do While myNum > 10 myNum = myNum - 1 counter = counter + 1 Loop MsgBox "The loop made " & counter & " repetitions." End Sub Sub ChkLastWhile() counter = 0 myNum = 9 Do myNum = myNum - 1 counter = counter + 1 Loop While myNum > 10 MsgBox "The loop made " & counter & " repetitions." End Sub ``` ### 直到条件变为 True 时重复语句 有两种方式使用 **Until** 关键字在 **Do...Loop** 语句中检查条件。可以在进入循环之前检查条件(如 `ChkFirstUntil` 过程所示),或在循环至少运行一次之后检查条件(如 `ChkLastUntil` 过程所示)。当条件仍为 **False** 时继续循环。 ```vb Sub ChkFirstUntil() counter = 0 myNum = 20 Do Until myNum = 10 myNum = myNum - 1 counter = counter + 1 Loop MsgBox "The loop made " & counter & " repetitions." End Sub Sub ChkLastUntil() counter = 0 myNum = 1 Do myNum = myNum + 1 counter = counter + 1 Loop Until myNum = 10 MsgBox "The loop made " & counter & " repetitions." End Sub ``` ### 从循环内部退出 Do...Loop 语句 [**Exit Do**](/official/Reference/Core/Exit) 语句从内部退出 **Do...Loop**。例如,要退出无限循环,可在 [**If...Then...Else**](/official/Reference/Core/If-Then-Else) 语句或 [**Select Case**](/official/Reference/Core/Select-Case) 语句的 **True** 语句块中使用 **Exit Do** 语句。如果条件为 **False**,循环将正常运行。 在以下示例中,`myNum` 被赋予一个创建无限循环的值。**If...Then...Else** 语句检查此条件然后退出,防止无限循环。 ```vb Sub ExitExample() counter = 0 myNum = 9 Do Until myNum = 10 myNum = myNum - 1 counter = counter + 1 If myNum < 10 Then Exit Do Loop MsgBox "The loop made " & counter & " repetitions." End Sub ``` ::: info 要停止无限循环,请按ESC或CTRL+BREAK。 ::: --- --- url: /en/official/Reference/CustomControls/Enumerations/DockMode.md --- # DockMode How a control is positioned relative to its container --- attached to one edge, filling the whole client area, or not docked at all (positioned absolutely by [**Left**](/en/official/Reference/CustomControls/#controls) / [**Top**](/en/official/Reference/CustomControls/#controls) / [**Width**](/en/official/Reference/CustomControls/#controls) / [**Height**](/en/official/Reference/CustomControls/#controls)). Used by the **Dock** property that every concrete custom control inherits. | Constant | Value | Description | |----------|-------|-------------| | **tbDockNone** | 0 | Not docked. The control's **Left**, **Top**, **Width**, and **Height** are used directly, modulated by the control's [**Anchors**](/en/official/Reference/CustomControls/Styles/Anchors) when the container resizes. | | **tbDockLeft** | 1 | Attached to the container's left edge. Width is preserved; height is stretched to the container's client area. | | **tbDockTop** | 2 | Attached to the container's top edge. Height is preserved; width is stretched. | | **tbDockRight** | 3 | Attached to the container's right edge. Width is preserved; height is stretched. | | **tbDockBottom** | 4 | Attached to the container's bottom edge. Height is preserved; width is stretched. | | **tbDockFill** | 5 | Fills the entire remaining client area, after other docked siblings have claimed their edges. | Order matters when more than one sibling is docked inside the same container: each docked control claims its edge from whatever client area remains *after* its earlier-added siblings have claimed theirs. The control with **Dock = tbDockFill** is therefore added last so that it inherits the residual space: ```vb Private Sub Form_Load() lblHeader.Dock = tbDockTop ' attached to the top, full width lblStatus.Dock = tbDockBottom ' attached to the bottom, full width pnlTree.Dock = tbDockLeft ' attached to the left, between header and status pnlAside.Dock = tbDockRight ' attached to the right, between header and status pnlMain.Dock = tbDockFill ' fills whatever is left in the middle End Sub ``` Setting **Dock** to anything other than **tbDockNone** makes the control's own [**Anchors**](/en/official/Reference/CustomControls/Styles/Anchors) irrelevant --- docking takes over the position and size completely. Manual positioning resumes when **Dock** is reset to **tbDockNone**. --- --- url: /zh/official/Reference/CustomControls/Enumerations/DockMode.md --- # DockMode 控件相对于其容器的定位方式——附着到一个边缘、填充整个客户区域或不停靠(由 [**Left**](/official/Reference/CustomControls/#controls) / [**Top**](/official/Reference/CustomControls/#controls) / [**Width**](/official/Reference/CustomControls/#controls) / [**Height**](/official/Reference/CustomControls/#controls) 绝对定位)。由每个具体自定义控件继承的 **Dock** 属性使用。 | 常量 | 值 | 说明 | |------|----|------| | **tbDockNone** | 0 | 不停靠。控件的 **Left**、**Top**、**Width** 和 **Height** 直接使用,由控件的 [**Anchors**](/official/Reference/CustomControls/Styles/Anchors) 在容器调整大小时调节。 | | **tbDockLeft** | 1 | 附着到容器左边缘。保留宽度;高度拉伸到容器客户区域。 | | **tbDockTop** | 2 | 附着到容器上边缘。保留高度;宽度拉伸。 | | **tbDockRight** | 3 | 附着到容器右边缘。保留宽度;高度拉伸。 | | **tbDockBottom** | 4 | 附着到容器底边缘。保留高度;宽度拉伸。 | | **tbDockFill** | 5 | 填充其他停靠同级声明边缘后的整个剩余客户区域。 | 当同一容器内有多个同级停靠时顺序很重要:每个停靠控件从*在其之前添加的同级*声明其边缘后的剩余客户区域中声明其边缘。因此 **Dock = tbDockFill** 的控件最后添加以继承残余空间: ```vb Private Sub Form_Load() lblHeader.Dock = tbDockTop ' attached to the top, full width lblStatus.Dock = tbDockBottom ' attached to the bottom, full width pnlTree.Dock = tbDockLeft ' attached to the left, between header and status pnlAside.Dock = tbDockRight ' attached to the right, between header and status pnlMain.Dock = tbDockFill ' fills whatever is left in the middle End Sub ``` 将 **Dock** 设为 **tbDockNone** 以外的任何值会使控件自身的 [**Anchors**](/official/Reference/CustomControls/Styles/Anchors) 无关——停靠完全接管位置和大小。当 **Dock** 重置为 **tbDockNone** 时恢复手动定位。 --- --- url: /en/official/Reference/VBRUN/Constants/DockModeConstants.md --- # DockModeConstants Dock-edge values for forms and toolbars that can be docked against a side of their container. | Constant | Value | Description | |----------|-------|-------------| | **vbDockNone** | 0 | The window is not docked. | | **vbDockLeft** | 1 | The window is docked against the left edge of the container. | | **vbDockTop** | 2 | The window is docked against the top edge. | | **vbDockRight** | 3 | The window is docked against the right edge. | | **vbDockBottom** | 4 | The window is docked against the bottom edge. | | **vbDockFill** | 5 | The window fills the entire container area. | --- --- url: /zh/official/Reference/VBRUN/Constants/DockModeConstants.md --- # DockModeConstants 可停靠到容器某一边缘的窗体和工具栏的停靠边缘值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbDockNone** | 0 | 窗口未停靠。 | | **vbDockLeft** | 1 | 窗口停靠在容器左侧边缘。 | | **vbDockTop** | 2 | 窗口停靠在顶部边缘。 | | **vbDockRight** | 3 | 窗口停靠在右侧边缘。 | | **vbDockBottom** | 4 | 窗口停靠在底部边缘。 | | **vbDockFill** | 5 | 窗口填充整个容器区域。 | --- --- url: /en/official/Documentation.md --- # Documentation Development This section covers everything related to the twinBASIC documentation: the URL contract the compiler and IDE rely on, the build / preview / deploy workflow for content contributors, every script and batch file in the repository, and the internals of the `tbdocs` static site generator that produces the site. ## Toolchain overview Three commands handle the entire build-and-verify workflow. `build.bat` produces three output trees from the markdown source; `check.bat` validates link integrity on the two HTML trees; `book.bat` renders the PDF from the third. ![Toolchain overview](/assets/images/mmd/toolchain-overview.svg) `build.bat` must run before either of the other two --- `check.bat` reads from `_site/` and `_site-offline/`, while `book.bat` reads from `_site-pdf/`. A clean `build.bat && check.bat` is the bar for "ready to commit". ## Build pipeline A single `build.bat` run drives `tbdocs` through eight phases plus a Mermaid pre-phase. ![Build pipeline, eight phases plus the Mermaid pre-phase](/assets/images/mmd/build-phases.svg) Phases 1--6 produce the online tree (`_site/`). Phase 7 mirrors it into a `file://`-browsable offline copy. Phase 8 assembles the sparse PDF source tree that `book.bat` later renders into the final PDF. The [Pipeline Stages](/en/official/Documentation/Pipeline-Stages) page documents every phase's interface contract; the [tbdocs Builder](/en/official/Documentation/Builder) page covers the design rationale. ## Sub-pages * [Permanent Links](/en/official/Documentation/Permanent-Links) --- the stable `/tB/` URL contract under which the IDE help system, in-source `[Documentation(...)]` attribute links, and external references resolve. * [Building and Deployment](/en/official/Documentation/Building) --- the day-to-day workflow for editing content: requirements, building, serving locally, link checking, Mermaid diagrams, screenshots, and the GitHub Pages deployment. * [Tools and Scripts](/en/official/Documentation/Tools) --- one-line-per-tool reference for every script, batch file, and CLI flag exposed by the documentation toolchain (intended audience: doc contributors). * [tbdocs Builder](/en/official/Documentation/Builder) --- detailed technical documentation for the `tbdocs` static site generator that lives under [`builder/`](https://github.com/twinbasic/documentation/tree/main/builder). Read this when modifying the build pipeline itself. Sub-pages: * [Pipeline Stages](/en/official/Documentation/Pipeline-Stages) --- per-stage interface reference: function signatures, reads/writes, and every exported symbol. * [Book Configuration](/en/official/Documentation/Book-Configuration) --- `_book.yml` key reference for the PDF chapter manifest. * [Extending the Builder](/en/official/Documentation/Extending) --- tutorial for adding a new pipeline stage or a markdown-it plugin. * [PDF Generation](/en/official/Documentation/PDF-Generation) --- internals of the PDF renderer: `render-book.mjs`, paged.browser.js, and the pdf-lib shims. * [Library Patches](/en/official/Documentation/Fixes) --- every modification to `paged.browser.js` and the `fast-*.mjs` pdf-lib shims: upstream problem, applied fix, and mechanism. --- --- url: /en/official/Reference/VBA/Interaction/DoEvents.md --- # DoEvents Yields execution so the operating system can dispatch pending window messages and other events. Syntax: **DoEvents()** Returns an **Integer** indicating the number of open forms in the application; returns 0 in hosts that do not maintain a forms collection. **DoEvents** passes control to the operating system. Control is returned to the caller after the operating system has finished processing the events in its queue and after any keystrokes pending in the [**SendKeys**](/en/official/Reference/VBA/Interaction/SendKeys) queue have been delivered. **DoEvents** is most useful for simple things like keeping a UI responsive during a tight loop, or letting the user cancel a long-running operation. For genuinely long-running work, prefer a timer or a background worker (e.g. an out-of-process ActiveX EXE) so the operating system handles the multitasking. ::: warning Whenever the processor is yielded inside an event procedure, that procedure must not be re-entered from a different code path before the original call returns; otherwise the program may behave unpredictably. Likewise, avoid **DoEvents** when other applications might interact with the procedure in unforeseen ways during the time control is yielded. ::: ### Example This example yields to the operating system once every 1000 iterations of a loop. ```vb Dim I As Long, OpenForms As Long For I = 1 To 150000 If I Mod 1000 = 0 Then OpenForms = DoEvents() End If Next I ``` ### See Also * [SendKeys](/en/official/Reference/VBA/Interaction/SendKeys) statement --- --- url: /zh/official/Reference/VBA/Interaction/DoEvents.md --- # DoEvents 让出执行权,以便操作系统能分派挂起的窗口消息和其他事件。 语法:**DoEvents()** 返回一个**Integer**,指示应用程序中打开的窗体数量;在不维护窗体集合的宿主中返回0。 **DoEvents**将控制权传递给操作系统。在操作系统完成处理其队列中的事件以及[**SendKeys**](/official/Reference/VBA/Interaction/SendKeys)队列中挂起的按键交付后,控制权返回给调用者。 **DoEvents**对于简单的事情最有用,例如在紧密循环期间保持UI响应,或让用户取消长时间运行的操作。对于真正长时间运行的工作,建议使用定时器或后台工作器(例如进程外ActiveX EXE),以便操作系统处理多任务。 ::: warning 每当在事件过程中让出处理器时,该过程在原始调用返回之前不得从不同的代码路径重新进入;否则程序可能会产生不可预测的行为。同样,在让出控制权期间其他应用程序可能以不可预见的方式与过程交互时,避免使用**DoEvents**。 ::: ### 示例 本示例在循环中每1000次迭代让出一次控制权给操作系统。 ```vb Dim I As Long, OpenForms As Long For I = 1 To 150000 If I Mod 1000 = 0 Then OpenForms = DoEvents() End If Next I ``` ### 另请参阅 * [SendKeys](/official/Reference/VBA/Interaction/SendKeys)语句 --- --- url: /en/challenge/2026/202601.md --- **Project Name:** Twinbasic Diagnostic Tool - By woeoio **Description:** 🏆 A Windows system diagnostic tool built with TwinBASIC, providing real-time monitoring and multi-format report export capabilities. Inspired by Linux's htop tool, featuring a modular architecture design and running completely independently without any external dependencies. **Reported Diagnostic Categories:** * ✅ **Operating System Information** - Windows version, build number, architecture, computer name, username * ✅ **CPU Information** - Processor name, core count, architecture, frequency, revision * ✅ **Memory Usage** - Physical memory, virtual memory, page file, memory load percentage * ✅ **Disk Information** - All logical drives, disk space, usage rate * ✅ **Process Information** - Running process list, PID, thread count, total processes * ✅ **Environment Variables** - System environment variables (such as PATH, etc.) * ✅ **System Uptime** - System runtime since boot * ✅ **Locale Settings** - Language region, code page, time zone * ✅ **Network Configuration** - Hostname, IP addresses, network adapters * ✅ **Installed Runtimes** - .NET Framework, .NET Core, VC++ Redistributable * ✅ **CPU Real-time Load** - Dynamic CPU usage monitoring ![示例截图](/challenges/202601/demo1.png) ![示例截图](/challenges/202601/demo2.png) *** ## 🎯 Compliance with Competition Requirements ### ✅ Core Requirements (@ai/002.md:15-25) | Requirement | Implementation | | ---------------------------------- | ------------------------------------------------------------------ | | 📦 Built with **twinBASIC** | ✅ Fully developed in TwinBASIC language | | 📁 Single `.twinproj` file | ✅ Single project file, all source code in one project | | 💻 Generate standalone Windows EXE | ✅ Compiles to independent executable file | | 🪟 Windows 10+ compatible | ✅ Uses Win10+ supported APIs, backward compatible | | 🔒 No admin privileges required | ✅ All collectors run under regular user permissions | | 🚫 No external dependencies | ✅ Only uses built-in WinAPI and TwinBASIC features | | 🖥️ Console output | ✅ Provides real-time monitoring mode and multi-format export mode | *** ## 📊 Detailed Evaluation Criteria (@ai/002.md:43-55) ### 1. 📈 Practicality of Reported Information **Implementation Highlights:** * 🎯 **11 diagnostic categories** - Far exceeds the competition's "at least three categories" requirement * 📊 **Dynamic + Static data separation** - Three refresh modes: Static/Dynamic/SemiDynamic * 🔄 **Summary mode support** - Some collectors support lightweight summary data for better performance * 📏 **Smart formatting** - Uses `FormatHelper` for friendly display of byte counts and time * 📋 **Multi-format output** - Supports TEXT, JSON, and HTML report formats * 💻 **Dual-mode operation** - Supports double-click to start real-time monitoring and command-line file export **Usage Methods:** **🖱️ Method 1: Double-click to start (Real-time monitoring + Interactive mode)** ```bash # Double-click diagnostic.exe directly or run without parameters in command line diagnostic.exe ``` * 🎯 Enters real-time monitoring interface, automatically refreshes system status every second * ⌨️ Supports interactive hotkeys (F1/F2/F3/F4/F10/Q/Arrow keys, etc.) * 🔄 Graceful exit with Ctrl+C or press Q/F10 **📤 Method 2: Command-line file export (Batch report generation)** ```bash # Export plain text report (for scripts/batch files) diagnostic.exe /text > report.txt # Export JSON format (for programmatic parsing) diagnostic.exe /json > report.json # Export HTML report (for browser viewing) diagnostic.exe /html > report.html # Get help information diagnostic.exe /help ``` ![示例截图](/challenges/202601/demo3.png) ![示例截图](/challenges/202601/demo4.png) ![示例截图](/challenges/202601/demo5.png) ![示例截图](/challenges/202601/demo6.png) ![示例截图](/challenges/202601/demo7.png) **Usage Scenarios:** * 🔍 **Daily monitoring** - Double-click to start, view system status in real-time * 📊 **Troubleshooting** - Export reports for historical data analysis * 🤖 **Automation scripts** - Combine with command-line export for periodic diagnostics * 📧 **Technical support** - Export HTML/JSON to send to technical teams *** ### 2. ⚡ Performance Optimization **Technical Implementation:** * 🎯 **Refresh mode classification:** * `Static` - System info, CPU info, etc. (fetched once) * `Dynamic` - CPU load, memory, processes, etc. (refreshed every second) * `SemiDynamic` - Disk, network (optional refresh, changes slowly) * 📊 **On-demand data collection:** ```vb ' Real-time monitoring only collects summary (fast) engine.RunAll(True) ' useSummary = True ' Export mode collects complete data engine.RunAll(False) ' useSummary = False ``` * 🚀 **Generic result containers** - `DiagnosticResult(Of T)` avoids code duplication * 🎨 **Double-buffer rendering** - `cConsoleBuffer` reduces screen flicker *** ### 3. 📦 Minimal EXE File Size **Optimization Strategies:** * ✅ **Zero external dependencies** - No third-party libraries * ✅ **Pure WinAPI calls** - Direct system API calls, no intermediate layers * ✅ **Modular design** - Features loaded on-demand * ✅ **Avoid redundant code** - Use generics to eliminate duplication **Expected Result:** Compressed EXE should be in the **~200-400 KB** range *** ### 4. 📖 Code Documentation Completeness or Self-Explanatory **Documentation System:** * 📝 **File header comments** - Explain file purpose * 🎯 **Clear interface definitions** - `IDiagnosticCollector` defines standards * 🔧 **Private method comments** - Explanations for complex logic * 📚 **Console library README** - Detailed documentation in `Console/README.md` **Code Self-Explanatory Nature:** ```vb ' Clear class and method names Public Class OSInfoCollector Implements IDiagnosticCollector Public Property Get IDiagnosticCollector_CategoryName() As String Return "Operating System" ' Clear at a glance End Property End Class ``` *** ### 5. 🧪 Interesting or Clever API Usage **Highlight Techniques:** 1. **`RtlGetVersion` API** - Bypasses compatibility layer to get real Windows version ```vb ' More accurate than GetVersionEx If RtlGetVersion(osvi) = 0 Then ' Gets real Windows 10/11 version number End If ``` 2. **`GetNativeSystemInfo`** - Gets real CPU architecture (x64/x86/ARM64) ```vb GetNativeSystemInfo sysInfo ' Correctly detects even for 64-bit processes on 32-bit systems ``` 3. **`CreateToolhelp32Snapshot`** - Process enumeration without admin privileges ```vb Dim hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) Process32FirstW/NextW enumerates all processes ``` 4. **`GetLogicalDrives` + `GetDiskFreeSpaceEx`** - Combined disk information usage 5. **`GetAdaptersInfo` + `WSA`** - Network information from Winsock 6. **Registry reading** - CPU name dynamically retrieved from `HKEY_LOCAL_MACHINE` ```vb RegOpenKeyExW / RegQueryValueExW ' Gets real CPU model name ``` *** ### 6. 📊 Derived or Inferred System Metrics **Smart Calculations:** 1. **Windows version name derivation** ```vb Private Function GetWindowsVersionName(major, minor, build) As String Select Case major Case 10 If build >= 22000 Then Return "Windows 11" Else Return "Windows 10" ``` 2. **CPU architecture mapping** ```vb PROCESSOR_ARCHITECTURE_AMD64 → "x64 (AMD64)" PROCESSOR_ARCHITECTURE_ARM64 → "ARM64" PROCESSOR_ARCHITECTURE_INTEL → "x86 (Intel)" ``` 3. **Disk usage calculation** ```vb Dim usedPercent = (usedBytes / totalBytes) * 100 result.AddItem "C: Used", "120 GB (45.0%)" ``` 4. **Uptime formatting** ```vb ' Milliseconds → "Xd HH:MM:SS" format FormatHelper.FormatUptime(GetTickCount64()) ``` 5. **Smart byte count formatting** ```vb FormatHelper.FormatBytes(bytes) → "16.38 GB" FormatHelper.FormatBytes(bytes, 0) → "16 GB" ``` *** ### 7. ✨ Overall Elegance and Completeness **Architecture Design:** ``` src/ ├── Interfaces/ # Interface definitions │ └── IDiagnosticCollector.twin ├── Core/ # Core engine │ ├── DiagnosticEngine.twin │ └── RefreshMode.twin ├── Generics/ # Generic containers │ ├── DiagnosticResult.twin │ ├── List.twin │ ├── Dictionary.twin │ └── KeyValuePair.twin ├── Collectors/ # Data collectors │ ├── Static/ # Static data (fetch once) │ ├── Dynamic/ # Dynamic data (refresh each time) │ └── SemiDynamic/ # Semi-dynamic data (optional refresh) ├── Formatters/ # Output formatters │ ├── TextFormatter.twin │ ├── JsonFormatter.twin │ └── HtmlFormatter.twin ├── Console/ # Console library │ ├── cConsole.twin │ ├── cConsoleBuffer.twin │ ├── ProgressBar.twin │ └── ... ├── WinAPI/ # Windows API declarations │ ├── Declarations.twin │ └── Structures.twin └── Main/ # Program entry └── MainModule.twin ``` **Design Principles:** * 🔌 **Dependency injection** - Dynamic collector registration * 🎨 **Single responsibility** - Clear responsibilities for each class * 📦 **Open/closed principle** - Easy to extend with new collectors * 🔄 **Interface abstraction** - `IDiagnosticCollector` unified standard *** ### 🏆 Extra Credit Items (@ai/002.md:54-55) #### ✅ Using Newer TwinBASIC Features 1. **Generics** ```vb ' Generic result container Public Class DiagnosticResult(Of T) Private m_Items As List(Of T) End Class ' Generic list Dim results As List(Of DiagnosticResult(Of KeyValuePair(Of String, String))) ``` 2. **Delegates** ```vb ' Event callback delegate Public Delegate Sub DiagnosticCompleteHandler( _ ByVal category As String, _ ByVal success As Boolean, _ ByVal itemCount As Long) ' Delegate property Public Property Let OnCollectorCompleted( _ ByVal handler As DiagnosticCompleteHandler) End Property ``` 3. **Interface Implementation (Implements)** ```vb Public Class OSInfoCollector Implements IDiagnosticCollector Public Property Get IDiagnosticCollector_CategoryName() As String End Class ``` 4. **Return Statement** ```vb Public Function GetUsageColor(ByVal percent As Double) As ConsoleColor If percent < 50 Then Return ConsoleColor.Green If percent < 80 Then Return ConsoleColor.Yellow Return ConsoleColor.Red End Function ``` 5. **Short-circuit Operators** ```vb If m_Running AndAlso m_CurrentScreen IsNot Nothing Then m_CurrentScreen.Render() End If ``` 6. **Class Constructors** ```vb Public Sub New(ByVal categoryName As String) m_Category = categoryName m_Items = New List(Of T) End Sub ``` #### ✅ Particularly Clear or Insightful Design 1. **Three-mode refresh architecture** - Static/Dynamic/SemiDynamic 2. **Summary vs Complete data** - Flexible data collection strategy 3. **Independent console library** - Reusable `cConsole` package 4. **Multi-format export** - TEXT/JSON/HTML unified interface 5. **Elegant error handling** - `DiagnosticResult.SetError()` 6. **Event-driven** - Traditional events + delegate callback dual support 7. **Dual-mode operation** - Double-click real-time monitoring + command-line file export 8. **Multi-UI extension architecture** - Core abstraction layer supports Console/GUI/WEB multiple callers *** ## 📅 Current Progress and Roadmap ### ✅ Completed Phases (Phase 1-4) #### 🎉 Phase 1: Basic Framework ✅ * ✅ `DiagnosticEngine` core diagnostic engine * ✅ `IDiagnosticCollector` interface definition * ✅ `RefreshMode` refresh mode enumeration * ✅ Generic containers: `List`, `Dictionary`, `KeyValuePair`, `DiagnosticResult` #### 🎉 Phase 2: Console Library ✅ (Can be extracted and shared to TwinBASIC Package Manager) * ✅ `cConsole` main console class * UTF-8 encoding support * Colored output * Cursor control * Screen control * Read/write functions * Drawing functions (borders, progress bars) * ✅ `cConsoleBuffer` double-buffer class * ✅ `cConsoleStyle` ANSI/VT100 style library * ✅ `cConsoleAPI` Windows Console API declarations * ✅ `ProgressBar` progress bar component * ✅ `RealtimeDisplay` real-time monitoring display * ✅ `ConsoleHelper` helper utility class * 📚 **Complete README documentation** (`Console/README.md`) #### 🎉 Phase 3: Diagnostic Object Package ✅ (Can be extracted and shared to TwinBASIC Package Manager) * ✅ **Static collectors** (Static - fetch once): * `OSInfoCollector` - Operating system information * `CPUInfoCollector` - CPU information * `LocaleCollector` - Locale settings * `EnvironmentCollector` - Environment variables * `RuntimesCollector` - Installed runtimes * ✅ **Dynamic collectors** (Dynamic - refresh each time): * `CPULoadCollector` - CPU real-time load * `MemoryInfoCollector` - Memory usage * `UptimeCollector` - System uptime * `ProcessInfoCollector` - Process information * ✅ **Semi-dynamic collectors** (SemiDynamic - optional refresh): * `DiskInfoCollector` - Disk information * `NetworkInfoCollector` - Network configuration #### 🎉 Phase 4: Output Formatters ✅ * ✅ `IOutputFormatter` interface definition * ✅ `TextFormatter` - Plain text format * ✅ `JsonFormatter` - JSON format * ✅ `HtmlFormatter` - HTML format * ✅ `FormatterFactory` - Formatter factory #### 🎉 Phase 5: Utility Classes ✅ * ✅ `FormatHelper` - Formatting utilities (bytes, time, strings) * ✅ `StringBuilder` - String builder * ✅ `WinAPI` module - Unified Windows API declarations * `Declarations.twin` - API function declarations * `Structures.twin` - Structure definitions #### 🎉 Phase 6: Main Program ✅ * ✅ `MainModule` - Program entry point * Command-line argument parsing * Real-time monitoring mode * Export mode (TEXT/JSON/HTML) * Help information * ✅ **Dual-mode operation support**: * 🖱️ **Double-click startup** - Default to real-time monitoring and interactive mode * 📤 **Command-line export** - Supports `/text`, `/json`, `/html` parameters to export files * ✅ Command-line support: ```bash # Method 1: Double-click startup (Real-time monitoring + Interactive) diagnostic.exe # Method 2: Command-line file export diagnostic.exe /text > report.txt diagnostic.exe /json > report.json diagnostic.exe /html > report.html diagnostic.exe /help ``` *** ### 🚧 In Progress/To Complete (Phase 7-8) #### 📋 Phase 7: Advanced UI Features (In Design) According to design document `ai/004.md`, planned to implement: * 🔄 **Splash Screen** * Auto-switch after 3 seconds * ASCII Art LOGO display * Red background + white text * 🖼️ **Main Screen** * Top info area (CPU, memory progress bars) * Process list area (scrollable) * Hotkey bar (F1-F10) * htop-style layout * ℹ️ **About Screen** * Project information * Help documentation * Hotkey instructions **Status:** Core architecture ready, RealtimeDisplay has basic framework implemented #### 📋 Phase 8: Interaction Enhancements (In Design) * ⌨️ **Keyboard event handling** * F1: Show about * F2: Save TXT report * F3: Save HTML report * F4: Refresh data * F10/Q: Exit * Up/Down: Scroll process list * PageUp/PageDown: Page navigation * 🖱️ **Ctrl+C graceful exit** * 🔄 **Window size adaptation** **Status:** cConsole already supports `OnKeyPress`, `OnResize` events *** ### 🎯 Future Optimizations (Optional) #### 📋 Phase 9: Core Abstraction and Multi-UI Support (Architecture Evolution) * 🏗️ **Core abstraction layer refactoring** * Extract `DiagnosticEngine` and collectors as independent core library * Define `IUIPresenter` interface as data presentation abstraction * Core layer completely independent of UI dependencies, pure data layer * 🎨 **Multiple caller implementations** * **Console TUI** - Existing real-time monitoring interface enhancement * **Native GUI** - Desktop application based on WinForms/WPF * **Web UI** - HTTP server + browser interface (REST API + WebSocket real-time push) * **CLI Interface** - Pure command-line tool (already implemented) * 📐 **Architecture Design** ``` ┌─────────────────────────────────────────────┐ │ UI Layer (Callers) │ ├──────────┬──────────┬──────────┬────────────┤ │ Console │ GUI │ Web UI │ CLI │ │ TUI │ WinForms │ HTML/JS │ Export │ └────┬─────┴────┬─────┴────┬─────┴────┬───────┘ │ │ │ │ ┌────┴──────────┴──────────┴──────────┴───────┐ │ Core Layer (Core Implementation) │ │ ┌──────────────────────────────────────┐ │ │ │ DiagnosticEngine │ │ │ │ (Register collectors, data │ │ │ │ collection, event callbacks) │ │ │ └──────────────────────────────────────┘ │ │ ┌──────────────────────────────────────┐ │ │ │ Collectors (Static/Dynamic/...) │ │ │ │ IDiagnosticCollector interface │ │ │ └──────────────────────────────────────┘ │ │ ┌──────────────────────────────────────┐ │ │ │ Formatters (Text/JSON/HTML) │ │ │ │ IOutputFormatter interface │ │ │ └──────────────────────────────────────┘ │ └─────────────────────────────────────────────┘ │ │ │ │ ┌────┴──────────┴──────────┴──────────┴───────┐ │ Data Layer (Data Models) │ │ DiagnosticResult(Of T) │ │ KeyValuePair(Of String, String) │ └─────────────────────────────────────────────┘ ``` **Implementation Value:** * 🔌 **Plugin-based extension** - Adding new UIs requires no core code changes * 📱 **Multi-platform coverage** - Same core library serves multiple scenarios * 🧪 **Independent testing** - Core logic separated from UI, easy unit testing * 📦 **Module reuse** - Core library can be independently published to TwinBASIC Package Manager #### 📋 Phase 10: Feature Enhancements * 🔍 **Process sorting** - Sort by CPU/Memory/PID * 📊 **Historical data** - CPU/Memory history curves * 🎨 **Theme switching** - Light/Dark themes * 💾 **Configuration file** - Save user preferences * 📤 **More export formats** - CSV, XML, Markdown #### 📋 Phase 11: Packaging and Release * 📦 Single .twinproj file integration * 🧪 Complete testing * 📝 Final documentation * 🚀 Submit to competition *** ## 📊 Diagnostic Item Coverage Checklist (@ai/002.md:29-39) | Diagnostic Item | Implementation Class | Status | Refresh Mode | | -------------------------------- | ---------------------- | ------ | ------------ | | ✅ OS version/build number | `OSInfoCollector` | ✅ | Static | | ✅ CPU Information | `CPUInfoCollector` | ✅ | Static | | ✅ Memory Usage | `MemoryInfoCollector` | ✅ | Dynamic | | ✅ Disk Information | `DiskInfoCollector` | ✅ | SemiDynamic | | ✅ Process Information | `ProcessInfoCollector` | ✅ | Dynamic | | ✅ Environment Variables | `EnvironmentCollector` | ✅ | Static | | ✅ System Uptime | `UptimeCollector` | ✅ | Dynamic | | ✅ Locale Settings/Code Page | `LocaleCollector` | ✅ | Static | | ✅ Network Configuration | `NetworkInfoCollector` | ✅ | SemiDynamic | | ✅ Installed Runtimes | `RuntimesCollector` | ✅ | Static | | 🎁 **Bonus**: CPU Real-time Load | `CPULoadCollector` | ✅ | Dynamic | **Total:** 11 diagnostic categories (far exceeding the competition's "at least three" requirement) ✨ *** ## 🎯 Summary This project demonstrates TwinBASIC's powerful capabilities through: 1. ✨ **Elegant architecture** - Modular, interface-driven, separation of concerns 2. 🚀 **Performance optimization** - Three-level refresh modes, summary data, generic reuse 3. 📦 **Zero dependencies** - Pure WinAPI, no external libraries 4. 🎨 **Modern features** - Generics, delegates, interfaces, Return, short-circuit operators 5. 📖 **Comprehensive documentation** - Clear comments for every class and method 6. 🧪 **Clever API usage** - RtlGetVersion, GetNativeSystemInfo, etc. 7. 📊 **Rich functionality** - 11 diagnostic categories, 3 export formats 8. 🔄 **Extensibility** - Easy to add new collectors and formatters 9. 💻 **Dual-mode operation** - Supports double-click real-time monitoring and command-line file export 10. 🎯 **Multi-UI architecture** - Core abstraction layer supports Console/GUI/WEB multiple callers The project not only meets all competition requirements but also demonstrates professional software engineering practices and TwinBASIC's modern language features. Both the console library and diagnostic object packages can be independently extracted and shared to the TwinBASIC Package Manager, contributing reusable components to the community. Future plans include further abstracting the core implementation layer to support multiple UI callers (Console TUI/Native GUI/Web WEBUI), enabling broader application scenarios. *** ## Video Demo ## Download (open source) [示例下载](/challenges/202601/TwinbasicDiagnosticTUI.zip) --- --- url: /en/official/Reference/VBRUN/Constants/DragConstants.md --- # DragConstants Action values for the **Drag** method of a control, controlling the start, end, or cancellation of a manual drag. | Constant | Value | Description | |----------|-------|-------------| | **vbCancel** | 0 | Cancel the drag operation in progress. | | **vbBeginDrag** | 1 | Begin dragging the control. | | **vbEndDrag** | 2 | Drop the control at the current location. | --- --- url: /zh/official/Reference/VBRUN/Constants/DragConstants.md --- # DragConstants 控件**Drag**方法的操作值,控制手动拖动的开始、结束或取消。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbCancel** | 0 | 取消正在进行的拖动操作。 | | **vbBeginDrag** | 1 | 开始拖动控件。 | | **vbEndDrag** | 2 | 在当前位置放下控件。 | --- --- url: /en/official/Reference/VBRUN/Constants/DragModeConstants.md --- # DragModeConstants Values for the **DragMode** property of a control, controlling whether dragging starts automatically when the user clicks-and-drags or only when **Drag** is called explicitly. | Constant | Value | Description | |----------|-------|-------------| | **vbManual** | 0 | The control is not draggable until **Drag** is called from code. | | **vbAutomatic** | 1 | Dragging starts automatically when the user presses the mouse button on the control. | --- --- url: /zh/official/Reference/VBRUN/Constants/DragModeConstants.md --- # DragModeConstants 控件**DragMode**属性的值,控制拖动是自动开始(用户点击并拖动时)还是仅在显式调用**Drag**时开始。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbManual** | 0 | 控件在代码调用**Drag**之前不可拖动。 | | **vbAutomatic** | 1 | 用户在控件上按下鼠标按钮时自动开始拖动。 | --- --- url: /en/official/Reference/VBRUN/Constants/DragOverConstants.md --- # DragOverConstants State values reported in the *State* argument of a control's **DragOver** event. | Constant | Value | Description | |----------|-------|-------------| | **vbEnter** | 0 | The dragged source has just entered the target. | | **vbLeave** | 1 | The dragged source has just left the target. | | **vbOver** | 2 | The dragged source is moving over the target. | --- --- url: /zh/official/Reference/VBRUN/Constants/DragOverConstants.md --- # DragOverConstants 控件**DragOver**事件的*State*参数中报告的状态值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbEnter** | 0 | 拖动源刚进入目标。 | | **vbLeave** | 1 | 拖动源刚离开目标。 | | **vbOver** | 2 | 拖动源正在目标上方移动。 | --- --- url: /en/official/Reference/VBRUN/Constants/DrawModeConstants.md --- # DrawModeConstants GDI raster-operation values for the **DrawMode** property, controlling how the pen colour is combined with the existing pixels when drawing with **PSet**, **Line**, **Circle**, and similar methods. | Constant | Value | Description | |----------|-------|-------------| | **vbBlackness** | 1 | Output is black. | | **vbNotMergePen** | 2 | Inverse of **vbMergePen**. | | **vbMaskNotPen** | 3 | Combination of the colours common to the background and the inverse of the pen. | | **vbNotCopyPen** | 4 | Inverse of **vbCopyPen**. | | **vbMaskPenNot** | 5 | Combination of the pen and the inverse of the screen. | | **vbInvert** | 6 | Inverse of the existing screen colour. | | **vbXorPen** | 7 | XOR of the pen and the screen. | | **vbNotMaskPen** | 8 | Inverse of **vbMaskPen**. | | **vbMaskPen** | 9 | Combination of the colours common to both the pen and the screen. | | **vbNotXorPen** | 10 | Inverse of **vbXorPen**. | | **vbNop** | 11 | No drawing --- the screen is left unchanged. | | **vbMergeNotPen** | 12 | Combination of the screen and the inverse of the pen. | | **vbCopyPen** | 13 | Output is the pen colour (the default). | | **vbMergePenNot** | 14 | Combination of the pen and the inverse of the screen. | | **vbMergePen** | 15 | Combination of the pen colour and the screen colour. | | **vbWhiteness** | 16 | Output is white. | --- --- url: /zh/official/Reference/VBRUN/Constants/DrawModeConstants.md --- # DrawModeConstants **DrawMode**属性的GDI光栅操作值,控制使用**PSet**、**Line**、**Circle**和类似方法绘图时画笔颜色如何与现有像素组合。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbBlackness** | 1 | 输出为黑色。 | | **vbNotMergePen** | 2 | **vbMergePen**的反转。 | | **vbMaskNotPen** | 3 | 背景与画笔反转的共有颜色组合。 | | **vbNotCopyPen** | 4 | **vbCopyPen**的反转。 | | **vbMaskPenNot** | 5 | 画笔与屏幕反转的组合。 | | **vbInvert** | 6 | 现有屏幕颜色的反转。 | | **vbXorPen** | 7 | 画笔与屏幕的异或。 | | **vbNotMaskPen** | 8 | **vbMaskPen**的反转。 | | **vbMaskPen** | 9 | 画笔与屏幕共有颜色的组合。 | | **vbNotXorPen** | 10 | **vbXorPen**的反转。 | | **vbNop** | 11 | 不绘图 --- 屏幕保持不变。 | | **vbMergeNotPen** | 12 | 屏幕与画笔反转的组合。 | | **vbCopyPen** | 13 | 输出为画笔颜色(默认)。 | | **vbMergePenNot** | 14 | 画笔与屏幕反转的组合。 | | **vbMergePen** | 15 | 画笔颜色与屏幕颜色的组合。 | | **vbWhiteness** | 16 | 输出为白色。 | --- --- url: /en/official/Reference/VBRUN/Constants/DrawStyleConstants.md --- # DrawStyleConstants Line-style values for the **DrawStyle** property, controlling the appearance of lines drawn with **Line** and **Circle**. | Constant | Value | Description | |----------|-------|-------------| | **vbSolid** | 0 | Solid line (the default). | | **vbDash** | 1 | Dashed line. | | **vbDot** | 2 | Dotted line. | | **vbDashDot** | 3 | Dash-dot pattern. | | **vbDashDotDot** | 4 | Dash-dot-dot pattern. | | **vbInvisible** | 5 | The line is not drawn. | | **vbInsideSolid** | 6 | A solid line drawn entirely within the bounds of any closed shape. | --- --- url: /zh/official/Reference/VBRUN/Constants/DrawStyleConstants.md --- # DrawStyleConstants **DrawStyle**属性的线条样式值,控制使用**Line**和**Circle**绘制的线条外观。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbSolid** | 0 | 实线(默认)。 | | **vbDash** | 1 | 虚线。 | | **vbDot** | 2 | 点线。 | | **vbDashDot** | 3 | 点划线。 | | **vbDashDotDot** | 4 | 双点划线。 | | **vbInvisible** | 5 | 不绘制线条。 | | **vbInsideSolid** | 6 | 完全在任何闭合形状边界内绘制的实线。 | --- --- url: /en/official/Reference/VB/DriveListBox.md --- # DriveListBox class A **DriveListBox** is a Win32 native drop-down combo control that auto-populates with the drives reported by the operating system. The user picks one from the list; code reads the chosen drive through [**Drive**](#drive) and typically forwards it to a [**DirListBox**](/en/official/Reference/VB/DirListBox/) (whose [**Path**](/en/official/Reference/VB/DirListBox/#path) it can be assigned to directly) to build a file picker alongside a [**FileListBox**](/en/official/Reference/VB/FileListBox/). The control is normally placed on a **Form** or **UserControl** at design time. The default property is [**Drive**](#drive) and the default event is [**Change**](#change). ```vb Private Sub Form_Load() Drive1.Drive = "C:" Dir1.Path = Drive1.Drive File1.Path = Dir1.Path End Sub Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub ``` ## Drive list The list is populated automatically when the underlying window is created, by asking the OS for every currently-attached drive. Each entry combines the drive letter with the volume label, or --- for a network drive --- the UNC path the drive is mapped to: | Entry shape | Meaning | |----------------------|------------------------------------------------------------------| | `c: [Windows]` | Fixed or removable disk; volume label in brackets. | | `d:` (no brackets) | Drive present but no volume label (unformatted, or empty CD-ROM).| | `z: [\\srv\share]` | Network drive; UNC path in brackets. | Each entry is owner-drawn with an icon chosen from the drive type --- closed disk, removable, fixed, CD-ROM, network, or RAM disk. The list cannot be edited from code: [**AddItem**](/en/official/Reference/VB/ComboBox/#additem), [**RemoveItem**](/en/official/Reference/VB/ComboBox/#removeitem), and [**Clear**](/en/official/Reference/VB/ComboBox/#clear) are present in the type library for VB6 source compatibility but raise run-time error 438 (*Object doesn't support this property or method*) when called. Call [**Refresh**](#refresh) to re-read the drive set from the OS --- useful after a removable medium is inserted or a network drive is mapped. [**ListCount**](#listcount) is the number of entries, [**List**](#list) returns the text of any entry by zero-based index, and [**TopIndex**](#topindex) controls vertical scrolling within the drop-down portion when it is open. [**NewIndex**](#newindex) reports the position of the last entry added during population (useful only when re-reading the list from code). ## Drive property semantics Reading [**Drive**](#drive) returns the *displayed text* of the currently selected entry --- drive letter, colon, and (where applicable) the bracketed volume label or UNC path, exactly as shown in the combo. Assigning to [**Drive**](#drive) looks only at the **first character** of the value and selects the entry whose drive letter matches (case-insensitively, by prefix). Anything after the first character is ignored, so `"C"`, `"C:"`, and `"C:\Windows"` all select the **C:** drive. If no entry matches the letter --- e.g. when the requested drive is not currently attached --- the assignment is silently ignored, leaving the previous selection in place. Assigning a value that matches the current selection does not raise [**Change**](#change); assigning a different value does. ```vb Drive1.Drive = "D" ' select drive D if present, else no-op Debug.Print Drive1.Drive ' "d: [Backup]" (the displayed text) ``` ## OLE drag and drop [**OLEDropMode**](#oledropmode) lets the control act as a drop target (restricted to **vbOLEDropNone** or **vbOLEDropManual**). Source-side automatic OLE drag is not supported on this control --- VB6's `OLEDragMode` property was non-functional here and is omitted in twinBASIC. Call [**OLEDrag**](#oledrag) from code if a manual drag is needed. ## Properties ### Appearance Determines how the control's border is drawn by the OS. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). ### BackColor The background colour of the drop-down list entries, as an **OLE\_COLOR**. Defaults to the system window-background colour. Selected entries paint with the system highlight colour regardless of this setting. Changing this calls [**Refresh**](#refresh) so the new colour takes effect immediately. ### CausesValidation Determines whether the previously focused control's [**Validate**](#validate) event runs before this control receives the focus. **Boolean**, default **True**. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a drive list box. Always **vbDriveListBox**. ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Drive The currently selected drive. **Default property.** Syntax: *object*.**Drive** \[ = *string* ] Reading returns the displayed text of the selected entry --- drive letter, colon, and (where applicable) the bracketed volume label or UNC path. Writing examines only the first character of *string* and selects the entry whose drive letter matches; values that do not match any present drive are silently ignored. Assigning a value that changes the selection raises [**Change**](#change). See [Drive property semantics](#drive-property-semantics) above for details. ### Enabled Determines whether the control accepts user input. A disabled drive list box still shows its current selection but is dimmed and ignores keyboard and mouse interaction. **Boolean**, default **True**. ### Font The **StdFont** used to render the drive entries. The convenience properties **FontName**, **FontSize**, **FontBold**, **FontItalic**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. ### ForeColor The text colour for entries that are not currently selected, as an **OLE\_COLOR**. Defaults to the system window-text colour. Disabled entries draw in the system grey-text colour, and selected entries draw in the system highlight-text colour, regardless of this setting. Changing this calls [**Refresh**](#refresh). ### Height The control's height when the drop-down is closed, in twips by default (or in the container's **ScaleMode** units). **Single**. The drop-down portion is sized by the OS. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the control has focus. ### hWnd The Win32 window handle for the underlying combo box, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Read-only at run time. ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Single**. ### List The displayed text of the drive entry at the given index. Read-only. Syntax: *object*.**List**( *Index* ) *Index* : *required* A **Long** zero-based item position, from `0` to `ListCount - 1`. ### ListCount The number of drive entries currently in the list, as a **Long**. Read-only. ### ListIndex The zero-based index of the selected entry, or `-1` if nothing is selected. **Long**. Assigning a value that differs from the current one selects that entry and raises [**Change**](#change). ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### NewIndex The zero-based index at which the most recent list-population step inserted an entry, or `-1` if the list is empty. **Long**. Updated while the list is being filled (during [**Initialize**](#initialize) and after [**Refresh**](#refresh)); rarely useful at run time but read by some VB6-compatibility code. ### OLEDropMode How the control responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on a DriveListBox. ### Opacity The control's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Requires Windows 8 or later for child controls. ### Parent A reference to the **Form** (or **UserControl**) that contains this control. Read-only. ### TabIndex The position of the control in the form's TAB-key navigation order. **Long**. ### TabStop Whether the user can reach the control by pressing the **TAB** key. **Boolean**, default **True**. A disabled control is skipped regardless of this setting. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the control. ### Top The vertical distance from the top of the container to the top of the control. **Single**. ### TopIndex The zero-based index of the entry shown at the top of the drop-down portion. Assigning a value scrolls the list so that entry is at the top, and raises [**Scroll**](#scroll) when the value actually changes. **Long**. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered control. Default `-1` disables the effect. Requires Windows 8 or later for child controls. ### Visible Whether the control is shown. **Boolean**, default **True**. ### VisualStyles Whether the OS theme engine should be used when drawing the control. **Boolean**. ### WhatsThisHelpID A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### WheelScrollEvent When **True** (default), mouse-wheel notifications over the drop-down list raise the [**Scroll**](#scroll) event; when **False**, the wheel still scrolls the list but [**Scroll**](#scroll) is suppressed. **Boolean**. VB6 never raised **Scroll** for wheel events; set this to **False** to match that behaviour exactly. ### Width The control's width. **Single**. ## Methods ### Drag Begins, completes, or cancels a manual drag-and-drop operation when [**DragMode**](#dragmode) is **vbManual**. DriveListBox does not raise mouse events itself, so the call typically lives in a parent **Form** or container's mouse handler. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the control, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Re-reads the set of currently-attached drives from the operating system and repopulates the list, then redraws the control. Useful after a removable medium is inserted or a network drive is mapped or disconnected --- the control does not watch for these events on its own. Does not raise [**Change**](#change), even if the previously-selected drive is no longer present (the selection moves to entry `0`). Syntax: *object*.**Refresh** ### SetFocus Moves the input focus to the control. The control must be both [**Visible**](#visible) and [**Enabled**](#enabled), or run-time error 5 (*Invalid procedure call or argument*) is raised. Syntax: *object*.**SetFocus** ### ShowWhatsThis Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Change Raised after the selected drive changes --- whether the user picked a different entry from the drop-down or code assigned a different value to [**Drive**](#drive) or [**ListIndex**](#listindex). Not raised for assignments that match the current selection, nor during [**Refresh**](#refresh) or the initial population that occurs before [**Initialize**](#initialize). **Default event.** Syntax: *object*\_**Change**( ) ### CloseUp Raised when the drop-down portion closes --- either because the user picked an entry, clicked elsewhere, or pressed **Esc**. Syntax: *object*\_**CloseUp**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### DropDown Raised when the user opens the drop-down portion. Syntax: *object*\_**DropDown**( ) ### GotFocus Raised when the control receives the input focus. Syntax: *object*\_**GotFocus**( ) ### Initialize Raised once, immediately after the underlying window is created and the initial list of drives has been loaded. New in twinBASIC --- VB6 had no equivalent on this control. Syntax: *object*\_**Initialize**( ) ### KeyDown Raised when the user presses any key while the control has focus. Syntax: *object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress Raised when the user types a character that produces an ANSI keystroke. Syntax: *object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp Raised when the user releases a key while the control has focus. Syntax: *object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus Raised when the control loses the input focus. Syntax: *object*\_**LostFocus**( ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Scroll Raised when the drop-down list is scrolled --- by the scroll bar, the keyboard, or (when [**WheelScrollEvent**](#wheelscrollevent) is **True**) the mouse wheel. The new offset can be read from [**TopIndex**](#topindex). Syntax: *object*\_**Scroll**( ) ### Validate Raised when the focus is moving to another control whose [**CausesValidation**](#causesvalidation) is **True**. Setting *Cancel* to **True** keeps the focus on this control. Syntax: *object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /zh/official/Reference/VB/DriveListBox.md --- # DriveListBox 类 **DriveListBox** 是一个 Win32 原生下拉组合框控件,自动填充操作系统报告的驱动器列表。用户从列表中选择一个驱动器;代码通过 [**Drive**](#drive) 读取所选驱动器,通常将其传递给 [**DirListBox**](/official/Reference/VB/DirListBox/)(可直接赋值给其 [**Path**](/official/Reference/VB/DirListBox/#path) 属性),并与 [**FileListBox**](/official/Reference/VB/FileListBox/) 一起构建文件选择器。该控件通常在设计时放置在 **Form** 或 **UserControl** 上。默认属性为 [**Drive**](#drive),默认事件为 [**Change**](#change)。 ```vb Private Sub Form_Load() Drive1.Drive = "C:" Dir1.Path = Drive1.Drive File1.Path = Dir1.Path End Sub Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub ``` ## 驱动器列表 当底层窗口创建时,列表通过向操作系统查询所有当前连接的驱动器自动填充。每个条目将驱动器字母与卷标组合,或者---对于网络驱动器---与驱动器映射到的 UNC 路径组合: | 条目格式 | 含义 | |----------------------|------------------------------------------------------------------| | `c: [Windows]` | 固定或可移动磁盘;方括号中为卷标。 | | `d:`(无方括号) | 驱动器存在但无卷标(未格式化,或空 CD-ROM)。| | `z: [\\srv\share]` | 网络驱动器;方括号中为 UNC 路径。 | 每个条目为自绘模式,图标根据驱动器类型选择---关闭的磁盘、可移动、固定、CD-ROM、网络或 RAM 磁盘。列表不能通过代码编辑:[**AddItem**](/official/Reference/VB/ComboBox/#additem)、[**RemoveItem**](/official/Reference/VB/ComboBox/#removeitem) 和 [**Clear**](/official/Reference/VB/ComboBox/#clear) 存在于类型库中仅为了 VB6 源代码兼容性,但调用时会引发运行时错误 438(*对象不支持此属性或方法*)。调用 [**Refresh**](#refresh) 可从操作系统重新读取驱动器集合---在插入可移动介质或映射网络驱动器后很有用。 [**ListCount**](#listcount) 是条目数,[**List**](#list) 通过从零开始的索引返回任意条目的文本,[**TopIndex**](#topindex) 控制下拉部分打开时的垂直滚动。[**NewIndex**](#newindex) 报告列表填充期间最后添加的条目位置(仅在从代码重新读取列表时有意义)。 ## Drive 属性语义 读取 [**Drive**](#drive) 返回当前选中条目的*显示文本*---驱动器字母、冒号以及(如适用)方括号中的卷标或 UNC 路径,与组合框中显示的完全一致。 对 [**Drive**](#drive) 赋值仅检查值的**第一个字符**,并选择驱动器字母匹配的条目(不区分大小写,按前缀匹配)。第一个字符之后的任何内容都被忽略,因此 `"C"`、`"C:"` 和 `"C:\Windows"` 都会选择 **C:** 驱动器。如果没有条目与该字母匹配(例如,请求的驱动器当前未连接),赋值将被静默忽略,保持先前的选择不变。赋值与当前选择相同的值不会引发 [**Change**](#change);赋值不同的值则会引发。 ```vb Drive1.Drive = "D" ' 如果驱动器 D 存在则选择,否则无操作 Debug.Print Drive1.Drive ' "d: [Backup]"(显示文本) ``` ## OLE 拖放 [**OLEDropMode**](#oledropmode) 允许控件作为放置目标(仅限 **vbOLEDropNone** 或 **vbOLEDropManual**)。此控件不支持源端自动 OLE 拖动---VB6 的 `OLEDragMode` 属性在此控件上无效,在 twinBASIC 中已省略。如果需要手动拖动,可从代码调用 [**OLEDrag**](#oledrag)。 ## 属性 ### Appearance 确定操作系统如何绘制控件边框。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants) 的成员:**vbAppearFlat** 或 **vbAppear3d**(默认)。 ### BackColor 下拉列表条目的背景色,类型为 **OLE\_COLOR**。默认为系统窗口背景色。选中的条目使用系统高亮色绘制,不受此设置影响。更改此属性会调用 [**Refresh**](#refresh),使新颜色立即生效。 ### CausesValidation 确定在此控件获得焦点之前,先前聚焦控件的 [**Validate**](#validate) 事件是否运行。**Boolean**,默认 **True**。 ### ControlType 只读的 [**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants) 值,将此控件标识为驱动器列表框。始终为 **vbDriveListBox**。 ### DragIcon 在控件被拖放时用作鼠标光标的 **StdPicture**(参见 [**Drag**](#drag) 和 [**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自动拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants) 的成员:**vbManual**(0,默认---从代码调用 [**Drag**](#drag))或 **vbAutomatic**(1)。 ### Drive 当前选中的驱动器。**默认属性。** 语法:*object*.**Drive** \[ = *string* ] 读取时返回选中条目的显示文本---驱动器字母、冒号以及(如适用)方括号中的卷标或 UNC 路径。写入时仅检查 *string* 的第一个字符并选择驱动器字母匹配的条目;与任何现有驱动器不匹配的值将被静默忽略。赋值更改选择时会引发 [**Change**](#change)。详见上文的 [Drive 属性语义](#drive-property-semantics)。 ### Enabled 确定控件是否接受用户输入。禁用的驱动器列表框仍显示当前选择,但变灰并忽略键盘和鼠标交互。**Boolean**,默认 **True**。 ### Font 用于渲染驱动器条目的 **StdFont**。便捷属性 **FontName**、**FontSize**、**FontBold**、**FontItalic**、**FontStrikethru** 和 **FontUnderline** 读取或写入此对象的相应成员。 ### ForeColor 未选中条目的文本颜色,类型为 **OLE\_COLOR**。默认为系统窗口文本色。禁用的条目使用系统灰色文本色绘制,选中的条目使用系统高亮文本色绘制,不受此设置影响。更改此属性会调用 [**Refresh**](#refresh)。 ### Height 下拉框关闭时控件的高度,默认以缇为单位(或使用容器的 **ScaleMode** 单位)。**Single**。下拉部分的大小由操作系统决定。 ### HelpContextID 一个 **Long**,标识应用程序帮助文件中的主题,当控件有焦点时用户按 **F1** 会检索此值。 ### hWnd 底层组合框的 Win32 窗口句柄,类型为 **LongPtr**。只读。适用于传递给 API 函数。 ### Index 当控件是控件数组的一部分时,此实例在数组中的 **Long** 类型从零开始的索引。运行时只读。 ### Left 从容器的左边缘到控件左边缘的水平距离。**Single**。 ### List 指定索引处驱动器条目的显示文本。只读。 语法:*object*.**List**( *Index* ) *Index* : *必需* 一个 **Long** 类型的从零开始的条目位置,从 `0` 到 `ListCount - 1`。 ### ListCount 列表中当前驱动器条目的数量,类型为 **Long**。只读。 ### ListIndex 选中条目的从零开始的索引,如果未选中任何条目则为 `-1`。**Long**。赋值与当前值不同的值会选中该条目并引发 [**Change**](#change)。 ### MouseIcon 当 [**MousePointer**](#mousepointer) 为 **vbCustom** 且指针位于控件上方时用作鼠标光标的 **StdPicture**。 ### MousePointer 指针位于控件上方时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants) 的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### NewIndex 最近一次列表填充步骤插入条目的从零开始的索引,如果列表为空则为 `-1`。**Long**。在列表填充期间更新([**Initialize**](#initialize) 期间和 [**Refresh**](#refresh) 之后);运行时很少使用,但某些 VB6 兼容代码会读取此值。 ### OLEDropMode 控件如何响应 OLE 放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants) 的受限成员:**vbOLEDropNone** 或 **vbOLEDropManual**。DriveListBox 不支持自动放置模式。 ### Opacity 控件的不透明度百分比(0--100,默认 100)。范围外的值在 **Initialize** 时被钳位。子控件需要 Windows 8 或更高版本。 ### Parent 对包含此控件的 **Form**(或 **UserControl**)的引用。只读。 ### TabIndex 控件在窗体 TAB 键导航顺序中的位置。**Long**。 ### TabStop 用户是否可以通过按 **TAB** 键到达此控件。**Boolean**,默认 **True**。禁用的控件无论此设置如何都会被跳过。 ### Tag 一个自由格式的 **String**,应用程序可用于将自定义数据与控件关联。框架忽略此属性。 ### ToolTipText 当用户将鼠标悬停在控件上方时作为工具提示显示的多行 **String**。 ### Top 从容器顶部到控件顶部的垂直距离。**Single**。 ### TopIndex 下拉部分顶部显示的条目的从零开始的索引。赋值会滚动列表使该条目位于顶部,并在值实际更改时引发 [**Scroll**](#scroll)。**Long**。 ### TransparencyKey 一个 **OLE\_COLOR**,设置后在渲染的控件中变为完全透明。默认 `-1` 禁用此效果。子控件需要 Windows 8 或更高版本。 ### Visible 控件是否显示。**Boolean**,默认 **True**。 ### VisualStyles 绘制控件时是否使用操作系统主题引擎。**Boolean**。 ### WhatsThisHelpID 一个 **Long**,标识应用程序帮助文件中的"这是什么?"帮助弹出主题。参见 [**ShowWhatsThis**](#showwhatsthis)。 ### WheelScrollEvent 当为 **True**(默认)时,下拉列表上的鼠标滚轮通知会引发 [**Scroll**](#scroll) 事件;当为 **False** 时,滚轮仍会滚动列表但 [**Scroll**](#scroll) 被抑制。**Boolean**。VB6 从未为滚轮事件引发 **Scroll**;将此设置为 **False** 可完全匹配该行为。 ### Width 控件的宽度。**Single**。 ## 方法 ### Drag 当 [**DragMode**](#dragmode) 为 **vbManual** 时,开始、完成或取消手动拖放操作。DriveListBox 本身不引发鼠标事件,因此调用通常位于父 **Form** 或容器的鼠标处理程序中。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants) 的成员:**vbCancel**(0)、**vbBeginDrag**(1,默认)或 **vbEndDrag**(2)。 ### Move 在单次调用中重新定位并可选地调整控件大小。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 一个 **Single**,给出新的水平位置。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从控件发起 OLE 拖动操作,引发 [**OLEStartDrag**](#olestartdrag) 事件以便应用程序填充 **DataObject**。 语法:*object*.**OLEDrag** ### Refresh 从操作系统重新读取当前连接的驱动器集合,重新填充列表,然后重绘控件。在插入可移动介质或映射/断开网络驱动器后很有用---控件本身不会监视这些事件。不会引发 [**Change**](#change),即使先前选中的驱动器不再存在(选择会移到条目 `0`)。 语法:*object*.**Refresh** ### SetFocus 将输入焦点移至控件。控件必须同时 [**Visible**](#visible) 和 [**Enabled**](#enabled),否则引发运行时错误 5(*无效的过程调用或参数*)。 语法:*object*.**SetFocus** ### ShowWhatsThis 以"这是什么?"弹出窗口的形式显示由 [**WhatsThisHelpID**](#whatsthishelpid) 标识的主题。 语法:*object*.**ShowWhatsThis** ### ZOrder 将控件置于其同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants) 的成员:**vbBringToFront**(0,默认)或 **vbSendToBack**(1)。 ## 事件 ### Change 在选中的驱动器更改后引发---无论是用户从下拉列表中选择了不同的条目,还是代码向 [**Drive**](#drive) 或 [**ListIndex**](#listindex) 赋了不同的值。与当前选择匹配的赋值不会引发此事件,[**Refresh**](#refresh) 或 [**Initialize**](#initialize) 之前的初始填充期间也不会引发。**默认事件。** 语法:*object*\_**Change**( ) ### CloseUp 当下拉部分关闭时引发---可能是因为用户选择了条目、点击了其他位置或按了 **Esc**。 语法:*object*\_**CloseUp**( ) ### DragDrop 当手动拖动操作在目标控件上结束时,在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 当手动拖动操作进行时,在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### DropDown 当用户打开下拉部分时引发。 语法:*object*\_**DropDown**( ) ### GotFocus 当控件获得输入焦点时引发。 语法:*object*\_**GotFocus**( ) ### Initialize 在底层窗口创建且初始驱动器列表已加载后立即引发一次。twinBASIC 新增---VB6 在此控件上没有等效事件。 语法:*object*\_**Initialize**( ) ### KeyDown 当控件有焦点时用户按下任意键引发。 语法:*object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress 当用户输入产生 ANSI 按键的字符时引发。 语法:*object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp 当控件有焦点时用户释放按键引发。 语法:*object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus 当控件失去输入焦点时引发。 语法:*object*\_**LostFocus**( ) ### OLECompleteDrag 当 OLE 拖动操作完成时,在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 当用户在目标控件上放置数据时,在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver 当 OLE 拖动经过目标控件时,在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 在拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的数据格式时,在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag 在 OLE 拖动开始时在源控件上引发,以便应用程序填充 **DataObject** 并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Scroll 当下拉列表被滚动时引发---通过滚动条、键盘或(当 [**WheelScrollEvent**](#wheelscrollevent) 为 **True** 时)鼠标滚轮。新的偏移可从 [**TopIndex**](#topindex) 读取。 语法:*object*\_**Scroll**( ) ### Validate 当焦点正在移动到另一个 [**CausesValidation**](#causesvalidation) 为 **True** 的控件时引发。将 *Cancel* 设置为 **True** 可使焦点保持在此控件上。 语法:*object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /en/official/Tutorials/CEF/Driving-Monaco.md --- # Driving Monaco from twinBASIC A case study combining everything from the previous tutorials: a form with **two** [**CefBrowser**](/en/official/Reference/CEF/CefBrowser/) controls --- the Microsoft Monaco editor on the left, a live HTML preview on the right. As the user types, Monaco posts the edited source to twinBASIC, which mirrors it into the preview pane. The complete project ships as *Sample 1b --- Chromium Embedded Framework Examples* in the New-Project dialog (form *Example 3*). ## Architecture ![](/assets/MonacoArchitecture.yN_RVrrc.svg) The editor runs as a local web app under a virtual hostname; the preview pane is fed raw HTML through [**NavigateToString**](/en/official/Reference/CEF/CefBrowser/#navigatetostring). ## Runtime version requirement Monaco uses modern JavaScript features that don't exist in older Chromium versions. The sample checks at startup and warns if the loaded runtime is too old: ```vb If WebView.CefMajorVersion < 109 Then MsgBox "Sorry, Monaco is not supported by this old version of CEF." End If ``` In practice this means **v109** or **v145** for this tutorial --- **v49** lacks the JavaScript API Monaco depends on. See [Getting started](/en/official/Tutorials/CEF/Getting-started) for picking the right package reference. ## Setting up the editor's assets The Monaco editor ships as a ~2 MB collection of JavaScript, CSS, and font files. Drop them into a `Resources` sub-folder of your project --- call it `MONACO_DEMO` --- alongside an `index.html` and a small bootstrap `script.js`. The [Hosting local web assets](/en/official/Tutorials/CEF/Hosting-local-web-assets) tutorial describes the layout. The page itself is a single `<div id='container'>` plus the bootstrap script that listens for an *initial-content* message from the host: ```html <!DOCTYPE html> <html> <head> <script src="/vs/loader.js"></script> <script src="/script.js"></script> <link rel="stylesheet" href="/styles.css"> </head> <body> <div id="container"></div> </body> </html> ``` ```js window.chrome.webview.addEventListener('message', (event) => { let initialHTML = event.data; require.config({ paths: { 'vs': 'https://monaco.example/vs' } }); require(["vs/editor/editor.main"], () => { let editor = monaco.editor.create(document.getElementById('container'), { value: initialHTML, language: 'html', theme: 'vs-dark', minimap: { enabled: false } }); editor.onDidChangeModelContent(() => { // Inform the host of every edit. window.chrome.webview.postMessage(editor.getValue()); }); }); }); ``` ## The BASIC side Drop two `CefBrowser` controls on a form --- `WebView` (the editor) and `WebViewPreview` (the renderer). The `Ready` handler deploys the assets, registers the virtual host, and navigates: ```vb Private localPath As String Private Sub WebView_Ready() Handles WebView.Ready localPath = Environ$("USERPROFILE") & "\Documents\tbMonacoDemo" CopyResourcesFolderContentsToLocalPath "MONACO_DEMO", localPath WebView.SetVirtualHostNameToFolderMapping _ "monaco.example", localPath & "\" WebView.Navigate "https://monaco.example/index.html" End Sub ``` (`CopyResourcesFolderContentsToLocalPath` is the helper from [Hosting local web assets](/en/official/Tutorials/CEF/Hosting-local-web-assets).) The two controls share a single helper browser process --- the first **CefBrowser** to reach [**Ready**](/en/official/Reference/CEF/CefBrowser/#ready) launches it, the second one attaches to the existing process. That sharing is what makes the two-pane pattern cheap. ## Pushing the initial content Once Monaco has finished loading, the bootstrap script listens for a `message` event containing the HTML to seed the editor with. Fire that message after the editor's [**NavigationComplete**](/en/official/Reference/CEF/CefBrowser/#navigationcomplete): ```vb Private Sub WebView_NavigationComplete( _ ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) _ Handles WebView.NavigationComplete If WebView.DocumentURL <> "https://monaco.example/index.html" Then Exit Sub Dim initialHTML As String = _ StrConv(LoadResData("initial-editor-html.html", "MONACO_DEMO"), vbFromUTF8) WebView.PostWebMessage(initialHTML) WebViewPreview.NavigateToString(initialHTML) End Sub ``` [**LoadResData**](/en/official/Reference/VB/Global/#loadresdata) returns the resource bytes; `StrConv(..., vbFromUTF8)` decodes them. [**PostWebMessage**](/en/official/Reference/CEF/CefBrowser/#postwebmessage) hands the string to Monaco's `message` listener; [**NavigateToString**](/en/official/Reference/CEF/CefBrowser/#navigatetostring) seeds the preview pane with the same text rendered as HTML. The `If` guard at the top is important --- [**NavigationComplete**](/en/official/Reference/CEF/CefBrowser/#navigationcomplete) fires for *every* navigation, including internal Monaco asset loads. Only seed the editor on the navigation to `index.html`. ## Live preview Every keystroke in Monaco fires its `onDidChangeModelContent` callback, which `postMessage`s the new content back to BASIC. That arrives as the [**JsMessage**](/en/official/Reference/CEF/CefBrowser/#jsmessage) event --- feed it straight into the preview: ```vb Private Sub WebView_JsMessage(ByVal Message As Variant) Handles WebView.JsMessage WebViewPreview.NavigateToString(Message) End Sub ``` That's it --- the preview pane re-renders on every edit. ## Detecting a missing runtime A reasonable fraction of users will run the application on a machine where the CEF runtime ZIP has not been installed. The [**Error**](/en/official/Reference/CEF/CefBrowser/#error) event reports this case with the exact path the control searched: ```vb Private Sub WebView_Error(ByVal code As Long, ByVal msg As String) _ Handles WebView.Error MsgBox "Failed to initialize the CEF control." & vbCrLf & vbCrLf & _ "Code: " & Hex$(code) & vbCrLf & _ msg, vbExclamation, "CEF" End Sub ``` The fix is to install the matching runtime ZIP from [github.com/twinbasic/cef-runtimes](https://github.com/twinbasic/cef-runtimes/releases/), or to ship the runtime alongside the application and point [**EnvironmentOptions.BrowserExecutableFolder**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#browserexecutablefolder) at it during the [**Create**](/en/official/Reference/CEF/CefBrowser/#create) event. See [Getting started](/en/official/Tutorials/CEF/Getting-started) for the install path and the ZIPs. ## Where next * [Hosting local web assets](/en/official/Tutorials/CEF/Hosting-local-web-assets) -- the `CopyResourcesFolderContentsToLocalPath` helper and virtual-host pattern this tutorial builds on. * [JavaScript interop](/en/official/Tutorials/CEF/JavaScript-interop) -- the two bridges between BASIC and JavaScript. * [Re-entrancy](/en/official/Tutorials/CEF/Re-entrancy) -- why the live-preview pattern is safe even though it's mostly synchronous-looking. * [CefBrowser reference](/en/official/Reference/CEF/CefBrowser/) -- every property, method, and event. * [Driving Monaco (WebView2)](/en/official/Tutorials/WebView2/Driving-Monaco) -- the parallel implementation using the [**WebView2**](/en/official/Reference/WebView2/WebView2/) control. --- --- url: /en/official/Tutorials/WebView2/Driving-Monaco.md --- # Driving Monaco from twinBASIC A case study combining everything from the previous tutorials: a form with **two** [**WebView2**](/en/official/Reference/WebView2/WebView2/) controls --- the Microsoft Monaco editor on the left, a live HTML preview on the right. As the user types, Monaco posts the edited source to twinBASIC, which mirrors it into the preview pane. The complete project ships as *Sample 0 --- WebView2 Examples* in the New-Project dialog (form *Example 3*). ## Architecture ![](/assets/MonacoArchitecture.yN_RVrrc.svg) The editor runs as a local web app under a virtual hostname; the preview pane is fed raw HTML through [**NavigateToString**](/en/official/Reference/WebView2/WebView2/#navigatetostring). ## Setting up the editor's assets The Monaco editor ships as a ~2 MB collection of JavaScript, CSS, and font files. Drop them into a `Resources` sub-folder of your project --- call it `MONACO_DEMO` --- alongside an `index.html` and a small bootstrap `script.js`. The [Hosting local web assets](/en/official/Tutorials/WebView2/Hosting-local-web-assets) tutorial describes the layout. The page itself is a single `<div id='container'>` plus the bootstrap script that listens for an *initial-content* message from the host: ```html <!DOCTYPE html> <html> <head> <script src="/vs/loader.js"></script> <script src="/script.js"></script> <link rel="stylesheet" href="/styles.css"> </head> <body> <div id="container"></div> </body> </html> ``` ```js window.chrome.webview.addEventListener('message', (event) => { let initialHTML = event.data; require.config({ paths: { 'vs': 'https://monaco.example/vs' } }); require(["vs/editor/editor.main"], () => { let editor = monaco.editor.create(document.getElementById('container'), { value: initialHTML, language: 'html', theme: 'vs-dark', minimap: { enabled: false } }); editor.onDidChangeModelContent(() => { // Inform the host of every edit. window.chrome.webview.postMessage(editor.getValue()); }); }); }); ``` ## The BASIC side Drop two `WebView2` controls on a form --- `WebView` (the editor) and `WebViewPreview` (the renderer). The `Ready` handler deploys the assets, registers the virtual host, and navigates: ```vb Private localPath As String Private Sub WebView_Ready() Handles WebView.Ready localPath = Environ$("USERPROFILE") & "\Documents\tbMonacoDemo" CopyResourcesFolderContentsToLocalPath "MONACO_DEMO", localPath WebView.SetVirtualHostNameToFolderMapping _ "monaco.example", localPath & "\", wv2ResourceAllow WebView.Navigate "https://monaco.example/index.html" End Sub ``` (`CopyResourcesFolderContentsToLocalPath` is the helper from [Hosting local web assets](/en/official/Tutorials/WebView2/Hosting-local-web-assets).) ## Pushing the initial content Once Monaco has finished loading, the bootstrap script listens for a `message` event containing the HTML to seed the editor with. Fire that message after the editor's [**NavigationComplete**](/en/official/Reference/WebView2/WebView2/#navigationcomplete): ```vb Private Sub WebView_NavigationComplete( _ ByVal IsSuccess As Boolean, ByVal WebErrorStatus As Long) _ Handles WebView.NavigationComplete Dim initialHTML As String = _ StrConv(LoadResData("initial-editor-html.html", "MONACO_DEMO"), vbFromUTF8) WebView.PostWebMessage(initialHTML) WebViewPreview.NavigateToString(initialHTML) End Sub ``` [**LoadResData**](/en/official/Reference/VB/Global/#loadresdata) returns the resource bytes; `StrConv(..., vbFromUTF8)` decodes them. [**PostWebMessage**](/en/official/Reference/WebView2/WebView2/#postwebmessage) hands the string to Monaco's `message` listener; [**NavigateToString**](/en/official/Reference/WebView2/WebView2/#navigatetostring) seeds the preview pane with the same text rendered as HTML. ## Live preview Every keystroke in Monaco fires its `onDidChangeModelContent` callback, which `postMessage`s the new content back to BASIC. That arrives as the [**JsMessage**](/en/official/Reference/WebView2/WebView2/#jsmessage) event --- feed it straight into the preview: ```vb Private Sub WebView_JsMessage(ByVal Message As Variant) Handles WebView.JsMessage WebViewPreview.NavigateToString(Message) End Sub ``` That's it --- the preview pane re-renders on every edit. ## Detecting a missing Edge runtime A reasonable fraction of users will run the application on a machine where the WebView2 Evergreen runtime isn't installed. The [**Error**](/en/official/Reference/WebView2/WebView2/#error) event reports this case as Win32 error code `&H80070002` (`ERROR_FILE_NOT_FOUND`): ```vb Private Sub WebView_Error(ByVal code As Long, ByVal msg As String) _ Handles WebView.Error Const ERROR_FILE_NOT_FOUND As Long = &H80070002 If code = ERROR_FILE_NOT_FOUND Then MsgBox "Failed to initialize the WebView2 control." & vbCrLf & _ "Please install the WebView2 (Evergreen) runtime.", _ vbExclamation, "WebView2" Else MsgBox "WebView2 error " & Hex$(code) & ": " & msg, _ vbExclamation, "WebView2" End If End Sub ``` It is worth handling this even in single-WebView applications --- the message you show here is the difference between *"nothing happens"* and *"oh, I need to install something"*. ## Where next * [Hosting local web assets](/en/official/Tutorials/WebView2/Hosting-local-web-assets) -- the `CopyResourcesFolderContentsToLocalPath` helper and virtual-host pattern this tutorial builds on. * [JavaScript interop](/en/official/Tutorials/WebView2/JavaScript-interop) -- the three bridges between BASIC and JavaScript. * [WebView2 reference](/en/official/Reference/WebView2/WebView2/) -- every property, method, and event. --- --- url: /en/official/Reference/WinNativeCommonCtls/DTPicker.md --- # DTPicker class A **DTPicker** is a date / time picker control. The inline field shows the current date or time formatted per [**Format**](#format); clicking the dropdown arrow opens a [**MonthView**](/en/official/Reference/WinNativeCommonCtls/MonthView)-style calendar for picking a new date, and dismissing the calendar updates [**Value**](#value). ```vb Private Sub Form_Load() DTPicker1.Format = dtpShortDate DTPicker1.MinDate = DateSerial(2020, 1, 1) DTPicker1.MaxDate = DateSerial(2030, 12, 31) DTPicker1.Value = Date End Sub Private Sub DTPicker1_Change() Debug.Print "User picked: " & DTPicker1.Value End Sub ``` The control inherits the focusable rect-dockable members from `BaseControlFocusable` --- size, position, **Anchors**, **Dock**, **Font**, **BackColor** / **ForeColor**, **Appearance**, **MousePointer** / **MouseIcon**, **ToolTipText**, **DragMode** / **DragIcon**, **Drag**, **Refresh**, **SetFocus**, **TabIndex** / **TabStop**, **ZOrder**, **CausesValidation**, **VisualStyles**, **hWnd**, **HelpContextID** / **WhatsThisHelpID**. ## Format and value [**Format**](#format) selects one of four display styles --- long date, short date, time, or a custom format string supplied through [**CustomFormat**](#customformat). The inline value is always a **Date**, but [**Value**](#value) is typed **Variant** because a [**CheckBox**](#checkbox)-equipped picker may have no date assigned (the user can clear the checkbox), in which case [**Value**](#value) reads as **Null**. The convenience accessors [**Year**](#year), [**Month**](#month), [**Week**](#week), [**Day**](#day), [**Hour**](#hour), [**Minute**](#minute), and [**Second**](#second) decompose the current value into individual components; assigning to any of them rewrites [**Value**](#value) with the requested component changed. The [**StartOfWeek**](#startofweek) property selects the first-day-of-week used by the calendar dropdown and by [**Week**](#week). ## Custom format and callback events When [**Format**](#format) is set to **dtpCustom**, the [**CustomFormat**](#customformat) string controls the display. The format syntax follows the Win32 `GetDateFormat` / `GetTimeFormat` picture string (e.g. `"dddd, MMMM dd, yyyy"`). Tokens enclosed in callback markers (`X` literals in the format) raise the [**Format**](#format-event), [**FormatSize**](#formatsize), and [**CallbackKeyDown**](#callbackkeydown) events so the application can render its own field content and respond to keyboard navigation across it. ## Calendar appearance When the dropdown calendar is shown, the [**CalendarBackColor**](#calendarbackcolor), [**CalendarForeColor**](#calendarforecolor), [**CalendarTitleBackColor**](#calendartitlebackcolor), [**CalendarTitleForeColor**](#calendartitleforecolor), and [**CalendarTrailingForeColor**](#calendartrailingforecolor) properties control the calendar's colors via `DTM_SETMCCOLOR`. The [**CalendarShowToday**](#calendarshowtoday), [**CalendarShowTodayCircle**](#calendarshowtodaycircle), [**CalendarShowWeekNumbers**](#calendarshowweeknumbers), and [**CalendarShowTrailingDates**](#calendarshowtrailingdates) booleans toggle the corresponding `MCS_…` style flags on the embedded calendar. [**hWndCalendar**](#hwndcalendar) returns the Win32 handle of the dropped-down calendar window --- useful for advanced customization. It is only valid between the [**DropDown**](#dropdown) and [**CloseUp**](#closeup) events. ## Properties ### CalendarBackColor The calendar dropdown's background color. **OLE\_COLOR**. Default: **vbWindowBackground**. Applied to the embedded month calendar via `DTM_SETMCCOLOR` / `MCSC_MONTHBK`. ### CalendarForeColor The calendar dropdown's text color. **OLE\_COLOR**. Default: **vbButtonText**. ### CalendarShowToday Whether the calendar dropdown shows the "Today: …" string at the bottom. **Boolean**. Default: **True**. ### CalendarShowTodayCircle Whether the calendar dropdown highlights today's date with a circle. **Boolean**. Default: **True**. ### CalendarShowTrailingDates Whether the calendar dropdown shows the leading and trailing days of the previous and next month. **Boolean**. Default: **True**. ### CalendarShowWeekNumbers Whether the calendar dropdown shows a week-number column on the left. **Boolean**. Default: **False**. ### CalendarTitleBackColor The calendar dropdown's title bar background color. **OLE\_COLOR**. Default: **vb3DFace**. ### CalendarTitleForeColor The calendar dropdown's title bar text color. **OLE\_COLOR**. Default: **vbButtonText**. ### CalendarTrailingForeColor The text color used for trailing days from adjacent months when [**CalendarShowTrailingDates**](#calendarshowtrailingdates) is **True**. **OLE\_COLOR**. Default: **vbGrayText**. ### CheckBox Whether the picker includes a checkbox next to the date value. **Boolean**. Default: **False**. When **True**, the user can clear the checkbox to leave the picker without a value, in which case [**Value**](#value) returns **Null**. Assigning **Null** to [**Value**](#value) when **CheckBox** is **False** raises run-time error 35787 (*"Can't set Value to NULL when CheckBox property = FALSE"*). Changing this property at run time recreates the underlying Win32 window --- the property cannot be flipped in the GWL\_STYLE alone. ### CustomFormat The picture string used when [**Format**](#format) is **dtpCustom**. **String**. Default: empty. Follows the Win32 `GetDateFormat` syntax (e.g. `"dddd, MMMM dd, yyyy"`, `"hh:mm:ss tt"`). ### Day The day-of-month component of [**Value**](#value). **Integer** (1--31). Reading returns the current day; assigning rewrites the date with the new day, raising run-time error 380 if the assigned value is out of range for the current month. See also [**DayCount**](#daycount). ### DayCount The number of days in the current value's month. **Long**, read-only. Computed from [**Year**](#year) and [**Month**](#month). Useful for bounds-checking before assigning [**Day**](#day). ### DayOfWeek The day-of-week the current [**Value**](#value) falls on, as a [**VbDayOfWeek**](/en/official/Reference/VBA/Constants/VbDayOfWeek) member (`vbSunday` through `vbSaturday`). Read-only. ### Format The display format. A member of [**DTPickerFormatConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants): **dtpLongDate**, **dtpShortDate**, **dtpTime**, **dtpCustom**. Default: **dtpShortDate**. ### Hour The hour component of [**Value**](#value), in 24-hour form. **Integer** (1--23 --- note that `0` is rejected with run-time error 380 by the setter; read returns the live value). Reading is unrestricted. ### hWndCalendar The Win32 handle of the dropped-down calendar window. **HWND**, read-only. Valid only between the [**DropDown**](#dropdown) and [**CloseUp**](#closeup) events; reads as 0 when the calendar is closed. ### MaxDate The upper bound of the navigable date range. **Date**. Default: `9999-12-31`. Assigning a value lower than [**MinDate**](#mindate) raises run-time error 35775. If the current [**Value**](#value) exceeds the new **MaxDate**, [**Value**](#value) is clamped down to **MaxDate**. ### MinDate The lower bound of the navigable date range. **Date**. Default: `1601-01-01`. Assigning a value higher than [**MaxDate**](#maxdate) raises run-time error 35775. If the current [**Value**](#value) is below the new **MinDate**, [**Value**](#value) is clamped up to **MinDate**. ### Minute The minute component of [**Value**](#value). **Integer** (1--59 on assignment; 0--59 on read). ### Month The month-of-year component of [**Value**](#value). **Integer** (1--12). Assigning an out-of-range value raises run-time error 380. ### RightToLeft ::: info **RightToLeft** is tagged `[Unimplemented]` and has no effect; reading and writing the property compiles but the underlying Win32 control's RTL mode is not switched. ::: A **Boolean**. ### Second The seconds component of [**Value**](#value). **Integer** (1--59 on assignment; 0--59 on read). ### StartOfWeek Which day of the week is rendered as the leftmost column in the calendar dropdown. A [**VbDayOfWeek**](/en/official/Reference/VBA/Constants/VbDayOfWeek) member. Defaults to the system's first-day-of-week setting (resolved through `vbUseSystemDayOfWeek`). ### UpDown Whether the picker uses a spin-button widget instead of a dropdown calendar. **Boolean**. Default: **False**. When **True**, the user adjusts the date by clicking up / down arrows next to each field; the calendar dropdown is suppressed. Changing this property at run time recreates the underlying Win32 window. ### Value The selected date / time. **Variant**. The default member. Reads as a **Date** when the checkbox is checked (or [**CheckBox**](#checkbox) is **False**) or **Null** when the checkbox is cleared. Assigning **Null** when [**CheckBox**](#checkbox) is **False** raises run-time error 35787. Assigning a date outside \[[**MinDate**](#mindate), [**MaxDate**](#maxdate)] raises run-time error 35773. Assigning a numeric (non-**Date**) value implicitly converts via **CDate**. Assigning **Empty** is treated the same as assigning **Null**. Changing [**Value**](#value) fires [**Change**](#change) once the control is past its initialization phase. ### Week The ISO-style week-of-year for the current [**Value**](#value). **Integer** (1--53). The setter applies a delta of `DateAdd("ww", …)` so changing **Week** preserves the day-of-week within the week. Assigning out-of-range raises run-time error 380. Honors [**StartOfWeek**](#startofweek) when computing the week boundary. ### Year The year component of [**Value**](#value). **Integer**. ## Events ### CallbackKeyDown Raised when the user presses a key while a custom callback field is focused. Lets the application interpret the key (e.g. arrow-up / arrow-down to cycle through enum values) and rewrite the date. Syntax: *object*\_**CallbackKeyDown**( **ByVal** *KeyCode* **As Integer**, **ByVal** *Shift* **As Integer**, **ByVal** *CallbackField* **As String**, *CallbackDate* **As Date** ) *KeyCode* : A [**KeyCodeConstants**](/en/official/Reference/VBRUN/Constants/KeyCodeConstants) value identifying the pressed key. *Shift* : A bitmask of [**ShiftConstants**](/en/official/Reference/VBRUN/Constants/ShiftConstants) values. *CallbackField* : The picture-string token identifying which callback field is focused. *CallbackDate* : **In / out** --- the current value the application can mutate before the event returns. ### Change Raised when [**Value**](#value) has changed, either by user interaction or by code. Does not fire during the initial property-deserialization pass at form load. Syntax: *object*\_**Change**( ) ### Click Raised on a mouse click inside the control's rectangle. Syntax: *object*\_**Click**( ) ### CloseUp Raised when the dropdown calendar closes --- either by the user picking a date, by clicking outside the calendar, or by pressing **Esc**. Syntax: *object*\_**CloseUp**( ) ### DblClick Raised on a double-click inside the control's rectangle. Syntax: *object*\_**DblClick**( ) ### DragDrop Inherited drag-drop event. See [**DragMode**](/en/official/Reference/VB/CheckBox/#dragmode). ### DragOver Inherited drag-drop event. ### DropDown Raised when the dropdown calendar opens. The handler can use [**hWndCalendar**](#hwndcalendar) to customize the dropped-down calendar window. Syntax: *object*\_**DropDown**( ) ### Format Raised for each custom callback field that needs rendering, when [**Format**](#format) is **dtpCustom** and the [**CustomFormat**](#customformat) string contains callback tokens. Syntax: *object*\_**Format**( **ByVal** *CallbackField* **As String**, *FormattedString* **As String** ) *CallbackField* : The picture-string token identifying which callback field is being rendered. *FormattedString* : **Out** --- the application sets this to the text the picker should display in the field. ### FormatSize Raised before [**Format**](#format-event) to ask how many character cells to reserve for the callback field. The picker uses the current [**Font**](/en/official/Reference/VB/CheckBox/#font) to measure the rendered width. Syntax: *object*\_**FormatSize**( **ByVal** *CallbackField* **As String**, *Size* **As Integer** ) *CallbackField* : The picture-string token identifying the callback field. *Size* : **Out** --- the application sets this to the expected character count. ### GotFocus Inherited focus event. ### Initialize Raised after the control's window has been created and its properties initialised from persisted state. Fires once per form-load. Syntax: *object*\_**Initialize**( ) ### LostFocus Inherited focus event. ### MouseDown Inherited mouse event. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Inherited mouse event. ### MouseUp Inherited mouse event. ### OLECompleteDrag, OLEDragDrop, OLEDragOver, OLEGiveFeedback, OLESetData, OLEStartDrag Inherited OLE drag-and-drop events. See [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants) for the **OLEDropMode** values. ### Validate Inherited validation event. Set *Cancel* to **True** to keep focus on the control. Syntax: *object*\_**Validate**( *Cancel* **As Boolean** ) ## See Also * [MonthView](/en/official/Reference/WinNativeCommonCtls/MonthView) -- the full-month calendar control; **DTPicker**'s dropdown uses the same underlying Win32 control * [DTPickerFormatConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants) -- the **Format** values * [ControlTypeConstants](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) -- where **vbDTPicker** lives --- --- url: /zh/official/Reference/WinNativeCommonCtls/DTPicker.md --- # DTPicker 类 **DTPicker** 是一个日期/时间选择器控件。内联字段按 [**Format**](#format) 显示当前日期或时间;点击下拉箭头打开 [**MonthView**](/official/Reference/WinNativeCommonCtls/MonthView) 风格的日历以选取新日期,关闭日历后更新 [**Value**](#value)。 ```vb Private Sub Form_Load() DTPicker1.Format = dtpShortDate DTPicker1.MinDate = DateSerial(2020, 1, 1) DTPicker1.MaxDate = DateSerial(2030, 12, 31) DTPicker1.Value = Date End Sub Private Sub DTPicker1_Change() Debug.Print "User picked: " & DTPicker1.Value End Sub ``` 控件从 `BaseControlFocusable` 继承可聚焦矩形可停靠成员 --- 大小、位置、**Anchors**、**Dock**、**Font**、**BackColor** / **ForeColor**、**Appearance**、**MousePointer** / **MouseIcon**、**ToolTipText**、**DragMode** / **DragIcon**、**Drag**、**Refresh**、**SetFocus**、**TabIndex** / **TabStop**、**ZOrder**、**CausesValidation**、**VisualStyles**、**hWnd**、**HelpContextID** / **WhatsThisHelpID**。 ## 格式和值 [**Format**](#format) 选择四种显示样式之一 --- 长日期、短日期、时间或通过 [**CustomFormat**](#customformat) 提供的自定义格式字符串。内联值始终是 **Date**,但 [**Value**](#value) 类型为 **Variant**,因为带 [**CheckBox**](#checkbox) 的选择器可能没有赋值日期(用户可清除复选框),此时 [**Value**](#value) 读取为 **Null**。 便捷访问器 [**Year**](#year)、[**Month**](#month)、[**Week**](#week)、[**Day**](#day)、[**Hour**](#hour)、[**Minute**](#minute) 和 [**Second**](#second) 将当前值分解为各个分量;对其中任何一个赋值会用更改后分量重写 [**Value**](#value)。[**StartOfWeek**](#startofweek) 属性选择日历下拉和 [**Week**](#week) 所使用的一周起始日。 ## 自定义格式和回调事件 当 [**Format**](#format) 设为 **dtpCustom** 时,[**CustomFormat**](#customformat) 字符串控制显示。格式语法遵循Win32 `GetDateFormat` / `GetTimeFormat` 图片字符串(如 `"dddd, MMMM dd, yyyy"`)。包含在回调标记中的标记(格式中的 `X` 字面量)触发 [**Format**](#format-event)、[**FormatSize**](#formatsize) 和 [**CallbackKeyDown**](#callbackkeydown) 事件,以便应用程序渲染自己的字段内容并响应其中的键盘导航。 ## 日历外观 当下拉日历显示时,[**CalendarBackColor**](#calendarbackcolor)、[**CalendarForeColor**](#calendarforecolor)、[**CalendarTitleBackColor**](#calendartitlebackcolor)、[**CalendarTitleForeColor**](#calendartitleforecolor) 和 [**CalendarTrailingForeColor**](#calendartrailingforecolor) 属性通过 `DTM_SETMCCOLOR` 控制日历颜色。[**CalendarShowToday**](#calendarshowtoday)、[**CalendarShowTodayCircle**](#calendarshowtodaycircle)、[**CalendarShowWeekNumbers**](#calendarshowweeknumbers) 和 [**CalendarShowTrailingDates**](#calendarshowtrailingdates) 布尔值切换嵌入日历上对应的 `MCS_…` 样式标志。 [**hWndCalendar**](#hwndcalendar) 返回下拉日历窗口的Win32句柄 --- 用于高级自定义。仅在 [**DropDown**](#dropdown) 和 [**CloseUp**](#closeup) 事件之间有效。 ## 属性 ### CalendarBackColor 日历下拉的背景颜色。**OLE\_COLOR**。默认:**vbWindowBackground**。通过 `DTM_SETMCCOLOR` / `MCSC_MONTHBK` 应用于嵌入的月历。 ### CalendarForeColor 日历下拉的文本颜色。**OLE\_COLOR**。默认:**vbButtonText**。 ### CalendarShowToday 日历下拉是否在底部显示"Today: …"字符串。**Boolean**。默认:**True**。 ### CalendarShowTodayCircle 日历下拉是否用圆圈高亮今日日期。**Boolean**。默认:**True**。 ### CalendarShowTrailingDates 日历下拉是否显示上月末和下月初的前导和尾随日期。**Boolean**。默认:**True**。 ### CalendarShowWeekNumbers 日历下拉是否在左侧显示周数列。**Boolean**。默认:**False**。 ### CalendarTitleBackColor 日历下拉的标题栏背景颜色。**OLE\_COLOR**。默认:**vb3DFace**。 ### CalendarTitleForeColor 日历下拉的标题栏文本颜色。**OLE\_COLOR**。默认:**vbButtonText**。 ### CalendarTrailingForeColor 当 [**CalendarShowTrailingDates**](#calendarshowtrailingdates) 为 **True** 时用于相邻月份尾随日期的文本颜色。**OLE\_COLOR**。默认:**vbGrayText**。 ### CheckBox 选择器是否在日期值旁包含复选框。**Boolean**。默认:**False**。为 **True** 时,用户可清除复选框使选择器无值,此时 [**Value**](#value) 返回 **Null**。当 **CheckBox** 为 **False** 时对 [**Value**](#value) 赋值 **Null** 引发运行时错误 35787(*"Can't set Value to NULL when CheckBox property = FALSE"*)。 运行时更改此属性会重新创建底层Win32窗口 --- 该属性无法仅通过 GWL\_STYLE 切换。 ### CustomFormat 当 [**Format**](#format) 为 **dtpCustom** 时使用的图片字符串。**String**。默认:空。遵循Win32 `GetDateFormat` 语法(如 `"dddd, MMMM dd, yyyy"`、`"hh:mm:ss tt"`)。 ### Day [**Value**](#value) 的月中第几天分量。**Integer**(1--31)。读取返回当前天;赋值以新天重写日期,超出当月范围时引发运行时错误 380。参见 [**DayCount**](#daycount)。 ### DayCount 当前值所在月份的天数。**Long**,只读。从 [**Year**](#year) 和 [**Month**](#month) 计算。用于在赋值 [**Day**](#day) 之前进行边界检查。 ### DayOfWeek 当前 [**Value**](#value) 是星期几,作为 [**VbDayOfWeek**](/official/Reference/VBA/Constants/VbDayOfWeek) 的成员(`vbSunday` 到 `vbSaturday`)。只读。 ### Format 显示格式。[**DTPickerFormatConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants) 的成员:**dtpLongDate**、**dtpShortDate**、**dtpTime**、**dtpCustom**。默认:**dtpShortDate**。 ### Hour [**Value**](#value) 的小时分量,24小时制。**Integer**(1--23 --- 注意设置器拒绝 `0` 并引发运行时错误 380;读取返回实时值)。读取不受限制。 ### hWndCalendar 下拉日历窗口的Win32句柄。**HWND**,只读。仅在 [**DropDown**](#dropdown) 和 [**CloseUp**](#closeup) 事件之间有效;日历关闭时读取为 0。 ### MaxDate 可导航日期范围的上限。**Date**。默认:`9999-12-31`。赋值低于 [**MinDate**](#mindate) 时引发运行时错误 35775。如果当前 [**Value**](#value) 超过新的 **MaxDate**,[**Value**](#value) 被钳位到 **MaxDate**。 ### MinDate 可导航日期范围的下限。**Date**。默认:`1601-01-01`。赋值高于 [**MaxDate**](#maxdate) 时引发运行时错误 35775。如果当前 [**Value**](#value) 低于新的 **MinDate**,[**Value**](#value) 被钳位到 **MinDate**。 ### Minute [**Value**](#value) 的分钟分量。**Integer**(赋值时 1--59;读取时 0--59)。 ### Month [**Value**](#value) 的月份分量。**Integer**(1--12)。赋值超出范围时引发运行时错误 380。 ### RightToLeft ::: info **RightToLeft** 标记为 `[Unimplemented]`,没有任何效果;读写该属性可编译,但底层Win32控件的RTL模式不会被切换。 ::: 一个 **Boolean**。 ### Second [**Value**](#value) 的秒分量。**Integer**(赋值时 1--59;读取时 0--59)。 ### StartOfWeek 日历下拉中哪一天渲染为最左列。[**VbDayOfWeek**](/official/Reference/VBA/Constants/VbDayOfWeek) 的成员。默认为系统的一周起始日设置(通过 `vbUseSystemDayOfWeek` 解析)。 ### UpDown 选择器是否使用微调按钮部件代替下拉日历。**Boolean**。默认:**False**。为 **True** 时,用户通过点击每个字段旁的上/下箭头调整日期;日历下拉被抑制。 运行时更改此属性会重新创建底层Win32窗口。 ### Value 选定的日期/时间。**Variant**。默认成员。 当复选框选中(或 [**CheckBox**](#checkbox) 为 **False**)时读取为 **Date**,复选框清除时读取为 **Null**。当 [**CheckBox**](#checkbox) 为 **False** 时赋值 **Null** 引发运行时错误 35787。赋值超出 \[[**MinDate**](#mindate), [**MaxDate**](#maxdate)] 的日期引发运行时错误 35773。 赋值数值(非 **Date**)类型时隐式通过 **CDate** 转换。赋值 **Empty** 等同于赋值 **Null**。更改 [**Value**](#value) 在控件完成初始化阶段后触发 [**Change**](#change)。 ### Week 当前 [**Value**](#value) 的ISO风格年周数。**Integer**(1--53)。设置器应用 `DateAdd("ww", …)` 的差值,因此更改 **Week** 会保留周内的星期几。赋值超出范围时引发运行时错误 380。计算周边界时遵循 [**StartOfWeek**](#startofweek)。 ### Year [**Value**](#value) 的年份分量。**Integer**。 ## 事件 ### CallbackKeyDown 当自定义回调字段获得焦点时用户按下键触发。让应用程序解释按键(例如上/下箭头循环枚举值)并重写日期。 语法:*object*\_**CallbackKeyDown**(**ByVal** *KeyCode* **As Integer**,**ByVal** *Shift* **As Integer**,**ByVal** *CallbackField* **As String**,*CallbackDate* **As Date**) *KeyCode* : 一个 [**KeyCodeConstants**](/official/Reference/VBRUN/Constants/KeyCodeConstants) 值,标识按下的键。 *Shift* : [**ShiftConstants**](/official/Reference/VBRUN/Constants/ShiftConstants) 值的位掩码。 *CallbackField* : 标识聚焦的回调字段的图片字符串标记。 *CallbackDate* : **输入/输出** --- 应用程序可在事件返回前修改的当前值。 ### Change 当 [**Value**](#value) 已更改时触发,无论通过用户交互还是代码。在窗体加载的初始属性反序列化期间不触发。 语法:*object*\_**Change**( ) ### Click 在控件矩形内鼠标点击时触发。 语法:*object*\_**Click**( ) ### CloseUp 当下拉日历关闭时触发 --- 无论用户选取日期、点击日历外部还是按 **Esc**。 语法:*object*\_**CloseUp**( ) ### DblClick 在控件矩形内双击时触发。 语法:*object*\_**DblClick**( ) ### DragDrop 继承的拖放事件。参见 [**DragMode**](/official/Reference/VB/CheckBox/#dragmode)。 ### DragOver 继承的拖放事件。 ### DropDown 当下拉日历打开时触发。处理程序可使用 [**hWndCalendar**](#hwndcalendar) 自定义下拉的日历窗口。 语法:*object*\_**DropDown**( ) ### Format 当 [**Format**](#format) 为 **dtpCustom** 且 [**CustomFormat**](#customformat) 字符串包含回调标记时,为每个需要渲染的自定义回调字段触发。 语法:*object*\_**Format**(**ByVal** *CallbackField* **As String**,*FormattedString* **As String**) *CallbackField* : 标识正在渲染的回调字段的图片字符串标记。 *FormattedString* : **输出** --- 应用程序将其设为选择器应在字段中显示的文本。 ### FormatSize 在 [**Format**](#format-event) 之前触发,询问为回调字段保留多少字符单元格。选择器使用当前 [**Font**](/official/Reference/VB/CheckBox/#font) 测量渲染宽度。 语法:*object*\_**FormatSize**(**ByVal** *CallbackField* **As String**,*Size* **As Integer**) *CallbackField* : 标识回调字段的图片字符串标记。 *Size* : **输出** --- 应用程序将其设为预期字符数。 ### GotFocus 继承的焦点事件。 ### Initialize 控件窗口创建并从持久化状态初始化属性后触发。每次窗体加载触发一次。 语法:*object*\_**Initialize**( ) ### LostFocus 继承的焦点事件。 ### MouseDown 继承的鼠标事件。 语法:*object*\_**MouseDown**(*Button* **As Integer**,*Shift* **As Integer**,*X* **As Single**,*Y* **As Single**) ### MouseMove 继承的鼠标事件。 ### MouseUp 继承的鼠标事件。 ### OLECompleteDrag, OLEDragDrop, OLEDragOver, OLEGiveFeedback, OLESetData, OLEStartDrag 继承的OLE拖放事件。参见 [**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants) 获取 **OLEDropMode** 值。 ### Validate 继承的验证事件。将 *Cancel* 设为 **True** 以将焦点保留在控件上。 语法:*object*\_**Validate**(*Cancel* **As Boolean**) ## 另见 * [MonthView](/official/Reference/WinNativeCommonCtls/MonthView) --- 全月日历控件;**DTPicker** 的下拉使用相同的底层Win32控件 * [DTPickerFormatConstants](/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants) --- **Format** 的值 * [ControlTypeConstants](/official/Reference/VBRUN/Constants/ControlTypeConstants) --- **vbDTPicker** 所在位置 --- --- url: /en/packages/vbccr/datetime/dtpicker.md description: >- DTPicker Control - VBCCR Development Manual, complete API reference based on source code --- # DTPicker Control Based on the Windows date-time picker common control, provides date and time selection with custom formatting capabilities. ## Enumerations ### DtpFormatConstants | Constant | Value | Description | |----------|-------|-------------| | DtpFormatLongDate | 0 | Long date format | | DtpFormatShortDate | 1 | Short date format | | DtpFormatTime | 2 | Time format | | DtpFormatCustom | 3 | Custom format | ## Properties ### Name ```vb Property Get Name() As String ``` Returns the name used to identify the object in code. ### Tag ```vb Property Get/Let Tag() As String ``` Stores extra data needed by the program. ### Parent ```vb Property Get Parent() As Object ``` Returns the object that contains this object. ### Container `Property Get Container() As Object` / `Property Set Container(ByVal Value As Object)` Returns/sets the container of the object. ### Left ```vb Property Get/Let Left() As Single ``` Returns/sets the distance between the left edge of the object and the left edge of its container. ### Top ```vb Property Get/Let Top() As Single ``` Returns/sets the distance between the top edge of the object and the top edge of its container. ### Width ```vb Property Get/Let Width() As Single ``` Returns/sets the width of the object. ### Height ```vb Property Get/Let Height() As Single ``` Returns/sets the height of the object. ### Visible ```vb Property Get/Let Visible() As Boolean ``` Returns/sets whether the object is visible. ### ToolTipText ```vb Property Get/Let ToolTipText() As String ``` Returns/sets the tooltip text displayed when the mouse hovers. ### HelpContextID ```vb Property Get/Let HelpContextID() As Long ``` Specifies the default help file context ID for the object. ### WhatsThisHelpID ```vb Property Get/Let WhatsThisHelpID() As Long ``` Returns/sets the context number associated with the object. ### DragIcon ```vb Property Get/Let/Set DragIcon() As IPictureDisp ``` Returns/sets the icon displayed during a drag-and-drop operation. ### DragMode ```vb Property Get/Let DragMode() As Integer ``` Returns/sets the drag mode (manual or automatic). ### hWnd ```vb Property Get hWnd() As LongPtr ``` Returns the window handle of the date-time picker control. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Returns the window handle of the UserControl. ### hWndCalendar ```vb Property Get hWndCalendar() As LongPtr ``` Returns the window handle of the drop-down calendar control. ### Font ```vb Property Get/Let/Set Font() As StdFont ``` Returns/sets the control font. ### CalendarFont ```vb Property Get/Let/Set CalendarFont() As StdFont ``` Returns/sets the drop-down calendar font. ### VisualStyles ```vb Property Get/Let VisualStyles() As Boolean ``` Returns/sets whether visual styles are enabled. ### Enabled ```vb Property Get/Let Enabled() As Boolean ``` Returns/sets whether the control responds to user events. ### OLEDropMode ```vb Property Get/Let OLEDropMode() As OLEDropModeConstants ``` Returns/sets whether the object can act as an OLE drop target. See common enumerations. ### MousePointer ```vb Property Get/Let MousePointer() As CCMousePointerConstants ``` Returns/sets the mouse pointer type. See common enumerations. ### MouseIcon ```vb Property Get/Let/Set MouseIcon() As IPictureDisp ``` Returns/sets the custom mouse icon. ### MouseTrack ```vb Property Get/Let MouseTrack() As Boolean ``` Returns/sets whether MouseEnter/MouseLeave events are fired. ### RightToLeft ```vb Property Get/Let RightToLeft() As Boolean ``` Determines the text display direction and visual appearance of the control on bidirectional systems. ### RightToLeftLayout ```vb Property Get/Let RightToLeftLayout() As Boolean ``` Returns/sets whether right-to-left mirrored layout is enabled. ### RightToLeftMode ```vb Property Get/Let RightToLeftMode() As CCRightToLeftModeConstants ``` Returns/sets the right-to-left mode. See common enumerations. ### CalendarBackColor ```vb Property Get/Let CalendarBackColor() As OLE_COLOR ``` Returns/sets the background color of the calendar month area. ### CalendarForeColor ```vb Property Get/Let CalendarForeColor() As OLE_COLOR ``` Returns/sets the foreground color of the calendar month area. ### CalendarTitleBackColor ```vb Property Get/Let CalendarTitleBackColor() As OLE_COLOR ``` Returns/sets the background color of the calendar title. ### CalendarTitleForeColor ```vb Property Get/Let CalendarTitleForeColor() As OLE_COLOR ``` Returns/sets the foreground color of the calendar title. ### CalendarTrailingForeColor ```vb Property Get/Let CalendarTrailingForeColor() As OLE_COLOR ``` Returns/sets the foreground color of the calendar trailing dates. ### CalendarShowToday ```vb Property Get/Let CalendarShowToday() As Boolean ``` Returns/sets whether the calendar displays the "today" date at the bottom. ### CalendarShowTodayCircle ```vb Property Get/Let CalendarShowTodayCircle() As Boolean ``` Returns/sets whether a circle is drawn around today's date. ### CalendarShowWeekNumbers ```vb Property Get/Let CalendarShowWeekNumbers() As Boolean ``` Returns/sets whether the calendar displays week numbers. ### CalendarShowTrailingDates ```vb Property Get/Let CalendarShowTrailingDates() As Boolean ``` Returns/sets whether the calendar displays dates from the previous/next month. ### CalendarAlignment ```vb Property Get/Let CalendarAlignment() As CCLeftRightAlignmentConstants ``` Returns/sets the alignment of the calendar. See common enumerations. ### CalendarDayState ```vb Property Get/Let CalendarDayState() As Boolean ``` Returns/sets whether the calendar supports bold dates in the CalendarGetDayBold event. ### CalendarUseShortestDayNames ```vb Property Get/Let CalendarUseShortestDayNames() As Boolean ``` Returns/sets whether the calendar uses the shortest day names. ### MinDate ```vb Property Get/Let MinDate() As Date ``` Returns/sets the minimum selectable date. ### MaxDate ```vb Property Get/Let MaxDate() As Date ``` Returns/sets the maximum selectable date. ### Value ```vb Property Get/Let Value() As Variant ``` Returns/sets the current date-time value. ### Year ```vb Property Get Year() As Integer ``` Returns the year of the current date (read-only). ### Month ```vb Property Get Month() As Integer ``` Returns the month of the current date (read-only). ### Week ```vb Property Get Week() As Integer ``` Returns the week number of the current date (read-only). ### Day ```vb Property Get Day() As Integer ``` Returns the day of the current date (read-only). ### Hour ```vb Property Get Hour() As Integer ``` Returns the hour of the current time (read-only). ### Minute ```vb Property Get Minute() As Integer ``` Returns the minute of the current time (read-only). ### Second ```vb Property Get Second() As Integer ``` Returns the second of the current time (read-only). ### Format ```vb Property Get/Let Format() As DtpFormatConstants ``` Returns/sets the display format of the date-time. ### CustomFormat ```vb Property Get/Let CustomFormat() As String ``` Returns/sets the custom format string. ### UpDown ```vb Property Get/Let UpDown() As Boolean ``` Returns/sets whether to use up/down buttons instead of a drop-down calendar. ### CheckBox ```vb Property Get/Let CheckBox() As Boolean ``` Returns/sets whether a check box is displayed in the control. ### AllowUserInput ```vb Property Get/Let AllowUserInput() As Boolean ``` Returns/sets whether the user can directly input dates. ### StartOfWeek ```vb Property Get/Let StartOfWeek() As Integer ``` Returns/sets the first day of the week (0=system default, 1=Monday, ..., 7=Sunday). ### DroppedDown ```vb Property Get DroppedDown() As Boolean ``` Returns whether the calendar is in the dropped-down state (read-only). ### Selected ```vb Property Get Selected() As Boolean ``` Returns whether the check box is checked (read-only). ### DayCount ```vb Property Get DayCount() As Long ``` Returns the number of currently visible dates (read-only). ### DayOfWeek ```vb Property Get DayOfWeek() As Integer ``` Returns the day of the week for the current date (read-only). ### SystemStartOfWeek ```vb Property Get SystemStartOfWeek() As Integer ``` Returns the system setting for the first day of the week (read-only). ## Methods ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag-and-drop operation. ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` Starts, ends, or cancels a drag operation. ### SetFocus ```vb Public Sub SetFocus() ``` Moves focus to the control. ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` Places the control at the front or back of the Z-order. ### Refresh ```vb Public Sub Refresh() ``` Forces the control to repaint. ### GetIdealSize ```vb Public Sub GetIdealSize(ByRef Width As Long, ByRef Height As Long) ``` Retrieves the ideal size of the control. ## Events ### Click ```vb Public Event Click() ``` Occurs when the user presses and releases a mouse button. ### DropDown ```vb Public Event DropDown() ``` Occurs when the drop-down calendar is about to be displayed. ### CloseUp ```vb Public Event CloseUp() ``` Occurs when the user closes the calendar. ### Change ```vb Public Event Change() ``` Occurs when the contents of the control change. ### ContextMenu ```vb Public Event ContextMenu(ByRef Handled As Boolean, ByVal X As Single, ByVal Y As Single) ``` Occurs when the user right-clicks or presses Shift+F10. ### CalendarGetDayBold ```vb Public Event CalendarGetDayBold(ByVal StartDate As Date, ByVal Count As Long, ByRef State() As Boolean) ``` Occurs when the calendar requests bold date information. Requires comctl32.dll version 6.1 or later. ### CalendarContextMenu ```vb Public Event CalendarContextMenu(ByRef Handled As Boolean, ByVal X As Single, ByVal Y As Single) ``` Occurs when the calendar area is right-clicked. ### CallbackKeyDown ```vb Public Event CallbackKeyDown(ByVal KeyCode As Integer, ByVal Shift As Integer, ByVal CallbackField As String, ByRef CallbackDate As Date) ``` Occurs when the user presses a key on a callback field. ### FormatString ```vb Public Event FormatString(ByVal CallbackField As String, ByRef FormattedString As String) ``` Occurs when the control requests the display text for a callback field. ### FormatSize ```vb Public Event FormatSize(ByVal CallbackField As String, ByRef Size As Integer) ``` Occurs when the control needs to know the maximum allowed size of a callback field. ### BeforeUserInput ```vb Public Event BeforeUserInput(ByVal hWndEdit As LongPtr) ``` Occurs when the user attempts to input a string. ### ParseUserInput ```vb Public Event ParseUserInput(ByVal Text As String, ByRef ParseDate As Variant) ``` Occurs when the user has finished input, requiring parsing of the input string. ### AfterUserInput ```vb Public Event AfterUserInput() ``` Occurs when user input has been completed or cancelled. ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Occurs before the KeyDown event. ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Occurs before the KeyUp event. ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` Occurs when the user presses a key. ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` Occurs when the user releases a key. ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` Occurs when the user presses and releases a character key. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when the user presses a mouse button. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when the user moves the mouse. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when the user releases a mouse button. ### MouseEnter ```vb Public Event MouseEnter() ``` Occurs when the mouse enters the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Occurs when the mouse leaves the control. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` Occurs when an OLE drag-and-drop operation has completed. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when data is dropped on the control via an OLE drag-and-drop operation. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` Occurs when the mouse passes over the control during an OLE drag-and-drop operation. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` Occurs when the mouse cursor needs to be changed. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` Occurs when the drop target requests data. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` Occurs when an OLE drag-and-drop operation is initiated. ## Code Examples ### Basic Usage ```vb Private Sub Form_Load() With DTPicker1 .Format = DtpFormatShortDate .Value = Date .MinDate = #1/1/1900# .MaxDate = #12/31/9999# End With End Sub Private Sub DTPicker1_Change() MsgBox "Selected date: " & DTPicker1.Value End Sub ``` ### Custom Format and Callback ```vb Private Sub Form_Load() DTPicker1.Format = DtpFormatCustom DTPicker1.CustomFormat = "yyyy年MM月dd日 '第' w '周'" End Sub Private Sub DTPicker1_FormatString(ByVal CallbackField As String, ByRef FormattedString As String) Select Case CallbackField Case "w" FormattedString = CStr(DatePart("ww", DTPicker1.Value, vbMonday)) End Select End Sub ``` --- --- url: >- /en/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants.md --- # DTPickerFormatConstants Selects the display format used by a [**DTPicker**](/en/official/Reference/WinNativeCommonCtls/DTPicker) control. Used by the [**DTPicker.Format**](/en/official/Reference/WinNativeCommonCtls/DTPicker#format) property. When set to **dtpCustom**, the picker also reads [**DTPicker.CustomFormat**](/en/official/Reference/WinNativeCommonCtls/DTPicker#customformat) to control the actual display. | Member | Value | Description | |-------------------|-------|------------------------------------------------------------------------| | **dtpLongDate** | 0 | Long date format, e.g. *"Tuesday, January 14, 2025"*. | | **dtpShortDate** | 1 | Short date format, e.g. *"1/14/2025"*. | | **dtpTime** | 2 | Time format, e.g. *"3:45:00 PM"*. | | **dtpCustom** | 3 | Custom picture string from [**CustomFormat**](/en/official/Reference/WinNativeCommonCtls/DTPicker#customformat). | ## See Also * [DTPicker](/en/official/Reference/WinNativeCommonCtls/DTPicker) -- the consuming control --- --- url: >- /zh/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants.md --- # DTPickerFormatConstants 选择 [**DTPicker**](/official/Reference/WinNativeCommonCtls/DTPicker) 控件使用的显示格式。由 [**DTPicker.Format**](/official/Reference/WinNativeCommonCtls/DTPicker#format) 属性使用。 当设置为 **dtpCustom** 时,选择器还会读取 [**DTPicker.CustomFormat**](/official/Reference/WinNativeCommonCtls/DTPicker#customformat) 来控制实际显示。 | 成员 | 值 | 描述 | |-------------------|-------|------------------------------------------------------------------------| | **dtpLongDate** | 0 | 长日期格式,例如 *"Tuesday, January 14, 2025"*。 | | **dtpShortDate** | 1 | 短日期格式,例如 *"1/14/2025"*。 | | **dtpTime** | 2 | 时间格式,例如 *"3:45:00 PM"*。 | | **dtpCustom** | 3 | 来自 [**CustomFormat**](/official/Reference/WinNativeCommonCtls/DTPicker#customformat) 的自定义图片字符串。 | ## 另见 * [DTPicker](/official/Reference/WinNativeCommonCtls/DTPicker) —— 使用该枚举的控件 --- --- url: /en/official/IDE/Menu/Edit.md --- # Edit Menu ![Edit Menu](/assets/Menu_Edit.Y09uiSar.png "Edit Menu") * Undo CTRL + Z * Redo CTRL + Y *** * Cut CTRL + X / SHIFT + DELETE * Copy CTRL + C / CTRL + INSERT * Paste CTRL + V * Delete DELETE * Select All CTRL + A *** * Find... CTRL + F * Replace... CTRL + H * Find In Project... CTRL + SHIFT + Y *** * Indent CTRL + ] * Outdent CTRL + \[ * Format Selection * Format Document *** * Quick Find... ALT + F * Quick Replace... ALT + H * Select All Matchtes ALT + A *** * Fold CTRL + { * Fold Procedures CTRL + ALT + ARROWLEFT * Fold All * Unfold CTRL + } * Unfold Procedures CTRL + ALT + ARROWRIGHT * Unfold All *** * Go To Line/Column... *** * Transform To Uppercase * Transform To Lowercase * TransformTo Titlecase * Transform To Snakecase --- --- url: /en/official/IDE/Editor.md --- # Editor ![Editor](/assets/Editor.DHImjvC5.png "Editor") ## Options * Show Code Folding * never * *when hovering* * always * Render Whitespace * all * *none* * boundary * selection * trailing * Font Size * 8px * ... * *13px* * ... * 30px * Show Navigation Bar * above * below * none * ✔ Show Indent Guides * ✔ Show Line Numbers * Code Hints Always Visible * Sticky Scroll * ✔ Show MiniMap * Show Advanced Info On Hover * Show Single Row Of Tabs * ✔ Auto Prettify Code * ✔ Show CodeLens Run Procedure ## Tabs List When a file is open in the *Editor* it will be listed in the *Tabs List* and you can jump between them here. ![Editor Tabs List (Example)](Images/Editor_TabsList_Example.png "Editor Tabs List (Example)") *Recently Closed*. ![Editor Tabs List Recently Closed](Images/Editor_TabsList_RecentlyClosed.png "Editor Tabs List Recently Closed") *Recently Closed - List* ![Editor Tabs List Recently Closed Examples](/assets/Editor_TabsList_RecentlyClosed_Example.CzbZXcDf.png "Editor Tabs List Recently Closed Examples") --- --- url: /en/official/Reference/tbIDE/Editor.md --- # Editor class The base interface every IDE editor presents. **Editor** itself exposes only the universal members --- [**Path**](#path), [**Type**](#type), [**SetFocus**](#setfocus), [**Close**](#close), [**Save**](#save), [**IsDirty**](#isdirty) --- and an instance returned from [**Editors.Item**](/en/official/Reference/tbIDE/Editors#item) or the [**Host.OnChangedActiveEditor**](/en/official/Reference/tbIDE/Host#onchangedactiveeditor) event is normally a *specific* editor kind (e.g. [**CodeEditor**](/en/official/Reference/tbIDE/CodeEditor) for code panes), reachable by casting. ## Castability An **Editor** returned by the IDE is castable to the specific editor kind for the underlying pane. For a code pane the cast target is [**CodeEditor**](/en/official/Reference/tbIDE/CodeEditor); other editor kinds may be added in future IDE versions and will follow the same pattern. Use `TypeOf` to test before casting: ```vb If Host.ActiveEditors.Count > 0 Then If TypeOf Host.ActiveEditors(0) Is CodeEditor Then Dim codeEditor As CodeEditor = Host.ActiveEditors(0) Host.DebugConsole.PrintText "selected text: " & codeEditor.SelectedText End If End If ``` Cast unconditionally only when the source --- e.g. an [**OnChangedActiveEditor**](/en/official/Reference/tbIDE/Host#onchangedactiveeditor) handler for a known editor kind --- guarantees the underlying type. ## Properties ### IsDirty **True** if the editor has unsaved changes. **Boolean**, read-only. ### Path The internal virtual-FS path of the file the editor is displaying --- e.g. `"twinbasic:/Sources/MainModule.twin"`. **String**, read-only. Resolves through [**FileSystem.ResolvePath**](/en/official/Reference/tbIDE/FileSystem#resolvepath). ### Type A short string identifying the editor kind --- e.g. `"CodeEditor"` for a code pane. **String**, read-only. Useful for diagnostic log lines; for capability dispatch prefer `TypeOf` over comparing this string. ## Methods ### Close Closes the editor. If the editor is dirty, the IDE may prompt the user before actually closing. Syntax: *editor*.**Close** ### Save Saves the editor's contents. Syntax: *editor*.**Save** ### SetFocus Brings the editor to the foreground and gives it keyboard focus. Syntax: *editor*.**SetFocus** --- --- url: /zh/official/Reference/tbIDE/Editor.md --- # Editor 类 每个 IDE 编辑器呈现的基础接口。**Editor** 本身只暴露通用成员——[**Path**](#path)、[**Type**](#type)、[**SetFocus**](#setfocus)、[**Close**](#close)、[**Save**](#save)、[**IsDirty**](#isdirty)——而从 [**Editors.Item**](/official/Reference/tbIDE/Editors#item) 或 [**Host.OnChangedActiveEditor**](/official/Reference/tbIDE/Host#onchangedactiveeditor) 事件返回的实例通常是*特定*的编辑器类型(例如代码窗格的 [**CodeEditor**](/official/Reference/tbIDE/CodeEditor)),可通过转换获取。 ## 可转换性 IDE 返回的 **Editor** 可转换为底层窗格的特定编辑器类型。对于代码窗格,转换目标是 [**CodeEditor**](/official/Reference/tbIDE/CodeEditor);未来 IDE 版本可能添加其他编辑器类型,并遵循相同模式。 在转换前使用 `TypeOf` 测试: ```vb If Host.ActiveEditors.Count > 0 Then If TypeOf Host.ActiveEditors(0) Is CodeEditor Then Dim codeEditor As CodeEditor = Host.ActiveEditors(0) Host.DebugConsole.PrintText "selected text: " & codeEditor.SelectedText End If End If ``` 仅当来源——例如已知编辑器类型的 [**OnChangedActiveEditor**](/official/Reference/tbIDE/Host#onchangedactiveeditor) 处理程序——保证底层类型时,才可无条件转换。 ## 属性 ### IsDirty 如果编辑器有未保存的更改则为 **True**。**Boolean**,只读。 ### Path 编辑器显示的文件的内部虚拟文件系统路径——例如 `"twinbasic:/Sources/MainModule.twin"`。**String**,只读。通过 [**FileSystem.ResolvePath**](/official/Reference/tbIDE/FileSystem#resolvepath) 解析。 ### Type 标识编辑器类型的短字符串——例如代码窗格为 `"CodeEditor"`。**String**,只读。适用于诊断日志行;对于能力分派,优先使用 `TypeOf` 而非比较此字符串。 ## 方法 ### Close 关闭编辑器。如果编辑器有未保存的更改,IDE 可能会在实际关闭前提示用户。 语法:*editor*.**Close** ### Save 保存编辑器的内容。 语法:*editor*.**Save** ### SetFocus 将编辑器带到前台并给予键盘焦点。 语法:*editor*.**SetFocus** --- --- url: /en/official/Reference/tbIDE/Editors.md --- # Editors class The collection of editors active in the IDE --- accessible through [**Host.ActiveEditors**](/en/official/Reference/tbIDE/Host#activeeditors). The IDE currently exposes exactly one active editor at a time, but the collection interface allows future versions to expose more. The most common operations are `Host.ActiveEditors(0)` (the active editor) and [**Open**](#open) (jump to a file at a given line / column). ```vb ' Read the selection out of the currently-focused code pane: If Host.ActiveEditors.Count > 0 Then If TypeOf Host.ActiveEditors(0) Is CodeEditor Then Dim codeEditor As CodeEditor = Host.ActiveEditors(0) Host.DebugConsole.PrintText codeEditor.SelectedText End If End If ' Navigate to a specific file + line + column: Host.ActiveEditors.Open "twinbasic:/Sources/MainModule.twin", 42, 8 Host.ActiveEditors.Item(0).SetFocus ``` ## Properties ### Count Number of editors currently active. **Long**, read-only. Currently always **0** or **1**. ### Item Indexed access to the editor collection. **DefaultMember** --- so `Host.ActiveEditors(0)` is equivalent to `Host.ActiveEditors.Item(0)`. Syntax: *editors*( *Index* ) **As** [**Editor**](/en/official/Reference/tbIDE/Editor) *Index* : A zero-based **Variant** index. Currently `0` is the only valid value when an editor is open. The returned object is an [**Editor**](/en/official/Reference/tbIDE/Editor) but is usually castable to a more specific kind (e.g. [**CodeEditor**](/en/official/Reference/tbIDE/CodeEditor) for a code pane) --- see [Editor castability](/en/official/Reference/tbIDE/Editor#castability). ## Methods ### Open Opens (or re-focuses) the editor for a given file, optionally positioning the caret at a specific line and column. Syntax: *editors*.**Open** *Path* \[, *LineNumber* ] \[, *ColumnNumber* ] \[, *Options* ] *Path* : *required* The virtual-FS path of the file to open. **String**. Typically starts with `"twinbasic:/"`; the value returned by [**FileSystemItem.Path**](/en/official/Reference/tbIDE/FileSystemItem#path) or [**Editor.Path**](/en/official/Reference/tbIDE/Editor#path) is always a valid argument. *LineNumber* : *optional* One-based line number to navigate to. **Long**. Default **0** (no navigation --- open the file at its remembered cursor position). *ColumnNumber* : *optional* One-based column number on the requested line. **Long**. Default **0** (column 1). *Options* : *optional* An [**EditorOpenOptions**](#editoropenoptions) value. Default [**NONE**](#EditorOpenOptions_NONE). After **Open** returns, the requested file is the active editor; call `Editors.Item(0).SetFocus` to give it keyboard focus. ```vb Host.ActiveEditors.Open File.Path, LineNumber, ColumnNumber Host.ActiveEditors.Item(0).SetFocus ``` ## EditorOpenOptions A flags enum declared inline on the **Editors** interface; consumed by [**Open**](#open). Currently a single-value placeholder --- additional flags may appear in later IDE versions. | Constant | Value | Description | |----------|-------|-------------| | **NONE** | 0 | No special open options. | --- --- url: /zh/official/Reference/tbIDE/Editors.md --- # Editors 类 IDE 中活动编辑器的集合——通过 [**Host.ActiveEditors**](/official/Reference/tbIDE/Host#activeeditors) 访问。IDE 当前同一时间只暴露一个活动编辑器,但集合接口允许未来版本暴露更多。最常见的操作是 `Host.ActiveEditors(0)`(活动编辑器)和 [**Open**](#open)(跳转到指定文件的指定行/列)。 ```vb ' 从当前聚焦的代码窗格读取选择内容: If Host.ActiveEditors.Count > 0 Then If TypeOf Host.ActiveEditors(0) Is CodeEditor Then Dim codeEditor As CodeEditor = Host.ActiveEditors(0) Host.DebugConsole.PrintText codeEditor.SelectedText End If End If ' 导航到特定文件 + 行 + 列: Host.ActiveEditors.Open "twinbasic:/Sources/MainModule.twin", 42, 8 Host.ActiveEditors.Item(0).SetFocus ``` ## 属性 ### Count 当前活动的编辑器数量。**Long**,只读。当前始终为 **0** 或 **1**。 ### Item 编辑器集合的索引访问。**DefaultMember**——因此 `Host.ActiveEditors(0)` 等同于 `Host.ActiveEditors.Item(0)`。 语法:*editors*( *Index* ) **As** [**Editor**](/official/Reference/tbIDE/Editor) *Index* : 一个基于 0 的 **Variant** 索引。当前打开编辑器时 `0` 是唯一有效值。 返回的对象是 [**Editor**](/official/Reference/tbIDE/Editor),但通常可转换为更具体的类型(例如代码窗格的 [**CodeEditor**](/official/Reference/tbIDE/CodeEditor))——参见[编辑器可转换性](/official/Reference/tbIDE/Editor#可转换性)。 ## 方法 ### Open 打开(或重新聚焦)指定文件的编辑器,可选地将插入符定位到特定行和列。 语法:*editors*.**Open** *Path* \[, *LineNumber* ] \[, *ColumnNumber* ] \[, *Options* ] *Path* : *必需* 要打开的文件的虚拟文件系统路径。**String**。通常以 `"twinbasic:/"` 开头;[**FileSystemItem.Path**](/official/Reference/tbIDE/FileSystemItem#path) 或 [**Editor.Path**](/official/Reference/tbIDE/Editor#path) 返回的值始终是有效参数。 *LineNumber* : *可选* 要导航到的基于 1 的行号。**Long**。默认 **0**(不导航——在文件记住的光标位置打开)。 *ColumnNumber* : *可选* 请求行上基于 1 的列号。**Long**。默认 **0**(第 1 列)。 *Options* : *可选* 一个 [**EditorOpenOptions**](#editoropenoptions) 值。默认 [**NONE**](#EditorOpenOptions_NONE)。 **Open** 返回后,请求的文件成为活动编辑器;调用 `Editors.Item(0).SetFocus` 给予它键盘焦点。 ```vb Host.ActiveEditors.Open File.Path, LineNumber, ColumnNumber Host.ActiveEditors.Item(0).SetFocus ``` ## EditorOpenOptions 在 **Editors** 接口上内联声明的标志枚举;由 [**Open**](#open) 消费。当前为单值占位符——未来 IDE 版本可能添加更多标志。 | 常量 | 值 | 描述 | |------|-----|------| | **NONE** | 0 | 无特殊打开选项。 | --- --- url: /en/official/Reference/VBA/HiddenModule/Emit.md --- # Emit Splices raw bytes into the codegen output of the enclosing procedure. Syntax: **Emit** *Values* ... *Values* : *required* A **ParamArray** of **Byte** values that are emitted, in order, at the location of the call. The bytes are written into the procedure's machine code at the spot where **Emit** appears --- there is no run-time call. Used together with the **Naked** procedure modifier to write inline assembly. ### Example A naked **InterlockedIncrement** that adds one to *Addend* atomically. ```vb Public Function InlineInterlockedIncrement CDecl Naked(Addend As Long) As Long #If Win64 Then Emit(&Hb8, &H01, &H00, &H00, &H00) ' mov eax,0x1 Emit(&Hf0, &H0f, &Hc1, &H41, &H00) ' lock xadd DWORD PTR [rcx+0x4],eax Emit(&Hff, &Hc0) ' inc eax Emit(&Hc3) ' ret #Else Emit(&H8b, &H4c, &H24, &H04) ' mov ecx, DWORD PTR _Addend$[esp-4] Emit(&Hb8, &H01, &H00, &H00, &H00) ' mov eax, 1 Emit(&Hf0, &H0f, &Hc1, &H01) ' lock xadd DWORD PTR [ecx], eax Emit(&H40) ' inc eax Emit(&Hc3) ' ret 0 #End If End Function ``` ### See Also * [EmitAny](/en/official/Reference/VBA/HiddenModule/EmitAny) procedure * [Direct Assembly Insertion](/en/official/Features/Advanced/Assembly) * [StackOffset](/en/official/Reference/VBA/HiddenModule/StackOffset) function --- --- url: /zh/official/Reference/VBA/HiddenModule/Emit.md --- # Emit 将原始字节拼接到封闭过程的代码生成输出中。 语法:**Emit** *Values* ... *Values* : *必需* 一个**Byte**值的**ParamArray**,按顺序在调用位置处发出。 这些字节被写入过程机器代码中**Emit**出现的位置——没有运行时调用。与**Naked**过程修饰符一起使用来编写内联汇编。 ### 示例 一个原子的**InterlockedIncrement**,将*Addend*加一。 ```vb Public Function InlineInterlockedIncrement CDecl Naked(Addend As Long) As Long #If Win64 Then Emit(&Hb8, &H01, &H00, &H00, &H00) ' mov eax,0x1 Emit(&Hf0, &H0f, &Hc1, &H41, &H00) ' lock xadd DWORD PTR [rcx+0x4],eax Emit(&Hff, &Hc0) ' inc eax Emit(&Hc3) ' ret #Else Emit(&H8b, &H4c, &H24, &H04) ' mov ecx, DWORD PTR _Addend$[esp-4] Emit(&Hb8, &H01, &H00, &H00, &H00) ' mov eax, 1 Emit(&Hf0, &H0f, &Hc1, &H01) ' lock xadd DWORD PTR [ecx], eax Emit(&H40) ' inc eax Emit(&Hc3) ' ret 0 #End If End Function ``` ### 另请参阅 * [EmitAny](/official/Reference/VBA/HiddenModule/EmitAny)过程 * [直接汇编插入](/official/Features/Advanced/Assembly) * [StackOffset](/official/Reference/VBA/HiddenModule/StackOffset)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/EmitAny.md --- # EmitAny Splices typed literal values into the codegen output of the enclosing procedure. The size of the output is inferred from each value's data type. Syntax: **EmitAny** *Values* ... *Values* : *required* A **ParamArray** of typed literals. Each value contributes its in-memory representation --- one byte for **Byte**, two for **Integer**, four for **Long** or **Single**, eight for **Currency**, **Double**, or **LongLong**, and pointer-sized for **LongPtr**. The values are written into the procedure's machine code at the spot where **EmitAny** appears. Useful when an instruction's operand mixes opcodes and a multi-byte immediate --- letting **EmitAny** size the immediate correctly avoids splitting it into a sequence of [**Emit**](/en/official/Reference/VBA/HiddenModule/Emit) calls. ### Example ```vb ' mov eax, 0x12345678 — emit the opcode + a 32-bit immediate. EmitAny(CByte(&HB8), CLng(&H12345678)) ``` ### See Also * [Emit](/en/official/Reference/VBA/HiddenModule/Emit) procedure * [Direct Assembly Insertion](/en/official/Features/Advanced/Assembly) --- --- url: /zh/official/Reference/VBA/HiddenModule/EmitAny.md --- # EmitAny 将类型化字面值拼接到封闭过程的代码生成输出中。输出的大小从每个值的数据类型推断。 语法:**EmitAny** *Values* ... *Values* : *必需* 类型化字面值的**ParamArray**。每个值贡献其内存表示——**Byte**一个字节,**Integer**两个字节,**Long**或**Single**四个字节,**Currency**、**Double**或**LongLong**八个字节,**LongPtr**为指针大小。 这些值被写入过程机器代码中**EmitAny**出现的位置。当指令的操作数混合了操作码和多字节立即数时非常有用——让**EmitAny**正确确定立即数的大小避免了将其拆分为一系列[**Emit**](/official/Reference/VBA/HiddenModule/Emit)调用。 ### 示例 ```vb ' mov eax, 0x12345678 — emit the opcode + a 32-bit immediate. EmitAny(CByte(&HB8), CLng(&H12345678)) ``` ### 另请参阅 * [Emit](/official/Reference/VBA/HiddenModule/Emit)过程 * [直接汇编插入](/official/Features/Advanced/Assembly) --- --- url: /en/official/Reference/Core/End.md --- # End Ends a procedure or block. Syntax: * **End**\ Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the [**Open**](/en/official/Reference/Core/Open) statement, and to clear variables. * **End Function**\ Required to end a [**Function**](/en/official/Reference/Core/Function) statement. * **End If**\ Required to end a block [**If...Then...Else**](/en/official/Reference/Core/If-Then-Else) statement. * **End Property**\ Required to end a [**Property Get**](/en/official/Reference/Core/Property), [**Property Let**](/en/official/Reference/Core/Property), and [**Property Set**](/en/official/Reference/Core/Property) procedure. * **End Select**\ Required to end a [**Select Case**](/en/official/Reference/Core/Select-Case) statement. * **End Sub** Required to end a [**Sub**](/en/official/Reference/Core/Sub) statement. * **End Type** Required to end a user-defined type (UDT) definition ([**Type**](/en/official/Reference/Core/Type) statement). * **End With** Required to end a [**With**](/en/official/Reference/Core/With) statement. When executed, the **End** statement resets all module-level variables and all static local variables in all modules. To preserve the value of these variables, use the [**Stop**](/en/official/Reference/Core/Stop) statement instead --- execution can then resume while preserving the value of those variables. ::: warning The **End** statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code placed in the Unload, QueryUnload, and Terminate events of forms and class modules is not executed. Objects created from class modules are destroyed, files opened by using the **Open** statement are closed, and memory used by the program is freed. Object references held by other programs are invalidated. ::: The **End** statement provides a way to force the program to halt. For normal termination of a Visual Basic program, all forms should be unloaded. The program closes as soon as there are no other programs holding references to objects created from public class modules and no code executing. ### Example This example uses the **End** statement to end code execution if the user enters an invalid password. ```vb Sub Form_Load Dim Password, Pword PassWord = "Swordfish" Pword = InputBox("Type in your password") If Pword <> PassWord Then MsgBox "Sorry, incorrect password" End End If End Sub ``` --- --- url: /zh/official/Reference/Core/End.md --- # End 结束过程或块。 语法: * **End**\ 立即终止执行。本身从不是必需的,但可以放在过程中任何位置以结束代码执行、关闭用 [**Open**](/official/Reference/Core/Open) 语句打开的文件并清除变量。 * **End Function**\ 结束 [**Function**](/official/Reference/Core/Function) 语句所必需。 * **End If**\ 结束块 [**If...Then...Else**](/official/Reference/Core/If-Then-Else) 语句所必需。 * **End Property**\ 结束 [**Property Get**](/official/Reference/Core/Property)、[**Property Let**](/official/Reference/Core/Property) 和 [**Property Set**](/official/Reference/Core/Property) 过程所必需。 * **End Select**\ 结束 [**Select Case**](/official/Reference/Core/Select-Case) 语句所必需。 * **End Sub** 结束 [**Sub**](/official/Reference/Core/Sub) 语句所必需。 * **End Type** 结束用户自定义类型(UDT)定义([**Type**](/official/Reference/Core/Type) 语句)所必需。 * **End With** 结束 [**With**](/official/Reference/Core/With) 语句所必需。 执行时,**End** 语句重置所有模块中所有模块级变量和所有静态局部变量。要保留这些变量的值,请改用 [**Stop**](/official/Reference/Core/Stop) 语句——然后可以在保留这些变量值的情况下恢复执行。 ::: warning **End** 语句突然停止代码执行,不调用Unload、QueryUnload或Terminate事件,也不调用任何其他Visual Basic代码。窗体和类模块的Unload、QueryUnload和Terminate事件中的代码不会被执行。从类模块创建的对象被销毁,使用 **Open** 语句打开的文件被关闭,程序使用的内存被释放。其他程序持有的对象引用变为无效。 ::: **End** 语句提供了一种强制程序停止的方式。对于Visual Basic程序的正常终止,应卸载所有窗体。当没有其他程序持有对公共类模块创建的对象的引用且没有代码在执行时,程序关闭。 ### 示例 本示例使用 **End** 语句在用户输入无效密码时结束代码执行。 ```vb Sub Form_Load Dim Password, Pword PassWord = "Swordfish" Pword = InputBox("Type in your password") If Pword <> PassWord Then MsgBox "Sorry, incorrect password" End End If End Sub ``` --- --- url: /en/official/Features/Advanced/API-Declarations.md --- # Enhancements to API and Method Declarations twinBASIC provides several enhancements to API and method declarations to make working with external libraries easier. ## DeclareWide The `DeclareWide` keyword, in place of `Declare`, disables ANSI<->Unicode conversion for API calls. This applies both directly to arguments, and to String arguments inside a UDT. For example, the following are equivalent in functionality: ```vb Public Declare PtrSafe Sub FooW Lib "some.dll" (ByVal bar As LongPtr) Public DeclareWide PtrSafe Sub Foo Lib "some.dll" Alias "FooW" (ByVal bar As String) ``` Both represent a fully Unicode operation, but the allows direct use of the `String` datatype without requiring the use of `StrPtr` to prevent conversion. ::: warning This does **not** change the underlying data types-- the `String` type is a `BSTR`, not an `LPWSTR`, so in the event an API returns a pre-allocated `LPWSTR`, rather than filling a buffer you have created, it will not provide a valid `String` type. This would be the case where an API parameter is given as `[out] LPWSTR *arg`. ::: ## CDecl Support The cdecl calling convention is supported both for API declares and methods in your code. This includes DLL exports in standard DLLs. ### Examples ```vb Private DeclareWide PtrSafe Function _wtoi64 CDecl Lib "msvcrt" (ByVal psz As String) As LongLong` ``` ```vb [ DllExport ] Public Function MyExportedFunction CDecl(foo As Long, Bar As Long) As Long ``` ### CDecl Callbacks Support for callbacks using `CDecl` is also available. You would pass a delegate that includes `CDecl` as the definition in the prototype. Here is an example code that performs a quicksort using the [`qsort` function](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-wsprintfw): ```vb Private Delegate Function LongComparator CDecl ( _ ByRef a As Long, _ ByRef b As Long _ ) As Long Private Declare PtrSafe Sub qsort CDecl _ Lib "msvcrt" ( _ ByRef pFirst As Any, _ ByVal lNumber As Long, _ ByVal lSize As Long, _ ByVal pfnComparator As LongComparator _ ) Public Sub CallMe() Dim z() As Long Dim i As Long Dim s As String ReDim z(10) As Long For i = 0 To UBound(z) z(i) = Int(Rnd * 1000) Next i qsort z(0), UBound(z) + 1, LenB(z(0)), AddressOf Comparator For i = 0 To UBound(z) s = s & CStr(z(i)) & vbNewLine Next i MsgBox s End Sub Private Function Comparator CDecl( _ ByRef a As Long, _ ByRef b As Long _ ) As Long Comparator = a - b End Function ``` ## Support for Passing User-Defined Types ByVal Simple UDTs can now be passed ByVal in APIs, interfaces, and any other method. In VBx this previously required workarounds like passing each argument separately. ```vb Public Declare PtrSafe Function LBItemFromPt Lib "comctl32" (ByVal hLB As LongPtr, ByVal PXY As POINT, ByVal bAutoScroll As BOOL) As Long Interface IDropTarget Extends stdole.IUnknown Sub DragEnter(ByVal pDataObject As IDataObject, ByVal grfKeyState As KeyStateMouse, ByVal pt As POINT, pdwEffect As DROPEFFECTS) ``` and so on. For this feature, a "simple" UDT is one that does not have members that are reference counted or are otherwise managed in the background, so may not contain interface, String, or Variant types. They may contain other UDTs. ## Variadic Arguments Support With `cdecl` calling convention fully supported, twinBASIC can also handle variadic functions. In C/C++, those functions contain an ellipsis `...` as part of their arguments. This is represented in tB As `{ByRef | ByVal} ParamArray ... As Any()`. Note that `ByRef` or `ByVal` must be explicitly marked; implicit `ByRef` is not allowed. ### Example Using wsprintfW Using the [given C/C++ prototype](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-wsprintfw): ```c int WINAPIV wsprintfW( /* [out] */ LPWSTR unnamedParam1, /* [in] */ LPCWSTR unnamedParam2, /* ... */ ); ``` The twinBASIC declaration and function using it can be written as shown: ```vb Private DeclareWide PtrSafe Function wsprintfW CDecl _ Lib "user32" ( _ ByVal buf As String, _ ByVal format As String, _ ByVal ParamArray args As Any() _ ) As Long Private Sub Test() Dim buf As String = Space(1024) wsprintfW(buf, "%d %d %d", 1, 2, 3) MsgBox buf End Sub ``` ### va\_list Arguments For functions which contain the `va_list` type as part of their arguments the ParamArray declaration must be `ByRef`. ## PreserveSig The `[PreserveSig]` attribute was described earlier for COM methods, but it can also be used on API declares. For APIs, the default is `True`. So therefore, you can specify `False` to rewrite the last parameter as a return. ### Example ```vb Public Declare PtrSafe Function SHGetDesktopFolder Lib "shell32" (ppshf As IShellFolder) As Long ``` can be rewritten as: ```vb [PreserveSig(False)] Public Declare PtrSafe Function SHGetDesktopFolder Lib "shell32" () As IShellFolder` ``` --- --- url: /en/official/Features/Language/Pointers.md --- # Enhanced Pointer Functionality twinBASIC provides several enhancements for working with pointers. ## ByVal Nothing While not strictly new syntax, twinBASIC also adds support for `ByVal Nothing`, to override a `ByRef <interface>` argument and pass a null pointer there. ## ByVal vbNullPtr Allows passing null pointers to UDT members of APIs/interfaces. The equivalent behavior in VBx is to declare them `As Any` and then pass `ByVal 0` at call sites. ### Example ```vb Type Foo bar As Long End Type Public Declare PtrSafe Function MyFunc Lib "MyDLL" (pFoo As Foo) As Long Private Sub CallMyFunc() Dim ret As Long = MyFunc(ByVal vbNullPtr) End Sub ``` ## Substitute Pointers for UDTs More generally, in both APIs and local methods, any argument taking a user-defined type can instead be passed a `ByVal LongPtr`, with the new special constant `vbNullPtr` used for a null pointer: ```vb Public Declare PtrSafe Function CreateFileW Lib "kernel32" (ByVal lpFileName As LongPtr, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, lpSecurityAttributes As SECURITY_ATTRIBUTES, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As LongPtr) As LongPtr hFile = CreateFileW(StrPtr("name"), 0, 0, ByVal vbNullPtr, '...) '---or--- Dim pSec As SECURITY_ATTRIBUTES Dim lPtr As LongPtr = VarPtr(pSec) hFile = CreateFileW(StrPtr("name"), 0, 0, ByVal lPtr, '...) ``` ## CType(Of `<type>`) The `CType(Of <type>)` operator specifies an explicit intent to cast one type to another. This can be used for casting `LongPtr` (or `Long` on 32bit/`LongLong` on 64bit) to a custom user-defined type, with or without making a copy of it, depending on the usage. This allows not just for casting directly without a `CopyMemory` call, but also, setting the members of a UDT represented only by a pointer, without copying memory back and forth. ### Example Consider the following UDTs: ```vb Private Type foo a As Long b As Long pfizz As LongPtr 'A pointer to a variable of type fizz End Type Private Type bar pfoo As LongPtr 'A pointer to a variable of type foo End Type Private Type fizz c As Long End Type ``` The following code examples work to manipulate the pointers: ```vb Sub call1() Dim f As foo test1 VarPtr(f) Debug.Print f.a, f.b End Sub Sub test1(ByVal ptr As LongPtr) With CType(Of foo)(ptr) .a = 1 .b = 2 End With End Sub ``` This will print `1 2`. ```vb Sub call2() Dim f As foo, b As bar b.pfoo = VarPtr(f) test2 b Debug.Print f.a, f.b End Sub Sub test2(b As bar) With CType(Of foo)(b.pfoo) .a = 3 .b = 4 End With End Sub ``` This will print `3 4`. ```vb Sub call3() Dim f As foo, b As bar, z As fizz f.pfizz = VarPtr(z) b.pfoo = VarPtr(f) test3 b Debug.Print z.c End Sub Sub test3(b As bar) CType(Of fizz)(CType(Of foo)(b.pfoo).pfizz).c = 4 End Sub ``` This will print `4`. Free standing use and nesting is also allowed; the above will print `4`. While the examples here are local code only, this is particularly useful for APIs, where you're forced to work with pointers extensively. ## Len/LenB(Of `<type>`) Support The classic `Len` and `LenB` functions can now be used to directly get the length/size of a type, both intrinsic and user-defined, without needing have declared a variable of that type. For instance, to know the pointer size, you can use `LenB(Of LongPtr)`. ## Improvements to AddressOf `AddressOf` can be now be used on class/form/usercontrol members, including from outside the class by specifying the instance. Also, no need for `FARPROC`-type functions, you can use it like `Ptr = AddressOf Func`. So if you have class `CFoo` with member function `bar`, the following is valid: ```vb Dim foo1 As New CFoo Dim lpfn As LongPtr = AddressOf foo1.bar ``` --- --- url: /en/official/Reference/Core/Enum.md --- # Enum Declares a type for an enumeration. Syntax: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Enum** *name*\ >     *membername* \[**=** *constantexpression* ]\ >     *membername* \[**=** *constantexpression* ] . . .\ > **End Enum** *attributes* : *optional* One or more of:\ [EnumId](/en/official/Reference/Attributes#enumid), [Flags](/en/official/Reference/Attributes#flags), [PopulateFrom](/en/official/Reference/Attributes#populatefrom) **Public** : *optional* Specifies that the **Enum** type is visible throughout the project. **Enum** types are **Public** by default. **Private** : *optional* Specifies that the **Enum** type is visible only within the module in which it appears. *name* : The name of the **Enum** type. The *name* must be a valid Visual Basic identifier and is specified as the type when declaring variables or parameters of the **Enum** type. *membername* : A valid Visual Basic identifier specifying the name by which a constituent element of the **Enum** type will be known. *constantexpression* : *optional* Value of the element (evaluates to a **Long**). If no *constantexpression* is specified, the value assigned is either zero (if it is the first *membername* ), or 1 greater than the value of the immediately preceding *membername*. Enumeration variables are variables declared with an **Enum** type. Both variables and parameters can be declared with an **Enum** type. The elements of the **Enum** type are initialized to constant values within the **Enum** statement. The assigned values can't be modified at run time and can include both positive and negative numbers. For example: ```vb Enum SecurityLevel IllegalEntry = -1 SecurityLevel1 = 0 SecurityLevel2 = 1 End Enum ``` An **Enum** statement can appear only at the module level. After the **Enum** type is defined, it can be used to declare variables, parameters, or procedures returning its type. An **Enum** type name cannot be qualified with a module name. **Public Enum** types in a class module are not members of the class; however, they are written to the type library. **Enum** types defined in standard modules aren't written to type libraries. **Public Enum** types of the same name can't be defined in both standard modules and class modules because they share the same name space. When two **Enum** types in different type libraries have the same name, but different elements, a reference to a variable of the type depends on which type library has higher priority in the **References**. An **Enum** type cannot be used as the target in a **With** block. ### Example The following example shows the **Enum** statement used to define a collection of named constants. In this case, the constants are colors that might be used to design data entry forms for a database. ```vb Public Enum InterfaceColors icMistyRose = &HE1E4FF& icSlateGray = &H908070& icDodgerBlue = &HFF901E& icDeepSkyBlue = &HFFBF00& icSpringGreen = &H7FFF00& icForestGreen = &H228B22& icGoldenrod = &H20A5DA& icFirebrick = &H2222B2& End Enum ``` --- --- url: /zh/official/Reference/Core/Enum.md --- # Enum 声明枚举类型。 语法: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Enum** *name*\ >     *membername* \[**=** *constantexpression* ]\ >     *membername* \[**=** *constantexpression* ] . . .\ > **End Enum** *attributes* : *可选* 以下一个或多个:\ [EnumId](/official/Reference/Attributes#enumid)、[Flags](/official/Reference/Attributes#flags)、[PopulateFrom](/official/Reference/Attributes#populatefrom) **Public** : *可选* 指定 **Enum** 类型在整个项目中可见。**Enum** 类型默认为 **Public**。 **Private** : *可选* 指定 **Enum** 类型仅在其出现的模块内可见。 *name* : **Enum** 类型的名称。*name* 必须是有效的Visual Basic标识符,在声明 **Enum** 类型的变量或参数时作为类型指定。 *membername* : 有效的Visual Basic标识符,指定 **Enum** 类型组成元素的名称。 *constantexpression* : *可选* 元素的值(求值为 **Long**)。如果未指定 *constantexpression*,则赋值为零(如果是第一个 *membername*),或比紧接前一个 *membername* 的值大1。 枚举变量是用 **Enum** 类型声明的变量。变量和参数都可以用 **Enum** 类型声明。**Enum** 类型的元素在 **Enum** 语句中初始化为常量值。赋值不能在运行时修改,可以包含正数和负数。例如: ```vb Enum SecurityLevel IllegalEntry = -1 SecurityLevel1 = 0 SecurityLevel2 = 1 End Enum ``` **Enum** 语句只能出现在模块级别。定义 **Enum** 类型后,可用于声明变量、参数或返回其类型的过程。**Enum** 类型名不能用模块名限定。 类模块中的 **Public Enum** 类型不是类的成员;但是,它们会写入类型库。标准模块中定义的 **Enum** 类型不会写入类型库。同名的 **Public Enum** 类型不能同时在标准模块和类模块中定义,因为它们共享同一命名空间。当不同类型库中的两个 **Enum** 类型同名但元素不同时,对该类型变量的引用取决于哪个类型库在 **引用** 中具有更高优先级。 **Enum** 类型不能用作 **With** 块的目标。 ### 示例 以下示例展示使用 **Enum** 语句定义命名常量集合。在此例中,常量是可能用于设计数据库数据输入窗体的颜色。 ```vb Public Enum InterfaceColors icMistyRose = &HE1E4FF& icSlateGray = &H908070& icDodgerBlue = &HFF901E& icDeepSkyBlue = &HFFBF00& icSpringGreen = &H7FFF00& icForestGreen = &H228B22& icGoldenrod = &H20A5DA& icFirebrick = &H2222B2& End Enum ``` --- --- url: /en/official/Reference/CEF/Enumerations.md --- # Enumerations The two user-facing enumerations the **CEF** package exposes. The package's larger set of internal `cef_*_t` enums (mirroring the CEF C API) lives in `Private Module` wrappers and is not part of the public API. | Enumeration | Used by | |-------------|---------| | [CefLogSeverity](/en/official/Reference/CEF/Enumerations/CefLogSeverity) | [**EnvironmentOptions.LogSeverity**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#logseverity) | | [cefPrintOrientation](/en/official/Reference/CEF/Enumerations/cefPrintOrientation) | `Orientation` on [**PrintToPdf**](/en/official/Reference/CEF/CefBrowser/#printtopdf) | --- --- url: /en/official/Reference/CustomControls/Enumerations.md --- # Enumerations The enumerations used by the **CustomControls** package's properties and style objects. All live in `Module Constants` inside the **CustomControls DESIGNER** library, with the exception of the [**SliderDirection**](/en/official/Reference/CustomControls/WaynesSlider/#sliderdirection) and [**SliderDisplayValueFormat**](/en/official/Reference/CustomControls/WaynesSlider/#sliderdisplayvalueformat) enums nested inside the **WaynesSlider** control. | Enumeration | Used by | |-------------|---------| | [BorderStyle](/en/official/Reference/CustomControls/Enumerations/BorderStyle) | [**WindowsFormOptions.BorderStyle**](/en/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#borderstyle) | | [ColorRGBA](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) | [**FillColorPoint.Color**](/en/official/Reference/CustomControls/Styles/Fill#color); `Long`-compatible type alias for ABGR colours | | [CornerShape](/en/official/Reference/CustomControls/Enumerations/CornerShape) | [**Corner.Shape**](/en/official/Reference/CustomControls/Styles/Corners#shape) | | [Customtate](/en/official/Reference/CustomControls/Enumerations/Customtate) | reserved; duplicate of [**WindowState**](/en/official/Reference/CustomControls/Enumerations/WindowState) | | [DockMode](/en/official/Reference/CustomControls/Enumerations/DockMode) | the inherited **Dock** property of every control | | [FillPattern](/en/official/Reference/CustomControls/Enumerations/FillPattern) | [**Fill.Pattern**](/en/official/Reference/CustomControls/Styles/Fill#pattern) | | [FontWeight](/en/official/Reference/CustomControls/Enumerations/FontWeight) | [**FontStyle.Weight**](/en/official/Reference/CustomControls/Styles/TextRendering#weight) | | [PixelCount](/en/official/Reference/CustomControls/Enumerations/PixelCount) | size, position, padding, stroke widths, radii; `Long`-compatible type alias | | [PointSize](/en/official/Reference/CustomControls/Enumerations/PointSize) | [**FontStyle.Size**](/en/official/Reference/CustomControls/Styles/TextRendering#size); `Long`-compatible type alias | | [StartupPosition](/en/official/Reference/CustomControls/Enumerations/StartupPosition) | [**WindowsFormOptions.StartUpPosition**](/en/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#startupposition) | | [TextAlignment](/en/official/Reference/CustomControls/Enumerations/TextAlignment) | [**TextRendering.Alignment**](/en/official/Reference/CustomControls/Styles/TextRendering#alignment) | | [TextOverflowMode](/en/official/Reference/CustomControls/Enumerations/TextOverflowMode) | [**TextRendering.OverflowMode**](/en/official/Reference/CustomControls/Styles/TextRendering#overflowmode) | | [WindowState](/en/official/Reference/CustomControls/Enumerations/WindowState) | [**WindowsFormOptions.WindowState**](/en/official/Reference/CustomControls/WaynesForm/WindowsFormOptions#windowstate) | --- --- url: /en/official/Reference/Enumerations.md --- # Enumerations An *enumeration* defines a named set of integer constants. Passing an enum member instead of a bare integer makes call sites self-documenting and allows the IDE to offer completion for the valid values. Each built-in package groups its enumerations under a dedicated sub-folder; this page indexes all of them. The sections below list enumerations [by package](#by-package), followed by an [alphabetical index](#alphabetical-index). *** ## By package ### VBA Package Fifteen enumerations covering window styles, comparison modes, message-box options, variable types, date and time constants, file attributes, and more. * [**VbAppWinStyle**](/en/official/Reference/VBA/Constants/VbAppWinStyle) -- window-style values for the *windowstyle* argument of [**Shell**](/en/official/Reference/VBA/Interaction/Shell) * [**VbArchitecture**](/en/official/Reference/VBA/Constants/VbArchitecture) -- processor-architecture values returned by [**ProcessorArchitecture**](/en/official/Reference/VBA/Compilation/ProcessorArchitecture) * [**VbCalendar**](/en/official/Reference/VBA/Constants/VbCalendar) -- calendar-type values for the [**Calendar**](/en/official/Reference/Core/Calendar) property * [**VbCallType**](/en/official/Reference/VBA/Constants/VbCallType) -- procedure-call type flags for **CallByName** * [**VbCompareMethod**](/en/official/Reference/VBA/Constants/VbCompareMethod) -- text-comparison modes for [**InStr**](/en/official/Reference/VBA/Strings/InStr), [**Replace**](/en/official/Reference/VBA/Strings/Replace), [**Split**](/en/official/Reference/VBA/Strings/Split), and similar * [**VbDateTimeFormat**](/en/official/Reference/VBA/Constants/VbDateTimeFormat) -- format codes for [**FormatDateTime**](/en/official/Reference/VBA/Strings/FormatDateTime) * [**VbDayOfWeek**](/en/official/Reference/VBA/Constants/VbDayOfWeek) -- day-of-week constants for [**DateAdd**](/en/official/Reference/VBA/DateTime/DateAdd), [**DateDiff**](/en/official/Reference/VBA/DateTime/DateDiff), [**Weekday**](/en/official/Reference/VBA/DateTime/Weekday), and similar * [**VbFileAttribute**](/en/official/Reference/VBA/Constants/VbFileAttribute) -- attribute flags for [**Dir**](/en/official/Reference/VBA/FileSystem/Dir), [**GetAttr**](/en/official/Reference/VBA/FileSystem/GetAttr), and [**SetAttr**](/en/official/Reference/VBA/FileSystem/SetAttr) * [**VbFirstWeekOfYear**](/en/official/Reference/VBA/Constants/VbFirstWeekOfYear) -- first-week-of-year selectors for [**DateDiff**](/en/official/Reference/VBA/DateTime/DateDiff), [**DatePart**](/en/official/Reference/VBA/DateTime/DatePart), and [**Weekday**](/en/official/Reference/VBA/DateTime/Weekday) * [**VbIMEStatus**](/en/official/Reference/VBA/Constants/VbIMEStatus) -- Input Method Editor mode constants * [**VbMsgBoxResult**](/en/official/Reference/VBA/Constants/VbMsgBoxResult) -- identifies the button clicked in a [**MsgBox**](/en/official/Reference/VBA/Interaction/MsgBox) dialog * [**VbMsgBoxStyle**](/en/official/Reference/VBA/Constants/VbMsgBoxStyle) -- buttons, icons, modality, and other flags for [**MsgBox**](/en/official/Reference/VBA/Interaction/MsgBox) * [**VbStrConv**](/en/official/Reference/VBA/Constants/VbStrConv) -- conversion-type flags for [**StrConv**](/en/official/Reference/VBA/Strings/StrConv) * [**VbTriState**](/en/official/Reference/VBA/Constants/VbTriState) -- three-state values for formatting functions such as [**FormatNumber**](/en/official/Reference/VBA/Strings/FormatNumber) and [**FormatCurrency**](/en/official/Reference/VBA/Strings/FormatCurrency) * [**VbVarType**](/en/official/Reference/VBA/Constants/VbVarType) -- Variant subtype codes returned by [**VarType**](/en/official/Reference/VBA/Information/VarType) ### VBRUN Package Eighty-six enumerations covering every aspect of classic VB6 controls and forms --- alignment, border styles, colours, drag-and-drop, OLE container options, printer settings, window states, and more. * [**AlignConstants**](/en/official/Reference/VBRUN/Constants/AlignConstants) -- **Align** property values for picture boxes, toolbars, and data controls * [**AlignmentConstants**](/en/official/Reference/VBRUN/Constants/AlignmentConstants) -- text alignment for label, text-box, and option-button controls * [**AlignmentConstantsNoCenter**](/en/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter) -- left/right alignment values where centre is not available * [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants) -- drawing style for the **Appearance** property * [**ApplicationStartConstants**](/en/official/Reference/VBRUN/Constants/ApplicationStartConstants) -- standalone vs. Automation-invoked start-up mode * [**AspectTypeConstants**](/en/official/Reference/VBRUN/Constants/AspectTypeConstants) -- OLE rendering aspect identifiers for **DataObjectFormat** * [**AsyncReadConstants**](/en/official/Reference/VBRUN/Constants/AsyncReadConstants) -- flags for the *AsyncReadOptions* argument of **UserControl.AsyncRead** * [**AsyncStatusCodeConstants**](/en/official/Reference/VBRUN/Constants/AsyncStatusCodeConstants) -- status codes reported during **AsyncReadProgress** * [**AsyncTypeConstants**](/en/official/Reference/VBRUN/Constants/AsyncTypeConstants) -- data kind delivered by **UserControl.AsyncRead** * [**BackFillStyleConstants**](/en/official/Reference/VBRUN/Constants/BackFillStyleConstants) -- opaque vs. transparent background fill * [**BorderStyleConstants**](/en/official/Reference/VBRUN/Constants/BorderStyleConstants) -- line style for the **BorderStyle** property of Shape and Line controls * [**ButtonConstants**](/en/official/Reference/VBRUN/Constants/ButtonConstants) -- style for command buttons with optional image-based appearance * [**CheckBoxConstants**](/en/official/Reference/VBRUN/Constants/CheckBoxConstants) -- state values for the check-box **Value** property * [**ClipboardConstants**](/en/official/Reference/VBRUN/Constants/ClipboardConstants) -- clipboard format identifiers for **DataObject** and **Clipboard** * [**ColorConstants**](/en/official/Reference/VBRUN/Constants/ColorConstants) -- common named RGB colours * [**ComboBoxConstants**](/en/official/Reference/VBRUN/Constants/ComboBoxConstants) -- style values for the combo-box **Style** property * [**ControlBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants) -- border style for text boxes, picture boxes, and labels * [**ControlBorderStyleConstantsCustom**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstantsCustom) -- extended border style including custom-drawn borders * [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) -- identifiers for standard intrinsic control types * [**DatabaseTypeConstants**](/en/official/Reference/VBRUN/Constants/DatabaseTypeConstants) -- database engine for the **DefaultType** property of a Data control * [**DataBOFconstants**](/en/official/Reference/VBRUN/Constants/DataBOFconstants) -- action when the user moves past the start of a recordset * [**DataEOFConstants**](/en/official/Reference/VBRUN/Constants/DataEOFConstants) -- action when the user moves past the end of a recordset * [**DataErrorConstants**](/en/official/Reference/VBRUN/Constants/DataErrorConstants) -- response values for the Data control's **Error** event * [**DataValidateConstants**](/en/official/Reference/VBRUN/Constants/DataValidateConstants) -- action codes in the **Validate** event * [**DefaultCursorTypeConstants**](/en/official/Reference/VBRUN/Constants/DefaultCursorTypeConstants) -- cursor-driver for the Data control's connection * [**DockModeConstants**](/en/official/Reference/VBRUN/Constants/DockModeConstants) -- dock-edge values for forms and toolbars * [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants) -- action values for the **Drag** method * [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants) -- automatic vs. manual drag-mode for controls * [**DragOverConstants**](/en/official/Reference/VBRUN/Constants/DragOverConstants) -- state values in the **DragOver** event * [**DrawModeConstants**](/en/official/Reference/VBRUN/Constants/DrawModeConstants) -- GDI raster-operation values for the **DrawMode** property * [**DrawStyleConstants**](/en/official/Reference/VBRUN/Constants/DrawStyleConstants) -- line style for the **DrawStyle** property * [**FillStyleConstants**](/en/official/Reference/VBRUN/Constants/FillStyleConstants) -- fill pattern for the **FillStyle** property * [**FillStyleConstantsEx**](/en/official/Reference/VBRUN/Constants/FillStyleConstantsEx) -- extended fill patterns including gradient fills * [**FormArrangeConstants**](/en/official/Reference/VBRUN/Constants/FormArrangeConstants) -- arrangement modes for the MDI **Arrange** method * [**FormBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/FormBorderStyleConstants) -- border and frame style for the form's **BorderStyle** property * [**FormShowConstants**](/en/official/Reference/VBRUN/Constants/FormShowConstants) -- modality values for the *Modal* argument of **Show** * [**FormWindowStateConstants**](/en/official/Reference/VBRUN/Constants/FormWindowStateConstants) -- window-state values for a form's **WindowState** property * [**HitResultConstants**](/en/official/Reference/VBRUN/Constants/HitResultConstants) -- return values from a **UserControl**'s **HitTest** event * [**KeyCodeConstants**](/en/official/Reference/VBRUN/Constants/KeyCodeConstants) -- virtual-key codes for **KeyDown** and **KeyUp** events * [**LinkModeConstants**](/en/official/Reference/VBRUN/Constants/LinkModeConstants) -- DDE link-mode values for the **LinkMode** property * [**ListBoxConstants**](/en/official/Reference/VBRUN/Constants/ListBoxConstants) -- style values for the list-box **Style** property * [**LoadPictureColorConstants**](/en/official/Reference/VBRUN/Constants/LoadPictureColorConstants) -- colour depth for **LoadPicture** * [**LoadPictureSizeConstants**](/en/official/Reference/VBRUN/Constants/LoadPictureSizeConstants) -- size selector for **LoadPicture** * [**LoadResConstants**](/en/official/Reference/VBRUN/Constants/LoadResConstants) -- resource-type values for **LoadResPicture** * [**LogEventTypeConstants**](/en/official/Reference/VBRUN/Constants/LogEventTypeConstants) -- severity values for **LogEvent** * [**LogModeConstants**](/en/official/Reference/VBRUN/Constants/LogModeConstants) -- destination and behaviour flags for **App.StartLogging** * [**MenuAccelConstants**](/en/official/Reference/VBRUN/Constants/MenuAccelConstants) -- keyboard-accelerator codes for menu-item shortcuts * [**MenuControlConstants**](/en/official/Reference/VBRUN/Constants/MenuControlConstants) -- alignment and trigger-button flags for **PopupMenu** * [**MouseButtonConstants**](/en/official/Reference/VBRUN/Constants/MouseButtonConstants) -- bit flags for the *Button* argument of mouse events * [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants) -- cursor-shape values for the **MousePointer** property * [**MultiSelectConstants**](/en/official/Reference/VBRUN/Constants/MultiSelectConstants) -- multi-selection mode for the list-box **MultiSelect** property * [**NegotiatePositionConstants**](/en/official/Reference/VBRUN/Constants/NegotiatePositionConstants) -- menu placement during OLE in-place activation * [**OldLinkModeConstants**](/en/official/Reference/VBRUN/Constants/OldLinkModeConstants) -- legacy DDE link-mode values retained for compatibility * [**OLEContainerActivateConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerActivateConstants) -- activation trigger for the **AutoActivate** property * [**OLEContainerConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerConstants) -- combined enumeration of all OLE container option values * [**OLEContainerDisplayTypeConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants) -- display style for the OLE container **DisplayType** property * [**OLEContainerSizeModeConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants) -- sizing rules for the OLE container **SizeMode** property * [**OLEContainerTypesAllowedConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants) -- object-type filter for **OLETypeAllowed** * [**OLEContainerUpdateOptionsConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants) -- update mode for a linked OLE object * [**OLEDragConstants**](/en/official/Reference/VBRUN/Constants/OLEDragConstants) -- OLE drag-mode values for **OLEDragMode** * [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants) -- OLE drop-mode values for **OLEDropMode** * [**OLEDropEffectConstants**](/en/official/Reference/VBRUN/Constants/OLEDropEffectConstants) -- bit flags for the *Effect* argument of OLE drag-and-drop events * [**PaletteModeConstants**](/en/official/Reference/VBRUN/Constants/PaletteModeConstants) -- palette-source values for forms and UserControls * [**ParentControlsType**](/en/official/Reference/VBRUN/Constants/ParentControlsType) -- wrapping mode for the **ParentControls** collection * [**PictureTypeConstants**](/en/official/Reference/VBRUN/Constants/PictureTypeConstants) -- subtype values for **stdole.IPictureDisp** * [**PrinterObjectConstants**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants) -- combined enumeration of all **Printer** object option values * [**PrinterObjectConstants\_ColorMode**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_ColorMode) -- colour mode for **Printer.ColorMode** * [**PrinterObjectConstants\_Duplex**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_Duplex) -- duplex mode for **Printer.Duplex** * [**PrinterObjectConstants\_Orientation**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_Orientation) -- paper orientation for **Printer.Orientation** * [**PrinterObjectConstants\_PaperBin**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperBin) -- paper source for **Printer.PaperBin** * [**PrinterObjectConstants\_PaperSize**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperSize) -- paper size for **Printer.PaperSize** * [**PrinterObjectConstants\_PrintQuality**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_PrintQuality) -- print quality for **Printer.PrintQuality** * [**QueryUnloadConstants**](/en/official/Reference/VBRUN/Constants/QueryUnloadConstants) -- reason codes for the form's **QueryUnload** event * [**RasterOpConstants**](/en/official/Reference/VBRUN/Constants/RasterOpConstants) -- GDI raster-operation codes for **PaintPicture** * [**RecordsetTypeConstants**](/en/official/Reference/VBRUN/Constants/RecordsetTypeConstants) -- recordset type for a Data control * [**ScaleModeConstants**](/en/official/Reference/VBRUN/Constants/ScaleModeConstants) -- measurement units for the **ScaleMode** property * [**ScrollBarConstants**](/en/official/Reference/VBRUN/Constants/ScrollBarConstants) -- which scrollbars appear on text-box and similar controls * [**ShapeConstants**](/en/official/Reference/VBRUN/Constants/ShapeConstants) -- geometric shape values for the Shape control's **Shape** property * [**ShiftConstants**](/en/official/Reference/VBRUN/Constants/ShiftConstants) -- modifier-key bit flags for mouse and key events * [**ShortcutConstants**](/en/official/Reference/VBRUN/Constants/ShortcutConstants) -- shortcut-key identifiers for menu items * [**StartUpPositionConstants**](/en/official/Reference/VBRUN/Constants/StartUpPositionConstants) -- initial position for a form's **StartUpPosition** property * [**StorageTypeContants**](/en/official/Reference/VBRUN/Constants/StorageTypeContants) -- OLE data-storage medium identifiers for **DataObjectFormat** * [**SystemColorConstants**](/en/official/Reference/VBRUN/Constants/SystemColorConstants) -- system-UI colour references (pass through **TranslateColor** for plain RGB) * [**VariantTypeConstants**](/en/official/Reference/VBRUN/Constants/VariantTypeConstants) -- legacy DAO field-type tags retained for compatibility * [**VerticalAlignmentConstants**](/en/official/Reference/VBRUN/Constants/VerticalAlignmentConstants) -- vertical text alignment for cell-style controls * [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants) -- position selectors for the **ZOrder** method ### WebView2 Package Ten enumerations for navigation errors, permissions, download placement, script dialogs, print orientation, and resource-request filtering. * [**wv2DefaultDownloadCornerAlign**](/en/official/Reference/WebView2/Enumerations/wv2DefaultDownloadCornerAlign) -- anchors the built-in download-progress dialog to a corner of the control * [**wv2ErrorStatus**](/en/official/Reference/WebView2/Enumerations/wv2ErrorStatus) -- reason a navigation failed (passed in the **NavigationComplete** event) * [**wv2HostResourceAccessKind**](/en/official/Reference/WebView2/Enumerations/wv2HostResourceAccessKind) -- cross-origin access policy for a virtual hostname mapping * [**wv2KeyEventKind**](/en/official/Reference/WebView2/Enumerations/wv2KeyEventKind) -- keyboard message kind in the **AcceleratorKeyPressed** event * [**wv2PermissionKind**](/en/official/Reference/WebView2/Enumerations/wv2PermissionKind) -- which device or browser capability a page is requesting * [**wv2PermissionState**](/en/official/Reference/WebView2/Enumerations/wv2PermissionState) -- the host's decision on a permission request * [**wv2PrintOrientation**](/en/official/Reference/WebView2/Enumerations/wv2PrintOrientation) -- page orientation for **PrintToPdf** * [**wv2ProcessFailedKind**](/en/official/Reference/WebView2/Enumerations/wv2ProcessFailedKind) -- identifies which WebView2 process failed * [**wv2ScriptDialogKind**](/en/official/Reference/WebView2/Enumerations/wv2ScriptDialogKind) -- which JavaScript dialog primitive the page is trying to open * [**wv2WebResourceContext**](/en/official/Reference/WebView2/Enumerations/wv2WebResourceContext) -- request kind matched by a web-resource filter ### CustomControls Package Thirteen enumerations governing the appearance and behaviour of the `Waynes...` custom controls. * [**BorderStyle**](/en/official/Reference/CustomControls/Enumerations/BorderStyle) -- Win32 frame style for a **WaynesForm** window * [**ColorRGBA**](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) -- 32-bit ABGR colour value type alias * [**CornerShape**](/en/official/Reference/CustomControls/Enumerations/CornerShape) -- shape of a single corner of a control (square, rounded, cut) * [**Customtate**](/en/official/Reference/CustomControls/Enumerations/Customtate) -- control state flags for custom-state painting * [**DockMode**](/en/official/Reference/CustomControls/Enumerations/DockMode) -- how a control is positioned relative to its container * [**FillPattern**](/en/official/Reference/CustomControls/Enumerations/FillPattern) -- how colour stops in a **Fill** are applied across the painted area * [**FontWeight**](/en/official/Reference/CustomControls/Enumerations/FontWeight) -- font weight on the standard 100--900 OpenType scale * [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount) -- pixel-measurement type alias used throughout the package * [**PointSize**](/en/official/Reference/CustomControls/Enumerations/PointSize) -- typographic-point font-size type alias * [**StartupPosition**](/en/official/Reference/CustomControls/Enumerations/StartupPosition) -- initial position of a **WaynesForm** window when first shown * [**TextAlignment**](/en/official/Reference/CustomControls/Enumerations/TextAlignment) -- horizontal and vertical text alignment within a control * [**TextOverflowMode**](/en/official/Reference/CustomControls/Enumerations/TextOverflowMode) -- how text that does not fit is truncated * [**WindowState**](/en/official/Reference/CustomControls/Enumerations/WindowState) -- minimized, restored, or maximized state of a **WaynesForm** ### CEF Package Two enumerations for log verbosity and print orientation. * [**CefLogSeverity**](/en/official/Reference/CEF/Enumerations/CefLogSeverity) -- minimum severity at which the CEF runtime records messages to its debug log * [**cefPrintOrientation**](/en/official/Reference/CEF/Enumerations/cefPrintOrientation) -- page orientation for **PrintToPdf** ### WinServicesLib Package Four enumerations covering service type, start mode, control codes, and runtime status. * [**ServiceControlCodeConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants) -- control codes the SCM can deliver to a running service * [**ServiceStartConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceStartConstants) -- when and how the SCM starts a service * [**ServiceStatusConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants) -- runtime-state values a service reports to the SCM * [**ServiceTypeConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceTypeConstants) -- Win32 service-type values (own process, shared host, kernel driver) ### WinNativeCommonCtls Package Ten enumerations for the eight native common controls. * [**DTPickerFormatConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants) -- display format for a **DTPicker** control * [**ImlDrawConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) -- render-style flags for **ListImage.Draw** * [**OrientationConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/OrientationConstants) -- horizontal / vertical orientation for **Slider** and **UpDown** * [**TreeBorderStyleConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeBorderStyleConstants) -- border style shared by **TreeView** and **ListView** * [**TreeLabelEditConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeLabelEditConstants) -- when inline label editing is triggered on a **TreeView** * [**TreeLineStyleConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeLineStyleConstants) -- whether the **TreeView** draws lines from root nodes or only child nodes * [**TreeRelationshipConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeRelationshipConstants) -- where a new node is inserted relative to an existing node * [**TreeSortOrderConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortOrderConstants) -- ascending or descending sort order for **TreeView** and **Node** * [**TreeSortTypeConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortTypeConstants) -- case-sensitive or case-insensitive sort comparison * [**TreeStyleConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeStyleConstants) -- composite visual style of a **TreeView** (buttons, lines, icons) *** ## Alphabetical index **A** * [**AlignConstants**](/en/official/Reference/VBRUN/Constants/AlignConstants) -- **Align** property values (VBRUN) * [**AlignmentConstants**](/en/official/Reference/VBRUN/Constants/AlignmentConstants) -- text alignment for labels and text boxes (VBRUN) * [**AlignmentConstantsNoCenter**](/en/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter) -- left/right text alignment without centre (VBRUN) * [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants) -- drawing style for **Appearance** property (VBRUN) * [**ApplicationStartConstants**](/en/official/Reference/VBRUN/Constants/ApplicationStartConstants) -- standalone vs. Automation start mode (VBRUN) * [**AspectTypeConstants**](/en/official/Reference/VBRUN/Constants/AspectTypeConstants) -- OLE rendering aspect identifiers (VBRUN) * [**AsyncReadConstants**](/en/official/Reference/VBRUN/Constants/AsyncReadConstants) -- **UserControl.AsyncRead** option flags (VBRUN) * [**AsyncStatusCodeConstants**](/en/official/Reference/VBRUN/Constants/AsyncStatusCodeConstants) -- **AsyncReadProgress** status codes (VBRUN) * [**AsyncTypeConstants**](/en/official/Reference/VBRUN/Constants/AsyncTypeConstants) -- data kind from **UserControl.AsyncRead** (VBRUN) **B** * [**BackFillStyleConstants**](/en/official/Reference/VBRUN/Constants/BackFillStyleConstants) -- opaque vs. transparent background (VBRUN) * [**BorderStyle**](/en/official/Reference/CustomControls/Enumerations/BorderStyle) -- Win32 frame style for **WaynesForm** (CustomControls) * [**BorderStyleConstants**](/en/official/Reference/VBRUN/Constants/BorderStyleConstants) -- line style for Shape and Line controls (VBRUN) * [**ButtonConstants**](/en/official/Reference/VBRUN/Constants/ButtonConstants) -- style for graphical command buttons (VBRUN) **C** * [**CefLogSeverity**](/en/official/Reference/CEF/Enumerations/CefLogSeverity) -- CEF debug-log minimum severity (CEF) * [**cefPrintOrientation**](/en/official/Reference/CEF/Enumerations/cefPrintOrientation) -- page orientation for **PrintToPdf** (CEF) * [**CheckBoxConstants**](/en/official/Reference/VBRUN/Constants/CheckBoxConstants) -- check-box **Value** property state (VBRUN) * [**ClipboardConstants**](/en/official/Reference/VBRUN/Constants/ClipboardConstants) -- clipboard format identifiers (VBRUN) * [**ColorConstants**](/en/official/Reference/VBRUN/Constants/ColorConstants) -- named RGB colours (VBRUN) * [**ColorRGBA**](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) -- 32-bit ABGR colour type alias (CustomControls) * [**ComboBoxConstants**](/en/official/Reference/VBRUN/Constants/ComboBoxConstants) -- combo-box **Style** property values (VBRUN) * [**ControlBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants) -- border style for intrinsic controls (VBRUN) * [**ControlBorderStyleConstantsCustom**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstantsCustom) -- extended border style including custom-drawn (VBRUN) * [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) -- standard intrinsic control type identifiers (VBRUN) * [**CornerShape**](/en/official/Reference/CustomControls/Enumerations/CornerShape) -- corner shape (square, rounded, cut) (CustomControls) * [**Customtate**](/en/official/Reference/CustomControls/Enumerations/Customtate) -- control state flags for custom painting (CustomControls) **D** * [**DatabaseTypeConstants**](/en/official/Reference/VBRUN/Constants/DatabaseTypeConstants) -- Data control database engine (VBRUN) * [**DataBOFconstants**](/en/official/Reference/VBRUN/Constants/DataBOFconstants) -- action at beginning of recordset (VBRUN) * [**DataEOFConstants**](/en/official/Reference/VBRUN/Constants/DataEOFConstants) -- action at end of recordset (VBRUN) * [**DataErrorConstants**](/en/official/Reference/VBRUN/Constants/DataErrorConstants) -- Data control **Error** event response values (VBRUN) * [**DataValidateConstants**](/en/official/Reference/VBRUN/Constants/DataValidateConstants) -- action codes in the **Validate** event (VBRUN) * [**DefaultCursorTypeConstants**](/en/official/Reference/VBRUN/Constants/DefaultCursorTypeConstants) -- cursor driver for a Data control connection (VBRUN) * [**DockMode**](/en/official/Reference/CustomControls/Enumerations/DockMode) -- how a CustomControl is docked (CustomControls) * [**DockModeConstants**](/en/official/Reference/VBRUN/Constants/DockModeConstants) -- dock-edge values for forms and toolbars (VBRUN) * [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants) -- **Drag** method action values (VBRUN) * [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants) -- automatic vs. manual drag mode (VBRUN) * [**DragOverConstants**](/en/official/Reference/VBRUN/Constants/DragOverConstants) -- state values in the **DragOver** event (VBRUN) * [**DrawModeConstants**](/en/official/Reference/VBRUN/Constants/DrawModeConstants) -- GDI raster-operation for **DrawMode** (VBRUN) * [**DrawStyleConstants**](/en/official/Reference/VBRUN/Constants/DrawStyleConstants) -- line style for **DrawStyle** property (VBRUN) * [**DTPickerFormatConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants) -- **DTPicker** display format (WinNativeCommonCtls) **F** * [**FillPattern**](/en/official/Reference/CustomControls/Enumerations/FillPattern) -- how colour stops in a **Fill** are applied (CustomControls) * [**FillStyleConstants**](/en/official/Reference/VBRUN/Constants/FillStyleConstants) -- fill pattern for **FillStyle** property (VBRUN) * [**FillStyleConstantsEx**](/en/official/Reference/VBRUN/Constants/FillStyleConstantsEx) -- extended fill patterns with gradient fills (VBRUN) * [**FontWeight**](/en/official/Reference/CustomControls/Enumerations/FontWeight) -- font weight on the 100--900 scale (CustomControls) * [**FormArrangeConstants**](/en/official/Reference/VBRUN/Constants/FormArrangeConstants) -- MDI child-window arrangement modes (VBRUN) * [**FormBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/FormBorderStyleConstants) -- form border and frame style (VBRUN) * [**FormShowConstants**](/en/official/Reference/VBRUN/Constants/FormShowConstants) -- modality for **Show** (VBRUN) * [**FormWindowStateConstants**](/en/official/Reference/VBRUN/Constants/FormWindowStateConstants) -- form window state (VBRUN) **H** * [**HitResultConstants**](/en/official/Reference/VBRUN/Constants/HitResultConstants) -- **UserControl.HitTest** return values (VBRUN) **I** * [**ImlDrawConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) -- **ListImage.Draw** render-style flags (WinNativeCommonCtls) **K** * [**KeyCodeConstants**](/en/official/Reference/VBRUN/Constants/KeyCodeConstants) -- virtual-key codes for key events (VBRUN) **L** * [**LinkModeConstants**](/en/official/Reference/VBRUN/Constants/LinkModeConstants) -- DDE link-mode values (VBRUN) * [**ListBoxConstants**](/en/official/Reference/VBRUN/Constants/ListBoxConstants) -- list-box **Style** property values (VBRUN) * [**LoadPictureColorConstants**](/en/official/Reference/VBRUN/Constants/LoadPictureColorConstants) -- **LoadPicture** colour depth (VBRUN) * [**LoadPictureSizeConstants**](/en/official/Reference/VBRUN/Constants/LoadPictureSizeConstants) -- **LoadPicture** size selector (VBRUN) * [**LoadResConstants**](/en/official/Reference/VBRUN/Constants/LoadResConstants) -- **LoadResPicture** resource type (VBRUN) * [**LogEventTypeConstants**](/en/official/Reference/VBRUN/Constants/LogEventTypeConstants) -- **LogEvent** severity values (VBRUN) * [**LogModeConstants**](/en/official/Reference/VBRUN/Constants/LogModeConstants) -- **App.StartLogging** destination flags (VBRUN) **M** * [**MenuAccelConstants**](/en/official/Reference/VBRUN/Constants/MenuAccelConstants) -- menu-item keyboard-accelerator codes (VBRUN) * [**MenuControlConstants**](/en/official/Reference/VBRUN/Constants/MenuControlConstants) -- **PopupMenu** alignment and trigger flags (VBRUN) * [**MouseButtonConstants**](/en/official/Reference/VBRUN/Constants/MouseButtonConstants) -- mouse-event *Button* argument bit flags (VBRUN) * [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants) -- **MousePointer** property cursor shape (VBRUN) * [**MultiSelectConstants**](/en/official/Reference/VBRUN/Constants/MultiSelectConstants) -- list-box multi-selection mode (VBRUN) **N** * [**NegotiatePositionConstants**](/en/official/Reference/VBRUN/Constants/NegotiatePositionConstants) -- menu placement during OLE in-place activation (VBRUN) **O** * [**OldLinkModeConstants**](/en/official/Reference/VBRUN/Constants/OldLinkModeConstants) -- legacy DDE link-mode values (VBRUN) * [**OLEContainerActivateConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerActivateConstants) -- OLE container auto-activation trigger (VBRUN) * [**OLEContainerConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerConstants) -- combined OLE container option values (VBRUN) * [**OLEContainerDisplayTypeConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants) -- OLE container display style (VBRUN) * [**OLEContainerSizeModeConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants) -- OLE container sizing rules (VBRUN) * [**OLEContainerTypesAllowedConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants) -- OLE container object-type filter (VBRUN) * [**OLEContainerUpdateOptionsConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants) -- OLE container update mode (VBRUN) * [**OLEDragConstants**](/en/official/Reference/VBRUN/Constants/OLEDragConstants) -- **OLEDragMode** property values (VBRUN) * [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants) -- **OLEDropMode** property values (VBRUN) * [**OLEDropEffectConstants**](/en/official/Reference/VBRUN/Constants/OLEDropEffectConstants) -- OLE drag-and-drop *Effect* bit flags (VBRUN) * [**OrientationConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/OrientationConstants) -- horizontal / vertical for **Slider** and **UpDown** (WinNativeCommonCtls) **P** * [**PaletteModeConstants**](/en/official/Reference/VBRUN/Constants/PaletteModeConstants) -- palette source for forms and UserControls (VBRUN) * [**ParentControlsType**](/en/official/Reference/VBRUN/Constants/ParentControlsType) -- **ParentControls** collection wrapping mode (VBRUN) * [**PictureTypeConstants**](/en/official/Reference/VBRUN/Constants/PictureTypeConstants) -- **IPictureDisp** subtype values (VBRUN) * [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount) -- pixel-measurement type alias (CustomControls) * [**PointSize**](/en/official/Reference/CustomControls/Enumerations/PointSize) -- typographic-point font-size type alias (CustomControls) * [**PrinterObjectConstants**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants) -- combined **Printer** object option values (VBRUN) * [**PrinterObjectConstants\_ColorMode**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_ColorMode) -- **Printer.ColorMode** values (VBRUN) * [**PrinterObjectConstants\_Duplex**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_Duplex) -- **Printer.Duplex** values (VBRUN) * [**PrinterObjectConstants\_Orientation**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_Orientation) -- **Printer.Orientation** values (VBRUN) * [**PrinterObjectConstants\_PaperBin**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperBin) -- **Printer.PaperBin** values (VBRUN) * [**PrinterObjectConstants\_PaperSize**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_PaperSize) -- **Printer.PaperSize** values (VBRUN) * [**PrinterObjectConstants\_PrintQuality**](/en/official/Reference/VBRUN/Constants/PrinterObjectConstants_PrintQuality) -- **Printer.PrintQuality** values (VBRUN) **Q** * [**QueryUnloadConstants**](/en/official/Reference/VBRUN/Constants/QueryUnloadConstants) -- **QueryUnload** event reason codes (VBRUN) **R** * [**RasterOpConstants**](/en/official/Reference/VBRUN/Constants/RasterOpConstants) -- GDI raster-operation codes for **PaintPicture** (VBRUN) * [**RecordsetTypeConstants**](/en/official/Reference/VBRUN/Constants/RecordsetTypeConstants) -- Data control recordset type (VBRUN) **S** * [**ScaleModeConstants**](/en/official/Reference/VBRUN/Constants/ScaleModeConstants) -- measurement units for **ScaleMode** (VBRUN) * [**ScrollBarConstants**](/en/official/Reference/VBRUN/Constants/ScrollBarConstants) -- which scrollbars appear on a control (VBRUN) * [**ServiceControlCodeConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants) -- SCM control codes for a running service (WinServicesLib) * [**ServiceStartConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceStartConstants) -- service start mode (WinServicesLib) * [**ServiceStatusConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants) -- service runtime state values (WinServicesLib) * [**ServiceTypeConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceTypeConstants) -- Win32 service type (WinServicesLib) * [**ShapeConstants**](/en/official/Reference/VBRUN/Constants/ShapeConstants) -- geometric shape for the Shape control (VBRUN) * [**ShiftConstants**](/en/official/Reference/VBRUN/Constants/ShiftConstants) -- modifier-key bit flags for mouse and key events (VBRUN) * [**ShortcutConstants**](/en/official/Reference/VBRUN/Constants/ShortcutConstants) -- menu-item keyboard shortcut identifiers (VBRUN) * [**StartupPosition**](/en/official/Reference/CustomControls/Enumerations/StartupPosition) -- initial position of a **WaynesForm** (CustomControls) * [**StartUpPositionConstants**](/en/official/Reference/VBRUN/Constants/StartUpPositionConstants) -- form **StartUpPosition** property values (VBRUN) * [**StorageTypeContants**](/en/official/Reference/VBRUN/Constants/StorageTypeContants) -- OLE data-storage medium identifiers (VBRUN) * [**SystemColorConstants**](/en/official/Reference/VBRUN/Constants/SystemColorConstants) -- system-UI colour references (VBRUN) **T** * [**TextAlignment**](/en/official/Reference/CustomControls/Enumerations/TextAlignment) -- horizontal and vertical text alignment (CustomControls) * [**TextOverflowMode**](/en/official/Reference/CustomControls/Enumerations/TextOverflowMode) -- text truncation mode (CustomControls) * [**TreeBorderStyleConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeBorderStyleConstants) -- **TreeView** and **ListView** border style (WinNativeCommonCtls) * [**TreeLabelEditConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeLabelEditConstants) -- **TreeView** inline-label-editing trigger (WinNativeCommonCtls) * [**TreeLineStyleConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeLineStyleConstants) -- **TreeView** tree-lines scope (WinNativeCommonCtls) * [**TreeRelationshipConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeRelationshipConstants) -- **Nodes.Add** insertion position (WinNativeCommonCtls) * [**TreeSortOrderConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortOrderConstants) -- **TreeView** / **Node** sort direction (WinNativeCommonCtls) * [**TreeSortTypeConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortTypeConstants) -- **TreeView** / **Node** sort comparison mode (WinNativeCommonCtls) * [**TreeStyleConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeStyleConstants) -- **TreeView** composite visual style (WinNativeCommonCtls) **V** * [**VbAppWinStyle**](/en/official/Reference/VBA/Constants/VbAppWinStyle) -- window-style values for **Shell** (VBA) * [**VbArchitecture**](/en/official/Reference/VBA/Constants/VbArchitecture) -- processor-architecture values (VBA) * [**VbCalendar**](/en/official/Reference/VBA/Constants/VbCalendar) -- calendar type values (VBA) * [**VbCallType**](/en/official/Reference/VBA/Constants/VbCallType) -- **CallByName** call-type flags (VBA) * [**VbCompareMethod**](/en/official/Reference/VBA/Constants/VbCompareMethod) -- text-comparison mode for string functions (VBA) * [**VbDateTimeFormat**](/en/official/Reference/VBA/Constants/VbDateTimeFormat) -- **FormatDateTime** format codes (VBA) * [**VbDayOfWeek**](/en/official/Reference/VBA/Constants/VbDayOfWeek) -- day-of-week constants for date functions (VBA) * [**VbFileAttribute**](/en/official/Reference/VBA/Constants/VbFileAttribute) -- file-attribute flags (VBA) * [**VbFirstWeekOfYear**](/en/official/Reference/VBA/Constants/VbFirstWeekOfYear) -- first-week-of-year selectors for date functions (VBA) * [**VbIMEStatus**](/en/official/Reference/VBA/Constants/VbIMEStatus) -- Input Method Editor mode constants (VBA) * [**VbMsgBoxResult**](/en/official/Reference/VBA/Constants/VbMsgBoxResult) -- **MsgBox** button-clicked identifier (VBA) * [**VbMsgBoxStyle**](/en/official/Reference/VBA/Constants/VbMsgBoxStyle) -- **MsgBox** button, icon, and modality flags (VBA) * [**VbStrConv**](/en/official/Reference/VBA/Constants/VbStrConv) -- **StrConv** conversion-type flags (VBA) * [**VbTriState**](/en/official/Reference/VBA/Constants/VbTriState) -- three-state values for formatting functions (VBA) * [**VbVarType**](/en/official/Reference/VBA/Constants/VbVarType) -- **VarType** Variant subtype codes (VBA) * [**VariantTypeConstants**](/en/official/Reference/VBRUN/Constants/VariantTypeConstants) -- legacy DAO field-type tags (VBRUN) * [**VerticalAlignmentConstants**](/en/official/Reference/VBRUN/Constants/VerticalAlignmentConstants) -- vertical text alignment (VBRUN) **W** * [**WindowState**](/en/official/Reference/CustomControls/Enumerations/WindowState) -- **WaynesForm** window state (CustomControls) * [**wv2DefaultDownloadCornerAlign**](/en/official/Reference/WebView2/Enumerations/wv2DefaultDownloadCornerAlign) -- download-dialog corner alignment (WebView2) * [**wv2ErrorStatus**](/en/official/Reference/WebView2/Enumerations/wv2ErrorStatus) -- navigation failure reason (WebView2) * [**wv2HostResourceAccessKind**](/en/official/Reference/WebView2/Enumerations/wv2HostResourceAccessKind) -- virtual-hostname cross-origin access policy (WebView2) * [**wv2KeyEventKind**](/en/official/Reference/WebView2/Enumerations/wv2KeyEventKind) -- accelerator-key event kind (WebView2) * [**wv2PermissionKind**](/en/official/Reference/WebView2/Enumerations/wv2PermissionKind) -- permission request capability identifier (WebView2) * [**wv2PermissionState**](/en/official/Reference/WebView2/Enumerations/wv2PermissionState) -- permission-request decision (WebView2) * [**wv2PrintOrientation**](/en/official/Reference/WebView2/Enumerations/wv2PrintOrientation) -- **PrintToPdf** page orientation (WebView2) * [**wv2ProcessFailedKind**](/en/official/Reference/WebView2/Enumerations/wv2ProcessFailedKind) -- failed WebView2 process identifier (WebView2) * [**wv2ScriptDialogKind**](/en/official/Reference/WebView2/Enumerations/wv2ScriptDialogKind) -- JavaScript dialog kind (WebView2) * [**wv2WebResourceContext**](/en/official/Reference/WebView2/Enumerations/wv2WebResourceContext) -- web-resource filter request kind (WebView2) **Z** * [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants) -- **ZOrder** method position selectors (VBRUN) *** ### See Also * [Statements](/en/official/Reference/Statements) -- alphabetical index of language statements * [Procedures and Functions](/en/official/Reference/Procedures-and-Functions) -- alphabetical index of callable runtime members * [Operators](/en/official/Reference/Operators) -- arithmetic, comparison, logical, and bitwise operators * [Packages](/en/official/Reference/Packages) -- all twelve built-in packages --- --- url: /en/official/Reference/WebView2/Enumerations.md --- # Enumerations The `wv2…` enumerations used by the **WebView2** control's properties, methods, and event arguments. Their members have the constant value defined by the underlying `COREWEBVIEW2_*` enumeration in the Edge WebView2 runtime --- the comment beside each `Enum` in the source records the runtime name. | Enumeration | Used by | |-------------|---------| | [wv2DefaultDownloadCornerAlign](/en/official/Reference/WebView2/Enumerations/wv2DefaultDownloadCornerAlign) | corner alignment of the built-in download dialog | | [wv2ErrorStatus](/en/official/Reference/WebView2/Enumerations/wv2ErrorStatus) | `WebErrorStatus` on **NavigationComplete** | | [wv2HostResourceAccessKind](/en/official/Reference/WebView2/Enumerations/wv2HostResourceAccessKind) | **SetVirtualHostNameToFolderMapping** | | [wv2KeyEventKind](/en/official/Reference/WebView2/Enumerations/wv2KeyEventKind) | `KeyState` on **AcceleratorKeyPressed** | | [wv2PermissionKind](/en/official/Reference/WebView2/Enumerations/wv2PermissionKind) | `PermissionKind` on **PermissionRequested** | | [wv2PermissionState](/en/official/Reference/WebView2/Enumerations/wv2PermissionState) | `State` on **PermissionRequested** | | [wv2PrintOrientation](/en/official/Reference/WebView2/Enumerations/wv2PrintOrientation) | `Orientation` on **PrintToPdf** | | [wv2ProcessFailedKind](/en/official/Reference/WebView2/Enumerations/wv2ProcessFailedKind) | `Kind` on **ProcessFailed** | | [wv2ScriptDialogKind](/en/official/Reference/WebView2/Enumerations/wv2ScriptDialogKind) | `ScriptDialogKind` on **ScriptDialogOpening** | | [wv2WebResourceContext](/en/official/Reference/WebView2/Enumerations/wv2WebResourceContext) | `FilterContext` on **AddWebResourceRequestedFilter** / **RemoveWebResourceRequestedFilter** | --- --- url: /en/official/Reference/WinNativeCommonCtls/Enumerations.md --- # WinNativeCommonCtls Enumerations The ten module-level enumerations declared in the package's shared modules and exposed to user code. Each is reachable from any project that references the package. Per-control nested enumerations (those declared *inside* a `<Name>BaseCtl` class --- `ListViewConstants`, `ListArrangeConstants`, `ListLabelEditConstants`, `ListTextBackgroundConstants`, `ListColumnAlignmentConstants`, `PrbOrientation`, `PrbScrolling`, `PrbState`, `TickStyleConstants`, `TextPositionConstants`, `ImageListColorDepth`) are documented on the page of the control that declares them, not under this folder. ## DTPicker * [DTPickerFormatConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants) -- the [**DTPicker.Format**](/en/official/Reference/WinNativeCommonCtls/DTPicker#format) values ## ImageList * [ImlDrawConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) -- the *Style* flags for [**ListImage.Draw**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImage#draw) ## Shared (Slider, UpDown) * [OrientationConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/OrientationConstants) -- the horizontal / vertical enum used by [**Slider.Orientation**](/en/official/Reference/WinNativeCommonCtls/Slider#orientation) and [**UpDown.Orientation**](/en/official/Reference/WinNativeCommonCtls/UpDown#orientation) ## TreeView (and ListView via TreeBorderStyleConstants) * [TreeBorderStyleConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeBorderStyleConstants) -- the [**TreeView.BorderStyle**](/en/official/Reference/WinNativeCommonCtls/TreeView/#borderstyle) and [**ListView.BorderStyle**](/en/official/Reference/WinNativeCommonCtls/ListView/#borderstyle) values * [TreeLabelEditConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeLabelEditConstants) -- the [**TreeView.LabelEdit**](/en/official/Reference/WinNativeCommonCtls/TreeView/#labeledit) values * [TreeLineStyleConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeLineStyleConstants) -- the [**TreeView.LineStyle**](/en/official/Reference/WinNativeCommonCtls/TreeView/#linestyle) values * [TreeRelationshipConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeRelationshipConstants) -- the *Relationship* values for [**Nodes.Add**](/en/official/Reference/WinNativeCommonCtls/TreeView/Nodes#add) * [TreeSortOrderConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortOrderConstants) -- the [**TreeView.SortOrder**](/en/official/Reference/WinNativeCommonCtls/TreeView/#sortorder) and [**Node.SortOrder**](/en/official/Reference/WinNativeCommonCtls/TreeView/Node#sortorder) values * [TreeSortTypeConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortTypeConstants) -- the [**TreeView.SortType**](/en/official/Reference/WinNativeCommonCtls/TreeView/#sorttype) and [**Node.SortType**](/en/official/Reference/WinNativeCommonCtls/TreeView/Node#sorttype) values * [TreeStyleConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeStyleConstants) -- the [**TreeView.Style**](/en/official/Reference/WinNativeCommonCtls/TreeView/#style) values --- --- url: /en/official/Reference/WinServicesLib/Enumerations.md --- # Enumerations The four user-facing enumerations the **WinServicesLib** package exposes. All four come from the public `ServicesConstantsPublic` module in the package source; the larger set of internal `SERVICE_*` constants the source uses to call into `advapi32.dll` lives in a `Private Module` and is not part of the public API. | Enumeration | Used by | |-------------|---------| | [ServiceTypeConstants](/en/official/Reference/WinServicesLib/Enumerations/ServiceTypeConstants) | [**ServiceManager.Type**](/en/official/Reference/WinServicesLib/ServiceManager#type), [**ServiceState.Type**](/en/official/Reference/WinServicesLib/ServiceState#type) | | [ServiceStartConstants](/en/official/Reference/WinServicesLib/Enumerations/ServiceStartConstants) | [**ServiceManager.InstallStartMode**](/en/official/Reference/WinServicesLib/ServiceManager#installstartmode) | | [ServiceControlCodeConstants](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants) | [**Services.ControlService**](/en/official/Reference/WinServicesLib/Services#controlservice), the *dwControl* parameter of [**ITbService.ChangeState**](/en/official/Reference/WinServicesLib/ITbService#changestate) | | [ServiceStatusConstants](/en/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants) | [**ServiceManager.ReportStatus**](/en/official/Reference/WinServicesLib/ServiceManager#reportstatus) | The member-name prefixes are inherited from the underlying Win32 SDK constants --- `tb…` on the *configuration* enums ([**ServiceTypeConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceTypeConstants), [**ServiceStartConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceStartConstants)) and `vb…` on the *runtime* enums ([**ServiceControlCodeConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants), [**ServiceStatusConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants)). The split is not deliberate; treat the prefixes as part of the member names and ignore the asymmetry. --- --- url: /zh/official/Reference/WebView2/Enumerations.md --- # 枚举 **WebView2** 控件的属性、方法和事件参数使用的 `wv2…` 枚举。其成员的常量值由 Edge WebView2 运行时中底层 `COREWEBVIEW2_*` 枚举定义——源代码中每个 `Enum` 旁的注释记录了运行时名称。 | 枚举 | 使用者 | |------|--------| | [wv2DefaultDownloadCornerAlign](/official/Reference/WebView2/Enumerations/wv2DefaultDownloadCornerAlign) | 内置下载对话框的角对齐 | | [wv2ErrorStatus](/official/Reference/WebView2/Enumerations/wv2ErrorStatus) | **NavigationComplete** 上的 `WebErrorStatus` | | [wv2HostResourceAccessKind](/official/Reference/WebView2/Enumerations/wv2HostResourceAccessKind) | **SetVirtualHostNameToFolderMapping** | | [wv2KeyEventKind](/official/Reference/WebView2/Enumerations/wv2KeyEventKind) | **AcceleratorKeyPressed** 上的 `KeyState` | | [wv2PermissionKind](/official/Reference/WebView2/Enumerations/wv2PermissionKind) | **PermissionRequested** 上的 `PermissionKind` | | [wv2PermissionState](/official/Reference/WebView2/Enumerations/wv2PermissionState) | **PermissionRequested** 上的 `State` | | [wv2PrintOrientation](/official/Reference/WebView2/Enumerations/wv2PrintOrientation) | **PrintToPdf** 上的 `Orientation` | | [wv2ProcessFailedKind](/official/Reference/WebView2/Enumerations/wv2ProcessFailedKind) | **ProcessFailed** 上的 `Kind` | | [wv2ScriptDialogKind](/official/Reference/WebView2/Enumerations/wv2ScriptDialogKind) | **ScriptDialogOpening** 上的 `ScriptDialogKind` | | [wv2WebResourceContext](/official/Reference/WebView2/Enumerations/wv2WebResourceContext) | **AddWebResourceRequestedFilter** / **RemoveWebResourceRequestedFilter** 上的 `FilterContext` | --- --- url: /zh/official/Reference/WinNativeCommonCtls/Enumerations.md --- # WinNativeCommonCtls 枚举 包的共享模块中声明并暴露给用户代码的十个模块级枚举。每个枚举都可以从引用该包的任何项目中访问。 每控件嵌套枚举(在 `<Name>BaseCtl` 类*内部*声明的 —— `ListViewConstants`、`ListArrangeConstants`、`ListLabelEditConstants`、`ListTextBackgroundConstants`、`ListColumnAlignmentConstants`、`PrbOrientation`、`PrbScrolling`、`PrbState`、`TickStyleConstants`、`TextPositionConstants`、`ImageListColorDepth`)记录在声明它们的控件页面上,而非此文件夹下。 ## DTPicker * [DTPickerFormatConstants](/official/Reference/WinNativeCommonCtls/Enumerations/DTPickerFormatConstants) —— [**DTPicker.Format**](/official/Reference/WinNativeCommonCtls/DTPicker#format) 的取值 ## ImageList * [ImlDrawConstants](/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) —— [**ListImage.Draw**](/official/Reference/WinNativeCommonCtls/ImageList/ListImage#draw) 的 *Style* 标志 ## 共享(Slider、UpDown) * [OrientationConstants](/official/Reference/WinNativeCommonCtls/Enumerations/OrientationConstants) —— [**Slider.Orientation**](/official/Reference/WinNativeCommonCtls/Slider#orientation) 和 [**UpDown.Orientation**](/official/Reference/WinNativeCommonCtls/UpDown#orientation) 使用的水平/垂直枚举 ## TreeView(及 ListView via TreeBorderStyleConstants) * [TreeBorderStyleConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeBorderStyleConstants) —— [**TreeView.BorderStyle**](/official/Reference/WinNativeCommonCtls/TreeView/#borderstyle) 和 [**ListView.BorderStyle**](/official/Reference/WinNativeCommonCtls/ListView/#borderstyle) 的取值 * [TreeLabelEditConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeLabelEditConstants) —— [**TreeView.LabelEdit**](/official/Reference/WinNativeCommonCtls/TreeView/#labeledit) 的取值 * [TreeLineStyleConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeLineStyleConstants) —— [**TreeView.LineStyle**](/official/Reference/WinNativeCommonCtls/TreeView/#linestyle) 的取值 * [TreeRelationshipConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeRelationshipConstants) —— [**Nodes.Add**](/official/Reference/WinNativeCommonCtls/TreeView/Nodes#add) 的 *Relationship* 取值 * [TreeSortOrderConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortOrderConstants) —— [**TreeView.SortOrder**](/official/Reference/WinNativeCommonCtls/TreeView/#sortorder) 和 [**Node.SortOrder**](/official/Reference/WinNativeCommonCtls/TreeView/Node#sortorder) 的取值 * [TreeSortTypeConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortTypeConstants) —— [**TreeView.SortType**](/official/Reference/WinNativeCommonCtls/TreeView/#sorttype) 和 [**Node.SortType**](/official/Reference/WinNativeCommonCtls/TreeView/Node#sorttype) 的取值 * [TreeStyleConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeStyleConstants) —— [**TreeView.Style**](/official/Reference/WinNativeCommonCtls/TreeView/#style) 的取值 --- --- url: /en/official/Reference/VBA/Interaction/Environ.md --- # Environ, Environ$ Returns the value associated with an operating-system environment variable, looked up either by name or by 1-based position in the environment-string table. Syntax: * **Environ$(** *envstring* **)**, **Environ(** *envstring* **)** * **Environ$(** *number* **)**, **Environ(** *number* **)** *envstring* : *required* String expression containing the name of an environment variable. *number* : *required* Numeric expression giving the 1-based position of an entry in the process environment-string table. *number* may be any numeric expression and is rounded to a whole number before being evaluated. The `$`-suffixed forms return a **String**; the unsuffixed forms return a **Variant** (**String**). When called with *envstring*, **Environ** returns the value assigned to that environment variable --- that is, the text following the equal sign (`=`) in the environment-string table for that variable. If *envstring* can't be found in the table, a zero-length string (`""`) is returned. When called with *number*, **Environ** returns the entire entry at that position, including the variable name, the equal sign, and the value (e.g. `"PATH=C:\Windows;C:\Windows\System32"`). If there is no entry at that position, a zero-length string is returned. ### Example This example iterates over the environment-string table to find the entry number and the value length for `PATH`. ```vb Dim EnvString As String, Indx As Long, PathLen As Long Indx = 1 Do EnvString = Environ(Indx) If Left(EnvString, 5) = "PATH=" Then PathLen = Len(Environ("PATH")) Debug.Print "PATH entry = " & Indx & " and length = " & PathLen Exit Do Else Indx = Indx + 1 End If Loop Until EnvString = "" If PathLen = 0 Then Debug.Print "No PATH environment variable exists." End If ``` --- --- url: /zh/official/Reference/VBA/Interaction/Environ.md --- # Environ, Environ$ 返回与操作系统环境变量关联的值,可按名称或环境字符串表中基于1的位置查找。 语法: * **Environ$(** *envstring* **)**, **Environ(** *envstring* **)** * **Environ$(** *number* **)**, **Environ(** *number* **)** *envstring* : *必需* 字符串表达式,包含环境变量的名称。 *number* : *必需* 数值表达式,给出进程环境字符串表中条目的基于1的位置。*number*可以是任何数值表达式,在求值前四舍五入为整数。 带`$`后缀的形式返回**String**;不带后缀的形式返回**Variant**(**String**)。 使用*envstring*调用时,**Environ**返回分配给该环境变量的值——即该变量在环境字符串表中等号(`=`)后面的文本。如果在表中找不到*envstring*,则返回零长度字符串(`""`)。 使用*number*调用时,**Environ**返回该位置的整个条目,包括变量名、等号和值(例如`"PATH=C:\Windows;C:\Windows\System32"`)。如果该位置没有条目,则返回零长度字符串。 ### 示例 本示例遍历环境字符串表以查找`PATH`的条目编号和值长度。 ```vb Dim EnvString As String, Indx As Long, PathLen As Long Indx = 1 Do EnvString = Environ(Indx) If Left(EnvString, 5) = "PATH=" Then PathLen = Len(Environ("PATH")) Debug.Print "PATH entry = " & Indx & " and length = " & PathLen Exit Do Else Indx = Indx + 1 End If Loop Until EnvString = "" If PathLen = 0 Then Debug.Print "No PATH environment variable exists." End If ``` --- --- url: /en/official/Reference/CEF/CefBrowser/EnvironmentOptions.md --- # CefEnvironmentOptions class Pre-creation configuration for the CEF environment --- runtime folder, user-data folder, and the optional debug-log destination. Available on every [**CefBrowser**](/en/official/Reference/CEF/CefBrowser/) control as its **EnvironmentOptions** property; the control instantiates one automatically before raising the [**Create**](/en/official/Reference/CEF/CefBrowser/#create) event. The fields below take effect only while the CEF runtime is being launched --- that is, *before or during* the control's [**Create**](/en/official/Reference/CEF/CefBrowser/#create) event. Assigning them after that point has no effect on the live environment. ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.UserDataFolder = _ Environ$("APPDATA") & "\MyApp\CEF\" CefBrowser1.EnvironmentOptions.LogFilePath = _ Environ$("APPDATA") & "\MyApp\CEF\debug.log" CefBrowser1.EnvironmentOptions.LogSeverity = CefLogWarning End Sub ``` The type itself is `Private Class` --- instances are reachable only through the control's **EnvironmentOptions** property, and a variable typed as **CefEnvironmentOptions** cannot be declared from outside the package. ## Properties ### BrowserExecutableFolder Path to the folder containing `libcef.dll` and its accompanying runtime files. **String**. Default: empty (the runtime is loaded from `%LocalAppData%\twinBASIC_CEF_Runtime\<version-stamped-folder>` --- see [Installing runtime files](/en/official/Reference/CEF/#installing-runtime-files)). Set this to point at a portable side-by-side deployment, e.g. a CEF folder shipped beside the application executable: ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.BrowserExecutableFolder = _ App.Path & "\cef145_win64" End Sub ``` If `libcef.dll` is not found at the configured (or default) location, the [**Error**](/en/official/Reference/CEF/CefBrowser/#error) event fires with the exact path that was searched. ### LogFilePath Path to a writable file CEF will append its debug log to. **String**. Default: empty (no log file is written, regardless of [**LogSeverity**](#logseverity)). Used together with [**LogSeverity**](#logseverity) --- messages at or above the chosen severity are written to this file. The log is appended across runs; rotate or delete the file as needed. ### LogSeverity The minimum severity at which CEF records messages to the log file named by [**LogFilePath**](#logfilepath). [**CefLogSeverity**](/en/official/Reference/CEF/Enumerations/CefLogSeverity). Default: **CefLogDisable** (logging off). Set to **CefLogWarning** or **CefLogError** when investigating runtime issues, and back to **CefLogDisable** for normal use. ### UserDataFolder Path to the folder CEF uses for the user profile --- cache, cookies, history, local storage, and so on. **String**. Default: empty (the runtime picks a folder under `%LocalAppData%\twinBASIC_CEF\<ProjectName>\`). Set a writable, application-specific path when the default would end up in a read-only location, or when multiple deployments of the same application must keep their profiles separate. The same folder cannot be opened by two CEF processes simultaneously --- if it's already locked, the [**Error**](/en/official/Reference/CEF/CefBrowser/#error) event fires with *"CEF cache path already locked by another process"*. ### See Also * [CefBrowser control class](/en/official/Reference/CEF/CefBrowser/) * [Create event](/en/official/Reference/CEF/CefBrowser/#create) * [Installing runtime files](/en/official/Reference/CEF/#installing-runtime-files) * [Overriding the runtime location](/en/official/Reference/CEF/#overriding-the-runtime-location) * [WebView2EnvironmentOptions](/en/official/Reference/WebView2/WebView2/EnvironmentOptions) -- the WebView2 counterpart --- --- url: /en/official/Reference/WebView2/WebView2/EnvironmentOptions.md --- # WebView2EnvironmentOptions class Holds the host's pre-creation configuration for the underlying WebView2 environment --- folder layout, additional command-line arguments, locale, and a few policy switches. Exposed on every [**WebView2**](/en/official/Reference/WebView2/WebView2/) control as its **EnvironmentOptions** property; the control instantiates one automatically before raising the [**Create**](/en/official/Reference/WebView2/WebView2/#create) event. The fields below take effect only while the WebView2 environment is being constructed --- that is, *before or during* the control's [**Create**](/en/official/Reference/WebView2/WebView2/#create) event. Assigning them after that point has no effect on the live environment. ```vb Private Sub WebView21_Create() WebView21.EnvironmentOptions.UserDataFolder = _ Environ$("APPDATA") & "\MyApp\WebView2\" WebView21.EnvironmentOptions.Language = "en-GB" End Sub ``` The type itself is `Private Class` --- instances are reachable only through the control's **EnvironmentOptions** property, and a variable typed as **WebView2EnvironmentOptions** cannot be declared from outside the package. ## Properties ### AdditionalBrowserArguments Extra command-line switches passed straight through to the Edge browser process --- same syntax as `msedge.exe`. **String**. Default: empty. ### AllowSingleSignOnUsingOSPrimaryAccount When **True**, single sign-on uses the operating system's primary account (typical for Azure AD-joined machines). **Boolean**. Default: **False**. ### BrowserExecutableFolder Path to a fixed-version WebView2 browser distribution. Leave empty (the default) to load the system-wide Evergreen runtime; set this to point at a side-by-side fixed-version deployment. **String**. ### EnableTrackingPrevention Whether Edge's tracking-prevention feature is active in this environment. **Boolean**. Default: **True**. ### ExclusiveUserDataFolderAccess When **True**, the runtime locks the user-data folder so that no other WebView2 instance can use it concurrently. **Boolean**. Default: **False**. ### Language The language and locale Edge should report in `Accept-Language` and use for its UI strings --- BCP-47 form, e.g. `"en-GB"`, `"fr-FR"`. **String**. Default: empty (the runtime picks the system default). ### TargetCompatibleBrowserVersion The minimum Edge browser version this application is built against --- used by the loader to decide whether a runtime can host it. **String**. Default: `"86.0.616.0"` (the minimum version that supports WebView2). ### UserDataFolder Path to the folder Edge uses for the user profile --- cache, cookies, history, local storage, password manager, and so on. Leave empty (the default) to let the runtime pick a folder beside the host executable; set it to keep user data outside the install location, e.g. under `%APPDATA%`. **String**. Setting a writable user-data folder is the usual remedy for the *"Error occurred creating the WebView2 controller"* failure on installs that live under `Program Files`. ### See Also * [WebView2 control class](/en/official/Reference/WebView2/WebView2/) * [Create event](/en/official/Reference/WebView2/WebView2/#create) * [Customizing the UserDataFolder tutorial](/en/official/Tutorials/WebView2/Customize-the-UserDataFolder) --- --- url: /zh/official/Reference/CEF/CefBrowser/EnvironmentOptions.md --- # CefEnvironmentOptions 类 CEF环境的预创建配置——运行时文件夹、用户数据文件夹和可选的调试日志目标。在每个 [**CefBrowser**](/official/Reference/CEF/CefBrowser/) 控件上可作为其 **EnvironmentOptions** 属性使用;控件在触发 [**Create**](/official/Reference/CEF/CefBrowser/#create) 事件之前自动实例化一个。 以下字段仅在CEF运行时启动期间生效——即在控件的 [**Create**](/official/Reference/CEF/CefBrowser/#create) 事件*之前或期间*。在该时间点之后赋值对运行中的环境没有影响。 ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.UserDataFolder = _ Environ$("APPDATA") & "\MyApp\CEF\" CefBrowser1.EnvironmentOptions.LogFilePath = _ Environ$("APPDATA") & "\MyApp\CEF\debug.log" CefBrowser1.EnvironmentOptions.LogSeverity = CefLogWarning End Sub ``` 该类型本身是 `Private Class`——实例只能通过控件的 **EnvironmentOptions** 属性访问,无法从包外部声明类型为 **CefEnvironmentOptions** 的变量。 ## 属性 ### BrowserExecutableFolder 包含 `libcef.dll` 及其伴随运行时文件的文件夹路径。**String**。默认:空(运行时从 `%LocalAppData%\twinBASIC_CEF_Runtime\<version-stamped-folder>` 加载——参见[安装运行时文件](/official/Reference/CEF/#installing-runtime-files))。 设置此项以指向便携式并排部署,例如应用程序可执行文件旁边的CEF文件夹: ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.BrowserExecutableFolder = _ App.Path & "\cef145_win64" End Sub ``` 如果在配置的(或默认的)位置未找到 `libcef.dll`,[**Error**](/official/Reference/CEF/CefBrowser/#error) 事件将触发并附带所搜索的确切路径。 ### LogFilePath CEF将追加其调试日志的可写入文件路径。**String**。默认:空(无论 [**LogSeverity**](#logseverity) 如何设置,都不写入日志文件)。 与 [**LogSeverity**](#logseverity) 配合使用——等于或高于所选严重级别的消息写入此文件。日志在多次运行之间追加;根据需要轮换或删除文件。 ### LogSeverity CEF将消息记录到由 [**LogFilePath**](#logfilepath) 命名的日志文件的最低严重级别。[**CefLogSeverity**](/official/Reference/CEF/Enumerations/CefLogSeverity)。默认:**CefLogDisable**(日志记录关闭)。 在排查运行时问题时设置为 **CefLogWarning** 或 **CefLogError**,正常使用时设置回 **CefLogDisable**。 ### UserDataFolder CEF用于用户配置文件的文件夹路径——缓存、Cookie、历史记录、本地存储等。**String**。默认:空(运行时在 `%LocalAppData%\twinBASIC_CEF\<ProjectName>\` 下选择一个文件夹)。 当默认位置可能位于只读位置,或同一应用程序的多个部署必须保持其配置文件独立时,设置一个可写入的、特定于应用程序的路径。同一文件夹不能同时被两个CEF进程打开——如果已被锁定,[**Error**](/official/Reference/CEF/CefBrowser/#error) 事件将触发,消息为 *"CEF cache path already locked by another process"*。 ### 另见 * [CefBrowser 控件类](/official/Reference/CEF/CefBrowser/) * [Create 事件](/official/Reference/CEF/CefBrowser/#create) * [安装运行时文件](/official/Reference/CEF/#installing-runtime-files) * [覆盖运行时位置](/official/Reference/CEF/#overriding-the-runtime-location) * [WebView2EnvironmentOptions](/official/Reference/WebView2/WebView2/EnvironmentOptions) -- WebView2的对应项 --- --- url: /zh/official/Reference/WebView2/WebView2/EnvironmentOptions.md --- # WebView2EnvironmentOptions 类 保存宿主对底层 WebView2 环境的预创建配置——文件夹布局、额外命令行参数、区域设置和一些策略开关。在每个 [**WebView2**](/official/Reference/WebView2/WebView2/) 控件上作为其 **EnvironmentOptions** 属性暴露;控件在触发 [**Create**](/official/Reference/WebView2/WebView2/#create) 事件之前自动实例化一个。 以下字段仅在 WebView2 环境构造期间生效——即在控件的 [**Create**](/official/Reference/WebView2/WebView2/#create) 事件*之前或期间*。之后赋值对活动环境无影响。 ```vb Private Sub WebView21_Create() WebView21.EnvironmentOptions.UserDataFolder = _ Environ$("APPDATA") & "\MyApp\WebView2\" WebView21.EnvironmentOptions.Language = "en-GB" End Sub ``` 类型本身是 `Private Class`——实例只能通过控件的 **EnvironmentOptions** 属性访问,无法从包外部声明 **WebView2EnvironmentOptions** 类型的变量。 ## 属性 ### AdditionalBrowserArguments 直接传递给 Edge 浏览器进程的额外命令行开关——语法与 `msedge.exe` 相同。**String**。默认:空。 ### AllowSingleSignOnUsingOSPrimaryAccount 当 **True** 时,单点登录使用操作系统的主账户(Azure AD 加入的机器上常见)。**Boolean**。默认:**False**。 ### BrowserExecutableFolder 固定版本 WebView2 浏览器分发的路径。留空(默认)以加载系统范围的 Evergreen 运行时;设置此值以指向并行部署的固定版本。**String**。 ### EnableTrackingPrevention Edge 的跟踪防护功能在此环境中是否激活。**Boolean**。默认:**True**。 ### ExclusiveUserDataFolderAccess 当 **True** 时,运行时锁定用户数据文件夹,使其他 WebView2 实例无法同时使用。**Boolean**。默认:**False**。 ### Language Edge 应在 `Accept-Language` 中报告并用于 UI 字符串的语言和区域设置——BCP-47 格式,例如 `"en-GB"`、`"fr-FR"`。**String**。默认:空(运行时选择系统默认值)。 ### TargetCompatibleBrowserVersion 此应用程序构建所针对的最低 Edge 浏览器版本——加载器用此决定运行时是否能托管它。**String**。默认:`"86.0.616.0"`(支持 WebView2 的最低版本)。 ### UserDataFolder Edge 用于用户配置文件的文件夹路径——缓存、Cookie、历史记录、本地存储、密码管理器等。留空(默认)让运行时在宿主可执行文件旁边选择一个文件夹;设置此值以将用户数据保留在安装位置之外,例如 `%APPDATA%` 下。**String**。 设置可写的用户数据文件夹是解决安装在 `Program Files` 下的程序出现 *"创建 WebView2 控制器时发生错误"* 故障的常用方法。 ### 另见 * [WebView2 控件类](/official/Reference/WebView2/WebView2/) * [Create 事件](/official/Reference/WebView2/WebView2/#create) * [自定义 UserDataFolder 教程](/official/Tutorials/WebView2/Customize-the-UserDataFolder) --- --- url: /en/official/Reference/VBA/FileSystem/EOF.md --- # EOF Returns an **Integer** containing the **Boolean** value **True** when the end of a file opened for **Random** or sequential **Input** has been reached. Syntax: **EOF(** *filenumber* **)** *filenumber* : *required* **Integer** containing any valid file number. ### Remarks Use **EOF** to avoid the error generated by attempting to get input past the end of a file. The **EOF** function returns **False** until the end of the file has been reached. With files opened for **Random** or **Binary** access, **EOF** returns **False** until the last executed **Get** statement is unable to read an entire record. With files opened for **Binary** access, an attempt to read through the file by using the **Input** function until **EOF** returns **True** generates an error. Use the [LOF](/en/official/Reference/VBA/FileSystem/LOF) and **Loc** functions instead of **EOF** when reading binary files with **Input**, or use **Get** when using the **EOF** function. With files opened for **Output**, **EOF** always returns **True**. ### Example This example uses the **EOF** function to detect the end of a file. This example assumes that `MYFILE` is a text file with a few lines of text. ```vb Dim InputData Open "MYFILE" For Input As #1 ' Open file for input. Do While Not EOF(1) ' Check for end of file. Line Input #1, InputData ' Read line of data. Debug.Print InputData ' Print to the Immediate window. Loop Close #1 ' Close file. ``` ### See Also * [LOF](/en/official/Reference/VBA/FileSystem/LOF) function --- --- url: /zh/official/Reference/VBA/FileSystem/EOF.md --- # EOF 返回一个**Integer**,当已到达以**Random**或顺序**Input**模式打开的文件末尾时,包含**Boolean**值**True**。 语法:**EOF(** *filenumber* **)** *filenumber* : *必需* **Integer**,包含任何有效的文件号。 ### 备注 使用**EOF**可避免在文件末尾之后尝试获取输入时产生的错误。 **EOF**函数在到达文件末尾之前返回**False**。对于以**Random**或**Binary**访问模式打开的文件,**EOF**在最后执行的**Get**语句无法读取完整记录之前返回**False**。 对于以**Binary**访问模式打开的文件,尝试使用**Input**函数读取文件直到**EOF**返回**True**会产生错误。使用**Input**读取二进制文件时,请使用[LOF](/official/Reference/VBA/FileSystem/LOF)和**Loc**函数代替**EOF**,或在使用**EOF**函数时使用**Get**。对于以**Output**模式打开的文件,**EOF**始终返回**True**。 ### 示例 本示例使用**EOF**函数检测文件末尾。本示例假设`MYFILE`是一个包含几行文本的文本文件。 ```vb Dim InputData Open "MYFILE" For Input As #1 ' Open file for input. Do While Not EOF(1) ' Check for end of file. Line Input #1, InputData ' Read line of data. Debug.Print InputData ' Print to the Immediate window. Loop Close #1 ' Close file. ``` ### 另请参阅 * [LOF](/official/Reference/VBA/FileSystem/LOF)函数 --- --- url: /en/official/Reference/Core/Eqv.md --- # Eqv operator Used to perform a bitwise equivalence on two expressions --- the logical inverse of [**Xor**](/en/official/Reference/Core/Xor). Syntax: > *result* **=** *expression1* **Eqv** *expression2* *result* : Any numeric variable. *expression1*, *expression2* : Any expressions. If either expression is **Null**, *result* is also **Null**. When neither expression is **Null**, *result* is determined according to the following table: | If *expression1* is | And *expression2* is | The *result* is | |:-----|:-----|:-----| | **True** | **True** | **True** | | **True** | **False** | **False** | | **False** | **True** | **False** | | **False** | **False** | **True** | The **Eqv** operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in *result* according to the following table: | If bit in *expression1* is | And bit in *expression2* is | The *result* is | |:-----:|:-----:|:-----:| | 0 | 0 | 1 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | ::: info **Eqv** always evaluates *both* operands. ::: ### Example This example uses the **Eqv** operator to perform logical equivalence on two expressions. ```vb Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B Eqv B > C ' Returns True. MyCheck = B > A Eqv B > C ' Returns False. MyCheck = A > B Eqv B > D ' Returns Null. MyCheck = A Eqv B ' Returns -3 (bitwise comparison). ``` ### See Also * [**Xor** operator](/en/official/Reference/Core/Xor) * [**Imp** operator](/en/official/Reference/Core/Imp) * [**And** operator](/en/official/Reference/Core/And) * [**Or** operator](/en/official/Reference/Core/Or) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Eqv.md --- # Eqv 运算符 用于对两个表达式执行按位等价运算——[**Xor**](/official/Reference/Core/Xor) 的逻辑逆运算。 语法: > *result* **=** *expression1* **Eqv** *expression2* *result* : 任意数值变量。 *expression1*, *expression2* : 任意表达式。 如果任一表达式为 **Null**,则 *result* 也为 **Null**。当两个表达式都不为 **Null** 时,*result* 根据下表确定: | 如果 *expression1* 为 | 且 *expression2* 为 | 则 *result* 为 | |:-----|:-----|:-----| | **True** | **True** | **True** | | **True** | **False** | **False** | | **False** | **True** | **False** | | **False** | **False** | **True** | **Eqv** 运算符对两个数值表达式中相同位置的位执行按位比较,并根据下表在 *result* 中设置相应的位: | 如果 *expression1* 中的位为 | 且 *expression2* 中的位为 | 则 *result* 为 | |:-----:|:-----:|:-----:| | 0 | 0 | 1 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | ::: info **Eqv** 总是求值*两个*操作数。 ::: ### 示例 本示例使用 **Eqv** 运算符对两个表达式执行逻辑等价运算。 ```vb Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B Eqv B > C ' Returns True. MyCheck = B > A Eqv B > C ' Returns False. MyCheck = A > B Eqv B > D ' Returns Null. MyCheck = A Eqv B ' Returns -3 (bitwise comparison). ``` ### 另请参阅 * [**Xor** 运算符](/official/Reference/Core/Xor) * [**Imp** 运算符](/official/Reference/Core/Imp) * [**And** 运算符](/official/Reference/Core/And) * [**Or** 运算符](/official/Reference/Core/Or) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Reference/Core/Erase.md --- # Erase Reinitializes the elements of fixed-size arrays, or releases dynamic-array storage space. Syntax: **Erase** *arraylist* *arraylist* : one or more comma-delimited array variables to be erased **Erase** behaves differently depending on whether an array is fixed-size (ordinary) or dynamic. **Erase** recovers no memory for fixed-size arrays. Erase sets the elements of a fixed array as follows: | Type of array | Effect of Erase on fixed-array elements | |-|-| | Fixed numeric array | Sets each element to zero. | | Fixed string array (variable length) | Sets each element to a zero-length string (""). | | Fixed string array (fixed length) | Sets each element to zero. | | Fixed Variant array | Sets each element to **Empty**. | | Array of user-defined types | Sets each element as if it were a separate variable. | | Array of objects | Sets each element to the special value **Nothing**. | **Erase** frees the memory used by dynamic arrays. Before the program can refer to the dynamic array again, it must redeclare the array variable's dimensions by using a ReDim statement. ### Example This example uses the **Erase** statement to reinitialize the elements of fixed-size arrays and deallocate dynamic-array storage space. ```vb ' Declare array variables. Dim NumArray(10) As Integer ' Integer array. Dim StrVarArray(10) As String ' Variable-string array. Dim StrFixArray(10) As String * 10 ' Fixed-string array. Dim VarArray(10) As Variant ' Variant array. Dim DynamicArray() As Integer ' Dynamic array. ReDim DynamicArray(10) ' Allocate storage space. Erase NumArray ' Each element set to 0. Erase StrVarArray ' Each element set to zero-length ' string (""). Erase StrFixArray ' Each element set to 0. Erase VarArray ' Each element set to Empty. Erase DynamicArray ' Free memory used by array. ``` --- --- url: /zh/official/Reference/Core/Erase.md --- # Erase 重新初始化固定大小数组的元素,或释放动态数组的存储空间。 语法:**Erase** *arraylist* *arraylist* : 要清除的一个或多个逗号分隔的数组变量 **Erase** 的行为取决于数组是固定大小(普通)还是动态的。**Erase** 不为固定大小数组回收内存。Erase 按以下方式设置固定数组的元素: | 数组类型 | Erase 对固定数组元素的影响 | |-|-| | 固定数值数组 | 将每个元素设为零。 | | 固定字符串数组(变长) | 将每个元素设为零长度字符串("")。 | | 固定字符串数组(定长) | 将每个元素设为零。 | | 固定Variant数组 | 将每个元素设为 **Empty**。 | | 用户自定义类型数组 | 将每个元素像单独变量一样设置。 | | 对象数组 | 将每个元素设为特殊值 **Nothing**。 | **Erase** 释放动态数组使用的内存。程序再次引用动态数组之前,必须使用ReDim语句重新声明数组变量的维度。 ### 示例 本示例使用 **Erase** 语句重新初始化固定大小数组的元素并释放动态数组的存储空间。 ```vb ' Declare array variables. Dim NumArray(10) As Integer ' Integer array. Dim StrVarArray(10) As String ' Variable-string array. Dim StrFixArray(10) As String * 10 ' Fixed-string array. Dim VarArray(10) As Variant ' Variant array. Dim DynamicArray() As Integer ' Dynamic array. ReDim DynamicArray(10) ' Allocate storage space. Erase NumArray ' Each element set to 0. Erase StrVarArray ' Each element set to zero-length ' string (""). Erase StrFixArray ' Each element set to 0. Erase VarArray ' Each element set to Empty. Erase DynamicArray ' Free memory used by array. ``` --- --- url: /en/official/Reference/VBA/Information/Erl.md --- # Erl Returns a **Long** containing the line number of the most recently executed statement at which a run-time error was raised. Syntax: **Erl** \[ **()** ] A *line number* is a numeric label that prefixes a statement, such as the `110:` in `110: x = 1 / 0`. They are a relic of older Basic dialects, retained mainly so that error handlers can report where a fault occurred. **Erl** is set to that label when an error is raised inside the labelled statement, and reset to **0** when the active error handler exits via **Resume**, **Resume Next**, or any **Exit** statement. If the statement that raised the error has no preceding line number, **Erl** returns **0**. ### Example This example uses **Erl** to log the line number where a run-time error was raised. ```vb Sub Demo() On Error GoTo Handler 100: Dim x As Double 110: x = 1 / 0 ' Generates a division-by-zero error. Exit Sub Handler: Debug.Print "Error at line "; Erl ' Prints "Error at line 110". End Sub ``` ### See Also * [Err](/en/official/Reference/VBA/Information/Err) property * [On Error](/en/official/Reference/Core/On-Error) statement --- --- url: /zh/official/Reference/VBA/Information/Erl.md --- # Erl 返回一个**Long**,包含引发运行时错误的最近执行语句的行号。 语法:**Erl** \[ **()** ] *行号*是语句前缀的数字标签,例如`110:`在`110: x = 1 / 0`中。它们是旧版Basic方言的遗留特性,保留主要是为了让错误处理程序能报告故障发生的位置。当错误在标记语句内引发时,**Erl**设置为该标签,当活动错误处理程序通过**Resume**、**Resume Next**或任何**Exit**语句退出时,**Erl**重置为**0**。 如果引发错误的语句没有前面的行号,**Erl**返回**0**。 ### 示例 本示例使用**Erl**记录引发运行时错误的行号。 ```vb Sub Demo() On Error GoTo Handler 100: Dim x As Double 110: x = 1 / 0 ' Generates a division-by-zero error. Exit Sub Handler: Debug.Print "Error at line "; Erl ' Prints "Error at line 110". End Sub ``` ### 另请参阅 * [Err](/official/Reference/VBA/Information/Err)属性 * [On Error](/official/Reference/Core/On-Error)语句 --- --- url: /en/official/Reference/VBA/Information/Err.md --- # Err Returns or sets the [**ErrObject**](/en/official/Reference/VBA/ErrObject/) describing the current run-time error state. Syntax: * **Err** \[ **()** ] * **Err** **=** *errorNumber* *errorNumber* : A **Long** error code to assign to the **Err** object. This is shorthand for `Err.Number = errorNumber`, since [**Number**](/en/official/Reference/VBA/ErrObject/Number) is the default property of **ErrObject**. The **Err** object is intrinsic and global --- there is no need to declare or construct one. Its properties are populated when a run-time error is raised, and reset to zero or zero-length strings when the active error handler exits via **Resume**, **Resume Next**, or any **Exit** statement, or when [**Err.Clear**](/en/official/Reference/VBA/ErrObject/Clear) is called explicitly. To generate a run-time error from user code, use the [**Raise**](/en/official/Reference/VBA/ErrObject/Raise) method rather than the **Error** statement, especially for class-module and Automation errors. ### Example This example uses the [**Number**](/en/official/Reference/VBA/ErrObject/Number), [**Description**](/en/official/Reference/VBA/ErrObject/Description), [**HelpContext**](/en/official/Reference/VBA/ErrObject/HelpContext), [**HelpFile**](/en/official/Reference/VBA/ErrObject/HelpFile), and [**Source**](/en/official/Reference/VBA/ErrObject/Source) properties of the **Err** object to construct an error-message dialog. ```vb Dim Msg As String On Error Resume Next ' Defer error handling. Err.Clear Err.Raise 6 ' Generate an "Overflow" error. If Err.Number <> 0 Then Msg = "Error # " & Err.Number & " was generated by " _ & Err.Source & vbCrLf & vbCrLf & Err.Description MsgBox Msg, vbMsgBoxHelpButton, "Error", Err.HelpFile, Err.HelpContext End If ``` ### See Also * [ErrObject](/en/official/Reference/VBA/ErrObject/) module * [Erl](/en/official/Reference/VBA/Information/Erl) function * [On Error](/en/official/Reference/Core/On-Error) statement --- --- url: /zh/official/Reference/VBA/Information/Err.md --- # Err 返回或设置描述当前运行时错误状态的[**ErrObject**](/official/Reference/VBA/ErrObject/)。 语法: * **Err** \[ **()** ] * **Err** **=** *errorNumber* *errorNumber* : **Long**错误代码,分配给**Err**对象。这是`Err.Number = errorNumber`的简写,因为[**Number**](/official/Reference/VBA/ErrObject/Number)是**ErrObject**的默认属性。 **Err**对象是内在且全局的——无需声明或构造。当运行时错误引发时其属性被填充,当活动错误处理程序通过**Resume**、**Resume Next**或任何**Exit**语句退出时,或显式调用[**Err.Clear**](/official/Reference/VBA/ErrObject/Clear)时,属性重置为零或零长度字符串。 要从用户代码生成运行时错误,请使用[**Raise**](/official/Reference/VBA/ErrObject/Raise)方法而非**Error**语句,特别是对于类模块和Automation错误。 ### 示例 本示例使用**Err**对象的[**Number**](/official/Reference/VBA/ErrObject/Number)、[**Description**](/official/Reference/VBA/ErrObject/Description)、[**HelpContext**](/official/Reference/VBA/ErrObject/HelpContext)、[**HelpFile**](/official/Reference/VBA/ErrObject/HelpFile)和[**Source**](/official/Reference/VBA/ErrObject/Source)属性构造错误消息对话框。 ```vb Dim Msg As String On Error Resume Next ' Defer error handling. Err.Clear Err.Raise 6 ' Generate an "Overflow" error. If Err.Number <> 0 Then Msg = "Error # " & Err.Number & " was generated by " _ & Err.Source & vbCrLf & vbCrLf & Err.Description MsgBox Msg, vbMsgBoxHelpButton, "Error", Err.HelpFile, Err.HelpContext End If ``` ### 另请参阅 * [ErrObject](/official/Reference/VBA/ErrObject/)模块 * [Erl](/official/Reference/VBA/Information/Erl)函数 * [On Error](/official/Reference/Core/On-Error)语句 --- --- url: /en/official/Reference/VBA/ErrObject.md --- # ErrObject class The **Err** object holds information about the most recent run-time error. It is a global, intrinsic singleton --- there is no need to declare it or construct one with **New**, just reference it as **Err**. The default property is [**Number**](/en/official/Reference/VBA/ErrObject/Number), so a bare **Err** is equivalent to `Err.Number`. ## Inspecting an error When a run-time error is raised inside a procedure that has an active error handler installed with [**On Error**](/en/official/Reference/Core/On-Error), execution jumps to the handler with the **Err** object's properties populated. The handler reads [**Number**](/en/official/Reference/VBA/ErrObject/Number) to identify the error, [**Description**](/en/official/Reference/VBA/ErrObject/Description) for a human-readable message, and [**Source**](/en/official/Reference/VBA/ErrObject/Source) to learn where it originated. ```vb Sub Demo() On Error GoTo Handler Err.Raise 6 ' Generate an Overflow error. Exit Sub Handler: Debug.Print Err.Number ' 6 Debug.Print Err.Description ' "Overflow" End Sub ``` The properties are reset to their zero values when the handler exits via **Resume**, **Resume Next**, or any **Exit** statement, or when [**Clear**](/en/official/Reference/VBA/ErrObject/Clear) is called explicitly. ## Raising a custom error Code can generate its own run-time error by calling [**Raise**](/en/official/Reference/VBA/ErrObject/Raise). Custom error numbers should be biased by [**vbObjectError**](/en/official/Reference/VBA/Constants/#vbObjectError) so that they don't collide with twinBASIC's built-in numbers. Setting [**Source**](/en/official/Reference/VBA/ErrObject/Source) and [**Description**](/en/official/Reference/VBA/ErrObject/Description) at the call site gives the error handler something useful to inspect or display. ```vb Public Sub WithdrawCash(ByVal Amount As Currency) If Amount > Balance Then Err.Raise vbObjectError + 1001, _ Source:="Account.WithdrawCash", _ Description:="Insufficient funds." End If ' ... End Sub ``` ## Members * [Clear](/en/official/Reference/VBA/ErrObject/Clear) -- resets all properties of the **Err** object to their zero values * [Description](/en/official/Reference/VBA/ErrObject/Description) -- returns or sets a string describing the error * [HelpContext](/en/official/Reference/VBA/ErrObject/HelpContext) -- returns or sets the context ID of a Help topic associated with the error * [HelpFile](/en/official/Reference/VBA/ErrObject/HelpFile) -- returns or sets the path to the Help file associated with the error * [LastDllError](/en/official/Reference/VBA/ErrObject/LastDllError) -- returns the last system error code from a call into a DLL * [LastHresult](/en/official/Reference/VBA/ErrObject/LastHresult) -- returns the last HRESULT returned from a COM object method call * [Number](/en/official/Reference/VBA/ErrObject/Number) -- returns or sets the error number; the default member of **Err** * [Raise](/en/official/Reference/VBA/ErrObject/Raise) -- generates a run-time error * [ReturnHResult](/en/official/Reference/VBA/ErrObject/ReturnHResult) -- sets a custom HRESULT to be returned from the current method * [Source](/en/official/Reference/VBA/ErrObject/Source) -- returns or sets the name of the object or application that generated the error --- --- url: /zh/official/Reference/VBA/ErrObject.md --- # ErrObject 类 **Err** 对象保存有关最近运行时错误的信息。它是一个全局的内在单例——无需声明或使用 **New** 构造,直接引用 **Err** 即可。默认属性为 [**Number**](/official/Reference/VBA/ErrObject/Number),因此单独的 **Err** 等效于 `Err.Number`。 ## 检查错误 当在使用 [**On Error**](/official/Reference/Core/On-Error) 安装了活动错误处理程序的过程内发生运行时错误时,执行跳转到处理程序,**Err** 对象的属性已填充。处理程序读取 [**Number**](/official/Reference/VBA/ErrObject/Number) 以标识错误,读取 [**Description**](/official/Reference/VBA/ErrObject/Description) 获取可读消息,读取 [**Source**](/official/Reference/VBA/ErrObject/Source) 了解错误来源。 ```vb Sub Demo() On Error GoTo Handler Err.Raise 6 ' Generate an Overflow error. Exit Sub Handler: Debug.Print Err.Number ' 6 Debug.Print Err.Description ' "Overflow" End Sub ``` 当处理程序通过 **Resume**、**Resume Next** 或任何 **Exit** 语句退出,或显式调用 [**Clear**](/official/Reference/VBA/ErrObject/Clear) 时,属性将重置为零值。 ## 引发自定义错误 代码可以通过调用 [**Raise**](/official/Reference/VBA/ErrObject/Raise) 来生成自己的运行时错误。自定义错误号应加上 [**vbObjectError**](/official/Reference/VBA/Constants/#vbObjectError) 偏移,以避免与 twinBASIC 的内置编号冲突。在调用处设置 [**Source**](/official/Reference/VBA/ErrObject/Source) 和 [**Description**](/official/Reference/VBA/ErrObject/Description) 可为错误处理程序提供有用的检查或显示信息。 ```vb Public Sub WithdrawCash(ByVal Amount As Currency) If Amount > Balance Then Err.Raise vbObjectError + 1001, _ Source:="Account.WithdrawCash", _ Description:="Insufficient funds." End If ' ... End Sub ``` ## 成员 * [Clear](/official/Reference/VBA/ErrObject/Clear) -- 将 **Err** 对象的所有属性重置为零值 * [Description](/official/Reference/VBA/ErrObject/Description) -- 返回或设置描述错误的字符串 * [HelpContext](/official/Reference/VBA/ErrObject/HelpContext) -- 返回或设置与错误关联的帮助主题上下文 ID * [HelpFile](/official/Reference/VBA/ErrObject/HelpFile) -- 返回或设置与错误关联的帮助文件路径 * [LastDllError](/official/Reference/VBA/ErrObject/LastDllError) -- 返回 DLL 调用的最后一个系统错误代码 * [LastHresult](/official/Reference/VBA/ErrObject/LastHresult) -- 返回 COM 对象方法调用返回的最后一个 HRESULT * [Number](/official/Reference/VBA/ErrObject/Number) -- 返回或设置错误号;**Err** 的默认成员 * [Raise](/official/Reference/VBA/ErrObject/Raise) -- 生成运行时错误 * [ReturnHResult](/official/Reference/VBA/ErrObject/ReturnHResult) -- 设置从当前方法返回的自定义 HRESULT * [Source](/official/Reference/VBA/ErrObject/Source) -- 返回或设置生成错误的对象或应用程序名称 --- --- url: /en/official/Reference/Core/Error.md --- # Error Simulates the occurrence of an error. Syntax: **Error** *errornumber* *errornumber* : can be any valid error number. The **Error** statement is supported for backward compatibility. In new code, especially when creating objects, use the **Err** object's **Raise** method to generate run-time errors. If *errornumber* is defined, the **Error** statement calls the error handler after the properties of the **Err** object are assigned the following default values: | Property | Value | | :--------------- | :----------------------------------------------------------- | | **Number** | Value specified as argument to **Error** statement. Can be any valid error number. | | **Source** | Name of the current Visual Basic project. | | **Description** | String expression corresponding to the return value of the **Error** function for the specified **Number**, if this string exists. If the string doesn't exist, **Description** contains a zero-length string (""). | | **HelpFile** | The fully qualified drive, path, and file name of the appropriate Visual Basic Help file. | | **HelpContext** | The appropriate Visual Basic Help file context ID for the error corresponding to the **Number** property. | | **LastDLLError** | Zero. | If no error handler exists or if none is enabled, an error message is created and displayed from the **Err** object properties. ### Example This example uses the **Error** statement to simulate error number 11. ```vb On Error Resume Next ' Defer error handling. Error 11 ' Simulate the "Division by zero" error. ``` --- --- url: /zh/official/Reference/Core/Error.md --- # Error 模拟错误的发生。 语法:**Error** *errornumber* *errornumber* : 可以是任何有效的错误号。 **Error** 语句为向后兼容而受支持。在新代码中,特别是创建对象时,请使用 **Err** 对象的 **Raise** 方法生成运行时错误。 如果定义了 *errornumber*,**Error** 语句在 **Err** 对象的属性被赋予以下默认值后调用错误处理程序: | 属性 | 值 | | :--------------- | :----------------------------------------------------------- | | **Number** | 作为 **Error** 语句参数指定的值。可以是任何有效的错误号。 | | **Source** | 当前Visual Basic项目的名称。 | | **Description** | 与指定 **Number** 的 **Error** 函数返回值对应的字符串表达式(如果该字符串存在)。如果字符串不存在,**Description** 包含零长度字符串("")。 | | **HelpFile** | 适当的Visual Basic帮助文件的完整驱动器、路径和文件名。 | | **HelpContext** | 与 **Number** 属性对应的错误在适当的Visual Basic帮助文件中的上下文ID。 | | **LastDLLError** | 零。 | 如果不存在错误处理程序或未启用任何错误处理程序,则会从 **Err** 对象属性创建并显示错误消息。 ### 示例 本示例使用 **Error** 语句模拟错误号11。 ```vb On Error Resume Next ' Defer error handling. Error 11 ' Simulate the "Division by zero" error. ``` --- --- url: /zh/official/Reference/VBA/Conversion/Error.md --- # Error, Error$ 返回与给定错误号对应的错误消息。 语法: * **Error$** \[ **(** *errornumber* **)** ] * **Error** \[ **(** *errornumber* **)** ] *errornumber* : *可选* 任何有效的错误号。如果 *errornumber* 是有效的错误号但未定义,**Error** 返回字符串 `"Application-defined or object-defined error"`。如果 *errornumber* 无效,将发生错误。如果省略 *errornumber*,则返回与最近一次运行时错误对应的消息。如果未发生过运行时错误,或 *errornumber* 为 `0`,**Error** 返回零长度字符串(`""`)。 `$` 后缀形式返回 **String**;无后缀形式返回 **Variant** (**String**)。 ::: info **Error** *函数*(此处描述的)与 [**Error**](/official/Reference/Core/Error) *语句*同名但是不同的语言元素。函数返回错误号的消息文本;语句引发运行时错误。 ::: 检查 **Err** 对象的属性设置以识别最近的运行时错误。**Error** 函数的返回值对应于 **Err** 对象的 **Description** 属性。 ### 示例 此示例使用 **Error** 函数打印与指定错误号对应的错误消息。 ```vb Private Sub PrintError() Dim ErrorNumber As Long, count As Long count = 1: ErrorNumber = 1 On Error GoTo EOSb Do While count < 100 Do While Error(ErrorNumber) = "Application-defined or object-defined error" ErrorNumber = ErrorNumber + 1 Loop Debug.Print count & "-Error(" & ErrorNumber & "): " & Error(ErrorNumber) ErrorNumber = ErrorNumber + 1 count = count + 1 Loop EOSb: Debug.Print ErrorNumber End Sub ``` ### 另请参阅 * [Error](/official/Reference/Core/Error) 语句 * [CVErr](/official/Reference/VBA/Conversion/CVErr) 函数 --- --- url: /en/official/Reference/VBA/Conversion/Error.md --- # Error, Error$ Returns the error message that corresponds to a given error number. Syntax: * **Error$** \[ **(** *errornumber* **)** ] * **Error** \[ **(** *errornumber* **)** ] *errornumber* : *optional* Any valid error number. If *errornumber* is a valid error number but is not defined, **Error** returns the string `"Application-defined or object-defined error"`. If *errornumber* is not valid, an error occurs. If *errornumber* is omitted, the message corresponding to the most recent run-time error is returned. If no run-time error has occurred, or *errornumber* is `0`, **Error** returns a zero-length string (`""`). The `$`-suffixed form returns a **String**; the unsuffixed form returns a **Variant** (**String**). ::: info The **Error** *function* (described here) and the [**Error**](/en/official/Reference/Core/Error) *statement* share a name but are different language elements. The function returns the message text for an error number; the statement raises a run-time error. ::: Examine the property settings of the **Err** object to identify the most recent run-time error. The return value of the **Error** function corresponds to the **Description** property of the **Err** object. ### Example This example uses the **Error** function to print error messages that correspond to the specified error numbers. ```vb Private Sub PrintError() Dim ErrorNumber As Long, count As Long count = 1: ErrorNumber = 1 On Error GoTo EOSb Do While count < 100 Do While Error(ErrorNumber) = "Application-defined or object-defined error" ErrorNumber = ErrorNumber + 1 Loop Debug.Print count & "-Error(" & ErrorNumber & "): " & Error(ErrorNumber) ErrorNumber = ErrorNumber + 1 count = count + 1 Loop EOSb: Debug.Print ErrorNumber End Sub ``` ### See Also * [Error](/en/official/Reference/Core/Error) statement * [CVErr](/en/official/Reference/VBA/Conversion/CVErr) function --- --- url: /en/official/Reference/VBRUN/ErrorCallstack.md --- # ErrorCallstack class An **ErrorCallstack** object is a snapshot of the chain of procedures that were active on the call stack at the moment a run-time error was raised --- outermost frame first, innermost (the procedure that actually raised the error) last. Each frame is exposed as an [**ErrorStackFrame**](/en/official/Reference/VBRUN/ErrorStackFrame/), describing one procedure by its project, module, and procedure names. The snapshot is read through the **Callstack** property of an **ErrorContext** object, which is itself accessible from the structured error-handling machinery --- typically inside a `Catch` block or an **On Error** handler. ```vb Sub LogStackTrace(ByVal Stack As ErrorCallstack) Dim i As Long For i = 1 To Stack.Count Dim Frame As ErrorStackFrame Set Frame = Stack.Items(i) Debug.Print Frame.ProjectName & "." & Frame.ModuleName & "." & Frame.ProcedureName Next i End Sub ``` The collection is read-only and has no `_NewEnum` member, so it cannot be iterated with **For Each** --- use a numeric loop from `1` to [**Count**](#count) and read each frame with [**Items**](#items). ## Members ### Count Returns the number of frames in the snapshot. Syntax: *object*.**Count** *object* : *required* An object expression that evaluates to an **ErrorCallstack** object. The value is a **Long**. Valid indexes for [**Items**](#items) run from `1` to **Count**. **Count** is `0` if no procedures were on the stack at the time the snapshot was taken. ### Items Returns one frame from the snapshot by its one-based position. Syntax: *object*.**Items(** *Index* **)** *object* : *required* An object expression that evaluates to an **ErrorCallstack** object. *Index* : *required* A **Long** giving the one-based position of the frame to return. Frame `1` is the outermost procedure on the stack; frame [**Count**](#count) is the innermost --- the procedure that raised the error. *Index* must be between `1` and **Count**; otherwise an error occurs. The result is an [**ErrorStackFrame**](/en/official/Reference/VBRUN/ErrorStackFrame/) describing the procedure at that position. --- --- url: /zh/official/Reference/VBRUN/ErrorCallstack.md --- *** title: ErrorCallstack parent: VBRUN Package nav\_order: 13 permalink: /tB/Packages/VBRUN/ErrorCallstack/ --------------------------------------------- # ErrorCallstack 类 **ErrorCallstack**对象是引发运行时错误时调用堆栈上活动过程链的快照——最外层帧在前,最内层(实际引发错误的过程)在后。每个帧以[**ErrorStackFrame**](/official/Reference/VBRUN/ErrorStackFrame/)的形式公开,通过其项目、模块和过程名称描述一个过程。 快照通过**ErrorContext**对象的**Callstack**属性读取,而**ErrorContext**本身可从结构化错误处理机制访问——通常在Catch块或**On Error**处理器内部。 `vb Sub LogStackTrace(ByVal Stack As ErrorCallstack) Dim i As Long For i = 1 To Stack.Count Dim Frame As ErrorStackFrame Set Frame = Stack.Items(i) Debug.Print Frame.ProjectName & "." & Frame.ModuleName & "." & Frame.ProcedureName Next i End Sub ` 此集合为只读,没有\_NewEnum成员,因此不能使用**For Each**迭代——请使用从1到[**Count**](#count)的数值循环,并使用[**Items**](#items)读取每个帧。 ## 成员 ### Count 返回快照中的帧数。 语法:*object*.**Count** *object* : *必需* 求值为**ErrorCallstack**对象的对象表达式。 值为**Long**。[**Items**](#items)的有效索引范围从1到**Count**。如果拍摄快照时堆栈上没有过程,**Count**为�。 ### Items 按从一开始的位置从快照中返回一个帧。 语法:*object*.**Items(** *Index* **)** *object* : *必需* 求值为**ErrorCallstack**对象的对象表达式。 *Index* : *必需* 给出要返回帧从一开始位置的**Long**。帧1是堆栈上最外层的过程;帧[**Count**](#count)是最内层——引发错误的过程。*Index*必须在1和**Count**之间;否则将发生错误。 结果为描述该位置过程的[**ErrorStackFrame**](/official/Reference/VBRUN/ErrorStackFrame/)。 --- --- url: /en/official/Reference/VBRUN/ErrorContext.md --- # ErrorContext class An **ErrorContext** object captures everything the runtime knows about a run-time error: its identity ([**Number**](#number), [**Description**](#description), [**Source**](#source)), its help references ([**HelpFile**](#helpfile), [**HelpContext**](#helpcontext)), the operating-system error code at the time it was raised ([**LastDLLError**](#lastdllerror)), the [**State**](#state) of the error-handling machinery, and a snapshot of the [**Callstack**](#callstack) from the moment of the failure. It is twinBASIC's structured counterpart to the simpler [**Err**](/en/official/Reference/VBA/ErrObject/) object. The error-identity properties (**Number**, **Description**, **Source**, **HelpFile**, **HelpContext**, **LastDLLError**) have the same meaning here as on the **Err** object --- see the [**ErrObject**](/en/official/Reference/VBA/ErrObject/) module for a discussion of each. **State** and **Callstack** are unique to **ErrorContext** and reflect the structured error-handling machinery that has no equivalent on the legacy **Err** object. ## Members ### Callstack Returns a snapshot of the call stack as it was when the error was raised, as an [**ErrorCallstack**](/en/official/Reference/VBRUN/ErrorCallstack/). Syntax: *object*.**Callstack** *object* : *required* An object expression that evaluates to an **ErrorContext** object. The snapshot lists every active procedure outermost-first; the innermost frame is the procedure that raised the error. The collection is read-only --- see [**ErrorCallstack**](/en/official/Reference/VBRUN/ErrorCallstack/) for how to iterate it. ### Description Returns a short text description of the error, as a **String**. Read-only. Syntax: *object*.**Description** *object* : *required* An object expression that evaluates to an **ErrorContext** object. For runtime-defined errors, this is the message the runtime would have shown in an unhandled-error dialog. For user-defined errors, it is whatever string was passed to **Err.Raise**. ### HelpContext Returns the help-file context ID associated with the error, as a **Long**. Read-only. Syntax: *object*.**HelpContext** *object* : *required* An object expression that evaluates to an **ErrorContext** object. When [**HelpFile**](#helpfile) names a help file, **HelpContext** identifies the topic in that file that documents the error. **0** if no help context is associated. ### HelpFile Returns the path of the help file associated with the error, as a **String**. Read-only. Syntax: *object*.**HelpFile** *object* : *required* An object expression that evaluates to an **ErrorContext** object. A zero-length string if no help file is associated. ### LastDLLError Returns the last operating-system error code recorded by a call into a Windows DLL, as a **Long**. Read-only. Syntax: *object*.**LastDLLError** *object* : *required* An object expression that evaluates to an **ErrorContext** object. twinBASIC's error trapping does not catch failures inside `Declare`d Windows API calls --- those calls report failure through their return value, and the calling code has to inspect this property to learn the underlying Win32 error. The value is meaningful only on Windows. ### Number Returns the run-time error number, as a **Long**. Read-only. Syntax: *object*.**Number** *object* : *required* An object expression that evaluates to an **ErrorContext** object. Built-in errors use the standard VBA error codes (for example, `9` for "Subscript out of range" or `91` for "Object variable or With block variable not set"). User-defined errors raised with **Err.Raise** typically add the **vbObjectError** offset to a small per-application code. ### Source Returns the name of the object or application that raised the error, as a **String**. Read-only. Syntax: *object*.**Source** *object* : *required* An object expression that evaluates to an **ErrorContext** object. For errors raised inside a twinBASIC project, this is the project name; for errors raised by an Automation server, it is the application's programmatic identifier. User code can supply any string when calling **Err.Raise**. ### State Returns or sets a value identifying which error-handling construct is currently active, as an **OnErrorStatus** value. Syntax: *object*.**State** \[ **=** *value* ] *object* : *required* An object expression that evaluates to an **ErrorContext** object. The runtime updates **State** as control flows through error handlers, **Try**/**Catch**/**Finally** blocks, and the various propagation paths. Reading the property tells diagnostic code which construct it is being invoked from. Assigning to it overrides the runtime's idea of what to do next --- a deliberately advanced operation, useful mainly to diagnostic tools and to libraries that manage their own error flow. The **OnErrorStatus** enumeration values are: `OnErrorGoto0` (`&H1`) : An **On Error GoTo 0** is currently in effect --- no handler is installed. `OnErrorResumeNext` (`&H2`) : An **On Error Resume Next** is currently in effect. `OnErrorGotoLabel` (`&H3`) : An **On Error GoTo** *label* is currently in effect. `OnErrorEnd` (`&H4`) : Execution is being terminated because of an unhandled error. `OnErrorDebug` (`&H5`) : The runtime is about to break into the debugger. `CalledByLocalHandler` (`&H6`) : The currently executing code was called by a local error handler. `OnErrorRetry` (`&H7`) : A retry of the failing statement is in progress (the structured equivalent of **Resume**). `OnErrorPropagate` (`&H8`) : An unhandled error is being propagated up the call stack. `OnErrorExitProcedure` (`&H9`) : An error is forcing the current procedure to exit. `OnErrorCatch` (`&Ha`) : Control is inside a **Catch** block matching a specific error. `OnErrorCatchAll` (`&Hb`) : Control is inside a general "catch all" block. `OnErrorInsideCatch` (`&Hc`) : Control is nested inside a **Catch** block (a further error has been raised inside a handler). `OnErrorInsideCatchAll` (`&Hd`) : Control is nested inside a "catch all" block. `OnErrorInsideFinally` (`&He`) : Control is inside a **Finally** block. `OnErrorPropagateCatch` (`&Hf`) : An error is being propagated out of a **Catch** block. `OnErrorPropagateCatchAll` (`&H10`) : An error is being propagated out of a "catch all" block. --- --- url: /zh/official/Reference/VBRUN/ErrorContext.md --- # ErrorContext 类 **ErrorContext**对象捕获运行时关于运行时错误的所有信息:其标识([**Number**](#number)、[**Description**](#description)、[**Source**](#source))、帮助引用([**HelpFile**](#helpfile)、[**HelpContext**](#helpcontext))、引发时的操作系统错误代码([**LastDLLError**](#lastdllerror))、错误处理机制的[**State**](#state)以及故障时刻的[**Callstack**](#callstack)快照。它是twinBASIC对较简单的[**Err**](/official/Reference/VBA/ErrObject/)对象的结构化对应。 错误标识属性(**Number**、**Description**、**Source**、**HelpFile**、**HelpContext**、**LastDLLError**)在此处的含义与**Err**对象上相同——参见[**ErrObject**](/official/Reference/VBA/ErrObject/)模块中各项的讨论。**State**和**Callstack**是**ErrorContext**独有的,反映了旧版**Err**对象上没有对应功能的结构化错误处理机制。 ## 成员 ### Callstack 返回错误引发时调用堆栈的快照,类型为[**ErrorCallstack**](/official/Reference/VBRUN/ErrorCallstack/)。 语法:*object*.**Callstack** *object* : *必需* 求值为**ErrorContext**对象的对象表达式。 快照按最外层在前列出每个活动过程;最内层帧是引发错误的过程。此集合为只读——参见[**ErrorCallstack**](/official/Reference/VBRUN/ErrorCallstack/)了解如何迭代。 ### Description 返回错误的简短文本描述,类型为**String**。只读。 语法:*object*.**Description** *object* : *必需* 求值为**ErrorContext**对象的对象表达式。 对于运行时定义的错误,这是运行时将在未处理错误对话框中显示的消息。对于用户定义的错误,它是传递给**Err.Raise**的字符串。 ### HelpContext 返回与错误关联的帮助文件上下文ID,类型为**Long**。只读。 语法:*object*.**HelpContext** *object* : *必需* 求值为**ErrorContext**对象的对象表达式。 当[**HelpFile**](#helpfile)指定帮助文件时,**HelpContext**标识该文件中记录错误的主题。如果没有关联的帮助上下文则为**0**。 ### HelpFile 返回与错误关联的帮助文件路径,类型为**String**。只读。 语法:*object*.**HelpFile** *object* : *必需* 求值为**ErrorContext**对象的对象表达式。 如果没有关联的帮助文件则为零长度字符串。 ### LastDLLError 返回Windows DLL调用记录的最后一个操作系统错误代码,类型为**Long**。只读。 语法:*object*.**LastDLLError** *object* : *必需* 求值为**ErrorContext**对象的对象表达式。 twinBASIC的错误捕获不会捕获Declare声明的Windows API调用内部的失败——这些调用通过返回值报告失败,调用代码必须检查此属性来了解底层Win32错误。此值仅在Windows上有意义。 ### Number 返回运行时错误编号,类型为**Long**。只读。 语法:*object*.**Number** *object* : *必需* 求值为**ErrorContext**对象的对象表达式。 内置错误使用标准VBA错误代码(例如,9表示"下标越范围",91表示"对象变量或With块变量未设置")。使用**Err.Raise**引发的用户定义错误通常将**vbObjectError**偏移量加到每个应用程序的小代码上。 ### Source 返回引发错误的对象或应用程序名称,类型为**String**。只读。 语法:*object*.**Source** *object* : *必需* 求值为**ErrorContext**对象的对象表达式。 对于在twinBASIC项目内部引发的错误,这是项目名称;对于由Automation服务器引发的错误,这是应用程序的编程标识符。用户代码在调用**Err.Raise**时可提供任意字符串。 ### State 返回或设置标识当前活动错误处理构造的值,类型为**OnErrorStatus**值。 语法:*object*.**State** \[ **=** *value* ] *object* : *必需* 求值为**ErrorContext**对象的对象表达式。 运行时在控制流经过错误处理器、**Try**/**Catch**/**Finally**块以及各种传播路径时更新**State**。读取此属性可告诉诊断代码它是从哪个构造调用的。对其赋值会覆盖运行时对下一步操作的决定——这是一种刻意设计的高级操作,主要用于诊断工具和管理自身错误流的库。 **OnErrorStatus**枚举值为: OnErrorGoto0(\&H1) : 当前生效**On Error GoTo 0**——未安装处理器。 OnErrorResumeNext(\&H2) : 当前生效**On Error Resume Next**。 OnErrorGotoLabel(\&H3) : 当前生效**On Error GoTo** *label*。 OnErrorEnd(\&H4) : 因未处理错误导致执行终止。 OnErrorDebug(\&H5) : 运行时即将中断进入调试器。 CalledByLocalHandler(\&H6) : 当前执行的代码由本地错误处理器调用。 OnErrorRetry(\&H7) : 正在重试失败语句(**Resume**的结构化等价)。 OnErrorPropagate(\&H8) : 未处理的错误正在沿调用堆栈向上传播。 OnErrorExitProcedure(\&H9) : 错误正在强制当前过程退出。 OnErrorCatch(\&Ha) : 控制在匹配特定错误的**Catch**块内。 OnErrorCatchAll(\&Hb) : 控制在通用的"捕获全部"块内。 OnErrorInsideCatch(\&Hc) : 控制嵌套在**Catch**块内(处理器内部又引发了错误)。 OnErrorInsideCatchAll(\&Hd) : 控制嵌套在"捕获全部"块内。 OnErrorInsideFinally(\&He) : 控制在**Finally**块内。 OnErrorPropagateCatch(\&Hf) : 错误正在从**Catch**块传播出去。 OnErrorPropagateCatchAll(\&H10) : 错误正在从"捕获全部"块传播出去。 --- --- url: /en/official/Reference/VBRUN/ErrorStackFrame.md --- # ErrorStackFrame class An **ErrorStackFrame** describes one procedure that was active on the call stack at the moment a run-time error was raised --- the project it belongs to, the module that contains it, and its own name. Frames are produced by iterating an [**ErrorCallstack**](/en/official/Reference/VBRUN/ErrorCallstack/) snapshot, which in turn is reachable from the [**Callstack**](/en/official/Reference/VBRUN/ErrorContext/#callstack) property of an [**ErrorContext**](/en/official/Reference/VBRUN/ErrorContext/). Every property is read-only. ```vb Sub LogStackTrace(ByVal Stack As ErrorCallstack) Dim i As Long For i = 1 To Stack.Count Dim Frame As ErrorStackFrame Set Frame = Stack.Items(i) Debug.Print Frame.ProjectName & "." & Frame.ModuleName & "." & Frame.ProcedureName Next i End Sub ``` ## Members ### ModuleName Returns the name of the module --- the standard module, class module, form, or user control --- that contains the procedure for this frame, as a **String**. Syntax: *object*.**ModuleName** *object* : *required* An object expression that evaluates to an **ErrorStackFrame** object. ### ProcedureName Returns the name of the procedure for this frame, as a **String**. Syntax: *object*.**ProcedureName** *object* : *required* An object expression that evaluates to an **ErrorStackFrame** object. For property accessors, this is the property name without the `Get`/`Let`/`Set` prefix; for event handlers, it is the compiler-generated handler name in the usual `<Object>_<Event>` form. ### ProjectName Returns the name of the twinBASIC project that contains the procedure for this frame, as a **String**. Syntax: *object*.**ProjectName** *object* : *required* An object expression that evaluates to an **ErrorStackFrame** object. For frames from a referenced package or compiled DLL, this is the name of the originating project. --- --- url: /zh/official/Reference/VBRUN/ErrorStackFrame.md --- # ErrorStackFrame 类 **ErrorStackFrame**描述引发运行时错误时调用堆栈上活动的一个过程——其所属项目、包含它的模块及其自身名称。帧通过迭代[**ErrorCallstack**](/official/Reference/VBRUN/ErrorCallstack/)快照产生,而快照可从[**ErrorContext**](/official/Reference/VBRUN/ErrorContext/)的[**Callstack**](/official/Reference/VBRUN/ErrorContext/#callstack)属性获取。每个属性均为只读。 ```vb Sub LogStackTrace(ByVal Stack As ErrorCallstack) Dim i As Long For i = 1 To Stack.Count Dim Frame As ErrorStackFrame Set Frame = Stack.Items(i) Debug.Print Frame.ProjectName & "." & Frame.ModuleName & "." & Frame.ProcedureName Next i End Sub ``` ## 成员 ### ModuleName 返回包含此帧过程的标准模块、类模块、窗体或用户控件的模块名称,类型为**String**。 语法:*object*.**ModuleName** *object* : *必需* 求值为**ErrorStackFrame**对象的对象表达式。 ### ProcedureName 返回此帧的过程名称,类型为**String**。 语法:*object*.**ProcedureName** *object* : *必需* 求值为**ErrorStackFrame**对象的对象表达式。 对于属性访问器,这是不带Get/Let/Set前缀的属性名称;对于事件处理器,是编译器生成的处理器名称,采用惯用的`<Object>_<Event>`格式。 ### ProjectName 返回包含此帧过程的twinBASIC项目名称,类型为**String**。 语法:*object*.**ProjectName** *object* : *必需* 求值为**ErrorStackFrame**对象的对象表达式。 对于来自引用包或已编译DLL的帧,这是原始项目的名称。 --- --- url: /en/official/Reference/VBA/HiddenModule/Eval.md --- # Eval Compiles and evaluates a twinBASIC expression supplied as a string, returning the result as a **Variant**. Syntax: **Eval(** *Expression* **)** **As Variant** *Expression* : *required* **String**. A twinBASIC expression that resolves to a value --- for example, `"2 + 2"`, `"Sqr(2)"`, or `"UCase(""hello"")"`. A fresh [**TbExpressionService**](/en/official/Reference/VBA/TbExpressionService/) is built for every call, with the standard library binder registered so the standard runtime functions ([**Sin**](/en/official/Reference/VBA/Math/Sin), [**Sqr**](/en/official/Reference/VBA/Math/Sqr), [**Len**](/en/official/Reference/VBA/Strings/Len), [**CStr**](/en/official/Reference/VBA/Conversion/CStr), and the rest) are visible. The expression is then compiled and evaluated once, and the service is discarded. For repeated evaluation of the same source, or for expressions that need to see application objects, construct the service explicitly and reuse a compiled [**ITbExpression**](/en/official/Reference/VBA/TbExpressionService/#itbexpression-interface). ### Example ```vb Debug.Print Eval("2 * (Sqr(2) + 1)") ' 4.82842712474619 Debug.Print Eval("UCase(""hello"")") ' "HELLO" ``` ### See Also * [ExpressionService module](/en/official/Reference/VBA/TbExpressionService/) --- --- url: /zh/official/Reference/VBA/HiddenModule/Eval.md --- # Eval 编译并计算以字符串形式提供的twinBASIC表达式,将结果作为**Variant**返回。 语法:**Eval(** *Expression* **)** **As Variant** *Expression* : *必需* **String**。一个可解析为值的twinBASIC表达式——例如`"2 + 2"`、`"Sqr(2)"`或`"UCase(""hello"")"`。 每次调用都会构建一个新的[**TbExpressionService**](/official/Reference/VBA/TbExpressionService/),并注册标准库绑定器,使标准运行时函数([**Sin**](/official/Reference/VBA/Math/Sin)、[**Sqr**](/official/Reference/VBA/Math/Sqr)、[**Len**](/official/Reference/VBA/Strings/Len)、[**CStr**](/official/Reference/VBA/Conversion/CStr)等)可见。表达式随后被编译和计算一次,服务即被丢弃。 对于重复计算同一源代码,或需要访问应用程序对象的表达式,请显式构建服务并重用已编译的[**ITbExpression**](/official/Reference/VBA/TbExpressionService/#itbexpression-interface)。 ### 示例 ```vb Debug.Print Eval("2 * (Sqr(2) + 1)") ' 4.82842712474619 Debug.Print Eval("UCase(""hello"")") ' "HELLO" ``` ### 另请参阅 * [ExpressionService模块](/official/Reference/VBA/TbExpressionService/) --- --- url: /en/official/Reference/VBA/TbExpressionService/Evaluate.md --- # Evaluate Runs a compiled expression and returns its current value. Syntax: *expression*.**Evaluate()** *expression* : *required* An object expression that evaluates to an [**ITbExpression**](./#itbexpression-interface), typically the value returned by [**Compile**](/en/official/Reference/VBA/TbExpressionService/Compile). The return value is a **Variant** holding the result of the expression. Its subtype reflects the natural type of the value --- for example, **Double** for a numeric expression, **String** for a text-producing one, **Boolean** for a comparison. Each call re-runs the expression against the current state of its bindings. If the bound objects expose properties whose values can change between calls --- host application state, the current row of a recordset, configurable parameters --- evaluating the same compiled expression twice may legitimately return different values. A run-time error raised inside the expression --- division by zero, type mismatch, an invalid call into a bound object --- propagates out of **Evaluate** like any other run-time error. ### Example This example compiles an expression that references a property on the host object via [**AddCustomBinderObject**](/en/official/Reference/VBA/TbExpressionService/AddCustomBinderObject), then evaluates it twice with the property having different values. ```vb Dim Service As TbExpressionService = New TbExpressionService Service.AddStdLibraryBinder() Service.AddCustomBinderObject "State", Me, IsAppObject Dim Expr As ITbExpression = Service.Compile("Counter * 2") Me.Counter = 1 : Debug.Print Expr.Evaluate() ' 2 Me.Counter = 5 : Debug.Print Expr.Evaluate() ' 10 ``` ### See Also * [Compile](/en/official/Reference/VBA/TbExpressionService/Compile) method * [Bind](/en/official/Reference/VBA/TbExpressionService/Bind) method --- --- url: /zh/official/Reference/VBA/TbExpressionService/Evaluate.md --- # Evaluate 运行编译表达式并返回其当前值。 语法:*expression*.**Evaluate()** *expression* : *必需* 计算结果为 [**ITbExpression**](./#itbexpression-interface) 的对象表达式,通常为 [**Compile**](/official/Reference/VBA/TbExpressionService/Compile) 返回的值。 返回值为 **Variant**,包含表达式的结果。其子类型反映值的自然类型——例如,数值表达式为 **Double**,文本生成为 **String**,比较为 **Boolean**。 每次调用都会根据其绑定的当前状态重新运行表达式。如果绑定对象暴露的属性值在调用之间可能变化——宿主应用程序状态、记录集的当前行、可配置参数——对同一编译表达式求值两次可能合法地返回不同的值。 表达式内部引发的运行时错误——除零、类型不匹配、对绑定对象的无效调用——像任何其他运行时错误一样从 **Evaluate** 传播出来。 ### 示例 此示例编译一个通过 [**AddCustomBinderObject**](/official/Reference/VBA/TbExpressionService/AddCustomBinderObject) 引用宿主对象属性的表达式,然后在属性具有不同值时求值两次。 ```vb Dim Service As TbExpressionService = New TbExpressionService Service.AddStdLibraryBinder() Service.AddCustomBinderObject "State", Me, IsAppObject Dim Expr As ITbExpression = Service.Compile("Counter * 2") Me.Counter = 1 : Debug.Print Expr.Evaluate() ' 2 Me.Counter = 5 : Debug.Print Expr.Evaluate() ' 10 ``` ### 另请参阅 * [Compile](/official/Reference/VBA/TbExpressionService/Compile) 方法 * [Bind](/official/Reference/VBA/TbExpressionService/Bind) 方法 --- --- url: /en/official/Reference/Core/Event.md --- # Event Declares a user-defined event. Syntax: \[ **Public** ] **Event** *procedurename* \[ (*arglist*) ] **Public** : *optional*. Specifies that the **Event** is visible throughout the project. **Events** types are **Public** by default. Note that events can only be raised in the module in which they are declared. *procedurename* : Name of the event; follows standard variable naming conventions. *arglist* : \[ **ByVal** | **ByRef** ] *varname* \[ **()** ] \[ **As** *type* ] **ByVal** : *optional* Indicates that the argument is passed by value. **ByRef** : *optional* Indicates that the argument is passed by reference. **ByRef** is the default, unlike in Visual Basic .NET. *varname* : Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions. *type* : *optional* Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal, Date, String (variable length only), Object, Variant, a user-defined type (UDT), or an object type. After the event has been declared, use the [**RaiseEvent**](/en/official/Reference/Core/RaiseEvent) statement to fire the event. A syntax error occurs if an **Event** declaration appears in a standard module. An event can't be declared to return a value. A typical event might be declared and raised as shown in the following fragments. ```vb ' Declare an event at module level of a class module Event LogonCompleted (UserName as String) Sub RaiseEvent LogonCompleted("AntoineJan") End Sub ``` Event arguments are declared the same way as procedure arguments, with the following exceptions: events cannot have named arguments, **Optional** arguments, or **ParamArray** arguments. Events don't have return values. ### Example The following example uses events to count off seconds during a demonstration of the fastest 100-meter race. The code illustrates all of the event-related methods, properties, and statements, including the **Event** statement. The class that raises an event is the event source, and the classes that implement the event are the sinks. An event source can have multiple sinks for the events it generates. When the class raises the event, that event is fired on every class that has elected to sink events for that instance of the object. The example also uses a form (`Form1`) with a button (`Command1`), a label (`Label1`), and two text boxes (`Text1` and `Text2`). When the button is clicked, the first text box displays "From Now" and the second starts to count seconds. When the full time (9.84 seconds) has elapsed, the first text box displays "Until Now" and the second displays "9.84". The code specifies the initial and terminal states of the form. It also contains the code executed when events are raised. ```vb Class Form1 Option Explicit Private WithEvents mText As TimerState Private Sub Command1_Click() Text1.Text = "From Now" Text1.Refresh Text2.Text = "0" Text2.Refresh Call mText.TimerTask(9.84) End Sub Private Sub Form_Load() Command1.Caption = "Click to Start Timer" Text1.Text = "" Text2.Text = "" Label1.Caption = "The fastest 100 meter run took this long:" Set mText = New TimerState End Sub Private Sub mText_ChangeText() Text1.Text = "Until Now" Text2.Text = "9.84" End Sub Private Sub mText_UpdateTime(ByVal dblJump As Double) Text2.Text = Str(Format(dblJump, "0")) DoEvents End Sub End Class ``` The remaining code is in a class module named TimerState. The **Event** statements declare the procedures initiated when events are raised. VB ```vb Class TimerState Option Explicit Public Event UpdateTime(ByVal dblJump As Double) Public Event ChangeText() Public Sub TimerTask(ByVal Duration As Double) Dim dblStart As Double Dim dblSecond As Double Dim dblSoFar As Double dblStart = Timer dblSoFar = dblStart Do While Timer < dblStart + Duration If Timer - dblSoFar >= 1 Then dblSoFar = dblSoFar + 1 RaiseEvent UpdateTime(Timer - dblStart) End If Loop RaiseEvent ChangeText End Sub End Class ``` --- --- url: /zh/official/Reference/Core/Event.md --- # Event 声明用户自定义事件。 语法:\[ **Public** ] **Event** *procedurename* \[ (*arglist*) ] **Public** : *可选*。指定 **Event** 在整个项目中可见。**Event** 类型默认为 **Public**。注意事件只能在声明它们的模块中引发。 *procedurename* : 事件的名称;遵循标准变量命名约定。 *arglist* : \[ **ByVal** | **ByRef** ] *varname* \[ **()** ] \[ **As** *type* ] **ByVal** : *可选* 指示参数按值传递。 **ByRef** : *可选* 指示参数按引用传递。**ByRef** 是默认方式,与Visual Basic .NET不同。 *varname* : 表示传递给过程的参数的变量名称;遵循标准变量命名约定。 *type* : *可选* 传递给过程的参数的数据类型;可以是Byte、Boolean、Integer、Long、Currency、Single、Double、Decimal、Date、String(仅限变长)、Object、Variant、用户自定义类型(UDT)或对象类型。 声明事件后,使用 [**RaiseEvent**](/official/Reference/Core/RaiseEvent) 语句触发事件。如果 **Event** 声明出现在标准模块中,将产生语法错误。事件不能声明为返回值。典型的事件声明和触发如下片段所示。 ```vb ' Declare an event at module level of a class module Event LogonCompleted (UserName as String) Sub RaiseEvent LogonCompleted("AntoineJan") End Sub ``` 事件参数的声明方式与过程参数相同,但有以下例外:事件不能有命名参数、**Optional** 参数或 **ParamArray** 参数。事件没有返回值。 ### 示例 以下示例使用事件在最快100米赛跑演示期间倒数秒数。代码说明了所有与事件相关的方法、属性和语句,包括 **Event** 语句。 引发事件的类是事件源,实现事件的类是接收器。一个事件源可以有多个接收器来处理它生成的事件。当类引发事件时,该事件会在每个选择接收该对象实例事件的类上触发。 示例还使用了包含按钮(`Command1`)、标签(`Label1`)和两个文本框(`Text1` 和 `Text2`)的窗体(`Form1`)。当按钮被点击时,第一个文本框显示"From Now",第二个文本框开始计数秒数。当完整时间(9.84秒)过去后,第一个文本框显示"Until Now",第二个显示"9.84"。 代码指定了窗体的初始和终止状态。还包含引发事件时执行的代码。 ```vb Class Form1 Option Explicit Private WithEvents mText As TimerState Private Sub Command1_Click() Text1.Text = "From Now" Text1.Refresh Text2.Text = "0" Text2.Refresh Call mText.TimerTask(9.84) End Sub Private Sub Form_Load() Command1.Caption = "Click to Start Timer" Text1.Text = "" Text2.Text = "" Label1.Caption = "The fastest 100 meter run took this long:" Set mText = New TimerState End Sub Private Sub mText_ChangeText() Text1.Text = "Until Now" Text2.Text = "9.84" End Sub Private Sub mText_UpdateTime(ByVal dblJump As Double) Text2.Text = Str(Format(dblJump, "0")) DoEvents End Sub End Class ``` 其余代码在名为TimerState的类模块中。**Event** 语句声明了事件引发时启动的过程。 ```vb Class TimerState Option Explicit Public Event UpdateTime(ByVal dblJump As Double) Public Event ChangeText() Public Sub TimerTask(ByVal Duration As Double) Dim dblStart As Double Dim dblSecond As Double Dim dblSoFar As Double dblStart = Timer dblSoFar = dblStart Do While Timer < dblStart + Duration If Timer - dblSoFar >= 1 Then dblSoFar = dblSoFar + 1 RaiseEvent UpdateTime(Timer - dblStart) End If Loop RaiseEvent ChangeText End Sub End Class ``` --- --- url: /en/official/Reference/WinEventLogLib/EventLog.md --- # EventLog class A generic class representing one Windows Event Log source. The type parameters supply the schema of events the source can report: *T1* is an enumeration of event IDs, *T2* is an enumeration of categories. Member names from those enums become the human-readable strings the Event Viewer shows. Syntax: **New EventLog(Of** *T1*, *T2* **)** ( *LogName* ) *T1* : *required* The enumeration type whose members name the event IDs this source can report. Passed as the *EventId* argument of [**LogSuccess**](#logsuccess) / [**LogFailure**](#logfailure). *T2* : *required* The enumeration type whose members name the categories events fall into. Passed as the *CategoryId* argument of [**LogSuccess**](#logsuccess) / [**LogFailure**](#logfailure). The number of categories declared in *T2* is what [**Register**](#register) writes as the registry's `CategoryCount`. *LogName* : *required* A **String** naming the event source. A leaf name like `"MyService"` is registered under the **Application** log (`Application\MyService`); a path like `"System\MyService"` is registered under the named parent log. The trailing segment is the source name --- it appears in the Event Viewer's **Source** column. ```vb Public Enum MyEventIds StartupOk = 1000 StartupFailed = 1001 End Enum Public Enum MyCategories General = 1 Network = 2 End Enum Dim Log As New EventLog(Of MyEventIds, MyCategories)("MyService") ``` Both type arguments are required at instantiation --- twinBASIC does not deduce them from the *LogName* constructor argument. See the [Generics](/en/official/Features/Language/Generics) page for the general rules. A class that needs to expose [**LogSuccess**](#logsuccess) / [**LogFailure**](#logfailure) / [**Register**](#register) as if those methods were its own can mix the **EventLog** members in through [**Implements ... Via**](/en/official/Features/Language/Inheritance) composition --- see the [composition-delegation idiom](/en/official/Reference/WinEventLogLib/#composition-delegation-idiom) section on the package overview for the canonical service-class pattern. The package [overview](/en/official/Reference/WinEventLogLib/) covers the install-then-log lifecycle, the [`[PopulateFrom("json", ...)]` message-resource convention](/en/official/Reference/WinEventLogLib/#populatefrom-convention), registry layout, and the [composition-delegation idiom](/en/official/Reference/WinEventLogLib/#composition-delegation-idiom). ## Methods ### LogFailure Writes an **Error**-type entry to the log. Syntax: *object*.**LogFailure** *EventId*, *CategoryId* \[, *AdditionalStrings* ... ] *EventId* : *required* A *T1* value naming the event being reported. Becomes the numeric **Event ID** column in the Event Viewer; the corresponding member name from *T1* is used to look up the message string. *CategoryId* : *required* A *T2* value naming the category the event belongs to. Becomes the numeric **Task Category** column. *AdditionalStrings* : *optional* A **ParamArray** of values inserted into the event's message string at the `%1`, `%2`, … placeholders. Each value is converted to a **String** before being passed to `ReportEventW`. ::: info Despite the name, **LogFailure** writes an **Error** entry --- the Windows event type `EVENTLOG_ERROR_TYPE` (= 1). It does *not* write an *Audit Failure* entry. That event type, and *Warning* and *Audit Success*, are not currently reachable through this class. ::: The first call after construction lazily resolves the source handle via `RegisterEventSourceW`; if [**Register**](#register) has not been run for this *LogName*, the entry is still written but the Event Viewer cannot resolve the message strings and shows *"The description for Event ID X cannot be found"*. ### LogSuccess Writes an **Information**-type entry to the log. Syntax: *object*.**LogSuccess** *EventId*, *CategoryId* \[, *AdditionalStrings* ... ] *EventId* : *required* A *T1* value naming the event being reported. Becomes the numeric **Event ID** column in the Event Viewer. *CategoryId* : *required* A *T2* value naming the category the event belongs to. *AdditionalStrings* : *optional* A **ParamArray** of values inserted into the event's message string at the `%1`, `%2`, … placeholders. ::: info The Windows event type for this call is `EVENTLOG_SUCCESS` (= 0), which is the Win32 SDK's literal name for the **Information** event type --- *not* an Audit Success entry. The class spells the method **LogSuccess** to track the SDK constant, but the entries that appear in `eventvwr.msc` are tagged **Information**. ::: ### New Constructs an **EventLog** instance bound to a single source name. Syntax: **New EventLog(Of** *T1*, *T2* **)** ( *LogName* ) *LogName* : *required* A **String** naming the source. See the top of this page for the leaf-name vs full-path syntax. The constructor only stores *LogName*. The first call to [**LogSuccess**](#logsuccess) / [**LogFailure**](#logfailure) lazily acquires the Win32 source handle via `RegisterEventSourceW`. [**Register**](#register) writes the registry entries the Event Viewer reads when rendering messages --- it must be run separately, once, with admin rights. ### Register Writes the registry entries that declare this EXE as the message provider for the source. Syntax: *object*.**Register** Creates `HKLM\SYSTEM\CurrentControlSet\Services\EventLog\<LogPath>` (prepending `Application\` if *LogName* is a leaf name) and writes: * **EventMessageFile** = `App.ModulePath` (the running EXE) * **CategoryMessageFile** = `App.ModulePath` * **CategoryCount** = the largest declared value in *T2*, resolved at compile time via [**GetDeclaredMaxEnumValue**](/en/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue)`(Of T2)` ::: warning **Register** requires administrator rights --- it writes to `HKEY_LOCAL_MACHINE`. The usual pattern is to call it once from an elevated installer, not from the application's normal startup path. ::: The Event Viewer renders message strings by loading **EventMessageFile** and looking up the message resource keyed by *EventId*. Because **EventMessageFile** points at `App.ModulePath`, the same EXE that calls **Register** must be the one that later calls [**LogSuccess**](#logsuccess) / [**LogFailure**](#logfailure); otherwise the Event Viewer cannot find the message strings. See [Message resources](/en/official/Reference/WinEventLogLib/#message-resources) and [The `[PopulateFrom("json", ...)]` convention](/en/official/Reference/WinEventLogLib/#populatefrom-convention) on the package landing page for the recommended way to populate the resource. If the registry key cannot be opened for write, **Register** raises run-time error 5 *"Failed to register event log source (`<LogName>`)"*. Typical causes are insufficient privileges and a *LogPath* that points at a non-existent parent log. The lower-level [**EventLogHelperPublic.RegisterEventLogInternal**](/en/official/Reference/WinEventLogLib/EventLogHelperPublic#registereventloginternal) is what **Register** delegates to; use it directly only when registering a source without binding it to a generic *T2* (and so without using **GetDeclaredMaxEnumValue** to derive the category count). ## See Also * [WinEventLogLib](/en/official/Reference/WinEventLogLib/) package -- overview, lifecycle, message-resource generation * [EventLogHelperPublic](/en/official/Reference/WinEventLogLib/EventLogHelperPublic) module -- the lower-level registration helper * [Generics](/en/official/Features/Language/Generics) feature -- syntax rules for generic class instantiation --- --- url: /zh/official/Reference/WinEventLogLib/EventLog.md --- # EventLog 类 表示一个Windows事件日志源的通用类。类型参数提供源可报告的事件架构:*T1* 是事件ID的枚举,*T2* 是类别的枚举。这些枚举的成员名称成为事件查看器显示的人类可读字符串。 语法:**New EventLog(Of** *T1*, *T2* **)** ( *LogName* ) *T1* : *必需* 其成员命名此源可报告的事件ID的枚举类型。作为 [**LogSuccess**](#logsuccess) / [**LogFailure**](#logfailure) 的 *EventId* 参数传递。 *T2* : *必需* 其成员命名事件所属类别的枚举类型。作为 [**LogSuccess**](#logsuccess) / [**LogFailure**](#logfailure) 的 *CategoryId* 参数传递。*T2* 中声明的类别数是 [**Register**](#register) 写入注册表 `CategoryCount` 的值。 *LogName* : *必需* 命名事件源的 **String**。叶名称如 `"MyService"` 注册在 **Application** 日志下(`Application\MyService`);路径如 `"System\MyService"` 注册在命名的父日志下。尾段是源名称——它出现在事件查看器的 **Source** 列中。 ```vb Public Enum MyEventIds StartupOk = 1000 StartupFailed = 1001 End Enum Public Enum MyCategories General = 1 Network = 2 End Enum Dim Log As New EventLog(Of MyEventIds, MyCategories)("MyService") ``` 两个类型参数在实例化时都是必需的——twinBASIC 不会从 *LogName* 构造函数参数推导它们。参见[泛型](/official/Features/Language/Generics)页面了解一般规则。 需要将 [**LogSuccess**](#logsuccess) / [**LogFailure**](#logfailure) / [**Register**](#register) 暴露为自身方法的类可以通过 [**Implements ... Via**](/official/Features/Language/Inheritance) 组合混入 **EventLog** 成员——参见包概述上的[组合委托惯用法](/official/Reference/WinEventLogLib/#composition-delegation-idiom)部分了解规范的服务类模式。 包[概述](/official/Reference/WinEventLogLib/)涵盖了先安装后记录的生命周期、[`[PopulateFrom("json", ...)]` 消息资源惯例](/official/Reference/WinEventLogLib/#populatefrom-convention)、注册表布局和[组合委托惯用法](/official/Reference/WinEventLogLib/#composition-delegation-idiom)。 ## 方法 ### LogFailure 向日志写入 **Error** 类型条目。 语法:*对象*.**LogFailure** *EventId*, *CategoryId* \[, *AdditionalStrings* ... ] *EventId* : *必需* 命名所报告事件的 *T1* 值。成为事件查看器中的数字 **Event ID** 列;使用 *T1* 中的对应成员名称查找消息字符串。 *CategoryId* : *必需* 命名事件所属类别的 *T2* 值。成为数字 **Task Category** 列。 *AdditionalStrings* : *可选* 在事件消息字符串的 `%1`、`%2`、… 占位符处插入的值的 **ParamArray**。每个值在传递给 `ReportEventW` 之前转换为 **String**。 ::: info 尽管名称如此,**LogFailure** 写入的是 **Error** 条目——Windows事件类型 `EVENTLOG_ERROR_TYPE`(= 1)。它*不是*写入审核失败条目。该事件类型以及 *Warning* 和 *Audit Success* 目前无法通过此类访问。 ::: 构造后的首次调用通过 `RegisterEventSourceW` 延迟解析源句柄;如果此 *LogName* 尚未运行 [**Register**](#register),条目仍然会被写入,但事件查看器无法解析消息字符串,显示 *"The description for Event ID X cannot be found"*。 ### LogSuccess 向日志写入 **Information** 类型条目。 语法:*对象*.**LogSuccess** *EventId*, *CategoryId* \[, *AdditionalStrings* ... ] *EventId* : *必需* 命名所报告事件的 *T1* 值。成为事件查看器中的数字 **Event ID** 列。 *CategoryId* : *必需* 命名事件所属类别的 *T2* 值。 *AdditionalStrings* : *可选* 在事件消息字符串的 `%1`、`%2`、… 占位符处插入的值的 **ParamArray**。 ::: info 此调用的Windows事件类型是 `EVENTLOG_SUCCESS`(= 0),这是Win32 SDK对 **Information** 事件类型的字面名称——*不是*审核成功条目。类将方法命名为 **LogSuccess** 以跟踪SDK常量,但 `eventvwr.msc` 中出现的条目标记为 **Information**。 ::: ### New 构造绑定到单个源名称的 **EventLog** 实例。 语法:**New EventLog(Of** *T1*, *T2* **)** ( *LogName* ) *LogName* : *必需* 命名源的 **String**。参见本页顶部了解叶名称与完整路径的语法。 构造函数仅存储 *LogName*。首次调用 [**LogSuccess**](#logsuccess) / [**LogFailure**](#logfailure) 时通过 `RegisterEventSourceW` 延迟获取Win32源句柄。[**Register**](#register) 写入事件查看器渲染消息时读取的注册表条目——必须单独运行一次,且需要管理员权限。 ### Register 写入将此EXE声明为源的消息提供程序的注册表条目。 语法:*对象*.**Register** 创建 `HKLM\SYSTEM\CurrentControlSet\Services\EventLog\<LogPath>`(如果 *LogName* 是叶名称则添加 `Application\` 前缀)并写入: * **EventMessageFile** = `App.ModulePath`(正在运行的EXE) * **CategoryMessageFile** = `App.ModulePath` * **CategoryCount** = *T2* 中声明的最大值,在编译时通过 [**GetDeclaredMaxEnumValue**](/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue)`(Of T2)` 解析 ::: warning **Register** 需要管理员权限——它写入 `HKEY_LOCAL_MACHINE`。通常的做法是从提升的安装程序中调用一次,而不是从应用程序的正常启动路径中调用。 ::: 事件查看器通过加载 **EventMessageFile** 并按 *EventId* 键控查找消息资源来渲染消息字符串。由于 **EventMessageFile** 指向 `App.ModulePath`,调用 **Register** 的EXE必须是后来调用 [**LogSuccess**](#logsuccess) / [**LogFailure**](#logfailure) 的同一个;否则事件查看器找不到消息字符串。参见包着陆页上的[消息资源](/official/Reference/WinEventLogLib/#message-resources)和[`[PopulateFrom("json", ...)]` 惯例](/official/Reference/WinEventLogLib/#populatefrom-convention)了解填充资源的推荐方式。 如果注册表键无法打开以进行写入,**Register** 引发运行时错误5 *"Failed to register event log source (`<LogName>`)"*。典型原因是权限不足和 *LogPath* 指向不存在的父日志。 更底层的 [**EventLogHelperPublic.RegisterEventLogInternal**](/official/Reference/WinEventLogLib/EventLogHelperPublic#registereventloginternal) 是 **Register** 委托的对象;仅在不将源绑定到通用 *T2*(因此不使用 **GetDeclaredMaxEnumValue** 推导类别计数)的情况下注册源时直接使用。 ## 另见 * [WinEventLogLib](/official/Reference/WinEventLogLib/) 包 -- 概述、生命周期、消息资源生成 * [EventLogHelperPublic](/official/Reference/WinEventLogLib/EventLogHelperPublic) 模块 -- 更底层的注册辅助模块 * [泛型](/official/Features/Language/Generics) 功能 -- 泛型类实例化的语法规则 --- --- url: /en/official/Reference/WinEventLogLib/EventLogHelperPublic.md --- # EventLogHelperPublic module A single low-level helper that writes the registry entries Windows reads when rendering Event Log messages. Most projects do not call into this module directly --- [**EventLog.Register**](/en/official/Reference/WinEventLogLib/EventLog#register) wraps the call and automatically supplies the category count from the *T2* type argument. Use **EventLogHelperPublic** only when registering a source outside the generic [**EventLog**](/en/official/Reference/WinEventLogLib/EventLog) class (for example, when the category count cannot be derived from a declared enum). ## RegisterEventLogInternal Writes the registry entries that declare the running EXE as the message provider for an event source. Syntax: **EventLogHelperPublic.RegisterEventLogInternal** *LogPath*, *CategoryCount* *LogPath* : *required* A **String** naming the source. A leaf name like `"MyService"` is registered under the **Application** log (rewritten internally to `"Application\MyService"`); a full path like `"System\MyService"` is registered under the named parent log. The trailing segment is the source name displayed in the Event Viewer's **Source** column. *CategoryCount* : *required* A **Long** giving the number of categories declared for this source --- the largest value in the corresponding category enum. Stored as the registry's `CategoryCount` DWORD; the Event Viewer uses it to bound category-string lookups in the EXE's message-table resource. Creates `HKLM\SYSTEM\CurrentControlSet\Services\EventLog\<LogPath>` and writes: * **EventMessageFile** = `App.ModulePath` (the running EXE; **REG\_SZ**) * **CategoryMessageFile** = `App.ModulePath` (**REG\_SZ**) * **CategoryCount** = *CategoryCount* (**REG\_DWORD**) ::: warning **RegisterEventLogInternal** writes under `HKEY_LOCAL_MACHINE` and requires administrator rights. The usual pattern is to call it once from an elevated installer, not from the application's normal startup path. ::: If the registry key cannot be opened for write, **RegisterEventLogInternal** raises run-time error 5 with the message *"Failed to register event log source (`<LogName>`)"*, where `<LogName>` is the trailing segment of *LogPath*. Typical causes are insufficient privileges and a *LogPath* whose parent log (e.g. `"Application"`, `"System"`) does not exist. ## See Also * [WinEventLogLib](/en/official/Reference/WinEventLogLib/) package -- overview, lifecycle, message-resource generation * [EventLog](/en/official/Reference/WinEventLogLib/EventLog) class -- the generic class whose [**Register**](/en/official/Reference/WinEventLogLib/EventLog#register) method wraps this helper --- --- url: /zh/official/Reference/WinEventLogLib/EventLogHelperPublic.md --- # EventLogHelperPublic 模块 一个低级辅助模块,写入Windows在渲染事件日志消息时读取的注册表条目。大多数项目不直接调用此模块——[**EventLog.Register**](/official/Reference/WinEventLogLib/EventLog#register) 包装了该调用并自动从 *T2* 类型参数提供类别计数。仅在通用 [**EventLog**](/official/Reference/WinEventLogLib/EventLog) 类之外注册源时使用 **EventLogHelperPublic**(例如,当类别计数无法从声明的枚举推导时)。 ## RegisterEventLogInternal 写入将正在运行的EXE声明为事件源的消息提供程序的注册表条目。 语法:**EventLogHelperPublic.RegisterEventLogInternal** *LogPath*, *CategoryCount* *LogPath* : *必需* 命名源的 **String**。叶名称如 `"MyService"` 注册在 **Application** 日志下(内部重写为 `"Application\MyService"`);完整路径如 `"System\MyService"` 注册在命名的父日志下。尾段是事件查看器 **Source** 列中显示的源名称。 *CategoryCount* : *必需* 给出为此源声明的类别数的 **Long**——对应类别枚举中的最大值。存储为注册表的 `CategoryCount` DWORD;事件查看器使用它来限制在EXE的消息表资源中查找类别字符串的范围。 创建 `HKLM\SYSTEM\CurrentControlSet\Services\EventLog\<LogPath>` 并写入: * **EventMessageFile** = `App.ModulePath`(正在运行的EXE;**REG\_SZ**) * **CategoryMessageFile** = `App.ModulePath`(**REG\_SZ**) * **CategoryCount** = *CategoryCount*(**REG\_DWORD**) ::: warning **RegisterEventLogInternal** 写入 `HKEY_LOCAL_MACHINE`,需要管理员权限。通常的做法是从提升的安装程序中调用一次,而不是从应用程序的正常启动路径中调用。 ::: 如果注册表键无法打开以进行写入,**RegisterEventLogInternal** 引发运行时错误5,消息为 *"Failed to register event log source (`<LogName>`)"*,其中 `<LogName>` 是 *LogPath* 的尾段。典型原因是权限不足和 *LogPath* 的父日志(例如 `"Application"`、`"System"`)不存在。 ## 另见 * [WinEventLogLib](/official/Reference/WinEventLogLib/) 包 -- 概述、生命周期、消息资源生成 * [EventLog](/official/Reference/WinEventLogLib/EventLog) 类 -- 其 [**Register**](/official/Reference/WinEventLogLib/EventLog#register) 方法包装了此辅助模块的通用类 --- --- url: /en/official/Reference/Assert/Exact.md --- # Exact module The **Exact** module of the [**Assert**](/en/official/Reference/Assert/) package supplies assertions with the strictest possible comparison semantics. String comparisons are case-sensitive; numeric values must match in datatype as well as value (so `5` is not equal to `5.0`); `vbNullString` is distinct from `""`; `Empty` is distinct from `0`, `False`, `""`, and `vbNullString`; and object default members are not evaluated. **Exact** flags any kind of implicit conversion or coercion in the values being tested. ## Comparison semantics The four equality assertions in this module --- [**AreEqual**](#areequal), [**AreNotEqual**](#arenotequal), [**SequenceEquals**](#sequenceequals), and [**NotSequenceEquals**](#notsequenceequals) --- apply the rules listed below. The remaining assertions are unaffected. * *String* comparisons are case-sensitive (regardless of the project's `Option Compare` setting). * The datatype of the compared values must match exactly. `Long` and `Double`, `Long` and `Currency`, and `Integer` and `Long` are all considered different. * `vbNullString` and a zero-length **String** (`""`) are considered different. * `Empty` is considered different from `0`, `False`, `""`, and `vbNullString`. * Object references are compared by identity (the **Is** operator); default-member values are not retrieved. * `Null` is never equal to anything, not even to itself --- use [**IsNull**](#isnull) / [**IsNotNull**](#isnotnull) to test for it. ```vb ' All of these fail under Exact: Exact.AreEqual 5, 5.0 ' Long vs Double — datatypes differ Exact.AreEqual vbNullString, "" ' the two empty-string forms are distinct Exact.AreEqual Empty, 0 ' Empty is distinct from 0 Exact.AreEqual "Hello", "hello" ' case-sensitive ``` ## Diagnostic outcome ### Succeed Records that the test reached this point without failure. Syntax: **Exact.Succeed** A test procedure that returns without any assertion having failed is reported as passing implicitly, so calling **Succeed** explicitly is rarely necessary. It is occasionally useful in branches that would otherwise look ambiguous about their outcome --- for example, the body of a loop that should reach the end. ### Fail Unconditionally records a test failure. Syntax: **Exact.Fail** \[ *Message* ] *Message* : *optional* A **String** describing the failure, recorded together with the source location of the call. **Fail** marks code paths that should be unreachable in a passing test --- most often after a call that is expected to raise an error, in a branch that runs when the call returned normally instead. ```vb On Error Resume Next target.SomethingThatShouldRaise If Err.Number = 0 Then Exact.Fail "expected an error, got success" ``` ### Inconclusive Records the test as inconclusive --- neither a pass nor a failure. Syntax: **Exact.Inconclusive** \[ *Message* ] *Message* : *optional* A **String** describing why the result is inconclusive. **Inconclusive** records that a precondition for the test could not be established and the assertion logic that follows would be meaningless. A common case is a setup step that failed to find a required external resource --- a test database, a configured network endpoint --- where the test itself is neither passing nor failing on its own merits. ## Equality ### AreEqual Asserts that *Actual* is equal to *Expected*. Syntax: **Exact.AreEqual** *Expected*, *Actual* \[, *Message* ] *Expected* : *required* A **Variant** holding the expected value. *Actual* : *required* A **Variant** holding the value produced by the code under test. *Message* : *optional* A **String** included in the failure record if the comparison fails. The comparison follows this module's [comparison semantics](#comparison-semantics) --- *Expected* and *Actual* must have the same datatype, strings are compared case-sensitively, and `Empty`, `vbNullString`, and `""` are all distinct from one another. If either operand is **Null**, the assertion fails --- `Null` is never equal to anything; use [**IsNull**](#isnull) to test for **Null** explicitly. ### AreNotEqual Asserts that *Actual* is not equal to *Expected*. Syntax: **Exact.AreNotEqual** *Expected*, *Actual* \[, *Message* ] *Expected* : *required* A **Variant** holding a value that *Actual* must differ from. *Actual* : *required* A **Variant** holding the value produced by the code under test. *Message* : *optional* A **String** included in the failure record if the values are equal. Comparison uses this module's [comparison semantics](#comparison-semantics). If either operand is **Null**, the assertion passes --- `Null` is never equal to anything. ### AreSame Asserts that *Actual* and *Expected* refer to the *same* object --- equivalent to `Expected Is Actual`. Syntax: **Exact.AreSame** *Expected*, *Actual* \[, *Message* ] *Expected* : *required* A **Variant** holding the expected object reference. *Actual* : *required* A **Variant** holding the reference produced by the code under test. *Message* : *optional* A **String** included in the failure record if the references differ. Reference identity is independent of the module's other comparison rules --- **AreSame** always uses the **Is** operator, never default-member equality. To compare values rather than references, use [**AreEqual**](#areequal). ### AreNotSame Asserts that *Actual* and *Expected* refer to *different* objects --- equivalent to `Expected IsNot Actual`. Syntax: **Exact.AreNotSame** *Expected*, *Actual* \[, *Message* ] *Expected* : *required* A **Variant** holding a reference that *Actual* must differ from. *Actual* : *required* A **Variant** holding the reference produced by the code under test. *Message* : *optional* A **String** included in the failure record if the references are the same. ## Boolean ### IsTrue Asserts that *Condition* evaluates to **True**. Syntax: **Exact.IsTrue** *Condition* \[, *Message* ] *Condition* : *required* A **Variant** holding the condition to test. The value is interpreted as a **Boolean** --- zero is **False**, any non-zero value is **True**. *Message* : *optional* A **String** included in the failure record if the condition is **False**. If *Condition* is **Null**, the assertion fails. ### IsFalse Asserts that *Condition* evaluates to **False**. Syntax: **Exact.IsFalse** *Condition* \[, *Message* ] *Condition* : *required* A **Variant** holding the condition to test. Zero is **False**, any non-zero value is **True**. *Message* : *optional* A **String** included in the failure record if the condition is **True**. If *Condition* is **Null**, the assertion fails --- `Null` is neither **True** nor **False**. ## Reference and value state ### IsNothing Asserts that *Value* is the **Nothing** object reference. Syntax: **Exact.IsNothing** *Value* \[, *Message* ] *Value* : *required* A **Variant** holding the object reference to test. *Message* : *optional* A **String** included in the failure record if *Value* refers to an object. This is the object-reference test, equivalent to `Value Is Nothing`. To check for the **Null** value of a **Variant** instead, use [**IsNull**](#isnull). ### IsNotNothing Asserts that *Value* refers to an object --- i.e. is *not* the **Nothing** reference. Syntax: **Exact.IsNotNothing** *Value* \[, *Message* ] *Value* : *required* A **Variant** holding the object reference to test. *Message* : *optional* A **String** included in the failure record if *Value* is **Nothing**. ### IsNull Asserts that *Value* is the **Null** value of a **Variant**. Syntax: **Exact.IsNull** *Value* \[, *Message* ] *Value* : *required* A **Variant** holding the value to test. *Message* : *optional* A **String** included in the failure record if *Value* is not **Null**. Equivalent to checking [**IsNull**](/en/official/Reference/VBA/Information/IsNull)`(Value) = True`. To check for the **Nothing** object reference instead, use [**IsNothing**](#isnothing). ### IsNotNull Asserts that *Value* is not the **Null** value of a **Variant**. Syntax: **Exact.IsNotNull** *Value* \[, *Message* ] *Value* : *required* A **Variant** holding the value to test. *Message* : *optional* A **String** included in the failure record if *Value* is **Null**. ## Sequence ### SequenceEquals Asserts that *Actual* and *Expected* contain the same number of elements, in the same order, with each pair of elements equal under this module's [comparison semantics](#comparison-semantics). Syntax: **Exact.SequenceEquals** *Expected*, *Actual* \[, *FailMessage* ] *Expected* : *required* A **Variant** holding an array, **Collection**, or other enumerable value. *Actual* : *required* A **Variant** holding the sequence produced by the code under test. *FailMessage* : *optional* A **String** included in the failure record if the sequences differ. Both arguments must support iteration via **For Each**. The assertion fails on the first mismatched pair, on a length difference, or if one side is empty while the other is not. Element comparison uses the same per-pair rules as [**AreEqual**](#areequal), so under **Exact** the elements must additionally match in datatype. ### NotSequenceEquals Asserts that *Actual* and *Expected* differ --- they contain a different number of elements, or at least one pair of corresponding elements differs under this module's [comparison semantics](#comparison-semantics). Syntax: **Exact.NotSequenceEquals** *Expected*, *Actual* \[, *FailMessage* ] *Expected* : *required* A **Variant** holding an array, **Collection**, or other enumerable value. *Actual* : *required* A **Variant** holding the sequence produced by the code under test. *FailMessage* : *optional* A **String** included in the failure record if the sequences are equal. ## See Also * [Strict](/en/official/Reference/Assert/Strict) -- case-sensitive strings, but otherwise behaves like a direct comparison in twinBASIC code * [Permissive](/en/official/Reference/Assert/Permissive) -- case-insensitive strings; otherwise behaves like a direct comparison in twinBASIC code * [Assert package](/en/official/Reference/Assert/) -- overview of all three modules and the comparison-semantics table --- --- url: /zh/official/Reference/Assert/Exact.md --- # Exact 模块 [**Assert**](/official/Reference/Assert/) 包的 **Exact** 模块提供具有最严格比较语义的断言。字符串比较区分大小写;数值必须在数据类型和值上都匹配(因此 `5` 不等于 `5.0`);`vbNullString` 与 `""` 不同;`Empty` 与 `0`、`False`、`""` 和 `vbNullString` 不同;不评估对象默认成员。**Exact** 会标记被测试值中任何形式的隐式转换或强制转换。 ## 比较语义 此模块中的四个相等性断言---[**AreEqual**](#areequal)、[**AreNotEqual**](#arenotequal)、[**SequenceEquals**](#sequenceequals) 和 [**NotSequenceEquals**](#notsequenceequals)---应用以下规则。其余断言不受影响。 * *字符串*比较区分大小写(无论项目的 `Option Compare` 设置如何)。 * 被比较值的数据类型必须完全匹配。`Long` 和 `Double`、`Long` 和 `Currency`、`Integer` 和 `Long` 都被视为不同。 * `vbNullString` 和零长度 **String**(`""`)被视为不同。 * `Empty` 被视为与 `0`、`False`、`""` 和 `vbNullString` 不同。 * 对象引用按标识(**Is** 运算符)比较;不检索默认成员值。 * `Null` 永远不等于任何值,甚至不等于自身---使用 [**IsNull**](#isnull) / [**IsNotNull**](#isnotnull) 来测试它。 ```vb ' 在 Exact 下以下全部失败: Exact.AreEqual 5, 5.0 ' Long 对 Double — 数据类型不同 Exact.AreEqual vbNullString, "" ' 两种空字符串形式是不同的 Exact.AreEqual Empty, 0 ' Empty 与 0 不同 Exact.AreEqual "Hello", "hello" ' 区分大小写 ``` ## 诊断结果 ### Succeed 记录测试已到达此点而未失败。 语法:**Exact.Succeed** 返回时没有任何断言失败的测试过程隐式报告为通过,因此显式调用 **Succeed** 很少有必要。偶尔用于结果看起来可能模糊的分支---例如,应该到达末尾的循环体。 ### Fail 无条件记录测试失败。 语法:**Exact.Fail** \[ *Message* ] *Message* : *可选* 一个 **String**,描述失败,与调用的源位置一起记录。 **Fail** 标记在通过测试中不应可达的代码路径---最常见的是在预期引发错误的调用之后,在调用正常返回时运行的分支中。 ```vb On Error Resume Next target.SomethingThatShouldRaise If Err.Number = 0 Then Exact.Fail "expected an error, got success" ``` ### Inconclusive 将测试记录为不确定---既非通过也非失败。 语法:**Exact.Inconclusive** \[ *Message* ] *Message* : *可选* 一个 **String**,描述结果不确定的原因。 **Inconclusive** 记录测试的前提条件无法建立,后续的断言逻辑将没有意义。常见情况是设置步骤未能找到所需的外部资源---测试数据库、已配置的网络端点---此时测试本身既非凭自身优点通过也非失败。 ## 相等性 ### AreEqual 断言 *Actual* 等于 *Expected*。 语法:**Exact.AreEqual** *Expected*, *Actual* \[, *Message* ] *Expected* : *必需* 一个 **Variant**,持有预期值。 *Actual* : *必需* 一个 **Variant**,持有被测代码产生的值。 *Message* : *可选* 一个 **String**,在比较失败时包含在失败记录中。 比较遵循此模块的[比较语义](#comparison-semantics)---*Expected* 和 *Actual* 必须具有相同的数据类型,字符串区分大小写比较,`Empty`、`vbNullString` 和 `""` 彼此不同。如果任一操作数为 **Null**,断言失败---`Null` 永远不等于任何值;使用 [**IsNull**](#isnull) 显式测试 **Null**。 ### AreNotEqual 断言 *Actual* 不等于 *Expected*。 语法:**Exact.AreNotEqual** *Expected*, *Actual* \[, *Message* ] *Expected* : *必需* 一个 **Variant**,持有 *Actual* 必须与之不同的值。 *Actual* : *必需* 一个 **Variant**,持有被测代码产生的值。 *Message* : *可选* 一个 **String**,在值相等时包含在失败记录中。 比较使用此模块的[比较语义](#comparison-semantics)。如果任一操作数为 **Null**,断言通过---`Null` 永远不等于任何值。 ### AreSame 断言 *Actual* 和 *Expected* 引用*同一*对象---等同于 `Expected Is Actual`。 语法:**Exact.AreSame** *Expected*, *Actual* \[, *Message* ] *Expected* : *必需* 一个 **Variant**,持有预期的对象引用。 *Actual* : *必需* 一个 **Variant**,持有被测代码产生的引用。 *Message* : *可选* 一个 **String**,在引用不同时包含在失败记录中。 引用标识与模块的其他比较规则无关---**AreSame** 始终使用 **Is** 运算符,从不使用默认成员相等性。要比较值而非引用,请使用 [**AreEqual**](#areequal)。 ### AreNotSame 断言 *Actual* 和 *Expected* 引用*不同*的对象---等同于 `Expected IsNot Actual`。 语法:**Exact.AreNotSame** *Expected*, *Actual* \[, *Message* ] *Expected* : *必需* 一个 **Variant**,持有 *Actual* 必须与之不同的引用。 *Actual* : *必需* 一个 **Variant**,持有被测代码产生的引用。 *Message* : *可选* 一个 **String**,在引用相同时包含在失败记录中。 ## 布尔 ### IsTrue 断言 *Condition* 求值为 **True**。 语法:**Exact.IsTrue** *Condition* \[, *Message* ] *Condition* : *必需* 一个 **Variant**,持有要测试的条件。值被解释为 **Boolean**---零为 **False**,任何非零值为 **True**。 *Message* : *可选* 一个 **String**,在条件为 **False** 时包含在失败记录中。 如果 *Condition* 为 **Null**,断言失败。 ### IsFalse 断言 *Condition* 求值为 **False**。 语法:**Exact.IsFalse** *Condition* \[, *Message* ] *Condition* : *必需* 一个 **Variant**,持有要测试的条件。零为 **False**,任何非零值为 **True**。 *Message* : *可选* 一个 **String**,在条件为 **True** 时包含在失败记录中。 如果 *Condition* 为 **Null**,断言失败---`Null` 既非 **True** 也非 **False**。 ## 引用和值状态 ### IsNothing 断言 *Value* 是 **Nothing** 对象引用。 语法:**Exact.IsNothing** *Value* \[, *Message* ] *Value* : *必需* 一个 **Variant**,持有要测试的对象引用。 *Message* : *可选* 一个 **String**,在 *Value* 引用对象时包含在失败记录中。 这是对象引用测试,等同于 `Value Is Nothing`。要改为检查 **Variant** 的 **Null** 值,请使用 [**IsNull**](#isnull)。 ### IsNotNothing 断言 *Value* 引用对象---即*不是* **Nothing** 引用。 语法:**Exact.IsNotNothing** *Value* \[, *Message* ] *Value* : *必需* 一个 **Variant**,持有要测试的对象引用。 *Message* : *可选* 一个 **String**,在 *Value* 为 **Nothing** 时包含在失败记录中。 ### IsNull 断言 *Value* 是 **Variant** 的 **Null** 值。 语法:**Exact.IsNull** *Value* \[, *Message* ] *Value* : *必需* 一个 **Variant**,持有要测试的值。 *Message* : *可选* 一个 **String**,在 *Value* 不是 **Null** 时包含在失败记录中。 等同于检查 [**IsNull**](/official/Reference/VBA/Information/IsNull)`(Value) = True`。要改为检查 **Nothing** 对象引用,请使用 [**IsNothing**](#isnothing)。 ### IsNotNull 断言 *Value* 不是 **Variant** 的 **Null** 值。 语法:**Exact.IsNotNull** *Value* \[, *Message* ] *Value* : *必需* 一个 **Variant**,持有要测试的值。 *Message* : *可选* 一个 **String**,在 *Value* 为 **Null** 时包含在失败记录中。 ## 序列 ### SequenceEquals 断言 *Actual* 和 *Expected* 包含相同数量的元素,顺序相同,且每对元素在此模块的[比较语义](#comparison-semantics)下相等。 语法:**Exact.SequenceEquals** *Expected*, *Actual* \[, *FailMessage* ] *Expected* : *必需* 一个 **Variant**,持有数组、**Collection** 或其他可枚举值。 *Actual* : *必需* 一个 **Variant**,持有被测代码产生的序列。 *FailMessage* : *可选* 一个 **String**,在序列不同时包含在失败记录中。 两个参数都必须支持通过 **For Each** 迭代。断言在第一对不匹配时、长度不同时或一方为空而另一方不为空时失败。元素比较使用与 [**AreEqual**](#areequal) 相同的逐对规则,因此在 **Exact** 下元素还必须在数据类型上匹配。 ### NotSequenceEquals 断言 *Actual* 和 *Expected* 不同---它们包含不同数量的元素,或至少有一对对应元素在此模块的[比较语义](#comparison-semantics)下不同。 语法:**Exact.NotSequenceEquals** *Expected*, *Actual* \[, *FailMessage* ] *Expected* : *必需* 一个 **Variant**,持有数组、**Collection** 或其他可枚举值。 *Actual* : *必需* 一个 **Variant**,持有被测代码产生的序列。 *FailMessage* : *可选* 一个 **String**,在序列相等时包含在失败记录中。 ## 另见 * [Strict](/official/Reference/Assert/Strict) -- 区分大小写字符串,但其他方面与 twinBASIC 代码中的直接比较行为一致 * [Permissive](/official/Reference/Assert/Permissive) -- 不区分大小写字符串;其他方面与 twinBASIC 代码中的直接比较行为一致 * [Assert 包](/official/Reference/Assert/) -- 所有三个模块的概述和比较语义表 --- --- url: /en/official/Reference/VBA/Collection/Exists.md --- # Exists Returns **True** if a specified key exists in a **Collection** object; **False** if it does not. Syntax: *object*.**Exists(** *key* **)** *object* : *required* An object expression that evaluates to a **Collection** object. *key* : *required* A **String** value identifying the item to locate in the collection. ::: info **Exists** is a twinBASIC extension; the classic VBA **Collection** object has no **Exists** method. The same effect in VBA requires calling [**Item**](/en/official/Reference/VBA/Collection/Item) inside an error-handling block. ::: Key comparison is governed by the [**KeyCompareMode**](/en/official/Reference/VBA/Collection/KeyCompareMode) property. ### Example ```vb Dim MyCollection As New Collection MyCollection.Add "alpha", Key:="a" MyCollection.Add "beta", Key:="b" If MyCollection.Exists("a") Then Debug.Print "Key 'a' is in the collection." End If If Not MyCollection.Exists("z") Then Debug.Print "Key 'z' is not in the collection." End If ``` ### See Also * [Add](/en/official/Reference/VBA/Collection/Add) method * [Item](/en/official/Reference/VBA/Collection/Item) method * [Keys](/en/official/Reference/VBA/Collection/Keys) method * [KeyCompareMode](/en/official/Reference/VBA/Collection/KeyCompareMode) property --- --- url: /zh/official/Reference/VBA/Collection/Exists.md --- # Exists 如果指定的键存在于 **Collection** 对象中,则返回 **True**;否则返回 **False**。 语法:*object*.**Exists(** *key* **)** *object* : *必需* 一个计算结果为 **Collection** 对象的对象表达式。 *key* : *必需* 一个 **String** 值,标识要在集合中查找的项。 ::: info **Exists** 是 twinBASIC 扩展;经典 VBA 的 **Collection** 对象没有 **Exists** 方法。在 VBA 中要实现相同效果,需要在错误处理块中调用 [**Item**](/official/Reference/VBA/Collection/Item)。 ::: 键比较由 [**KeyCompareMode**](/official/Reference/VBA/Collection/KeyCompareMode) 属性控制。 ### 示例 ```vb Dim MyCollection As New Collection MyCollection.Add "alpha", Key:="a" MyCollection.Add "beta", Key:="b" If MyCollection.Exists("a") Then Debug.Print "Key 'a' is in the collection." End If If Not MyCollection.Exists("z") Then Debug.Print "Key 'z' is not in the collection." End If ``` ### 另请参阅 * [Add](/official/Reference/VBA/Collection/Add) 方法 * [Item](/official/Reference/VBA/Collection/Item) 方法 * [Keys](/official/Reference/VBA/Collection/Keys) 方法 * [KeyCompareMode](/official/Reference/VBA/Collection/KeyCompareMode) 属性 --- --- url: /en/official/Reference/Core/Exit.md --- # Exit Exits a block of **Do…Loop**, **For…Next**, **While...Wend**, **Function**, **Sub**, or **Property** code. Syntax: * **Exit Do**\ Provides a way to exit a **[Do...Loop](/en/official/Reference/Core/Do-Loop)** statement. It can be used only inside a **Do...Loop** statement. **Exit Do** transfers control to the statement following the **Loop** statement. When used within nested **Do...Loop** statements, **Exit Do** transfers control to the loop that is one nested level above the loop where **Exit Do** occurs. * **Exit For**\ Provides a way to exit a **For** loop. It can be used only in a **[For...Next](/en/official/Reference/Core/For-Next)** or **[For Each...Next](/en/official/Reference/Core/For-Next)** loop. **Exit For** transfers control to the statement following the **Next** statement. When used within nested **For** loops, **Exit For** transfers control to the loop that is one nested level above the loop where **Exit For** occurs. * **Exit While**\ Provides a way to exit a **[While...Wend](/en/official/Reference/Core/While-Wend)** loop. It can be used only inside a **While...Wend** statement. **Exit While** transfers control to the statement following the **Wend** statement. When used within nested **While...Wend** statements, **Exit While** transfers control to the loop that is one nested level above the loop where **Exit While** occurs. **Exit While** is a twinBASIC extension; classic VBA has no early-exit form for **While...Wend**. * **Exit Function**\ Immediately exits the **[Function](/en/official/Reference/Core/Function)** procedure in which it appears. Execution continues with the statement following the statement that called the **Function**. * **Exit Property**\ Immediately exits the **[Property](/en/official/Reference/Core/Property)** procedure in which it appears. Execution continues with the statement following the statement that called the **Property** procedure. * **Exit Sub**\ Immediately exits the **[Sub](/en/official/Reference/Core/Sub)** procedure in which it appears. Execution continues with the statement following the statement that called the **Sub** procedure. Do not confuse **Exit** statements with **End** statements. **Exit** does not define the end of a structure. ### Example This example uses the **Exit** statement to exit a **For...Next** loop, a **Do...Loop**, and a **Sub** procedure. ```vb Sub ExitStatementDemo() Dim I%, MyNum% Do ' Set up infinite loop. For I = 1 To 1000 ' Loop 1000 times. MyNum = Int(Rnd * 1000) ' Generate random numbers. Select Case MyNum ' Evaluate random number. Case 7: Exit For ' If 7, exit For...Next. Case 29: Exit Do ' If 29, exit Do...Loop. Case 54: Exit Sub ' If 54, exit Sub procedure. End Select Next I Loop End Sub ``` --- --- url: /zh/official/Reference/Core/Exit.md --- # Exit 退出 **Do…Loop**、**For…Next**、**While...Wend**、**Function**、**Sub** 或 **Property** 代码块。 语法: * **Exit Do**\ 提供退出 **[Do...Loop](/official/Reference/Core/Do-Loop)** 语句的方式。只能在 **Do...Loop** 语句内使用。**Exit Do** 将控制权转移到 **Loop** 语句之后的语句。在嵌套的 **Do...Loop** 语句中使用时,**Exit Do** 将控制权转移到比出现 **Exit Do** 的循环高一层嵌套的循环。 * **Exit For**\ 提供退出 **For** 循环的方式。只能在 **[For...Next](/official/Reference/Core/For-Next)** 或 **[For Each...Next](/official/Reference/Core/For-Next)** 循环中使用。**Exit For** 将控制权转移到 **Next** 语句之后的语句。在嵌套的 **For** 循环中使用时,**Exit For** 将控制权转移到比出现 **Exit For** 的循环高一层嵌套的循环。 * **Exit While**\ 提供退出 **[While...Wend](/official/Reference/Core/While-Wend)** 循环的方式。只能在 **While...Wend** 语句内使用。**Exit While** 将控制权转移到 **Wend** 语句之后的语句。在嵌套的 **While...Wend** 语句中使用时,**Exit While** 将控制权转移到比出现 **Exit While** 的循环高一层嵌套的循环。**Exit While** 是twinBASIC扩展;经典VBA没有 **While...Wend** 的提前退出形式。 * **Exit Function**\ 立即退出出现它的 **[Function](/official/Reference/Core/Function)** 过程。执行继续到调用 **Function** 的语句之后的语句。 * **Exit Property**\ 立即退出出现它的 **[Property](/official/Reference/Core/Property)** 过程。执行继续到调用 **Property** 过程的语句之后的语句。 * **Exit Sub**\ 立即退出出现它的 **[Sub](/official/Reference/Core/Sub)** 过程。执行继续到调用 **Sub** 过程的语句之后的语句。 不要将 **Exit** 语句与 **End** 语句混淆。**Exit** 不定义结构的结束。 ### 示例 本示例使用 **Exit** 语句退出 **For...Next** 循环、**Do...Loop** 和 **Sub** 过程。 ```vb Sub ExitStatementDemo() Dim I%, MyNum% Do ' Set up infinite loop. For I = 1 To 1000 ' Loop 1000 times. MyNum = Int(Rnd * 1000) ' Generate random numbers. Select Case MyNum ' Evaluate random number. Case 7: Exit For ' If 7, exit For...Next. Case 29: Exit Do ' If 29, exit Do...Loop. Case 54: Exit Sub ' If 54, exit Sub procedure. End Select Next I Loop End Sub ``` --- --- url: /en/official/Reference/VBA/Math/Exp.md --- # Exp Returns a **Double** specifying *e* (the base of natural logarithms) raised to a power. Syntax: **Exp(** *number* **)** *number* : *required* A **Double** or any valid numeric expression. If the value of *number* exceeds 709.782712893, an error occurs. The constant *e* is approximately 2.718282. ::: info The **Exp** function complements the action of the [**Log**](/en/official/Reference/VBA/Math/Log) function and is sometimes referred to as the antilogarithm. ::: ### Example This example uses the **Exp** function to return *e* raised to a power. ```vb Dim MyAngle, MyHSin ' Define angle in radians. MyAngle = 1.3 ' Calculate hyperbolic sine. MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2 ``` ### See Also * [Log](/en/official/Reference/VBA/Math/Log) function --- --- url: /zh/official/Reference/VBA/Math/Exp.md --- # Exp 返回一个 **Double**,指定 *e*(自然对数的底)的指定幂次。 语法:**Exp(** *number* **)** *number* : *必需* **Double** 或任何有效的数值表达式。 如果 *number* 的值超过 709.782712893,将发生错误。常量 *e* 约为 2.718282。 ::: info **Exp** 函数补充 [**Log**](/official/Reference/VBA/Math/Log) 函数的操作,有时被称为反对数。 ::: ### 示例 此示例使用 **Exp** 函数返回 *e* 的指定幂次。 ```vb Dim MyAngle, MyHSin ' Define angle in radians. MyAngle = 1.3 ' Calculate hyperbolic sine. MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2 ``` ### 另请参阅 * [Log](/official/Reference/VBA/Math/Log) 函数 --- --- url: /en/official/Documentation/Extending.md --- # Extending the Builder How to add a new pipeline stage or a custom markdown-it plugin to `tbdocs`. This guide assumes working knowledge of modern JavaScript (async/await, ES modules) but not of the build pipeline internals. Read [Pipeline Stages](/en/official/Documentation/Pipeline-Stages) first for the data contracts each stage operates on. ## Two extension points **New pipeline stage** --- a new `.mjs` module that reads from the `pages` array or `site` object and writes output to disk or to page fields. The module exports one async function. The orchestrator in `tbdocs.mjs` calls it at the right point in the fixed sequence. No plugin registry or hook system is involved. **New markdown-it plugin** --- a function that configures the shared markdown-it instance with additional parsing or rendering rules. Registered in `createMarkdownIt` inside `render.mjs`. Both Phase 2's SEO title extraction and Phase 3's body render use the same instance, so the plugin runs on every page. ::: warning Stage module changes are not hot-reloaded. After editing a stage module, stop and restart `serve.bat` (Ctrl+C, then re-run) to load the change. ::: *** ## Adding a pipeline stage ### 1. Write the module Create `builder/my-stage.mjs`. Export one async function. The standard signature takes the `pages` array, the `site` object, and any additional context the stage needs (typically `destRoot`), and returns a stats object for logging: ```js import { writeFileMkdirp } from "./write.mjs"; import path from "node:path"; export async function myStage(pages, site, destRoot) { const manifest = pages.map((p) => ({ url: p.permalink, title: p.frontmatter.title ?? null, })); const dest = path.join(destRoot, "pages-manifest.json"); await writeFileMkdirp(dest, JSON.stringify(manifest, null, 2)); return { entries: manifest.length }; } ``` Use the I/O utilities exported by `write.mjs` --- `writeFileMkdirp`, `mkdirRec`, `runLimited`, `safeWrite` --- rather than raw `fs.writeFile` calls. They handle directory creation and include the destination path in error messages. ::: warning If the stage writes to disk, check `opts.dryRun` and skip all filesystem writes when it is `true`. The `dryRun` flag is passed through the same `opts` object the orchestrator receives and must propagate to all I/O operations. ::: If the stage writes new fields to page objects, add them at the point in `runBuild` where they first appear, and list them in the [data model table](/en/official/Documentation/Pipeline-Stages#page-objects-pages) in Pipeline Stages so other developers know which phase sets each field. ### 2. Register the stage in `tbdocs.mjs` Add an import at the top of `builder/tbdocs.mjs`: ```js import { myStage } from "./my-stage.mjs"; ``` Then call the stage in `runBuild` at the right position in the sequence. Most auxiliary stages belong after Phase 5 (write) and before Phase 7 (offline), so the online tree is complete when they run: ```js const myStats = await myStage(pages, site, destRoot); t.lap("my-stage"); if (myStats) { console.log(` my-stage: ${myStats.entries} entries`); } ``` `t.lap("my-stage")` records wall-clock time for the step; the label appears in the timing summary line at the end of the build. ### 3. Handle the `dryRun` flag When `dryRun` is `true`, the stage should log what it would do without touching the filesystem: ```js export async function myStage(pages, site, destRoot, { dryRun = false } = {}) { const manifest = pages.map((p) => ({ url: p.permalink, title: p.frontmatter.title ?? null, })); if (dryRun) { console.log(`[dry-run] my-stage: would write ${manifest.length} entries`); return { entries: manifest.length }; } const dest = path.join(destRoot, "pages-manifest.json"); await writeFileMkdirp(dest, JSON.stringify(manifest, null, 2)); return { entries: manifest.length }; } ``` ### 4. Verify Run `build.bat` and look for the timing label in the output. Then run `check.bat` to confirm the new output does not break existing link resolution or the page-count guard. *** ## Adding a markdown-it plugin ### Background `createMarkdownIt` in `render.mjs` builds the single markdown-it instance the entire pipeline uses. It applies `markdown-it-attrs`, `markdown-it-deflist`, `markdown-it-footnote`, and roughly ten in-tree plugins in a fixed order. A new plugin becomes part of that order. The same instance is used for Phase 2's SEO title extraction (via `renderTitle`) and Phase 3's body render (via `renderPhase`). A plugin that changes how inline content renders affects both passes. A block-level plugin that adds new tokens generally affects only Phase 3, since `renderTitle` strips all HTML. ### 1. Write the plugin A markdown-it plugin is a function that receives the `md` instance (and an optional options object) and mutates it by adding rules, overriding renderer functions, or adjusting options. **Renderer override example** --- wrap every `<table>` in a scrollable container: ```js export function tableWrapPlugin(md) { const originalOpen = md.renderer.rules.table_open ?? ((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options)); const originalClose = md.renderer.rules.table_close ?? ((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options)); md.renderer.rules.table_open = (tokens, idx, options, env, self) => '<div class="table-wrapper">' + originalOpen(tokens, idx, options, env, self); md.renderer.rules.table_close = (tokens, idx, options, env, self) => originalClose(tokens, idx, options, env, self) + "</div>"; } ``` **Block rule example** --- a new fenced syntax that emits a `<div class="callout">`: ```js export function calloutPlugin(md) { md.block.ruler.before( "fence", "callout", (state, startLine, endLine, silent) => { const pos = state.bMarks[startLine] + state.tShift[startLine]; const max = state.eMarks[startLine]; if (state.src.slice(pos, pos + 3) !== ":::") return false; if (silent) return true; const label = state.src.slice(pos + 3, max).trim(); state .push("callout_open", "div", 1) .attrSet("class", `callout callout-${label}`); state.line = startLine + 1; while (state.line < endLine) { if ( state.src.slice( state.bMarks[state.line] + state.tShift[state.line], state.eMarks[state.line], ) === ":::" ) { state.line++; break; } state.line++; } state.push("callout_close", "div", -1); return true; }, ); } ``` For the full markdown-it rule API --- block rules, inline rules, core rules, renderer rule overrides --- see the [markdown-it documentation](https://markdown-it.github.io/markdown-it/) and the existing in-tree plugins in `render.mjs` as worked examples. ### 2. Register in `render.mjs` Open `builder/render.mjs`. Add an import near the top of the file (alongside the other in-tree plugin imports): ```js import { tableWrapPlugin } from "./table-wrap-plugin.mjs"; ``` Find `createMarkdownIt` and add `md.use(tableWrapPlugin)` in the plugin chain. **Order matters** --- place the new plugin after any plugins it depends on, and before any plugins that may conflict with its token types: ```js export function createMarkdownIt(ctx) { const md = new MarkdownIt({ ... }); // ... existing npm plugins ... // ... existing in-tree plugins ... md.use(tableWrapPlugin); // new plugin, appended after existing ones return md; } ``` ### 3. Verify Run `build.bat` and open one of the affected pages in the browser (or use `serve.bat` for live reload). Then run `check.bat` to confirm no links are broken and the build exits cleanly. Watch Phase 3 timing in the console output --- a block rule that traverses the full token stream on every page can add measurable time to the ~1--2 s hot path. *** ## Testing both extension types The same four-step workflow applies to any change to the builder: 1. **`build.bat`** --- runs the full pipeline; a clean exit means no build-time errors. 2. **`serve.bat`** --- live-reload server; navigate to affected pages in the browser to spot visual regressions. 3. **`check.bat`** --- offline link and integrity check; catches broken links and missing pages introduced by the change. 4. **`book.bat`** --- re-runs the PDF build; required if the stage or plugin affects Phase 8 or the `book.html` output. A clean run of all four is the bar for "ready to commit". ::: info `check.bat` requires `build.bat` to have run first; it reads from `_site/` and `_site-offline/`. ::: *** ## See Also * [Pipeline Stages](/en/official/Documentation/Pipeline-Stages) -- full data model and export reference for every stage. * [tbdocs Builder](/en/official/Documentation/Builder) -- narrative design rationale for the pipeline. * [Building and Deployment](/en/official/Documentation/Building) -- the day-to-day build workflow for content contributors. --- --- url: /en/official/Features.md --- # Features This section documents all the features and enhancements that twinBASIC brings compared to VBx and earlier BASIC dialects. twinBASIC maintains backward compatibility with VBx syntax while providing these new features. Most enhancements are opt-in, allowing you to gradually adopt them in your projects. For detailed documentation on each feature, navigate to the specific category listed below. ## Categories ### [Attributes](/en/official/Features/Attributes-Intro) Attributes allow you to annotate Forms, Modules, Classes, Types, Enums, Declares, and procedures with compiler instructions and metadata. These are now visible directly in your code editor. ### [Language Syntax](/en/official/Features/Language/) twinBASIC introduces numerous language enhancements including: * New data types: **LongPtr**, **LongLong**, **Decimal**, * Native **Interface** and **CoClass** definitions, * OOP features with **Implements Via** and **Inherits,** * Generics and method overloading, * Enhanced operators and literals, * Type inference and pointer functionality, * UDT enhancements with methods and events. ### [Project Configuration](/en/official/Features/Project-Configuration/) twinBASIC offers various project types and configuration options: * Standard DLLs, Console applications, Services, and Kernel drivers * Compiler options for optimization and security * Entry point override and IAT placement * Registration options for ActiveX projects ### [Standard Library](/en/official/Features/Standard-Library/) Enhancements to the standard library include: * Full Unicode support throughout * File I/O with multiple encoding options * New built-in functions and App object properties * Direct COM error handling access * Destructuring assignment for arrays ### [GUI Components](/en/official/Features/GUI-Components/) Modernized GUI components featuring: * Enhanced forms with transparency and alpha blending * Control anchoring and docking * Windowed and windowless controls * 64-bit support and DPI awareness * New controls (QR Code, Multiframe, CheckMark) ### [Package Management](/en/official/Features/Packages/) twinBASIC\[^1] has a centralized package repository, called TWINSERV. Users can publish both public and private packages. Package browsing, downloading, and publishing is seamlessly integrated into the IDE. Packages are collections of components that can be referenced from another twinBASIC project. They are distributed as TWINPACK files that contains everything needed by the components in that package. \[^1]: A service of TWINBASIC LTD offered to the user community. ### [Advanced Features](/en/official/Features/Advanced/) Advanced programming capabilities: * Multithreading support via direct API calls * Direct assembly insertion with `Emit()` * Static linking of OBJ and LIB files * Enhanced API declarations (CDecl, variadic args, ByVal UDTs) * Parameterized constructors and class exports ### [Compiler and IDE Features](/en/official/Features/Compiler-IDE/) Improved development experience: * Compiler warnings and strict mode * Debug trace logger and stale pointer detection * CodeLens for running Subs directly * Modern IDE with themes, code folding, and more * Package server for code sharing ### [Fusion](/en/official/Features/Fusion) Fusion enables 64-bit applications to host 32-bit ActiveX controls (and vice versa) by transparently bridging them through an out-of-process host executable using IPC-based communication. ### [64bit Compilation](/en/official/Features/64bit) twinBASIC can compile native 64bit executables in addition to 32bit, using the **LongPtr** data type and **PtrSafe** keyword for API declarations. --- --- url: /en/official/IDE/Menu/File.md --- # File Menu ![File (Menu)](/assets/Menu_File.44veW5jh.png "File (Menu)") * New Project... CTRL + N * Open Project... CTRL + O * Open Recent... * Close Project *** * Save Project CTRL + S * Save Project As... *** * Export Project... * Save Current Document *** * Build * Clean *** * Exit ALT + F4 --- --- url: /en/official/Reference/tbIDE/File.md --- # File class A file inside the IDE's virtual file system. Extends [**FileSystemItem**](/en/official/Reference/tbIDE/FileSystemItem) with content accessors --- raw bytes via [**Data**](#data) / [**DataLen**](#datalen), a decoded text view via [**Text**](#text), a text-with-options accessor via [**ReadText**](#readtext), plus an [**IsDirty**](#isdirty) flag indicating unsaved changes. A **File** also inherits the universal [**FileSystemItem**](/en/official/Reference/tbIDE/FileSystemItem) members --- [**Name**](/en/official/Reference/tbIDE/FileSystemItem#name), [**Path**](/en/official/Reference/tbIDE/FileSystemItem#path), [**Type**](/en/official/Reference/tbIDE/FileSystemItem#type), [**Parent**](/en/official/Reference/tbIDE/FileSystemItem#parent). The [**Type**](/en/official/Reference/tbIDE/FileSystemItem#type) value tells the addin what encoding the file is in and whether the text accessors are applicable; see [**FileSystemItemType**](/en/official/Reference/tbIDE/FileSystemItem#filesystemitemtype) for the list. ```vb ' Read every source file's text: Private Sub WalkAllFiles(ByVal folder As Folder) Dim item As FileSystemItem For Each item In folder If TypeOf item Is Folder Then WalkAllFiles item Else Dim file As File = item If file.Type <> FileOTHER Then ProcessText file.Path, file.ReadText(ReadTextFlags.CommentsToWhitespace) End If End If Next End Sub ``` ::: info File **content is currently read-only** from the addin's perspective. The interface declares `Property Let` accessors for [**Data**](#data) and [**Text**](#text) but they are tagged `[Unimplemented]`. Use [**Editor.Save**](/en/official/Reference/tbIDE/Editor#save) on an active editor pane to persist text changes made through that pane, or [**CodeEditor.Text**](/en/official/Reference/tbIDE/CodeEditor#text) / [**CodeEditor.SelectedText**](/en/official/Reference/tbIDE/CodeEditor#selectedtext) for in-editor edits. ::: ## Properties ### Data The raw on-disk bytes of the file. Read returns a **Byte()** of the current content. The `Property Let` form is declared but marked `[Unimplemented]` --- writes are not currently supported. Syntax: *file*.**Data** **As Byte()** ### DataLen The length in bytes of the current content --- equivalent to `UBound(file.Data) + 1` but without copying the array. **LongLong**, read-only. Useful for size displays and quick file-size comparisons. ### IsDirty **True** if the file has unsaved changes in the IDE. **Boolean**, read-only. ### Text The file's content decoded as a **String**, with the appropriate UTF-16 conversion for the underlying encoding ([**FileTWIN**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileTWIN) → UTF-8 → UTF-16; [**FileBAS**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileBAS) / [**FileCLS**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileCLS) → System-ANSI → UTF-16; [**FileVIRTUALDOC**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileVIRTUALDOC) / [**FileUIDESIGNER**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileUIDESIGNER) / [**FileJSON**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileJSON) → UTF-8 → UTF-16). Calling on a [**FileOTHER**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileOTHER) is not supported. Read returns the decoded text. The `Property Let` form is declared but marked `[Unimplemented]` --- writes are not currently supported. Syntax: *file*.**Text** **As String** ## Methods ### ReadText A text-with-options accessor --- the [**Text**](#text) view, but with optional transforms applied. Currently the only option strips comments and replaces them with whitespace; future versions may add more. Syntax: *file*.**ReadText**( *Options* ) **As String** *Options* : *required* A [**ReadTextFlags**](#readtextflags) value. Pass `0` for raw text equivalent to reading [**Text**](#text); pass [**CommentsToWhitespace**](#ReadTextFlags_CommentsToWhitespace) to mask out comments while preserving line and column positions of every non-comment character. Valid on every text file kind ([**FileTWIN**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileTWIN), [**FileBAS**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileBAS), [**FileCLS**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileCLS), [**FileVIRTUALDOC**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileVIRTUALDOC), [**FileUIDESIGNER**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileUIDESIGNER), [**FileJSON**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileJSON)); calling on a [**FileOTHER**](/en/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileOTHER) is not supported. The line and column structure of the returned text matches the original file --- `CommentsToWhitespace` only blanks the comment characters, never moves the surrounding code. The option is therefore suitable for indexers / search tools that need both "find non-comment occurrences" and "report the position in the original file". ## ReadTextFlags The option flags consumed by [**ReadText**](#readtext). A `[Flags]`-tagged enum --- values can be `Or`'ed in future versions. | Constant | Value | Description | |----------|-------|-------------| | **CommentsToWhitespace** | 1 | Replace every byte that is part of a comment with a space. Line / column positions of every non-comment character are preserved. | --- --- url: /zh/official/Reference/tbIDE/File.md --- # File 类 IDE 虚拟文件系统中的文件。扩展 [**FileSystemItem**](/official/Reference/tbIDE/FileSystemItem),增加了内容访问器——通过 [**Data**](#data) / [**DataLen**](#datalen) 的原始字节、通过 [**Text**](#text) 的解码文本视图、通过 [**ReadText**](#readtext) 的带选项文本访问器,以及指示未保存更改的 [**IsDirty**](#isdirty) 标志。 **File** 还继承了通用的 [**FileSystemItem**](/official/Reference/tbIDE/FileSystemItem) 成员——[**Name**](/official/Reference/tbIDE/FileSystemItem#name)、[**Path**](/official/Reference/tbIDE/FileSystemItem#path)、[**Type**](/official/Reference/tbIDE/FileSystemItem#type)、[**Parent**](/official/Reference/tbIDE/FileSystemItem#parent)。[**Type**](/official/Reference/tbIDE/FileSystemItem#type) 值告诉插件文件使用什么编码以及文本访问器是否适用;参见 [**FileSystemItemType**](/official/Reference/tbIDE/FileSystemItem#filesystemitemtype) 的列表。 ```vb ' 读取每个源文件的文本: Private Sub WalkAllFiles(ByVal folder As Folder) Dim item As FileSystemItem For Each item In folder If TypeOf item Is Folder Then WalkAllFiles item Else Dim file As File = item If file.Type <> FileOTHER Then ProcessText file.Path, file.ReadText(ReadTextFlags.CommentsToWhitespace) End If End If Next End Sub ``` ::: info 文件**内容目前从插件角度是只读的**。接口声明了 [**Data**](#data) 和 [**Text**](#text) 的 `Property Let` 访问器,但它们标记为 `[Unimplemented]`。使用活动编辑器窗格上的 [**Editor.Save**](/official/Reference/tbIDE/Editor#save) 来持久保存通过该窗格所做的文本更改,或使用 [**CodeEditor.Text**](/official/Reference/tbIDE/CodeEditor#text) / [**CodeEditor.SelectedText**](/official/Reference/tbIDE/CodeEditor#selectedtext) 进行编辑器内编辑。 ::: ## 属性 ### Data 文件的原始磁盘字节。读取返回当前内容的 **Byte()**。`Property Let` 形式已声明但标记为 `[Unimplemented]`——当前不支持写入。 语法:*file*.**Data** **As Byte()** ### DataLen 当前内容的字节长度——等同于 `UBound(file.Data) + 1` 但无需复制数组。**LongLong**,只读。适用于大小显示和快速文件大小比较。 ### IsDirty 如果文件在 IDE 中有未保存的更改则为 **True**。**Boolean**,只读。 ### Text 文件内容解码为 **String**,根据底层编码进行适当的 UTF-16 转换([**FileTWIN**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileTWIN) → UTF-8 → UTF-16;[**FileBAS**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileBAS) / [**FileCLS**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileCLS) → 系统 ANSI → UTF-16;[**FileVIRTUALDOC**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileVIRTUALDOC) / [**FileUIDESIGNER**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileUIDESIGNER) / [**FileJSON**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileJSON) → UTF-8 → UTF-16)。对 [**FileOTHER**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileOTHER) 调用不受支持。 读取时返回解码文本。`Property Let` 形式已声明但标记为 `[Unimplemented]`——当前不支持写入。 语法:*file*.**Text** **As String** ## 方法 ### ReadText 带选项的文本访问器——[**Text**](#text) 视图,但应用了可选变换。当前唯一选项是去除注释并用空白替换;未来版本可能添加更多。 语法:*file*.**ReadText**( *Options* ) **As String** *Options* : *必需* 一个 [**ReadTextFlags**](#readtextflags) 值。传入 `0` 获取等同于读取 [**Text**](#text) 的原始文本;传入 [**CommentsToWhitespace**](#ReadTextFlags_CommentsToWhitespace) 以在保留每个非注释字符的行和列位置的同时屏蔽注释。 适用于所有文本文件类型([**FileTWIN**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileTWIN)、[**FileBAS**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileBAS)、[**FileCLS**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileCLS)、[**FileVIRTUALDOC**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileVIRTUALDOC)、[**FileUIDESIGNER**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileUIDESIGNER)、[**FileJSON**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileJSON));对 [**FileOTHER**](/official/Reference/tbIDE/FileSystemItem#FileSystemItemType_FileOTHER) 调用不受支持。 返回文本的行和列结构与原始文件匹配——`CommentsToWhitespace` 仅将注释字符空白化,从不移动周围的代码。因此该选项适用于需要同时"查找非注释出现"和"报告在原始文件中的位置"的索引器/搜索工具。 ## ReadTextFlags 由 [**ReadText**](#readtext) 消费的选项标志。标记为 `[Flags]` 的枚举——未来版本中值可以 `Or` 组合。 | 常量 | 值 | 描述 | |------|-----|------| | **CommentsToWhitespace** | 1 | 将注释中的每个字节替换为空格。每个非注释字符的行/列位置被保留。 | --- --- url: /en/official/Features/Standard-Library/File-IO.md --- # Encoding Options for File I/O The `Open` statement supports Unicode through the use of a new `Encoding` keyword and variable, and allows you to specify a wide range of encoding options in addition to standard Unicode options. ## Usage Example ```vb Open "C:\MyFile.txt" For Input Encoding utf_8 As #1 ``` ## Supported Encodings See the [Text Encodings table](/en/official/Reference/Core/Open#text-encodings) on the **Open** statement reference page. --- --- url: /en/official/Reference/VBA/FileSystem/FileAttr.md --- # FileAttr Returns a **Long** representing the file mode for files opened with the **Open** statement. Syntax: **FileAttr(** *filenumber* **,** *returntype* **)** *filenumber* : *required* **Integer** containing any valid file number. *returntype* : *required* **Integer** indicating the type of information to return. Must be **1** to return the file access mode. ### Return Values The following return values indicate the file access mode: | Mode | Value | |------------|:-----:| | **Input** | 1 | | **Output** | 2 | | **Random** | 4 | | **Append** | 8 | | **Binary** | 32 | ### Example This example uses the **FileAttr** function to return the file mode of an open file. ```vb Dim FileNum, Mode FileNum = 1 ' Assign file number. Open "TESTFILE" For Append As FileNum ' Open file. Mode = FileAttr(FileNum, 1) ' Returns 8 (Append file mode). Close FileNum ' Close file. ``` ### See Also * [LOF](/en/official/Reference/VBA/FileSystem/LOF), [EOF](/en/official/Reference/VBA/FileSystem/EOF) functions --- --- url: /zh/official/Reference/VBA/FileSystem/FileAttr.md --- # FileAttr 返回一个**Long**,表示以**Open**语句打开的文件模式。 语法:**FileAttr(** *filenumber* **,** *returntype* **)** *filenumber* : *必需* **Integer**,包含任何有效的文件号。 *returntype* : *必需* **Integer**,指示要返回的信息类型。必须为**1**以返回文件访问模式。 ### 返回值 以下返回值表示文件访问模式: | 模式 | 值 | |-------------|:---:| | **Input** | 1 | | **Output** | 2 | | **Random** | 4 | | **Append** | 8 | | **Binary** | 32 | ### 示例 本示例使用**FileAttr**函数返回打开文件的模式。 ```vb Dim FileNum, Mode FileNum = 1 ' Assign file number. Open "TESTFILE" For Append As FileNum ' Open file. Mode = FileAttr(FileNum, 1) ' Returns 8 (Append file mode). Close FileNum ' Close file. ``` ### 另请参阅 * [LOF](/official/Reference/VBA/FileSystem/LOF)、[EOF](/official/Reference/VBA/FileSystem/EOF)函数 --- --- url: /en/official/Reference/VBA/FileSystem/FileCopy.md --- # FileCopy Copies a file. Syntax: **FileCopy** *source*, *destination* *source* : *required* String expression that specifies the name of the file to be copied. The *source* may include directory or folder, and drive. *destination* : *required* String expression that specifies the target file name. The *destination* may include directory or folder, and drive. An error occurs when **FileCopy** is used on a file that is currently open. ### Example This example uses the **FileCopy** statement to copy one file to another. For the purposes of this example, assume that the file contains some data. ```vb Dim SourceFile, DestinationFile SourceFile = "SRCFILE" ' Define source file name. DestinationFile = "DESTFILE" ' Define target file name. FileCopy SourceFile, DestinationFile ' Copy source to target. ``` ### See Also * [Kill](/en/official/Reference/VBA/FileSystem/Kill) statement * [Name](/en/official/Reference/Core/Name) statement * [FileLen](/en/official/Reference/VBA/FileSystem/FileLen) function --- --- url: /zh/official/Reference/VBA/FileSystem/FileCopy.md --- # FileCopy 复制文件。 语法:**FileCopy** *source*, *destination* *source* : *必需* 字符串表达式,指定要复制的文件名。*source*可以包含目录或文件夹以及驱动器。 *destination* : *必需* 字符串表达式,指定目标文件名。*destination*可以包含目录或文件夹以及驱动器。 对当前已打开的文件使用**FileCopy**时会产生错误。 ### 示例 本示例使用**FileCopy**语句将一个文件复制到另一个文件。在本示例中,假设文件包含一些数据。 ```vb Dim SourceFile, DestinationFile SourceFile = "SRCFILE" ' Define source file name. DestinationFile = "DESTFILE" ' Define target file name. FileCopy SourceFile, DestinationFile ' Copy source to target. ``` ### 另请参阅 * [Kill](/official/Reference/VBA/FileSystem/Kill)语句 * [Name](/official/Reference/Core/Name)语句 * [FileLen](/official/Reference/VBA/FileSystem/FileLen)函数 --- --- url: /zh/official/Reference/Core/FileCopy.md --- # FileCopy 语句 filecopy 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/FileCopy.md --- # FileCopy Statement Documentation for the filecopy keyword is not yet available. --- --- url: /en/official/Reference/VBA/FileSystem/FileDateTime.md --- # FileDateTime Returns a **Variant** (**Date**) indicating the date and time when a file was created or last modified. Syntax: **FileDateTime(** *pathname* **)** *pathname* : *required* String expression that specifies a file name. The *pathname* may include the directory or folder, and the drive. ### Example This example uses the **FileDateTime** function to determine the date and time a file was created or last modified. The format of the date and time displayed is based on the system's locale settings. ```vb Dim MyStamp ' Assume TESTFILE was last modified on February 12, 1993 at 4:35:47 PM. ' Assume English/U.S. locale settings. MyStamp = FileDateTime("TESTFILE") ' Returns "2/12/93 4:35:47 PM". ``` ### See Also * [FileLen](/en/official/Reference/VBA/FileSystem/FileLen), [GetAttr](/en/official/Reference/VBA/FileSystem/GetAttr) functions --- --- url: /zh/official/Reference/VBA/FileSystem/FileDateTime.md --- # FileDateTime 返回一个**Variant**(**Date**),指示文件创建或最后修改的日期和时间。 语法:**FileDateTime(** *pathname* **)** *pathname* : *必需* 字符串表达式,指定文件名。*pathname*可以包含目录或文件夹以及驱动器。 ### 示例 本示例使用**FileDateTime**函数确定文件创建或最后修改的日期和时间。显示的日期和时间格式取决于系统的区域设置。 ```vb Dim MyStamp ' Assume TESTFILE was last modified on February 12, 1993 at 4:35:47 PM. ' Assume English/U.S. locale settings. MyStamp = FileDateTime("TESTFILE") ' Returns "2/12/93 4:35:47 PM". ``` ### 另请参阅 * [FileLen](/official/Reference/VBA/FileSystem/FileLen)、[GetAttr](/official/Reference/VBA/FileSystem/GetAttr)函数 --- --- url: /en/official/Reference/VBA/FileSystem/FileLen.md --- # FileLen Returns a **Long** specifying the length of a file in bytes. Syntax: **FileLen(** *pathname* **)** *pathname* : *required* String expression that specifies a file name. The *pathname* may include the directory or folder, and the drive. If the specified file is open when the **FileLen** function is called, the value returned represents the size of the file immediately before it was opened. ::: info Use the [LOF](/en/official/Reference/VBA/FileSystem/LOF) function to obtain the length of an open file. ::: ### Example This example uses the **FileLen** function to return the length of a file in bytes. For purposes of this example, assume that `TESTFILE` is a file containing some data. ```vb Dim MySize MySize = FileLen("TESTFILE") ' Returns file length (bytes). ``` ### See Also * [LOF](/en/official/Reference/VBA/FileSystem/LOF) function * [FileDateTime](/en/official/Reference/VBA/FileSystem/FileDateTime) function --- --- url: /zh/official/Reference/VBA/FileSystem/FileLen.md --- # FileLen 返回一个**Long**,指定文件的字节长度。 语法:**FileLen(** *pathname* **)** *pathname* : *必需* 字符串表达式,指定文件名。*pathname*可以包含目录或文件夹以及驱动器。 如果调用**FileLen**函数时指定文件已打开,则返回的值表示文件打开前的大小。 ::: info 使用[LOF](/official/Reference/VBA/FileSystem/LOF)函数获取打开文件的长度。 ::: ### 示例 本示例使用**FileLen**函数返回文件的字节长度。在本示例中,假设`TESTFILE`是一个包含一些数据的文件。 ```vb Dim MySize MySize = FileLen("TESTFILE") ' Returns file length (bytes). ``` ### 另请参阅 * [LOF](/official/Reference/VBA/FileSystem/LOF)函数 * [FileDateTime](/official/Reference/VBA/FileSystem/FileDateTime)函数 --- --- url: /en/official/Reference/VB/FileListBox.md --- # FileListBox class A **FileListBox** is a Win32 native list control that displays the files in a single directory, filtered by a wildcard pattern and a set of file-attribute toggles. It is normally placed on a **Form** or **UserControl** at design time and paired with a [**DriveListBox**](/en/official/Reference/VB/DriveListBox/) and a [**DirListBox**](/en/official/Reference/VB/DirListBox/) to make a complete file picker --- their **Change** events feed into **FileListBox.Path**, and the user selects a name from the list. The default property is [**FileName**](#filename) and the default event is [**Click**](#click). ```vb Private Sub Form_Load() Drive1.Drive = "C:\" Dir1.Path = Drive1.Drive File1.Path = Dir1.Path File1.Pattern = "*.txt;*.log" End Sub Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub Private Sub File1_DblClick() OpenFile File1.PathWithBackslash & File1.FileName End Sub ``` ## Path and Pattern [**Path**](#path) is the directory whose files are listed. It defaults to [**App.Path**](/en/official/Reference/VB/App/#path) when the control is first created. Setting it from code reloads the list, raises [**PathChange**](#pathchange), and trims any trailing backslash (except for a drive root). Setting a bare drive specifier without a backslash --- `"C:"` --- is silently rejected; use `"C:\"`. Assigning a path that does not exist raises run-time error 76 (*Path not found*). [**PathWithBackslash**](#pathwithbackslash) returns the same value with a trailing backslash always present, which is convenient when concatenating with [**FileName**](#filename). [**Pattern**](#pattern) is one or more wildcard masks separated by semicolons (`"*.txt;*.doc"`). Each mask is matched case-insensitively using the **Like** operator; a file is shown if it matches *any* mask. The default is `"*.*"`. Setting **Pattern** reloads the list and raises [**PatternChange**](#patternchange) when the new value differs from the previous one. ## File-attribute filters Five **Boolean** properties decide which files are included after the pattern matches: | Property | Meaning when **True** (default in **bold**) | |-------------------------------|-----------------------------------------------------------------------------------| | [**Archive**](#archive) | **Include files with the archive bit set.** | | [**Hidden**](#hidden) | Include hidden files. | | [**Normal**](#normal) | **Include files with no special attributes.** | | [**ReadOnly**](#readonly) | **Include read-only files.** | | [**System**](#system) | Include system files. | A file passes if every attribute it carries is permitted. **Normal** is the odd one out: it gates files that carry *no* attribute at all, so setting **Normal = False** with the others left at their defaults restricts the list to files that explicitly have one of the included attributes. Changing any of these reloads the list and raises [**PatternChange**](#patternchange) --- the event is shared with [**Pattern**](#pattern), matching the VB6 behaviour even though the name is misleading. ## Selecting files [**MultiSelect**](#multiselect) chooses among single-, simple-, and extended-selection ([**MultiSelectConstants**](/en/official/Reference/VBRUN/Constants/MultiSelectConstants)). Changing it recreates the underlying window (the path, pattern, and current selection are restored automatically). [**ListIndex**](#listindex) gives or sets the focused entry (`-1` for none), and [**FileName**](#filename) returns its text. [**Selected**](#selected) reads or writes the selection state of any individual item; [**SelCount**](#selcount) counts how many items are currently selected; [**SelectedIndices**](#selectedindices) returns them as a **Collection**: ```vb Dim idx As Variant For Each idx In File1.SelectedIndices() Debug.Print File1.PathWithBackslash & File1.List(idx) Next ``` ## OLE drag and drop When [**OLEDragMode**](#oledragmode) is set to **vbOLEDragAutomatic**, dragging the selected entry (or entries, in multi-select mode) starts an OLE drag whose data is the corresponding full path or paths. [**OLEDropMode**](#oledropmode) controls drop-target behaviour and is restricted to **vbOLEDropNone** or **vbOLEDropManual**. ## Properties ### Appearance Determines how the control's border is drawn by the OS. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). Combined with [**BorderStyle**](#borderstyle) to choose between a flat single-line border and a sunken client edge. ### Archive When **True** (default), files with the archive attribute are included in the list. **Boolean**. Changing this reloads the list and raises [**PatternChange**](#patternchange). ### BackColor The background colour, as an **OLE\_COLOR**. Defaults to the system window-background colour. ### BorderStyle A member of [**ControlBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants): **vbNoBorder** (0) or **vbFixedSingleBorder** (1, default). Combined with [**Appearance**](#appearance): a 3-D appearance plus single border yields the standard sunken client edge; flat appearance plus single border yields a one-pixel outline. ### CausesValidation Determines whether the previously focused control's [**Validate**](#validate) event runs before this control receives the focus. **Boolean**, default **True**. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a file list box. Always **vbFileListBox**. ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the control accepts user input. A disabled file list box still shows its contents but is dimmed and ignores keyboard and mouse interaction. **Boolean**, default **True**. ### FileName The name of the file at the current [**ListIndex**](#listindex), without any leading path. **Default property.** Syntax: *object*.**FileName** \[ = *string* ] Reading **FileName** returns the text of the highlighted entry, or an empty string when [**ListIndex**](#listindex) is `-1`. Setting **FileName** searches the list for an exact, case-insensitive match and selects that entry if found; if no entry matches, the assignment has no visible effect. ### Font The **StdFont** used to render file names. The convenience properties **FontName**, **FontSize**, **FontBold**, **FontItalic**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. Changing the font rescales each item's row height when [**IntegralHeight**](#integralheight) is **True**. ### ForeColor The text colour for entries that are not currently selected, as an **OLE\_COLOR**. Defaults to the system window-text colour. Disabled entries draw in the system grey-text colour, and selected entries draw in the system highlight-text colour, regardless of this setting. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). When [**IntegralHeight**](#integralheight) is **True**, the OS quantises this to a whole number of rows. **Single**. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the control has focus. ### Hidden When **True**, files with the hidden attribute are included in the list. **Boolean**, default **False**. Changing this reloads the list and raises [**PatternChange**](#patternchange). ### hWnd The Win32 window handle for the underlying list box, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Read-only at run time. ### IntegralHeight When **True** (default), the OS adjusts the control's height so that the visible portion shows whole rows rather than partial ones. When **False**, the control honours [**Height**](#height) exactly. **Boolean**. Changing this at run time recreates the underlying window. ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Single**. ### List The text of an item, indexed by zero-based position. Read-only. Syntax: *object*.**List**( *Index* ) *Index* : *required* A **Long** zero-based item position. ### ListCount The number of files currently shown in the list, as a **Long**. Read-only. ### ListIndex The zero-based index of the focused item, or `-1` if no item is focused. **Long**. In multi-select modes the focused item and the selected items are independent --- see [**Selected**](#selected). Assigning a value that differs from the current one focuses that item and raises [**Click**](#click). ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### MultiSelect The selection mode. A member of [**MultiSelectConstants**](/en/official/Reference/VBRUN/Constants/MultiSelectConstants): **vbMultiSelectNone** (0, default --- single selection), **vbMultiSelectSimple** (1 --- each click toggles), or **vbMultiSelectExtended** (2 --- **Shift** for ranges, **Ctrl** for individual toggles). Changing this at run time recreates the underlying window; the current path, pattern, top-index, and focused item are restored, but multi-item selections are not. ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### Normal When **True** (default), files with no attribute bits set are included in the list. When **False**, only files that explicitly carry one of the other included attributes are shown. **Boolean**. Changing this reloads the list and raises [**PatternChange**](#patternchange). ### OLEDragMode Whether the control acts as an automatic OLE drag source. A member of [**OLEDragConstants**](/en/official/Reference/VBRUN/Constants/OLEDragConstants): **vbOLEDragManual** (0, default --- call [**OLEDrag**](#oledrag) from code) or **vbOLEDragAutomatic** (1 --- dragging an entry starts an OLE drag whose **Text** data is the full path of the selected file, or a list of paths in multi-select mode). ### OLEDropMode How the control responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on a FileListBox. ### Opacity The control's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Requires Windows 8 or later for child controls. ### Parent A reference to the **Form** (or **UserControl**) that contains this control. Read-only. ### Path The directory whose files are listed. **String**. Defaults to [**App.Path**](/en/official/Reference/VB/App/#path) when the control is first created. Syntax: *object*.**Path** \[ = *string* ] Reading **Path** returns the directory currently shown --- without a trailing backslash (except for a drive root, which is always returned as `"C:\"`). Setting **Path** reloads the list and raises [**PathChange**](#pathchange) when the new value differs from the current one. A bare drive specifier with no backslash (`"C:"`) is silently rejected; use `"C:\"`. Assigning a path that does not exist raises run-time error 76 (*Path not found*). ### PathWithBackslash The same value as [**Path**](#path), but always with a trailing backslash. **String**, read-only. Convenient for concatenating with [**FileName**](#filename) to build a full path. ### Pattern The wildcard mask, or semicolon-separated list of masks, used to filter the file list. **String**, default `"*.*"`. Syntax: *object*.**Pattern** \[ = *string* ] A file is shown if it matches *any* of the masks (case-insensitively, using the **Like** operator). Setting an empty string is treated as `"*.*"`. Changing **Pattern** reloads the list and raises [**PatternChange**](#patternchange) when the new value differs from the current one. ```vb File1.Pattern = "*.txt;*.log" ' .txt or .log files ``` ### ReadOnly When **True** (default), files with the read-only attribute are included in the list. **Boolean**. Changing this reloads the list and raises [**PatternChange**](#patternchange). Note that **ReadOnly** is a reserved word in twinBASIC and must be referenced through a member access (`File1.ReadOnly`) or escaped (`[ReadOnly]`) in declarations. ### SelCount The number of items currently selected, as a **Long**. Read-only. Equal to `0` or `1` when [**MultiSelect**](#multiselect) is **vbMultiSelectNone**. ### Selected The selection state of an individual item. Syntax: *object*.**Selected**( *Index* ) \[ = *boolean* ] *Index* : *required* A **Long** zero-based item position. Reading **Selected(*Index*)** returns **True** when that item is selected. Assigning a value that differs from the current one updates the selection and raises [**Click**](#click); in single-select mode (**vbMultiSelectNone**) assigning **True** focuses the item, and assigning **False** has no observable effect. ### System When **True**, files with the system attribute are included in the list. **Boolean**, default **False**. Changing this reloads the list and raises [**PatternChange**](#patternchange). ### TabIndex The position of the control in the form's TAB-key navigation order. **Long**. ### TabStop Whether the user can reach the control by pressing the **TAB** key. **Boolean**, default **True**. A disabled control is skipped regardless of this setting. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the control. ### Top The vertical distance from the top of the container to the top of the control. **Single**. ### TopIndex The zero-based index of the item shown at the top of the visible area. Assigning a value scrolls the list so that item is at the top, and raises [**Scroll**](#scroll) when the value actually changes. **Long**. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered control. Default `-1` disables the effect. Requires Windows 8 or later for child controls. ### Visible Whether the control is shown. **Boolean**, default **True**. ### VisualStyles Whether the OS theme engine should be used when drawing the control. **Boolean**, default **True**. ### WhatsThisHelpID A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### WheelScrollEvent When **True** (default), mouse-wheel notifications over the control raise the [**Scroll**](#scroll) event; when **False**, the wheel still scrolls the list but [**Scroll**](#scroll) is suppressed. **Boolean**. VB6 never raised **Scroll** for wheel events; set this to **False** to match that behaviour exactly. ### Width The control's width. **Single**. ## Methods ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Typically called from a [**MouseDown**](#mousedown) handler when [**DragMode**](#dragmode) is **vbManual**. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the control, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Re-reads the contents of the current [**Path**](#path) from disk and repaints the control. Useful when the directory has been modified outside the application --- the control does not watch the file system on its own. Does not raise [**PathChange**](#pathchange) or [**PatternChange**](#patternchange). Syntax: *object*.**Refresh** ### SelectedIndices Returns the zero-based indices of every currently-selected item as a **Collection** of **Long** values, in ascending order. Useful for iterating multi-selections without scanning [**Selected**](#selected) for every index. Syntax: *object*.**SelectedIndices** ```vb Dim idx As Variant For Each idx In File1.SelectedIndices() Debug.Print File1.PathWithBackslash & File1.List(idx) Next ``` ### SetFocus Moves the input focus to the control. The control must be both [**Visible**](#visible) and [**Enabled**](#enabled), or run-time error 5 (*Invalid procedure call or argument*) is raised. Syntax: *object*.**SetFocus** ### ShowWhatsThis Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Click Raised after the focused item changes --- whether the user clicked a different entry, used the keyboard to move the focus, or code assigned a different value to [**ListIndex**](#listindex) or [**Selected**](#selected). Also raised when the selection is cancelled. **Default event.** Syntax: *object*\_**Click**( ) ### DblClick Raised when the user double-clicks an entry. Unlike [**DirListBox**](/en/official/Reference/VB/DirListBox/), the **FileListBox** does *not* navigate on double-click --- typically the application listens for **DblClick** to open the file the user has chosen. Syntax: *object*\_**DblClick**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus Raised when the control receives the input focus. Syntax: *object*\_**GotFocus**( ) ### Initialize Raised once, immediately after the underlying window is created and the initial list of files has been loaded from [**App.Path**](/en/official/Reference/VB/App/#path). New in twinBASIC --- VB6 had no equivalent on this control. Syntax: *object*\_**Initialize**( ) ### KeyDown Raised when the user presses any key while the control has focus. Syntax: *object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress Raised when the user types a character that produces an ANSI keystroke. Syntax: *object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp Raised when the user releases a key while the control has focus. Syntax: *object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus Raised when the control loses the input focus. Syntax: *object*\_**LostFocus**( ) ### MouseDown Raised when the user presses any mouse button over the control. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the control. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the control. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Fires whether the drag was initiated automatically (with [**OLEDragMode**](#oledragmode) set to **vbOLEDragAutomatic**) or by an explicit [**OLEDrag**](#oledrag) call. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### PathChange Raised after [**Path**](#path) has changed --- typically because code assigned a new value to it. Not raised for assignments that match the current value. Syntax: *object*\_**PathChange**( ) ### PatternChange Raised after [**Pattern**](#pattern) has changed *or* after one of the file-attribute filter properties --- [**Archive**](#archive), [**Hidden**](#hidden), [**Normal**](#normal), [**ReadOnly**](#readonly), [**System**](#system) --- has changed. Not raised for pattern assignments that match the current value. The shared event matches the VB6 behaviour even though the name is misleading. Syntax: *object*\_**PatternChange**( ) ### Scroll Raised when the visible portion of the list scrolls --- by the scroll bar, the keyboard, or (when [**WheelScrollEvent**](#wheelscrollevent) is **True**) the mouse wheel. The new offset can be read from [**TopIndex**](#topindex). Syntax: *object*\_**Scroll**( ) ### Validate Raised when the focus is moving to another control whose [**CausesValidation**](#causesvalidation) is **True**. Setting *Cancel* to **True** keeps the focus on this control. Syntax: *object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /zh/official/Reference/VB/FileListBox.md --- # FileListBox 类 **FileListBox**是一个Win32原生列表控件,显示单个目录中的文件,通过通配符模式和一组文件属性开关进行筛选。通常在设计时放置在**Form**或**UserControl**上,与[**DriveListBox**](/official/Reference/VB/DriveListBox/)和[**DirListBox**](/official/Reference/VB/DirListBox/)配对构成完整的文件选择器——它们的**Change**事件馈入**FileListBox.Path**,用户从列表中选择文件名。默认属性是[**FileName**](#filename),默认事件是[**Click**](#click)。 ```vb Private Sub Form_Load() Drive1.Drive = "C:\" Dir1.Path = Drive1.Drive File1.Path = Dir1.Path File1.Pattern = "*.txt;*.log" End Sub Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub Private Sub File1_DblClick() OpenFile File1.PathWithBackslash & File1.FileName End Sub ``` ## Path和Pattern [**Path**](#path)是列出文件的目录。控件首次创建时默认为[**App.Path**](/official/Reference/VB/App/#path)。从代码设置它会重新加载列表、引发[**PathChange**](#pathchange)并修剪尾部反斜杠(驱动器根目录除外)。设置不带反斜杠的纯驱动器标识符——`"C:"`——会被静默拒绝;请使用`"C:\"`。赋值不存在的路径会引发运行时错误76(*Path not found*)。[**PathWithBackslash**](#pathwithbackslash)返回始终带尾部反斜杠的相同值,与[**FileName**](#filename)拼接时很方便。 [**Pattern**](#pattern)是一个或多个用分号分隔的通配符掩码(`"*.txt;*.doc"`)。每个掩码使用**Like**运算符进行不区分大小写的匹配;文件匹配*任何*掩码都会显示。默认为`"*.*"`。设置**Pattern**会在新值与之前不同时重新加载列表并引发[**PatternChange**](#patternchange)。 ## 文件属性筛选器 五个**Boolean**属性决定模式匹配后包含哪些文件: | 属性 | 为**True**时的含义(默认值加粗) | |-------------------------------|-----------------------------------------------------------------------------------| | [**Archive**](#archive) | **包含设置了存档位的文件。** | | [**Hidden**](#hidden) | 包含隐藏文件。 | | [**Normal**](#normal) | **包含无特殊属性的文件。** | | [**ReadOnly**](#readonly) | **包含只读文件。** | | [**System**](#system) | 包含系统文件。 | 文件所携带的每个属性都被允许时才能通过。**Normal**是特殊情况:它控制不携带*任何*属性的文件,因此在其他属性保持默认的情况下设置**Normal = False**会将列表限制为明确具有某个已包含属性的文件。更改这些属性中的任何一个都会重新加载列表并引发[**PatternChange**](#patternchange)——该事件与[**Pattern**](#pattern)共享,与VB6行为匹配,尽管名称有误导性。 ## 选择文件 [**MultiSelect**](#multiselect)在单项、简单和扩展选择模式之间选择([**MultiSelectConstants**](/official/Reference/VBRUN/Constants/MultiSelectConstants))。更改它会重新创建底层窗口(路径、模式和当前选择会自动恢复)。 [**ListIndex**](#listindex)获取或设置焦点条目(`-1`表示无),[**FileName**](#filename)返回其文本。[**Selected**](#selected)读取或写入任何单个条目的选择状态;[**SelCount**](#selcount)计算当前选中条目数;[**SelectedIndices**](#selectedindices)以**Collection**返回它们: ```vb Dim idx As Variant For Each idx In File1.SelectedIndices() Debug.Print File1.PathWithBackslash & File1.List(idx) Next ``` ## OLE拖放 当[**OLEDragMode**](#oledragmode)设置为**vbOLEDragAutomatic**时,拖动选中的条目(或多选模式下的多个条目)会启动OLE拖动,其数据为对应的完整路径。[**OLEDropMode**](#oledropmode)控制放置目标行为,仅限于**vbOLEDropNone**或**vbOLEDropManual**。 ## 属性 ### Appearance 确定操作系统如何绘制控件的边框。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。与[**BorderStyle**](#borderstyle)组合使用,可选平面单线边框或凹陷的客户端边缘。 ### Archive 当为**True**(默认)时,带存档属性的文件包含在列表中。**Boolean**。更改此属性会重新加载列表并引发[**PatternChange**](#patternchange)。 ### BackColor 背景颜色,类型为**OLE\_COLOR**。默认为系统窗口背景色。 ### BorderStyle [**ControlBorderStyleConstants**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants)的成员:**vbNoBorder** (0)或**vbFixedSingleBorder** (1,默认)。与[**Appearance**](#appearance)组合使用:3D外观加单线边框产生标准凹陷客户端边缘;平面外观加单线边框产生一像素轮廓线。 ### CausesValidation 确定先前获得焦点的控件的[**Validate**](#validate)事件是否在此控件获得焦点之前运行。**Boolean**,默认**True**。 ### ControlType 只读的[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值,将此控件标识为文件列表框。始终为**vbFileListBox**。 ### DragIcon 控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自动拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual** (0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic** (1)。 ### Enabled 确定控件是否接受用户输入。禁用的文件列表框仍显示其内容但变暗并忽略键盘和鼠标交互。**Boolean**,默认**True**。 ### FileName 当前[**ListIndex**](#listindex)处文件的名称,不带任何前导路径。**默认属性。** 语法:*object*.**FileName** \[ = *string* ] 读取**FileName**返回高亮条目的文本,当[**ListIndex**](#listindex)为`-1`时返回空字符串。设置**FileName**会在列表中搜索精确的不区分大小写匹配,如果找到则选中该条目;如果无匹配条目,赋值无可见效果。 ### Font 用于渲染文件名的**StdFont**。便捷属性**FontName**、**FontSize**、**FontBold**、**FontItalic**、**FontStrikethru**和**FontUnderline**读写此对象的相应成员。当[**IntegralHeight**](#integralheight)为**True**时,更改字体会重新缩放每项的行高。 ### ForeColor 未选中条目的文本颜色,类型为**OLE\_COLOR**。默认为系统窗口文本色。禁用条目使用系统灰色文本色绘制,选中条目使用系统高亮文本色绘制,不受此设置影响。 ### Height 控件的高度,默认以缇为单位(或使用容器的**ScaleMode**单位)。当[**IntegralHeight**](#integralheight)为**True**时,操作系统将其量化为整行数。**Single**。 ### HelpContextID 标识应用程序帮助文件中主题的**Long**值,当用户在控件具有焦点时按**F1**时检索。 ### Hidden 当为**True**时,带隐藏属性的文件包含在列表中。**Boolean**,默认**False**。更改此属性会重新加载列表并引发[**PatternChange**](#patternchange)。 ### hWnd 底层列表框的Win32窗口句柄,类型为**LongPtr**。只读。可用于传递给API函数。 ### Index 当控件是控件数组的一部分时,此实例在数组中的从零开始的**Long**索引。运行时只读。 ### IntegralHeight 当为**True**(默认)时,操作系统调整控件高度使可见部分显示完整行而非部分行。当为**False**时,控件精确遵循[**Height**](#height)。**Boolean**。在运行时更改此属性会重新创建底层窗口。 ### Left 从容器的左边缘到控件左边缘的水平距离。**Single**。 ### List 条目的文本,按从零开始的位置索引。只读。 语法:*object*.**List**( *Index* ) *Index* : *必需* 从零开始的**Long**条目位置。 ### ListCount 列表中当前显示的文件数,类型为**Long**。只读。 ### ListIndex 焦点条目的从零开始的索引,无焦点条目时为`-1`。**Long**。在多选模式下焦点条目和选中条目是独立的——参见[**Selected**](#selected)。赋值与当前值不同的值会聚焦该条目并引发[**Click**](#click)。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针位于控件上时用作鼠标光标的**StdPicture**。 ### MousePointer 指针位于控件上时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### MultiSelect 选择模式。[**MultiSelectConstants**](/official/Reference/VBRUN/Constants/MultiSelectConstants)的成员:**vbMultiSelectNone** (0,默认——单项选择)、**vbMultiSelectSimple** (1——每次单击切换)或**vbMultiSelectExtended** (2——**Shift**选择范围,**Ctrl**切换单项)。在运行时更改此属性会重新创建底层窗口;当前路径、模式、顶部索引和焦点条目会恢复,但多项选择不会。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### Normal 当为**True**(默认)时,无属性位的文件包含在列表中。当为**False**时,仅显示明确携带某个已包含属性的文件。**Boolean**。更改此属性会重新加载列表并引发[**PatternChange**](#patternchange)。 ### OLEDragMode 控件是否作为自动OLE拖动源。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDragConstants)的成员:**vbOLEDragManual** (0,默认——从代码调用[**OLEDrag**](#oledrag))或**vbOLEDragAutomatic** (1——拖动条目会启动OLE拖动,其**Text**数据为选中文件的完整路径,多选模式下为路径列表)。 ### OLEDropMode 控件如何响应OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**或**vbOLEDropManual**。FileListBox不支持自动放置模式。 ### Opacity 控件的不透明度百分比(0--100,默认100)。超出范围的值在**Initialize**时被钳制。子控件需要Windows 8或更高版本。 ### Parent 对包含此控件的**Form**(或**UserControl**)的引用。只读。 ### Path 列出文件的目录。**String**。控件首次创建时默认为[**App.Path**](/official/Reference/VB/App/#path)。 语法:*object*.**Path** \[ = *string* ] 读取**Path**返回当前显示的目录——不带尾部反斜杠(驱动器根目录除外,始终返回为`"C:\"`)。设置**Path**会在新值与当前值不同时重新加载列表并引发[**PathChange**](#pathchange)。不带反斜杠的纯驱动器标识符(`"C:"`)会被静默拒绝;请使用`"C:\"`。赋值不存在的路径会引发运行时错误76(*Path not found*)。 ### PathWithBackslash 与[**Path**](#path)相同的值,但始终带尾部反斜杠。**String**,只读。与[**FileName**](#filename)拼接构建完整路径时很方便。 ### Pattern 用于筛选文件列表的通配符掩码,或分号分隔的掩码列表。**String**,默认`"*.*"`。 语法:*object*.**Pattern** \[ = *string* ] 文件匹配*任何*掩码时显示(不区分大小写,使用**Like**运算符)。设置空字符串被视为`"*.*"`。更改**Pattern**会在新值与当前值不同时重新加载列表并引发[**PatternChange**](#patternchange)。 ```vb File1.Pattern = "*.txt;*.log" ' .txt或.log文件 ``` ### ReadOnly 当为**True**(默认)时,带只读属性的文件包含在列表中。**Boolean**。更改此属性会重新加载列表并引发[**PatternChange**](#patternchange)。注意**ReadOnly**是twinBASIC中的保留字,必须通过成员访问(`File1.ReadOnly`)或在声明中转义(`[ReadOnly]`)来引用。 ### SelCount 当前选中的条目数,类型为**Long**。只读。当[**MultiSelect**](#multiselect)为**vbMultiSelectNone**时等于`0`或`1`。 ### Selected 单个条目的选择状态。 语法:*object*.**Selected**( *Index* ) \[ = *boolean* ] *Index* : *必需* 从零开始的**Long**条目位置。 读取**Selected(*Index*)**在该条目被选中时返回**True**。赋值与当前值不同的值会更新选择并引发[**Click**](#click);在单项选择模式(**vbMultiSelectNone**)下赋值**True**会聚焦该条目,赋值**False**无明显效果。 ### System 当为**True**时,带系统属性的文件包含在列表中。**Boolean**,默认**False**。更改此属性会重新加载列表并引发[**PatternChange**](#patternchange)。 ### TabIndex 控件在窗体TAB键导航顺序中的位置。**Long**。 ### TabStop 用户是否可以通过按**TAB**键到达控件。**Boolean**,默认**True**。禁用的控件无论此设置如何都会被跳过。 ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### ToolTipText 当用户将鼠标悬停在控件上时作为工具提示显示的多行**String**。 ### Top 从容器顶部到控件顶部的垂直距离。**Single**。 ### TopIndex 可见区域顶部显示条目的从零开始的索引。赋值会滚动列表使该条目位于顶部,当值实际改变时引发[**Scroll**](#scroll)。**Long**。 ### TransparencyKey 一个**OLE\_COLOR**值,设置后在渲染的控件中变为完全透明。默认`-1`禁用此效果。子控件需要Windows 8或更高版本。 ### Visible 控件是否显示。**Boolean**,默认**True**。 ### VisualStyles 绘制控件时是否使用操作系统主题引擎。**Boolean**,默认**True**。 ### WhatsThisHelpID 标识应用程序帮助文件中"这是什么?"弹出帮助主题的**Long**值。参见[**ShowWhatsThis**](#showwhatsthis)。 ### WheelScrollEvent 当为**True**(默认)时,控件上的鼠标滚轮通知引发[**Scroll**](#scroll)事件;当为**False**时,滚轮仍会滚动列表但[**Scroll**](#scroll)被抑制。**Boolean**。VB6从不为滚轮事件引发**Scroll**;将此设置为**False**可完全匹配该行为。 ### Width 控件的宽度。**Single**。 ## 方法 ### Drag 开始、完成或取消手动拖放操作。通常在[**DragMode**](#dragmode)为**vbManual**时从[**MouseDown**](#mousedown)处理程序中调用。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel** (0)、**vbBeginDrag** (1,默认)或**vbEndDrag** (2)。 ### Move 在单次调用中重新定位并可选地调整控件大小。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**值。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从控件发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### Refresh 从磁盘重新读取当前[**Path**](#path)的内容并重绘控件。当目录在应用程序外部被修改时很有用——控件不会自行监视文件系统。不引发[**PathChange**](#pathchange)或[**PatternChange**](#patternchange)。 语法:*object*.**Refresh** ### SelectedIndices 以升序**Long**值的**Collection**返回每个当前选中条目的从零开始的索引。用于迭代多选而无需扫描每个索引的[**Selected**](#selected)。 语法:*object*.**SelectedIndices** ```vb Dim idx As Variant For Each idx In File1.SelectedIndices() Debug.Print File1.PathWithBackslash & File1.List(idx) Next ``` ### SetFocus 将输入焦点移至控件。控件必须同时[**Visible**](#visible)和[**Enabled**](#enabled),否则引发运行时错误5(*Invalid procedure call or argument*)。 语法:*object*.**SetFocus** ### ShowWhatsThis 以"这是什么?"弹出的方式显示由[**WhatsThisHelpID**](#whatsthishelpid)标识的主题。 语法:*object*.**ShowWhatsThis** ### ZOrder 将控件置于其同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront** (0,默认)或**vbSendToBack** (1)。 ## 事件 ### Click 焦点条目更改后引发——无论用户点击了不同的条目、使用键盘移动焦点,还是代码赋值了不同的[**ListIndex**](#listindex)或[**Selected**](#selected)值。选择被取消时也会引发。**默认事件。** 语法:*object*\_**Click**( ) ### DblClick 用户双击条目时引发。与[**DirListBox**](/official/Reference/VB/DirListBox/)不同,**FileListBox**在双击时*不会*导航——通常应用程序监听**DblClick**来打开用户选择的文件。 语法:*object*\_**DblClick**( ) ### DragDrop 手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus 控件获得输入焦点时引发。 语法:*object*\_**GotFocus**( ) ### Initialize 在底层窗口创建且从[**App.Path**](/official/Reference/VB/App/#path)加载初始文件列表后立即引发一次。twinBASIC新增——VB6在此控件上没有等效功能。 语法:*object*\_**Initialize**( ) ### KeyDown 用户在控件具有焦点时按下任意键引发。 语法:*object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress 用户键入产生ANSI击键的字符时引发。 语法:*object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp 用户在控件具有焦点时释放键引发。 语法:*object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus 控件失去输入焦点时引发。 语法:*object*\_**LostFocus**( ) ### MouseDown 用户在控件上按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 光标在控件上移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 用户在控件上释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 用户将数据放置到目标控件上时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的数据格式时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。无论拖动是自动启动的([**OLEDragMode**](#oledragmode)设置为**vbOLEDragAutomatic**)还是通过显式[**OLEDrag**](#oledrag)调用都会引发。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### PathChange 在[**Path**](#path)更改后引发——通常因为代码赋值了新值。对于与当前值相同的赋值不引发。 语法:*object*\_**PathChange**( ) ### PatternChange 在[**Pattern**](#pattern)更改*或*某个文件属性筛选属性——[**Archive**](#archive)、[**Hidden**](#hidden)、[**Normal**](#normal)、[**ReadOnly**](#readonly)、[**System**](#system)——更改后引发。对于与当前值相同的模式赋值不引发。共享事件与VB6行为匹配,尽管名称有误导性。 语法:*object*\_**PatternChange**( ) ### Scroll 列表的可见部分滚动时引发——通过滚动条、键盘或(当[**WheelScrollEvent**](#wheelscrollevent)为**True**时)鼠标滚轮。新偏移量可从[**TopIndex**](#topindex)读取。 语法:*object*\_**Scroll**( ) ### Validate 焦点移动到另一个[**CausesValidation**](#causesvalidation)为**True**的控件时引发。将*Cancel*设置为**True**可使焦点保留在此控件上。 语法:*object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /en/official/Reference/VBRUN/DataObject/Files.md --- # Files Returns a [**DataObjectFiles**](/en/official/Reference/VBRUN/DataObject/DataObjectFiles) collection holding the file paths the **DataObject** contains. Syntax: *object*.**Files** *object* : *required* An object expression that evaluates to a **DataObject**. This is the typical way to read the payload of a Windows shell drag-and-drop, which arrives as a list of fully qualified paths under the `vbCFFiles` clipboard format. Each element of the collection is a **String**. The source side may also fill the **DataObject** with a list of files by adding paths to this collection --- see [**DataObjectFiles.Add**](/en/official/Reference/VBRUN/DataObject/DataObjectFiles#add). ### Example ```vb Private Sub Form_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, _ Shift As Integer, X As Single, Y As Single) If Data.GetFormat(vbCFFiles) Then Dim Path As Variant For Each Path In Data.Files Debug.Print Path Next Path End If End Sub ``` ### See Also * [DataObjectFiles](/en/official/Reference/VBRUN/DataObject/DataObjectFiles) collection * [GetFormat](/en/official/Reference/VBRUN/DataObject/GetFormat) method * [SetData](/en/official/Reference/VBRUN/DataObject/SetData) method --- --- url: /zh/official/Reference/VBRUN/DataObject/Files.md --- # Files 返回[**DataObjectFiles**](/official/Reference/VBRUN/DataObject/DataObjectFiles)集合,保存**DataObject**包含的文件路径。 语法:*object*.**Files** *object* : *必需* 求值为**DataObject**的对象表达式。 这是读取Windows Shell拖放有效负载的典型方式,以`vbCFFiles`剪贴板格式到达的完全限定路径列表。集合的每个元素是**String**。 源端也可以通过向此集合添加路径来填充**DataObject**的文件列表——参见[**DataObjectFiles.Add**](/official/Reference/VBRUN/DataObject/DataObjectFiles#add)。 ### 示例 ```vb Private Sub Form_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, _ Shift As Integer, X As Single, Y As Single) If Data.GetFormat(vbCFFiles) Then Dim Path As Variant For Each Path In Data.Files Debug.Print Path Next Path End If End Sub ``` ### 另见 * [DataObjectFiles](/official/Reference/VBRUN/DataObject/DataObjectFiles) 集合 * [GetFormat](/official/Reference/VBRUN/DataObject/GetFormat) 方法 * [SetData](/official/Reference/VBRUN/DataObject/SetData) 方法 --- --- url: /en/official/Reference/tbIDE/FileSystem.md --- # FileSystem class A handle into the IDE's virtual file system --- the abstraction that lets an addin traverse and read source files without touching the on-disk paths. The **FileSystem** is reached through [**Host.FileSystem**](/en/official/Reference/tbIDE/Host#filesystem). For the more common per-project case, [**Host.CurrentProject.RootFolder**](/en/official/Reference/tbIDE/Project#rootfolder) is also a [**Folder**](/en/official/Reference/tbIDE/Folder) and is usually the right entry point --- the global **FileSystem** matters when an addin needs to address files outside the project's own root. ```vb Dim item As FileSystemItem = Host.FileSystem.ResolvePath("twinbasic:/Sources/MainModule.twin") ``` ## Properties ### RootFolder The root of the virtual file system. **As** [**Folder**](/en/official/Reference/tbIDE/Folder). Read-only. ## Methods ### ResolvePath Looks up the [**FileSystemItem**](/en/official/Reference/tbIDE/FileSystemItem) at a given path. The path uses the IDE's `twinbasic:/` URI scheme --- the same scheme that [**FileSystemItem.Path**](/en/official/Reference/tbIDE/FileSystemItem#path) and [**Editor.Path**](/en/official/Reference/tbIDE/Editor#path) return. Syntax: *fileSystem*.**ResolvePath**( *Path* ) **As** [**FileSystemItem**](/en/official/Reference/tbIDE/FileSystemItem) *Path* : *required* A virtual-FS path. **String**. Must include the `twinbasic:/` prefix. The returned object is a [**FileSystemItem**](/en/official/Reference/tbIDE/FileSystemItem) but is usually castable to its specific kind --- a [**File**](/en/official/Reference/tbIDE/File) for regular files, a [**Folder**](/en/official/Reference/tbIDE/Folder) for folders. Test with `TypeOf … Is Folder` before casting when the path's kind is not known statically. --- --- url: /zh/official/Reference/tbIDE/FileSystem.md --- # FileSystem 类 IDE 虚拟文件系统的句柄——让插件能够在不触及磁盘路径的情况下遍历和读取源文件的抽象。通过 [**Host.FileSystem**](/official/Reference/tbIDE/Host#filesystem) 访问。对于更常见的每项目场景,[**Host.CurrentProject.RootFolder**](/official/Reference/tbIDE/Project#rootfolder) 也是一个 [**Folder**](/official/Reference/tbIDE/Folder),通常是正确的入口点——当插件需要访问项目自身根目录之外的文件时,全局 **FileSystem** 才有意义。 ```vb Dim item As FileSystemItem = Host.FileSystem.ResolvePath("twinbasic:/Sources/MainModule.twin") ``` ## 属性 ### RootFolder 虚拟文件系统的根。**As** [**Folder**](/official/Reference/tbIDE/Folder)。只读。 ## 方法 ### ResolvePath 查找给定路径处的 [**FileSystemItem**](/official/Reference/tbIDE/FileSystemItem)。路径使用 IDE 的 `twinbasic:/` URI 方案——与 [**FileSystemItem.Path**](/official/Reference/tbIDE/FileSystemItem#path) 和 [**Editor.Path**](/official/Reference/tbIDE/Editor#path) 返回的方案相同。 语法:*fileSystem*.**ResolvePath**( *Path* ) **As** [**FileSystemItem**](/official/Reference/tbIDE/FileSystemItem) *Path* : *必需* 一个虚拟文件系统路径。**String**。必须包含 `twinbasic:/` 前缀。 返回的对象是 [**FileSystemItem**](/official/Reference/tbIDE/FileSystemItem),但通常可转换为其具体类型——常规文件为 [**File**](/official/Reference/tbIDE/File),文件夹为 [**Folder**](/official/Reference/tbIDE/Folder)。当路径的类型在静态上未知时,在转换前用 `TypeOf … Is Folder` 测试。 --- --- url: /en/official/Reference/VBA/FileSystem.md --- # FileSystem module The **FileSystem** module groups together the procedures and statements for working with files and directories on disk. Its members divide cleanly into two camps: *pathname-based* operations that act on something named in the filesystem (creating and deleting files and directories, querying their attributes, iterating over a directory listing), and *file-number-based* operations that act on a handle previously returned by the **Open** statement (reading, positioning, formatting, and tracking the channel). ## Navigating directories [**ChDrive**](/en/official/Reference/VBA/FileSystem/ChDrive) changes the current drive, [**ChDir**](/en/official/Reference/VBA/FileSystem/ChDir) changes the current directory on a given drive, and [**CurDir**](/en/official/Reference/VBA/FileSystem/CurDir) returns the path of the current drive --- or of any other drive, if one is named. [**MkDir**](/en/official/Reference/VBA/FileSystem/MkDir) and [**RmDir**](/en/official/Reference/VBA/FileSystem/RmDir) create and remove directories. ```vb ChDrive "D" ChDir "D:\Projects" Debug.Print CurDir ' "D:\Projects" MkDir "D:\Projects\Output" ``` ## Inspecting files and directories [**Dir**](/en/official/Reference/VBA/FileSystem/Dir) is the wildcard matcher: pass it a pathname containing `*` or `?` and it returns the first matching name, then call it again with no arguments to step through subsequent matches until it returns `""`. [**FileLen**](/en/official/Reference/VBA/FileSystem/FileLen) returns the size of a file in bytes without opening it, and [**FileDateTime**](/en/official/Reference/VBA/FileSystem/FileDateTime) returns its last-modified timestamp. [**GetAttr**](/en/official/Reference/VBA/FileSystem/GetAttr) and [**SetAttr**](/en/official/Reference/VBA/FileSystem/SetAttr) read and write the [**VbFileAttribute**](/en/official/Reference/VBA/Constants/VbFileAttribute) flag bits --- read-only, hidden, system, archive --- and **GetAttr** also reports whether a name refers to a directory by setting the **vbDirectory** bit. ```vb Dim Name As String Name = Dir("C:\Logs\*.log") Do While Name <> "" Debug.Print Name & vbTab & FileLen("C:\Logs\" & Name) Name = Dir Loop ``` ## Copying and deleting [**FileCopy**](/en/official/Reference/VBA/FileSystem/FileCopy) copies one file to another, and [**Kill**](/en/official/Reference/VBA/FileSystem/Kill) deletes files matching a wildcard pattern. Both operate by pathname and raise a run-time error when asked to act on a file the current process has open. ```vb FileCopy "C:\Data\report.xlsx", "C:\Backup\report.xlsx" Kill "C:\Backup\*.tmp" ``` ## Opening and tracking file numbers The lower-level read/write statements --- **Open**, **Close**, **Get**, **Put**, **Print**, **Write**, **Input**, and **Line Input** --- work in terms of a *file number* in the range 1--511. [**FreeFile**](/en/official/Reference/VBA/FileSystem/FreeFile) returns the next number that isn't currently in use, sparing the caller from picking one by hand and racing other code to it. Once a file is open, [**FileAttr**](/en/official/Reference/VBA/FileSystem/FileAttr) reports the access mode --- **Input**, **Output**, **Random**, **Append**, or **Binary** --- that the file number was opened with. [**Reset**](/en/official/Reference/VBA/FileSystem/Reset) closes every file number currently open and flushes its buffers, and is most useful as a last-ditch cleanup before exit. ```vb Dim N As Long N = FreeFile Open "C:\Data\report.txt" For Input As #N ' ... read ... Close #N ``` ## Position within an open file For an open file number, [**EOF**](/en/official/Reference/VBA/FileSystem/EOF) returns **True** once a sequential read has run past the last record, [**LOF**](/en/official/Reference/VBA/FileSystem/LOF) returns the file's total length in bytes, and [**Loc**](/en/official/Reference/VBA/FileSystem/Loc) returns the current read/write position. The unit of *position* depends on the open mode --- record number for **Random**, byte offset for **Binary**, and the byte position divided by 128 for sequential modes --- so the per-mode tables on each function's page are the authoritative reference. [**Seek**](/en/official/Reference/VBA/FileSystem/Seek) doubles as a function and a statement: the function returns the position of the **next** read or write (whereas **Loc** reports the position of the *last*), and the statement repositions the file pointer ahead of the next operation. ```vb Dim N As Long, Line As String N = FreeFile Open "C:\Data\big.log" For Input As #N Do While Not EOF(N) Line Input #N, Line Loop Close #N ``` ## Reading and formatting through open file numbers [**Input**](/en/official/Reference/VBA/FileSystem/Input) and [**Input$**](/en/official/Reference/VBA/FileSystem/Input) return a fixed number of characters read from a file number opened with **Open**, as a **Variant** or a **String** respectively; [**InputB**](/en/official/Reference/VBA/FileSystem/InputB) and [**InputB$**](/en/official/Reference/VBA/FileSystem/InputB) are their byte-oriented counterparts, counting raw bytes rather than UTF-16 characters. They differ from the **Input #** statement in that they return every character they read --- commas, newlines, quotation marks, leading spaces, and all --- making them the right choice when the bytes on disk are not a stream of comma-delimited values. [**Width**](/en/official/Reference/VBA/FileSystem/Width) sets the output line width on a sequential output channel: subsequent **Print #** wraps to a new line once the chosen number of characters has been written, or never wraps at all when *Width* is `0`. ## Members * [ChDir](/en/official/Reference/VBA/FileSystem/ChDir) -- changes the current directory or folder * [ChDrive](/en/official/Reference/VBA/FileSystem/ChDrive) -- changes the current drive * [CurDir](/en/official/Reference/VBA/FileSystem/CurDir) -- returns the current path * [Dir](/en/official/Reference/VBA/FileSystem/Dir) -- returns the name of a file, directory, folder, or volume label that matches a pattern * [EOF](/en/official/Reference/VBA/FileSystem/EOF) -- returns whether the end of a file opened for **Random** or sequential **Input** has been reached * [FileAttr](/en/official/Reference/VBA/FileSystem/FileAttr) -- returns the file mode for files opened with the **Open** statement * [FileCopy](/en/official/Reference/VBA/FileSystem/FileCopy) -- copies a file * [FileDateTime](/en/official/Reference/VBA/FileSystem/FileDateTime) -- returns the date and time when a file was created or last modified * [FileLen](/en/official/Reference/VBA/FileSystem/FileLen) -- returns the length of a file in bytes * [FreeFile](/en/official/Reference/VBA/FileSystem/FreeFile) -- returns the next file number available for use by the **Open** statement * [GetAttr](/en/official/Reference/VBA/FileSystem/GetAttr) -- returns the attributes of a file or directory * [Input, Input$](/en/official/Reference/VBA/FileSystem/Input) -- reads a fixed number of characters from an open sequential file * [InputB, InputB$](/en/official/Reference/VBA/FileSystem/InputB) -- reads a fixed number of bytes from an open sequential file * [Kill](/en/official/Reference/VBA/FileSystem/Kill) -- deletes files from a disk * [Loc](/en/official/Reference/VBA/FileSystem/Loc) -- returns the current read/write position within an open file * [LOF](/en/official/Reference/VBA/FileSystem/LOF) -- returns the size, in bytes, of an open file * [MkDir](/en/official/Reference/VBA/FileSystem/MkDir) -- creates a new directory or folder * [Reset](/en/official/Reference/VBA/FileSystem/Reset) -- closes all disk files opened by using the **Open** statement * [RmDir](/en/official/Reference/VBA/FileSystem/RmDir) -- removes an existing directory or folder * [Seek](/en/official/Reference/VBA/FileSystem/Seek) -- returns or sets the read/write position within an open file * [SetAttr](/en/official/Reference/VBA/FileSystem/SetAttr) -- sets attribute information for a file * [Width](/en/official/Reference/VBA/FileSystem/Width) -- sets the line width for a sequential output file --- --- url: /zh/official/Reference/VBA/FileSystem.md --- # FileSystem模块 **FileSystem**模块将用于处理磁盘文件和目录的过程和语句组合在一起。其成员可分为两类:*基于路径名*的操作,作用于文件系统中命名的对象(创建和删除文件与目录、查询属性、遍历目录列表),以及*基于文件号*的操作,作用于先前由**Open**语句返回的句柄(读取、定位、格式化和跟踪通道)。 ## 导航目录 [**ChDrive**](/official/Reference/VBA/FileSystem/ChDrive)更改当前驱动器,[**ChDir**](/official/Reference/VBA/FileSystem/ChDir)更改指定驱动器上的当前目录,[**CurDir**](/official/Reference/VBA/FileSystem/CurDir)返回当前驱动器的路径——如果指定了其他驱动器,则返回该驱动器的路径。[**MkDir**](/official/Reference/VBA/FileSystem/MkDir)和[**RmDir**](/official/Reference/VBA/FileSystem/RmDir)分别创建和删除目录。 ```vb ChDrive "D" ChDir "D:\Projects" Debug.Print CurDir ' "D:\Projects" MkDir "D:\Projects\Output" ``` ## 检查文件和目录 [**Dir**](/official/Reference/VBA/FileSystem/Dir)是通配符匹配器:传入包含`*`或`?`的路径名,它返回第一个匹配的名称,然后不带参数再次调用可遍历后续匹配项,直到返回`""`。[**FileLen**](/official/Reference/VBA/FileSystem/FileLen)无需打开文件即可返回文件大小(字节),[**FileDateTime**](/official/Reference/VBA/FileSystem/FileDateTime)返回最后修改时间戳。[**GetAttr**](/official/Reference/VBA/FileSystem/GetAttr)和[**SetAttr**](/official/Reference/VBA/FileSystem/SetAttr)读取和写入[**VbFileAttribute**](/official/Reference/VBA/Constants/VbFileAttribute)标志位——只读、隐藏、系统、存档——**GetAttr**还通过设置**vbDirectory**位来报告名称是否指向目录。 ```vb Dim Name As String Name = Dir("C:\Logs\*.log") Do While Name <> "" Debug.Print Name & vbTab & FileLen("C:\Logs\" & Name) Name = Dir Loop ``` ## 复制和删除 [**FileCopy**](/official/Reference/VBA/FileSystem/FileCopy)将一个文件复制到另一个文件,[**Kill**](/official/Reference/VBA/FileSystem/Kill)删除匹配通配符模式的文件。两者都通过路径名操作,当要求对当前进程已打开的文件执行操作时会引发运行时错误。 ```vb FileCopy "C:\Data\report.xlsx", "C:\Backup\report.xlsx" Kill "C:\Backup\*.tmp" ``` ## 打开和跟踪文件号 较低层的读/写语句——**Open**、**Close**、**Get**、**Put**、**Print**、**Write**、**Input**和**Line Input**——使用1--511范围内的*文件号*进行操作。[**FreeFile**](/official/Reference/VBA/FileSystem/FreeFile)返回当前未使用的下一个文件号,使调用者无需手动选择并与其他代码竞争。文件打开后,[**FileAttr**](/official/Reference/VBA/FileSystem/FileAttr)报告文件号打开时的访问模式——**Input**、**Output**、**Random**、**Append**或**Binary**。[**Reset**](/official/Reference/VBA/FileSystem/Reset)关闭所有当前打开的文件号并刷新其缓冲区,在退出前作为最后的清理最为有用。 ```vb Dim N As Long N = FreeFile Open "C:\Data\report.txt" For Input As #N ' ... read ... Close #N ``` ## 打开文件中的位置 对于打开的文件号,[**EOF**](/official/Reference/VBA/FileSystem/EOF)在顺序读取超过最后一条记录后返回**True**,[**LOF**](/official/Reference/VBA/FileSystem/LOF)返回文件的总长度(字节),[**Loc**](/official/Reference/VBA/FileSystem/Loc)返回当前读/写位置。*位置*的单位取决于打开模式——**Random**模式为记录号,**Binary**模式为字节偏移量,顺序模式为字节位置除以128——因此每个函数页面上的按模式说明表是权威参考。[**Seek**](/official/Reference/VBA/FileSystem/Seek)兼具函数和语句的功能:函数返回*下一次*读或写的位置(而**Loc**报告*上一次*的位置),语句在下一次操作前重新定位文件指针。 ```vb Dim N As Long, Line As String N = FreeFile Open "C:\Data\big.log" For Input As #N Do While Not EOF(N) Line Input #N, Line Loop Close #N ``` ## 通过文件号读取和格式化 [**Input**](/official/Reference/VBA/FileSystem/Input)和[**Input$**](/official/Reference/VBA/FileSystem/Input)从以**Open**语句打开的文件号中读取固定数量的字符,分别返回**Variant**和**String**;[**InputB**](/official/Reference/VBA/FileSystem/InputB)和[**InputB$**](/official/Reference/VBA/FileSystem/InputB)是它们的面向字节版本,计算原始字节数而非UTF-16字符数。它们与\*\*Input #\*\*语句的不同之处在于,它们返回读取到的每个字符——逗号、换行符、引号、前导空格等——当磁盘上的字节不是逗号分隔值的流时,它们是正确的选择。 [**Width**](/official/Reference/VBA/FileSystem/Width)设置顺序输出通道上的输出行宽:后续的\*\*Print #\*\*在写入指定数量的字符后换行,当*Width*为`0`时则永不换行。 ## 成员 * [ChDir](/official/Reference/VBA/FileSystem/ChDir) -- 更改当前目录或文件夹 * [ChDrive](/official/Reference/VBA/FileSystem/ChDrive) -- 更改当前驱动器 * [CurDir](/official/Reference/VBA/FileSystem/CurDir) -- 返回当前路径 * [Dir](/official/Reference/VBA/FileSystem/Dir) -- 返回与模式匹配的文件、目录、文件夹或卷标的名称 * [EOF](/official/Reference/VBA/FileSystem/EOF) -- 返回是否已到达以**Random**或顺序**Input**模式打开的文件末尾 * [FileAttr](/official/Reference/VBA/FileSystem/FileAttr) -- 返回以**Open**语句打开的文件模式 * [FileCopy](/official/Reference/VBA/FileSystem/FileCopy) -- 复制文件 * [FileDateTime](/official/Reference/VBA/FileSystem/FileDateTime) -- 返回文件创建或最后修改的日期和时间 * [FileLen](/official/Reference/VBA/FileSystem/FileLen) -- 返回文件的字节长度 * [FreeFile](/official/Reference/VBA/FileSystem/FreeFile) -- 返回**Open**语句可用的下一个文件号 * [GetAttr](/official/Reference/VBA/FileSystem/GetAttr) -- 返回文件或目录的属性 * [Input, Input$](/official/Reference/VBA/FileSystem/Input) -- 从打开的顺序文件中读取固定数量的字符 * [InputB, InputB$](/official/Reference/VBA/FileSystem/InputB) -- 从打开的顺序文件中读取固定数量的字节 * [Kill](/official/Reference/VBA/FileSystem/Kill) -- 从磁盘删除文件 * [Loc](/official/Reference/VBA/FileSystem/Loc) -- 返回打开文件中当前的读/写位置 * [LOF](/official/Reference/VBA/FileSystem/LOF) -- 返回打开文件的大小(字节) * [MkDir](/official/Reference/VBA/FileSystem/MkDir) -- 创建新目录或文件夹 * [Reset](/official/Reference/VBA/FileSystem/Reset) -- 关闭所有以**Open**语句打开的磁盘文件 * [RmDir](/official/Reference/VBA/FileSystem/RmDir) -- 删除现有目录或文件夹 * [Seek](/official/Reference/VBA/FileSystem/Seek) -- 返回或设置打开文件中的读/写位置 * [SetAttr](/official/Reference/VBA/FileSystem/SetAttr) -- 设置文件的属性信息 * [Width](/official/Reference/VBA/FileSystem/Width) -- 设置顺序输出文件的行宽 --- --- url: /en/official/Reference/tbIDE/FileSystemItem.md --- # FileSystemItem class The base interface for everything inside the IDE's virtual file system. Both [**File**](/en/official/Reference/tbIDE/File) and [**Folder**](/en/official/Reference/tbIDE/Folder) extend **FileSystemItem** and inherit its four universal members ([**Name**](#name), [**Path**](#path), [**Type**](#type), [**Parent**](#parent)). An item returned from a [**Folder**](/en/official/Reference/tbIDE/Folder) enumeration or from [**FileSystem.ResolvePath**](/en/official/Reference/tbIDE/FileSystem#resolvepath) is normally castable to its specific kind --- the [**Type**](#type) property or `TypeOf` discriminates between them. ```vb Dim item As FileSystemItem For Each item In Host.CurrentProject.RootFolder If TypeOf item Is Folder Then ' …recurse Else Dim file As File = item ' …read End If Next ``` ## Properties ### Name The item's name (the last segment of its [**Path**](#path)). **String**, read-only. For files, includes the extension. ### Parent The folder that contains this item. **As** [**Folder**](/en/official/Reference/tbIDE/Folder). Read-only. The root folder's **Parent** is **Nothing**. ### Path The item's full virtual-FS path --- e.g. `"twinbasic:/Sources/MainModule.twin"`. **String**, read-only. Suitable as the *Path* argument to [**Editors.Open**](/en/official/Reference/tbIDE/Editors#open) and [**FileSystem.ResolvePath**](/en/official/Reference/tbIDE/FileSystem#resolvepath). ### Type The kind of item. **As** [**FileSystemItemType**](#filesystemitemtype) (see below). Read-only. For folders the value is always [**Folder**](#FileSystemItemType_Folder); for files it identifies the file's encoding and role. ## FileSystemItemType A type discriminator returned by [**Type**](#type). | Constant | Value | Description | |----------|-------|-------------| | **Folder** | 0 | A folder. | | **FileVIRTUALDOC** | 1 | A read-only virtual document --- the placeholder content the IDE renders for unrecognised file types. Unicode (UTF-16). | | **FileOTHER** | 2 | A file the IDE recognises as binary or whose encoding it cannot determine. [**File.ReadText**](/en/official/Reference/tbIDE/File#readtext) is not supported on this kind. | | **FileTWIN** | 3 | A twinBASIC source file (`.twin`). UTF-8 encoded on disk. | | **FileBAS** | 4 | A VB6-compatible standard module file (`.bas`). System ANSI encoded on disk. | | **FileCLS** | 5 | A VB6-compatible class module file (`.cls`). System ANSI encoded on disk. | | **FileUIDESIGNER** | 6 | A UI-designer surface for a Form, expressed as JSON. UTF-8 encoded. | | **FileJSON** | 7 | A JSON file --- typically the project's `Settings` or other JSON project data. UTF-8 encoded. | --- --- url: /zh/official/Reference/tbIDE/FileSystemItem.md --- # FileSystemItem 类 IDE 虚拟文件系统中所有内容的基础接口。[**File**](/official/Reference/tbIDE/File) 和 [**Folder**](/official/Reference/tbIDE/Folder) 都扩展 **FileSystemItem** 并继承其四个通用成员([**Name**](#name)、[**Path**](#path)、[**Type**](#type)、[**Parent**](#parent))。从 [**Folder**](/official/Reference/tbIDE/Folder) 枚举或 [**FileSystem.ResolvePath**](/official/Reference/tbIDE/FileSystem#resolvepath) 返回的项通常可转换为其具体类型——[**Type**](#type) 属性或 `TypeOf` 可在它们之间进行区分。 ```vb Dim item As FileSystemItem For Each item In Host.CurrentProject.RootFolder If TypeOf item Is Folder Then ' …递归 Else Dim file As File = item ' …读取 End If Next ``` ## 属性 ### Name 项的名称(其 [**Path**](#path) 的最后一段)。**String**,只读。对于文件,包括扩展名。 ### Parent 包含此项的文件夹。**As** [**Folder**](/official/Reference/tbIDE/Folder)。只读。根文件夹的 **Parent** 为 **Nothing**。 ### Path 项的完整虚拟文件系统路径——例如 `"twinbasic:/Sources/MainModule.twin"`。**String**,只读。可用作 [**Editors.Open**](/official/Reference/tbIDE/Editors#open) 和 [**FileSystem.ResolvePath**](/official/Reference/tbIDE/FileSystem#resolvepath) 的 *Path* 参数。 ### Type 项的类型。**As** [**FileSystemItemType**](#filesystemitemtype)(见下文)。只读。对于文件夹,值始终为 [**Folder**](#FileSystemItemType_Folder);对于文件,它标识文件的编码和角色。 ## FileSystemItemType 由 [**Type**](#type) 返回的类型判别值。 | 常量 | 值 | 描述 | |------|-----|------| | **Folder** | 0 | 一个文件夹。 | | **FileVIRTUALDOC** | 1 | 只读虚拟文档——IDE 为无法识别的文件类型渲染的占位内容。Unicode (UTF-16)。 | | **FileOTHER** | 2 | IDE 识别为二进制的文件或无法确定其编码的文件。[**File.ReadText**](/official/Reference/tbIDE/File#readtext) 不支持此类型。 | | **FileTWIN** | 3 | twinBASIC 源文件(`.twin`)。磁盘上为 UTF-8 编码。 | | **FileBAS** | 4 | VB6 兼容的标准模块文件(`.bas`)。磁盘上为系统 ANSI 编码。 | | **FileCLS** | 5 | VB6 兼容的类模块文件(`.cls`)。磁盘上为系统 ANSI 编码。 | | **FileUIDESIGNER** | 6 | 窗体的 UI 设计器表面,以 JSON 表示。UTF-8 编码。 | | **FileJSON** | 7 | JSON 文件——通常是项目的 `Settings` 或其他 JSON 项目数据。UTF-8 编码。 | --- --- url: /en/official/Reference/CustomControls/Styles/Fill.md --- # Fill class The colour or gradient that paints a region --- background of a control, body of a border, fill of a grid line, foreground of text. A **Fill** has two parts: a [**Pattern**](#pattern) that picks the gradient direction (or `tbPatternNone` for transparent), and a [**ColorPoints**](#colorpoints) collection of one or more colour stops that supply the actual colours. A single solid colour is just a one-stop fill: call [**ColorPoints.SetSolidColor**](#setsolidcolor) with a `Long` colour, or [**SetSimplePattern**](#setsimplepattern) on the parent **Fill** for a two-colour gradient. ```vb btnGo.NormalState.BackgroundFill.ColorPoints.SetSolidColor vbBlue btnGo.HoverState.BackgroundFill.SetSimplePattern vbBlue, vbWhite, _ Pattern:=tbGradientNorthToSouth ``` For three or more colour stops, build [**FillColorPoint**](#fillcolorpoint-class) instances and pass them to [**SetColorPoints**](#setcolorpoints). The stops accept fully-opaque ARGB literals (`&HFF` alpha in the high byte) --- see [**ColorRGBA**](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) for the encoding: ```vb With pnlHeader.BackgroundFill .Pattern = tbGradientNorthToSouth .ColorPoints.SetColorPoints _ New FillColorPoint(&HFFF3E58F, 0), _ New FillColorPoint(&HFF99CCFF, 50), _ New FillColorPoint(&HFF014C99, 100) End With ``` ## Properties ### ColorPoints The [**FillColorPoints**](#fillcolorpoints-class) collection holding the gradient stops. Always present and pre-allocated; assigning new stops is done by calling methods on this object rather than replacing the collection. ### Pattern How the colours in [**ColorPoints**](#colorpoints) are mapped across the region. A member of [**FillPattern**](/en/official/Reference/CustomControls/Enumerations/FillPattern). Default: **tbGradientNorthToSouth**. Use **tbPatternNone** to make the **Fill** transparent. ## Methods ### SetSimplePattern Replaces the colour stops with a two-stop gradient between two solid colours, optionally adjusting the [**Granularity**](#granularity) and [**Pattern**](#pattern) at the same time. The colours are given as ordinary `Long` values (the `vb…` colour constants or a hex literal); the opaque alpha mask is OR-ed in automatically. Syntax: *object*.**SetSimplePattern** *Value1RGB*, *Value2RGB* \[, *Granularity* \[, *Pattern* ] ] *Value1RGB* : *required* A **Long** RGB colour for the first gradient stop (position 0). *Value2RGB* : *required* A **Long** RGB colour for the second gradient stop (position 100). *Granularity* : *optional* The colour-table size assigned to [**Granularity**](#granularity). Default: 100. *Pattern* : *optional* A member of [**FillPattern**](/en/official/Reference/CustomControls/Enumerations/FillPattern). Default: **tbGradientNorthToSouth**. ### SetSimplePatternRGBA Same as [**SetSimplePattern**](#setsimplepattern) but accepts raw 32-bit [**ColorRGBA**](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) values with their own alpha channels rather than three-byte RGB colours. Syntax: *object*.**SetSimplePatternRGBA** *Value1RGBA*, *Value2RGBA* \[, *Granularity* \[, *Pattern* ] ] *Value1RGBA* : *required* A [**ColorRGBA**](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) (ABGR) value for the first gradient stop. *Value2RGBA* : *required* A [**ColorRGBA**](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) (ABGR) value for the second gradient stop. *Granularity* : *optional* The colour-table size assigned to [**Granularity**](#granularity). Default: 100. *Pattern* : *optional* A member of [**FillPattern**](/en/official/Reference/CustomControls/Enumerations/FillPattern). Default: **tbGradientNorthToSouth**. ## Events ### OnChanged Raised whenever [**Pattern**](#pattern) is assigned or the [**ColorPoints**](#colorpoints) collection raises its own **OnChanged**. ## FillColorPoints class The collection of [**FillColorPoint**](#fillcolorpoint-class) stops that define a [**Fill**](#)'s colour gradient. Accessed as [**Fill.ColorPoints**](#colorpoints). Internally an array of **FillColorPoint** plus a [**Granularity**](#granularity) integer. ### Granularity The size of the generated colour table that interpolates the stops. Higher values give smoother gradients; a value of 2 produces a hard transition between just two colours regardless of how many stops the collection holds. **Long**. Default: 100. ### Values The array of [**FillColorPoint**](#fillcolorpoint-class) gradient stops. Read-write, but in practice populated through the [**SetSolidColor**](#setsolidcolor), [**SetSolidColorRGBA**](#setsolidcolorrgba), [**SetColorPoints**](#setcolorpoints), or [**SetColorPointsArray**](#setcolorpointsarray) methods rather than by assigning the array directly. ### SetSolidColor Replaces the stop array with a single fully-opaque stop. Takes a three-byte `Long` colour and OR-s in the opaque alpha mask. Syntax: *object*.**SetSolidColor** *ValueRGB* *ValueRGB* : *required* A **Long** RGB colour. ### SetSolidColorRGBA Replaces the stop array with a single stop whose alpha is taken from the supplied value rather than forced opaque. Syntax: *object*.**SetSolidColorRGBA** *ValueRGBA* *ValueRGBA* : *required* A [**ColorRGBA**](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) (ABGR) value. ### SetColorPoints Replaces the stop array with the supplied [**FillColorPoint**](#fillcolorpoint-class) values, in order. Syntax: *object*.**SetColorPoints** *ColorPoint1* \[, *ColorPoint2*, … ] *ColorPoint1*, *ColorPoint2*, … : *required* One or more [**FillColorPoint**](#fillcolorpoint-class) objects, passed as **Variant**s through a `ParamArray`. ### SetColorPointsArray Replaces the stop array with the contents of an existing array of [**FillColorPoint**](#fillcolorpoint-class). Syntax: *object*.**SetColorPointsArray** *ColorPoints* ( ) *ColorPoints* : *required* An array of [**FillColorPoint**](#fillcolorpoint-class). Uninitialised or empty arrays leave the collection unchanged. ### OnChanged Raised when the array of stops is reassigned or when any single stop raises its own **OnChanged**, or when [**Granularity**](#granularity) is assigned. The parent [**Fill**](#) listens for this event and re-raises its own. ## FillColorPoint class A single gradient stop --- a colour together with the position (0--100 %) at which the colour applies along the gradient. Elements of the [**FillColorPoints.Values**](#values) array. ### Color The stop's colour as a 32-bit ABGR value. [**ColorRGBA**](/en/official/Reference/CustomControls/Enumerations/ColorRGBA). ### PositionPercent The stop's position along the gradient, as a percentage from 0 to 100. **Double**. A two-stop gradient typically has stops at 0 and 100; intermediate stops at 25 / 50 / 75 produce smooth multi-colour transitions. ### New Constructs a [**FillColorPoint**](#fillcolorpoint-class). The parameterless overload sets neither field; the two-argument overload sets both. Syntax: **New FillColorPoint** \[ ( *ColorRGBA*, *PositionPercent* ) ] *ColorRGBA* : *optional* A [**ColorRGBA**](/en/official/Reference/CustomControls/Enumerations/ColorRGBA) value to assign to [**Color**](#color). *PositionPercent* : *optional* A **Double** to assign to [**PositionPercent**](#positionpercent). ### OnChanged Raised when either [**Color**](#color) or [**PositionPercent**](#positionpercent) is assigned. The parent [**FillColorPoints**](#fillcolorpoints-class) listens for this event. --- --- url: /zh/official/Reference/CustomControls/Styles/Fill.md --- # Fill 类 绘制区域的颜色或渐变——控件的背景、边框的主体、网格线的填充、文本的前景。**Fill** 有两部分:[**Pattern**](#pattern) 选择渐变方向(或 `tbPatternNone` 表示透明),以及 [**ColorPoints**](#colorpoints) 包含一个或多个颜色 stops 的集合,提供实际颜色。 单色填充就是单 stop 填充:用 `Long` 颜色调用 [**ColorPoints.SetSolidColor**](#setsolidcolor),或在父 **Fill** 上调用 [**SetSimplePattern**](#setsimplepattern) 实现双色渐变。 ```vb btnGo.NormalState.BackgroundFill.ColorPoints.SetSolidColor vbBlue btnGo.HoverState.BackgroundFill.SetSimplePattern vbBlue, vbWhite, _ Pattern:=tbGradientNorthToSouth ``` 对于三个或更多颜色 stops,构建 [**FillColorPoint**](#fillcolorpoint-class) 实例并传给 [**SetColorPoints**](#setcolorpoints)。stops 接受完全不透明的 ARGB 字面量(`&HFF` alpha 在高字节)——参见 [**ColorRGBA**](/official/Reference/CustomControls/Enumerations/ColorRGBA) 了解编码: ```vb With pnlHeader.BackgroundFill .Pattern = tbGradientNorthToSouth .ColorPoints.SetColorPoints _ New FillColorPoint(&HFFF3E58F, 0), _ New FillColorPoint(&HFF99CCFF, 50), _ New FillColorPoint(&HFF014C99, 100) End With ``` ## 属性 ### ColorPoints 持有渐变 stops 的 [**FillColorPoints**](#fillcolorpoints-class) 集合。始终存在且已预分配;赋新 stops 通过调用此对象上的方法完成而非替换集合。 ### Pattern [**ColorPoints**](#colorpoints) 中的颜色如何映射到区域。[**FillPattern**](/official/Reference/CustomControls/Enumerations/FillPattern) 的成员。默认:**tbGradientNorthToSouth**。使用 **tbPatternNone** 使 **Fill** 透明。 ## 方法 ### SetSimplePattern 用两个纯色之间的双 stop 渐变替换颜色 stops,可选同时调整 [**Granularity**](#granularity) 和 [**Pattern**](#pattern)。颜色以普通 `Long` 值给出(`vb…` 颜色常量或十六进制字面量);不透明 alpha 掩码自动 OR 进去。 语法:*object*.**SetSimplePattern** *Value1RGB*, *Value2RGB* \[, *Granularity* \[, *Pattern* ] ] *Value1RGB* : *必需* **Long** RGB 颜色,第一个渐变 stop(位置 0)。 *Value2RGB* : *必需* **Long** RGB 颜色,第二个渐变 stop(位置 100)。 *Granularity* : *可选* 赋给 [**Granularity**](#granularity) 的颜色表大小。默认:100。 *Pattern* : *可选* [**FillPattern**](/official/Reference/CustomControls/Enumerations/FillPattern) 的成员。默认:**tbGradientNorthToSouth**。 ### SetSimplePatternRGBA 与 [**SetSimplePattern**](#setsimplepattern) 相同,但接受带有自身 alpha 通道的原始 32 位 [**ColorRGBA**](/official/Reference/CustomControls/Enumerations/ColorRGBA) 值而非三字节 RGB 颜色。 语法:*object*.**SetSimplePatternRGBA** *Value1RGBA*, *Value2RGBA* \[, *Granularity* \[, *Pattern* ] ] *Value1RGBA* : *必需* [**ColorRGBA**](/official/Reference/CustomControls/Enumerations/ColorRGBA)(ABGR)值,第一个渐变 stop。 *Value2RGBA* : *必需* [**ColorRGBA**](/official/Reference/CustomControls/Enumerations/ColorRGBA)(ABGR)值,第二个渐变 stop。 *Granularity* : *可选* 赋给 [**Granularity**](#granularity) 的颜色表大小。默认:100。 *Pattern* : *可选* [**FillPattern**](/official/Reference/CustomControls/Enumerations/FillPattern) 的成员。默认:**tbGradientNorthToSouth**。 ## 事件 ### OnChanged [**Pattern**](#pattern) 被赋值或 [**ColorPoints**](#colorpoints) 集合触发其自身的 **OnChanged** 时触发。 ## FillColorPoints 类 定义 [**Fill**](#) 颜色渐变的 [**FillColorPoint**](#fillcolorpoint-class) stops 集合。通过 [**Fill.ColorPoints**](#colorpoints) 访问。内部为 **FillColorPoint** 数组加 [**Granularity**](#granularity) 整数。 ### Granularity 插值 stops 的生成颜色表大小。值越高渐变越平滑;值为 2 产生仅两种颜色之间的硬过渡,无论集合中有多少 stops。**Long**。默认:100。 ### Values [**FillColorPoint**](#fillcolorpoint-class) 渐变 stops 数组。可读写,但实际上通过 [**SetSolidColor**](#setsolidcolor)、[**SetSolidColorRGBA**](#setsolidcolorrgba)、[**SetColorPoints**](#setcolorpoints) 或 [**SetColorPointsArray**](#setcolorpointsarray) 方法填充而非直接赋数组。 ### SetSolidColor 用单个完全不透明 stop 替换 stop 数组。接受三字节 `Long` 颜色并 OR 进不透明 alpha 掩码。 语法:*object*.**SetSolidColor** *ValueRGB* *ValueRGB* : *必需* **Long** RGB 颜色。 ### SetSolidColorRGBA 用单个 stop 替换 stop 数组,其 alpha 取自提供的值而非强制不透明。 语法:*object*.**SetSolidColorRGBA** *ValueRGBA* *ValueRGBA* : *必需* [**ColorRGBA**](/official/Reference/CustomControls/Enumerations/ColorRGBA)(ABGR)值。 ### SetColorPoints 用提供的 [**FillColorPoint**](#fillcolorpoint-class) 值按顺序替换 stop 数组。 语法:*object*.**SetColorPoints** *ColorPoint1* \[, *ColorPoint2*, … ] *ColorPoint1*, *ColorPoint2*, … : *必需* 一个或多个 [**FillColorPoint**](#fillcolorpoint-class) 对象,通过 `ParamArray` 以 **Variant** 传入。 ### SetColorPointsArray 用现有 [**FillColorPoint**](#fillcolorpoint-class) 数组的内容替换 stop 数组。 语法:*object*.**SetColorPointsArray** *ColorPoints* ( ) *ColorPoints* : *必需* [**FillColorPoint**](#fillcolorpoint-class) 数组。未初始化或空数组使集合不变。 ### OnChanged stop 数组被重新赋值或任一 stop 触发其自身的 **OnChanged**,或 [**Granularity**](#granularity) 被赋值时触发。父 [**Fill**](#) 监听此事件并重新触发自身的。 ## FillColorPoint 类 单个渐变 stop——颜色及沿渐变的位置(0--100%)。[**FillColorPoints.Values**](#values) 数组的元素。 ### Color stop 的颜色,32 位 ABGR 值。[**ColorRGBA**](/official/Reference/CustomControls/Enumerations/ColorRGBA)。 ### PositionPercent stop 沿渐变的位置,0 到 100 的百分比。**Double**。双 stop 渐变通常在 0 和 100 位置;25 / 50 / 75 的中间 stops 产生平滑的多色过渡。 ### New 构造 [**FillColorPoint**](#fillcolorpoint-class)。无参重载不设置任何字段;双参数重载设置两个字段。 语法:**New FillColorPoint** \[ ( *ColorRGBA*, *PositionPercent* ) ] *ColorRGBA* : *可选* [**ColorRGBA**](/official/Reference/CustomControls/Enumerations/ColorRGBA) 值,赋给 [**Color**](#color)。 *PositionPercent* : *可选* **Double**,赋给 [**PositionPercent**](#positionpercent)。 ### OnChanged [**Color**](#color) 或 [**PositionPercent**](#positionpercent) 被赋值时触发。父 [**FillColorPoints**](#fillcolorpoints-class) 监听此事件。 --- --- url: /en/official/Reference/CustomControls/Enumerations/FillPattern.md --- # FillPattern Identifies how the colour table held by a [**Fill**](/en/official/Reference/CustomControls/Styles/Fill) is applied across the area being painted. The same colour stops produce very different results depending on the pattern --- a north-to-south gradient with two stops paints a top-to-bottom transition, while a corner gradient with the same stops paints from one corner outward. Used by [**Fill.Pattern**](/en/official/Reference/CustomControls/Styles/Fill#pattern). | Constant | Value | Description | |----------|-------|-------------| | **tbPatternNone** | 0 | No fill --- leaves the region transparent. | | **tbGradientNorthToSouth** | 1 | Linear gradient from the top edge down to the bottom edge. | | **tbGradientSouthToNorth** | 2 | Linear gradient from the bottom edge up to the top edge. | | **tbGradientWestToEast** | 3 | Linear gradient from the left edge across to the right edge. | | **tbGradientEastToWest** | 4 | Linear gradient from the right edge across to the left edge. | | **tbGradientNorthWestToSouthEast** | 5 | Linear diagonal gradient from the top-left corner to the bottom-right. | | **tbGradientNorthWestToSouthEastAlt** | 6 | Alternate diagonal: same axis as **tbGradientNorthWestToSouthEast** but with the stops mirrored about the centre. | | **tbGradientNorthEastToSouthWest** | 7 | Linear diagonal gradient from the top-right corner to the bottom-left. | | **tbGradientNorthEastToSouthWestAlt** | 8 | Alternate diagonal: same axis as **tbGradientNorthEastToSouthWest** but mirrored. | | **tbGradientSouthWestToNorthEast** | 9 | Linear diagonal gradient from the bottom-left corner to the top-right. | | **tbGradientSouthWestToNorthEastAlt** | 10 | Alternate diagonal: same axis as **tbGradientSouthWestToNorthEast** but mirrored. | | **tbGradientSouthEastToNorthWest** | 11 | Linear diagonal gradient from the bottom-right corner to the top-left. | | **tbGradientSouthEastToNorthWestAlt** | 12 | Alternate diagonal: same axis as **tbGradientSouthEastToNorthWest** but mirrored. | | **tbGradientCornerTopLeft** | 13 | Radial-style gradient emanating from the top-left corner outward. | | **tbGradientCornerTopRight** | 14 | Radial-style gradient emanating from the top-right corner outward. | | **tbGradientCornerBottomLeft** | 15 | Radial-style gradient emanating from the bottom-left corner outward. | | **tbGradientCornerBottomRight** | 16 | Radial-style gradient emanating from the bottom-right corner outward. | | **tbGradientCornerTopLeftAlt** | 17 | Alternate top-left corner gradient with the stops mirrored. | | **tbGradientCornerTopRightAlt** | 18 | Alternate top-right corner gradient with the stops mirrored. | | **tbGradientCornerBottomLeftAlt** | 19 | Alternate bottom-left corner gradient with the stops mirrored. | | **tbGradientCornerBottomRightAlt** | 20 | Alternate bottom-right corner gradient with the stops mirrored. | The colour table itself comes from the array of [**FillColorPoint**](/en/official/Reference/CustomControls/Styles/Fill#fillcolorpoint-class) values inside [**Fill.ColorPoints**](/en/official/Reference/CustomControls/Styles/Fill#colorpoints), interpolated to the configured [**Granularity**](/en/official/Reference/CustomControls/Styles/Fill#granularity). The same two-stop pair painted with three different patterns produces three quite different results: ```vb ' Top fades to bottom pnlOne.BackgroundFill.SetSimplePattern vbWhite, &H99CCFF, _ Pattern:=tbGradientNorthToSouth ' Left fades to right pnlTwo.BackgroundFill.SetSimplePattern vbWhite, &H99CCFF, _ Pattern:=tbGradientWestToEast ' Emanates from the top-left corner pnlThree.BackgroundFill.SetSimplePattern vbWhite, &H99CCFF, _ Pattern:=tbGradientCornerTopLeft ``` **tbPatternNone** produces a flat region with no gradient --- the `Fill` becomes fully transparent and the area behind the control shows through. --- --- url: /zh/official/Reference/CustomControls/Enumerations/FillPattern.md --- # FillPattern 标识 [**Fill**](/official/Reference/CustomControls/Styles/Fill) 持有的颜色表如何跨被绘制区域应用。相同的颜色 stops 根据模式产生非常不同的结果——双 stop 的北到南渐变绘制上到下过渡,而相同 stops 的角渐变从一个角向外绘制。由 [**Fill.Pattern**](/official/Reference/CustomControls/Styles/Fill#pattern) 使用。 | 常量 | 值 | 说明 | |------|----|------| | **tbPatternNone** | 0 | 无填充——区域保持透明。 | | **tbGradientNorthToSouth** | 1 | 从上边缘到下边缘的线性渐变。 | | **tbGradientSouthToNorth** | 2 | 从下边缘到上边缘的线性渐变。 | | **tbGradientWestToEast** | 3 | 从左边缘跨到右边缘的线性渐变。 | | **tbGradientEastToWest** | 4 | 从右边缘跨到左边缘的线性渐变。 | | **tbGradientNorthWestToSouthEast** | 5 | 从左上角到右下角的线性对角渐变。 | | **tbGradientNorthWestToSouthEastAlt** | 6 | 替代对角:与 **tbGradientNorthWestToSouthEast** 同轴但 stops 关于中心镜像。 | | **tbGradientNorthEastToSouthWest** | 7 | 从右上角到左下角的线性对角渐变。 | | **tbGradientNorthEastToSouthWestAlt** | 8 | 替代对角:与 **tbGradientNorthEastToSouthWest** 同轴但镜像。 | | **tbGradientSouthWestToNorthEast** | 9 | 从左下角到右上角的线性对角渐变。 | | **tbGradientSouthWestToNorthEastAlt** | 10 | 替代对角:与 **tbGradientSouthWestToNorthEast** 同轴但镜像。 | | **tbGradientSouthEastToNorthWest** | 11 | 从右下角到左上角的线性对角渐变。 | | **tbGradientSouthEastToNorthWestAlt** | 12 | 替代对角:与 **tbGradientSouthEastToNorthWest** 同轴但镜像。 | | **tbGradientCornerTopLeft** | 13 | 从左上角向外辐射的径向风格渐变。 | | **tbGradientCornerTopRight** | 14 | 从右上角向外辐射的径向风格渐变。 | | **tbGradientCornerBottomLeft** | 15 | 从左下角向外辐射的径向风格渐变。 | | **tbGradientCornerBottomRight** | 16 | 从右下角向外辐射的径向风格渐变。 | | **tbGradientCornerTopLeftAlt** | 17 | 替代左上角渐变,stops 镜像。 | | **tbGradientCornerTopRightAlt** | 18 | 替代右上角渐变,stops 镜像。 | | **tbGradientCornerBottomLeftAlt** | 19 | 替代左下角渐变,stops 镜像。 | | **tbGradientCornerBottomRightAlt** | 20 | 替代右下角渐变,stops 镜像。 | 颜色表来自 [**Fill.ColorPoints**](/official/Reference/CustomControls/Styles/Fill#colorpoints) 内的 [**FillColorPoint**](/official/Reference/CustomControls/Styles/Fill#fillcolorpoint-class) 值数组,插值到配置的 [**Granularity**](/official/Reference/CustomControls/Styles/Fill#granularity)。 相同双 stop 对用三种不同模式绘制产生三种截然不同的结果: ```vb ' Top fades to bottom pnlOne.BackgroundFill.SetSimplePattern vbWhite, &H99CCFF, _ Pattern:=tbGradientNorthToSouth ' Left fades to right pnlTwo.BackgroundFill.SetSimplePattern vbWhite, &H99CCFF, _ Pattern:=tbGradientWestToEast ' Emanates from the top-left corner pnlThree.BackgroundFill.SetSimplePattern vbWhite, &H99CCFF, _ Pattern:=tbGradientCornerTopLeft ``` **tbPatternNone** 产生无渐变的平坦区域——`Fill` 变为完全透明,控件后面的区域可见。 --- --- url: /en/official/Reference/VBRUN/Constants/FillStyleConstants.md --- # FillStyleConstants Pattern values for the **FillStyle** property of forms, picture boxes, and shape controls. | Constant | Value | Description | |----------|-------|-------------| | **vbFSSolid** | 0 | Solid fill in **FillColor**. | | **vbFSTransparent** | 1 | No fill --- the background shows through. | | **vbHorizontalLine** | 2 | Horizontal lines. | | **vbVerticalLine** | 3 | Vertical lines. | | **vbUpwardDiagonal** | 4 | Upward-sloping diagonal lines. | | **vbDownwardDiagonal** | 5 | Downward-sloping diagonal lines. | | **vbCross** | 6 | Crossed horizontal and vertical lines. | | **vbDiagonalCross** | 7 | Crossed diagonal lines. | --- --- url: /zh/official/Reference/VBRUN/Constants/FillStyleConstants.md --- # FillStyleConstants 窗体、图片框和形状控件的**FillStyle**属性的图案值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbFSSolid** | 0 | 以**FillColor**纯色填充。 | | **vbFSTransparent** | 1 | 不填充 --- 背景可见。 | | **vbHorizontalLine** | 2 | 水平线。 | | **vbVerticalLine** | 3 | 垂直线。 | | **vbUpwardDiagonal** | 4 | 上斜对角线。 | | **vbDownwardDiagonal** | 5 | 下斜对角线。 | | **vbCross** | 6 | 十字交叉线。 | | **vbDiagonalCross** | 7 | 对角交叉线。 | --- --- url: /en/official/Reference/VBRUN/Constants/FillStyleConstantsEx.md --- # FillStyleConstantsEx Extended fill-pattern values for controls that support twinBASIC's gradient fills in addition to the classic patterns from [**FillStyleConstants**](/en/official/Reference/VBRUN/Constants/FillStyleConstants). The enumeration is tagged **\[MustBeQualified]**, so members must be referenced through the enum name (`FillStyleConstantsEx.vbGradientNS`) to avoid clashing with [**FillStyleConstants**](/en/official/Reference/VBRUN/Constants/FillStyleConstants). | Constant | Value | Description | |----------|-------|-------------| | **vbFSSolid** | 0 | Solid fill in **FillColor**. | | **vbFSTransparent** | 1 | No fill --- the background shows through. | | **vbHorizontalLine** | 2 | Horizontal lines. | | **vbVerticalLine** | 3 | Vertical lines. | | **vbUpwardDiagonal** | 4 | Upward-sloping diagonal lines. | | **vbDownwardDiagonal** | 5 | Downward-sloping diagonal lines. | | **vbCross** | 6 | Crossed horizontal and vertical lines. | | **vbDiagonalCross** | 7 | Crossed diagonal lines. | | **vbGradientNS** | 8 | Vertical (north--south) linear gradient. *(twinBASIC addition.)* | | **vbGradientWE** | 9 | Horizontal (west--east) linear gradient. *(twinBASIC addition.)* | --- --- url: /zh/official/Reference/VBRUN/Constants/FillStyleConstantsEx.md --- # FillStyleConstantsEx 支持twinBASIC渐变填充(除[**FillStyleConstants**](/official/Reference/VBRUN/Constants/FillStyleConstants)中的经典图案外)的控件的扩展填充图案值。该枚举标记为\*\*\[MustBeQualified]\*\*,因此成员必须通过枚举名引用(`FillStyleConstantsEx.vbGradientNS`),以避免与[**FillStyleConstants**](/official/Reference/VBRUN/Constants/FillStyleConstants)冲突。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbFSSolid** | 0 | 以**FillColor**纯色填充。 | | **vbFSTransparent** | 1 | 不填充 --- 背景可见。 | | **vbHorizontalLine** | 2 | 水平线。 | | **vbVerticalLine** | 3 | 垂直线。 | | **vbUpwardDiagonal** | 4 | 上斜对角线。 | | **vbDownwardDiagonal** | 5 | 下斜对角线。 | | **vbCross** | 6 | 十字交叉线。 | | **vbDiagonalCross** | 7 | 对角交叉线。 | | **vbGradientNS** | 8 | 垂直(南北)线性渐变。*(twinBASIC新增)* | | **vbGradientWE** | 9 | 水平(东西)线性渐变。*(twinBASIC新增)* | --- --- url: /en/official/Reference/VBA/Strings/Filter.md --- # Filter Returns a zero-based array containing a subset of a string array based on a specified filter criteria. Syntax: **Filter(** *sourcearray*, *match* \[ **,** *include* \[ **,** *compare* ] ] **)** *sourcearray* : *required* One-dimensional array of strings to be searched. *match* : *required* String to search for. *include* : *optional* **Boolean** value indicating whether to return substrings that include or exclude *match*. If *include* is **True**, **Filter** returns the subset of the array that contains *match* as a substring. If *include* is **False**, **Filter** returns the subset of the array that does not contain *match* as a substring. *compare* : *optional* Numeric value indicating the kind of string comparison to use. See settings below. The *compare* argument can have the following values: | Constant | Value | Description | |------------------------|-------|------------------------------------------------------------------------------------------| | **vbUseCompareOption** | -1 | Performs a comparison by using the setting of the [**Option Compare**](/en/official/Reference/Core/Option) statement. | | **vbBinaryCompare** | 0 | Performs a binary comparison. | | **vbTextCompare** | 1 | Performs a textual comparison. | The array returned by the **Filter** function contains only enough elements to contain the number of matched items. ### See Also * [Join](/en/official/Reference/VBA/Strings/Join), [Split](/en/official/Reference/VBA/Strings/Split) functions --- --- url: /zh/official/Reference/VBA/Strings/Filter.md --- # Filter 返回一个从零开始的数组,包含基于指定筛选条件的字符串数组的子集。 语法:**Filter(** *sourcearray*, *match* \[ **,** *include* \[ **,** *compare* ] ] **)** *sourcearray* : *必需* 要搜索的一维字符串数组。 *match* : *必需* 要搜索的字符串。 *include* : *可选* **Boolean**值,指示是否返回包含或排除*match*的子字符串。如果*include*为**True**,**Filter**返回包含*match*作为子字符串的数组子集。如果*include*为**False**,**Filter**返回不包含*match*作为子字符串的数组子集。 *compare* : *可选* 数值,指示要使用的字符串比较类型。参见下面的设置。 *compare*参数可以取以下值: | 常量 | 值 | 描述 | |------------------------|-----|----------------------------------------------------------------------------------| | **vbUseCompareOption** | -1 | 使用[**Option Compare**](/official/Reference/Core/Option)语句的设置进行比较。 | | **vbBinaryCompare** | 0 | 执行二进制比较。 | | **vbTextCompare** | 1 | 执行文本比较。 | **Filter**函数返回的数组仅包含足够的元素来容纳匹配项的数量。 ### 另请参阅 * [Join](/official/Reference/VBA/Strings/Join)、[Split](/official/Reference/VBA/Strings/Split)函数 --- --- url: /zh/official/Reference/VBA/Financial.md --- # Financial 模块 **Financial** 模块将解决标准时间价值问题的过程组合在一起——固定周期现金流的贷款和储蓄计划的年金计算、不规则现金流系列的收益率和现值分析,以及三种不同会计惯例下的资产折旧。 ## 年金 *年金*是一系列在等间隔期间进行的固定现金支付。模块的七个函数描述同一个基础年金模型,区别仅在于它们求解*哪个*量:[**FV**](/official/Reference/VBA/Financial/FV) 返回终值(最终付款后的现金余额),[**PV**](/official/Reference/VBA/Financial/PV) 返回现值(未来现金流的当前价值),[**Pmt**](/official/Reference/VBA/Financial/Pmt) 返回每期付款金额,[**NPer**](/official/Reference/VBA/Financial/NPer) 返回期数,[**Rate**](/official/Reference/VBA/Financial/Rate) 返回每期利率。[**IPmt**](/official/Reference/VBA/Financial/IPmt) 和 [**PPmt**](/official/Reference/VBA/Financial/PPmt) 将单笔付款分解为利息和本金部分。 这七个函数都采用相同的核心参数——*rate*、*nper*、*pmt*、*pv*、*fv*、*type*——以不同顺序排列,未知的参数省略。*rate* 是每期利率(年百分比除以每年期数);*nper* 是总付款期数;*pmt* 是每期付款额;*pv* 和 *fv* 是现值和终值;*type* 为 `0` 表示期末付款,为 `1` 表示期初付款。**Rate** 额外接受 *guess* 参数——它通过迭代求解方程,当默认值 10% 无法在 20 个循环内收敛时,可以提供起始估计值。 ```vb Const APR As Double = 0.06 Dim Monthly As Double Monthly = -Pmt(APR / 12, 30 * 12, 200000) ' fixed monthly payment on a 30-year, $200,000 mortgage at 6 % APR ``` ## 变动现金流 对于各期现金流不同的投资,三个函数接受值数组而非单一付款额。[**NPV**](/official/Reference/VBA/Financial/NPV) 返回按选定折现率折现的现金流净现值;[**IRR**](/official/Reference/VBA/Financial/IRR) 返回内部收益率——使 **NPV** 为零的折现率;[**MIRR**](/official/Reference/VBA/Financial/MIRR) 返回修正内部收益率,其中流出和再投资流入以不同利率折现。数组中值的顺序很重要——元素 *i* 是第 *i* 期的现金流——数组必须包含至少一个负值(付款)和一个正值(收入)。与 **Rate** 一样,**IRR** 和 **MIRR** 都通过迭代计算,接受可选的 *guess*。 ```vb Dim CashFlows(0 To 4) As Double CashFlows(0) = -70000 ' initial outlay CashFlows(1) = 22000 : CashFlows(2) = 25000 CashFlows(3) = 28000 : CashFlows(4) = 31000 Debug.Print IRR(CashFlows) ' approximate internal rate of return Debug.Print NPV(0.0625, CashFlows) ' net present value at a 6.25 % discount rate ``` ## 折旧 三个函数在三种不同会计惯例下返回资产在选定期间的折旧,全部以资产的初始*成本*、其使用寿命结束时的*残值*及其以期为单位的*寿命*为参数。[**SLN**](/official/Reference/VBA/Financial/SLN) 应用直线折旧法,将损耗价值均匀分摊到每期。[**DDB**](/official/Reference/VBA/Financial/DDB) 应用双倍余额递减法(或选定倍数),前期折旧最高,此后几何递减。[**SYD**](/official/Reference/VBA/Financial/SYD) 应用年数总和法——也是加速折旧,但线性递减。 **SLN** 每期返回相同值;**DDB** 和 **SYD** 因此都需要额外的 *period* 参数指定要报告哪一期。 ## 符号约定和单位 两个约定贯穿整个模块。首先,**现金流有符号**:付出的钱(抵押贷款还款、储蓄存款、投资支出)用负数表示,收到的钱(贷款收入、储蓄提取、股息)用正数表示。无论值是作为单一参数(*pmt*、*pv*、*fv*)还是作为现金流数组的元素,都适用相同的约定——将付款输入为正数是导致意外结果的最常见原因。 其次,**利率和期数必须共享时间单位**。如果 *nper* 以月为单位,*rate* 必须是月利率(通常是年利率除以十二);如果 *nper* 以年为单位,*rate* 必须是年利率。折旧也类似:资产的 *life* 和查询的 *period* 必须以相同单位表示。 ## 成员 * [DDB](/official/Reference/VBA/Financial/DDB) -- 使用双倍余额递减法计算资产指定期间的折旧 * [FV](/official/Reference/VBA/Financial/FV) -- 基于定期固定付款和固定利率的年金终值 * [IPmt](/official/Reference/VBA/Financial/IPmt) -- 年金指定期间的利息付款 * [IRR](/official/Reference/VBA/Financial/IRR) -- 定期现金流的内部收益率 * [MIRR](/official/Reference/VBA/Financial/MIRR) -- 定期现金流的修正内部收益率 * [NPer](/official/Reference/VBA/Financial/NPer) -- 基于定期固定付款和固定利率的年金期数 * [NPV](/official/Reference/VBA/Financial/NPV) -- 基于定期现金流和折现率的投资净现值 * [Pmt](/official/Reference/VBA/Financial/Pmt) -- 基于定期固定付款和固定利率的年金付款 * [PPmt](/official/Reference/VBA/Financial/PPmt) -- 年金指定期间的本金付款 * [PV](/official/Reference/VBA/Financial/PV) -- 基于定期固定付款和固定利率的年金现值 * [Rate](/official/Reference/VBA/Financial/Rate) -- 年金每期利率 * [SLN](/official/Reference/VBA/Financial/SLN) -- 资产单期的直线折旧 * [SYD](/official/Reference/VBA/Financial/SYD) -- 资产指定期间的年数总和折旧 --- --- url: /en/official/Reference/VBA/Financial.md --- # Financial module The **Financial** module groups together the procedures that solve standard time-value-of-money problems --- annuity calculations for loans and savings plans with fixed periodic cash flows, return and present-value analysis for irregular cash flow streams, and asset depreciation under three different accounting conventions. ## Annuities An *annuity* is a series of fixed cash payments made at equally spaced intervals. Seven of the module's functions describe the same underlying annuity model and differ only in *which* of its quantities they solve for: [**FV**](/en/official/Reference/VBA/Financial/FV) returns the future value (the cash balance after the final payment), [**PV**](/en/official/Reference/VBA/Financial/PV) the present value (the value today of the future cash flows), [**Pmt**](/en/official/Reference/VBA/Financial/Pmt) the periodic payment amount, [**NPer**](/en/official/Reference/VBA/Financial/NPer) the number of periods, and [**Rate**](/en/official/Reference/VBA/Financial/Rate) the interest rate per period. [**IPmt**](/en/official/Reference/VBA/Financial/IPmt) and [**PPmt**](/en/official/Reference/VBA/Financial/PPmt) decompose a single payment into its interest and principal portions. All seven take the same core arguments --- *rate*, *nper*, *pmt*, *pv*, *fv*, *type* --- in different orders, with the unknown one omitted. *rate* is the interest rate per period (an annual percentage divided by the number of periods per year); *nper* is the total number of payment periods; *pmt* is the payment per period; *pv* and *fv* are the present and future values; *type* is `0` if payments fall at the end of the period and `1` if at the beginning. **Rate** additionally accepts a *guess* argument --- it solves its equation iteratively, and a starting estimate can be supplied when the default of 10 % fails to converge in twenty cycles. ```vb Const APR As Double = 0.06 Dim Monthly As Double Monthly = -Pmt(APR / 12, 30 * 12, 200000) ' fixed monthly payment on a 30-year, $200,000 mortgage at 6 % APR ``` ## Variable cash flows For investments whose cash flows vary period to period, three functions take an array of values rather than a single payment amount. [**NPV**](/en/official/Reference/VBA/Financial/NPV) returns the net present value of the cash flows discounted at a chosen rate; [**IRR**](/en/official/Reference/VBA/Financial/IRR) returns the internal rate of return --- the discount rate that would make **NPV** zero; and [**MIRR**](/en/official/Reference/VBA/Financial/MIRR) returns the modified internal rate of return, where outflows and reinvested inflows are discounted at separate rates. The order of values within the array is significant --- element *i* is the cash flow for period *i* --- and the array must contain at least one negative entry (a payment) and one positive entry (a receipt). Like **Rate**, both **IRR** and **MIRR** are computed iteratively and accept an optional *guess*. ```vb Dim CashFlows(0 To 4) As Double CashFlows(0) = -70000 ' initial outlay CashFlows(1) = 22000 : CashFlows(2) = 25000 CashFlows(3) = 28000 : CashFlows(4) = 31000 Debug.Print IRR(CashFlows) ' approximate internal rate of return Debug.Print NPV(0.0625, CashFlows) ' net present value at a 6.25 % discount rate ``` ## Depreciation Three functions return the depreciation of an asset over a chosen period under three different accounting conventions, all parameterised by the asset's initial *cost*, its *salvage* value at the end of its useful life, and its *life* in periods. [**SLN**](/en/official/Reference/VBA/Financial/SLN) applies straight-line depreciation, spreading the lost value uniformly across each period. [**DDB**](/en/official/Reference/VBA/Financial/DDB) applies the double-declining balance method (or a chosen multiplier), front-loading the depreciation so it is highest in the first period and decreases geometrically thereafter. [**SYD**](/en/official/Reference/VBA/Financial/SYD) applies sum-of-years' digits depreciation --- also accelerated, but linearly tapered. **SLN** returns the same value for every period; **DDB** and **SYD** therefore both take an additional *period* argument naming which period to report. ## Sign conventions and units Two conventions span the entire module. First, **cash flows have a sign**: money paid *out* (mortgage payments, deposits to savings, investment outlays) is represented by a negative number, and money received (loan proceeds, savings withdrawals, dividends) by a positive number. The same convention applies whether the value appears as a single argument (*pmt*, *pv*, *fv*) or as an element of a cash flow array --- entering a payment as a positive number is the most common cause of an unexpected result. Second, **rates and counts must share a time unit**. If *nper* is given in months, *rate* must be the monthly rate (typically the annual rate divided by twelve); if *nper* is given in years, *rate* must be the annual rate. The same applies to depreciation: the *life* of the asset and the *period* being queried must be expressed in the same units. ## Members * [DDB](/en/official/Reference/VBA/Financial/DDB) -- depreciation of an asset for a specified period via the double-declining balance method * [FV](/en/official/Reference/VBA/Financial/FV) -- future value of an annuity based on periodic fixed payments and a fixed interest rate * [IPmt](/en/official/Reference/VBA/Financial/IPmt) -- interest payment for a given period of an annuity * [IRR](/en/official/Reference/VBA/Financial/IRR) -- internal rate of return for a series of periodic cash flows * [MIRR](/en/official/Reference/VBA/Financial/MIRR) -- modified internal rate of return for a series of periodic cash flows * [NPer](/en/official/Reference/VBA/Financial/NPer) -- number of periods for an annuity based on periodic fixed payments and a fixed interest rate * [NPV](/en/official/Reference/VBA/Financial/NPV) -- net present value of an investment based on a series of periodic cash flows and a discount rate * [Pmt](/en/official/Reference/VBA/Financial/Pmt) -- payment for an annuity based on periodic fixed payments and a fixed interest rate * [PPmt](/en/official/Reference/VBA/Financial/PPmt) -- principal payment for a given period of an annuity * [PV](/en/official/Reference/VBA/Financial/PV) -- present value of an annuity based on periodic fixed payments and a fixed interest rate * [Rate](/en/official/Reference/VBA/Financial/Rate) -- interest rate per period for an annuity * [SLN](/en/official/Reference/VBA/Financial/SLN) -- straight-line depreciation of an asset for a single period * [SYD](/en/official/Reference/VBA/Financial/SYD) -- sum-of-years' digits depreciation of an asset for a specified period --- --- url: /en/official/IDE/FindReplace.md --- # Find / Replace ![Find / Replace](/assets/FindReplace.DytG1fIX.png "Find / Replace") Find What Replace With * Current Procedure * Current Module * Current File * Current Project * Selected Text Direction: All / Down / Up ![Find / Replace - Direction](Images/FindReplace_Direction.png "Find / Replace - Direction") * Whole Word Only * Match Case * Pattern Matching * Match Regular Expressions * Inside Packages Find Next Cancel Replace Replace All --- --- url: /en/official/Reference/VBA/Conversion/Fix.md --- # Fix Returns the integer portion of a number, truncating toward zero. Syntax: **Fix(** *number* **)** *number* : *required* A **Double** or any valid numeric expression. If *number* contains **Null**, **Null** is returned. **Fix** removes the fractional part of *number* and returns the resulting integer value. If *number* is negative, **Fix** returns the first negative integer greater than or equal to *number*; that is, it truncates toward zero. For example, **Fix** converts `-8.4` to `-8`. **Fix(** *number* **)** is equivalent to **Sgn(** *number* **) \* Int(Abs(** *number* **))**. The return value has the same type as *number*. ::: info The closely related [**Int**](/en/official/Reference/VBA/Conversion/Int) function rounds toward negative infinity rather than truncating toward zero. For positive numbers the two are identical; for negative numbers they differ. ::: ### Example This example illustrates how the **Fix** function returns the integer portion of a number. For a negative number argument, the **Fix** function returns the first negative integer greater than or equal to the number. ```vb Dim MyNumber MyNumber = Fix(99.2) ' Returns 99. MyNumber = Fix(-99.8) ' Returns -99. MyNumber = Fix(-99.2) ' Returns -99. ``` ### See Also * [Int](/en/official/Reference/VBA/Conversion/Int), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng) functions --- --- url: /zh/official/Reference/VBA/Conversion/Fix.md --- # Fix 返回数字的整数部分,向零截断。 语法:**Fix(** *number* **)** *number* : *必需* **Double** 或任何有效的数值表达式。如果 *number* 包含 **Null**,则返回 **Null**。 **Fix** 移除 *number* 的小数部分并返回结果整数值。如果 *number* 为负数,**Fix** 返回大于或等于 *number* 的第一个负整数;即向零截断。例如,**Fix** 将 `-8.4` 转换为 `-8`。 **Fix(** *number* **)** 等效于 **Sgn(** *number* **) \* Int(Abs(** *number* **))**。 返回值的类型与 *number* 相同。 ::: info 密切相关的 [**Int**](/official/Reference/VBA/Conversion/Int) 函数向负无穷舍入而非向零截断。对于正数,两者相同;对于负数,它们不同。 ::: ### 示例 此示例说明 **Fix** 函数如何返回数字的整数部分。对于负数参数,**Fix** 函数返回大于或等于该数的第一个负整数。 ```vb Dim MyNumber MyNumber = Fix(99.2) ' Returns 99. MyNumber = Fix(-99.8) ' Returns -99. MyNumber = Fix(-99.2) ' Returns -99. ``` ### 另请参阅 * [Int](/official/Reference/VBA/Conversion/Int)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLng](/official/Reference/VBA/Conversion/CLng) 函数 --- --- url: /en/official/Reference/tbIDE/Folder.md --- # Folder class A folder inside the IDE's virtual file system. Extends [**FileSystemItem**](/en/official/Reference/tbIDE/FileSystemItem) with child-enumeration capability --- [**Count**](#count), [**Item**](#item), and standard **For Each** iteration that yields each child as a [**FileSystemItem**](/en/official/Reference/tbIDE/FileSystemItem) (use `TypeOf` to discriminate folders from files). A **Folder** also inherits the universal [**FileSystemItem**](/en/official/Reference/tbIDE/FileSystemItem) members --- [**Name**](/en/official/Reference/tbIDE/FileSystemItem#name), [**Path**](/en/official/Reference/tbIDE/FileSystemItem#path), [**Type**](/en/official/Reference/tbIDE/FileSystemItem#type), [**Parent**](/en/official/Reference/tbIDE/FileSystemItem#parent). The most common entry point is [**Host.CurrentProject.RootFolder**](/en/official/Reference/tbIDE/Project#rootfolder), and the most common operation is a **For Each** recursive traversal. ```vb Private Sub WalkAllFiles(ByVal folder As Folder) Dim item As FileSystemItem For Each item In folder If TypeOf item Is Folder Then WalkAllFiles item Else Dim file As File = item ' …process the file End If Next End Sub ``` ::: warning The twinBASIC IDE is multi-threaded. The same folder can change while an addin holds a reference to it --- files arrive, files disappear, indices renumber. The supported way to traverse a folder is **For Each**; index-based access through [**Count**](#count) / [**Item**](#item) races against the IDE's own threads and will sometimes miss or duplicate entries. Always prefer **For Each** for traversal. ::: ## Properties ### Count Number of items currently in the folder. **Long**, read-only. ::: warning The value can change between two reads --- the IDE is multi-threaded. **Do not** use this as a `For i = 0 To Count - 1` loop bound; use **For Each** instead. ::: ### IsPackagesFolder **True** if this folder is the project's special `Packages` folder (the one that contains every referenced package's source tree). **Boolean**, read-only. Useful when traversing the project for source-search purposes --- an addin that searches user code will usually want to *skip* the package sources: ```vb If folder.IsPackagesFolder And Not searchInsidePackages Then Exit Sub ``` ### Item Indexed or named access to a child item. **DefaultMember** --- so `folder(0)` is equivalent to `folder.Item(0)`, and `folder("MainModule.twin")` is equivalent to `folder.Item("MainModule.twin")`. Syntax: *folder*( *IndexOrName* ) **As** [**FileSystemItem**](/en/official/Reference/tbIDE/FileSystemItem) *IndexOrName* : A **Variant** --- either a zero-based **Long** index or a **String** child name. ::: warning Numeric indices race against the IDE's own threads --- the item at index `n` may have changed identity by the time the call returns. Named lookup is safer; **For Each** traversal is safer still. ::: --- --- url: /zh/official/Reference/tbIDE/Folder.md --- # Folder 类 IDE 虚拟文件系统中的文件夹。扩展 [**FileSystemItem**](/official/Reference/tbIDE/FileSystemItem),增加了子项枚举能力——[**Count**](#count)、[**Item**](#item),以及标准的 **For Each** 迭代,将每个子项作为 [**FileSystemItem**](/official/Reference/tbIDE/FileSystemItem) 产出(使用 `TypeOf` 区分文件夹和文件)。 **Folder** 还继承了通用的 [**FileSystemItem**](/official/Reference/tbIDE/FileSystemItem) 成员——[**Name**](/official/Reference/tbIDE/FileSystemItem#name)、[**Path**](/official/Reference/tbIDE/FileSystemItem#path)、[**Type**](/official/Reference/tbIDE/FileSystemItem#type)、[**Parent**](/official/Reference/tbIDE/FileSystemItem#parent)。最常见的入口点是 [**Host.CurrentProject.RootFolder**](/official/Reference/tbIDE/Project#rootfolder),最常见的操作是 **For Each** 递归遍历。 ```vb Private Sub WalkAllFiles(ByVal folder As Folder) Dim item As FileSystemItem For Each item In folder If TypeOf item Is Folder Then WalkAllFiles item Else Dim file As File = item ' …处理文件 End If Next End Sub ``` ::: warning twinBASIC IDE 是多线程的。当插件持有对文件夹的引用时,同一文件夹可能发生变化——文件到达、文件消失、索引重新编号。遍历文件夹的支持方式是 **For Each**;通过 [**Count**](#count) / [**Item**](#item) 的基于索引的访问与 IDE 自身线程竞争,有时会遗漏或重复条目。遍历时始终优先使用 **For Each**。 ::: ## 属性 ### Count 文件夹中当前的项数。**Long**,只读。 ::: warning 该值可能在两次读取之间发生变化——IDE 是多线程的。**不要**将其用作 `For i = 0 To Count - 1` 的循环边界;应使用 **For Each**。 ::: ### IsPackagesFolder 如果此文件夹是项目的特殊 `Packages` 文件夹(包含每个引用包的源代码树),则为 **True**。**Boolean**,只读。 在为源代码搜索而遍历项目时很有用——搜索用户代码的插件通常希望*跳过*包源代码: ```vb If folder.IsPackagesFolder And Not searchInsidePackages Then Exit Sub ``` ### Item 子项的索引或命名访问。**DefaultMember**——因此 `folder(0)` 等同于 `folder.Item(0)`,`folder("MainModule.twin")` 等同于 `folder.Item("MainModule.twin")`。 语法:*folder*( *IndexOrName* ) **As** [**FileSystemItem**](/official/Reference/tbIDE/FileSystemItem) *IndexOrName* : 一个 **Variant** —— 基于 0 的 **Long** 索引或 **String** 子项名称。 ::: warning 数字索引与 IDE 自身线程竞争——索引 `n` 处的项在调用返回时可能已改变身份。命名查找更安全;**For Each** 遍历更加安全。 ::: --- --- url: /en/official/Reference/VBRUN/AmbientProperties/Font.md --- # Font Returns the font the container would like its embedded controls to use by default, as an **stdole.IFontDisp**. Read-only. Syntax: *object*.**Font** *object* : *required* An object expression that evaluates to an **AmbientProperties** object. A control that does not have its own font explicitly set should display text using this font, so that its captions and labels match the typography of the surrounding container. The returned **IFontDisp** exposes properties such as **Name**, **Size**, **Bold**, **Italic**, and **Underline**. ### Example This example responds to an ambient **Font** change and applies it to the control's caption font. ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "Font" Set UserControl.Font = Ambient.Font End Select End Sub ``` ### See Also * [BackColor](/en/official/Reference/VBRUN/AmbientProperties/BackColor) property * [ForeColor](/en/official/Reference/VBRUN/AmbientProperties/ForeColor) property * [TextAlign](/en/official/Reference/VBRUN/AmbientProperties/TextAlign) property --- --- url: /zh/official/Reference/VBRUN/AmbientProperties/Font.md --- # Font 返回容器希望其嵌入控件默认使用的字体,类型为**stdole.IFontDisp**。只读。 语法:*object*.**Font** *object* : *必需* 求值为**AmbientProperties**对象的对象表达式。 未显式设置自身字体的控件应使用此字体显示文本,使其标题和标签与周围容器的排版匹配。返回的**IFontDisp**公开**Name**、**Size**、**Bold**、**Italic**和**Underline**等属性。 ### 示例 此示例响应环境**Font**更改并将其应用于控件的标题字体。 ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "Font" Set UserControl.Font = Ambient.Font End Select End Sub ``` ### 另见 * [BackColor](/official/Reference/VBRUN/AmbientProperties/BackColor) 属性 * [ForeColor](/official/Reference/VBRUN/AmbientProperties/ForeColor) 属性 * [TextAlign](/official/Reference/VBRUN/AmbientProperties/TextAlign) 属性 --- --- url: /en/packages/vbccr/lists/fontcombo.md description: >- FontCombo Control - VBCCR Development Manual, complete API reference based on source code --- # FontCombo Control Provides a font selection combo box control with a most-recently-used list, capable of enumerating system fonts and filtering by type and pitch. ## Enumerations ### FtcStyleConstants | Constant | Value | Description | |----------|-------|-------------| | FtcStyleDropDownCombo | 0 | Drop-down combo box (editable) | | FtcStyleSimpleCombo | 1 | Simple combo box (list always visible) | | FtcStyleDropDownList | 2 | Drop-down list (selection only) | ### FtcFontTypeConstants | Constant | Value | Description | |----------|-------|-------------| | FtcFontTypeTrueType | 0 | TrueType fonts only | | FtcFontTypeBitmap | 1 | Bitmap fonts only | | FtcFontTypeBitmapTrueType | 2 | Bitmap and TrueType fonts | ### FtcFontPitchConstants | Constant | Value | Description | |----------|-------|-------------| | FtcFontPitchAll | 0 | All pitches | | FtcFontPitchFixed | 1 | Fixed pitch | | FtcFontPitchVariable | 2 | Variable pitch | ## Properties ### Name ```vb Property Get Name() As String ``` Returns the name of the control. ### Tag ```vb Property Get/Let Tag() As String ``` Returns/sets the tag value of the control. ### Parent ```vb Property Get Parent() As Object ``` Returns the parent object of the control. ### Container ```vb Property Get/Set Container() As Object ``` Returns/sets the container of the control. ### Left ```vb Property Get/Let Left() As Single ``` Returns/sets the position of the left edge of the control. ### Top ```vb Property Get/Let Top() As Single ``` Returns/sets the position of the top edge of the control. ### Width ```vb Property Get/Let Width() As Single ``` Returns/sets the width of the control. ### Height ```vb Property Get/Let Height() As Single ``` Returns/sets the height of the control. ### Visible ```vb Property Get/Let Visible() As Boolean ``` Returns/sets whether the control is visible. ### ToolTipText ```vb Property Get/Let ToolTipText() As String ``` Returns/sets the tooltip text of the control. ### HelpContextID ```vb Property Get/Let HelpContextID() As Long ``` Returns/sets the help context ID of the control. ### WhatsThisHelpID ```vb Property Get/Let WhatsThisHelpID() As Long ``` Returns/sets the "What's This" help ID of the control. ### DragIcon ```vb Property Get/Let/Set DragIcon() As IPictureDisp ``` Returns/sets the icon displayed during drag operations. ### DragMode ```vb Property Get/Let DragMode() As Integer ``` Returns/sets the drag mode (manual or automatic). ### hWnd ```vb Property Get hWnd() As LongPtr ``` Returns the window handle of the combo box. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Returns the window handle of the UserControl. ### hWndEdit ```vb Property Get hWndEdit() As LongPtr ``` Returns the window handle of the edit box portion. ### hWndList ```vb Property Get hWndList() As LongPtr ``` Returns the window handle of the list portion. ### Font ```vb Property Get/Let/Set Font() As StdFont ``` Returns/sets the font used by the control. ### VisualStyles ```vb Property Get/Let VisualStyles() As Boolean ``` Returns/sets whether visual styles are enabled. ### BackColor ```vb Property Get/Let BackColor() As OLE_COLOR ``` Returns/sets the background color of the control. ### ForeColor ```vb Property Get/Let ForeColor() As OLE_COLOR ``` Returns/sets the foreground color of the control. ### Enabled ```vb Property Get/Let Enabled() As Boolean ``` Returns/sets whether the control is enabled. ### OLEDragMode ```vb Property Get/Let OLEDragMode() As VBRUN.OLEDragConstants ``` Returns/sets the OLE drag mode. ### OLEDropMode ```vb Property Get/Let OLEDropMode() As OLEDropModeConstants ``` Returns/sets the OLE drop mode. See common enumerations. ### MousePointer ```vb Property Get/Let MousePointer() As CCMousePointerConstants ``` Returns/sets the mouse pointer type. See common enumerations. ### MouseIcon ```vb Property Get/Let/Set MouseIcon() As IPictureDisp ``` Returns/sets the custom mouse icon. ### MouseTrack ```vb Property Get/Let MouseTrack() As Boolean ``` Returns/sets whether mouse enter/leave tracking is enabled. ### RightToLeft ```vb Property Get/Let RightToLeft() As Boolean ``` Returns/sets whether right-to-left layout is enabled. ### RightToLeftMode ```vb Property Get/Let RightToLeftMode() As CCRightToLeftModeConstants ``` Returns/sets the right-to-left mode. See common enumerations. ### BuddyControl ```vb Property Get/Set/Let BuddyControl() As Variant ``` Returns/sets the associated buddy control, which is notified to update when a font is selected. ### Style ```vb Property Get/Let Style() As FtcStyleConstants ``` Returns/sets the combo box style. ### FontType ```vb Property Get/Let FontType() As FtcFontTypeConstants ``` Returns/sets the font type filter for display. ### FontPitch ```vb Property Get/Let FontPitch() As FtcFontPitchConstants ``` Returns/sets the font pitch filter for display. ### Locked ```vb Property Get/Let Locked() As Boolean ``` Returns/sets whether the control is locked (prevents editing and selection). ### Text ```vb Property Get/Let Text() As String ``` Returns/sets the text in the edit box. ### Default ```vb Property Get/Let Default() As String ``` Returns/sets the default font name. ### ExtendedUI ```vb Property Get/Let ExtendedUI() As Boolean ``` Returns/sets whether extended user interface is used. ### MaxDropDownItems ```vb Property Get/Let MaxDropDownItems() As Integer ``` Returns/sets the maximum number of visible items in the drop-down list. ### IntegralHeight ```vb Property Get/Let IntegralHeight() As Boolean ``` Returns/sets whether only complete items are shown (no partial items truncated). ### MaxLength ```vb Property Get/Let MaxLength() As Long ``` Returns/sets the maximum number of characters that can be entered in the edit box. ### HorizontalExtent ```vb Property Get/Let HorizontalExtent() As Single ``` Returns/sets the horizontal scroll width of the list. ### IMEMode ```vb Property Get/Let IMEMode() As CCIMEModeConstants ``` Returns/sets the input method editor mode. See common enumerations. ### ScrollTrack ```vb Property Get/Let ScrollTrack() As Boolean ``` Returns/sets whether the scroll bar tracks in real time. ### AutoSelect ```vb Property Get/Let AutoSelect() As Boolean ``` Returns/sets whether the edit box text is automatically selected when the control receives focus. ### AlwaysFindExact ```vb Property Get/Let AlwaysFindExact() As Boolean ``` Returns/sets whether to always perform exact matching. ### RecentMax ```vb Property Get/Let RecentMax() As Integer ``` Returns/sets the maximum number of items in the recently used list (0-9), 0 hides the recent list. ### RecentBackColor ```vb Property Get/Let RecentBackColor() As OLE_COLOR ``` Returns/sets the background color of the recently used list. ### RecentForeColor ```vb Property Get/Let RecentForeColor() As OLE_COLOR ``` Returns/sets the foreground color of the recently used list. ### RecentCount ```vb Property Get RecentCount() As Long ``` Returns the number of items in the recently used list. Read-only. ### ListCount ```vb Property Get ListCount() As Long ``` Returns the total number of items in the list. Read-only. ### List ```vb Property Get List(ByVal Index As Long) As String ``` Returns the text of the list item at the specified index. Read-only. ### ListIndex ```vb Property Get/Let ListIndex() As Long ``` Returns/sets the index of the currently selected item. ### ItemData ```vb Property Get/Let ItemData(ByVal Index As Long) As LongPtr ``` Returns/sets the extra data for the item at the specified index. ### SelStart ```vb Property Get/Let SelStart() As Long ``` Returns/sets the starting position of the selected text. ### SelLength ```vb Property Get/Let SelLength() As Long ``` Returns/sets the length of the selected text. ### SelText ```vb Property Get/Let SelText() As String ``` Returns/sets the currently selected text. ### ItemHeight ```vb Property Get ItemHeight() As Single ``` Returns the height of list items. Read-only. ### FieldHeight ```vb Property Get FieldHeight() As Single ``` Returns the height of the edit box (or static text) portion. Read-only. ### DroppedDown ```vb Property Get/Let DroppedDown() As Boolean ``` Returns/sets whether the drop-down list is expanded. ### DropDownWidth ```vb Property Get/Let DropDownWidth() As Single ``` Returns/sets the width of the drop-down list. Not supported in simple style. ### TopIndex ```vb Property Get/Let TopIndex() As Long ``` Returns/sets the index of the top visible item in the list. ## Methods ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag operation. ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` Starts, ends, or cancels a drag operation. ### SetFocus ```vb Public Sub SetFocus() ``` Moves focus to this control. ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` Sets the control's Z-order position within its layer. ### Refresh ```vb Public Sub Refresh() ``` Forces a complete redraw of the control. ### FindItem ```vb Public Function FindItem(ByVal Text As String, Optional ByVal Index As Long = -1, Optional ByVal Partial As Boolean) As Long ``` Finds an item in the font combo box and returns its index. When Partial is True, performs partial matching. ### GetIdealHorizontalExtent ```vb Public Function GetIdealHorizontalExtent() As Single ``` Gets the ideal value for the horizontal scroll width. ### SelectItem ```vb Public Function SelectItem(ByVal Text As String, Optional ByVal Index As Long = -1) As Long ``` Searches for an item starting with the specified string and selects it. Case-insensitive. ### SaveRecent ```vb Public Function SaveRecent() As Variant ``` Saves the recently used list and returns a string array. ### RestoreRecent ```vb Public Sub RestoreRecent(ByVal ArgList As Variant) ``` Restores the recently used list from a previously saved state. ### ClearRecent ```vb Public Sub ClearRecent() ``` Clears the contents of the recently used list. ## Events ### Click ```vb Public Event Click() ``` Occurs when the control is clicked. ### DblClick ```vb Public Event DblClick() ``` Occurs when the control is double-clicked. ### Scroll ```vb Public Event Scroll() ``` Occurs when the list is scrolled. ### Change ```vb Public Event Change() ``` Occurs when the control content changes. ### ContextMenu ```vb Public Event ContextMenu(ByRef Handled As Boolean, ByVal X As Single, ByVal Y As Single) ``` Occurs on right-click or Shift+F10. Set Handled to True to prevent the default context menu. ### DropDown ```vb Public Event DropDown() ``` Occurs when the drop-down list is about to expand. ### CloseUp ```vb Public Event CloseUp() ``` Occurs when the drop-down list closes. ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Occurs before the KeyDown event. Set IsInputKey to mark whether the key is an input key. ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Occurs before the KeyUp event. ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` Occurs when a keyboard key is pressed. ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` Occurs when a keyboard key is released. ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` Occurs when a character key is pressed and released. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when a mouse button is pressed. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when the mouse is moved. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when a mouse button is released. ### MouseEnter ```vb Public Event MouseEnter() ``` Occurs when the mouse enters the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Occurs when the mouse leaves the control. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` Occurs on the source control after an OLE drag-drop operation is completed or canceled. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when data is dropped onto the control via an OLE drag-drop operation. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` Occurs when the mouse passes over the control during an OLE drag-drop operation. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` Occurs on the source control when the mouse cursor needs to change during an OLE drag-drop operation. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` Occurs on the source control when the drop target requests data. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` Occurs when an OLE drag-drop operation is started. ## Code Examples ### Basic Usage ```vb Private Sub Form_Load() With FontCombo1 .Style = FtcStyleDropDownCombo .FontType = FtcFontTypeTrueType .FontPitch = FtcFontPitchAll .RecentMax = 5 End With End Sub Private Sub FontCombo1_Click() Me.Font.Name = FontCombo1.Text Debug.Print "Selected font: " & FontCombo1.Text End Sub Private Sub Form_Unload(Cancel As Integer) Dim v As Variant v = FontCombo1.SaveRecent SaveSetting App.Title, "FontCombo", "Recent", Join(v, vbTab) End Sub ``` --- --- url: /en/official/Reference/CustomControls/Enumerations/FontWeight.md --- # FontWeight The weight of a font face, on the standard 100 -- 900 scale used by OpenType's `wght` axis and by CSS's `font-weight`. Assigned to [**FontStyle.Weight**](/en/official/Reference/CustomControls/Styles/TextRendering#weight); availability of each weight depends on which faces are installed for the chosen font family. | Constant | Value | Description | |----------|-------|-------------| | **tbThin** | 100 | The thinnest weight (also called Hairline). | | **tbExtraLight** | 200 | Also known as Ultra Light. | | **tbLight** | 300 | A noticeably thinner stroke than the regular weight. | | **tbNormal** | 400 | The default weight. Also known as Regular. Newly-constructed [**FontStyle**](/en/official/Reference/CustomControls/Styles/TextRendering) objects start here. | | **tbMedium** | 500 | Slightly heavier than **tbNormal**. | | **tbSemiBold** | 600 | Heavier still; also known as Demi Bold. | | **tbBold** | 700 | The standard bold weight. | | **tbExtraBold** | 800 | Also known as Ultra Bold. | | **tbHeavy** | 900 | The heaviest weight. Also known as Black. | --- --- url: /zh/official/Reference/CustomControls/Enumerations/FontWeight.md --- # FontWeight 字体的粗细,在 OpenType `wght` 轴和 CSS `font-weight` 使用的标准 100--900 刻度上。赋给 [**FontStyle.Weight**](/official/Reference/CustomControls/Styles/TextRendering#weight);每种粗细的可用性取决于所选字体系列安装了哪些字面。 | 常量 | 值 | 说明 | |------|----|------| | **tbThin** | 100 | 最细粗细(也称 Hairline)。 | | **tbExtraLight** | 200 | 也称 Ultra Light。 | | **tbLight** | 300 | 笔画明显比常规粗细更细。 | | **tbNormal** | 400 | 默认粗细。也称 Regular。新构造的 [**FontStyle**](/official/Reference/CustomControls/Styles/TextRendering) 对象从此开始。 | | **tbMedium** | 500 | 比 **tbNormal** 略重。 | | **tbSemiBold** | 600 | 更重;也称 Demi Bold。 | | **tbBold** | 700 | 标准粗体粗细。 | | **tbExtraBold** | 800 | 也称 Ultra Bold。 | | **tbHeavy** | 900 | 最重粗细。也称 Black。 | --- --- url: /en/official/Reference/Core/For-Each-Next.md --- # For Each...Next Repeats a group of statements for each element in an array or collection. Syntax: > **For Each** *element* \[ **As** *type* ] **In** *group*\ >      \[ *statements* ]\ >      \[ **Continue For** | **Exit For** ]\ >      \[ *statements* ]\ > **Next** \[ *element* ] *element* : Variable used to iterate through the elements of the collection or array. For collections, *element* can only be a **Variant** variable, a generic object variable, or any specific object variable. For arrays, *element* can only be a **Variant** variable. *type* : *optional* A type used to declare *element*.\ When present it is equivalent to placing `Dim element As type` immediately before the **For Each** statement. *group* : Name of an object collection or array (except an array of user-defined types (UDTs)). *statements* : *optional* One or more statements that are executed on each item in *group*. **Continue For** : *optional* Immediately skips remaining statements and begins next iteration, or exits the loop if no more iterations remain.\ **Continue For** is often used after evaluating some condition, for example **If...Then**. **Exit For** : *optional* Immediately exits the body of the loop.\ **Exit For** is often used after evaluating some condition, for example **If...Then**, and transfers control to the statement immediately following **Next**. The **For…Each** block is entered if there is at least one element in *group*. After the loop has been entered, all the statements in the loop are executed for the first element in *group*. If there are more elements in *group*, the statements in the loop continue to execute for each element. When there are no more elements in *group*, the loop is exited and execution continues with the statement following the **Next** statement. **For...Each...Next** loops can be nested by placing one **For…Each…Next** loop within another. However, each loop *element* must be unique. ::: info When *element* is omitted in a **Next** statement, execution continues as if *element* is included. If a **Next** statement is encountered before its corresponding **For** statement, an error occurs. ::: The **For...Each...Next** statement cannot be used with an array of user-defined types because a **Variant** can't contain a user-defined type. ### Example This example uses the **For Each...Next** statement to search the **Text** property of all elements in a collection for the existence of the string "Hello". In the example, *MyObject* is a text-related object and is an element of the collection *MyCollection*. Both are generic names used for illustration purposes only. ```vb Dim Found, MyObject, MyCollection Found = False ' Initialize variable. For Each MyObject In MyCollection ' Iterate through each element. If MyObject.Text = "Hello" Then ' If Text equals "Hello". Found = True ' Set Found to True. Exit For ' Exit loop. End If Next ``` --- --- url: /zh/official/Reference/Core/For-Each-Next.md --- # For Each...Next 对数组或集合中的每个元素重复执行一组语句。 语法: > **For Each** *element* \[ **As** *type* ] **In** *group*\ >      \[ *statements* ]\ >      \[ **Continue For** | **Exit For** ]\ >      \[ *statements* ]\ > **Next** \[ *element* ] *element* : 用于遍历集合或数组元素的变量。对于集合,*element* 只能是 **Variant** 变量、通用对象变量或任何特定对象变量。对于数组,*element* 只能是 **Variant** 变量。 *type* : *可选* 用于声明 *element* 的类型。\ 当存在时,等效于在 **For Each** 语句之前紧接放置 `Dim element As type`。 *group* : 对象集合或数组的名称(用户自定义类型(UDT)数组除外)。 *statements* : *可选* 对 *group* 中每个项执行的一条或多条语句。 **Continue For** : *可选* 立即跳过剩余语句并开始下一次迭代,如果没有更多迭代则退出循环。\ **Continue For** 通常在评估某个条件后使用,例如 **If...Then**。 **Exit For** : *可选* 立即退出循环体。\ **Exit For** 通常在评估某个条件后使用,例如 **If...Then**,并将控制权转移到紧接在 **Next** 之后的语句。 如果 *group* 中至少有一个元素,则进入 **For…Each** 块。进入循环后,对 *group* 中的第一个元素执行循环中的所有语句。如果 *group* 中有更多元素,循环中的语句继续为每个元素执行。当 *group* 中没有更多元素时,退出循环,执行继续到 **Next** 语句之后的语句。 **For...Each...Next** 循环可以通过将一个 **For…Each…Next** 循环放在另一个内部来嵌套。但每个循环的 *element* 必须唯一。 ::: info 当 **Next** 语句中省略 *element* 时,执行继续如同包含了 *element* 一样。如果在对应的 **For** 语句之前遇到 **Next** 语句,将发生错误。 ::: **For...Each...Next** 语句不能用于用户自定义类型的数组,因为 **Variant** 不能包含用户自定义类型。 ### 示例 本示例使用 **For Each...Next** 语句搜索集合中所有元素的 **Text** 属性是否存在字符串"Hello"。在示例中,*MyObject* 是文本相关对象,是集合 *MyCollection* 的元素。两者都是仅用于说明的通用名称。 ```vb Dim Found, MyObject, MyCollection Found = False ' Initialize variable. For Each MyObject In MyCollection ' Iterate through each element. If MyObject.Text = "Hello" Then ' If Text equals "Hello". Found = True ' Set Found to True. Exit For ' Exit loop. End If Next ``` --- --- url: /en/official/Reference/Core/For-Next.md --- # For...Next Repeats a group of statements while the loop counter approaches its final value. Syntax: > **For** *counter* \[ **As** *type* ] **=** *start* **To** *end* \[ **Step** *step* ]\ >      \[ *statements* ]\ >      \[ **Continue For** | **Exit For** ]\ >      \[ *statements* ] ...\ > **Next** \[ *counter* ] *counter* : Numeric variable used as a loop counter. The variable can't be a Boolean or an array element. *type* : *optional* A numeric type used to declare *counter*.\ When present it is equivalent to placing `Dim counter As type` immediately before the **For** statement. *start* : Initial value of *counter*. *end* : Final value of *counter*. *step* : *optional* Amount *counter* is changed each time through the loop. If not specified, *step* defaults to one. *statements* : *optional* One or more statements between **For** and **Next** that are executed the specified number of times. **Continue For** : *optional* Immediately skips remaining statements and begins next iteration, or exits the loop if no more iterations remain.\ **Continue For** is often used after evaluating some condition, for example **If...Then**. **Exit For** : *optional* Immediately exits the body of the loop.\ **Exit For** is often used after evaluating some condition, for example **If...Then**, and transfers control to the statement immediately following **Next**. The *step* argument can be either positive or negative. The value of the *step* argument determines loop processing as follows: | Value | Loop executes if | | :------------ | :----------------- | | Positive or 0 | *counter* <= *end* | | Negative | *counter* >= *end* | After all statements in the loop have executed, *step* is added to *counter*. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the **Next** statement. ::: tip Changing the value of *counter* while inside a loop can make code harder to read and debug. ::: **For...Next** loops can be nested by placing one **For...Next** loop within another. Give each loop a unique variable name as its *counter*. The following construction is correct: ```vb For I = 1 To 10 For J = 1 To 10 For K = 1 To 10 ' ... Next K Next J Next I ``` ::: info When *counter* is omitted in a **Next** statement, execution continues as if *counter* is included. If a **Next** statement is encountered before its corresponding **For** statement, an error occurs. ::: ### Example This example uses the **For...Next** statement to create a string that contains 10 instances of the numbers 0 through 9, each string separated from the other by a single space. The outer loop uses a loop counter variable that is decremented each time through the loop. ```vb Dim Words, Chars, MyString For Words = 10 To 1 Step -1 ' Set up 10 repetitions. For Chars = 0 To 9 ' Set up 10 repetitions. MyString = MyString & Chars ' Append number to string. Next Chars ' Increment counter MyString = MyString & " " ' Append a space. Next Words ``` --- --- url: /zh/official/Reference/Core/For-Next.md --- # For...Next 当循环计数器接近其终值时重复执行一组语句。 语法: > **For** *counter* \[ **As** *type* ] **=** *start* **To** *end* \[ **Step** *step* ]\ >      \[ *statements* ]\ >      \[ **Continue For** | **Exit For** ]\ >      \[ *statements* ] ...\ > **Next** \[ *counter* ] *counter* : 用作循环计数器的数值变量。该变量不能是Boolean或数组元素。 *type* : *可选* 用于声明 *counter* 的数值类型。\ 当存在时,等效于在 **For** 语句之前紧接放置 `Dim counter As type`。 *start* : *counter* 的初始值。 *end* : *counter* 的终值。 *step* : *可选* 每次循环时 *counter* 的变化量。如果未指定,*step* 默认为1。 *statements* : *可选* **For** 和 **Next** 之间的一条或多条语句,执行指定次数。 **Continue For** : *可选* 立即跳过剩余语句并开始下一次迭代,如果没有更多迭代则退出循环。\ **Continue For** 通常在评估某个条件后使用,例如 **If...Then**。 **Exit For** : *可选* 立即退出循环体。\ **Exit For** 通常在评估某个条件后使用,例如 **If...Then**,并将控制权转移到紧接在 **Next** 之后的语句。 *step* 参数可以是正数或负数。*step* 参数的值决定循环处理方式如下: | 值 | 循环执行条件 | | :------------ | :----------------- | | 正数或0 | *counter* <= *end* | | 负数 | *counter* >= *end* | 循环中所有语句执行完毕后,*step* 被加到 *counter* 上。此时,循环中的语句再次执行(基于最初使循环执行的相同测试),或退出循环,执行继续到 **Next** 语句之后的语句。 ::: tip 在循环内部更改 *counter* 的值可能使代码更难阅读和调试。 ::: **For...Next** 循环可以通过将一个 **For...Next** 循环放在另一个内部来嵌套。给每个循环一个唯一的变量名作为 *counter*。以下结构是正确的: ```vb For I = 1 To 10 For J = 1 To 10 For K = 1 To 10 ' ... Next K Next J Next I ``` ::: info 当 **Next** 语句中省略 *counter* 时,执行继续如同包含了 *counter* 一样。如果在对应的 **For** 语句之前遇到 **Next** 语句,将发生错误。 ::: ### 示例 本示例使用 **For...Next** 语句创建一个包含0到9数字10个实例的字符串,每个字符串之间用单个空格分隔。外层循环使用每次循环递减的循环计数器变量。 ```vb Dim Words, Chars, MyString For Words = 10 To 1 Step -1 ' Set up 10 repetitions. For Chars = 0 To 9 ' Set up 10 repetitions. MyString = MyString & Chars ' Append number to string. Next Chars ' Increment counter MyString = MyString & " " ' Append a space. Next Words ``` --- --- url: /en/official/Reference/VBRUN/AmbientProperties/ForeColor.md --- # ForeColor Returns the foreground colour the container would like its embedded controls to use by default, as an **stdole.OLE\_COLOR**. Read-only. Syntax: *object*.**ForeColor** *object* : *required* An object expression that evaluates to an **AmbientProperties** object. A control that does not have its own foreground colour explicitly set should draw its text and other foreground elements using this colour, so that it remains legible against the container's [**BackColor**](/en/official/Reference/VBRUN/AmbientProperties/BackColor). The value is an **OLE\_COLOR**: an RGB value, a system-colour reference, or a palette-index reference. Pass it through [**TranslateColor**](/en/official/Reference/VBA/Information/TranslateColor) to obtain a plain RGB value if needed. ### Example This example responds to an ambient **ForeColor** change and applies it to the control's text color. ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "ForeColor" UserControl.ForeColor = Ambient.ForeColor End Select End Sub ``` ### See Also * [BackColor](/en/official/Reference/VBRUN/AmbientProperties/BackColor) property * [Font](/en/official/Reference/VBRUN/AmbientProperties/Font) property * [Palette](/en/official/Reference/VBRUN/AmbientProperties/Palette) property --- --- url: /zh/official/Reference/VBRUN/AmbientProperties/ForeColor.md --- # ForeColor 返回容器希望其嵌入控件默认使用的前景色,类型为**stdole.OLE\_COLOR**。只读。 语法:*object*.**ForeColor** *object* : *必需* 求值为**AmbientProperties**对象的对象表达式。 未显式设置自身前景色的控件应使用此颜色绘制文本和其他前景元素,使其在容器的[**BackColor**](/official/Reference/VBRUN/AmbientProperties/BackColor)上保持可读。该值为**OLE\_COLOR**:RGB值、系统颜色引用或调色板索引引用。如需获取普通RGB值,可通过[**TranslateColor**](/official/Reference/VBA/Information/TranslateColor)转换。 ### 示例 此示例响应环境**ForeColor**更改并将其应用于控件的文本颜色。 ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "ForeColor" UserControl.ForeColor = Ambient.ForeColor End Select End Sub ``` ### 另见 * [BackColor](/official/Reference/VBRUN/AmbientProperties/BackColor) 属性 * [Font](/official/Reference/VBRUN/AmbientProperties/Font) 属性 * [Palette](/official/Reference/VBRUN/AmbientProperties/Palette) 属性 --- --- url: /en/official/Reference/VB/Form.md --- # Form class A **Form** is a top-level Win32 window that hosts the controls, menus, and drawing surface of a single twinBASIC user interface. Each form designed in the IDE becomes its own class derived from **Form** --- its controls become members of that class, its event handlers become methods on it, and the file's name becomes the class name. Code outside the form normally instantiates it implicitly through the global default-instance reference (`MyForm.Show`) or explicitly with `New MyForm`. The default property is [**Controls**](#controls) and the default event is [**Load**](#load). ```vb ' In Form1's code-behind: Private Sub Form_Load() Caption = "Welcome" Me.MinWidth = 4000 ' twips, ≈ 2 inches Me.MinHeight = 3000 End Sub Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer) If MsgBox("Quit?", vbYesNo) = vbNo Then Cancel = 1 End Sub ' In a startup module: Sub Main() Form1.Show vbModal End Sub ``` ## Lifecycle A form goes through six distinct events from creation to destruction: | Event | When | |----------------------------------|-------------------------------------------------------------------------------------| | [**Initialize**](#initialize) | Before the underlying window exists. The form's controls are not yet created. | | [**Load**](#load) | After the window and all controls have been created, before the form first appears. | | [**Activate**](#activate) | When the form becomes the active window in the application. | | [**Deactivate**](#deactivate) | When another form (or another application's window) takes activation away. | | [**QueryUnload**](#queryunload) | Before unload. Setting *Cancel* to non-zero keeps the form open. | | [**Unload**](#unload) | After **QueryUnload** approves. Setting *Cancel* to non-zero keeps the form open. | | [**Terminate**](#terminate) | After the window has been destroyed and the class instance is released. | Closing a form goes through both **QueryUnload** *and* **Unload**, so either can veto. The *UnloadMode* argument of **QueryUnload** ([**QueryUnloadConstants**](/en/official/Reference/VBRUN/Constants/QueryUnloadConstants)) reports whether the user clicked the close button, code called **Unload**, Windows is shutting down, the MDI parent is closing, and so on. ## Showing the form [**Show**](#show) makes the form visible. It accepts an optional [**FormShowConstants**](/en/official/Reference/VBRUN/Constants/FormShowConstants) argument: **vbModeless** (default --- the call returns immediately and the user can interact with other forms) or **vbModal** (the call blocks until the form is closed, and other forms in the application become unresponsive). MDI child forms cannot be shown modally; attempting to do so raises run-time error 404. ```vb dlgOptions.Show vbModal, Me ' modal, owned by the calling form ``` [**Hide**](#hide) and [**Close**](#close) reverse the effect: **Hide** just clears [**Visible**](#visible); **Close** runs the full unload sequence (**QueryUnload** then **Unload** then **Terminate**). The classic `Unload <FormName>` statement is the language-level equivalent of **Close**. [**StartUpPosition**](#startupposition) ([**StartUpPositionConstants**](/en/official/Reference/VBRUN/Constants/StartUpPositionConstants)) is read at the first **Show** to decide where the form is placed; afterwards the user (or code through [**Move**](#move) and [**WindowState**](#windowstate)) controls position. ## Window appearance [**BorderStyle**](#borderstyle) ([**FormBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/FormBorderStyleConstants)) chooses between sizable, fixed, dialog, tool, and borderless frames. [**Caption**](#caption) is the title-bar text. [**ControlBox**](#controlbox), [**MaxButton**](#maxbutton), and [**MinButton**](#minbutton) toggle the system menu and resize buttons. [**Icon**](#icon) supplies the small/large icon used by the system menu, the taskbar, and Alt-Tab. [**WindowState**](#windowstate) ([**FormWindowStateConstants**](/en/official/Reference/VBRUN/Constants/FormWindowStateConstants)) reads or sets normal / minimised / maximised state at run time. [**MinWidth**](#minwidth), [**MinHeight**](#minheight), [**MaxWidth**](#maxwidth), and [**MaxHeight**](#maxheight) constrain the *client area* in twips during interactive resizing. [**Moveable**](#moveable) decides whether the user can drag the form by its title bar; [**ShowInTaskbar**](#showintaskbar) decides whether the form shows up in the taskbar and Alt-Tab list. [**Opacity**](#opacity) and [**TransparencyKey**](#transparencykey) enable Windows' layered-window features for translucent forms and cut-out shapes. ## Drawing surface A **Form** is itself a graphics surface --- code can draw lines, shapes, and text directly on it. The coordinate system is governed by [**ScaleMode**](#scalemode) (default **vbTwips** --- the classic VB6 behaviour) and the [**ScaleLeft**](#scaleleft) / [**ScaleTop**](#scaletop) / [**ScaleWidth**](#scalewidth) / [**ScaleHeight**](#scaleheight) properties, which together describe the form's logical drawing rectangle. Setting **ScaleMode** to **vbUser** lets the four **Scale\*** properties define an arbitrary rectangle; the [**Scale**](#scale) method does this in a single call. The drawing primitives are [**Cls**](#cls), [**Circle**](#circle), [**Line**](#line), [**PSet**](#pset), [**PaintPicture**](#paintpicture), and the [**Print**](#print) statement (`Form1.Print "Hello"`) --- all use [**ForeColor**](#forecolor), [**FillColor**](#fillcolor), [**FillStyle**](#fillstyle), [**DrawWidth**](#drawwidth), [**DrawMode**](#drawmode), and [**DrawStyle**](#drawstyle) for their pen and fill, and the form's [**Font**](#font) for text. The current pen position is tracked by [**CurrentX**](#currentx) and [**CurrentY**](#currenty); [**TextWidth**](#textwidth) and [**TextHeight**](#textheight) measure a string in the current font. [**ScaleX**](#scalex) and [**ScaleY**](#scaley) convert single coordinates between scale modes. [**AutoRedraw**](#autoredraw) controls whether drawn output persists across paints: when **False** (default), the [**Paint**](#paint) event must redraw on every invalidation; when **True**, the form keeps an off-screen buffer that survives invalidations and the **Paint** event is suppressed. Setting [**Picture**](#picture) puts a bitmap behind the drawing layer; [**Image**](#image) returns the rendered combined surface as a **StdPicture**. ```vb Private Sub Form_Paint() Me.ScaleMode = vbPixels Me.ForeColor = vbBlue Me.DrawWidth = 3 Me.Line (10, 10)-(120, 80), , B ' rectangle Me.CurrentX = 16 : Me.CurrentY = 16 Me.Print "Hello, twinBASIC" End Sub ``` ## Controls and validation [**Controls**](#controls) is a collection of every control on the form, indexable by name or zero-based position. **Form** is also enumerable directly --- `For Each ctrl In Form1` yields the same items as `For Each ctrl In Form1.Controls`. [**Count**](#count) is shorthand for `Controls.Count`. [**ActiveControl**](#activecontrol) returns the currently focused child, or **Nothing** when no control on this form has the focus. [**KeyPreview**](#keypreview) routes keystrokes to the form's [**KeyDown**](#keydown), [**KeyUp**](#keyup), and [**KeyPress**](#keypress) events *before* the focused control sees them --- useful for application-wide hotkey handling. [**ValidateControls**](#validatecontrols) explicitly fires the active control's **Validate** event from code; it raises run-time error 380 if the validation handler sets *Cancel*. ## Menus and pop-ups Menu structures designed at form-design time appear automatically in the form's title bar. [**PopUpMenu**](#popupmenu) displays one of those menus as a context-menu pop-up at a specified location, raising the menu's **Click** event when the user picks an item. ```vb Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) If Button = vbRightButton Then PopUpMenu mnuContext End Sub ``` ## Properties ### ActiveControl The control on this form that currently has the input focus, as a **Control** object, or **Nothing** when no control on this form is focused. Read-only. ### AlwaysShowKeyboardCues When **True**, the form always shows underlines on access-key characters in [**Caption**](#caption)s and menu items, instead of only displaying them after the user presses **Alt**. **Boolean**, read-only at run time. Set at design time. ### Appearance Determines how the control's border is drawn by the OS. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). ::: info Retained for VB6 compatibility; the property has no observable effect on a form. ::: ### AutoRedraw Whether drawing performed on the form persists across invalidations. **Boolean**, default **False**. When **False**, drawing primitives --- [**Cls**](#cls), [**Circle**](#circle), [**Line**](#line), [**PSet**](#pset), [**PaintPicture**](#paintpicture), and [**Print**](#print) --- paint directly to the screen and the form must redraw them in its [**Paint**](#paint) event whenever the affected area is invalidated. When **True**, the form keeps an off-screen bitmap, drawing primitives paint into it (and immediately to the screen), the bitmap survives invalidations, and the **Paint** event is suppressed. Reading [**Image**](#image) returns this bitmap. ### BackColor The background colour of the form's client area, as an **OLE\_COLOR**. Defaults to the system 3-D face colour. Used as the fill colour for [**Cls**](#cls) and as the canvas behind [**Picture**](#picture). ### BorderStyle The window-frame style. A member of [**FormBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/FormBorderStyleConstants): **vbBSNone**, **vbFixedSingle**, **vbSizable** (default), **vbFixedDialog**, **vbFixedToolWindow**, **vbSizableToolWindow**, **vbSizableNoTitleBar** (new in twinBASIC), or **vbSizableToolWindowNoTitleBar** (new in twinBASIC). Run-time changes are accepted but only take effect after another change to the window --- typically reassigning [**Caption**](#caption). ### Caption The title-bar text. **String**. Syntax: *object*.**Caption** \[ = *string* ] Setting **Caption** updates the title bar immediately and re-syncs the title-bar style flags (so it can revive a title bar that was hidden because the previous **Caption** was empty). ### ClipControls Whether child controls are clipped out of the form's drawing region during paint. **Boolean**, default **True**. Read-only at run time --- set at design time. ### ControlBox Whether the form's title bar shows the system menu (and, with it, the close button). **Boolean**, default **True**. Setting it at run time re-syncs the title-bar style flags. ### Controls The collection of every control hosted by this form, indexable by control name or zero-based position. **Default property.** Read-only --- controls are added to the collection by the runtime, not by user code. ```vb Dim ctrl As Control For Each ctrl In Me.Controls ctrl.Enabled = False Next ``` ### Count The number of controls in [**Controls**](#controls), as a **Long**. Read-only. Equivalent to `Me.Controls.Count`. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a form. Always **vbForm**. ### CurrentX The horizontal pen position, in [**ScaleMode**](#scalemode) units, used by drawing primitives that omit a starting coordinate (for example, [**Print**](#print) and the rectangle form of [**Line**](#line)). **Double**. ### CurrentY The vertical pen position, in [**ScaleMode**](#scalemode) units, used by drawing primitives that omit a starting coordinate. **Double**. ### DpiScaleFactorX The horizontal DPI scale factor of the monitor the form is currently on, as a **Double**. `1.0` at 96 DPI, `1.25` at 120 DPI, `1.5` at 144 DPI, and so on. Read-only. ### DpiScaleFactorY The vertical DPI scale factor of the monitor the form is currently on. Currently always equal to [**DpiScaleFactorX**](#dpiscalefactorx). Read-only. ### DrawMode The raster operation that drawing primitives apply when combining the pen with the destination. A member of [**DrawModeConstants**](/en/official/Reference/VBRUN/Constants/DrawModeConstants): **vbCopyPen** (default) is normal opaque drawing; other values produce XOR, AND, NOT, and other pixel-mixing effects. ### DrawStyle The pen line pattern used by drawing primitives. A member of [**DrawStyleConstants**](/en/official/Reference/VBRUN/Constants/DrawStyleConstants): **vbSolid** (default), **vbDash**, **vbDot**, **vbDashDot**, **vbDashDotDot**, **vbInvisible**, or **vbInsideSolid**. ### DrawWidth The pen width in pixels for drawing primitives. **Long**, default `1`. Widths greater than 1 force [**DrawStyle**](#drawstyle) back to **vbSolid** (a Win32 GDI limitation). ### Enabled Determines whether the form accepts user input. A disabled form ignores keyboard and mouse input and dims its controls. **Boolean**, default **True**. ### FillColor The fill colour for closed shapes drawn by [**Circle**](#circle) and the rectangle form of [**Line**](#line). **OLE\_COLOR**, default `0` (black). Used only when [**FillStyle**](#fillstyle) is not **vbFSTransparent**. ### FillStyle The fill pattern for closed shapes. A member of [**FillStyleConstants**](/en/official/Reference/VBRUN/Constants/FillStyleConstants): **vbFSSolid**, **vbFSTransparent** (default), **vbHorizontalLine**, **vbVerticalLine**, **vbUpwardDiagonal**, **vbDownwardDiagonal**, **vbCross**, or **vbDiagonalCross**. ### Font The **StdFont** used by the [**Print**](#print) statement and other text drawing on this form. The convenience properties **FontName**, **FontSize**, **FontBold**, **FontItalic**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. ### FontTransparent When **True** (default), text drawn on the form has a transparent background, leaving the underlying drawing visible behind it. When **False**, text is drawn over an opaque rectangle filled with [**BackColor**](#backcolor). **Boolean**. ### ForeColor The pen colour used by [**Circle**](#circle), [**Line**](#line), [**PSet**](#pset), and the text drawn by [**Print**](#print). **OLE\_COLOR**. ### hDC The Win32 device context handle for the form, as a **LongPtr**. Read-only. Returns `0` when the underlying window has not yet been created. Useful for passing to GDI API calls. ### HasDC Whether the form keeps a private device context (`CS_OWNDC`) for its drawing surface. **Boolean**, default **True**. Read-only at run time --- set at design time. ### Height The form's outer height, in twips by default (or in the container's **ScaleMode** units). **Double**. Setting it resizes the window. Constrained at run time by [**MinHeight**](#minheight) and [**MaxHeight**](#maxheight) when those are non-zero. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the form has focus. ### hWnd The Win32 window handle for the form, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Icon The icon shown on the title bar, in the taskbar, and in Alt-Tab. A **StdPicture** of type **vbPicTypeIcon**. Assigning a non-icon picture clears the icon to the default Windows application icon. ### Image Returns the rendered drawing surface as a **StdPicture**. Read-only. Most useful when [**AutoRedraw**](#autoredraw) is **True** --- the returned picture is the persistent off-screen buffer. ### KeyPreview When **True**, the form's [**KeyDown**](#keydown), [**KeyUp**](#keyup), and [**KeyPress**](#keypress) events fire *before* the focused control receives the same keystroke. **Boolean**, default **False**. Useful for application-wide hotkeys; events still fire on the focused control afterwards. ### Left The horizontal position of the form's outer rectangle, in twips (or the calling code's **ScaleMode** units), measured from the left edge of the screen --- or, for an MDI child, from the left edge of the MDI parent's client area. **Double**. ### LinkMode ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: ### LinkTopic ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: ### MaxButton Whether the title bar shows the maximise button. **Boolean**, default **True**, read-only at run time. Set at design time. ### MaxHeight The maximum height of the form's *client area*, in twips. **Double**, default `0` (no limit). Honoured during interactive resizing. ### MaxWidth The maximum width of the form's *client area*, in twips. **Double**, default `0` (no limit). Honoured during interactive resizing. ### MDIChild When **True**, the form is hosted as a child inside an [**MDIForm**](/en/official/Reference/VB/MDIForm/). **Boolean**, read-only --- set at design time. An MDI child form cannot be shown modally. ### MinButton Whether the title bar shows the minimise button. **Boolean**, default **True**, read-only at run time. Set at design time. ### MinHeight The minimum height of the form's *client area*, in twips. **Double**, default `0` (no limit). Honoured during interactive resizing. ### MinWidth The minimum width of the form's *client area*, in twips. **Double**, default `0` (no limit). Honoured during interactive resizing. ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the form (and not over a child control with its own setting). ### MousePointer The mouse cursor shown when the pointer is over the form (and not over a child control with its own setting). A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Moveable Whether the user can drag the form by its title bar. **Boolean**, default **True**. ### Name The unique design-time name of the form. Read-only at run time. Also the class name of the generated form class. ### NegotiateMenus ::: info Reserved for compatibility with VB6's ActiveX-document menu negotiation feature; not currently implemented in twinBASIC. ::: ### OLEDropMode How the form responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on a Form. ### Opacity The form's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Values below 100 cause the form to become a layered window. ### Palette ::: info Reserved for compatibility with VB6's 256-colour palette feature; not currently implemented in twinBASIC. ::: ### PaletteMode ::: info Reserved for compatibility with VB6's 256-colour palette feature; not currently implemented in twinBASIC. ::: ### Picture A **StdPicture** drawn as the form's background. Painted before any drawing primitives or child controls. Assigning **Nothing** removes the background. ### PictureDpiScaling When **True**, [**Picture**](#picture) is scaled by the current DPI factor before drawing. **Boolean**, default **False**. ### RightToLeft ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### ScaleHeight The height of the logical drawing rectangle, in [**ScaleMode**](#scalemode) units. **Double**. Setting it (or [**ScaleWidth**](#scalewidth), [**ScaleLeft**](#scaleleft), or [**ScaleTop**](#scaletop)) implicitly switches **ScaleMode** to **vbUser**. ### ScaleLeft The logical horizontal coordinate of the left edge of the form's client area, in [**ScaleMode**](#scalemode) units. **Double**. Default `0`. ### ScaleMode The unit of measurement used by [**CurrentX**](#currentx), [**CurrentY**](#currenty), the drawing primitives, [**TextWidth**](#textwidth), and [**TextHeight**](#textheight). A member of [**ScaleModeConstants**](/en/official/Reference/VBRUN/Constants/ScaleModeConstants): **vbTwips** (default), **vbPoints**, **vbPixels**, **vbCharacters**, **vbInches**, **vbMillimeters**, **vbCentimeters**, or **vbUser** (the four **Scale\*** properties define the rectangle). ### ScaleTop The logical vertical coordinate of the top edge of the form's client area, in [**ScaleMode**](#scalemode) units. **Double**. Default `0`. ### ScaleWidth The width of the logical drawing rectangle, in [**ScaleMode**](#scalemode) units. **Double**. Setting it implicitly switches **ScaleMode** to **vbUser**. ### ShowInTaskbar Whether the form appears in the Windows taskbar and Alt-Tab list. **Boolean**, default **True**. Read-only at run time --- set at design time. ### StartUpPosition How the form's initial position is determined the first time it is shown. A member of [**StartUpPositionConstants**](/en/official/Reference/VBRUN/Constants/StartUpPositionConstants): **vbStartUpManual**, **vbStartUpOwner**, **vbStartUpScreen**, or **vbStartUpWindowsDefault** (default). Read-only at run time --- set at design time. ### TabFocusAutoSelect When **True**, a [**TextBox**](/en/official/Reference/VB/TextBox/) on this form whose own **TabFocusAutoSelect** is also **True** auto-selects its content when the focus enters it via the **TAB** key. **Boolean**, default **False**. ### Tag A free-form **String** the application can use to associate custom data with the form. Ignored by the framework. ### Top The vertical position of the form's outer rectangle, in twips (or the calling code's **ScaleMode** units), measured from the top edge of the screen --- or, for an MDI child, from the top edge of the MDI parent's client area. **Double**. ### TopMost Whether the form sits in the always-on-top z-order layer. **Boolean**, read-only at run time. Set at design time. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered form --- clicks pass through to whatever is underneath, and the corresponding pixels do not paint. Default `-1` disables the effect. ### Visible Whether the form is shown. **Boolean**, default **True**. Setting **Visible** to **True** when the form was hidden is equivalent to calling [**Show**](#show) **vbModeless**; setting it to **False** is equivalent to calling [**Hide**](#hide). ### WhatsThisButton When **True**, the title bar shows a "?" help button --- but only when [**MinButton**](#minbutton) is **False**, [**MaxButton**](#maxbutton) is **False**, [**ControlBox**](#controlbox) is **True**, and [**BorderStyle**](#borderstyle) is not a tool-window style. **Boolean**. ### WhatsThisHelp When **True**, [**WhatsThisMode**](#whatsthismode) and the title-bar help button enter Windows' "What's This?" cursor mode. **Boolean**, default **False**. ### Width The form's outer width, in twips by default (or in the container's **ScaleMode** units). **Double**. Setting it resizes the window. Constrained at run time by [**MinWidth**](#minwidth) and [**MaxWidth**](#maxwidth) when those are non-zero. ### WindowState The window's normal/minimised/maximised state. A member of [**FormWindowStateConstants**](/en/official/Reference/VBRUN/Constants/FormWindowStateConstants): **vbNormal** (0, default), **vbMinimized** (1), or **vbMaximized** (2). Setting it at run time updates the window placement immediately if the form is visible. ## Methods ### Circle Draws a circle, ellipse, or arc on the form using [**ForeColor**](#forecolor) for the outline and [**FillColor**](#fillcolor)/[**FillStyle**](#fillstyle) for the interior. Syntax: *object*.**Circle** \[ **Step** ] ( *X*, *Y* ), *Radius* \[, \[ *Color* ] \[, \[ *Start* ] \[, \[ *End* ] \[, *Aspect* ] ] ] ] *X*, *Y* : *required* The centre, in [**ScaleMode**](#scalemode) units. **Step** makes the centre relative to ([**CurrentX**](#currentx), [**CurrentY**](#currenty)). *Radius* : *required* A **Single** giving the radius in **ScaleMode** units. *Color* : *optional* An **OLE\_COLOR** for the outline; defaults to [**ForeColor**](#forecolor). *Start*, *End* : *optional* Angles in radians, used to draw an arc rather than a full circle. *Aspect* : *optional* Ratio of vertical to horizontal radius. `1.0` is circular; values away from `1.0` produce ellipses. ### Cls Clears any drawing performed by [**Circle**](#circle), [**Line**](#line), [**PSet**](#pset), [**PaintPicture**](#paintpicture), and [**Print**](#print), repaints [**BackColor**](#backcolor), and resets [**CurrentX**](#currentx) / [**CurrentY**](#currenty) to `0`. Does not affect the [**Picture**](#picture) backdrop or child controls. Syntax: *object*.**Cls** ### Close Initiates the form's unload sequence --- [**QueryUnload**](#queryunload), then [**Unload**](#unload), then [**Terminate**](#terminate). Either of the first two events can cancel the close by setting *Cancel* to non-zero. Equivalent to the language statement `Unload Me`. Syntax: *object*.**Close** ### Hide Hides the form without unloading it. The class instance and its controls are preserved; calling [**Show**](#show) (or assigning [**Visible**](#visible) = **True**) brings it back. Equivalent to assigning **Visible** = **False**. Syntax: *object*.**Hide** ### Line Draws a line, or a rectangle, on the form using [**ForeColor**](#forecolor) (or an explicit colour) and [**DrawWidth**](#drawwidth)/[**DrawStyle**](#drawstyle). Syntax: *object*.**Line** \[ \[ **Step** ] ( *X1*, *Y1* ) ] -\[ **Step** ] ( *X2*, *Y2* ) \[, \[ *Color* ] \[, **B** \[ **F** ] ] ] *X1*, *Y1* : *optional* The start point, in [**ScaleMode**](#scalemode) units. **Step** makes the point relative to ([**CurrentX**](#currentx), [**CurrentY**](#currenty)). When omitted, drawing begins from the current pen position. *X2*, *Y2* : *required* The end point, in **ScaleMode** units. **Step** makes the point relative to (*X1*, *Y1*). *Color* : *optional* An **OLE\_COLOR** for the line; defaults to [**ForeColor**](#forecolor). **B** : *optional* Draw a rectangle whose opposite corners are (*X1*, *Y1*) and (*X2*, *Y2*) instead of a line. **F** : *optional* When combined with **B**, fill the rectangle with [**ForeColor**](#forecolor) instead of [**FillColor**](#fillcolor)/[**FillStyle**](#fillstyle). ### Move Repositions and optionally resizes the form in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the form, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### PaintPicture Draws a **StdPicture** onto the form, with optional scaling and raster operations. Syntax: *object*.**PaintPicture** *Picture*, *X1*, *Y1* \[, *Width1* \[, *Height1* \[, *X2* \[, *Y2* \[, *Width2* \[, *Height2* \[, *Opcode* \[, *StretchQuality* ] ] ] ] ] ] ] ] *Picture* : *required* A **StdPicture** to draw. *X1*, *Y1* : *required* The destination upper-left corner, in [**ScaleMode**](#scalemode) units. *Width1*, *Height1* : *optional* Destination size; defaults to the picture's natural size. *X2*, *Y2*, *Width2*, *Height2* : *optional* The source rectangle within the picture; defaults to the whole picture. *Opcode* : *optional* A raster-operation code (member of [**RasterOpConstants**](/en/official/Reference/VBRUN/Constants/RasterOpConstants)). Defaults to **vbSrcCopy**. *StretchQuality* : *optional* The interpolation method when scaling. Defaults to normal quality. ### PopUpMenu Displays a [**Menu**](/en/official/Reference/VB/Menu/) as a context-menu pop-up at the specified location. Syntax: *object*.**PopUpMenu** *Menu* \[, *Flags* \[, *X* \[, *Y* \[, *DefaultMenu* ] ] ] ] *Menu* : *required* The **Menu** control to display. The menu must already exist on the form (or its MDI parent). *Flags* : *optional* A combination of [**MenuControlConstants**](/en/official/Reference/VBRUN/Constants/MenuControlConstants) controlling alignment and which mouse buttons trigger the menu items. *X*, *Y* : *optional* The screen-relative position to anchor the menu at, in [**ScaleMode**](#scalemode) units. Defaults to the current mouse position. *DefaultMenu* : *optional* The **Menu** sub-item to render in bold as the default action. ### Point ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. In VB6 this returns the **OLE\_COLOR** of a single pixel of the drawing surface. ::: Syntax: *object*.**Point**( *X*, *Y* ) ### Print Writes text to the form's drawing surface using [**Font**](#font), starting at [**CurrentX**](#currentx) / [**CurrentY**](#currenty) and advancing them as it goes. Dispatched through the VB6 **Print** statement so multiple expressions can be separated by `;` (no spacing) or `,` (tab to the next print zone). **Spc(n)** inserts *n* spaces and **Tab(n)** moves to print column *n*. Output honours [**Font**](#font), [**ForeColor**](#forecolor), and [**FontTransparent**](#fonttransparent), and --- when [**AutoRedraw**](#autoredraw) is **True** --- is recorded into the persistent off-screen bitmap so it survives invalidations. Syntax: *object*.**Print** \[ *expressionlist* ] \[ **;** | **,** ] A trailing `;` or `,` suppresses the newline so the next **Print** call continues on the same line; without a trailing separator, the pen advances to the start of the next line. ```vb Me.CurrentX = 10 : Me.CurrentY = 10 Me.Print "Name: "; sName, "Age: "; nAge ' two fields, tab-separated Me.Print ' blank line Me.Print "Total: " & Format$(Total, "0.00") ``` ### PrintForm Sends a screen-shot of the form's current visual state to the default printer through the [**Printer**](/en/official/Reference/VB/Printer/) object. Syntax: *object*.**PrintForm** \[ *ImplicitEndDoc* \[, *OutputAtCurrentPosition* ] ] *ImplicitEndDoc* : *optional* When **True** (default), the print job is finalised before returning; when **False**, the form is sent as a page but the print job stays open for further output. *OutputAtCurrentPosition* : *optional* When **True**, the form is rendered at the printer's current pen position rather than at the page origin. **Boolean**, default **False**. ### PSet Sets a single pixel on the form to a specified colour. Syntax: *object*.**PSet** \[ **Step** ] ( *X*, *Y* ) \[, *Color* ] *X*, *Y* : *required* The pixel position, in [**ScaleMode**](#scalemode) units. **Step** makes the position relative to ([**CurrentX**](#currentx), [**CurrentY**](#currenty)). *Color* : *optional* An **OLE\_COLOR**; defaults to [**ForeColor**](#forecolor). ### Refresh Forces an immediate repaint of the form, raising [**Paint**](#paint) when [**AutoRedraw**](#autoredraw) is **False**. Syntax: *object*.**Refresh** ### Scale Sets the form's logical drawing rectangle in a single call by assigning [**ScaleLeft**](#scaleleft), [**ScaleTop**](#scaletop), [**ScaleWidth**](#scalewidth), and [**ScaleHeight**](#scaleheight). Switches [**ScaleMode**](#scalemode) to **vbUser**. Calling **Scale** with no arguments resets the rectangle to a 1-to-1 mapping with the client area in pixels. Syntax: *object*.**Scale** \[ ( *X1*, *Y1* )-( *X2*, *Y2* ) ] *X1*, *Y1* : *optional* The logical coordinate at the top-left corner. *X2*, *Y2* : *optional* The logical coordinate at the bottom-right corner. ### ScaleX Converts a horizontal length from one [**ScaleMode**](#scalemode) to another. Syntax: *object*.**ScaleX**( *Width* \[, *FromScale* \[, *ToScale* ] ] ) *Width* : *required* A **Single** giving the source length. *FromScale*, *ToScale* : *optional* Members of [**ScaleModeConstants**](/en/official/Reference/VBRUN/Constants/ScaleModeConstants). Default to the current **ScaleMode** when omitted. ### ScaleY Converts a vertical length from one [**ScaleMode**](#scalemode) to another. Syntax: *object*.**ScaleY**( *Height* \[, *FromScale* \[, *ToScale* ] ] ) *Height* : *required* A **Single** giving the source length. *FromScale*, *ToScale* : *optional* Members of [**ScaleModeConstants**](/en/official/Reference/VBRUN/Constants/ScaleModeConstants). Default to the current **ScaleMode** when omitted. ### SetFocus Activates the form and gives input focus to the control whose [**TabIndex**](/en/official/Reference/VB/TextBox/#tabindex) is `0` (or to whichever control last held focus on this form). Syntax: *object*.**SetFocus** ### Show Makes the form visible. Triggers [**Load**](#load) on the first call. Syntax: *object*.**Show** \[ *Modal* \[, *OwnerForm* ] ] *Modal* : *optional* A member of [**FormShowConstants**](/en/official/Reference/VBRUN/Constants/FormShowConstants): **vbModeless** (0, default --- the call returns immediately) or **vbModal** (1 --- the call blocks until the form is closed and the user cannot interact with other forms). *OwnerForm* : *optional* For modal shows, the form that is disabled while this form is up; defaults to the currently active form. ### TextHeight Returns the height that the given string would occupy when drawn with the form's current [**Font**](#font), in [**ScaleMode**](#scalemode) units. Syntax: *object*.**TextHeight**( *Str* ) *Str* : *required* A **String** to measure. ### TextWidth Returns the width that the given string would occupy when drawn with the form's current [**Font**](#font), in [**ScaleMode**](#scalemode) units. Syntax: *object*.**TextWidth**( *Str* ) *Str* : *required* A **String** to measure. ### ValidateControls Fires the **Validate** event of the currently active control on this form. If the handler sets *Cancel* to **True**, **ValidateControls** raises run-time error 380 (*Invalid property value*); the caller can wrap this with `On Error` to detect a failed validation. Useful for checking pending input before saving or closing. Syntax: *object*.**ValidateControls** ### WhatsThisMode Enters Windows' "What's This?" cursor mode --- the next click on a control raises that control's help instead of activating it. [**WhatsThisHelp**](#whatsthishelp) must be **True**. Syntax: *object*.**WhatsThisMode** ### ZOrder Brings the form to the front or back of the top-level z-order. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Activate Raised when the form becomes the active window in the application --- either after [**Load**](#load) for the first show, or whenever it gains activation back from another window. Syntax: *object*\_**Activate**( ) ### Click Raised when the user single-clicks the form's client area (i.e. not over any child control). Syntax: *object*\_**Click**( ) ### DblClick Raised when the user double-clicks the form's client area. Syntax: *object*\_**DblClick**( ) ### Deactivate Raised when another window in the application takes activation away from this form. Not raised when activation moves to a window in a different application. Syntax: *object*\_**Deactivate**( ) ### DPIChange Raised when the form moves to a monitor with a different DPI scale, *but only* when the application is per-monitor DPI aware (`PROCESS_PER_MONITOR_DPI_AWARE`). The event's *NewDPI* argument gives the new effective DPI; child controls re-scale themselves automatically. New in twinBASIC. Syntax: *object*\_**DPIChange**( *NewDPI* **As Long** ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus Raised when the form receives the input focus and no enabled child control of the form is in a position to take it instead. A form with no focusable child controls receives focus directly. Syntax: *object*\_**GotFocus**( ) ### Initialize Raised once, before the underlying window is created and before any of the form's child controls exist. Useful for setting initial values on form-level fields. The form's controls cannot be referenced from this event. Syntax: *object*\_**Initialize**( ) ### KeyDown Raised when the user presses any key. Fires on the focused control by default; with [**KeyPreview**](#keypreview) **True**, fires on the form first. Syntax: *object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress Raised when the user types a character that produces an ANSI keystroke. Fires on the focused control by default; with [**KeyPreview**](#keypreview) **True**, fires on the form first. Syntax: *object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp Raised when the user releases a key. Fires on the focused control by default; with [**KeyPreview**](#keypreview) **True**, fires on the form first. Syntax: *object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LinkClose ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### LinkError ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### LinkExecute ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### LinkOpen ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### Load Raised after the form's window and all controls have been created, just before the form first appears on screen. The classic place to populate controls, attach data sources, and perform any initialisation that needs the controls to exist. **Default event.** Syntax: *object*\_**Load**( ) ### LostFocus Raised when the form loses the input focus. Syntax: *object*\_**LostFocus**( ) ### MouseDown Raised when the user presses any mouse button over the form's client area. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the form's client area. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the form's client area. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseWheel Raised when the mouse wheel turns over the form. New in twinBASIC. Syntax: *object*\_**MouseWheel**( *Delta* **As Integer**, *Horizontal* **As Boolean** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Paint Raised when an invalidated portion of the form needs to be redrawn. Suppressed when [**AutoRedraw**](#autoredraw) is **True** --- the form's persistent off-screen buffer is blitted to the screen instead. Syntax: *object*\_**Paint**( ) ### QueryUnload Raised before the form unloads, giving the application a chance to confirm or cancel the close. Setting *Cancel* to non-zero keeps the form open. Always raised before [**Unload**](#unload). Syntax: *object*\_**QueryUnload**( *Cancel* **As Integer**, *UnloadMode* **As Integer** ) *Cancel* : Set to non-zero (any non-zero value, conventionally **1**) to cancel the close. *UnloadMode* : A member of [**QueryUnloadConstants**](/en/official/Reference/VBRUN/Constants/QueryUnloadConstants) identifying what triggered the close --- the close button, code, Windows shutdown, the MDI parent, or the owner form. ### Resize Raised when the form is resized --- by the user, by code, by the OS following a [**WindowState**](#windowstate) change, or by initial layout during the first show. Syntax: *object*\_**Resize**( ) ### Terminate Raised after the form's window has been destroyed and the class instance is about to be released. The controls are no longer accessible at this point. Syntax: *object*\_**Terminate**( ) ### Unload Raised after [**QueryUnload**](#queryunload) approves and before the form's window is destroyed. Setting *Cancel* to non-zero keeps the form open and prevents the unload. Syntax: *object*\_**Unload**( *Cancel* **As Integer** ) *Cancel* : Set to non-zero (any non-zero value, conventionally **1**) to cancel the unload. --- --- url: /zh/official/Reference/VB/Form.md --- # Form 类 **Form** 是一个顶级 Win32 窗口,承载单个 twinBASIC 用户界面的控件、菜单和绘图表面。在 IDE 中设计的每个窗体都成为派生自**Form**的自身类——其控件成为该类的成员,其事件处理程序成为其上的方法,文件名成为类名。窗体外的代码通常通过全局默认实例引用(`MyForm.Show`)隐式实例化它,或使用`New MyForm`显式实例化。默认属性为[**Controls**](#controls),默认事件为[**Load**](#load)。 ```vb ' 在 Form1 的代码隐藏中: Private Sub Form_Load() Caption = "Welcome" Me.MinWidth = 4000 ' 缇,≈ 2 英寸 Me.MinHeight = 3000 End Sub Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer) If MsgBox("Quit?", vbYesNo) = vbNo Then Cancel = 1 End Sub ' 在启动模块中: Sub Main() Form1.Show vbModal End Sub ``` ## 生命周期 窗体从创建到销毁经历六个不同事件: | 事件 | 时机 | |----------------------------------|-------------------------------------------------------------------------------------| | [**Initialize**](#initialize) | 底层窗口存在之前。窗体的控件尚未创建。 | | [**Load**](#load) | 窗口和所有控件创建之后,窗体首次显示之前。 | | [**Activate**](#activate) | 窗体成为应用程序中的活动窗口时。 | | [**Deactivate**](#deactivate) | 另一个窗体(或另一个应用程序的窗口)夺取激活时。 | | [**QueryUnload**](#queryunload) | 卸载之前。将*Cancel*设置为非零可保持窗体打开。 | | [**Unload**](#unload) | **QueryUnload**通过之后。将*Cancel*设置为非零可保持窗体打开。 | | [**Terminate**](#terminate) | 窗口销毁且类实例释放之后。 | 关闭窗体经过**QueryUnload***和***Unload**两者,因此任一都可以否决。**QueryUnload**的*UnloadMode*参数([**QueryUnloadConstants**](/official/Reference/VBRUN/Constants/QueryUnloadConstants))报告用户是点击了关闭按钮、代码调用了**Unload**、Windows 正在关机、MDI 父窗体正在关闭等。 ## 显示窗体 [**Show**](#show)使窗体可见。它接受一个可选的[**FormShowConstants**](/official/Reference/VBRUN/Constants/FormShowConstants)参数:**vbModeless**(默认——调用立即返回,用户可与其他窗体交互)或**vbModal**(调用阻塞直到窗体关闭,应用程序中的其他窗体变得不可响应)。MDI 子窗体不能以模态方式显示;尝试这样做会引发运行时错误 404。 ```vb dlgOptions.Show vbModal, Me ' 模态,由调用窗体拥有 ``` [**Hide**](#hide)和[**Close**](#close)反转效果:**Hide**仅清除[**Visible**](#visible);**Close**运行完整的卸载序列(**QueryUnload**然后**Unload**然后**Terminate**)。经典的`Unload <FormName>`语句在语言层面等同于**Close**。 [**StartUpPosition**](#startupposition)([**StartUpPositionConstants**](/official/Reference/VBRUN/Constants/StartUpPositionConstants))在首次**Show**时读取以决定窗体放置位置;之后由用户(或代码通过[**Move**](#move)和[**WindowState**](#windowstate))控制位置。 ## 窗口外观 [**BorderStyle**](#borderstyle)([**FormBorderStyleConstants**](/official/Reference/VBRUN/Constants/FormBorderStyleConstants))在可调整大小、固定、对话框、工具和无边框框架之间选择。[**Caption**](#caption)是标题栏文本。[**ControlBox**](#controlbox)、[**MaxButton**](#maxbutton)和[**MinButton**](#minbutton)切换系统菜单和调整大小按钮。[**Icon**](#icon)提供系统菜单、任务栏和 Alt-Tab 使用的小/大图标。[**WindowState**](#windowstate)([**FormWindowStateConstants**](/official/Reference/VBRUN/Constants/FormWindowStateConstants))在运行时读取或设置正常/最小化/最大化状态。 [**MinWidth**](#minwidth)、[**MinHeight**](#minheight)、[**MaxWidth**](#maxwidth)和[**MaxHeight**](#maxheight)在交互式调整大小期间以缇为单位约束*客户区*。[**Moveable**](#moveable)决定用户是否可以通过标题栏拖动窗体;[**ShowInTaskbar**](#showintaskbar)决定窗体是否出现在任务栏和 Alt-Tab 列表中。 [**Opacity**](#opacity)和[**TransparencyKey**](#transparencykey)启用 Windows 的分层窗口功能,实现半透明窗体和镂空形状。 ## 绘图表面 **Form** 本身是一个图形表面——代码可以直接在其上绘制线条、形状和文本。坐标系由[**ScaleMode**](#scalemode)(默认**vbTwips**——经典 VB6 行为)和[**ScaleLeft**](#scaleleft) / [**ScaleTop**](#scaletop) / [**ScaleWidth**](#scalewidth) / [**ScaleHeight**](#scaleheight)属性控制,它们共同描述窗体的逻辑绘图矩形。将**ScaleMode**设置为**vbUser**允许四个**Scale\***属性定义任意矩形;[**Scale**](#scale)方法在单次调用中完成此操作。 绘图原语为[**Cls**](#cls)、[**Circle**](#circle)、[**Line**](#line)、[**PSet**](#pset)、[**PaintPicture**](#paintpicture)和[**Print**](#print)语句(`Form1.Print "Hello"`)——均使用[**ForeColor**](#forecolor)、[**FillColor**](#fillcolor)、[**FillStyle**](#fillstyle)、[**DrawWidth**](#drawwidth)、[**DrawMode**](#drawmode)和[**DrawStyle**](#drawstyle)作为画笔和填充,并使用窗体的[**Font**](#font)绘制文本。当前画笔位置由[**CurrentX**](#currentx)和[**CurrentY**](#currenty)跟踪;[**TextWidth**](#textwidth)和[**TextHeight**](#textheight)以当前字体测量字符串。[**ScaleX**](#scalex)和[**ScaleY**](#scaley)在比例模式之间转换单个坐标。 [**AutoRedraw**](#autoredraw)控制绘图输出是否在重绘时持久保留:当**False**(默认)时,[**Paint**](#paint)事件必须在每次失效时重绘;当**True**时,窗体保持一个在失效时存活的离屏缓冲区,**Paint**事件被抑制。设置[**Picture**](#picture)在绘图层后面放置位图;[**Image**](#image)以**StdPicture**形式返回渲染的组合表面。 ```vb Private Sub Form_Paint() Me.ScaleMode = vbPixels Me.ForeColor = vbBlue Me.DrawWidth = 3 Me.Line (10, 10)-(120, 80), , B ' 矩形 Me.CurrentX = 16 : Me.CurrentY = 16 Me.Print "Hello, twinBASIC" End Sub ``` ## 控件和验证 [**Controls**](#controls)是窗体上每个控件的集合,可按名称或零基位置索引。**Form** 也可直接枚举——`For Each ctrl In Form1`产生与`For Each ctrl In Form1.Controls`相同的项。[**Count**](#count)是`Controls.Count`的简写。[**ActiveControl**](#activecontrol)返回当前获得焦点的子控件,或当此窗体上没有控件获得焦点时返回**Nothing**。 [**KeyPreview**](#keypreview)将击键路由到窗体的[**KeyDown**](#keydown)、[**KeyUp**](#keyup)和[**KeyPress**](#keypress)事件,*在*焦点控件看到它们*之前*——适用于应用程序级热键处理。[**ValidateControls**](#validatecontrols)从代码显式触发活动控件的**Validate**事件;如果验证处理程序设置*Cancel*,则引发运行时错误 380。 ## 菜单和弹出菜单 在窗体设计时设计的菜单结构自动出现在窗体的标题栏中。[**PopUpMenu**](#popupmenu)将其中一个菜单作为上下文菜单弹出显示在指定位置,当用户选择项目时触发菜单的**Click**事件。 ```vb Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) If Button = vbRightButton Then PopUpMenu mnuContext End Sub ``` ## 属性 ### ActiveControl 此窗体上当前获得输入焦点的控件,为**Control**对象,或当此窗体上没有控件获得焦点时为**Nothing**。只读。 ### AlwaysShowKeyboardCues 当**True**时,窗体始终显示[**Caption**](#caption)和菜单项中访问键字符的下划线,而不是仅在用户按**Alt**后显示。**Boolean**,运行时只读。在设计时设置。 ### Appearance 决定操作系统如何绘制控件边框。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。 ::: info 保留用于 VB6 兼容性;该属性在窗体上没有可观察效果。 ::: ### AutoRedraw 在窗体上执行的绘图是否在失效时持久保留。**Boolean**,默认**False**。 当**False**时,绘图原语——[**Cls**](#cls)、[**Circle**](#circle)、[**Line**](#line)、[**PSet**](#pset)、[**PaintPicture**](#paintpicture)和[**Print**](#print)——直接绘制到屏幕,窗体必须在[**Paint**](#paint)事件中在受影响区域失效时重绘它们。当**True**时,窗体保持一个离屏位图,绘图原语绘制到其中(并立即到屏幕),位图在失效时存活,**Paint**事件被抑制。读取[**Image**](#image)返回此位图。 ### BackColor 窗体客户区的背景色,为**OLE\_COLOR**。默认为系统 3D 面颜色。用作[**Cls**](#cls)的填充色和[**Picture**](#picture)后面的画布。 ### BorderStyle 窗口框架样式。[**FormBorderStyleConstants**](/official/Reference/VBRUN/Constants/FormBorderStyleConstants)的成员:**vbBSNone**、**vbFixedSingle**、**vbSizable**(默认)、**vbFixedDialog**、**vbFixedToolWindow**、**vbSizableToolWindow**、**vbSizableNoTitleBar**(twinBASIC 新增)或**vbSizableToolWindowNoTitleBar**(twinBASIC 新增)。运行时更改被接受,但仅在窗口发生另一次更改后生效——通常是重新赋值[**Caption**](#caption)。 ### Caption 标题栏文本。**String**。 语法:*object*.**Caption** \[ = *string* ] 设置**Caption**会立即更新标题栏并重新同步标题栏样式标志(因此它可以恢复因前一个**Caption**为空而隐藏的标题栏)。 ### ClipControls 在绘制期间子控件是否从窗体的绘图区域中裁剪出去。**Boolean**,默认**True**。运行时只读——在设计时设置。 ### ControlBox 窗体标题栏是否显示系统菜单(以及关闭按钮)。**Boolean**,默认**True**。在运行时设置会重新同步标题栏样式标志。 ### Controls 此窗体承载的每个控件的集合,可按控件名称或零基位置索引。\*\*默认属性。\*\*只读——控件由运行时添加到集合中,而非用户代码。 ```vb Dim ctrl As Control For Each ctrl In Me.Controls ctrl.Enabled = False Next ``` ### Count [**Controls**](#controls)中的控件数量,为**Long**。只读。等效于`Me.Controls.Count`。 ### ControlType 标识此控件为窗体的只读[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值。始终为**vbForm**。 ### CurrentX 水平画笔位置,以[**ScaleMode**](#scalemode)单位表示,由省略起始坐标的绘图原语使用(例如[**Print**](#print)和[**Line**](#line)的矩形形式)。**Double**。 ### CurrentY 垂直画笔位置,以[**ScaleMode**](#scalemode)单位表示,由省略起始坐标的绘图原语使用。**Double**。 ### DpiScaleFactorX 窗体当前所在显示器的水平 DPI 缩放因子,为**Double**。96 DPI 时为`1.0`,120 DPI 时为`1.25`,144 DPI 时为`1.5`,以此类推。只读。 ### DpiScaleFactorY 窗体当前所在显示器的垂直 DPI 缩放因子。当前始终等于[**DpiScaleFactorX**](#dpiscalefactorx)。只读。 ### DrawMode 绘图原语在将画笔与目标组合时应用的光栅操作。[**DrawModeConstants**](/official/Reference/VBRUN/Constants/DrawModeConstants)的成员:**vbCopyPen**(默认)是正常不透明绘制;其他值产生 XOR、AND、NOT 和其他像素混合效果。 ### DrawStyle 绘图原语使用的画笔线型。[**DrawStyleConstants**](/official/Reference/VBRUN/Constants/DrawStyleConstants)的成员:**vbSolid**(默认)、**vbDash**、**vbDot**、**vbDashDot**、**vbDashDotDot**、**vbInvisible**或**vbInsideSolid**。 ### DrawWidth 绘图原语的画笔宽度,以像素为单位。**Long**,默认`1`。宽度大于 1 会强制[**DrawStyle**](#drawstyle)回到**vbSolid**(Win32 GDI 限制)。 ### Enabled 决定窗体是否接受用户输入。禁用的窗体忽略键盘和鼠标输入并使其控件变暗。**Boolean**,默认**True**。 ### FillColor 由[**Circle**](#circle)和[**Line**](#line)矩形形式绘制的封闭形状的填充色。**OLE\_COLOR**,默认`0`(黑色)。仅在[**FillStyle**](#fillstyle)不为**vbFSTransparent**时使用。 ### FillStyle 封闭形状的填充图案。[**FillStyleConstants**](/official/Reference/VBRUN/Constants/FillStyleConstants)的成员:**vbFSSolid**、**vbFSTransparent**(默认)、**vbHorizontalLine**、**vbVerticalLine**、**vbUpwardDiagonal**、**vbDownwardDiagonal**、**vbCross**或**vbDiagonalCross**。 ### Font 本窗体上[**Print**](#print)语句和其他文本绘制使用的**StdFont**。便利属性**FontName**、**FontSize**、**FontBold**、**FontItalic**、**FontStrikethru**和**FontUnderline**读取或写入此对象的相应成员。 ### FontTransparent 当**True**(默认)时,在窗体上绘制的文本具有透明背景,底层绘图在文本后面可见。当**False**时,文本绘制在以[**BackColor**](#backcolor)填充的不透明矩形上。**Boolean**。 ### ForeColor 由[**Circle**](#circle)、[**Line**](#line)、[**PSet**](#pset)使用的画笔颜色和[**Print**](#print)绘制的文本颜色。**OLE\_COLOR**。 ### hDC 窗体的 Win32 设备上下文句柄,为**LongPtr**。只读。当底层窗口尚未创建时返回`0`。适用于传递给 GDI API 调用。 ### HasDC 窗体是否为其绘图表面保持专用设备上下文(`CS_OWNDC`)。**Boolean**,默认**True**。运行时只读——在设计时设置。 ### Height 窗体的外部高度,默认以缇为单位(或容器**ScaleMode**单位)。**Double**。设置它会调整窗口大小。运行时受[**MinHeight**](#minheight)和[**MaxHeight**](#maxheight)约束(非零时)。 ### HelpContextID 标识应用程序帮助文件中主题的**Long**,当用户在窗体获得焦点时按**F1**时检索。 ### hWnd 窗体的 Win32 窗口句柄,为**LongPtr**。只读。适用于传递给 API 函数。 ### Icon 标题栏、任务栏和 Alt-Tab 中显示的图标。**vbPicTypeIcon**类型的**StdPicture**。赋值非图标图片会将图标清除为默认 Windows 应用程序图标。 ### Image 以**StdPicture**形式返回渲染的绘图表面。只读。当[**AutoRedraw**](#autoredraw)为**True**时最有用——返回的图片是持久的离屏缓冲区。 ### KeyPreview 当**True**时,窗体的[**KeyDown**](#keydown)、[**KeyUp**](#keyup)和[**KeyPress**](#keypress)事件在焦点控件接收相同击键*之前*触发。**Boolean**,默认**False**。适用于应用程序级热键;事件之后仍在焦点控件上触发。 ### Left 窗体外部矩形的水平位置,以缇为单位(或调用代码的**ScaleMode**单位),从屏幕左边缘测量——或对于 MDI 子窗体,从 MDI 父窗体客户区的左边缘测量。**Double**。 ### LinkMode ::: info 保留用于 VB6 DDE 功能兼容性;twinBASIC 中当前未实现。 ::: ### LinkTopic ::: info 保留用于 VB6 DDE 功能兼容性;twinBASIC 中当前未实现。 ::: ### MaxButton 标题栏是否显示最大化按钮。**Boolean**,默认**True**,运行时只读。在设计时设置。 ### MaxHeight 窗体*客户区*的最大高度,以缇为单位。**Double**,默认`0`(无限制)。在交互式调整大小时生效。 ### MaxWidth 窗体*客户区*的最大宽度,以缇为单位。**Double**,默认`0`(无限制)。在交互式调整大小时生效。 ### MDIChild 当**True**时,窗体作为子窗体承载在[**MDIForm**](/official/Reference/VB/MDIForm/)中。**Boolean**,只读——在设计时设置。MDI 子窗体不能以模态方式显示。 ### MinButton 标题栏是否显示最小化按钮。**Boolean**,默认**True**,运行时只读。在设计时设置。 ### MinHeight 窗体*客户区*的最小高度,以缇为单位。**Double**,默认`0`(无限制)。在交互式调整大小时生效。 ### MinWidth 窗体*客户区*的最小宽度,以缇为单位。**Double**,默认`0`(无限制)。在交互式调整大小时生效。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针位于窗体上方(且不在有自身设置的子控件上)时用作鼠标光标的**StdPicture**。 ### MousePointer 当指针位于窗体上方(且不在有自身设置的子控件上)时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Moveable 用户是否可以通过标题栏拖动窗体。**Boolean**,默认**True**。 ### Name 窗体的唯一设计时名称。运行时只读。也是生成的窗体类的类名。 ### NegotiateMenus ::: info 保留用于 VB6 ActiveX 文档菜单协商功能兼容性;twinBASIC 中当前未实现。 ::: ### OLEDropMode 窗体如何响应 OLE 放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**或**vbOLEDropManual**。Form 不支持自动放置模式。 ### Opacity 窗体的不透明度百分比(0--100,默认 100)。超出范围的值在**Initialize**时被钳制。低于 100 的值会使窗体成为分层窗口。 ### Palette ::: info 保留用于 VB6 256 色调色板功能兼容性;twinBASIC 中当前未实现。 ::: ### PaletteMode ::: info 保留用于 VB6 256 色调色板功能兼容性;twinBASIC 中当前未实现。 ::: ### Picture 作为窗体背景绘制的**StdPicture**。在任何绘图原语或子控件之前绘制。赋值**Nothing**移除背景。 ### PictureDpiScaling 当**True**时,[**Picture**](#picture)在绘制前按当前 DPI 因子缩放。**Boolean**,默认**False**。 ### RightToLeft ::: info 保留用于 VB6 兼容性;twinBASIC 中当前未实现。 ::: ### ScaleHeight 逻辑绘图矩形的高度,以[**ScaleMode**](#scalemode)单位表示。**Double**。设置它(或[**ScaleWidth**](#scalewidth)、[**ScaleLeft**](#scaleleft)或[**ScaleTop**](#scaletop))会隐式将**ScaleMode**切换为**vbUser**。 ### ScaleLeft 窗体客户区左边缘的逻辑水平坐标,以[**ScaleMode**](#scalemode)单位表示。**Double**。默认`0`。 ### ScaleMode 由[**CurrentX**](#currentx)、[**CurrentY**](#currenty)、绘图原语、[**TextWidth**](#textwidth)和[**TextHeight**](#textheight)使用的度量单位。[**ScaleModeConstants**](/official/Reference/VBRUN/Constants/ScaleModeConstants)的成员:**vbTwips**(默认)、**vbPoints**、**vbPixels**、**vbCharacters**、**vbInches**、**vbMillimeters**、**vbCentimeters**或**vbUser**(四个**Scale\***属性定义矩形)。 ### ScaleTop 窗体客户区顶边缘的逻辑垂直坐标,以[**ScaleMode**](#scalemode)单位表示。**Double**。默认`0`。 ### ScaleWidth 逻辑绘图矩形的宽度,以[**ScaleMode**](#scalemode)单位表示。**Double**。设置它会隐式将**ScaleMode**切换为**vbUser**。 ### ShowInTaskbar 窗体是否出现在 Windows 任务栏和 Alt-Tab 列表中。**Boolean**,默认**True**。运行时只读——在设计时设置。 ### StartUpPosition 窗体首次显示时如何确定初始位置。[**StartUpPositionConstants**](/official/Reference/VBRUN/Constants/StartUpPositionConstants)的成员:**vbStartUpManual**、**vbStartUpOwner**、**vbStartUpScreen**或**vbStartUpWindowsDefault**(默认)。运行时只读——在设计时设置。 ### TabFocusAutoSelect 当**True**时,此窗体上自身**TabFocusAutoSelect**也为**True**的[**TextBox**](/official/Reference/VB/TextBox/)在通过**TAB**键进入焦点时自动选中其内容。**Boolean**,默认**False**。 ### Tag 应用程序可用于将自定义数据与窗体关联的自由格式**String**。框架不使用此属性。 ### Top 窗体外部矩形的垂直位置,以缇为单位(或调用代码的**ScaleMode**单位),从屏幕顶边缘测量——或对于 MDI 子窗体,从 MDI 父窗体客户区的顶边缘测量。**Double**。 ### TopMost 窗体是否位于置顶层 z 顺序层。**Boolean**,运行时只读。在设计时设置。 ### TransparencyKey 一个**OLE\_COLOR**,设置后在渲染的窗体中变为完全透明——点击穿透到下方内容,相应像素不绘制。默认`-1`禁用效果。 ### Visible 窗体是否可见。**Boolean**,默认**True**。在窗体隐藏时将**Visible**设置为**True**等效于调用[**Show**](#show) **vbModeless**;设置为**False**等效于调用[**Hide**](#hide)。 ### WhatsThisButton 当**True**时,标题栏显示"?"帮助按钮——但仅当[**MinButton**](#minbutton)为**False**、[**MaxButton**](#maxbutton)为**False**、[**ControlBox**](#controlbox)为**True**且[**BorderStyle**](#borderstyle)不是工具窗口样式时。**Boolean**。 ### WhatsThisHelp 当**True**时,[**WhatsThisMode**](#whatsthismode)和标题栏帮助按钮进入 Windows 的"这是什么?"光标模式。**Boolean**,默认**False**。 ### Width 窗体的外部宽度,默认以缇为单位(或容器**ScaleMode**单位)。**Double**。设置它会调整窗口大小。运行时受[**MinWidth**](#minwidth)和[**MaxWidth**](#maxwidth)约束(非零时)。 ### WindowState 窗口的正常/最小化/最大化状态。[**FormWindowStateConstants**](/official/Reference/VBRUN/Constants/FormWindowStateConstants)的成员:**vbNormal**(0,默认)、**vbMinimized**(1)或**vbMaximized**(2)。在运行时设置会立即更新窗口位置(如果窗体可见)。 ## 方法 ### Circle 使用[**ForeColor**](#forecolor)绘制轮廓,使用[**FillColor**](#fillcolor)/[**FillStyle**](#fillstyle)填充内部,在窗体上绘制圆、椭圆或弧。 语法:*object*.**Circle** \[ **Step** ] ( *X*, *Y* ), *Radius* \[, \[ *Color* ] \[, \[ *Start* ] \[, \[ *End* ] \[, *Aspect* ] ] ] ] *X*, *Y* : *必需* 圆心,以[**ScaleMode**](#scalemode)单位表示。**Step**使圆心相对于([**CurrentX**](#currentx),[**CurrentY**](#currenty))。 *Radius* : *必需* 以**ScaleMode**单位给出半径的**Single**。 *Color* : *可选* 轮廓的**OLE\_COLOR**;默认为[**ForeColor**](#forecolor)。 *Start*、*End* : *可选* 以弧度为单位的角,用于绘制弧而非完整圆。 *Aspect* : *可选* 垂直与水平半径的比率。`1.0`为圆形;偏离`1.0`的值产生椭圆。 ### Cls 清除由[**Circle**](#circle)、[**Line**](#line)、[**PSet**](#pset)、[**PaintPicture**](#paintpicture)和[**Print**](#print)执行的任何绘图,以[**BackColor**](#backcolor)重绘,并将[**CurrentX**](#currentx) / [**CurrentY**](#currenty)重置为`0`。不影响[**Picture**](#picture)背景或子控件。 语法:*object*.**Cls** ### Close 启动窗体的卸载序列——[**QueryUnload**](#queryunload),然后[**Unload**](#unload),然后[**Terminate**](#terminate)。前两个事件中的任一都可以通过将*Cancel*设置为非零来取消关闭。等效于语言语句`Unload Me`。 语法:*object*.**Close** ### Hide 隐藏窗体而不卸载它。类实例及其控件被保留;调用[**Show**](#show)(或赋值[**Visible**](#visible) = **True**)可再次显示。等效于赋值**Visible** = **False**。 语法:*object*.**Hide** ### Line 使用[**ForeColor**](#forecolor)(或显式颜色)和[**DrawWidth**](#drawwidth)/[**DrawStyle**](#drawstyle)在窗体上绘制直线或矩形。 语法:*object*.**Line** \[ \[ **Step** ] ( *X1*, *Y1* ) ] -\[ **Step** ] ( *X2*, *Y2* ) \[, \[ *Color* ] \[, **B** \[ **F** ] ] ] *X1*, *Y1* : *可选* 起点,以[**ScaleMode**](#scalemode)单位表示。**Step**使点相对于([**CurrentX**](#currentx),[**CurrentY**](#currenty))。省略时,从当前画笔位置开始绘制。 *X2*, *Y2* : *必需* 终点,以**ScaleMode**单位表示。**Step**使点相对于(*X1*,*Y1*)。 *Color* : *可选* 线条的**OLE\_COLOR**;默认为[**ForeColor**](#forecolor)。 **B** : *可选* 绘制以(*X1*,*Y1*)和(*X2*,*Y2*)为对角的矩形而非线条。 **F** : *可选* 与**B**组合时,使用[**ForeColor**](#forecolor)而非[**FillColor**](#fillcolor)/[**FillStyle**](#fillstyle)填充矩形。 ### Move 在单次调用中重新定位并可选地调整窗体大小。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从窗体启动 OLE 拖动操作,触发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### PaintPicture 将**StdPicture**绘制到窗体上,支持可选缩放和光栅操作。 语法:*object*.**PaintPicture** *Picture*, *X1*, *Y1* \[, *Width1* \[, *Height1* \[, *X2* \[, *Y2* \[, *Width2* \[, *Height2* \[, *Opcode* \[, *StretchQuality* ] ] ] ] ] ] ] ] *Picture* : *必需* 要绘制的**StdPicture**。 *X1*, *Y1* : *必需* 目标左上角,以[**ScaleMode**](#scalemode)单位表示。 *Width1*, *Height1* : *可选* 目标尺寸;默认为图片的自然尺寸。 *X2*, *Y2*, *Width2*, *Height2* : *可选* 图片内的源矩形;默认为整个图片。 *Opcode* : *可选* 光栅操作代码([**RasterOpConstants**](/official/Reference/VBRUN/Constants/RasterOpConstants)的成员)。默认为**vbSrcCopy**。 *StretchQuality* : *可选* 缩放时的插值方法。默认为正常质量。 ### PopUpMenu 将[**Menu**](/official/Reference/VB/Menu/)作为上下文菜单弹出显示在指定位置。 语法:*object*.**PopUpMenu** *Menu* \[, *Flags* \[, *X* \[, *Y* \[, *DefaultMenu* ] ] ] ] *Menu* : *必需* 要显示的**Menu**控件。菜单必须已存在于窗体上(或其 MDI 父窗体上)。 *Flags* : *可选* [**MenuControlConstants**](/official/Reference/VBRUN/Constants/MenuControlConstants)的组合,控制对齐方式和哪些鼠标按钮触发菜单项。 *X*, *Y* : *可选* 锚定菜单的屏幕相对位置,以[**ScaleMode**](#scalemode)单位表示。默认为当前鼠标位置。 *DefaultMenu* : *可选* 以粗体渲染为默认操作的**Menu**子项。 ### Point ::: info 保留用于 VB6 兼容性;twinBASIC 中当前未实现。在 VB6 中此方法返回绘图表面单个像素的**OLE\_COLOR**。 ::: 语法:*object*.**Point**( *X*, *Y* ) ### Print 使用[**Font**](#font)将文本写入窗体的绘图表面,从[**CurrentX**](#currentx) / [**CurrentY**](#currenty)开始并随着输出推进。通过 VB6 **Print**语句分派,因此多个表达式可以用`;`(无间距)或`,`(跳到下一个打印区)分隔。\*\*Spc(n)\*\*插入*n*个空格,**Tab(n)**移到打印列*n*。输出遵循[**Font**](#font)、[**ForeColor**](#forecolor)和[**FontTransparent**](#fonttransparent),当[**AutoRedraw**](#autoredraw)为**True**时,记录到持久离屏位图中以在失效时存活。 语法:*object*.**Print** \[ *expressionlist* ] \[ **;** | **,** ] 末尾的`;`或`,`抑制换行,使下一个**Print**调用继续在同一行;没有末尾分隔符时,画笔推进到下一行的开头。 ```vb Me.CurrentX = 10 : Me.CurrentY = 10 Me.Print "Name: "; sName, "Age: "; nAge ' 两个字段,制表符分隔 Me.Print ' 空行 Me.Print "Total: " & Format$(Total, "0.00") ``` ### PrintForm 通过[**Printer**](/official/Reference/VB/Printer/)对象将窗体当前视觉状态的屏幕截图发送到默认打印机。 语法:*object*.**PrintForm** \[ *ImplicitEndDoc* \[, *OutputAtCurrentPosition* ] ] *ImplicitEndDoc* : *可选* 当**True**(默认)时,打印作业在返回前完成;当**False**时,窗体作为页面发送但打印作业保持打开以供进一步输出。 *OutputAtCurrentPosition* : *可选* 当**True**时,窗体在打印机当前画笔位置渲染而非页面原点。**Boolean**,默认**False**。 ### PSet 将窗体上的单个像素设置为指定颜色。 语法:*object*.**PSet** \[ **Step** ] ( *X*, *Y* ) \[, *Color* ] *X*, *Y* : *必需* 像素位置,以[**ScaleMode**](#scalemode)单位表示。**Step**使位置相对于([**CurrentX**](#currentx),[**CurrentY**](#currenty))。 *Color* : *可选* **OLE\_COLOR**;默认为[**ForeColor**](#forecolor)。 ### Refresh 强制窗体立即重绘,当[**AutoRedraw**](#autoredraw)为**False**时触发[**Paint**](#paint)。 语法:*object*.**Refresh** ### Scale 通过分配[**ScaleLeft**](#scaleleft)、[**ScaleTop**](#scaletop)、[**ScaleWidth**](#scalewidth)和[**ScaleHeight**](#scaleheight)在单次调用中设置窗体的逻辑绘图矩形。将[**ScaleMode**](#scalemode)切换为**vbUser**。不带参数调用**Scale**将矩形重置为与客户区以像素 1:1 映射。 语法:*object*.**Scale** \[ ( *X1*, *Y1* )-( *X2*, *Y2* ) ] *X1*, *Y1* : *可选* 左上角的逻辑坐标。 *X2*, *Y2* : *可选* 右下角的逻辑坐标。 ### ScaleX 将水平长度从一个[**ScaleMode**](#scalemode)转换为另一个。 语法:*object*.**ScaleX**( *Width* \[, *FromScale* \[, *ToScale* ] ] ) *Width* : *必需* 给出源长度的**Single**。 *FromScale*、*ToScale* : *可选* [**ScaleModeConstants**](/official/Reference/VBRUN/Constants/ScaleModeConstants)的成员。省略时默认为当前**ScaleMode**。 ### ScaleY 将垂直长度从一个[**ScaleMode**](#scalemode)转换为另一个。 语法:*object*.**ScaleY**( *Height* \[, *FromScale* \[, *ToScale* ] ] ) *Height* : *必需* 给出源长度的**Single**。 *FromScale*、*ToScale* : *可选* [**ScaleModeConstants**](/official/Reference/VBRUN/Constants/ScaleModeConstants)的成员。省略时默认为当前**ScaleMode**。 ### SetFocus 激活窗体并将输入焦点赋予[**TabIndex**](/official/Reference/VB/TextBox/#tabindex)为`0`的控件(或此窗体上最后持有焦点的控件)。 语法:*object*.**SetFocus** ### Show 使窗体可见。在首次调用时触发[**Load**](#load)。 语法:*object*.**Show** \[ *Modal* \[, *OwnerForm* ] ] *Modal* : *可选* [**FormShowConstants**](/official/Reference/VBRUN/Constants/FormShowConstants)的成员:**vbModeless**(0,默认——调用立即返回)或**vbModal**(1——调用阻塞直到窗体关闭且用户无法与其他窗体交互)。 *OwnerForm* : *可选* 对于模态显示,在此窗体打开期间被禁用的窗体;默认为当前活动窗体。 ### TextHeight 返回给定字符串使用窗体当前[**Font**](#font)绘制时将占用的宽度,以[**ScaleMode**](#scalemode)单位表示。 语法:*object*.**TextHeight**( *Str* ) *Str* : *必需* 要测量的**String**。 ### TextWidth 返回给定字符串使用窗体当前[**Font**](#font)绘制时将占用的宽度,以[**ScaleMode**](#scalemode)单位表示。 语法:*object*.**TextWidth**( *Str* ) *Str* : *必需* 要测量的**String**。 ### ValidateControls 触发此窗体上当前活动控件的**Validate**事件。如果处理程序将*Cancel*设置为**True**,**ValidateControls**引发运行时错误 380(*Invalid property value*);调用者可以用`On Error`包裹以检测失败的验证。适用于在保存或关闭之前检查待处理的输入。 语法:*object*.**ValidateControls** ### WhatsThisMode 进入 Windows 的"这是什么?"光标模式——下次点击控件会触发该控件的帮助而非激活它。[**WhatsThisHelp**](#whatsthishelp)必须为**True**。 语法:*object*.**WhatsThisMode** ### ZOrder 将窗体置于顶级 z 顺序的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront**(0,默认)或**vbSendToBack**(1)。 ## 事件 ### Activate 当窗体成为应用程序中的活动窗口时触发——无论是[**Load**](#load)后首次显示,还是从另一个窗口重新获得激活时。 语法:*object*\_**Activate**( ) ### Click 当用户单击窗体客户区(即不在任何子控件上)时触发。 语法:*object*\_**Click**( ) ### DblClick 当用户双击窗体客户区时触发。 语法:*object*\_**DblClick**( ) ### Deactivate 当应用程序中的另一个窗口从此窗体夺取激活时触发。当激活移到不同应用程序的窗口时不触发。 语法:*object*\_**Deactivate**( ) ### DPIChange 当窗体移动到具有不同 DPI 缩放的显示器时触发,*但仅当*应用程序是每显示器 DPI 感知的(`PROCESS_PER_MONITOR_DPI_AWARE`)。事件的*NewDPI*参数给出新的有效 DPI;子控件自动重新缩放。twinBASIC 新增。 语法:*object*\_**DPIChange**( *NewDPI* **As Long** ) ### DragDrop 当手动拖动操作在目标控件上结束时在该控件上触发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 当手动拖动操作进行中时在光标下方的控件上触发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus 当窗体获得输入焦点且没有启用的子控件可以代替它获得焦点时触发。没有可聚焦子控件的窗体直接获得焦点。 语法:*object*\_**GotFocus**( ) ### Initialize 触发一次,在底层窗口创建之前和窗体的任何子控件存在之前。适用于设置窗体级字段的初始值。不能从此事件引用窗体的控件。 语法:*object*\_**Initialize**( ) ### KeyDown 当用户按下任何键时触发。默认在焦点控件上触发;当[**KeyPreview**](#keypreview)为**True**时,先在窗体上触发。 语法:*object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress 当用户键入产生 ANSI 击键的字符时触发。默认在焦点控件上触发;当[**KeyPreview**](#keypreview)为**True**时,先在窗体上触发。 语法:*object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp 当用户释放键时触发。默认在焦点控件上触发;当[**KeyPreview**](#keypreview)为**True**时,先在窗体上触发。 语法:*object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LinkClose ::: info 保留用于 VB6 DDE 功能兼容性;twinBASIC 中当前不触发。 ::: ### LinkError ::: info 保留用于 VB6 DDE 功能兼容性;twinBASIC 中当前不触发。 ::: ### LinkExecute ::: info 保留用于 VB6 DDE 功能兼容性;twinBASIC 中当前不触发。 ::: ### LinkOpen ::: info 保留用于 VB6 DDE 功能兼容性;twinBASIC 中当前不触发。 ::: ### Load 在窗体的窗口和所有控件创建之后,窗体首次显示在屏幕之前触发。经典的初始化位置——填充控件、附加数据源以及执行需要控件存在的任何初始化。**默认事件。** 语法:*object*\_**Load**( ) ### LostFocus 当窗体失去输入焦点时触发。 语法:*object*\_**LostFocus**( ) ### MouseDown 当用户在窗体客户区上方按下任何鼠标按钮时触发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 当光标在窗体客户区上方移动时触发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 当用户在窗体客户区上方释放鼠标按钮时触发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseWheel 当鼠标滚轮在窗体上方转动时触发。twinBASIC 新增。 语法:*object*\_**MouseWheel**( *Delta* **As Integer**, *Horizontal* **As Boolean** ) ### OLECompleteDrag 当 OLE 拖动操作完成时在源控件上触发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 当用户将数据放置在目标控件上时触发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver 当 OLE 拖动经过目标控件时在该控件上触发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 在拖动期间在源控件上触发,以便应用程序可以调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的数据格式的数据时在源控件上触发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag 在 OLE 拖动开始时在源控件上触发,以便应用程序可以填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Paint 当窗体的失效部分需要重绘时触发。当[**AutoRedraw**](#autoredraw)为**True**时被抑制——窗体的持久离屏缓冲区被位块传送到屏幕。 语法:*object*\_**Paint**( ) ### QueryUnload 在窗体卸载之前触发,给应用程序确认或取消关闭的机会。将*Cancel*设置为非零可保持窗体打开。始终在[**Unload**](#unload)之前触发。 语法:*object*\_**QueryUnload**( *Cancel* **As Integer**, *UnloadMode* **As Integer** ) *Cancel* : 设置为非零(任何非零值,约定为**1**)以取消关闭。 *UnloadMode* : [**QueryUnloadConstants**](/official/Reference/VBRUN/Constants/QueryUnloadConstants)的成员,标识触发关闭的原因——关闭按钮、代码、Windows 关机、MDI 父窗体或所有者窗体。 ### Resize 当窗体调整大小时触发——由用户、代码、操作系统在[**WindowState**](#windowstate)更改后或首次显示期间的初始布局触发。 语法:*object*\_**Resize**( ) ### Terminate 在窗体的窗口已销毁且类实例即将释放后触发。此时控件不再可访问。 语法:*object*\_**Terminate**( ) ### Unload 在[**QueryUnload**](#queryunload)通过之后和窗体窗口销毁之前触发。将*Cancel*设置为非零可保持窗体打开并阻止卸载。 语法:*object*\_**Unload**( *Cancel* **As Integer** ) *Cancel* : 设置为非零(任何非零值,约定为**1**)以取消卸载。 --- --- url: /en/official/Reference/VBRUN/Constants/FormArrangeConstants.md --- # FormArrangeConstants Arrangement modes for the **Arrange** method of an MDI parent form, controlling how its child windows are laid out. | Constant | Value | Description | |----------|-------|-------------| | **vbCascade** | 0 | Cascade the open child windows. | | **vbTileHorizontal** | 1 | Tile the child windows horizontally. | | **vbTileVertical** | 2 | Tile the child windows vertically. | | **vbArrangeIcons** | 3 | Arrange the icons of the minimised child windows along the bottom of the MDI parent. | --- --- url: /zh/official/Reference/VBRUN/Constants/FormArrangeConstants.md --- # FormArrangeConstants MDI父窗体**Arrange**方法的排列模式,控制其子窗口的布局方式。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbCascade** | 0 | 层叠排列打开的子窗口。 | | **vbTileHorizontal** | 1 | 水平平铺子窗口。 | | **vbTileVertical** | 2 | 垂直平铺子窗口。 | | **vbArrangeIcons** | 3 | 沿MDI父窗口底部排列最小化子窗口的图标。 | --- --- url: /en/official/IDE/Menu/Format.md --- # Format Menu ![Format Menu](/assets/Menu_Format.C7B-ICY0.png "Format Menu") ![Format Menu](/assets/Menu_Format_1.BBLE3blt.png "Format Menu") * Align * Make Same Size *** * Horizontal Spacing * Vertical Spacing *** * Center In Container (Horizontally) * Center In Container (Vertically) *** * Bring To Front * Send To Back *** * Lock Controls ![Format Align Menu](/assets/Menu_Format_Align.BHoU0xe7.png "Format Align Menu") * Left ALT + ARROWLEFT * Center (Horizontal) * Right ALT + ARROWRIGHT *** * Top ALT + ARROWUP * Center (Vertical) * Bottom ALT + ARROWDOWN *** * To Grid ![Format Make Same Size Menu](/assets/Menu_Format_MakeSameSize.BNcLwAv6.png "Format Make Same Size Menu") * Width (Widest) CTRL + SHIFT + ARROWRIGHT * Width (Narrowest) CTRL + SHIFT + ARROWLEFT * Height (Tallest) CTRL + SHIFT + ARROWDOWN * Height (Shortest) CTRL + SHIFT + ARROWUP ![Format Horizontal Spacing Menu](/assets/Menu_Format_HorizontalSpacing.D2rxkKWw.png "Format Horizontal Spacing Menu") * Make Equal * Increase * Decrease * Remove ![Format Vertical Spacing Menu](/assets/Menu_Format_VerticalSpacing.C9Uk5-Qe.png "Format Vertical Spacing Menu") * Make Equal * Increase * Decrease * Remove --- --- url: /en/official/Reference/VBA/Strings/Format.md --- # Format Returns a **String** containing an expression formatted according to instructions contained in a format expression. Syntax: **Format$(** *expression* \[ **,** *format* \[ **,** *firstDayOfWeek* \[ **,** *firstWeekOfYear* ] ] ] **)**, **Format(** *expression* \[ **,** *format* \[ **,** *firstDayOfWeek* \[ **,** *firstWeekOfYear* ] ] ] **)** *expression* : *required* Any valid expression. *format* : *optional* A valid named or user-defined format expression. *firstDayOfWeek* : *optional* A constant that specifies the first day of the week. *firstWeekOfYear* : *optional* A constant that specifies the first week of the year. The `$`-suffixed form returns a **String**; the unsuffixed form returns a **Variant** (**String**). The *firstDayOfWeek* argument has these settings. | Constant | Value | Description | |----------------|-------|-----------------------| | **vbUseSystem**| 0 | Use NLS API setting. | | **vbSunday** | 1 | Sunday (default) | | **vbMonday** | 2 | Monday | | **vbTuesday** | 3 | Tuesday | | **vbWednesday**| 4 | Wednesday | | **vbThursday** | 5 | Thursday | | **vbFriday** | 6 | Friday | | **vbSaturday** | 7 | Saturday | The *firstWeekOfYear* argument has these settings. | Constant | Value | Description | |---------------------|-------|------------------------------------------------------------------------| | **vbUseSystem** | 0 | Use NLS API setting. | | **vbFirstJan1** | 1 | Start with week in which January 1 occurs (default). | | **vbFirstFourDays** | 2 | Start with the first week that has at least four days in the year. | | **vbFirstFullWeek** | 3 | Start with the first full week of the year. | | To format | Do this | |------------------------------|-------------------------------------------------------------------------------| | Numbers | Use predefined named numeric formats or create user-defined numeric formats. | | Dates and times | Use predefined named date/time formats or create user-defined date/time formats. | | Date and time serial numbers | Use date and time formats or numeric formats. | | Strings | Create user-defined string formats. | **Format** truncates *format* to 257 characters. When formatting a number without specifying *format*, **Format** provides functionality similar to the **Str** function, although it is internationally aware. However, positive numbers formatted as strings using **Format** don't include a leading space reserved for the sign of the value; those converted using **Str** retain the leading space. When formatting a non-localized numeric string, use a user-defined numeric format to ensure the desired appearance. ::: info If the [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property setting is `Gregorian` and *format* specifies date formatting, the supplied *expression* must be Gregorian. If the **Calendar** property setting is `Hijri`, the supplied *expression* must be Hijri. ::: If the calendar is Gregorian, the meaning of *format* expression symbols is unchanged. If the calendar is Hijri, all date format symbols (for example, *dddd*, *mmmm*, *yyyy*) have the same meaning but apply to the Hijri calendar. Format symbols remain in English; symbols that result in text display (for example, AM and PM) display the string (English or Arabic) associated with that symbol. The range of certain symbols changes when the calendar is Hijri. ### Date symbols | Symbol | Range | |----------|------------------------------------------------------------------------------------| | *d* | 1-31 (Day of month, with no leading zero) | | *dd* | 01-31 (Day of month, with a leading zero) | | *w* | 1-7 (Day of week, starting with Sunday = 1) | | *ww* | 1-53 (Week of year, with no leading zero; Week 1 starts on Jan 1) | | *m* | 1-12 (Month of year, with no leading zero, starting with January = 1) | | *mm* | 01-12 (Month of year, with a leading zero, starting with January = 01) | | *mmm* | Displays abbreviated month names (Hijri month names have no abbreviations) | | *mmmm* | Displays full month names | | *y* | 1-366 (Day of year) | | *yy* | 00-99 (Last two digits of year) | | *yyyy* | 100-9999 (Three- or Four-digit year) | ### Time symbols | Symbol | Range | |--------|--------------------------------------------------------------------------------------------------------------| | *h* | 0-23 (1-12 with "AM" or "PM" appended) (Hour of day, with no leading zero) | | *hh* | 00-23 (01-12 with "AM" or "PM" appended) (Hour of day, with a leading zero) | | *n* | 0-59 (Minute of hour, with no leading zero) | | *nn* | 00-59 (Minute of hour, with a leading zero) | | *m* | 0-59 (Minute of hour, with no leading zero). Only if preceded by *h* or *hh* | | *mm* | 00-59 (Minute of hour, with a leading zero). Only if preceded by *h* or *hh* | | *s* | 0-59 (Second of minute, with no leading zero) | | *ss* | 00-59 (Second of minute, with a leading zero) | ### Example This example shows various uses of the **Format** function to format values using both named formats and user-defined formats. For the date separator (`/`), time separator (`:`), and AM/PM literal, the actual formatted output displayed by the system depends on the locale settings on which the code is running. When times and dates are displayed in the development environment, the short time format and short date format of the code locale are used. When displayed by running code, the short time format and short date format of the system locale are used, which may differ from the code locale. For this example, English/U.S. is assumed. `MyTime` and `MyDate` are displayed in the development environment using the current system short time setting and short date setting. ```vb Dim MyTime, MyDate, MyStr MyTime = #17:04:23# MyDate = #January 27, 1993# ' Returns current system time in the system-defined long time format. MyStr = Format(Time, "Long Time") ' Returns current system date in the system-defined long date format. MyStr = Format(Date, "Long Date") MyStr = Format(MyTime, "h:m:s") ' Returns "17:4:23". MyStr = Format(MyTime, "hh:mm:ss am/pm") ' Returns "05:04:23 pm". MyStr = Format(MyTime, "hh:mm:ss AM/PM") ' Returns "05:04:23 PM". MyStr = Format(MyDate, "dddd, mmm d yyyy") ' Returns "Wednesday, Jan 27 1993". ' If format is not supplied, a string is returned. MyStr = Format(23) ' Returns "23". ' User-defined formats. MyStr = Format(5459.4, "##,##0.00") ' Returns "5,459.40". MyStr = Format(334.9, "###0.00") ' Returns "334.90". MyStr = Format(5, "0.00%") ' Returns "500.00%". MyStr = Format("HELLO", "<") ' Returns "hello". MyStr = Format("This is it", ">") ' Returns "THIS IS IT". ``` ### Different formats for different numeric values A user-defined format expression for numbers can have from one to four sections separated by semicolons. If the *format* argument contains one of the named numeric formats, only one section is allowed. | Sections | The result is | |------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | One section only | The format expression applies to all values. | | Two sections | The first section applies to positive values and zeros, the second to negative values. | | Three sections | The first section applies to positive values, the second to negative values, and the third to zeros. | | Four sections | The first section applies to positive values, the second to negative values, the third to zeros, and the fourth to **Null** values. | ```vb "$#,##0;($#,##0)" ``` When semicolons are included with nothing between them, the missing section is printed using the format of the positive value. For example, the following format displays positive and negative values using the format in the first section and displays "Zero" if the value is zero. ```vb "$#,##0;;\Z\e\r\o" ``` ### Different formats for different string values A format expression for strings can have one section or two sections separated by a semicolon (`;`). | Sections | The result is | |------------------|--------------------------------------------------------------------------------------------| | One section only | The format applies to all string data. | | Two sections | The first section applies to string data, the second to **Null** values and zero-length strings (`""`). | ### Named date/time formats The following table identifies the predefined date and time format names. | Format name | Description | |-------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **General Date** | Display a date and/or time, for example, 4/3/93 05:34 PM. If there is no fractional part, display only a date, for example, 4/3/93. If there is no integer part, display time only, for example, 05:34 PM. Date display is determined by the system settings. | | **Long Date** | Display a date according to the system long date format. | | **Medium Date** | Display a date using the medium date format appropriate for the language version of the host application. | | **Short Date** | Display a date using the system short date format. | | **Long Time** | Display a time using the system long time format; includes hours, minutes, seconds. | | **Medium Time** | Display time in 12-hour format using hours and minutes and the AM/PM designator. | | **Short Time** | Display a time using the 24-hour format, for example, 17:45. | ### Named numeric formats The following table identifies the predefined numeric format names. | Format name | Description | |--------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **General Number** | Display number with no thousand separator. | | **Currency** | Display number with thousand separator, if appropriate; display two digits to the right of the decimal separator. Output is based on system locale settings. | | **Fixed** | Display at least one digit to the left and two digits to the right of the decimal separator. | | **Standard** | Display number with thousand separator, at least one digit to the left and two digits to the right of the decimal separator. | | **Percent** | Display number multiplied by 100 with a percent sign (`%`) appended to the right; always display two digits to the right of the decimal separator. | | **Scientific** | Use standard scientific notation. | | **Yes/No** | Display No if number is 0; otherwise, display Yes. | | **True/False** | Display **False** if number is 0; otherwise, display **True**. | | **On/Off** | Display Off if number is 0; otherwise, display On. | ### User-defined string formats Use any of the following characters to create a format expression for strings. | Character | Description | |-----------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `@` | Character placeholder. Display a character or a space. If the string has a character in the position where the at symbol (`@`) appears in the format string, display it; otherwise, display a space in that position. Placeholders are filled from right to left unless there is an exclamation point character (`!`) in the format string. | | `&` | Character placeholder. Display a character or nothing. If the string has a character in the position where the ampersand (`&`) appears, display it; otherwise, display nothing. Placeholders are filled from right to left unless there is an exclamation point character (`!`) in the format string. | | `<` | Force lowercase. Display all characters in lowercase format. | | `>` | Force uppercase. Display all characters in uppercase format. | | `!` | Force left to right fill of placeholders. The default is to fill placeholders from right to left. | ### User-defined date/time formats The following table identifies the characters available for creating user-defined date/time formats. | Character | Description | |--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `:` | Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by the system settings. | | `/` | Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by the system settings. | | `c` | Display the date as `ddddd` and display the time as `ttttt`, in that order. Display only date information if there is no fractional part to the date serial number; display only time information if there is no integer portion. | | `d` | Display the day as a number without a leading zero (1--31). | | `dd` | Display the day as a number with a leading zero (01--31). | | `ddd` | Display the day as an abbreviation (Sun--Sat). Localized. | | `dddd` | Display the day as a full name (Sunday--Saturday). Localized. | | `ddddd` | Display the date as a complete date (including day, month, and year), formatted according to the system short date format setting. The default short date format is `m/d/yy`. | | `dddddd` | Display a date serial number as a complete date (including day, month, and year) formatted according to the long date setting recognized by the system. The default long date format is `mmmm dd, yyyy`. | | `w` | Display the day of the week as a number (1 for Sunday through 7 for Saturday). | | `ww` | Display the week of the year as a number (1--54). | | `m` | Display the month as a number without a leading zero (1--12). If `m` immediately follows `h` or `hh`, the minute rather than the month is displayed. | | `mm` | Display the month as a number with a leading zero (01--12). If `m` immediately follows `h` or `hh`, the minute rather than the month is displayed. | | `mmm` | Display the month as an abbreviation (Jan--Dec). Localized. | | `mmmm` | Display the month as a full month name (January--December). Localized. | | `q` | Display the quarter of the year as a number (1--4). | | `y` | Display the day of the year as a number (1--366). | | `yy` | Display the year as a 2-digit number (00--99). | | `yyyy` | Display the year as a 4-digit number (100--9999). | | `h` | Display the hour as a number without a leading zero (0--23). | | `hh` | Display the hour as a number with a leading zero (00--23). | | `n` | Display the minute as a number without a leading zero (0--59). | | `nn` | Display the minute as a number with a leading zero (00--59). | | `s` | Display the second as a number without a leading zero (0--59). | | `ss` | Display the second as a number with a leading zero (00--59). | | `ttttt` | Display a time as a complete time (including hour, minute, and second), formatted using the time separator defined by the time format recognized by the system. A leading zero is displayed if the leading zero option is selected and the time is before 10:00 A.M. or P.M. The default time format is `h:mm:ss`. | | `AM/PM` | Use the 12-hour clock and display an uppercase AM with any hour before noon; display an uppercase PM with any hour between noon and 11:59 P.M. | | `am/pm` | Use the 12-hour clock and display a lowercase AM with any hour before noon; display a lowercase PM with any hour between noon and 11:59 P.M. | | `A/P` | Use the 12-hour clock and display an uppercase A with any hour before noon; display an uppercase P with any hour between noon and 11:59 P.M. | | `a/p` | Use the 12-hour clock and display a lowercase A with any hour before noon; display a lowercase P with any hour between noon and 11:59 P.M. | | `AMPM` | Use the 12-hour clock and display the AM string literal as defined by the system with any hour before noon; display the PM string literal as defined by the system with any hour between noon and 11:59 P.M. | ### User-defined numeric formats The following table identifies the characters available for creating user-defined number formats. | Character | Description | |--------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | None | Display the number with no formatting. | | `0` | Digit placeholder. Display a digit or a zero. If the expression has a digit in the position where the `0` appears in the format string, display it; otherwise, display a zero in that position. If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, round the number to as many decimal places as there are zeros. If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, display the extra digits without modification. | | `#` | Digit placeholder. Display a digit or nothing. If the expression has a digit in the position where the `#` appears in the format string, display it; otherwise, display nothing in that position. This symbol works like the `0` digit placeholder, except that leading and trailing zeros aren't displayed if the number has the same or fewer digits than there are `#` characters on either side of the decimal separator in the format expression. | | `.` | Decimal placeholder. The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator. If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator. To display a leading zero with fractional numbers, use 0 as the first digit placeholder to the left of the decimal separator. The actual character used as a decimal placeholder in the formatted output depends on the Number Format recognized by the system. | | `%` | Percentage placeholder. The expression is multiplied by 100. The percent character (`%`) is inserted in the position where it appears in the format string. | | `,` | Thousand separator. Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (`0` or `#`). Two adjacent thousand separators or a thousand separator immediately to the left of the decimal separator means "scale the number by dividing it by 1000, rounding as needed." | | `:` | Time separator. See above. | | `/` | Date separator. See above. | | `E- E+ e- e+` | Scientific format. If the format expression contains at least one digit placeholder (`0` or `#`) to the right of `E-`, `E+`, `e-`, or `e+`, the number is displayed in scientific format and `E` or `e` is inserted between the number and its exponent. Use `E-` or `e-` to place a minus sign next to negative exponents. Use `E+` or `e+` to place a minus sign next to negative exponents and a plus sign next to positive exponents. | | `- + $ ( )` | Display a literal character. To display a character other than one of those listed, precede it with a backslash (`\`) or enclose it in double quotation marks (`" "`). | | `\` | Display the next character in the format string. Using a backslash is the same as enclosing the next character in double quotation marks. To display a backslash, use two backslashes (`\\`). | | `"ABC"` | Display the string inside the double quotation marks (`" "`). To include a string in *format* from within code, use `Chr(34)` to enclose the text (34 is the character code for a quotation mark `"`). | ### See Also * [FormatCurrency](/en/official/Reference/VBA/Strings/FormatCurrency), [FormatDateTime](/en/official/Reference/VBA/Strings/FormatDateTime), [FormatNumber](/en/official/Reference/VBA/Strings/FormatNumber), [FormatPercent](/en/official/Reference/VBA/Strings/FormatPercent) functions --- --- url: /zh/official/Reference/VBA/Strings/Format.md --- # Format 返回一个**String**,包含根据格式表达式中的指令格式化的表达式。 语法:**Format$(** *expression* \[ **,** *format* \[ **,** *firstDayOfWeek* \[ **,** *firstWeekOfYear* ] ] ] **)**, **Format(** *expression* \[ **,** *format* \[ **,** *firstDayOfWeek* \[ **,** *firstWeekOfYear* ] ] ] **)** *expression* : *必需* 任意有效的表达式。 *format* : *可选* 有效的命名或用户定义的格式表达式。 *firstDayOfWeek* : *可选* 指定一周第一天的常量。 *firstWeekOfYear* : *可选* 指定一年第一周的常量。 带`$`后缀的形式返回**String**;不带后缀的形式返回**Variant**(**String**)。 *firstDayOfWeek*参数的设置如下: | 常量 | 值 | 描述 | |------------------|-----|------------------------| | **vbUseSystem** | 0 | 使用NLS API设置。 | | **vbSunday** | 1 | 星期日(默认) | | **vbMonday** | 2 | 星期一 | | **vbTuesday** | 3 | 星期二 | | **vbWednesday** | 4 | 星期三 | | **vbThursday** | 5 | 星期四 | | **vbFriday** | 6 | 星期五 | | **vbSaturday** | 7 | 星期六 | *firstWeekOfYear*参数的设置如下: | 常量 | 值 | 描述 | |---------------------|-----|------------------------------------------------------------| | **vbUseSystem** | 0 | 使用NLS API设置。 | | **vbFirstJan1** | 1 | 从包含1月1日的那一周开始(默认)。 | | **vbFirstFourDays** | 2 | 从一年中至少有四天的第一周开始。 | | **vbFirstFullWeek** | 3 | 从一年的第一个完整周开始。 | | 格式目标 | 操作 | |--------------------|------------------------------------------------------------------------| | 数字 | 使用预定义的命名数字格式或创建用户定义的数字格式。 | | 日期和时间 | 使用预定义的命名日期/时间格式或创建用户定义的日期/时间格式。 | | 日期和时间序列数 | 使用日期和时间格式或数字格式。 | | 字符串 | 创建用户定义的字符串格式。 | **Format**将*format*截断为257个字符。 在不指定*format*的情况下格式化数字时,**Format**提供与**Str**函数类似的功能,但具有国际识别能力。但是,使用**Format**将正数格式化为字符串时不包含为数值符号保留的前导空格;而使用**Str**转换的则保留前导空格。 在格式化非本地化的数字字符串时,请使用用户定义的数字格式以确保所需的外观。 ::: info 如果[**Calendar**](/official/Reference/VBA/DateTime/Calendar)属性设置为`Gregorian`且*format*指定了日期格式,则提供的*expression*必须是公历。如果**Calendar**属性设置为`Hijri`,则提供的*expression*必须是回历。 ::: 如果日历为公历,*format*表达式符号的含义不变。如果日历为回历,所有日期格式符号(例如*dddd*、*mmmm*、*yyyy*)具有相同含义,但适用于回历。格式符号保持英文;产生文本显示的符号(例如AM和PM)显示与该符号关联的字符串(英文或阿拉伯文)。当日历为回历时,某些符号的范围会发生变化。 ### 日期符号 | 符号 | 范围 | |----------|----------------------------------------------------------------| | *d* | 1-31(月中的日,无前导零) | | *dd* | 01-31(月中的日,有前导零) | | *w* | 1-7(周中的日,从星期日=1开始) | | *ww* | 1-53(年中的周,无前导零;第1周从1月1日开始) | | *m* | 1-12(年中的月,无前导零,从一月=1开始) | | *mm* | 01-12(年中的月,有前导零,从一月=01开始) | | *mmm* | 显示月份缩写(回历月份名称无缩写) | | *mmmm* | 显示完整月份名称 | | *y* | 1-366(年中的日) | | *yy* | 00-99(年份的后两位数字) | | *yyyy* | 100-9999(三位或四位数字的年份) | ### 时间符号 | 符号 | 范围 | |-------|------------------------------------------------------------------------| | *h* | 0-23(附加"AM"或"PM"时为1-12)(时,无前导零) | | *hh* | 00-23(附加"AM"或"PM"时为01-12)(时,有前导零) | | *n* | 0-59(分,无前导零) | | *nn* | 00-59(分,有前导零) | | *m* | 0-59(分,无前导零)。仅在前面有*h*或*hh*时使用 | | *mm* | 00-59(分,有前导零)。仅在前面有*h*或*hh*时使用 | | *s* | 0-59(秒,无前导零) | | *ss* | 00-59(秒,有前导零) | ### 示例 本示例展示了**Format**函数的各种用法,使用命名格式和用户定义格式来格式化值。对于日期分隔符(`/`)、时间分隔符(`:`)和AM/PM文本,系统显示的实际格式化输出取决于运行代码的区域设置。在开发环境中显示时间和日期时,使用代码区域设置的短时间格式和短日期格式。由运行中的代码显示时,使用系统区域设置的短时间格式和短日期格式,这可能与代码区域设置不同。此示例假设为英语/美国设置。`MyTime`和`MyDate`在开发环境中使用当前系统短时间设置和短日期设置显示。 ```vb Dim MyTime, MyDate, MyStr MyTime = #17:04:23# MyDate = #January 27, 1993# ' Returns current system time in the system-defined long time format. MyStr = Format(Time, "Long Time") ' Returns current system date in the system-defined long date format. MyStr = Format(Date, "Long Date") MyStr = Format(MyTime, "h:m:s") ' Returns "17:4:23". MyStr = Format(MyTime, "hh:mm:ss am/pm") ' Returns "05:04:23 pm". MyStr = Format(MyTime, "hh:mm:ss AM/PM") ' Returns "05:04:23 PM". MyStr = Format(MyDate, "dddd, mmm d yyyy") ' Returns "Wednesday, Jan 27 1993". ' If format is not supplied, a string is returned. MyStr = Format(23) ' Returns "23". ' User-defined formats. MyStr = Format(5459.4, "##,##0.00") ' Returns "5,459.40". MyStr = Format(334.9, "###0.00") ' Returns "334.90". MyStr = Format(5, "0.00%") ' Returns "500.00%". MyStr = Format("HELLO", "<") ' Returns "hello". MyStr = Format("This is it", ">") ' Returns "THIS IS IT". ``` ### 不同数值的不同格式 数字的用户定义格式表达式可以有一到四个用分号分隔的节。如果*format*参数包含某个命名数字格式,则只允许一个节。 | 节数 | 结果 | |----------|----------------------------------------------------------------------------------------------------------------------------| | 仅一个节 | 格式表达式适用于所有值。 | | 两个节 | 第一节适用于正值和零,第二节适用于负值。 | | 三个节 | 第一节适用于正值,第二节适用于负值,第三节适用于零。 | | 四个节 | 第一节适用于正值,第二节适用于负值,第三节适用于零,第四节适用于**Null**值。 | ```vb "$#,##0;($#,##0)" ``` 当包含分号但中间没有任何内容时,缺少的节使用正值的格式打印。例如,以下格式使用第一节中的格式显示正值和负值,如果值为零则显示"Zero"。 ```vb "$#,##0;;\Z\e\r\o" ``` ### 不同字符串值的不同格式 字符串的格式表达式可以有一个节或两个用分号(`;`)分隔的节。 | 节数 | 结果 | |----------|------------------------------------------------------------------------------------------------------------| | 仅一个节 | 格式适用于所有字符串数据。 | | 两个节 | 第一节适用于字符串数据,第二节适用于**Null**值和零长度字符串(`""`)。 | ### 命名日期/时间格式 下表标识了预定义的日期和时间格式名称。 | 格式名称 | 描述 | |------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **General Date** | 显示日期和/或时间,例如4/3/93 05:34 PM。如果没有小数部分,则仅显示日期,例如4/3/93。如果没有整数部分,则仅显示时间,例如05:34 PM。日期显示由系统设置决定。 | | **Long Date** | 根据系统长日期格式显示日期。 | | **Medium Date** | 使用适合宿主应用程序语言版本的中等日期格式显示日期。 | | **Short Date** | 使用系统短日期格式显示日期。 | | **Long Time** | 使用系统长时间格式显示时间;包括小时、分钟、秒。 | | **Medium Time** | 使用12小时格式显示时间,包括小时和分钟以及AM/PM标志。 | | **Short Time** | 使用24小时格式显示时间,例如17:45。 | ### 命名数字格式 下表标识了预定义的数字格式名称。 | 格式名称 | 描述 | |-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **General Number** | 显示不带千位分隔符的数字。 | | **Currency** | 显示带千位分隔符的数字(如适用);在小数分隔符右侧显示两位数字。输出基于系统区域设置。 | | **Fixed** | 在小数分隔符左侧至少显示一位数字,右侧显示两位数字。 | | **Standard** | 显示带千位分隔符的数字,小数分隔符左侧至少一位数字,右侧两位数字。 | | **Percent** | 显示乘以100的数字,并在右侧附加百分号(`%`);始终在小数分隔符右侧显示两位数字。 | | **Scientific** | 使用标准科学记数法。 | | **Yes/No** | 如果数字为0则显示No;否则显示Yes。 | | **True/False** | 如果数字为0则显示**False**;否则显示**True**。 | | **On/Off** | 如果数字为0则显示Off;否则显示On。 | ### 用户定义的字符串格式 使用以下任意字符创建字符串的格式表达式。 | 字符 | 描述 | |------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `@` | 字符占位符。显示一个字符或空格。如果字符串在格式字符串中`@`符号出现的位置有一个字符,则显示该字符;否则,在该位置显示一个空格。占位符从右向左填充,除非格式字符串中有感叹号字符(`!`)。 | | `&` | 字符占位符。显示一个字符或不显示。如果字符串在`&`符号出现的位置有一个字符,则显示该字符;否则,不显示任何内容。占位符从右向左填充,除非格式字符串中有感叹号字符(`!`)。 | | `<` | 强制小写。以小写格式显示所有字符。 | | `>` | 强制大写。以大写格式显示所有字符。 | | `!` | 强制从左到右填充占位符。默认为从右到左填充占位符。 | ### 用户定义的日期/时间格式 下表标识了可用于创建用户定义日期/时间格式的字符。 | 字符 | 描述 | |---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `:` | 时间分隔符。在某些区域设置中,可能使用其他字符来表示时间分隔符。时间分隔符在格式化时间值时分隔小时、分钟和秒。格式化输出中用作时间分隔符的实际字符由系统设置决定。 | | `/` | 日期分隔符。在某些区域设置中,可能使用其他字符来表示日期分隔符。日期分隔符在格式化日期值时分隔日、月和年。格式化输出中用作日期分隔符的实际字符由系统设置决定。 | | `c` | 将日期显示为`ddddd`,将时间显示为`ttttt`,按此顺序。如果日期序列数没有小数部分,则仅显示日期信息;如果没有整数部分,则仅显示时间信息。 | | `d` | 将日显示为不带前导零的数字(1--31)。 | | `dd` | 将日显示为带前导零的数字(01--31)。 | | `ddd` | 将日显示为缩写(Sun--Sat)。本地化。 | | `dddd` | 将日显示为全名(Sunday--Saturday)。本地化。 | | `ddddd` | 将日期显示为完整日期(包括日、月和年),根据系统短日期格式设置进行格式化。默认短日期格式为`m/d/yy`。 | | `dddddd`| 将日期序列数显示为完整日期(包括日、月和年),根据系统识别的长日期设置进行格式化。默认长日期格式为`mmmm dd, yyyy`。 | | `w` | 将周中的日显示为数字(1表示星期日至7表示星期六)。 | | `ww` | 将年中的周显示为数字(1--54)。 | | `m` | 将月显示为不带前导零的数字(1--12)。如果`m`紧跟在`h`或`hh`之后,则显示分钟而非月份。 | | `mm` | 将月显示为带前导零的数字(01--12)。如果`m`紧跟在`h`或`hh`之后,则显示分钟而非月份。 | | `mmm` | 将月显示为缩写(Jan--Dec)。本地化。 | | `mmmm` | 将月显示为完整月份名称(January--December)。本地化。 | | `q` | 将年中的季度显示为数字(1--4)。 | | `y` | 将年中的日显示为数字(1--366)。 | | `yy` | 将年显示为2位数字(00--99)。 | | `yyyy` | 将年显示为4位数字(100--9999)。 | | `h` | 将小时显示为不带前导零的数字(0--23)。 | | `hh` | 将小时显示为带前导零的数字(00--23)。 | | `n` | 将分钟显示为不带前导零的数字(0--59)。 | | `nn` | 将分钟显示为带前导零的数字(00--59)。 | | `s` | 将秒显示为不带前导零的数字(0--59)。 | | `ss` | 将秒显示为带前导零的数字(00--59)。 | | `ttttt` | 将时间显示为完整时间(包括小时、分钟和秒),使用系统识别的时间格式定义的时间分隔符进行格式化。如果选择了前导零选项且时间在上午或下午10:00之前,则显示前导零。默认时间格式为`h:mm:ss`。 | | `AM/PM` | 使用12小时制,在中午之前的任何小时显示大写AM;在中午至11:59 P.M.之间的任何小时显示大写PM。 | | `am/pm` | 使用12小时制,在中午之前的任何小时显示小写am;在中午至11:59 P.M.之间的任何小时显示小写pm。 | | `A/P` | 使用12小时制,在中午之前的任何小时显示大写A;在中午至11:59 P.M.之间的任何小时显示大写P。 | | `a/p` | 使用12小时制,在中午之前的任何小时显示小写a;在中午至11:59 P.M.之间的任何小时显示小写p。 | | `AMPM` | 使用12小时制,在中午之前的任何小时显示由系统定义的AM字符串;在中午至11:59 P.M.之间的任何小时显示由系统定义的PM字符串。 | ### 用户定义的数字格式 下表标识了可用于创建用户定义数字格式的字符。 | 字符 | 描述 | |-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 无 | 显示不带格式的数字。 | | `0` | 数字占位符。显示一个数字或零。如果表达式在格式字符串中`0`出现的位置有一个数字,则显示该数字;否则,在该位置显示零。如果数字的位数少于格式表达式中零(小数点两侧)的位数,则显示前导零或尾随零。如果数字小数分隔符右侧的位数多于格式表达式中零的位数,则将数字四舍五入到零的位数。如果数字小数分隔符左侧的位数多于格式表达式中零的位数,则不加修改地显示多余的数字。 | | `#` | 数字占位符。显示一个数字或不显示。如果表达式在格式字符串中`#`出现的位置有一个数字,则显示该数字;否则,在该位置不显示任何内容。此符号的作用类似于`0`数字占位符,不同之处在于当数字的位数等于或少于格式表达式中小数分隔符两侧的`#`字符数时,不显示前导零和尾随零。 | | `.` | 小数占位符。小数占位符决定小数分隔符左侧和右侧显示多少位数字。如果格式表达式中此符号左侧仅包含数字符号,则小于1的数字以小数分隔符开头。要为小数显示前导零,请使用0作为小数分隔符左侧的第一个数字占位符。格式化输出中用作小数占位符的实际字符取决于系统识别的数字格式。 | | `%` | 百分比占位符。表达式乘以100。百分号(`%`)插入到格式字符串中出现的位置。 | | `,` | 千位分隔符。如果格式包含被数字占位符(`0`或`#`)包围的千位分隔符,则指定使用千位分隔符。两个相邻的千位分隔符或紧接在小数分隔符左侧的千位分隔符表示"将数字除以1000进行缩放,并根据需要四舍五入。" | | `:` | 时间分隔符。见上文。 | | `/` | 日期分隔符。见上文。 | | `E- E+ e- e+` | 科学格式。如果格式表达式中`E-`、`E+`、`e-`或`e+`的右侧至少包含一个数字占位符(`0`或`#`),则数字以科学格式显示,并在数字与其指数之间插入`E`或`e`。使用`E-`或`e-`在负指数旁放置减号。使用`E+`或`e+`在负指数旁放置减号,在正指数旁放置加号。 | | `- + $ ( )` | 显示原义字符。要显示未列出的字符,请在其前面加反斜杠(`\`)或用双引号(`" "`)将其括起来。 | | `\` | 显示格式字符串中的下一个字符。使用反斜杠与将下一个字符用双引号括起来的效果相同。要显示反斜杠,请使用两个反斜杠(`\\`)。 | | `"ABC"` | 显示双引号(`" "`)内的字符串。要在代码中的*format*中包含字符串,请使用`Chr(34)`将文本括起来(34是引号`"`的字符代码)。 | ### 另请参阅 * [FormatCurrency](/official/Reference/VBA/Strings/FormatCurrency)、[FormatDateTime](/official/Reference/VBA/Strings/FormatDateTime)、[FormatNumber](/official/Reference/VBA/Strings/FormatNumber)、[FormatPercent](/official/Reference/VBA/Strings/FormatPercent)函数 --- --- url: /en/official/Reference/VBA/Strings/FormatCurrency.md --- # FormatCurrency Returns an expression formatted as a currency value by using the currency symbol defined in the system control panel. Syntax: **FormatCurrency(** *expression* \[ **,** *numDigitsAfterDecimal* \[ **,** *includeLeadingDigit* \[ **,** *useParensForNegativeNumbers* \[ **,** *groupDigits* ] ] ] ] **)** *expression* : *required* Expression to be formatted. *numDigitsAfterDecimal* : *optional* Numeric value indicating how many places to the right of the decimal are displayed. Default value is -1, which indicates that the computer's regional settings are used. *includeLeadingDigit* : *optional* Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See settings below. *useParensForNegativeNumbers* : *optional* Tristate constant that indicates whether or not to place negative values within parentheses. See settings below. *groupDigits* : *optional* Tristate constant that indicates whether or not numbers are grouped by using the group delimiter specified in the computer's regional settings. See settings below. The *includeLeadingDigit*, *useParensForNegativeNumbers*, and *groupDigits* arguments have the following settings: | Constant | Value | Description | |------------------|-------|------------------------------------------------------| | **vbTrue** | -1 | True | | **vbFalse** | 0 | False | | **vbUseDefault** | -2 | Use the setting from the computer's regional settings. | When one or more optional arguments are omitted, the values for omitted arguments are provided by the computer's regional settings. The position of the currency symbol relative to the currency value is determined by the system's regional settings. ### See Also * [Format](/en/official/Reference/VBA/Strings/Format), [FormatNumber](/en/official/Reference/VBA/Strings/FormatNumber), [FormatPercent](/en/official/Reference/VBA/Strings/FormatPercent) functions --- --- url: /zh/official/Reference/VBA/Strings/FormatCurrency.md --- # FormatCurrency 返回一个使用系统控制面板中定义的货币符号格式化为货币值的表达式。 语法:**FormatCurrency(** *expression* \[ **,** *numDigitsAfterDecimal* \[ **,** *includeLeadingDigit* \[ **,** *useParensForNegativeNumbers* \[ **,** *groupDigits* ] ] ] ] **)** *expression* : *必需* 要格式化的表达式。 *numDigitsAfterDecimal* : *可选* 数值,指示小数点右侧显示多少位。默认值为-1,表示使用计算机的区域设置。 *includeLeadingDigit* : *可选* 三态常量,指示是否为小数值显示前导零。参见下面的设置。 *useParensForNegativeNumbers* : *可选* 三态常量,指示是否将负值放在括号内。参见下面的设置。 *groupDigits* : *可选* 三态常量,指示是否使用计算机区域设置中指定的组分隔符对数字进行分组。参见下面的设置。 *includeLeadingDigit*、*useParensForNegativeNumbers*和*groupDigits*参数的设置如下: | 常量 | 值 | 描述 | |-------------------|-----|--------------------------------| | **vbTrue** | -1 | True | | **vbFalse** | 0 | False | | **vbUseDefault** | -2 | 使用计算机区域设置中的设置。 | 当省略一个或多个可选参数时,省略参数的值由计算机的区域设置提供。货币符号相对于货币值的位置由系统的区域设置决定。 ### 另请参阅 * [Format](/official/Reference/VBA/Strings/Format)、[FormatNumber](/official/Reference/VBA/Strings/FormatNumber)、[FormatPercent](/official/Reference/VBA/Strings/FormatPercent)函数 --- --- url: /en/official/Reference/VBA/Strings/FormatDateTime.md --- # FormatDateTime Returns an expression formatted as a date or time. Syntax: **FormatDateTime(** *date* \[ **,** *namedFormat* ] **)** *date* : *required* Date expression to be formatted. *namedFormat* : *optional* Numeric value that indicates the date/time format used. If omitted, **vbGeneralDate** is used. The *namedFormat* argument has the following settings: | Constant | Value | Description | |--------------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **vbGeneralDate** | 0 | Display a date and/or time. If there is a date part, display it as a short date. If there is a time part, display it as a long time. If present, both parts are displayed. | | **vbLongDate** | 1 | Display a date by using the long date format specified in the system regional settings. | | **vbShortDate** | 2 | Display a date by using the short date format specified in the system regional settings. | | **vbLongTime** | 3 | Display a time by using the time format specified in the system regional settings. | | **vbShortTime** | 4 | Display a time by using the 24-hour format (`hh:mm`). | ### Example This example uses **FormatDateTime** to display a date value in several formats. ```vb Dim d As Date d = #2026-05-29# Debug.Print FormatDateTime(d, vbLongDate) ' e.g. "Friday, May 29, 2026" Debug.Print FormatDateTime(d, vbShortDate) ' e.g. "05/29/2026" Debug.Print FormatDateTime(d, vbLongTime) ' e.g. "12:00:00 AM" ``` ### See Also * [Format](/en/official/Reference/VBA/Strings/Format), [MonthName](/en/official/Reference/VBA/Strings/MonthName), [WeekdayName](/en/official/Reference/VBA/Strings/WeekdayName) functions --- --- url: /zh/official/Reference/VBA/Strings/FormatDateTime.md --- # FormatDateTime 返回一个格式化为日期或时间的表达式。 语法:**FormatDateTime(** *date* \[ **,** *namedFormat* ] **)** *date* : *必需* 要格式化的日期表达式。 *namedFormat* : *可选* 数值,指示所使用的日期/时间格式。如果省略,则使用**vbGeneralDate**。 *namedFormat*参数的设置如下: | 常量 | 值 | 描述 | |--------------------|-----|--------------------------------------------------------------------------------------------------------------------------------------------------| | **vbGeneralDate** | 0 | 显示日期和/或时间。如果有日期部分,显示为短日期。如果有时间部分,显示为长时间。如果两者都存在,则都显示。 | | **vbLongDate** | 1 | 使用系统区域设置中指定的长日期格式显示日期。 | | **vbShortDate** | 2 | 使用系统区域设置中指定的短日期格式显示日期。 | | **vbLongTime** | 3 | 使用系统区域设置中指定的时间格式显示时间。 | | **vbShortTime** | 4 | 使用24小时格式(`hh:mm`)显示时间。 | ### 示例 本示例使用**FormatDateTime**以多种格式显示日期值。 ```vb Dim d As Date d = #2026-05-29# Debug.Print FormatDateTime(d, vbLongDate) ' e.g. "Friday, May 29, 2026" Debug.Print FormatDateTime(d, vbShortDate) ' e.g. "05/29/2026" Debug.Print FormatDateTime(d, vbLongTime) ' e.g. "12:00:00 AM" ``` ### 另请参阅 * [Format](/official/Reference/VBA/Strings/Format)、[MonthName](/official/Reference/VBA/Strings/MonthName)、[WeekdayName](/official/Reference/VBA/Strings/WeekdayName)函数 --- --- url: /en/official/Reference/VBA/Strings/FormatNumber.md --- # FormatNumber Returns an expression formatted as a number. Syntax: **FormatNumber(** *expression* \[ **,** *numDigitsAfterDecimal* \[ **,** *includeLeadingDigit* \[ **,** *useParensForNegativeNumbers* \[ **,** *groupDigits* ] ] ] ] **)** *expression* : *required* Expression to be formatted. *numDigitsAfterDecimal* : *optional* Numeric value indicating how many places to the right of the decimal are displayed. Default value is -1, which indicates that the computer's regional settings are used. *includeLeadingDigit* : *optional* Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See settings below. *useParensForNegativeNumbers* : *optional* Tristate constant that indicates whether or not to place negative values within parentheses. See settings below. *groupDigits* : *optional* Tristate constant that indicates whether or not numbers are grouped by using the group delimiter specified in the computer's regional settings. See settings below. The *includeLeadingDigit*, *useParensForNegativeNumbers*, and *groupDigits* arguments have the following settings: | Constant | Value | Description | |------------------|-------|------------------------------------------------------| | **vbTrue** | -1 | True | | **vbFalse** | 0 | False | | **vbUseDefault** | -2 | Use the setting from the computer's regional settings. | When one or more optional arguments are omitted, the values for omitted arguments are provided by the computer's regional settings. ### See Also * [Format](/en/official/Reference/VBA/Strings/Format), [FormatCurrency](/en/official/Reference/VBA/Strings/FormatCurrency), [FormatPercent](/en/official/Reference/VBA/Strings/FormatPercent) functions --- --- url: /zh/official/Reference/VBA/Strings/FormatNumber.md --- # FormatNumber 返回一个格式化为数字的表达式。 语法:**FormatNumber(** *expression* \[ **,** *numDigitsAfterDecimal* \[ **,** *includeLeadingDigit* \[ **,** *useParensForNegativeNumbers* \[ **,** *groupDigits* ] ] ] ] **)** *expression* : *必需* 要格式化的表达式。 *numDigitsAfterDecimal* : *可选* 数值,指示小数点右侧显示多少位。默认值为-1,表示使用计算机的区域设置。 *includeLeadingDigit* : *可选* 三态常量,指示是否为小数值显示前导零。参见下面的设置。 *useParensForNegativeNumbers* : *可选* 三态常量,指示是否将负值放在括号内。参见下面的设置。 *groupDigits* : *可选* 三态常量,指示是否使用计算机区域设置中指定的组分隔符对数字进行分组。参见下面的设置。 *includeLeadingDigit*、*useParensForNegativeNumbers*和*groupDigits*参数的设置如下: | 常量 | 值 | 描述 | |-------------------|-----|--------------------------------| | **vbTrue** | -1 | True | | **vbFalse** | 0 | False | | **vbUseDefault** | -2 | 使用计算机区域设置中的设置。 | 当省略一个或多个可选参数时,省略参数的值由计算机的区域设置提供。 ### 另请参阅 * [Format](/official/Reference/VBA/Strings/Format)、[FormatCurrency](/official/Reference/VBA/Strings/FormatCurrency)、[FormatPercent](/official/Reference/VBA/Strings/FormatPercent)函数 --- --- url: /en/official/Reference/VBA/Strings/FormatPercent.md --- # FormatPercent Returns an expression formatted as a percentage (multiplied by 100) with a trailing `%` character. Syntax: **FormatPercent(** *expression* \[ **,** *numDigitsAfterDecimal* \[ **,** *includeLeadingDigit* \[ **,** *useParensForNegativeNumbers* \[ **,** *groupDigits* ] ] ] ] **)** *expression* : *required* Expression to be formatted. *numDigitsAfterDecimal* : *optional* Numeric value indicating how many places to the right of the decimal are displayed. Default value is -1, which indicates that the computer's regional settings are used. *includeLeadingDigit* : *optional* Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See settings below. *useParensForNegativeNumbers* : *optional* Tristate constant that indicates whether or not to place negative values within parentheses. See settings below. *groupDigits* : *optional* Tristate constant that indicates whether or not numbers are grouped by using the group delimiter specified in the computer's regional settings. See settings below. The *includeLeadingDigit*, *useParensForNegativeNumbers*, and *groupDigits* arguments have the following settings: | Constant | Value | Description | |------------------|-------|------------------------------------------------------| | **vbTrue** | -1 | True | | **vbFalse** | 0 | False | | **vbUseDefault** | -2 | Use the setting from the computer's regional settings. | When one or more optional arguments are omitted, the values for omitted arguments are provided by the computer's regional settings. ### See Also * [Format](/en/official/Reference/VBA/Strings/Format), [FormatCurrency](/en/official/Reference/VBA/Strings/FormatCurrency), [FormatNumber](/en/official/Reference/VBA/Strings/FormatNumber) functions --- --- url: /zh/official/Reference/VBA/Strings/FormatPercent.md --- # FormatPercent 返回一个格式化为百分比(乘以100)并带有尾部`%`字符的表达式。 语法:**FormatPercent(** *expression* \[ **,** *numDigitsAfterDecimal* \[ **,** *includeLeadingDigit* \[ **,** *useParensForNegativeNumbers* \[ **,** *groupDigits* ] ] ] ] **)** *expression* : *必需* 要格式化的表达式。 *numDigitsAfterDecimal* : *可选* 数值,指示小数点右侧显示多少位。默认值为-1,表示使用计算机的区域设置。 *includeLeadingDigit* : *可选* 三态常量,指示是否为小数值显示前导零。参见下面的设置。 *useParensForNegativeNumbers* : *可选* 三态常量,指示是否将负值放在括号内。参见下面的设置。 *groupDigits* : *可选* 三态常量,指示是否使用计算机区域设置中指定的组分隔符对数字进行分组。参见下面的设置。 *includeLeadingDigit*、*useParensForNegativeNumbers*和*groupDigits*参数的设置如下: | 常量 | 值 | 描述 | |-------------------|-----|--------------------------------| | **vbTrue** | -1 | True | | **vbFalse** | 0 | False | | **vbUseDefault** | -2 | 使用计算机区域设置中的设置。 | 当省略一个或多个可选参数时,省略参数的值由计算机的区域设置提供。 ### 另请参阅 * [Format](/official/Reference/VBA/Strings/Format)、[FormatCurrency](/official/Reference/VBA/Strings/FormatCurrency)、[FormatNumber](/official/Reference/VBA/Strings/FormatNumber)函数 --- --- url: /en/official/Reference/VBRUN/Constants/FormBorderStyleConstants.md --- # FormBorderStyleConstants Border-and-frame style values for the **BorderStyle** property of forms, choosing what kind of window decoration the form has and whether the user can resize it. | Constant | Value | Description | |----------|-------|-------------| | **vbBSNone** | 0 | The form has no border, title bar, or system menu. | | **vbFixedSingle** | 1 | A single-line, non-resizable border with a normal title bar. | | **vbSizable** | 2 | A resizable border with a normal title bar (the default for forms). | | **vbFixedDialog** | 3 | A dialog-style fixed border. | | **vbFixedToolWindow** | 4 | A non-resizable tool-window border with a small title bar. | | **vbSizableToolWindow** | 5 | A resizable tool-window border with a small title bar. | | **vbSizableNoTitleBar** | 6 | A resizable border without a title bar. *(twinBASIC addition.)* | | **vbSizableToolWindowNoTitleBar** | 7 | A resizable tool-window border without a title bar. *(twinBASIC addition.)* | --- --- url: /zh/official/Reference/VBRUN/Constants/FormBorderStyleConstants.md --- # FormBorderStyleConstants 窗体**BorderStyle**属性的边框和框架样式值,选择窗体具有哪种窗口装饰以及用户是否可以调整其大小。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbBSNone** | 0 | 窗体无边框、标题栏或系统菜单。 | | **vbFixedSingle** | 1 | 固定单线边框,不可调整大小,带正常标题栏。 | | **vbSizable** | 2 | 可调整大小的边框,带正常标题栏(窗体默认)。 | | **vbFixedDialog** | 3 | 对话框样式的固定边框。 | | **vbFixedToolWindow** | 4 | 不可调整大小的工具窗口边框,带小标题栏。 | | **vbSizableToolWindow** | 5 | 可调整大小的工具窗口边框,带小标题栏。 | | **vbSizableNoTitleBar** | 6 | 可调整大小的边框,无标题栏。*(twinBASIC新增)* | | **vbSizableToolWindowNoTitleBar** | 7 | 可调整大小的工具窗口边框,无标题栏。*(twinBASIC新增)* | --- --- url: /en/official/Features/GUI-Components/Forms.md --- # Form Features twinBASIC provides numerous enhancements to forms and form handling. ## Modern Image Format Support You no longer face an incredibly limited format selection for images in tB Forms and Controls; not only do the Bitmap and Icon formats support the full range of formats for those, you can additionally load PNG Images, JPEG Images, Metafiles (.emf/.wmf), and SVG Vector Graphics (.svg). ### Improved LoadPicture Additionally, `LoadPicture` can load all image types directly from a byte array, rather than requiring a file on disk. You can use this to load images from resource files or other sources. Note that if your projects references stdole2.tlb (most do), currently you must qualify it as `Global.LoadPicture` to get tB's custom binding that supports byte arrays. ## Transparency and Alpha Blending ### Form.TransparencyKey This new property specifies a color that will be transparent to the window below it in the z-order (all windows, not just in your project). Setting this property will cause the specified color to be 100% transparent. A Shape control with a solid `FillStyle` is a helpful tool to color the areas of the form in the key color. ### Form.Opacity This sets an alpha blending level for the entire form. Like transparency, this is to all windows immediately underneath it. Note that any areas covered by the `TransparencyKey` color will remain 100% transparent. The following image shows a Form with a `TransparencyKey` of Red, using a Shape control to define the transparent area, while also specifying 75% `Opacity` for the entire form: ![image](/assets/85f25aa2-abc8-4d42-8510-078f8ee4a324.CxpsK7Bj.png) ## Additional Form Features In addition to the above, forms have: * `DpiScaleX`/`DpiScaleY` properties to retrieve the current values * `.MinWidth`, `.MinHeight`, `.MaxWidth`, and `.MaxHeight` properties so subclassing isn't needed for this * `Form.TopMost` property. * Control anchoring: control x/y/cx/cy can made relative, so they're automatically moved/resized with the Form. For example if you put a TextBox in the bottom right, then check the Right and Bottom anchors (in addition to Top and Left), the bottom right will size with the form on resize. This saves a lot of boiler-plate sizing code. * Control docking: Controls can be fixed along one of the sides of the Form (or container), or made to fill the whole Form/container. Multiple controls can be combined and mixed/matched in docking positions. For more information on Control Anchoring and Control Docking, see the [Anchoring and Docking page](/en/official/Features/GUI-Components/Anchoring-Docking). ## High Quality Scaling in Image Controls Image controls now offer a `StretchMode` property that allows you to choose Bilinear, Bicubic, Lanczos3 and Lanczos8 stretching algorithms, which are far superior to the default stretching algorithm. These use built in algorithms so do not add additional dependencies or API calls. ## DPI Scaling PictureDpiScaling property for forms, usercontrols and pictureboxes: PictureDpiScaling property allows you to turn off DPI scaling of images so that they display at 1:1 rather than allowing the OS to stretch them. The idea being you may want to choose a different bitmap manually, rather than apply the somewhat limited OS-stretching. --- --- url: /en/official/Tutorials/Forms.md --- # Forms basics This tutorial builds a small temperature-converter application. By the end you will know how to add standard controls to a form, set their properties at design time and at runtime, write event handlers, and validate user input. ## What you will build A Standard EXE with one form. The user types a temperature value, selects a direction (Celsius to Fahrenheit or Fahrenheit to Celsius), clicks a button, and sees the result. The finished form looks something like this: The worked example is small enough to finish in under ten minutes, but it touches the controls and patterns that appear in almost every VB6-compatible program. ## Step 1: Create the project Open twinBASIC and choose **File → New Project → Standard EXE**. The IDE creates a new project with one form, `Form1`, already open in the designer. ## Step 2: Add and arrange controls The Toolbox panel on the left lists the controls available in the current project. You will need four control types: **Label**, **TextBox**, **Frame** (to group the OptionButtons), **OptionButton**, **CommandButton**, and a second **Label** for the output. If the Toolbox is not visible, open it with **View → Toolbox**. Double-click a control in the Toolbox to drop it onto the form, or click once in the Toolbox and then drag a rectangle on the form to place and size it. Add the following controls in order: | Control | Name | Caption / Text | Purpose | |---------|------|----------------|---------| | Label | `lblInputPrompt` | `Temperature:` | Prompt for the input field | | TextBox | `txtInput` | *(blank)* | User types the temperature value here | | Frame | `fraDirection` | `Convert` | Groups the two OptionButtons | | OptionButton | `optCtoF` | `Celsius → Fahrenheit` | Direction selector | | OptionButton | `optFtoC` | `Fahrenheit → Celsius` | Direction selector | | CommandButton | `cmdConvert` | `Convert` | Triggers the calculation | | Label | `lblResult` | *(blank)* | Displays the result | To rename a control, select it and change the **Name** property in the Properties window on the right. Change the displayed text by setting the **Caption** property (for labels, frames, option buttons, and command buttons) or the **Text** property (for text boxes). ::: info Place both OptionButtons inside the Frame by dragging them onto the frame rather than onto the form directly. Controls inside a Frame form an exclusive group --- selecting one automatically deselects the others. ::: ### Setting properties at design time Select `optCtoF` and set its **Value** property to `True` in the Properties window. This makes it the default selection when the form opens. Select `lblResult` and set its **Font** property. Click the `...` button next to the Font value to open the Font dialog. Choose a size that makes the result easy to read, such as 12 pt. ## Step 3: Write the event handler Double-click the `cmdConvert` button in the designer. The IDE switches to the Code Editor and creates a shell for the button's Click event: ```vb Private Sub cmdConvert_Click() End Sub ``` Fill it in as follows: ```vb Private Sub cmdConvert_Click() If Not IsNumeric(txtInput.Text) Then lblResult.Caption = "Please enter a number." Exit Sub End If Dim value As Double value = CDbl(txtInput.Text) Dim result As Double Dim unit As String If optCtoF.Value Then result = value * 9 / 5 + 32 unit = "°F" Else result = (value - 32) * 5 / 9 unit = "°C" End If lblResult.Caption = Format(result, "0.00") & " " & unit End Sub ``` The handler: 1. Checks that the input is numeric before converting it. [**IsNumeric**](/en/official/Reference/VBA/Information/IsNumeric) returns `False` for empty strings, letters, or punctuation other than a decimal point or leading minus. 2. Reads `optCtoF.Value` to determine the direction. Because the two OptionButtons are in the same Frame, exactly one of them is always `True`. 3. Calls [**Format**](/en/official/Reference/VBA/Strings/Format) to round the result to two decimal places. ## Step 4: Run the application Press **F5** (or **Run → Start**). The form appears. Type `100` into the text box, make sure `Celsius → Fahrenheit` is selected, and click **Convert**. The label should show `212.00 °F`. Try switching to `Fahrenheit → Celsius` and converting `32` --- the result should be `0.00 °C`. Close the form to stop the application and return to the IDE. ## Setting properties at runtime Design-time properties are convenient but limited. You can read and write most control properties from code at any time. Add a `Form_Load` handler to set the form's title bar text and give `lblResult` a starting caption: ```vb Private Sub Form_Load() Me.Caption = "Temperature Converter" lblResult.Caption = "Enter a value and click Convert." optCtoF.Value = True ' ensure the default is set in code too End Sub ``` `Me` refers to the current form --- equivalent to writing `Form1` from inside the form's own module. ## Handling the KeyPress event It is often convenient to trigger the conversion when the user presses **Enter** in the text box, without having to click the button. Double-click `txtInput` in the designer to open the code editor, then select `KeyPress` from the event drop-down at the top right: ```vb Private Sub txtInput_KeyPress(KeyAscii As Integer) If KeyAscii = vbKeyReturn Then KeyAscii = 0 ' suppress the beep cmdConvert_Click ' reuse the button's handler End If End Sub ``` [**vbKeyReturn**](/en/official/Reference/VBRUN/Constants/KeyCodeConstants) is the constant for the Enter key (ASCII 13). Setting `KeyAscii` to `0` tells the control not to process the keystroke further --- without this, pressing Enter in a TextBox makes a beep on most systems. ## A note on anchoring and docking The controls added above use absolute positions. If the user resizes the form, the controls stay where you placed them and the layout may look awkward. twinBASIC supports **anchoring** (a control stays a fixed distance from one or more form edges as the form resizes) and **docking** (a control fills an edge or the entire client area). These behaviours are set through the **Anchor** and **Dock** properties on the VB package controls. See [Features → Anchoring and Docking](/en/official/Features/GUI-Components/Anchoring-Docking) for a full explanation. ## Where to go next * **Windows API** -- calling Win32 functions to read system information and drive platform features: [Calling the Windows API](/en/official/Tutorials/Windows-API) * **Custom controls** -- owner-drawn controls with gradient fills and per-pixel painting: [CustomControls tutorials](/en/official/Tutorials/CustomControls/) * **WebView2** -- embedding the Microsoft Edge browser engine inside a form: [WebView2 tutorials](/en/official/Tutorials/WebView2/) --- --- url: /en/official/Reference/VBRUN/Constants/FormShowConstants.md --- # FormShowConstants Modality values for the *Modal* argument of a form's **Show** method. | Constant | Value | Description | |----------|-------|-------------| | **vbModeless** | 0 | The form is shown modeless: the calling code continues immediately and the user can interact with other windows in the application. | | **vbModal** | 1 | The form is shown modal: the call does not return until the form is closed, and the user cannot interact with other windows in the application until then. | --- --- url: /zh/official/Reference/VBRUN/Constants/FormShowConstants.md --- # FormShowConstants 窗体**Show**方法的*Modal*参数的模态值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbModeless** | 0 | 窗体以非模态显示:调用代码立即继续,用户可与应用程序中的其他窗口交互。 | | **vbModal** | 1 | 窗体以模态显示:调用在窗体关闭之前不返回,在此之前用户不能与应用程序中的其他窗口交互。 | --- --- url: /en/official/Reference/VBRUN/Constants/FormWindowStateConstants.md --- # FormWindowStateConstants Window-state values for the **WindowState** property of a form. | Constant | Value | Description | |----------|-------|-------------| | **vbNormal** | 0 | The form is shown at its normal size and position. | | **vbMinimized** | 1 | The form is minimised to an icon. | | **vbMaximized** | 2 | The form is maximised to fill the screen (or its MDI parent). | --- --- url: /zh/official/Reference/VBRUN/Constants/FormWindowStateConstants.md --- # FormWindowStateConstants 窗体**WindowState**属性的窗口状态值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbNormal** | 0 | 窗体以正常大小和位置显示。 | | **vbMinimized** | 1 | 窗体最小化为图标。 | | **vbMaximized** | 2 | 窗体最大化以填充屏幕(或其MDI父窗口)。 | --- --- url: /en/official/Reference/VB/Frame.md --- # Frame class A **Frame** is a Win32 native container control that groups a set of related controls inside a captioned border. It serves two distinct purposes --- a visual cue that the enclosed controls belong together, and a logical grouping for [**OptionButton**](/en/official/Reference/VB/OptionButton/) controls: option buttons inside the same frame are mutually exclusive of one another but independent of option buttons elsewhere on the form. Controls dropped onto a frame at design time become its children, and moving, hiding, disabling, or destroying the frame moves, hides, disables, or destroys the entire group with it. A frame cannot itself receive the input focus. The mnemonic marker (`&`) in its [**Caption**](#caption) is honoured, but pressing **Alt+** that character moves the focus to the next control in tab order rather than to the frame itself --- exactly like a [**Label**](/en/official/Reference/VB/Label/). The default property is [**Caption**](#caption) and the default event is [**Click**](#click). ```vb Private Sub Form_Load() fraOutput.Caption = "&Output format" optHTML.Caption = "&HTML" optMarkdown.Caption = "&Markdown" optPlain.Caption = "&Plain text" optHTML.Value = True ' default selection within fraOutput End Sub Private Sub fraOutput_Click() Debug.Print "Frame clicked (between the option buttons)" End Sub ``` ## Container behaviour A frame is a true container: each control inside it has the frame's `hWnd` as its Win32 parent and its coordinates are relative to the frame's client area, not the form. As a result: * Toggling [**Visible**](#visible) or [**Enabled**](#enabled) affects every contained control. * Calling [**Move**](#move) re-positions the frame and the children move with it without each child raising its own resize. * The frame's [**Anchors**](#anchors) and [**Dock**](#dock) settings let it stretch with its parent so the whole group resizes together. * A control's [**Container**](#container) property returns the frame it lives in (and the frame's own [**Container**](#container) returns the form, or another frame, that hosts it). ## Caption, mnemonics, and the border The text in [**Caption**](#caption) is rendered along the top edge of the border by the standard Win32 group-box style. An ampersand in the caption marks the next character as a keyboard mnemonic; use `&&` to display a literal ampersand. Pressing **Alt+** the marked character moves the focus to the next control in tab order --- the frame does not take focus itself. [**BorderStyle**](#borderstyle) chooses between the standard captioned single-line border (**vbFixedSingleBorder**, the default) and a borderless mode (**vbNoBorder**). In **vbNoBorder** mode the standard group-box rendering is bypassed entirely --- neither the line nor the caption text is drawn --- and the frame becomes a plain rectangular region. [**Appearance**](#appearance) further selects between the 3-D and flat variant of the standard border. ## OptionButton groups Each frame defines its own option-button group. When the user selects an [**OptionButton**](/en/official/Reference/VB/OptionButton/) whose parent is this frame, every other option button on the same frame is automatically cleared, but option buttons on the form (or in sibling frames) are not affected. Use frames to present multiple independent radio-style choices on the same form: ```vb ' Two independent option-button groups on one form: ' fraSize: optSmall, optMedium, optLarge ' fraColour: optRed, optGreen, optBlue ``` ## Transparency and opacity [**Opacity**](#opacity) and [**TransparencyKey**](#transparencykey) enable Windows' layered-window features. Setting [**Opacity**](#opacity) below 100 makes the frame and its contained controls translucent; setting [**TransparencyKey**](#transparencykey) to a colour makes pixels of that colour fully transparent on screen. Both features require Windows 8 or later when the frame contains child controls --- otherwise only the frame's own background is affected. ## Properties ### Anchors The set of edges of the parent that the frame's corresponding edges follow when the parent resizes. Read-only --- assign individual `.Left`, `.Top`, `.Right`, `.Bottom` flags through the returned **Anchors** object. ### Appearance Determines how the frame's border is drawn by the OS. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). ### BackColor The background colour of the frame's client area, as an **OLE\_COLOR**. Defaults to the system 3-D face colour. Painted behind contained controls. ### BorderStyle The style of the frame's border. A member of [**ControlBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants): **vbFixedSingleBorder** (1, default --- the captioned group-box line) or **vbNoBorder** (0). With **vbNoBorder** the caption is also suppressed and the frame becomes a borderless background panel. ### Caption The text rendered along the top edge of the frame's border. **String**. **Default property.** Syntax: *object*.**Caption** \[ = *string* ] An ampersand marks the next character as a mnemonic; `&&` produces a literal ampersand. The string is read directly from the underlying window --- assigning to **Caption** updates the rendering immediately. ### ClipControls Whether child controls are clipped out of the frame's drawing region during paint. **Boolean**, default **True**. Changing **ClipControls** at run time recreates the underlying window. ### Container The control that hosts this frame --- typically the form, or another frame. Read with **Get**, change with **Set**. Setting **Container** re-parents the frame to a different container at run time. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a frame. Always **vbFrame**. ### Dock Where the frame is docked within its container. A member of [**DockModeConstants**](/en/official/Reference/VBRUN/Constants/DockModeConstants): **vbDockNone** (default), **vbDockLeft**, **vbDockTop**, **vbDockRight**, **vbDockBottom**, or **vbDockFill**. Docked frames ignore [**Anchors**](#anchors). ### DragIcon A **StdPicture** used as the mouse cursor while the frame is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the frame should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the frame and its contained controls accept user input. A disabled frame dims its contents and ignores mouse and keyboard interaction. **Boolean**, default **True**. Changing **Enabled** triggers an immediate repaint so the border reflects the new state. ### Font The **StdFont** used to render [**Caption**](#caption). The convenience properties **FontBold**, **FontItalic**, **FontName**, **FontSize**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. ### FontBold Shortcut for `Font.Bold`. **Boolean**. ### FontItalic Shortcut for `Font.Italic`. **Boolean**. ### FontName Shortcut for `Font.Name`. **String**. ### FontSize Shortcut for `Font.Size`. **Single**, in points. ### FontStrikethru Shortcut for `Font.Strikethrough`. **Boolean**. ### FontUnderline Shortcut for `Font.Underline`. **Boolean**. ### ForeColor The colour used to draw [**Caption**](#caption), as an **OLE\_COLOR**. Defaults to the system button-text colour. ### Height The frame's height, in twips by default (or in the container's **ScaleMode** units). **Double**. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user invokes context help while the frame has the active control underneath it. ### hWnd The Win32 window handle for the frame, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the frame is part of a control array, the **Long** zero-based index of this instance within the array. Reading **Index** on a non-array instance raises run-time error 343 (*Object not an array*). Read-only at run time. ### Left The horizontal distance from the left edge of the container to the left edge of the frame. **Double**. ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the frame. ### MousePointer The mouse cursor shown when the pointer is over the frame (and not over a child control with its own setting). A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### MultiFramePosition When the frame is hosted inside a [**MultiFrame**](/en/official/Reference/VB/MultiFrame/) layout container, the **Long** zero-based position of this frame in the **MultiFrame**'s ordered sequence. Default `-1` (no position assigned). Outside of a **MultiFrame** the value is ignored. ### MultiFrameSize When the frame is hosted inside a [**MultiFrame**](/en/official/Reference/VB/MultiFrame/), its size as a percentage of the **MultiFrame**'s usable extent (`0` for "share evenly"). **Double**. Outside of a **MultiFrame** the value is ignored. ### Name The unique design-time name of the frame on its parent form. Read-only at run time. ### OLEDropMode How the frame responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on a Frame; assigning **vbOLEDropAutomatic** raises run-time error 5. ### Opacity The frame's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Values below 100 require Windows 8 or later when the frame has child controls; out-of-process child windows are not affected. ### OriginalMultiFramePosition The frame's [**MultiFramePosition**](#multiframeposition) at the moment the [**MultiFrame**](/en/official/Reference/VB/MultiFrame/) was last reflowed. **Long**, default `-1`. Used internally by the **MultiFrame** layout engine to compact positions after a frame is moved; not normally written from user code. ### Parent A reference to the [**Form**](/en/official/Reference/VB/Form/) (or **UserControl**) that ultimately contains the frame. Read-only. Distinct from [**Container**](#container), which returns the immediate parent (form *or* enclosing frame). ### RightToLeft ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### TabIndex The position of the frame in the form's TAB-key navigation order. **Long**. The frame itself does not receive focus, but **TabIndex** controls where the frame's mnemonic forwards focus to: **Alt+** the marked character moves to the next focusable control whose **TabIndex** is greater than this one. ### Tag A free-form **String** the application can use to associate custom data with the frame. Ignored by the framework. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the frame's border or background. ### Top The vertical distance from the top of the container to the top of the frame. **Double**. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered frame --- clicks pass through to whatever is underneath, and the corresponding pixels do not paint. Default `-1` disables the effect. Requires Windows 8 or later when the frame has child controls. ### Visible Whether the frame and its contained controls are shown. **Boolean**, default **True**. ### VisualStyles Whether the OS theme engine should be used when drawing the frame border and caption. **Boolean**, default **True**. ### WhatsThisHelpID ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. See [**ShowWhatsThis**](#showwhatsthis). ::: ### Width The frame's width. **Double**. ## Methods ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Typically called from a [**MouseDown**](#mousedown) handler when [**DragMode**](#dragmode) is **vbManual**. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the frame in a single call. Contained controls are repositioned with it. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the frame, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Forces an immediate repaint of the frame and its border. Syntax: *object*.**Refresh** ### SetFocus Attempts to move the input focus to the frame. Because a frame is not focusable, this call has no observable effect on which control holds the focus, but it is provided for parity with the rest of the control API and for compatibility with code that calls **SetFocus** generically. Syntax: *object*.**SetFocus** ### ShowWhatsThis ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the frame to the front or back of its sibling stack within the container. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Click Raised when the user single-clicks the frame's client area or border (i.e. not over any contained control). **Default event.** Syntax: *object*\_**Click**( ) ### DblClick Raised when the user double-clicks the frame's client area or border. Syntax: *object*\_**DblClick**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over this frame. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the frame while a manual drag operation is in progress over it. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### Initialize Raised once, after the frame's underlying window has been created but before any contained controls are populated. Useful for setting initial values that the frame's children will read on their own initialisation. Syntax: *object*\_**Initialize**( ) ### MouseDown Raised when the user presses any mouse button over the frame's client area or border. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the frame's client area or border. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the frame's client area or border. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseWheel Raised when the mouse wheel turns over the frame. New in twinBASIC. Syntax: *object*\_**MouseWheel**( *Delta* **As Integer**, *Horizontal* **As Boolean** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the frame when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the frame while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) --- --- url: /zh/official/Reference/VB/Frame.md --- # Frame 类 **Frame**是Win32原生容器控件,在一组带标题的边框内将一组相关控件分组。它有两个不同的用途——视觉上提示包含的控件属于同一组,以及为[**OptionButton**](/official/Reference/VB/OptionButton/)控件提供逻辑分组:同一框架内的选项按钮互斥,但与窗体上其他位置的选项按钮独立。在设计时拖放到框架上的控件成为其子级,移动、隐藏、禁用或销毁框架会随之移动、隐藏、禁用或销毁整个组。 框架本身不能接收输入焦点。其[**Caption**](#caption)中的助记标记(`&`)有效,但按\*\*Alt+\*\*该字符会将焦点移到TAB顺序中的下一个控件而非框架本身——与[**Label**](/official/Reference/VB/Label/)完全相同。 默认属性是[**Caption**](#caption),默认事件是[**Click**](#click)。 ```vb Private Sub Form_Load() fraOutput.Caption = "&Output format" optHTML.Caption = "&HTML" optMarkdown.Caption = "&Markdown" optPlain.Caption = "&Plain text" optHTML.Value = True ' default selection within fraOutput End Sub Private Sub fraOutput_Click() Debug.Print "Frame clicked (between the option buttons)" End Sub ``` ## 容器行为 框架是真正的容器:其中每个控件的Win32父级是框架的`hWnd`,其坐标相对于框架的客户区而非窗体。因此: * 切换[**Visible**](#visible)或[**Enabled**](#enabled)会影响每个包含的控件。 * 调用[**Move**](#move)重新定位框架,子控件随其移动而不会各自引发调整大小。 * 框架的[**Anchors**](#anchors)和[**Dock**](#dock)设置使其随父级拉伸,因此整个组一起调整大小。 * 控件的[**Container**](#container)属性返回其所在的框架(框架自身的[**Container**](#container)返回承载它的窗体或其他框架)。 ## 标题、助记符和边框 [**Caption**](#caption)中的文本由标准Win32分组框样式沿边框的顶部边缘渲染。标题中的和号将下一个字符标记为键盘助记符;使用`&&`显示字面和号。按\*\*Alt+\*\*标记字符将焦点移到TAB顺序中的下一个控件——框架本身不获取焦点。 [**BorderStyle**](#borderstyle)选择标准带标题单线边框(**vbFixedSingleBorder**,默认)和无边框模式(**vbNoBorder**)。在**vbNoBorder**模式下,标准分组框渲染被完全绕过——既不绘制线条也不绘制标题文本——框架成为纯矩形区域。[**Appearance**](#appearance)进一步选择标准边框的3-D和平面变体。 ## OptionButton 分组 每个框架定义自己的选项按钮组。当用户选择父级为此框架的[**OptionButton**](/official/Reference/VB/OptionButton/)时,同一框架上的所有其他选项按钮会自动清除,但窗体上(或同级框架中)的选项按钮不受影响。使用框架在同一窗体上呈现多个独立的单选式选择: ```vb ' Two independent option-button groups on one form: ' fraSize: optSmall, optMedium, optLarge ' fraColour: optRed, optGreen, optBlue ``` ## 透明度和不透明度 [**Opacity**](#opacity)和[**TransparencyKey**](#transparencykey)启用了Windows的分层窗口功能。将[**Opacity**](#opacity)设置为100以下会使框架及其包含的控件半透明;将[**TransparencyKey**](#transparencykey)设置为某种颜色会使该颜色的像素在屏幕上完全透明。这两个功能在框架包含子控件时需要Windows 8或更高版本——否则仅影响框架自身的背景。 ## 属性 ### Anchors 决定框架的哪些边随父级对应边调整的边集合。只读——通过返回的**Anchors**对象设置各个`.Left`、`.Top`、`.Right`、`.Bottom`标志。 ### Appearance 决定操作系统绘制框架边框的方式。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。 ### BackColor 框架客户区的背景色,作为**OLE\_COLOR**。默认为系统3D表面颜色。绘制在包含控件的后面。 ### BorderStyle 框架边框的样式。[**ControlBorderStyleConstants**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants)的成员:**vbFixedSingleBorder**(1,默认——带标题的分组框线条)或**vbNoBorder**(0)。使用**vbNoBorder**时标题也被抑制,框架成为无边框背景面板。 ### Caption 沿框架边框顶部边缘渲染的文本。**String**。**默认属性。** 语法:*object*.**Caption** \[ = *string* ] 和号将下一个字符标记为助记符;`&&`产生字面和号。字符串直接从底层窗口读取——赋值给**Caption**会立即更新渲染。 ### ClipControls 在绘制期间子控件是否被裁剪出框架的绘制区域。**Boolean**,默认**True**。在运行时更改**ClipControls**会重新创建底层窗口。 ### Container 承载此框架的控件——通常是窗体或其他框架。用**Get**读取,用**Set**更改。设置**Container**在运行时将框架重新设置为其他容器的子级。 ### ControlType 标识此控件为框架的只读[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值。始终为**vbFrame**。 ### Dock 框架在其容器中的停靠位置。[**DockModeConstants**](/official/Reference/VBRUN/Constants/DockModeConstants)的成员:**vbDockNone**(默认)、**vbDockLeft**、**vbDockTop**、**vbDockRight**、**vbDockBottom**或**vbDockFill**。停靠的框架忽略[**Anchors**](#anchors)。 ### DragIcon 在框架被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 框架是否应在用户按住鼠标时自行拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual**(0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic**(1)。 ### Enabled 决定框架及其包含的控件是否接受用户输入。禁用的框架会使内容变暗,忽略鼠标和键盘交互。**Boolean**,默认**True**。更改**Enabled**会触发立即重绘以使边框反映新状态。 ### Font 用于渲染[**Caption**](#caption)的**StdFont**。便捷属性**FontBold**、**FontItalic**、**FontName**、**FontSize**、**FontStrikethru**和**FontUnderline**读写此对象的对应成员。 ### FontBold `Font.Bold`的快捷方式。**Boolean**。 ### FontItalic `Font.Italic`的快捷方式。**Boolean**。 ### FontName `Font.Name`的快捷方式。**String**。 ### FontSize `Font.Size`的快捷方式。**Single**,以磅为单位。 ### FontStrikethru `Font.Strikethrough`的快捷方式。**Boolean**。 ### FontUnderline `Font.Underline`的快捷方式。**Boolean**。 ### ForeColor 用于绘制[**Caption**](#caption)的颜色,作为**OLE\_COLOR**。默认为系统按钮文本颜色。 ### Height 框架的高度,默认以缇为单位(或以容器的**ScaleMode**单位)。**Double**。 ### HelpContextID 标识应用程序帮助文件中主题的**Long**,当用户在框架下方有活动控件时调用上下文帮助时检索。 ### hWnd 框架的Win32窗口句柄,作为**LongPtr**。只读。适用于传递给API函数。 ### Index 当框架是控件数组的一部分时,此实例在数组中的**Long**零基索引。在非数组实例上读取**Index**会引发运行时错误343(*对象不是数组*)。运行时只读。 ### Left 从容器左边缘到框架左边缘的水平距离。**Double**。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针在框架上方时用作鼠标光标的**StdPicture**。 ### MousePointer 指针在框架上方(且不在有自身设置的子控件上方)时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### MultiFramePosition 当框架承载在[**MultiFrame**](/official/Reference/VB/MultiFrame/)布局容器内时,此框架在**MultiFrame**有序序列中的**Long**零基位置。默认`-1`(未分配位置)。在**MultiFrame**外部该值被忽略。 ### MultiFrameSize 当框架承载在[**MultiFrame**](/official/Reference/VB/MultiFrame/)内时,其尺寸作为**MultiFrame**可用范围的百分比(`0`表示"均匀共享")。**Double**。在**MultiFrame**外部该值被忽略。 ### Name 框架在其父窗体上的唯一设计时名称。运行时只读。 ### OLEDropMode 框架如何响应OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**或**vbOLEDropManual**。Frame不支持自动放置模式;赋值**vbOLEDropAutomatic**会引发运行时错误5。 ### Opacity 框架的不透明度百分比(0--100,默认100)。超出范围的值在**Initialize**时被钳制。低于100的值在框架有子控件时需要Windows 8或更高版本;进程外子窗口不受影响。 ### OriginalMultiFramePosition [**MultiFrame**](/official/Reference/VB/MultiFrame/)上次重排时框架的[**MultiFramePosition**](#multiframeposition)。**Long**,默认`-1`。由**MultiFrame**布局引擎在框架移动后用于压缩位置;通常不从用户代码写入。 ### Parent 对最终包含框架的[**Form**](/official/Reference/VB/Form/)(或**UserControl**)的引用。只读。与[**Container**](#container)不同,后者返回直接父级(窗体*或*封闭框架)。 ### RightToLeft ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: ### TabIndex 框架在窗体TAB键导航顺序中的位置。**Long**。框架本身不接收焦点,但**TabIndex**控制框架的助记符将焦点转发到哪里:**Alt+**标记字符移到**TabIndex**大于此值的下一个可聚焦控件。 ### Tag 应用程序可用于将自定义数据与框架关联的自由格式**String**。框架忽略此属性。 ### ToolTipText 用户悬停在框架边框或背景上方时作为工具提示显示的多行**String**。 ### Top 从容器顶部到框架顶部的垂直距离。**Double**。 ### TransparencyKey 设置后成为渲染框架中完全透明的**OLE\_COLOR**——点击穿过到下面内容,相应像素不绘制。默认`-1`禁用效果。框架有子控件时需要Windows 8或更高版本。 ### Visible 框架及其包含的控件是否显示。**Boolean**,默认**True**。 ### VisualStyles 绘制框架边框和标题时是否使用操作系统主题引擎。**Boolean**,默认**True**。 ### WhatsThisHelpID ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。参见[**ShowWhatsThis**](#showwhatsthis)。 ::: ### Width 框架的宽度。**Double**。 ## 方法 ### Drag 开始、完成或取消手动拖放操作。通常在[**DragMode**](#dragmode)为**vbManual**时从[**MouseDown**](#mousedown)处理程序调用。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel**(0)、**vbBeginDrag**(1,默认)或**vbEndDrag**(2)。 ### Move 在单次调用中重新定位并可选地调整框架的尺寸。包含的控件随其重新定位。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从框架发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### Refresh 强制立即重绘框架及其边框。 语法:*object*.**Refresh** ### SetFocus 尝试将输入焦点移到框架。由于框架不可聚焦,此调用对哪个控件持有焦点没有可见效果,但提供它是为了与控件API其余部分保持一致,以及与通用调用**SetFocus**的代码兼容。 语法:*object*.**SetFocus** ### ShowWhatsThis ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: 语法:*object*.**ShowWhatsThis** ### ZOrder 将框架带到容器内同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront**(0,默认)或**vbSendToBack**(1)。 ## 事件 ### Click 当用户单击框架的客户区或边框(即不在任何包含的控件上方)时引发。**默认事件。** 语法:*object*\_**Click**( ) ### DblClick 当用户双击框架的客户区或边框时引发。 语法:*object*\_**DblClick**( ) ### DragDrop 当手动拖动操作在此框架上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 当手动拖动操作在框架上方进行时在框架上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### Initialize 在框架的底层窗口已创建但尚未填充任何包含的控件后引发一次。适用于设置框架子级在其自身初始化时将读取的初始值。 语法:*object*\_**Initialize**( ) ### MouseDown 当用户在框架的客户区或边框上方按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 当光标在框架的客户区或边框上方移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 当用户在框架的客户区或边框上方释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseWheel 当鼠标滚轮在框架上方转动时引发。twinBASIC新增。 语法:*object*\_**MouseWheel**( *Delta* **As Integer**, *Horizontal* **As Boolean** ) ### OLECompleteDrag 当OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 当用户在框架上放置数据时在框架上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver 当OLE拖动经过框架时在框架上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 在拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的格式的数据时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag 在OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) --- --- url: /en/packages/vbccr/system/framew.md description: >- FrameW Control - VBCCR Development Manual, Complete API Reference Based on Source Code --- # FrameW Control Provides a container frame control that supports visual styles, transparent background, and image display. Can serve as a container for other controls. ## Enumerations No proprietary public enumerations. Uses the following common enumerations: CCAppearanceConstants, CCLeftRightAlignmentConstants, CCMousePointerConstants, CCRightToLeftModeConstants, OLEDropModeConstants. ## Properties ### Name ```vb Property Get Name() As String ``` Returns the name of the control. ### Tag ```vb Property Get/Let Tag() As String ``` Returns/sets the tag value of the control. ### Parent ```vb Property Get Parent() As Object ``` Returns the parent object of the control. ### Container ```vb Property Get/Set Container() As Object ``` Returns/sets the container of the control. ### Left ```vb Property Get/Let Left() As Single ``` Returns/sets the position of the left edge of the control. ### Top ```vb Property Get/Let Top() As Single ``` Returns/sets the position of the top edge of the control. ### Width ```vb Property Get/Let Width() As Single ``` Returns/sets the width of the control. ### Height ```vb Property Get/Let Height() As Single ``` Returns/sets the height of the control. ### Visible ```vb Property Get/Let Visible() As Boolean ``` Returns/sets whether the control is visible. ### ToolTipText ```vb Property Get/Let ToolTipText() As String ``` Returns/sets the tooltip text of the control. ### WhatsThisHelpID ```vb Property Get/Let WhatsThisHelpID() As Long ``` Returns/sets the "What's This" Help ID of the control. ### DragIcon ```vb Property Get/Let/Set DragIcon() As IPictureDisp ``` Returns/sets the icon displayed during drag operations. ### DragMode ```vb Property Get/Let DragMode() As Integer ``` Returns/sets the drag mode (manual or automatic). ### hWnd ```vb Property Get hWnd() As LongPtr ``` Returns the window handle of the control. ### Font ```vb Property Get/Let/Set Font() As StdFont ``` Returns/sets the font used by the control. ### VisualStyles ```vb Property Get/Let VisualStyles() As Boolean ``` Returns/sets whether visual styles are enabled. ### Appearance ```vb Property Get/Let Appearance() As CCAppearanceConstants ``` Returns/sets the visual appearance of the control. See Common Enumerations. ### BackColor ```vb Property Get/Let BackColor() As OLE_COLOR ``` Returns/sets the background color of the control. ### ForeColor ```vb Property Get/Let ForeColor() As OLE_COLOR ``` Returns/sets the foreground color of the control (caption text color). ### Enabled ```vb Property Get/Let Enabled() As Boolean ``` Returns/sets whether the control is enabled. ### OLEDropMode ```vb Property Get/Let OLEDropMode() As OLEDropModeConstants ``` Returns/sets the OLE drop mode. See Common Enumerations. ### MousePointer ```vb Property Get/Let MousePointer() As CCMousePointerConstants ``` Returns/sets the mouse pointer type. See Common Enumerations. ### MouseIcon Not available. The frame control does not support custom mouse icons. ### MouseTrack ```vb Property Get/Let MouseTrack() As Boolean ``` Returns/sets whether mouse enter/leave tracking is enabled. ### RightToLeft ```vb Property Get/Let RightToLeft() As Boolean ``` Returns/sets whether right-to-left layout is enabled. ### RightToLeftMode ```vb Property Get/Let RightToLeftMode() As CCRightToLeftModeConstants ``` Returns/sets the right-to-left mode. See Common Enumerations. ### BorderStyle ```vb Property Get/Let BorderStyle() As Integer ``` Returns/sets the border style of the control. Values: 0 (vbBSNone) no border, 1 (vbFixedSingle) fixed single border. ### Caption ```vb Property Get/Let Caption() As String ``` Returns/sets the frame caption text. ### UseMnemonic ```vb Property Get/Let UseMnemonic() As Boolean ``` Returns/sets whether the & character in the caption acts as an access key. ### Alignment ```vb Property Get/Let Alignment() As VBRUN.AlignmentConstants ``` Returns/sets the alignment of the caption. ### Transparent ```vb Property Get/Let Transparent() As Boolean ``` Returns/sets whether the control is transparent. ### Picture ```vb Property Get/Let/Set Picture() As IPictureDisp ``` Returns/sets the image displayed in the frame. ### PictureAlignment ```vb Property Get/Let PictureAlignment() As CCLeftRightAlignmentConstants ``` Returns/sets the alignment of the image. See Common Enumerations. ### ContainedControls ```vb Property Get ContainedControls() As VBRUN.ContainedControls ``` Returns the collection of controls contained by the frame. Read-only. ## Methods ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag operation. ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` Starts, ends, or cancels a drag operation. ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` Sets the Z-order position of the control within its layer. ### Refresh ```vb Public Sub Refresh() ``` Forces a complete repaint of the control. ## Events ### Click ```vb Public Event Click() ``` Occurs when the control is clicked. ### DblClick ```vb Public Event DblClick() ``` Occurs when the control is double-clicked. ### Resize ```vb Public Event Resize() ``` Occurs when the control is resized. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when a mouse button is pressed. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when the mouse is moved. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when a mouse button is released. ### MouseEnter ```vb Public Event MouseEnter() ``` Occurs when the mouse enters the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Occurs when the mouse leaves the control. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` Occurs on the source control after an OLE drag-and-drop operation is completed or cancelled. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when data is dropped onto the control via an OLE drag-and-drop operation. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` Occurs when the mouse moves over the control during an OLE drag-and-drop operation. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` Occurs on the source control when the mouse cursor needs to be changed during an OLE drag-and-drop operation. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` Occurs on the source control when the drop target requests data. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` Occurs when an OLE drag-and-drop operation is started. ## Code Examples ### Basic Usage ```vb Private Sub Form_Load() With FrameW1 .Caption = "Option Settings" .BorderStyle = vbFixedSingle .UseMnemonic = True .Alignment = vbLeftJustify .VisualStyles = True End With End Sub Private Sub FrameW1_Resize() Debug.Print "Frame size: " & FrameW1.Width & " x " & FrameW1.Height End Sub ``` --- --- url: /en/official/Reference/CustomControls/Framework.md --- # Framework The framework half of the [**CustomControls**](/en/official/Reference/CustomControls/) package --- the interfaces, callback objects, and drawing primitives an *author* of a custom control writes against. The eight concrete `Waynes…` controls in the package are themselves built on this framework; the same pieces are available to user code that needs to implement an entirely new custom control. A custom control: 1. Implements [**ICustomControl**](/en/official/Reference/CustomControls/Framework/ICustomControl) (or [**ICustomForm**](/en/official/Reference/CustomControls/Framework/ICustomForm) for a form-class custom control). 2. Stores the [**CustomControlContext**](/en/official/Reference/CustomControls/Framework/CustomControlContext) passed to it on **Initialize** and uses it to request repaints, create timers, or change the focused element. 3. Inside **Paint**, builds one or more `ElementDescriptor` records and passes them to the [**Canvas**](/en/official/Reference/CustomControls/Framework/Canvas) via **RuntimeUICCCanvasAddElement** --- the framework rasterises them, handles input routing, and dispatches events back through the descriptor's `AddressOf`-registered callbacks. ```vb Class MyControl Implements CustomControls.ICustomControl Private Context As CustomControls.CustomControlContext Private Sub OnInitialize(ByVal Ctx As CustomControls.CustomControlContext) _ Implements CustomControls.ICustomControl.Initialize Set Me.Context = Ctx End Sub Private Sub OnDestroy() _ Implements CustomControls.ICustomControl.Destroy End Sub Private Sub OnPaint(ByVal Canvas As CustomControls.Canvas) _ Implements CustomControls.ICustomControl.Paint ' build ElementDescriptor records and call Canvas.RuntimeUICCCanvasAddElement End Sub End Class ``` ## Interfaces * [ICustomControl](/en/official/Reference/CustomControls/Framework/ICustomControl) -- the interface implemented by every concrete custom control: **Initialize**, **Destroy**, **Paint** * [ICustomForm](/en/official/Reference/CustomControls/Framework/ICustomForm) -- the analogous interface for custom form classes ## Callback objects * [CustomControlContext](/en/official/Reference/CustomControls/Framework/CustomControlContext) -- the callback object passed to **Initialize**; **GetSerializer**, **Repaint**, **CreateTimer**, **ChangeFocusedElement** * [CustomFormContext](/en/official/Reference/CustomControls/Framework/CustomFormContext) -- a **CustomControlContext** extended with **Show** and **Close**, passed to a custom form's **Initialize** * [CustomControlTimer](/en/official/Reference/CustomControls/Framework/CustomControlTimer) -- the timer returned by **CustomControlContext.CreateTimer**; **Interval**, **Enabled**, **OnTimer** event * [CustomControlsCollection](/en/official/Reference/CustomControls/Framework/CustomControlsCollection) -- the **Controls** collection on a [**WaynesForm**](/en/official/Reference/CustomControls/WaynesForm/) or any other custom form ## Drawing primitives * [Canvas](/en/official/Reference/CustomControls/Framework/Canvas) -- the drawing surface passed to **Paint**; **RuntimeUICCCanvasAddElement**, plus size and DPI accessors * [SerializeInfo](/en/official/Reference/CustomControls/Framework/SerializeInfo) -- the per-instance serializer returned by **CustomControlContext.GetSerializer**; **RuntimeUISrzDeserialize**, design-mode flags, owner handle, runtime mode --- --- url: /zh/official/Reference/CustomControls/Framework.md --- # Framework [**CustomControls**](/official/Reference/CustomControls/) 包的框架部分——自定义控件*作者*编写时所针对的接口、回调对象和绘图基元。包中的八个具体 `Waynes…` 控件本身就是基于此框架构建的;相同的组件可用于需要实现全新自定义控件的用户代码。 自定义控件: 1. 实现 [**ICustomControl**](/official/Reference/CustomControls/Framework/ICustomControl)(或窗体类自定义控件的 [**ICustomForm**](/official/Reference/CustomControls/Framework/ICustomForm))。 2. 存储在 **Initialize** 时传入的 [**CustomControlContext**](/official/Reference/CustomControls/Framework/CustomControlContext),用于请求重绘、创建定时器或更改焦点元素。 3. 在 **Paint** 内部,构建一个或多个 `ElementDescriptor` 记录并通过 **RuntimeUICCCanvasAddElement** 传递给 [**Canvas**](/official/Reference/CustomControls/Framework/Canvas)——框架对其进行光栅化、处理输入路由,并通过描述符的 `AddressOf` 注册回调分发事件。 ```vb Class MyControl Implements CustomControls.ICustomControl Private Context As CustomControls.CustomControlContext Private Sub OnInitialize(ByVal Ctx As CustomControls.CustomControlContext) _ Implements CustomControls.ICustomControl.Initialize Set Me.Context = Ctx End Sub Private Sub OnDestroy() _ Implements CustomControls.ICustomControl.Destroy End Sub Private Sub OnPaint(ByVal Canvas As CustomControls.Canvas) _ Implements CustomControls.ICustomControl.Paint ' build ElementDescriptor records and call Canvas.RuntimeUICCCanvasAddElement End Sub End Class ``` ## 接口 * [ICustomControl](/official/Reference/CustomControls/Framework/ICustomControl) —— 每个具体自定义控件实现的接口:**Initialize**、**Destroy**、**Paint** * [ICustomForm](/official/Reference/CustomControls/Framework/ICustomForm) —— 自定义窗体类的相应接口 ## 回调对象 * [CustomControlContext](/official/Reference/CustomControls/Framework/CustomControlContext) —— 传递给 **Initialize** 的回调对象;**GetSerializer**、**Repaint**、**CreateTimer**、**ChangeFocusedElement** * [CustomFormContext](/official/Reference/CustomControls/Framework/CustomFormContext) —— 扩展了 **CustomControlContext** 的 **Show** 和 **Close**,传递给自定义窗体的 **Initialize** * [CustomControlTimer](/official/Reference/CustomControls/Framework/CustomControlTimer) —— 由 **CustomControlContext.CreateTimer** 返回的定时器;**Interval**、**Enabled**、**OnTimer** 事件 * [CustomControlsCollection](/official/Reference/CustomControls/Framework/CustomControlsCollection) —— [**WaynesForm**](/official/Reference/CustomControls/WaynesForm/) 或任何其他自定义窗体上的 **Controls** 集合 ## 绘图基元 * [Canvas](/official/Reference/CustomControls/Framework/Canvas) —— 传递给 **Paint** 的绘图表面;**RuntimeUICCCanvasAddElement**,以及大小和 DPI 访问器 * [SerializeInfo](/official/Reference/CustomControls/Framework/SerializeInfo) —— 由 **CustomControlContext.GetSerializer** 返回的每实例序列化器;**RuntimeUISrzDeserialize**、设计模式标志、所有者句柄、运行时模式 --- --- url: /en/official/Reference/VBA/FileSystem/FreeFile.md --- # FreeFile Returns an **Integer** representing the next file number available for use by the **Open** statement. Syntax: **FreeFile** \[ **(** *rangenumber* **)** ] *rangenumber* : *optional* **Variant** that specifies the range from which the next free file number is to be returned. Specify **0** (default) to return a file number in the range 1--255, inclusive. Specify **1** to return a file number in the range 256--511. Use **FreeFile** to supply a file number that is not already in use. ### Example This example uses the **FreeFile** function to return the next available file number. Five files are opened for output within the loop, and some sample data is written to each. ```vb Dim MyIndex, FileNumber For MyIndex = 1 To 5 ' Loop 5 times. FileNumber = FreeFile ' Get unused file number. Open "TEST" & MyIndex For Output As #FileNumber ' Create file name. Write #FileNumber, "This is a sample." ' Output text. Close #FileNumber ' Close file. Next MyIndex ``` --- --- url: /zh/official/Reference/VBA/FileSystem/FreeFile.md --- # FreeFile 返回一个**Integer**,表示**Open**语句可用的下一个文件号。 语法:**FreeFile** \[ **(** *rangenumber* **)** ] *rangenumber* : *可选* **Variant**,指定返回下一个空闲文件号的范围。指定**0**(默认)返回1--255范围内的文件号。指定**1**返回256--511范围内的文件号。 使用**FreeFile**提供一个尚未使用的文件号。 ### 示例 本示例使用**FreeFile**函数返回下一个可用的文件号。在循环中打开五个文件进行输出,并向每个文件写入一些示例数据。 ```vb Dim MyIndex, FileNumber For MyIndex = 1 To 5 ' Loop 5 times. FileNumber = FreeFile ' Get unused file number. Open "TEST" & MyIndex For Output As #FileNumber ' Create file name. Write #FileNumber, "This is a sample." ' Output text. Close #FileNumber ' Close file. Next MyIndex ``` --- --- url: /en/official/Reference/VBA/HiddenModule/FreeMem.md --- # FreeMem Releases a block of memory previously obtained from [**AllocMem**](/en/official/Reference/VBA/HiddenModule/AllocMem). Syntax: **FreeMem** *MemPointer* *MemPointer* : *required* **LongPtr**. The address returned by a previous call to [**AllocMem**](/en/official/Reference/VBA/HiddenModule/AllocMem). The pointer is invalid after the call returns. Passing a pointer that did not come from **AllocMem** --- including zero, or one that has already been freed --- has undefined behaviour. ### Example This example allocates a buffer, uses it, and then releases it with **FreeMem**. ```vb Dim buf As LongPtr = AllocMem(256) ' ... write and read buf ... FreeMem buf ' release the block; buf is invalid after this point ``` ### See Also * [AllocMem](/en/official/Reference/VBA/HiddenModule/AllocMem) function --- --- url: /zh/official/Reference/VBA/HiddenModule/FreeMem.md --- # FreeMem 释放先前从[**AllocMem**](/official/Reference/VBA/HiddenModule/AllocMem)获取的内存块。 语法:**FreeMem** *MemPointer* *MemPointer* : *必需* **LongPtr**。先前调用[**AllocMem**](/official/Reference/VBA/HiddenModule/AllocMem)返回的地址。 调用返回后该指针无效。传递非**AllocMem**产生的指针——包括零或已释放的指针——具有未定义行为。 ### 示例 本示例分配一个缓冲区,使用它,然后用**FreeMem**释放它。 ```vb Dim buf As LongPtr = AllocMem(256) ' ... write and read buf ... FreeMem buf ' release the block; buf is invalid after this point ``` ### 另请参阅 * [AllocMem](/official/Reference/VBA/HiddenModule/AllocMem)函数 --- --- url: /en/official/Miscellaneous/FAQs.md --- # Frequently Asked Questions ### [General](#general) - [Installation](#install-section) - [Using twinBASIC](#using-twinbasic) ## General ::: details What is twinBASIC? twinBASIC is a new BASIC language and development environment (IDE) aiming to be 100% backwards compatible with VB6/VBA. ::: ::: details Who is behind twinBASIC? twinBASIC is the work of Wayne Phillips, who operates the company [Everything Access](https://www.everythingaccess.com/), a well established provider of professional tools and services for Microsoft Access and VBA generally, including the popular vbWatchdog software. ::: ::: details Where can I get twinBASIC? The latest version can be downloaded from the [Releases section](https://github.com/twinbasic/twinbasic/releases) of the [main twinBASIC GitHub repository](https://github.com/twinbasic/twinbasic). See [How do I install twinBASIC](#installation) for more information on installation. ::: ::: details What is the current status of the project? twinBASIC is currently late into the **Beta** stage, under development and not yet at a stable 1.0 release. All of the VB6/VBA7 syntax and intrinsic functions have been implemented. All of the basic controls except the OLE control, and about half of the Common Controls, have been implemented. It supports Forms, Classes, and UserControls-- both as compiled OCX/DLL controls and as in-project code (i.e. like .ctl files). However, not all features of these, such as properties, events, and methods, have been completed. Additionally, ActiveX EXEs and VBG project group support are not yet implemented, and there's a fair number of bugs remaining. However, **tB can already run many existing projects**, even fairly complex and large ones. Many community members have managed to get their apps and other open source apps up and running with little to no difficulty, and created new projects from scratch. Check out these examples for a good real world demonstrate of how far along the project is: Krool's [VBCCR](https://github.com/Kr00l/VBCCR) and [VBFlexGrid](https://github.com/Kr00l/VBFLXGRD) controls, Ben Clothier's [TwinBasicSevenZip](https://github.com/bclothier/TwinBasicSevenZip), Carles PV's [Lemmings](https://github.com/fafalone/Lems64), Don Jarrett's [basicNES](https://github.com/fafalone/basicNES) Nintendo emulator, and Jon Johnson's [ucShellBrowse/ucShellTree](https://github.com/fafalone/ShellControls), [FileActivityMon ETW Event Tracer](https://github.com/fafalone/EventTrace), [cTaskDialog](https://github.com/fafalone/cTaskDialog64), and [many more](https://github.com/fafalone). ::: ::: details Is there an estimated timeline for when expected features will become available? Yes, see the [twinBASIC Roadmap](https://github.com/twinbasic/twinbasic/issues/335) in the Issues section for the latest update to the timeline. This roadmap only covers major components; smaller features are implemented in a less formal manner, usually when the related part of the codebase is being worked on. ::: ::: details What new features does twinBASIC have compared to VB6? **Many!** It has 64bit compilation (using VBA7x64 compatible syntax), generics, overloading, multithreading (API-only right now, built in syntax coming soon), inheritance, ability to define interfaces and coclasses in your project using BASIC-style syntax, Unicode support in all controls and the editor (.twin files only), support for modern image formats, numerous enhancements to *Implements*, ability to create standard DLLs and kernel mode drivers, ability to set UDT packing alignment, and dozens of others, all available *right now*, with many more planned in the future. For a full list of all the new features available right now, see the Wiki article [Overview of features new to twinBASIC](/en/official/Features/). ::: ::: details Where can I learn more about twinBASIC, find documentation, and participate in the community? [twinBASIC Home Page](https://twinbasic.com) twinBASIC GitHub: [Main section](https://github.com/twinbasic/twinbasic) | [Issues](https://github.com/twinbasic/twinbasic/issues) | [Discussions](https://github.com/twinbasic/twinbasic/discussions) | [Language Design](https://github.com/twinbasic/lang-design) | [ Language Specification](https://github.com/twinbasic/lang-spec) | [Documentation](https://docs.twinbasic.com) [twinBASIC Discord](https://discord.gg/UaW9GgKKuE) [twinBASIC Forum on VBForums](https://www.vbforums.com/forumdisplay.php?108-TwinBASIC) ::: ::: details Is twinBASIC Open Source? While open source models are possible in the future, at this time the compiler is not. There are plans in the works to open source the IDE. To address some of the major concerns this presents, once tB hits it first major release, the source code will be placed in escrow, to be released to the community in the event the author disappears or is unable to continue working on it due to death or serious illness/injury. ::: ::: details How much does twinBASIC cost? There are 3 editions of twinBASIC: The Community Edition is FREE. A splash screen is placed on compiled 64bit binaries and certain features like advanced optimized compilation and future cross-platform compilation are unavailable, but there are no restrictions on core language features or royalties imposed. To get those features, subscriptions are available for the Professional and Ultimate editions. For more details, including current pricing for Professional and Ultimate editions, [see this page](https://twinbasic.com/preorder.html). **Note:** You can change the subscription level at any time and the community edition is always available. There will be no lockout (see [the previous statement regarding escrow](#open-source)) so you will always have the ability to develop, test and compile. ::: ::: details Can I pay a one-time fee for a perpetual license? Due to the need for continuing income to be able to develop twinBASIC, subscriptions are the primary model for premium versions, which [are available](https://twinbasic.com/preorder.html) on a month-to-month or yearly basis. However, right now for a limited time, a buy-once perpetual license is available in the form of the [VIP Gold Lifetime Licence Initiative](https://twinbasic.com/vip.html). This provides not only a lifetime license to twinBASIC including updates and new versions, but numerous additional benefits available only to people who purchase this license. ::: ::: details Can twinBASIC be used to develop commercial products, and what royalties are owed? There are no restrictions on any edition of twinBASIC; they can all be used to develop commercial products, on a ROYALTY FREE basis. Nothing is owed for selling programs or other products created with twinBASIC. The twinBASIC software itself, however, may not be redistributed without appropriate license. ::: ::: details What does '100% backwards compatible' mean, technically? Backwards compatibility refers to matching all publicly documented syntax, included controls, component and control behavior, and control appearance. It does not include undocumented, proprietary internal implementation details. So for example all language keywords, functions, and methods are present and should give the same results, and Forms/Classes/UserControls should implement all the same publicly documented interfaces, but twinBASIC exe files are not internally structured in the same way, and there isn't compatibility with the undocumented VB project info structures in the exe, whose contents have been reverse engineered over the years by the community. Currently, all basic controls have reimplementations in twinBASIC that support Unicode and 64bit compilation except the OLE control; and a number of the primary Common Controls have also been reimplemented. Eventually, all controls shipped with VB6 Enterprise Edition will be reimplemented. Until that time, the original controls will still work in 32bit builds, and community members provide some alternatives, for example Krool's VBCCR controls and VBFlexGrid control all work and have 64bit-compatible twinBASIC versions. ::: ::: details So some of my projects won't work? Most projects do not use these reverse engineered internals, but some do: most commonly, for self-subclassing and callbacks inside Forms/Classes/UserControls; and also for multithreading and inline assembly. These routines have native support in twinBASIC without requiring internals hacks, so replacing these small parts of a few programs is very simple: `AddressOf` is supported on class members, so you can use regular subclassing and callback methods as you would if they were in a .bas module. `CreateThread` can be called without any special steps. And tB supports statically linked .obj files allowing incorporation of code from other languages, inline assembly in the form of `Emit()`/`EmitAny()` to insert instructions, and further support is planned in the future. Additionally, twinBASIC redirects the most common msvbvm60.dll (also msvbvm50.dll/vbe6.dll/vbe7.dll) functions used as `Declare` statements by users, all of which also work in x64, if you add the `PtrSafe` keyword like any other DLL definition. The following functions currently have redirects: `VarPtr, GetMem1, GetMem2, GetMem4, GetMem8, PutMem1, PutMem2, PutMem4, PutMem8, __vbaObjSet, __vbaObjSetAddRef, __vbaObjAddRef, __vbaCastObj, __vbaCopyBytes, __vbaCopyBytesZero, __vbaRefVarAry`, and `__vbaAryMove`. You may continue to use these with `Declare` statements to support the particular signatures you prefer. Further, declares for olepro32.dll are redirected to identical functions in oleaut32.dll, as olepro32 was deprecated by NT4 and doesn't have a 64bit version. Other than those special cases, it's exceedingly rare for projects to depend on reverse engineered internals. So the vast majority of projects run with zero modification. ::: ::: details How do I report bugs or other problems? The best way is to [create an issue](https://github.com/twinbasic/twinbasic/issues) in the twinBASIC GitHub repository. You can also create a post in the #bugs channel of the [twinBASIC Discord server](https://discord.gg/UaW9GgKKuE). ::: ::: details Is the twinBASIC IDE available in other languages? The IDE currently has basic support for localizing all of the front end UI, with translations supplied by members of the community. These can be obtained from [#langpacks on the tB Discord server](https://discord.com/channels/927638153546829845/1329533568376115282), there's currently around 10 including French, German, Italian, Portuguese, Russian, Chinese (Simplified), Chinese (Traditional), Japanese, Swedish, Hungarian, Greek, Catalan, Indonesian (Bahasa), and Malayalam. Others may have been posted since this was written; check the channel. Internal text such as the hover information does not yet support localization, but this is planned for the future. ::: ## Installation ::: details What are the system requirements for twinBASIC? The twinBASIC IDE is supported on Windows 7 through Windows 11. The installation is portable; you need only to extract the downloaded zip file then run; there's no installer. WebView2 is required. This is normally preinstalled on newer versions of Windows, and is installed along with Edge if you've installed that browser. You can also obtain it from [Microsoft's website](https://developer.microsoft.com/en-us/microsoft-edge/webview2?form=MA13LH#download-section). Select the Standalone Evergreen x86 version: ![image](/assets/94490c87-fafe-4d5b-ae39-d3cedba1c21d.DwCaeyAN.png) ::: ::: details twinBASIC won't run; says there's an invalid entry point. This issue is sometimes encountered on Windows 7. To be used on Windows 7, the OS must be fully updated; this error results from one or more missing updates. Run Windows Update to make sure you have all recent updates installed. If you still have problems, you can drop by the Discord or submit an issue on GitHub (see [`How do I report bugs or other problems?`](#bug-reporting)) ::: ::: details The IDE reports missing files when I try to launch it. If, when launching the twinBASIC IDE, you are notified of missing files, the most likely reason is that the anti-virus software installed on your PC has quarantined some of the files needed by twinBASIC, mistakenly thinking that they contain a virus or other malware. Such erroneous detections are common with newly released software, so please be assured this is just a false-positive detection --- see also [the previous entry](#false-scanner-alerts) for context. To get the twinBASIC IDE to launch successfully, configure your anti-virus software to disregard the twinBASIC executable files (EXEs and DLLs) within the root folder, and the `bin` subfolder. This usually means adding the root folder and the `bin` subfolder to an 'exception list' in your anti-virus software. After restoring the missing EXE and DLL files, you should find that launching the IDE via the `twinBASIC.exe` file works as expected. Please direct all negative emotions to your overactive anti-virus vendor :) ::: ::: details How do I install twinBASIC? tB does not require a full installation process, you need only extract the ZIP file. Download the latest version from the [Releases page](https://github.com/twinbasic/twinbasic/releases), named `twinBASIC_IDE_BETA_xxx.zip` (where xxx is a version number; click on 'Assets' to expand the file list if it's not already visible). ![img](/assets/ac019c1a-dcef-4964-a730-bc5b86c644ba.B4g1v4Fw.png) Download the zip and extract it to an **empty** folder. Do not simply overwrite a previous version; either delete everything in the folder or use a different one. Odd errors have been known to occur otherwise. It will run from this folder; some settings will be placed in AppData. ::: ::: details How big is the twinBASIC installation? The IDE is quite small, it's currently only a 25MB download, about 80MB extracted, and that is half due to LLVM libraries. ::: ::: details Where is twinBASIC IDE data stored? In addition to the directory you extract the IDE to, twinBASIC stores files and settings in several locations: * `%APPDATA%\Local\twinBASIC` * `%APPDATA%\Local\twinBASIC_Admin` * `%APPDATA%\Local\twinBASIC_WebPanel` * `%APPDATA%\Local\twinBASIC_WebPanel_Admin` (WebView2 user folders, this is for the IDE itself and not directly related to files/settings you interact with. Some of these folders may not exist.) * `%APPDATA%\Roaming\twinBASIC` (storage of themes, linked packages, and other files that you want to keep when deleting previous installs) * and in the registry under `HKEY_CURRENT_USER\Software\VB and VBA Program Settings\twinBASIC_IDE` (current IDE configuration info; recent project list, panel layouts, license info, selected theme, keyboard shortcuts, etc) ::: ::: details Is twinBASIC safe? (Some scanner) says it's malicious. Anyone who has ever tested their own programs against a wide variety of AV engines knows that unless your exe is 64bit and signed with a high-level certificate (and maybe not even then, until it's manually added to a trust list), false positives in a small number are simply a way of life. twinBASIC's IDE and compiler executables, like all apps in its position, may trigger a small number of positives on services like VirusTotal, particularly 32bit apps. These are almost always not from major vendors and/or "AI" based algorithmic detection. ::: ## Using twinBASIC ::: details How do I import my VB6 project into twinBASIC? The easiest way is through the import wizard. When you first start the twinBASIC IDE, you're presented with the New Project dialog- this contains an 'Import from VBP' option: ![image](/assets/7e1cb69c-6db3-4f3f-aea1-c1fae25938a2.Tr3U6QbZ.png) You can import individual files, from VB projects or any type, through the Import option on the Add menu, under Project or by right clicking the desired folder in the Project Explorer pane: ![img](/assets/2b32ab8c-fabc-4f42-9e6b-06e85574eaf4.DIphFkYh.png) **Note:** You can select .bas/.cls files individually, but to import Forms, UserControls, Property Pages, and Resource Files you must currently select the .vbp file they're associated with. You'll then be shown a list of files you can import (with their new twinBASIC extensions .tbform/.twin etc-- make sure to import both, e.g. for Form1.frm you'll see Form1.frm.tbform and Form1.frm.twin: ![img](/assets/16833fae-4bd7-418f-bb16-691a611a5b01.DZtfkOsM.png)::: ::: details Why do I see a lot of errors saying my variables are unrecognized? ![image](/assets/e409ea37-96ad-44c5-8017-3699ef04b53d.DRKjo9w2.png) While use is strongly recommended and considered a best practice, twinBASIC **does not** require `Option Explicit`. If you're seeing these errors, you may have overlooked a new feature of twinBASIC: automatically enabling `Option Explicit` project-wide. When you import a VB6 project, or create a new one, a small dialog pops up: ![image](/assets/05306a72-4ff6-427d-8970-969ef0c582e6.oT97U_Pc.png) If you leave "Option Explicit ON" checked, that means it will be enforced project-wide, regardless of whether `Option Explicit` is used in the form/module/etc itself. If you uncheck it, you won't get any errors for it, just a warning: "This variable has been auto-declared by the compiler due to Option Explicit being OFF". If you want, you can disable that warning in Project Settings: ![image](/assets/2a1c71fd-f81c-4bd3-b61a-0f2979e8961f.2xRWHNLi.png) For an existing project, the Project Scope Option Explicit can be turned on or off from Project Settings, under "Project: Option Explicit On": ![image](/assets/01009879-fdbc-4a8e-8683-353aab6193df.BrJkHsI_.png) ::: ::: details Does twinBASIC support addins? Addins for VB6 and VBA are not supported by the twinBASIC IDE. However, tB has its own addin infrastructure based on modern web technologies. See Samples 10 through 16 in the 'Samples' tab of the New Project dialog: ![image](/assets/0e24eb5c-c9af-49a9-a908-03968b211554.D4Bh5bza.png) twinBASIC supports **creating** addins for VBA. It's currently the only tool that supports creating these addins for 64bit Office using a language with 100% compatible syntax. See Sample 4 and Sample 5. There are two locations that the addins can be installed to: 1. `%appdata%\twinBASIC\addins\` - that's the preferred location as the TwinBasic distribution itself is not modified, and the addins won't get lost when upgrading to a newer version. 2. `<twinbasic unzip folder>\addins` - if you want to modify your TwinBasic installation. This is not generally recommended. ::: ::: details How do I use resources in twinBASIC? Currently tB does not have a dedicated resource editor; instead, resources are managed through the Project Explorer. In the tree, you'll see a Resources folder; by default, it will include ICON in a Standard EXE, and MANIFEST, if you've chosen to enable Visual Styles: ![image](/assets/71ddde83-a091-47e3-b5b8-681954b0639d.C95CiN1h.png) You can create additional folders here, using their standard names. For example a BITMAP group could be added, then used with `LoadResImage`. Unlike its predecessor, tB does not restrict the type of resources: you can create any type of folder you want, and import binary data into it. For example, some community projects have inserted `UIFILE` resources for Ribbon controls and `DIALOG` resources for property sheets. Resources can be imported by right-clicking the folder you want them in, and selecting Add->Import file... from the menu. If you're importing a project, the resources in a linked .res file will be imported automatically. #### Strings String table resources are currently treated specially; they're edited in the IDE as JSON. If you import from VBP with a .res, string resources will be automatically converted. If you right click the 'Resources' folder, and go to the 'Add' submenu, at the bottom, you'll find "Add resource: String table" that adds one populated with example strings: ![image](/assets/97cc8655-7a8b-47f3-b52c-eb1ddfce662f.DnjPdcw0.png) #### Group names If you create a new folder for a standard resource type, twinBASIC currently recognizes the following names, which you should use to create a folder under Resources: BITMAP\ CUSTOM\ CURSOR\ ICON\ MANIFEST\ RCDATA\ STRING\ MESSAGETABLE For other standard types, you must use the # (pound sign) followed their number. For example, for DIALOG (RT\*DIALOG) resources, do not name the folder dialog, it must be named `#5`. ANICURSOR would be named `#21`. And so on, for the [standard types](https://learn.microsoft.com/en-us/windows/win32/menurc/resource-types) with `RT*` constants. For any others, you can use any name you want, e.g. UIFILE can just be named UIFILE. **Note:** At this time, .res files can only be imported as part of a VBP. ::: ::: details How do I set my own icon for my program? By default newly created projects use the twinBASIC logo.\ Imported projects use the icon of the Form chosen in Settings. This can be modified or set for all projects in the same way: in the Settings dialog for your project, there is an "Icon Form" option from which you can select which Form's icon will be used for your exe. If you don't set that option, or your project contains no Forms, the icon can be managed manually through the Resources folder.\ If you're not already familiar with using resources in twinBASIC, see the FAQ entry right above this one. In this scenario, the icon used for your application in Explorer is the one in the Resources\ICON folder that comes first alphabetically. If you do not have an ICON folder in your project, you can create one by right-clicking the Resources folder and selecting Add->Add folder. ![image](/assets/8611d12a-d7a6-48cc-9544-cb27c5299aa5.BD-jiLGi.png) In the above picture, MyOwnIcon.ico would be used by Explorer and other apps to represent your .exe, as it comes before twinBASIC.ico alphabetically. **Note:** This will not be set as the icon of any form; icons for forms are set by the "Icon" property in the Properties list. You may set both the Icon Form option and include additional ICON resources. In this scenario, the Icon Form will take precedence- it will be inserted as #1, making it the first possible entry and therefore being used by Explorer. Do not use #1 for any of your additional icons in Resources in this scenario, the results may be unpredictable. ::: ::: details What are the runtime requirements for twinBASIC-produced EXEs/binaries? Programs and modules/controls produced by twinBASIC have no native dependencies besides standard Windows system DLLs and are completely standalone/portable, besides of course 3rd party files your code may use. No runtime is required to be present.\ Currently the minimum supported Windows version is **Windows XP**, with Windows 2000 support likely in the future. There are no current plans to support Windows ME, 98, 95, NT4, or earlier versions, as these lack key features for basic modernization provided by tB.\ Certain new tB-exclusive features like child control transparency require newer versions only if they're used.\ Everything should also work under WINE and ReactOS, but testing, while successful, has been minimal. Please share your experiences if you try this. ::: ::: details Why are EXEs produced by twinBASIC larger than VB6? The large majority of functionality, including major pieces like the Forms engine, is provided in VB6 applications/components by the msvbvm60.dll runtime, a 1.4MB file. twinBASIC applications/components have no such outside dependency; the Forms engine and all other functionality is included in the single exe, so the combined size isn't too far off. EXE size is expected to be reduced significantly with the introduction of LLVM-optimized compilation, coming soon. ::: --- --- url: /en/official/Reference/Core/Function.md --- # Function Declares the name, arguments, and code that form the body of a **Function** procedure. Syntax: > \[ *attributes* ]\ > \[ **Public** | **Private** | **Friend** | **Protected** ] \[ **Static** ] \[ **Overridable** ] **Function** *name* \[ **(** **Of** *typevars* **)** ] \[ **(** *arglist* **)** ] \[ **As** *type* ] \[ *binding-clause* ]\ >      \[ *statements* ] ...\ >      \[ \[ **Let** ] *name* **=** *expression* ] ...\ >      \[ **Set** *name* **=** *expression* ] ...\ >      \[ **Return** *expression* ] ...\ >      \[ **Exit Function** ] ...\ >      \[ *statements* ] ...\ > **End Function** *attributes* : One or more of:\ [ArrayBoundsChecks](/en/official/Reference/Attributes#arrayboundschecks), [BindOnlyIfNoArguments](/en/official/Reference/Attributes#bindonlyifnoarguments), [BindOnlyIfStringSuffix](/en/official/Reference/Attributes#bindonlyifstringsuffix), [CompileIf](/en/official/Reference/Attributes#compileif), [ConstantFoldable](/en/official/Reference/Attributes#constantfoldable), [ConstantFoldableNumericsOnly](/en/official/Reference/Attributes#constantfoldablenumericsonly), [Debuggable](/en/official/Reference/Attributes#debuggable), [DebugOnly](/en/official/Reference/Attributes#debugonly), [Description](/en/official/Reference/Attributes#description), [EnforceErrors](/en/official/Reference/Attributes#enforceerrors), [EnforceWarnings](/en/official/Reference/Attributes#enforcewarnings), [FloatingPointErrorChecks](/en/official/Reference/Attributes#floatingpointerrorchecks), [IntegerOverflowChecks](/en/official/Reference/Attributes#integeroverflowchecks), [MustBeQualified](/en/official/Reference/Attributes#mustbequalified), [RunAfterBuild](/en/official/Reference/Attributes#runafterbuild), [SimplerByVals](/en/official/Reference/Attributes#simplerbyvals), [TestCase](/en/official/Reference/Attributes#testcase), [Unimplemented](/en/official/Reference/Attributes#unimplemented) **Public** : *optional*. Indicates that the **Function** procedure is accessible to all other procedures in all modules. If used in a module that contains an **Option Private**, the procedure is not available outside the project. **Private** : *optional* Indicates that the **Function** procedure is accessible only to other procedures in the module where it is declared. **Friend** : *optional* Used only in a class module. Indicates that the **Function** procedure is visible throughout the project, but not visible to a controller of an instance of an object. **[Protected](/en/official/Reference/Core/Protected)** : *optional* (twinBASIC) Used only in a class. Indicates that the **Function** procedure is accessible from inside the declaring class and from classes that derive from it via [**Inherits**](/en/official/Features/Language/Inheritance#inherits-for-complete-oop), but not from outside callers. **Static** : *optional* Indicates that the **Function** procedure's local variables are preserved between calls. The **Static** attribute doesn't affect variables that are declared outside the **Function**, even if they are used in the procedure. **Overridable** : *optional* (twinBASIC) Marks the **Function** as an inheritance hook that classes derived via [**Inherits**](/en/official/Features/Language/Inheritance#inherits-for-complete-oop) may replace with an **Overrides** clause. Meaningful only on a member of a class that participates in an **Inherits** hierarchy. *name* : Name of the **Function**; follows standard variable naming conventions. **Of** *typevars* : *optional* One or more type variable names; following standard variable naming conventions. The names are separated by commas. Causes the function to be a generic function. *arglist* : *optional* List of variables representing arguments that are passed to the **Function** procedure when it is called. Multiple variables are separated by commas. **As** *type* : *optional* Data type of the value returned by the **Function** procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal, Date, String (except fixed length), Object, Variant, or any user-defined type (UDT). *binding-clause* : *optional* (twinBASIC) One of three trailing clauses that bind this body to a member declared elsewhere: * **Handles** *object*.*event* \[ **,** *object*.*event* … ] --- connects this **Function** as a handler for the named event(s), replacing the traditional `Object_Event` naming convention. See [**Handles** statement](/en/official/Reference/Core/Handles). * **Implements** *iface*.*member* \[ **,** *iface2*.*member2* … ] --- provides the body for the named [**Interface**](/en/official/Reference/Core/Interface) (or [**Class**](/en/official/Reference/Core/Class)) member, replacing the traditional `Iface_Member` naming convention. A comma-separated list permits one body to satisfy several interfaces' members at once. See [**Implements** statement](/en/official/Reference/Core/Implements). * **Overrides** *base*.*member* --- supplies the body for an **Overridable** *member* inherited via [**Inherits**](/en/official/Features/Language/Inheritance#inherits-for-complete-oop). Combine with **Overridable** on the same header to allow further-derived classes to override again. *statements* : *optional* Any group of statements to be executed within the **Function** procedure. **[Let](/en/official/Reference/Core/Let)** : *optional* Assigns a non-object-type return value of the **Function** without exiting the function. The **Let** keyword is optional. **[Set](/en/official/Reference/Core/Set)** : *optional* Assigns an object-type return value of the **Function** without exiting the function. **[Return](/en/official/Reference/Core/Return)** *expression* : *optional* Immediately returns from the function with *expression* as the return value. The *expression* is required in this form; a bare **Return** is reserved for the [**GoSub...Return**](/en/official/Reference/Core/GoSub-Return) construct and does not exit a **Function**. **[Exit Function](/en/official/Reference/Core/Exit)** : *optional* Immediately returns from the function without setting a return value. Used to leave a function early when no value needs to be returned (the function will yield its default return value: 0 for numeric types, `""` for strings, **Empty** for **Variant**, **Nothing** for object references). *expression* : *optional* Return value of the **Function**. ### *arglist* Syntax: One or more of\ \[ **Optional** ] \[ **ByVal** | **ByRef** ] \[ **ParamArray** ] *varname* \[ **()** ] \[ **As** *type* ] \[ **=** *defaultvalue* ] **Optional** : *optional* Indicates that an argument is not required. If used, all subsequent arguments in *arglist* must also be optional and declared by using the **Optional** keyword. **Optional** can't be used for any argument if **ParamArray** is used. **ByVal** : *optional* Indicates that the argument is passed by value. **ByRef** : *optional* Indicates that the argument is passed by reference. **ByRef** is the default unlike in Visual Basic .NET. **ParamArray** : *optional* Used only as the last argument in *arglist* to indicate that the final argument is an **Optional** array of **Variant** elements. The **ParamArray** keyword permits passing an arbitrary number of arguments. It may not be used with **ByVal**, **ByRef**, or **Optional**. *varname* : Name of the variable representing the argument; follows standard variable naming conventions. *type* : *optional* Data type of the argument passed to the procedure; may be **Byte**, **Boolean**, **Integer**, **Long**, **Currency**, **Single**, **Double**, **Decimal**, **Date**, **String** (variable length only), **Object**, **Variant**, a specific object type, or the name of a generic type argument. If the parameter is not **Optional**, a user-defined type may also be specified.\ If the name of a generic type parameter is used, it becomes bound to the concrete type of the argument passed to the function. The name binding has the scope of the body of the function. *defaultvalue* : *optional* Any constant or constant expression. Valid for **Optional** parameters only. If the type is an **Object**, an explicit default value can only be **Nothing**. If not explicitly specified by using **Public**, **Private**, or **Friend**, **Function** procedures are public by default. If **Static** isn't used, the value of local variables is not preserved between calls. The **Friend** keyword can only be used in class modules. However, **Friend** procedures can be accessed by procedures in any module of a project. A **Friend** procedure does not appear in the type library of its parent class, nor can a **Friend** procedure be late bound. **Function** procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The **Static** keyword usually isn't used with recursive **Function** procedures. All executable code must be in procedures. A **Function** procedure cannot be defined inside another **Function**, **[Sub](/en/official/Reference/Core/Sub)**, or **[Property](/en/official/Reference/Core/Property)** procedure. The **[Exit Function](/en/official/Reference/Core/Exit)** statement and the **[Return](/en/official/Reference/Core/Return)** *expression* statement both cause an immediate exit from a **Function** procedure. Program execution continues with the statement following the statement that called the **Function** procedure. Any number of these statements can appear anywhere in a **Function** procedure. **Exit Function** is the right choice when the return value has already been assigned (or the default is wanted); **Return** *expression* sets the return value and exits in a single step. Like a **Sub** procedure, a **Function** procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a **Sub** procedure, a **Function** procedure can appear on the right side of an expression in the same way as any intrinsic function --- such as **Sqr**, **Cos**, or **Chr** --- when the value returned by the function is needed. A **Function** procedure is called by using the function name, followed by the argument list in parentheses, in an expression. See the **[Call](/en/official/Reference/Core/Call)** statement for specific information about how to call **Function** procedures. To return a value from a function, assign the value to the function name, or provide it as an argument to the **Return** statement. Any number of such assignments and **Return** statements can appear anywhere within the procedure. If no value is assigned to *name*, the procedure returns a default value: a numeric function returns 0, a string function returns a zero-length string (""), and a **Variant** function returns **Empty**. A function that returns an object reference returns **Nothing** if no object reference is assigned to *name* (using **Set** or **Return**) within the **Function**. The following example shows how to assign a return value to a function. In this case, **False** is assigned to the name to indicate that some value was not found. ```vb Function BinarySearch(...) As Boolean '... ' Value not found. Return a value of False. If lower > upper Then BinarySearch = False Exit Function End If '... End Function ``` Variables used in **Function** procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using **Dim** or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure. A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything defined at the module level has the same name. When a procedure refers to an undeclared variable that has the same name as another procedure, constant, or variable, it is assumed that the procedure refers to that module-level name. Explicitly declare variables to avoid this kind of conflict. Use an **[Option Explicit](/en/official/Reference/Core/Option#Explicit)** statement to force explicit declaration of variables. Visual Basic may rearrange arithmetic expressions to increase internal efficiency. Avoid using a **Function** procedure in an arithmetic expression when the function changes the value of variables in the same expression. For more information about arithmetic operators, see Operators. ### Example This example uses the **Function** statement to declare the name, arguments, and code that form the body of a **Function** procedure. The last example uses hard-typed, initialized **Optional** arguments. ```vb ' The following user-defined function returns the square root of the ' argument passed to it. Function CalculateSquareRoot(NumberArg As Double) As Double If NumberArg < 0 Then ' Evaluate argument. Exit Function ' Exit to calling procedure. Else CalculateSquareRoot = Sqr(NumberArg) ' Return square root. End If End Function ``` Using the **ParamArray** keyword enables a function to accept a variable number of arguments. In the following definition, it is passed by value. ```vb Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs()) Dim ReturnValue ' If the function is invoked as follows: ReturnValue = CalcSum(4, 3, 2, 1) ' Local variables are assigned the following values: FirstArg = 4, ' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default ' lower bound for arrays = 1. End Function ``` **Optional** arguments can have default values and types other than **Variant**. ```vb ' If a function's arguments are defined as follows: Function MyFunc(MyStr As String,Optional MyArg1 As _ Integer = 5,Optional MyArg2 = "Dolly") Dim RetVal ' The function can be invoked as follows: RetVal = MyFunc("Hello", 2, "World") ' All 3 arguments supplied. RetVal = MyFunc("Test", , 5) ' Second argument omitted. ' Arguments one and three using named-arguments. RetVal = MyFunc(MyStr:="Hello ", MyArg1:=7) End Function ``` --- --- url: /zh/official/Reference/Core/Function.md --- # Function 声明构成 **Function** 过程体的名称、参数和代码。 语法: > \[ *attributes* ]\ > \[ **Public** | **Private** | **Friend** | **Protected** ] \[ **Static** ] \[ **Overridable** ] **Function** *name* \[ **(** **Of** *typevars* **)** ] \[ **(** *arglist* **)** ] \[ **As** *type* ] \[ *binding-clause* ]\ >      \[ *statements* ] ...\ >      \[ \[ **Let** ] *name* **=** *expression* ] ...\ >      \[ **Set** *name* **=** *expression* ] ...\ >      \[ **Return** *expression* ] ...\ >      \[ **Exit Function** ] ...\ >      \[ *statements* ] ...\ > **End Function** *attributes* : 以下一个或多个:\ [ArrayBoundsChecks](/official/Reference/Attributes#arrayboundschecks)、[BindOnlyIfNoArguments](/official/Reference/Attributes#bindonlyifnoarguments)、[BindOnlyIfStringSuffix](/official/Reference/Attributes#bindonlyifstringsuffix)、[CompileIf](/official/Reference/Attributes#compileif)、[ConstantFoldable](/official/Reference/Attributes#constantfoldable)、[ConstantFoldableNumericsOnly](/official/Reference/Attributes#constantfoldablenumericsonly)、[Debuggable](/official/Reference/Attributes#debuggable)、[DebugOnly](/official/Reference/Attributes#debugonly)、[Description](/official/Reference/Attributes#description)、[EnforceErrors](/official/Reference/Attributes#enforceerrors)、[EnforceWarnings](/official/Reference/Attributes#enforcewarnings)、[FloatingPointErrorChecks](/official/Reference/Attributes#floatingpointerrorchecks)、[IntegerOverflowChecks](/official/Reference/Attributes#integeroverflowchecks)、[MustBeQualified](/official/Reference/Attributes#mustbequalified)、[RunAfterBuild](/official/Reference/Attributes#runafterbuild)、[SimplerByVals](/official/Reference/Attributes#simplerbyvals)、[TestCase](/official/Reference/Attributes#testcase)、[Unimplemented](/official/Reference/Attributes#unimplemented) **Public** : *可选*。指示 **Function** 过程可被所有模块中的所有其他过程访问。如果在包含 **Option Private** 的模块中使用,则该过程在项目外不可用。 **Private** : *可选* 指示 **Function** 过程仅可被声明它的模块中的其他过程访问。 **Friend** : *可选* 仅在类模块中使用。指示 **Function** 过程在整个项目中可见,但对对象实例的控制器不可见。 **[Protected](/official/Reference/Core/Protected)** : *可选* (twinBASIC) 仅在类中使用。指示 **Function** 过程可从声明类的内部和通过 [**Inherits**](/official/Features/Language/Inheritance#inherits-for-complete-oop) 派生的类访问,但外部调用者不能访问。 **Static** : *可选* 指示 **Function** 过程的局部变量在调用之间保持其值。**Static** 属性不影响在 **Function** 外部声明的变量,即使它们在过程中使用。 **Overridable** : *可选* (twinBASIC) 将 **Function** 标记为继承钩子,通过 [**Inherits**](/official/Features/Language/Inheritance#inherits-for-complete-oop) 派生的类可以用 **Overrides** 子句替换。仅在参与 **Inherits** 层次结构的类成员上有意义。 *name* : **Function** 的名称;遵循标准变量命名约定。 **Of** *typevars* : *可选* 一个或多个类型变量名;遵循标准变量命名约定。名称用逗号分隔。使函数成为泛型函数。 *arglist* : *可选* 表示调用 **Function** 过程时传递的参数的变量列表。多个变量用逗号分隔。 **As** *type* : *可选* **Function** 过程返回值的数据类型;可以是Byte、Boolean、Integer、Long、Currency、Single、Double、Decimal、Date、String(定长除外)、Object、Variant或任何用户自定义类型(UDT)。 *binding-clause* : *可选* (twinBASIC) 三种尾部子句之一,将此函数体绑定到在别处声明的成员: * **Handles** *object*.*event* \[ **,** *object*.*event* … ]——将此 **Function** 连接为命名事件的处理程序,替代传统的 `Object_Event` 命名约定。参见 [**Handles** 语句](/official/Reference/Core/Handles)。 * **Implements** *iface*.*member* \[ **,** *iface2*.*member2* … ]——为命名的 [**Interface**](/official/Reference/Core/Interface)(或 [**Class**](/official/Reference/Core/Class))成员提供实现体,替代传统的 `Iface_Member` 命名约定。逗号分隔的列表允许一个函数体同时满足多个接口的成员。参见 [**Implements** 语句](/official/Reference/Core/Implements)。 * **Overrides** *base*.*member*——为通过 [**Inherits**](/official/Features/Language/Inheritance#inherits-for-complete-oop) 继承的 **Overridable** *member* 提供实现体。与同一头部的 **Overridable** 组合使用以允许更深层的派生类再次覆盖。 *statements* : *可选* 在 **Function** 过程内执行的任何语句组。 **[Let](/official/Reference/Core/Let)** : *可选* 在不退出函数的情况下赋值 **Function** 的非对象类型返回值。**Let** 关键字可选。 **[Set](/official/Reference/Core/Set)** : *可选* 在不退出函数的情况下赋值 **Function** 的对象类型返回值。 **[Return](/official/Reference/Core/Return)** *expression* : *可选* 立即以 *expression* 作为返回值从函数返回。此形式中 *expression* 是必需的;单独的 **Return** 保留给 [**GoSub...Return**](/official/Reference/Core/GoSub-Return) 构造,不会退出 **Function**。 **[Exit Function](/official/Reference/Core/Exit)** : *可选* 立即从函数返回而不设置返回值。用于在不需要返回值时提前离开函数(函数将产生其默认返回值:数值类型为0,字符串为 `""`,**Variant** 为 **Empty**,对象引用为 **Nothing**)。 *expression* : *可选* **Function** 的返回值。 ### *arglist* 语法:一个或多个\ \[ **Optional** ] \[ **ByVal** | **ByRef** ] \[ **ParamArray** ] *varname* \[ **()** ] \[ **As** *type* ] \[ **=** *defaultvalue* ] **Optional** : *可选* 指示参数不是必需的。如果使用,*arglist* 中所有后续参数也必须是可选的并使用 **Optional** 关键字声明。如果使用了 **ParamArray**,则不能对任何参数使用 **Optional**。 **ByVal** : *可选* 指示参数按值传递。 **ByRef** : *可选* 指示参数按引用传递。**ByRef** 是默认方式,与Visual Basic .NET不同。 **ParamArray** : *可选* 仅用作 *arglist* 中的最后一个参数,指示最后一个参数是 **Variant** 元素的 **Optional** 数组。**ParamArray** 关键字允许传递任意数量的参数。不能与 **ByVal**、**ByRef** 或 **Optional** 一起使用。 *varname* : 表示参数的变量名称;遵循标准变量命名约定。 *type* : *可选* 传递给过程的参数的数据类型;可以是 **Byte**、**Boolean**、**Integer**、**Long**、**Currency**、**Single**、**Double**、**Decimal**、**Date**、**String**(仅限变长)、**Object**、**Variant**、特定对象类型或泛型类型参数的名称。如果参数不是 **Optional**,也可以指定用户自定义类型。\ 如果使用泛型类型参数的名称,它将绑定到传递给函数的参数的具体类型。名称绑定具有函数体的作用域。 *defaultvalue* : *可选* 任何常量或常量表达式。仅对 **Optional** 参数有效。如果类型为 **Object**,显式默认值只能为 **Nothing**。 如果未使用 **Public**、**Private** 或 **Friend** 显式指定,**Function** 过程默认为公共的。 如果未使用 **Static**,局部变量的值在调用之间不保留。 **Friend** 关键字只能在类模块中使用。但 **Friend** 过程可以被项目中任何模块的过程访问。**Friend** 过程不出现在其父类的类型库中,也不能被后期绑定。 **Function** 过程可以递归;即它们可以调用自身来执行给定任务。但递归可能导致栈溢出。**Static** 关键字通常不与递归 **Function** 过程一起使用。 所有可执行代码必须在过程中。**Function** 过程不能定义在另一个 **Function**、[**Sub**](/official/Reference/Core/Sub) 或 [**Property**](/official/Reference/Core/Property) 过程内。 **[Exit Function](/official/Reference/Core/Exit)** 语句和 **[Return](/official/Reference/Core/Return)** *expression* 语句都会导致立即从 **Function** 过程退出。程序执行继续到调用 **Function** 过程的语句之后的语句。这些语句可以在 **Function** 过程中的任何位置出现任意数量。**Exit Function** 适用于返回值已经赋值(或想要默认值)的情况;**Return** *expression* 在一步中设置返回值并退出。 与 **Sub** 过程一样,**Function** 过程是可以接受参数、执行一系列语句并更改其参数值的独立过程。但与 **Sub** 过程不同,当需要函数返回的值时,**Function** 过程可以像任何内部函数——如 **Sqr**、**Cos** 或 **Chr**——一样出现在表达式的右侧。 通过在表达式中使用函数名后跟括号内的参数列表来调用 **Function** 过程。参见 **[Call](/official/Reference/Core/Call)** 语句了解如何调用 **Function** 过程的具体信息。 要从函数返回值,请将值赋给函数名,或将其作为 **Return** 语句的参数。此类赋值和 **Return** 语句可以在过程中的任何位置出现任意数量。如果没有将值赋给 *name*,过程返回默认值:数值函数返回0,字符串函数返回零长度字符串(""),**Variant** 函数返回 **Empty**。如果函数返回对象引用且在 **Function** 内未使用 **Set** 或 **Return** 将对象引用赋给 *name*,则返回 **Nothing**。 以下示例展示如何为函数赋返回值。在此例中,将 **False** 赋给函数名以指示未找到某个值。 ```vb Function BinarySearch(...) As Boolean '... ' Value not found. Return a value of False. If lower > upper Then BinarySearch = False Exit Function End If '... End Function ``` **Function** 过程中使用的变量分为两类:在过程中显式声明的和未显式声明的。 在过程中显式声明(使用 **Dim** 或等效方式)的变量始终是过程的局部变量。在过程中使用但未显式声明的变量也是局部变量,除非它们在过程外部的更高级别被显式声明。 过程可以使用未在过程中显式声明的变量,但如果模块级别定义了同名的任何内容,则可能发生命名冲突。当过程引用与另一个过程、常量或变量同名的未声明变量时,假定过程引用的是该模块级别的名称。显式声明变量以避免此类冲突。使用 **[Option Explicit](/official/Reference/Core/Option#Explicit)** 语句强制显式声明变量。 Visual Basic可能会重新排列算术表达式以提高内部效率。当函数更改同一表达式中变量的值时,避免在算术表达式中使用 **Function** 过程。有关算术运算符的更多信息,参见运算符。 ### 示例 本示例使用 **Function** 语句声明构成 **Function** 过程体的名称、参数和代码。最后一个示例使用强类型、初始化的 **Optional** 参数。 ```vb ' The following user-defined function returns the square root of the ' argument passed to it. Function CalculateSquareRoot(NumberArg As Double) As Double If NumberArg < 0 Then ' Evaluate argument. Exit Function ' Exit to calling procedure. Else CalculateSquareRoot = Sqr(NumberArg) ' Return square root. End If End Function ``` 使用 **ParamArray** 关键字使函数可以接受可变数量的参数。在以下定义中,它按值传递。 ```vb Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs()) Dim ReturnValue ' If the function is invoked as follows: ReturnValue = CalcSum(4, 3, 2, 1) ' Local variables are assigned the following values: FirstArg = 4, ' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default ' lower bound for arrays = 1. End Function ``` **Optional** 参数可以有默认值和 **Variant** 以外的类型。 ```vb ' If a function's arguments are defined as follows: Function MyFunc(MyStr As String,Optional MyArg1 As _ Integer = 5,Optional MyArg2 = "Dolly") Dim RetVal ' The function can be invoked as follows: RetVal = MyFunc("Hello", 2, "World") ' All 3 arguments supplied. RetVal = MyFunc("Test", , 5) ' Second argument omitted. ' Arguments one and three using named-arguments. RetVal = MyFunc(MyStr:="Hello ", MyArg1:=7) End Function ``` --- --- url: /en/official/Features/Fusion.md --- ## Introduction **Fusion** is a twinBASIC feature that enables 64-bit applications to host certain 32-bit ActiveX controls by transparently bridging them through an out-of-process helper executable. Traditionally, ActiveX controls must match the bitness of the host application. This limitation has long prevented the use of legacy 32-bit controls in modern 64-bit applications. Fusion removes this restriction by introducing a bridging layer that allows cross-architecture interaction. Please note: this technology has currently only been tested on Windows 10 and 11 machines. Results may vary on older operating systems. ## What does "out-of-process" mean? An **out-of-process** component runs in a separate executable (process) rather than within the same memory space as the main application. With *twinBASIC Fusion*: * Your main twinBASIC application runs as usual (e.g. 64-bit) * A secondary **host EXE** is launched automatically (e.g. 32-bit) * The ActiveX controls are created and hosted inside this secondary process * Communication between your main application and the controls is handled transparently by twinBASIC This separation allows incompatible architectures (e.g. 32-bit controls in a 64-bit app) to interoperate safely. ## Inter-Process Communication (IPC) Because *twinBASIC Fusion* operates across two separate processes, all interaction between your application and the hosted ActiveX controls is performed using **Inter-Process Communication (IPC)**. In simple terms, IPC is a mechanism that allows two independent processes to exchange data and invoke behaviour. With *twinBASIC Fusion*: * Method and property calls are **marshalled across the IPC layer** to the host EXE * The host EXE executes the call against the real ActiveX control instance * Return values are transmitted back to the calling process Events follow the same pattern in reverse: * The control raises an event inside the host EXE * The event is transmitted back across the IPC channel * Your application receives it as if it originated locally #### Important characteristics: * There is a small inherent overhead due to cross-process communication * All parameters and return values must be serialised/deserialised * Execution appears synchronous to your code, but is performed remotely ## Deadlocks and Freezes Due to the nature of cross-process communication and message pumping, some controls used with Fusion may be susceptible to **deadlocks or UI freezes**. If you encounter this, you can try enabling the following per-library option: **Fusion: Async Events** This changes how events are delivered across the IPC boundary and can help avoid re-entrancy and blocking issues in certain controls. ## Automatic Fusion Host EXE Generation When you open a twinBASIC project, the compiler evaluates whether all referenced ActiveX controls are available and registered for the current architecture. If one or more controls are not registered for the current architecture then twinBASIC will automatically generate a **Fusion host EXE** alongside your project, when required. When this occurs, you will see a note in the DEBUG CONSOLE: ![tbFusionDebugConsole](/assets/569099635-bc9553a6-fcce-487d-a478-dbee557f33b1.B_cnVAd6.png){style="width:412px; height:73px;"} This additional EXE acts as the out-of-process container for those controls and is managed automatically by the twinBASIC IDE ## ActiveX Hosting EXE Output Path A project-level setting allows you to control where the Fusion host EXE is generated: * **ActiveX Fusion Host EXE Output Path** ![tbFusionProjectSettings](/assets/569150839-9ffc87ac-250d-40a4-bb47-669b607ad76f.BWV5BCGv.png){style="width:800px; height:400px;"} If left blank (default), the standard build path set in the project settings is used. Unless overriden, the standard build path is: ${SourcePath}\Build${ProjectName}\_${Architecture}.${FileExtension} For Fusion host executables, `${Architecture}` will resolve to: * `win32host` * `win64host` This allows Fusion host EXEs to be clearly distinguished from normal build outputs. ## Per-Library Options Each COM reference (type library) exposes Fusion-specific options. ![tbFusionPerLibraryOptions](/assets/569100769-f1f2790a-0094-4843-809f-a8a9e928fd41.3trKvrDO.png){style="width:737px; height:323px;"} ### ActiveX Fusion Mode Controls how (and if) Fusion is applied for a given library. **Available options:** * `auto` (DEFAULT) Enables Fusion automatically only when the library is not available for the current architecture * 32-bit control in 64-bit build → uses `fusion64To32` * 64-bit control in 32-bit build → uses `fusion32To64` * `fusion32To64` * 32-bit builds: generates and uses a **64-bit host EXE** * 64-bit builds: Fusion is not used * `fusion64To32` * 64-bit builds: generates and uses a **32-bit host EXE** * 32-bit builds: Fusion is not used * `fusionAllTo64` * Both 32-bit and 64-bit builds use a **64-bit host EXE**\ This option allows you to run these controls as out-of-process Fusion controls on both architectures. * `fusionAllTo32` * Both 32-bit and 64-bit builds use a **32-bit host EXE**\ This option allows you to run these controls as out-of-process Fusion controls on both architectures. * `none` * Disables Fusion entirely for this library Please note: you cannot mix and match the explicit "Fusion Mode" settings across multiple libraries (except for 'auto' and 'none' modes, which can always be used). ### Fusion: Async Events Boolean option, defaults OFF When set, enables asynchronous event delivery across the IPC boundary (from host EXE to main app). This can help prevent deadlocks or freezes with certain controls. ::: info using this option means that you cannot return data to the hosted control via ByRef params (e.g. a `ByRef Cancel As Boolean` param would be ineffective). ::: ## Runtime Behaviour and Deployment For compiled builds at runtime: * The main application will look for the Fusion host EXE **in the same directory as the main executable** * The filename must match the one generated at build time If required, you can override this behaviour: ```vb App.FusionHostEXEPath = "C:\Path\To\Host.exe" ``` ### Important: This explicit path must be set **before** opening any Fusion-backed form or control. The Fusion host EXE must always be distributed with your application. Failure to include the host EXE will prevent Fusion-based controls from loading, and the main application process will end. ## Current Limitations Fusion is a compatibility layer, but not all ActiveX controls are supported. #### Currently NOT supported: * Windowless controls * Container controls * Controls that depend on other sited controls #### Other Known Limitations: * No tab navigation between controls * Property pages are not yet implemented * Unsupported Properties * ToolTipText * CausesValidation * DragMode * DragIcon * HelpContextID * WhatsThisHelpID * TabStop * TabIndex ## Event Differences Mouse events are not currently OLE-translated, therefore mouse event signatures (MouseDown, MouseUp, MouseMove) will differ from traditional ActiveX expectations. This is a current limitation, and will fixed in a later update. ## Summary *twinBASIC Fusion* provides a practical path for modernising applications while retaining compatibility with legacy ActiveX controls. By using an out-of-process architecture and fast IPC-based communication, *twinBASIC Fusion* enables cross-bitness interoperability while maintaining a familiar programming model. --- --- url: /zh/official/Features/Fusion.md --- ## 简介 **Fusion** 是 twinBASIC 的一项功能,使 64 位应用程序能够托管某些 32 位 ActiveX 控件,通过透明地将它们桥接到一个外部进程辅助可执行文件中。 传统上,ActiveX 控件的位数必须与宿主应用程序匹配。这一限制长期以来阻碍了在现代 64 位应用程序中使用遗留 32 位控件。Fusion 通过引入一个桥接层来消除此限制,允许跨架构交互。 请注意:此技术目前仅在 Windows 10 和 11 机器上经过测试。在较旧的操作系统上可能会有不同表现。 ## "外部进程"是什么意思? **外部进程**组件运行在单独的可执行文件(进程)中,而不是在主应用程序的同一内存空间内。 使用 *twinBASIC Fusion* 时: * 你的主 twinBASIC 应用程序照常运行(例如 64 位) * 一个辅助的**宿主 EXE** 会自动启动(例如 32 位) * ActiveX 控件在此辅助进程中创建和托管 * 主应用程序与控件之间的通信由 twinBASIC 透明处理 这种分离允许不兼容的架构(例如 64 位应用中的 32 位控件)安全地互操作。 ## 进程间通信 (IPC) 由于 *twinBASIC Fusion* 跨两个独立进程运行,应用程序与托管的 ActiveX 控件之间的所有交互都通过**进程间通信 (IPC)** 进行。 简单来说,IPC 是一种允许两个独立进程交换数据和调用行为的机制。 使用 *twinBASIC Fusion* 时: * 方法和属性调用**通过 IPC 层封送**到宿主 EXE * 宿主 EXE 对真实的 ActiveX 控件实例执行调用 * 返回值传回调用进程 事件以相反的方式遵循相同的模式: * 控件在宿主 EXE 中触发事件 * 事件通过 IPC 通道传回 * 你的应用程序接收到它,就像它是在本地产生的一样 #### 重要特征: * 由于跨进程通信,存在少量固有开销 * 所有参数和返回值必须被序列化/反序列化 * 执行对你的代码表现为同步的,但实际上在远程执行 ## 死锁和冻结 由于跨进程通信和消息泵的性质,使用 Fusion 的某些控件可能会出现**死锁或 UI 冻结**。 如果遇到此问题,可以尝试启用以下每个库的选项: **Fusion: 异步事件** 这会改变事件在 IPC 边界的传递方式,可以帮助某些控件避免重入和阻塞问题。 ## 自动生成 Fusion 宿主 EXE 当你打开 twinBASIC 项目时,编译器会评估所有引用的 ActiveX 控件是否可用于当前架构并已注册。 如果有一个或多个控件未为当前架构注册,twinBASIC 将在需要时自动在项目旁边生成一个 **Fusion 宿主 EXE**。 发生这种情况时,你会在调试控制台中看到一条提示: ![tbFusionDebugConsole](/assets/569099635-bc9553a6-fcce-487d-a478-dbee557f33b1.B_cnVAd6.png){style="width:412px; height:73px;"} 这个额外的 EXE 充当这些控件的外部进程容器,由 twinBASIC IDE 自动管理。 ## ActiveX 宿主 EXE 输出路径 项目级设置允许你控制 Fusion 宿主 EXE 的生成位置: * **ActiveX Fusion 宿主 EXE 输出路径** ![tbFusionProjectSettings](/assets/569150839-9ffc87ac-250d-40a4-bb47-669b607ad76f.BWV5BCGv.png){style="width:800px; height:400px;"} 如果留空(默认),则使用项目设置中的标准构建路径。除非被覆盖,标准构建路径为: ${SourcePath}\Build${ProjectName}\_${Architecture}.${FileExtension} 对于 Fusion 宿主可执行文件,`${Architecture}` 将解析为: * `win32host` * `win64host` 这使得 Fusion 宿主 EXE 可以与正常构建输出明确区分。 ## 每个库的选项 每个 COM 引用(类型库)都公开 Fusion 专用选项。 ![tbFusionPerLibraryOptions](/assets/569100769-f1f2790a-0094-4843-809f-a8a9e928fd41.3trKvrDO.png){style="width:737px; height:323px;"} ### ActiveX Fusion 模式 控制如何(以及是否)对给定库应用 Fusion。 **可用选项:** * `auto`(默认) 仅当库在当前架构下不可用时自动启用 Fusion * 64 位构建中的 32 位控件 → 使用 `fusion64To32` * 32 位构建中的 64 位控件 → 使用 `fusion32To64` * `fusion32To64` * 32 位构建:生成并使用 **64 位宿主 EXE** * 64 位构建:不使用 Fusion * `fusion64To32` * 64 位构建:生成并使用 **32 位宿主 EXE** * 32 位构建:不使用 Fusion * `fusionAllTo64` * 32 位和 64 位构建都使用 **64 位宿主 EXE** 此选项允许你在两种架构上都将这些控件作为外部进程 Fusion 控件运行。 * `fusionAllTo32` * 32 位和 64 位构建都使用 **32 位宿主 EXE** 此选项允许你在两种架构上都将这些控件作为外部进程 Fusion 控件运行。 * `none` * 完全禁用此库的 Fusion 请注意:你不能在多个库之间混用显式的"Fusion 模式"设置('auto' 和 'none' 模式除外,它们始终可以使用)。 ### Fusion: 异步事件 布尔选项,默认关闭。 启用后,在 IPC 边界启用异步事件传递(从宿主 EXE 到主应用程序)。这可以帮助防止某些控件出现死锁或冻结。 ::: info 使用此选项意味着你不能通过 ByRef 参数向托管控件返回数据(例如 `ByRef Cancel As Boolean` 参数将无效)。 ::: ## 运行时行为和部署 对于编译构建的运行时: * 主应用程序将在**与主可执行文件相同的目录**中查找 Fusion 宿主 EXE * 文件名必须与构建时生成的文件名匹配 如果需要,你可以覆盖此行为: ```vb App.FusionHostEXEPath = "C:\Path\To\Host.exe" ``` ### 重要提示: 此显式路径必须在打开任何基于 Fusion 的窗体或控件**之前**设置。Fusion 宿主 EXE 必须始终随你的应用程序一起分发。未包含宿主 EXE 将导致基于 Fusion 的控件无法加载,主应用程序进程将终止。 ## 当前限制 Fusion 是一个兼容层,但并非所有 ActiveX 控件都受支持。 #### 目前不支持: * 无窗口控件 * 容器控件 * 依赖其他驻留控件的控件 #### 其他已知限制: * 控件之间无 Tab 键导航 * 属性页尚未实现 * 不支持的属性 * ToolTipText * CausesValidation * DragMode * DragIcon * HelpContextID * WhatsThisHelpID * TabStop * TabIndex ## 事件差异 鼠标事件目前不进行 OLE 转换,因此鼠标事件签名(MouseDown、MouseUp、MouseMove)将与传统的 ActiveX 预期不同。这是当前的限制,将在后续更新中修复。 ## 总结 *twinBASIC Fusion* 为在现代化应用程序的同时保留与遗留 ActiveX 控件的兼容性提供了一条实用路径。 通过使用外部进程架构和基于 IPC 的快速通信,*twinBASIC Fusion* 实现了跨位数互操作,同时保持了熟悉的编程模型。 --- --- url: /en/official/Reference/VBA/Financial/FV.md --- # FV Returns a **Double** specifying the future value of an annuity based on periodic fixed payments and a fixed interest rate. Syntax: **FV(** *rate*, *nper*, *pmt* \[ **,** *pv* \[ **,** *type* ] ] **)** *rate* : *required* **Double** specifying interest rate per period. For example, for a car loan at an annual percentage rate (APR) of 10 percent with monthly payments, the rate per period is 0.1/12, or 0.0083. *nper* : *required* **Integer** specifying total number of payment periods in the annuity. For example, monthly payments on a four-year car loan total 4 \* 12 (or 48) payment periods. *pmt* : *required* **Double** specifying payment to be made each period. Payments usually contain principal and interest that doesn't change over the life of the annuity. *pv* : *optional* **Variant** specifying present value (or lump sum) of a series of future payments. For example, when borrowing money to buy a car, the loan amount is the present value to the lender of the monthly car payments to be made. If omitted, 0 is assumed. *type* : *optional* **Variant** specifying when payments are due. 0 means payments are due at the end of the period; 1 means payments are due at the beginning. If omitted, 0 is assumed. An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan). The *rate* and *nper* arguments must be calculated by using payment periods expressed in the same units. For example, if *rate* is calculated by using months, *nper* must also be calculated by using months. For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers. ### Example This example uses the **FV** function to return the future value of an investment given the percentage rate that accrues per period (`APR / 12`), the total number of payments (`TotPmts`), the payment (`Payment`), the current value of the investment (`PVal`), and a number that indicates whether the payment is made at the beginning or end of the payment period (`PayType`). Note that because `Payment` represents cash paid out, it's a negative number. ```vb Dim Fmt, Payment, APR, TotPmts, PayType, PVal, FVal Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. Fmt = "###,###,##0.00" ' Define money format. Payment = InputBox("How much do you plan to save each month?") APR = InputBox("Enter the expected interest annual percentage rate.") If APR > 1 Then APR = APR / 100 ' Ensure proper form. TotPmts = InputBox("For how many months do you expect to save?") PayType = MsgBox("Do you make payments at the end of month?", vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD PVal = InputBox("How much is in this savings account now?") FVal = FV(APR / 12, TotPmts, -Payment, -PVal, PayType) MsgBox "Your savings will be worth " & Format(FVal, Fmt) & "." ``` ### See Also * [PV](/en/official/Reference/VBA/Financial/PV), [NPer](/en/official/Reference/VBA/Financial/NPer), [Pmt](/en/official/Reference/VBA/Financial/Pmt), [Rate](/en/official/Reference/VBA/Financial/Rate) functions --- --- url: /zh/official/Reference/VBA/Financial/FV.md --- # FV 返回一个 **Double**,基于定期固定付款和固定利率指定年金的终值。 语法:**FV(** *rate*, *nper*, *pmt* \[ **,** *pv* \[ **,** *type* ] ] **)** *rate* : *必需* **Double**,指定每期利率。例如,对于年利率 10% 按月还款的汽车贷款,每期利率为 0.1/12,即 0.0083。 *nper* : *必需* **Integer**,指定年金的总付款期数。例如,四年期汽车贷款按月还款共有 4 \* 12(即 48)个付款期。 *pmt* : *必需* **Double**,指定每期付款额。付款通常包含本金和利息,在年金期限内不变。 *pv* : *可选* **Variant**,指定一系列未来付款的现值(或一次付清金额)。例如,借钱买车时,贷款金额就是贷款人将收到的月供的现值。如果省略,则假定为 0。 *type* : *可选* **Variant**,指定付款到期时间。0 表示期末到期;1 表示期初到期。如果省略,则假定为 0。 年金是在一段时间内进行的一系列固定现金支付。年金可以是贷款(如住房抵押贷款)或投资(如月度储蓄计划)。 *rate* 和 *nper* 参数必须使用相同单位的付款期计算。例如,如果 *rate* 按月计算,*nper* 也必须按月计算。 对于所有参数,支出的现金(如储蓄存款)用负数表示;收入的现金(如股息支票)用正数表示。 ### 示例 此示例使用 **FV** 函数返回投资的终值,给定每期应计百分比利率(`APR / 12`)、总付款次数(`TotPmts`)、付款额(`Payment`)、投资的当前价值(`PVal`)以及指示付款是在付款期初还是期末支付的数字(`PayType`)。注意,因为 `Payment` 代表支出的现金,所以是负数。 ```vb Dim Fmt, Payment, APR, TotPmts, PayType, PVal, FVal Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. Fmt = "###,###,##0.00" ' Define money format. Payment = InputBox("How much do you plan to save each month?") APR = InputBox("Enter the expected interest annual percentage rate.") If APR > 1 Then APR = APR / 100 ' Ensure proper form. TotPmts = InputBox("For how many months do you expect to save?") PayType = MsgBox("Do you make payments at the end of month?", vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD PVal = InputBox("How much is in this savings account now?") FVal = FV(APR / 12, TotPmts, -Payment, -PVal, PayType) MsgBox "Your savings will be worth " & Format(FVal, Fmt) & "." ``` ### 另请参阅 * [PV](/official/Reference/VBA/Financial/PV)、[NPer](/official/Reference/VBA/Financial/NPer)、[Pmt](/official/Reference/VBA/Financial/Pmt)、[Rate](/official/Reference/VBA/Financial/Rate) 函数 --- --- url: /en/official/Features/Language/Generics.md --- # Generics ::: warning Generics are syntactic sugar for copy-pasting code followed by a search-and-replace of type names. Everything that the generic syntax provides can be achieved without it by writing repetitive code. ::: This repetition is error-prone and tedious, however, and thus the generic syntax keeps the code DRY\[^1]. The generic syntax introduces *type parameters* / *type variables* whose *type-values* exist during compilation, as opposed to regular parameters and their values that exist during run-time only. Procedures, **Class**es and **Type**s (UDTs) can be made generic. ::: warning Generic **Type**s (UDTs) don't yet support member procedures (error TB5124). ::: ## Generic Procedures Syntax: * **Definition**\ ( **Function** | ... ) *name* **(Of** *type-variable-list* **)** **(** *parameter-list* **)** **As** *return-type* * In detail:\ ( **Function** | **Sub** | **Property** (**Get** | **Let** | **Set**) ) *name* **(Of** *type-var1* \[ **,** *type-var2* ...]**)** **(** *parameter-list* **)** **As** *return-type*\ The *parameter-list* can reference any of the type variables, e.g.\ `Sub MyPrint(Of T)(ByVal file&, value As T)` * **Invocation** or **Call Site**\ *name* \[ **(Of** *type-argument-list* **)** ] \[ **(** *argument-list* **)** ] * In detail:\ *name* \[ **(Of** *type-arg1* \[ **,** *type-arg2* ] **)** ] \[ **(** *argument-list* **)** ]\ The type variables from the definition's *parameter-list* are substituted with concrete or arguments types provided in the *argument-list*, unless provided explicitly as a type argument in the *type-argument-list*.\ The type variables that were not referenced in the *parameter-list* have to be provided in the *type-argument-list* as *type-arguments*. In the definition, the *type-variable-list*, i.e. **(Of** *type-var* ... **)**, introduces genericity. The type variables (*type-var*) introduce identifiers of arbitrary types that can be referenced within: * *parameter-list*, * *return-type*, and * the body of the procedure. In the invocation, the *type-argument-list*, i.e. **(Of** *type-arg* ... **)**, is optional as needed to provide types arguments for those type variables that don't appear in the *parameter-list* of the definition. The type variables that are used within the *parameter-list* are assigned type values of the respective arguments at the call site *unless their values are explicitly provided* in the *type-argument-list*. ### Call site type arguments Type variables that correspond to types that could be deduced from the call argument types must form a trailer of the *type-variable-list*: ```vb Sub MySub1(Of T, U, V)(argu As U, argv As V): End Sub MySub1(Of Long)(33%, 42%) ' Valid: deduced U, V = Integer MySub1(Of Long, Single)(33%, 42%) ' Valid: provided U = Single, deduced V = Integer MySub1(Of Long, Single, Double)(33%, 42%)' Valid: provided U = Single, provided V = Double MySub1(Of Long, , Double)(33%, 42%) ' Invalid: omitted deduced type must be trailing ``` Thus, to suppress deduction, put the type variable in the type list *before* the non-deducible type parameters: ```vb ' T must be provided, it won't be deduced Function MyFn1(Of T, U)(argu As T) As U: End Function MyFn1(Of Single, String)(10%) ' Valid: provided T = Single, U = String MyFn1(Of, String)(10%) ' Invalid: T is not trailing so it can't be omitted ' Effectively, the definition of MyFn1 ' suppresses deduction of T ``` Only the unused type variables may have their arguments omitted at positions *after the first* in the *type-variable-list*.: ```vb Sub MySub2(Of T, U, V)(argt As T, argv As V): End Sub Sub MySub3(Of U, V)(argv As V): End Sub MySub2(Of Single, , Double)(1%, 2%) ' Valid: unused U can be omitted as it's not the first ' in the type-parameter-list MySub3(Of, Single)(22%) ' Invalid: unused U can't be omitted as it's the first ' variable in the type-parameter-list ``` ### Example 1 In this example, the invocations of the generic **First** and **Last** subs don't need to explicitly provide type argument values using the *type-argument-list*, i.e. **(Of** ... **)**, since they can be deduced from the argument types. ```vb Public Function First(Of T)(Array() As T) As T If IsArrayInitialized(Array) Then Return Array(LBound(Array)) End Function Public Function Last(Of T)(Array() As T) As T If IsArrayInitialized(Array) Then Return Array(UBound(Array)) End Function Sub Test() Dim data() As String = Array("A", "B", "C") Debug.Assert First(data) = "A" Debug.Assert Last(data) = "C" End Sub ``` Without the generic syntax, the procedure would have had to be written for every type *T* it's used on. In the example below, that would be `T=String` and `T=Integer`: ```vb Public Function First(Array() As String) As String If IsArrayInitialized(Array) Then Return Array(LBound(Array)) End Function Public Function First(Array() As Integer) As Integer If IsArrayInitialized(Array) Then Return Array(LBound(Array)) End Function Sub Test() Dim strings() As String = Array("A", "B", "C") Dim ints() As Integer = Array(1, 2, 3) Debug.Assert First(strings) = "A" AndAlso First(ints) = 1 End Sub ``` ### Example 2 with some type variables not appearing in the *parameter-list* There are two common cases when a type variable might not appear in the *parameter-list*: * when it is the *result-type*, and/or * when it is used in the body of the procedure. The example below illustrates those possibilities: ```vb Public Function Caster(Of R, U, T)(value As T) As R Dim intermediate As U = CType(Of U)(value) Return CType(Of R)(intermediate) End Function Sub Test() ' Type T is deduced to be Single, from the argument 1.23! Debug.Assert Example(Of String, Integer)(1.23!) = "1" ' Type T is explicitly provided as Double. The argument is cast to that type. Debug.Print Example(Of String, Integer, Double)(1.23!) = "1" End Sub ``` The function **Caster** introduces three type variables within its scope: * **T** is by default deduced from the type of the **value** argument, or can be provided on invocation, * **R** is the result type and must be provided on invocation, * **U** is a type used in the body of the function and must be provided on invocation. ::: tip The order of the type variables in the definition can be chosen so that the trailing variable(s) are used in the *parameter-list*. The type-values of those type variable can thus be omitted if the types inferred from the argument types at the call site are appropriate. ::: 1. In the invocation `Example(Of String, Integer)(1.23!)`,\ *T* is deduced to be **Single**, *U* is provided and set to **Integer**, and **R** is provided and set to **String**. 2. In the invocation `Example(Of String, Integer, Double)(1.23!)`,\ *T* is provided and set to **Double**, *U* is provided and set to **Integer**, and *R* is provided and set to **String**. * First, the compiler will cast `1.23!` to the type of the formal parameter, that is to a **Double** `1.23#`. * Then, in the body of the function, the *value* is cast to **Integer** when it's assigned to **intermediate**. * Finally, also in the body, the **intermediate** is cast to the result type of **String**, and returned. ## Generic Classes And UDTs Syntax: * **Definition**\ \[ **Class** | ... ] *name* **(Of** *type-variable-list* **)** * In Detail:\ \[ **Class** | **Type** ] *name* **(Of** *type-var1* \[ **,** *type-var2* ... ] **)** * **Instantiation**\ *name* **(Of** *type-argument-list* **)** * In Detail:\ *name* **(Of** *type-arg1* \[ **,** *type-arg2* ... ] **)** The type variables (*type-var*) introduce identifiers of arbitrary types that can be referenced anywhere within the body of the class. ::: warning When instantiating generic classes and UDTs, **all of the type arguments** have to be provided. If they aren't, code generation errors and silent failures at runtime may occur. ::: ### Example of correct and incorrect instantiation ```vb Class MyClass(Of T, U) Function DumpT%(value As T): Debug.Print value: End Function Function DumpU%(value As U): Debug.Print value: End Function End Class Dim i As New MyClass(Of Integer) ' Invalid, U is not provided, silent error i.DumpT(12) ' Valid, uses T = Integer i.DumpU(12) ' Invalid, uses undefined U, causes a codegen/silent error Dim j As New MyClass(Of Integer, Single) ' Correct instantiation j.DumpU(12) ' Valid, uses U = Single ``` ### Type-instances vs object-instances A generic class enables substitution of type variables with type arguments provided in an instantiation. Every utterance of a generic class name with type arguments instantiates the generic class type into a regular class type. ::: info Compile Time: A generic class is instantiated by calling out its name with arguments. Run Time: Objects of those instantiated types can be created. ::: In the example below, two class types are instantiated: **MyClass**(**Integer**) and **MyClass**(**String**). This happens at compile time. No instances of **MyClass** are created at runtime, since both variables default to **Nothing**: ```vb Class MyClass(Of T) ' ... Sub Test() Dim intVar As MyClass(Integer) Dim strVar As MyClass(String) Debug.Assert intVar Is Nothing AndAlso strVar Is Nothing End Sub ``` ### List Class Example A Class generic allows the type in methods throughout the class. The following example shows this to make a generic List class: ```vb [COMCreatable(False)] Class List(Of T) Private mData() As T Sub New(preset() As T) mData = preset End Sub [DefaultMember] Function GetAt(ByVal index&) As T Return mData(index) End Function End Class Sub Test() Dim li As Any = New List(Of Integer)(Array(5, 6, 7)) Debug.Assert li(0) = 5 AndAlso li(2) = 7 End Sub ``` ### List UDT Example While generic UDTs don't support member procedures yet in twinBASIC, the data members are supported: ```vb Type ListU(Of T) value() As T End Type Sub Test() Dim lu As ListU(Of Long) ReDim lu.value(10) lu.value(0) = 5 End Sub ``` \[^1]: DRY = Don't Repeat Yourself --- --- url: /en/official/Reference/Core/Get.md --- # Get Reads data from an open disk file into a variable. ::: info This page documents the **Get** *statement* (file I/O). The unrelated **[Property Get](/en/official/Reference/Core/Property)** procedure form is a different use of the keyword. ::: Syntax: > **Get** \[ **#** ] *filenumber* **,** \[ *recnumber* ] **,** *varname* *filenumber* : Any valid file number. *recnumber* : *optional* **Variant** (**Long**). Record number (**Random** mode files) or byte number (**Binary** mode files) at which reading begins. *varname* : Valid variable name into which data is read. Data read with **Get** is usually written to a file with [**Put**](/en/official/Reference/Core/Put). The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. When *recnumber* is omitted, the next record or byte following the last **Get** or **Put** statement (or pointed to by the last [**Seek**](/en/official/Reference/VBA/FileSystem/Seek) function) is read. The delimiting commas must be included: ```vb Get #4, , FileBuffer ``` For files opened in **Random** mode, the following rules apply: * If the length of the data being read is less than the length specified in the **Len** clause of the [**Open**](/en/official/Reference/Core/Open) statement, **Get** reads subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being read. * If the variable being read into is a variable-length string, **Get** reads a 2-byte descriptor containing the string length and then reads the data that goes into the variable. Therefore, the record length specified by the **Len** clause in the **Open** statement must be at least 2 bytes greater than the actual length of the string. * If the variable being read into is a **Variant** of numeric type, **Get** reads 2 bytes identifying the **VarType** of the **Variant** and then the data that goes into the variable. For example, when reading a **Variant** of **VarType** 3, **Get** reads 6 bytes: 2 bytes identifying the **Variant** as **VarType** 3 (**Long**) and 4 bytes containing the **Long** data. The record length specified by the **Len** clause in the **Open** statement must be at least 2 bytes greater than the actual number of bytes required to store the variable. ::: info Use the **Get** statement to read a **Variant** array from disk; **Get** cannot read a scalar **Variant** containing an array. **Get** also cannot read objects from disk. ::: * If the variable being read into is a **Variant** of **VarType** 8 (**String**), **Get** reads 2 bytes identifying the **VarType**, 2 bytes indicating the length of the string, and then reads the string data. The record length specified by the **Len** clause in the **Open** statement must be at least 4 bytes greater than the actual length of the string. * If the variable being read into is a dynamic array, **Get** reads a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, `2 + 8 * NumberOfDimensions`. The record length specified by the **Len** clause in the **Open** statement must be greater than or equal to the sum of all the bytes required to read the array data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written to disk. ```vb Dim MyArray(1 To 5, 1 To 10) As Integer ``` The 118 bytes are distributed as follows: 18 bytes for the descriptor (`2 + 8 * 2`), and 100 bytes for the data (`5 * 10 * 2`). * If the variable being read into is a fixed-size array, **Get** reads only the data. No descriptor is read. * If the variable being read into is any other type of variable (not a variable-length string or a **Variant**), **Get** reads only the variable data. The record length specified by the **Len** clause in the **Open** statement must be greater than or equal to the length of the data being read. * **Get** reads elements of user-defined types as if each were being read individually, except that there is no padding between elements. On disk, a dynamic array in a user-defined type (written with **Put**) is prefixed by a descriptor whose length equals `2 + 8 * NumberOfDimensions`. The record length specified by the **Len** clause in the **Open** statement must be greater than or equal to the sum of all the bytes required to read the individual elements, including any arrays and their descriptors. For files opened in **Binary** mode, all of the **Random** rules apply, except: * The **Len** clause in the **Open** statement has no effect. **Get** reads all variables from disk contiguously; that is, with no padding between records. * For any array other than an array in a user-defined type, **Get** reads only the data. No descriptor is read. * **Get** reads variable-length strings that aren't elements of user-defined types without expecting the 2-byte length descriptor. The number of bytes read equals the number of characters already in the string. For example, the following statements read 10 bytes from file number 1: ```vb VarString = String(10, " ") Get #1, , VarString ``` ### Example This example uses the **Get** statement to read data from a file into a variable. This example assumes that `TESTFILE` is a file containing five records of the user-defined type `Record`. ```vb Type Record ' Define user-defined type. ID As Integer Name As String * 20 End Type Dim MyRecord As Record, Position ' Declare variables. ' Open sample file for random access. Open "TESTFILE" For Random As #1 Len = Len(MyRecord) ' Read the sample file using the Get statement. Position = 3 ' Define record number. Get #1, Position, MyRecord ' Read third record. Close #1 ' Close file. ``` ### See Also * [**Open** statement](/en/official/Reference/Core/Open) * [**Close** statement](/en/official/Reference/Core/Close) * [**Put** statement](/en/official/Reference/Core/Put) * [**Seek** function](/en/official/Reference/VBA/FileSystem/Seek) --- --- url: /zh/official/Reference/Core/Get.md --- # Get 将数据从打开的磁盘文件读入变量。 ::: info 本页记录 **Get** *语句*(文件I/O)。不相关的 **[Property Get](/official/Reference/Core/Property)** 过程形式是该关键字的不同用法。 ::: 语法: > **Get** \[ **#** ] *filenumber* **,** \[ *recnumber* ] **,** *varname* *filenumber* : 任何有效的文件号。 *recnumber* : *可选* **Variant** (**Long**)。开始读取的记录号(**Random** 模式文件)或字节号(**Binary** 模式文件)。 *varname* : 读入数据的有效变量名。 用 **Get** 读取的数据通常用 [**Put**](/official/Reference/Core/Put) 写入文件。文件中的第一条记录或字节位于位置1,第二条位于位置2,依此类推。省略 *recnumber* 时,读取上次 **Get** 或 **Put** 语句之后的下一条记录或字节(或上次 [**Seek**](/official/Reference/VBA/FileSystem/Seek) 函数指向的位置)。分隔逗号必须包括: ```vb Get #4, , FileBuffer ``` 对于以 **Random** 模式打开的文件,适用以下规则: * 如果读取的数据长度小于 [**Open**](/official/Reference/Core/Open) 语句 **Len** 子句中指定的长度,**Get** 在记录长度边界上读取后续记录。一条记录的末尾与下一条记录开头之间的空间用文件缓冲区的现有内容填充。由于无法确定填充数据量,通常最好让记录长度与读取数据的长度匹配。 * 如果读入的变量是变长字符串,**Get** 读取包含字符串长度的2字节描述符,然后读取进入变量的数据。因此,**Open** 语句中 **Len** 子句指定的记录长度必须至少比字符串的实际长度大2字节。 * 如果读入的变量是数值类型的 **Variant**,**Get** 读取2字节标识 **Variant** 的 **VarType**,然后读取进入变量的数据。例如,读取 **VarType** 3 的 **Variant** 时,**Get** 读取6字节:2字节标识 **Variant** 为 **VarType** 3(**Long**),4字节包含 **Long** 数据。**Open** 语句中 **Len** 子句指定的记录长度必须至少比存储变量所需的实际字节数大2字节。 ::: info 使用 **Get** 语句从磁盘读取 **Variant** 数组;**Get** 不能读取包含数组的标量 **Variant**。**Get** 也不能从磁盘读取对象。 ::: * 如果读入的变量是 **VarType** 8(**String**)的 **Variant**,**Get** 读取2字节标识 **VarType**,2字节指示字符串长度,然后读取字符串数据。**Open** 语句中 **Len** 子句指定的记录长度必须至少比字符串的实际长度大4字节。 * 如果读入的变量是动态数组,**Get** 读取长度等于2加8乘维数的描述符,即 `2 + 8 * NumberOfDimensions`。**Open** 语句中 **Len** 子句指定的记录长度必须大于或等于读取数组数据和数组描述符所需的所有字节之和。例如,以下数组声明在数组写入磁盘时需要118字节。 ```vb Dim MyArray(1 To 5, 1 To 10) As Integer ``` 118字节分布如下:18字节用于描述符(`2 + 8 * 2`),100字节用于数据(`5 * 10 * 2`)。 * 如果读入的变量是固定大小数组,**Get** 仅读取数据。不读取描述符。 * 如果读入的变量是任何其他类型的变量(不是变长字符串或 **Variant**),**Get** 仅读取变量数据。**Open** 语句中 **Len** 子句指定的记录长度必须大于或等于读取数据的长度。 * **Get** 读取用户自定义类型的元素就像每个元素单独读取一样,但元素之间没有填充。在磁盘上,用户自定义类型中的动态数组(用 **Put** 写入)前面有一个长度等于 `2 + 8 * NumberOfDimensions` 的描述符。**Open** 语句中 **Len** 子句指定的记录长度必须大于或等于读取各元素(包括任何数组及其描述符)所需的所有字节之和。 对于以 **Binary** 模式打开的文件,所有 **Random** 规则均适用,除了: * **Open** 语句中的 **Len** 子句无效。**Get** 从磁盘连续读取所有变量;即记录之间没有填充。 * 对于用户自定义类型以外的任何数组,**Get** 仅读取数据。不读取描述符。 * **Get** 读取不是用户自定义类型元素的变长字符串时,不期望2字节长度描述符。读取的字节数等于字符串中已有的字符数。例如,以下语句从文件号1读取10字节: ```vb VarString = String(10, " ") Get #1, , VarString ``` ### 示例 本示例使用 **Get** 语句从文件读取数据到变量。本示例假设 `TESTFILE` 是包含用户自定义类型 `Record` 的五条记录的文件。 ```vb Type Record ' Define user-defined type. ID As Integer Name As String * 20 End Type Dim MyRecord As Record, Position ' Declare variables. ' Open sample file for random access. Open "TESTFILE" For Random As #1 Len = Len(MyRecord) ' Read the sample file using the Get statement. Position = 3 ' Define record number. Get #1, Position, MyRecord ' Read third record. Close #1 ' Close file. ``` ### 另请参阅 * [**Open** 语句](/official/Reference/Core/Open) * [**Close** 语句](/official/Reference/Core/Close) * [**Put** 语句](/official/Reference/Core/Put) * [**Seek** 函数](/official/Reference/VBA/FileSystem/Seek) --- --- url: /en/official/Reference/VBA/Interaction/GetAllSettings.md --- # GetAllSettings Returns every key and its value in a section of an application's entry in the Windows registry. Syntax: **GetAllSettings(** *appname* **,** *section* **)** *appname* : *required* String expression containing the name of the application or project whose key settings are requested. *section* : *required* String expression containing the name of the section whose key settings are requested. Returns a **Variant** whose contents are a two-dimensional array of strings: each row holds one key and its value, in columns 0 and 1 respectively. **GetAllSettings** returns an uninitialized **Variant** if either *appname* or *section* does not exist. The root of these registry settings is: `Computer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings`. ### Example This example first uses [**SaveSetting**](/en/official/Reference/VBA/Interaction/SaveSetting) to make entries in the Windows registry for the application, then uses **GetAllSettings** to display every key/value in a section, and finally uses [**DeleteSetting**](/en/official/Reference/VBA/Interaction/DeleteSetting) to remove the application's entries. Note that the *appname* and *section* names themselves are not retrieved. ```vb ' Place some settings in the registry. SaveSetting AppName := "MyApp", Section := "Startup", _ Key := "Top", Setting := "75" SaveSetting "MyApp", "Startup", "Left", "50" ' Retrieve them. Dim MySettings As Variant, IntSettings As Long MySettings = GetAllSettings(AppName := "MyApp", Section := "Startup") For IntSettings = LBound(MySettings, 1) To UBound(MySettings, 1) Debug.Print MySettings(IntSettings, 0), MySettings(IntSettings, 1) Next IntSettings DeleteSetting "MyApp", "Startup" ``` ### See Also * [DeleteSetting](/en/official/Reference/VBA/Interaction/DeleteSetting) statement * [GetSetting](/en/official/Reference/VBA/Interaction/GetSetting) function * [SaveSetting](/en/official/Reference/VBA/Interaction/SaveSetting) statement --- --- url: /zh/official/Reference/VBA/Interaction/GetAllSettings.md --- # GetAllSettings 返回Windows注册表中应用程序条目某个节中的每个键及其值。 语法:**GetAllSettings(** *appname* **,** *section* **)** *appname* : *必需* 字符串表达式,包含请求其键设置的应用程序或项目的名称。 *section* : *必需* 字符串表达式,包含请求其键设置的节的名称。 返回一个**Variant**,其内容为二维字符串数组:每行包含一个键及其值,分别在第0列和第1列。如果*appname*或*section*不存在,**GetAllSettings**返回未初始化的**Variant**。 这些注册表设置的根路径为:`Computer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings`。 ### 示例 本示例首先使用[**SaveSetting**](/official/Reference/VBA/Interaction/SaveSetting)在Windows注册表中为应用程序创建条目,然后使用**GetAllSettings**显示某个节中的所有键值对,最后使用[**DeleteSetting**](/official/Reference/VBA/Interaction/DeleteSetting)删除应用程序的条目。注意*appname*和*section*名称本身不会被检索。 ```vb ' Place some settings in the registry. SaveSetting AppName := "MyApp", Section := "Startup", _ Key := "Top", Setting := "75" SaveSetting "MyApp", "Startup", "Left", "50" ' Retrieve them. Dim MySettings As Variant, IntSettings As Long MySettings = GetAllSettings(AppName := "MyApp", Section := "Startup") For IntSettings = LBound(MySettings, 1) To UBound(MySettings, 1) Debug.Print MySettings(IntSettings, 0), MySettings(IntSettings, 1) Next IntSettings DeleteSetting "MyApp", "Startup" ``` ### 另请参阅 * [DeleteSetting](/official/Reference/VBA/Interaction/DeleteSetting)语句 * [GetSetting](/official/Reference/VBA/Interaction/GetSetting)函数 * [SaveSetting](/official/Reference/VBA/Interaction/SaveSetting)语句 --- --- url: /en/official/Reference/VBA/FileSystem/GetAttr.md --- # GetAttr Returns an **Integer** representing the attributes of a file, directory, or folder. Syntax: **GetAttr(** *pathname* **)** *pathname* : *required* String expression that specifies a file name. The *pathname* may include the directory or folder, and the drive. ### Return Values The value returned by **GetAttr** is the sum of the following attribute values: | Constant | Value | Description | |-----------------|:-----:|------------------------| | **vbNormal** | 0 | Normal. | | **vbReadOnly** | 1 | Read-only. | | **vbHidden** | 2 | Hidden. | | **vbSystem** | 4 | System file. | | **vbDirectory** | 16 | Directory or folder. | | **vbArchive** | 32 | File has changed since last backup. | To determine which attributes are set, use the **And** operator to perform a bitwise comparison of the value returned by **GetAttr** and the value of the individual file attribute being tested. If the result is not zero, that attribute is set for the named file. ```vb Result = GetAttr(FName) And vbArchive ``` A nonzero value is returned if the Archive attribute is set. ### Example This example uses the **GetAttr** function to determine the attributes of a file and directory or folder. ```vb Dim MyAttr ' Assume file TESTFILE has hidden attribute set. MyAttr = GetAttr("TESTFILE") ' Returns 2. ' Returns nonzero if hidden attribute is set on TESTFILE. Debug.Print MyAttr And vbHidden ' Assume file TESTFILE has hidden and read-only attributes set. MyAttr = GetAttr("TESTFILE") ' Returns 3. ' Returns nonzero if hidden attribute is set on TESTFILE. Debug.Print MyAttr And (vbHidden + vbReadOnly) ' Assume MYDIR is a directory or folder. MyAttr = GetAttr("MYDIR") ' Returns 16. ``` ### See Also * [Dir](/en/official/Reference/VBA/FileSystem/Dir) function --- --- url: /zh/official/Reference/VBA/FileSystem/GetAttr.md --- # GetAttr 返回一个**Integer**,表示文件、目录或文件夹的属性。 语法:**GetAttr(** *pathname* **)** *pathname* : *必需* 字符串表达式,指定文件名。*pathname*可以包含目录或文件夹以及驱动器。 ### 返回值 **GetAttr**返回的值是以下属性值之和: | 常量 | 值 | 描述 | |-----------------|:---:|------------------------------------| | **vbNormal** | 0 | 普通。 | | **vbReadOnly** | 1 | 只读。 | | **vbHidden** | 2 | 隐藏。 | | **vbSystem** | 4 | 系统文件。 | | **vbDirectory** | 16 | 目录或文件夹。 | | **vbArchive** | 32 | 自上次备份后文件已更改。 | 要确定设置了哪些属性,请使用**And**运算符对**GetAttr**返回的值与要测试的单个文件属性值进行按位比较。如果结果不为零,则该文件的该属性已设置。 ```vb Result = GetAttr(FName) And vbArchive ``` 如果设置了存档属性,则返回非零值。 ### 示例 本示例使用**GetAttr**函数确定文件和目录或文件夹的属性。 ```vb Dim MyAttr ' Assume file TESTFILE has hidden attribute set. MyAttr = GetAttr("TESTFILE") ' Returns 2. ' Returns nonzero if hidden attribute is set on TESTFILE. Debug.Print MyAttr And vbHidden ' Assume file TESTFILE has hidden and read-only attributes set. MyAttr = GetAttr("TESTFILE") ' Returns 3. ' Returns nonzero if hidden attribute is set on TESTFILE. Debug.Print MyAttr And (vbHidden + vbReadOnly) ' Assume MYDIR is a directory or folder. MyAttr = GetAttr("MYDIR") ' Returns 16. ``` ### 另请参阅 * [Dir](/official/Reference/VBA/FileSystem/Dir)函数 --- --- url: /en/official/Reference/VBRUN/DataObject/GetData.md --- # GetData Returns the value previously stored in the **DataObject** under the given clipboard format, as a **Variant**. Syntax: *object*.**GetData(** *Format* **)** *object* : *required* An object expression that evaluates to a **DataObject**. *Format* : *required* A **ClipboardConstants** value identifying the format to read back --- for example `vbCFText`, `vbCFUnicodeText`, `vbCFBitmap`. If the **DataObject** does not contain data in *Format*, the result is **Empty**; check first with [**GetFormat**](/en/official/Reference/VBRUN/DataObject/GetFormat) when the format may not be present. The concrete subtype of the returned **Variant** depends on *Format*: text formats yield a **String**, `vbCFBitmap` yields an **stdole.IPictureDisp**, `vbCFFiles` yields a path or a path collection, and so on. To pull data out by a textual format name rather than a numeric clipboard constant, use [**GetDataByName**](/en/official/Reference/VBRUN/DataObject/GetDataByName). ### Example ```vb If Data.GetFormat(vbCFText) Then Dim Text As String Text = Data.GetData(vbCFText) Debug.Print Text End If ``` ### See Also * [GetDataByName](/en/official/Reference/VBRUN/DataObject/GetDataByName) method * [GetFormat](/en/official/Reference/VBRUN/DataObject/GetFormat) method * [SetData](/en/official/Reference/VBRUN/DataObject/SetData) method * [AvailableFormats](/en/official/Reference/VBRUN/DataObject/AvailableFormats) method --- --- url: /zh/official/Reference/VBRUN/DataObject/GetData.md --- # GetData 返回先前以给定剪贴板格式存储在**DataObject**中的值,类型为**Variant**。 语法:*object*.**GetData(** *Format* **)** *object* : *必需* 求值为**DataObject**的对象表达式。 *Format* : *必需* 标识要读回格式的**ClipboardConstants**值——例如`vbCFText`、`vbCFUnicodeText`、`vbCFBitmap`。如果**DataObject**不包含*Format*的数据,结果为**Empty**;当格式可能不存在时,请先使用[**GetFormat**](/official/Reference/VBRUN/DataObject/GetFormat)检查。 返回的**Variant**的具体子类型取决于*Format*:文本格式产生**String**,`vbCFBitmap`产生**stdole.IPictureDisp**,`vbCFFiles`产生路径或路径集合,等等。要按文本格式名称而非数字剪贴板常量提取数据,请使用[**GetDataByName**](/official/Reference/VBRUN/DataObject/GetDataByName)。 ### 示例 ```vb If Data.GetFormat(vbCFText) Then Dim Text As String Text = Data.GetData(vbCFText) Debug.Print Text End If ``` ### 另见 * [GetDataByName](/official/Reference/VBRUN/DataObject/GetDataByName) 方法 * [GetFormat](/official/Reference/VBRUN/DataObject/GetFormat) 方法 * [SetData](/official/Reference/VBRUN/DataObject/SetData) 方法 * [AvailableFormats](/official/Reference/VBRUN/DataObject/AvailableFormats) 方法 --- --- url: /en/official/Reference/VBRUN/DataObject/GetDataByName.md --- # GetDataByName Returns the value previously stored in the **DataObject** under a format identified by name, as a **Variant**. Syntax: *object*.**GetDataByName(** *Format* **)** *object* : *required* An object expression that evaluates to a **DataObject**. *Format* : *required* A **String** giving the name of the format to read back --- typically the name a custom clipboard format was registered under with `RegisterClipboardFormat`. If the **DataObject** does not contain data in *Format*, the result is **Empty**; check first with [**GetFormatByName**](/en/official/Reference/VBRUN/DataObject/GetFormatByName) when the format may not be present. ::: info **GetDataByName** is a twinBASIC addition; it has no equivalent in VB6. Use it when the consumer side knows the format only by its registered name and does not have the corresponding numeric identifier available. For the standard built-in formats, [**GetData**](/en/official/Reference/VBRUN/DataObject/GetData) with a **ClipboardConstants** value is more direct. ::: ### Example ```vb If Data.GetFormatByName("HTML Format") Then Dim Html As String Html = Data.GetDataByName("HTML Format") End If ``` ### See Also * [GetData](/en/official/Reference/VBRUN/DataObject/GetData) method * [GetFormatByName](/en/official/Reference/VBRUN/DataObject/GetFormatByName) method * [AvailableFormats](/en/official/Reference/VBRUN/DataObject/AvailableFormats) method --- --- url: /zh/official/Reference/VBRUN/DataObject/GetDataByName.md --- # GetDataByName 返回先前以名称标识的格式存储在**DataObject**中的值,类型为**Variant**。 语法:*object*.**GetDataByName(** *Format* **)** *object* : *必需* 求值为**DataObject**的对象表达式。 *Format* : *必需* 给出要读回格式名称的**String**——通常是自定义剪贴板格式通过`RegisterClipboardFormat`注册的名称。如果**DataObject**不包含*Format*的数据,结果为**Empty**;当格式可能不存在时,请先使用[**GetFormatByName**](/official/Reference/VBRUN/DataObject/GetFormatByName)检查。 ::: info **GetDataByName**是twinBASIC新增功能;VB6中没有对应功能。当消费端只知道格式的注册名称而没有相应的数字标识符时使用。对于标准内置格式,使用带**ClipboardConstants**值的[**GetData**](/official/Reference/VBRUN/DataObject/GetData)更直接。 ::: ### 示例 ```vb If Data.GetFormatByName("HTML Format") Then Dim Html As String Html = Data.GetDataByName("HTML Format") End If ``` ### 另见 * [GetData](/official/Reference/VBRUN/DataObject/GetData) 方法 * [GetFormatByName](/official/Reference/VBRUN/DataObject/GetFormatByName) 方法 * [AvailableFormats](/official/Reference/VBRUN/DataObject/AvailableFormats) 方法 --- --- url: /en/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue.md --- # GetDeclaredMaxEnumValue Returns the largest member value of a declared enumeration type, resolved at compile time. Syntax: **GetDeclaredMaxEnumValue(Of** *T* **)()** **As Long** *T* : *required* The enumeration type to query. Iterates over the members of *T* and returns the highest assigned value. Resolved at compile time and folded into the generated code as a numeric constant --- there is no run-time iteration. ### See Also * [GetDeclaredMinEnumValue](/en/official/Reference/VBA/HiddenModule/GetDeclaredMinEnumValue) function --- --- url: /zh/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue.md --- # GetDeclaredMaxEnumValue 返回已声明枚举类型的最大成员值,在编译时解析。 语法:**GetDeclaredMaxEnumValue(Of** *T* **)()** **As Long** *T* : *必需* 要查询的枚举类型。 遍历*T*的成员并返回最高的赋值。在编译时解析,并作为数值常量折叠到生成的代码中——没有运行时遍历。 ### 另请参阅 * [GetDeclaredMinEnumValue](/official/Reference/VBA/HiddenModule/GetDeclaredMinEnumValue)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/GetDeclaredMinEnumValue.md --- # GetDeclaredMinEnumValue Returns the smallest member value of a declared enumeration type, resolved at compile time. Syntax: **GetDeclaredMinEnumValue(Of** *T* **)()** **As Long** *T* : *required* The enumeration type to query. Iterates over the members of *T* and returns the lowest assigned value. Resolved at compile time and folded into the generated code as a numeric constant --- there is no run-time iteration. ### Example ```vb Enum Severity Trace = 0 Debug = 1 Info = 2 Warning = 3 Error = 4 End Enum Debug.Print GetDeclaredMinEnumValue(Of Severity)() ' 0 Debug.Print GetDeclaredMaxEnumValue(Of Severity)() ' 4 ``` ### See Also * [GetDeclaredMaxEnumValue](/en/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue) function --- --- url: /zh/official/Reference/VBA/HiddenModule/GetDeclaredMinEnumValue.md --- # GetDeclaredMinEnumValue 返回已声明枚举类型的最小成员值,在编译时解析。 语法:**GetDeclaredMinEnumValue(Of** *T* **)()** **As Long** *T* : *必需* 要查询的枚举类型。 遍历*T*的成员并返回最低的赋值。在编译时解析,并作为数值常量折叠到生成的代码中——没有运行时遍历。 ### 示例 ```vb Enum Severity Trace = 0 Debug = 1 Info = 2 Warning = 3 Error = 4 End Enum Debug.Print GetDeclaredMinEnumValue(Of Severity)() ' 0 Debug.Print GetDeclaredMaxEnumValue(Of Severity)() ' 4 ``` ### 另请参阅 * [GetDeclaredMaxEnumValue](/official/Reference/VBA/HiddenModule/GetDeclaredMaxEnumValue)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid.md --- # GetDeclaredTypeClsid Returns the COM CLSID (class identifier) associated with a declared type, resolved at compile time. Syntax: **GetDeclaredTypeClsid(Of** *T* **)()** **As String** *T* : *required* The type to query for. Typically a coclass declared with the **CoClassId** attribute or imported from a type library. The CLSID is returned in registry format (`{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}`). The lookup happens at compile time and the result is stored in the generated code as a string literal --- there is no run-time call. Returns an empty string if the type has no associated CLSID. ### See Also * [GetDeclaredTypeProgId](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId) function * [GetDeclaredTypeIid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid) function * [GetDeclaredTypeEventIid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid) function --- --- url: /zh/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid.md --- # GetDeclaredTypeClsid 返回与已声明类型关联的COM CLSID(类标识符),在编译时解析。 语法:**GetDeclaredTypeClsid(Of** *T* **)()** **As String** *T* : *必需* 要查询的类型。通常是使用**CoClassId**属性声明的coclass或从类型库导入的类型。 CLSID以注册表格式返回(`{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}`)。查找在编译时进行,结果作为字符串字面值存储在生成的代码中——没有运行时调用。 如果类型没有关联的CLSID,则返回空字符串。 ### 另请参阅 * [GetDeclaredTypeProgId](/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId)函数 * [GetDeclaredTypeIid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid)函数 * [GetDeclaredTypeEventIid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid.md --- # GetDeclaredTypeEventIid Returns the IID of the COM event interface associated with a declared type, resolved at compile time. Syntax: **GetDeclaredTypeEventIid(Of** *T* **)()** **As String** *T* : *required* The type to query for. Typically a coclass that exposes events via the **EventInterfaceId** attribute or imported from a type library. The IID is returned in registry format (`{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}`). The lookup happens at compile time and the result is stored in the generated code as a string literal --- there is no run-time call. Returns an empty string if the type has no associated event interface. ### See Also * [GetDeclaredTypeIid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid) function * [GetDeclaredTypeProgId](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId) function * [GetDeclaredTypeClsid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid) function --- --- url: /zh/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid.md --- # GetDeclaredTypeEventIid 返回与已声明类型关联的COM事件接口的IID,在编译时解析。 语法:**GetDeclaredTypeEventIid(Of** *T* **)()** **As String** *T* : *必需* 要查询的类型。通常是通过**EventInterfaceId**属性暴露事件的coclass或从类型库导入的类型。 IID以注册表格式返回(`{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}`)。查找在编译时进行,结果作为字符串字面值存储在生成的代码中——没有运行时调用。 如果类型没有关联的事件接口,则返回空字符串。 ### 另请参阅 * [GetDeclaredTypeIid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid)函数 * [GetDeclaredTypeProgId](/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId)函数 * [GetDeclaredTypeClsid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid.md --- # GetDeclaredTypeIid Returns the COM interface IID associated with a declared type, resolved at compile time. Syntax: **GetDeclaredTypeIid(Of** *T* **)()** **As String** *T* : *required* The type to query for. Typically an interface declared with the **InterfaceId** attribute or imported from a type library. The IID is returned in registry format (`{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}`). The lookup happens at compile time and the result is stored in the generated code as a string literal --- there is no run-time call. Useful when calling [**vbaCastObj**](/en/official/Reference/VBA/HiddenModule/vbaCastObj) or any API that takes an interface IID as a string. ### Example ```vb Dim Iid As String = GetDeclaredTypeIid(Of stdole.IPicture)() Dim AsPic As IUnknown = vbaCastObj(SomeObj, Iid) ``` ### See Also * [GetDeclaredTypeProgId](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId) function * [GetDeclaredTypeClsid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid) function * [GetDeclaredTypeEventIid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid) function * [vbaCastObj](/en/official/Reference/VBA/HiddenModule/vbaCastObj) function --- --- url: /zh/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid.md --- # GetDeclaredTypeIid 返回与已声明类型关联的COM接口IID,在编译时解析。 语法:**GetDeclaredTypeIid(Of** *T* **)()** **As String** *T* : *必需* 要查询的类型。通常是使用**InterfaceId**属性声明的接口或从类型库导入的类型。 IID以注册表格式返回(`{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}`)。查找在编译时进行,结果作为字符串字面值存储在生成的代码中——没有运行时调用。 在调用[**vbaCastObj**](/official/Reference/VBA/HiddenModule/vbaCastObj)或任何以接口IID字符串为参数的API时非常有用。 ### 示例 ```vb Dim Iid As String = GetDeclaredTypeIid(Of stdole.IPicture)() Dim AsPic As IUnknown = vbaCastObj(SomeObj, Iid) ``` ### 另请参阅 * [GetDeclaredTypeProgId](/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId)函数 * [GetDeclaredTypeClsid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid)函数 * [GetDeclaredTypeEventIid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid)函数 * [vbaCastObj](/official/Reference/VBA/HiddenModule/vbaCastObj)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId.md --- # GetDeclaredTypeProgId Returns the COM ProgID associated with a declared type, resolved at compile time. Syntax: **GetDeclaredTypeProgId(Of** *T* **)()** **As String** *T* : *required* The type to query for. Typically a coclass declared with the **CoClassId** attribute or imported from a type library. The ProgID is the human-readable name (`Application.Object`, `Scripting.Dictionary`, ...) that matches *T*'s CLSID in the registry. The lookup happens at compile time and the result is stored in the generated code as a string literal --- there is no run-time call. Returns an empty string if the type has no associated ProgID. ### Example ```vb Dim Id As String = GetDeclaredTypeProgId(Of MyApp.Document)() Debug.Print Id ' "MyApp.Document" ``` ### See Also * [GetDeclaredTypeClsid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid) function * [GetDeclaredTypeIid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid) function * [GetDeclaredTypeEventIid](/en/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid) function --- --- url: /zh/official/Reference/VBA/HiddenModule/GetDeclaredTypeProgId.md --- # GetDeclaredTypeProgId 返回与已声明类型关联的COM ProgID,在编译时解析。 语法:**GetDeclaredTypeProgId(Of** *T* **)()** **As String** *T* : *必需* 要查询的类型。通常是使用**CoClassId**属性声明的coclass或从类型库导入的类型。 ProgID是可读名称(`Application.Object`、`Scripting.Dictionary`等),在注册表中与*T*的CLSID匹配。查找在编译时进行,结果作为字符串字面值存储在生成的代码中——没有运行时调用。 如果类型没有关联的ProgID,则返回空字符串。 ### 示例 ```vb Dim Id As String = GetDeclaredTypeProgId(Of MyApp.Document)() Debug.Print Id ' "MyApp.Document" ``` ### 另请参阅 * [GetDeclaredTypeClsid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeClsid)函数 * [GetDeclaredTypeIid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeIid)函数 * [GetDeclaredTypeEventIid](/official/Reference/VBA/HiddenModule/GetDeclaredTypeEventIid)函数 --- --- url: /en/official/Reference/VBRUN/DataObject/GetFormat.md --- # GetFormat Returns whether the **DataObject** holds a value in the given clipboard format, as a **Boolean**. Syntax: *object*.**GetFormat(** *Format* **)** *object* : *required* An object expression that evaluates to a **DataObject**. *Format* : *required* A **ClipboardConstants** value identifying the format to test for --- for example `vbCFText`, `vbCFUnicodeText`, `vbCFBitmap`, `vbCFFiles`. The result is **True** if the **DataObject** can produce a value in *Format*, **False** otherwise. Use this before calling [**GetData**](/en/official/Reference/VBRUN/DataObject/GetData) when the format may not be present, so that an unknown format does not silently return **Empty**. ### Example ```vb If Data.GetFormat(vbCFFiles) Then Dim Path As Variant For Each Path In Data.Files Debug.Print Path Next Path End If ``` ### See Also * [GetData](/en/official/Reference/VBRUN/DataObject/GetData) method * [GetFormatByName](/en/official/Reference/VBRUN/DataObject/GetFormatByName) method * [AvailableFormats](/en/official/Reference/VBRUN/DataObject/AvailableFormats) method * [SetData](/en/official/Reference/VBRUN/DataObject/SetData) method --- --- url: /zh/official/Reference/VBRUN/DataObject/GetFormat.md --- # GetFormat 返回**DataObject**是否保存给定剪贴板格式的值,类型为**Boolean**。 语法:*object*.**GetFormat(** *Format* **)** *object* : *必需* 求值为**DataObject**的对象表达式。 *Format* : *必需* 标识要测试格式的**ClipboardConstants**值——例如`vbCFText`、`vbCFUnicodeText`、`vbCFBitmap`、`vbCFFiles`。 如果**DataObject**可以在*Format*中产生值,结果为**True**,否则为**False**。当格式可能不存在时,在调用[**GetData**](/official/Reference/VBRUN/DataObject/GetData)之前使用此方法,以免未知格式静默返回**Empty**。 ### 示例 ```vb If Data.GetFormat(vbCFFiles) Then Dim Path As Variant For Each Path In Data.Files Debug.Print Path Next Path End If ``` ### 另见 * [GetData](/official/Reference/VBRUN/DataObject/GetData) 方法 * [GetFormatByName](/official/Reference/VBRUN/DataObject/GetFormatByName) 方法 * [AvailableFormats](/official/Reference/VBRUN/DataObject/AvailableFormats) 方法 * [SetData](/official/Reference/VBRUN/DataObject/SetData) 方法 --- --- url: /en/official/Reference/VBRUN/DataObject/GetFormatByName.md --- # GetFormatByName Returns whether the **DataObject** holds a value in a format identified by name, as a **Boolean**. Syntax: *object*.**GetFormatByName(** *Format* **)** *object* : *required* An object expression that evaluates to a **DataObject**. *Format* : *required* A **String** giving the name of the format to test for --- typically the name a custom clipboard format was registered under with `RegisterClipboardFormat`. The result is **True** if the **DataObject** can produce a value in *Format*, **False** otherwise. Use this before calling [**GetDataByName**](/en/official/Reference/VBRUN/DataObject/GetDataByName) when the format may not be present. ::: info **GetFormatByName** is a twinBASIC addition; it has no equivalent in VB6. For the standard built-in formats, [**GetFormat**](/en/official/Reference/VBRUN/DataObject/GetFormat) with a **ClipboardConstants** value is more direct. ::: ### Example ```vb If Data.GetFormatByName("HTML Format") Then Dim Html As String Html = Data.GetDataByName("HTML Format") End If ``` ### See Also * [GetDataByName](/en/official/Reference/VBRUN/DataObject/GetDataByName) method * [GetFormat](/en/official/Reference/VBRUN/DataObject/GetFormat) method * [AvailableFormats](/en/official/Reference/VBRUN/DataObject/AvailableFormats) method --- --- url: /zh/official/Reference/VBRUN/DataObject/GetFormatByName.md --- # GetFormatByName 返回**DataObject**是否保存以名称标识的格式的值,类型为**Boolean**。 语法:*object*.**GetFormatByName(** *Format* **)** *object* : *必需* 求值为**DataObject**的对象表达式。 *Format* : *必需* 给出要测试格式名称的**String**——通常是自定义剪贴板格式通过`RegisterClipboardFormat`注册的名称。 如果**DataObject**可以在*Format*中产生值,结果为**True**,否则为**False**。当格式可能不存在时,在调用[**GetDataByName**](/official/Reference/VBRUN/DataObject/GetDataByName)之前使用此方法。 ::: info **GetFormatByName**是twinBASIC新增功能;VB6中没有对应功能。对于标准内置格式,使用带**ClipboardConstants**值的[**GetFormat**](/official/Reference/VBRUN/DataObject/GetFormat)更直接。 ::: ### 示例 ```vb If Data.GetFormatByName("HTML Format") Then Dim Html As String Html = Data.GetDataByName("HTML Format") End If ``` ### 另见 * [GetDataByName](/official/Reference/VBRUN/DataObject/GetDataByName) 方法 * [GetFormat](/official/Reference/VBRUN/DataObject/GetFormat) 方法 * [AvailableFormats](/official/Reference/VBRUN/DataObject/AvailableFormats) 方法 --- --- url: /en/official/Reference/VBA/HiddenModule/GetInheritedOwner.md --- # GetInheritedOwner Returns the inherited owner object of a control. Syntax: **GetInheritedOwner(** *Value* **)** **As Object** *Value* : *required* **Object**. The control whose inherited owner is wanted. For controls that participate in a control-container hierarchy, the inherited owner is the topmost owning object that supplies ambient settings --- typically the form. Returns **Nothing** when no inherited owner is set. ### Example This example reads the topmost container of a control and reports its type. ```vb ' Inside a VB control class Dim host As Object host = GetInheritedOwner(Me) If Not host Is Nothing Then Debug.Print "Container: " & TypeName(host) End If ``` ### See Also * [vbaCastObj](/en/official/Reference/VBA/HiddenModule/vbaCastObj) function --- --- url: /zh/official/Reference/VBA/HiddenModule/GetInheritedOwner.md --- # GetInheritedOwner 返回控件的继承所有者对象。 语法:**GetInheritedOwner(** *Value* **)** **As Object** *Value* : *必需* **Object**。要获取其继承所有者的控件。 对于参与控件容器层次结构的控件,继承所有者是提供环境设置的最上层拥有对象——通常是窗体。当没有设置继承所有者时返回**Nothing**。 ### 示例 本示例读取控件的最上层容器并报告其类型。 ```vb ' Inside a VB control class Dim host As Object host = GetInheritedOwner(Me) If Not host Is Nothing Then Debug.Print "Container: " & TypeName(host) End If ``` ### 另请参阅 * [vbaCastObj](/official/Reference/VBA/HiddenModule/vbaCastObj)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/GetMem1.md --- # GetMem1 Reads one byte from a memory address into a **Byte** variable. Syntax: **GetMem1** *Address* **,** *retVal* *Address* : *required* **LongPtr**. The address to read from. *retVal* : *required* **Byte**. The variable to receive the byte read from *Address*. The address is read directly with no bounds or alignment check. Reading from an address that does not belong to the process, or from one that has been freed, will crash the host. ### Example ```vb Dim s As String = "ABC" Dim b As Byte GetMem1 StrPtr(s), b Debug.Print b ' 65 — the low byte of the UTF-16 code unit for "A". ``` ### See Also * [GetMem2](/en/official/Reference/VBA/HiddenModule/GetMem2), [GetMem4](/en/official/Reference/VBA/HiddenModule/GetMem4), [GetMem8](/en/official/Reference/VBA/HiddenModule/GetMem8), [GetMemPtr](/en/official/Reference/VBA/HiddenModule/GetMemPtr) procedures * [PutMem1](/en/official/Reference/VBA/HiddenModule/PutMem1) procedure --- --- url: /zh/official/Reference/VBA/HiddenModule/GetMem1.md --- # GetMem1 从内存地址读取一个字节到**Byte**变量中。 语法:**GetMem1** *Address* **,** *retVal* *Address* : *必需* **LongPtr**。要读取的地址。 *retVal* : *必需* **Byte**。接收从*Address*读取的字节的变量。 直接读取地址,不进行边界或对齐检查。从不属于进程的地址或已释放的地址读取将导致宿主崩溃。 ### 示例 ```vb Dim s As String = "ABC" Dim b As Byte GetMem1 StrPtr(s), b Debug.Print b ' 65 — the low byte of the UTF-16 code unit for "A". ``` ### 另请参阅 * [GetMem2](/official/Reference/VBA/HiddenModule/GetMem2)、[GetMem4](/official/Reference/VBA/HiddenModule/GetMem4)、[GetMem8](/official/Reference/VBA/HiddenModule/GetMem8)、[GetMemPtr](/official/Reference/VBA/HiddenModule/GetMemPtr)过程 * [PutMem1](/official/Reference/VBA/HiddenModule/PutMem1)过程 --- --- url: /en/official/Reference/VBA/HiddenModule/GetMem2.md --- # GetMem2 Reads two bytes from a memory address into an **Integer** variable. Syntax: **GetMem2** *Address* **,** *retVal* *Address* : *required* **LongPtr**. The address to read from. *retVal* : *required* **Integer**. The variable to receive the value read from *Address*. The bytes are interpreted in the host's native byte order --- little-endian on x86 and x64. The address is read directly with no bounds or alignment check. ### Example This example writes a 16-bit value to a buffer and reads it back with **GetMem2**. ```vb Dim buf As LongPtr = AllocMem(4) PutMem2 buf, &H1234 Dim v As Integer GetMem2 buf, v ' v = &H1234 FreeMem buf ``` ### See Also * [GetMem1](/en/official/Reference/VBA/HiddenModule/GetMem1), [GetMem4](/en/official/Reference/VBA/HiddenModule/GetMem4), [GetMem8](/en/official/Reference/VBA/HiddenModule/GetMem8), [GetMemPtr](/en/official/Reference/VBA/HiddenModule/GetMemPtr) procedures * [PutMem2](/en/official/Reference/VBA/HiddenModule/PutMem2) procedure --- --- url: /zh/official/Reference/VBA/HiddenModule/GetMem2.md --- # GetMem2 从内存地址读取两个字节到**Integer**变量中。 语法:**GetMem2** *Address* **,** *retVal* *Address* : *必需* **LongPtr**。要读取的地址。 *retVal* : *必需* **Integer**。接收从*Address*读取的值的变量。 字节按宿主的本机字节序解释——x86和x64上为小端序。直接读取地址,不进行边界或对齐检查。 ### 示例 本示例将一个16位值写入缓冲区并用**GetMem2**读回。 ```vb Dim buf As LongPtr = AllocMem(4) PutMem2 buf, &H1234 Dim v As Integer GetMem2 buf, v ' v = &H1234 FreeMem buf ``` ### 另请参阅 * [GetMem1](/official/Reference/VBA/HiddenModule/GetMem1)、[GetMem4](/official/Reference/VBA/HiddenModule/GetMem4)、[GetMem8](/official/Reference/VBA/HiddenModule/GetMem8)、[GetMemPtr](/official/Reference/VBA/HiddenModule/GetMemPtr)过程 * [PutMem2](/official/Reference/VBA/HiddenModule/PutMem2)过程 --- --- url: /en/official/Reference/VBA/HiddenModule/GetMem4.md --- # GetMem4 Reads four bytes from a memory address into a **Long** variable. Syntax: **GetMem4** *Address* **,** *retVal* *Address* : *required* **LongPtr**. The address to read from. *retVal* : *required* **Long**. The variable to receive the value read from *Address*. The bytes are interpreted in the host's native byte order --- little-endian on x86 and x64. The address is read directly with no bounds or alignment check. ### Example This example writes a 32-bit value to a buffer and reads it back with **GetMem4**. ```vb Dim buf As LongPtr = AllocMem(4) PutMem4 buf, &H12345678 Dim v As Long GetMem4 buf, v ' v = &H12345678 FreeMem buf ``` ### See Also * [GetMem1](/en/official/Reference/VBA/HiddenModule/GetMem1), [GetMem2](/en/official/Reference/VBA/HiddenModule/GetMem2), [GetMem8](/en/official/Reference/VBA/HiddenModule/GetMem8), [GetMemPtr](/en/official/Reference/VBA/HiddenModule/GetMemPtr) procedures * [PutMem4](/en/official/Reference/VBA/HiddenModule/PutMem4) procedure --- --- url: /zh/official/Reference/VBA/HiddenModule/GetMem4.md --- # GetMem4 从内存地址读取四个字节到**Long**变量中。 语法:**GetMem4** *Address* **,** *retVal* *Address* : *必需* **LongPtr**。要读取的地址。 *retVal* : *必需* **Long**。接收从*Address*读取的值的变量。 字节按宿主的本机字节序解释——x86和x64上为小端序。直接读取地址,不进行边界或对齐检查。 ### 示例 本示例将一个32位值写入缓冲区并用**GetMem4**读回。 ```vb Dim buf As LongPtr = AllocMem(4) PutMem4 buf, &H12345678 Dim v As Long GetMem4 buf, v ' v = &H12345678 FreeMem buf ``` ### 另请参阅 * [GetMem1](/official/Reference/VBA/HiddenModule/GetMem1)、[GetMem2](/official/Reference/VBA/HiddenModule/GetMem2)、[GetMem8](/official/Reference/VBA/HiddenModule/GetMem8)、[GetMemPtr](/official/Reference/VBA/HiddenModule/GetMemPtr)过程 * [PutMem4](/official/Reference/VBA/HiddenModule/PutMem4)过程 --- --- url: /en/official/Reference/VBA/HiddenModule/GetMem8.md --- # GetMem8 Reads eight bytes from a memory address into a **Currency** variable. Syntax: **GetMem8** *Address* **,** *retVal* *Address* : *required* **LongPtr**. The address to read from. *retVal* : *required* **Currency**. The variable to receive the bytes read from *Address*. **Currency** is the convenient eight-byte signed-integer carrier used by these primitives because of its in-memory representation; the resulting bits are the raw 64-bit pattern stored at *Address*, scaled by the **Currency** type's fixed factor of 10000 only at the point of arithmetic. To work with the bits as an unscaled 64-bit integer, [**LSet**](/en/official/Reference/Core/LSet) the **Currency** value into a **LongLong** variable. The address is read directly with no bounds or alignment check. ### Example This example writes an 8-byte value to a buffer and reads it back with **GetMem8**. ```vb Dim buf As LongPtr = AllocMem(8) Dim src As Currency = 1000000@ PutMem8 buf, src Dim dst As Currency GetMem8 buf, dst ' dst = src (same raw 8-byte pattern) FreeMem buf ``` ### See Also * [GetMem1](/en/official/Reference/VBA/HiddenModule/GetMem1), [GetMem2](/en/official/Reference/VBA/HiddenModule/GetMem2), [GetMem4](/en/official/Reference/VBA/HiddenModule/GetMem4), [GetMemPtr](/en/official/Reference/VBA/HiddenModule/GetMemPtr) procedures * [PutMem8](/en/official/Reference/VBA/HiddenModule/PutMem8) procedure --- --- url: /zh/official/Reference/VBA/HiddenModule/GetMem8.md --- # GetMem8 从内存地址读取八个字节到**Currency**变量中。 语法:**GetMem8** *Address* **,** *retVal* *Address* : *必需* **LongPtr**。要读取的地址。 *retVal* : *必需* **Currency**。接收从*Address*读取的字节的变量。 **Currency**是这些原语使用的方便的八字节有符号整数载体,因为其内存表示;结果是存储在*Address*的原始64位模式,仅在算术运算时按**Currency**类型的固定因子10000进行缩放。要将位作为未缩放的64位整数处理,请使用[**LSet**](/official/Reference/Core/LSet)将**Currency**值转换为**LongLong**变量。 直接读取地址,不进行边界或对齐检查。 ### 示例 本示例将一个8字节值写入缓冲区并用**GetMem8**读回。 ```vb Dim buf As LongPtr = AllocMem(8) Dim src As Currency = 1000000@ PutMem8 buf, src Dim dst As Currency GetMem8 buf, dst ' dst = src (same raw 8-byte pattern) FreeMem buf ``` ### 另请参阅 * [GetMem1](/official/Reference/VBA/HiddenModule/GetMem1)、[GetMem2](/official/Reference/VBA/HiddenModule/GetMem2)、[GetMem4](/official/Reference/VBA/HiddenModule/GetMem4)、[GetMemPtr](/official/Reference/VBA/HiddenModule/GetMemPtr)过程 * [PutMem8](/official/Reference/VBA/HiddenModule/PutMem8)过程 --- --- url: /en/official/Reference/VBA/HiddenModule/GetMemPtr.md --- # GetMemPtr Reads a pointer-sized value from a memory address into a **LongPtr** variable. Syntax: **GetMemPtr** *Address* **,** *retVal* *Address* : *required* **LongPtr**. The address to read from. *retVal* : *required* **LongPtr**. The variable to receive the pointer-sized value read from *Address*. The number of bytes read matches the host's pointer width --- four bytes in 32-bit builds, eight bytes in 64-bit builds. The bytes are interpreted in the host's native byte order. The address is read directly with no bounds or alignment check. ### Example ```vb ' Read the IUnknown vtable pointer of a Collection instance. Dim c As Collection = New Collection Dim vtbl As LongPtr GetMemPtr ObjPtr(c), vtbl Debug.Print "vtable at "; Hex(vtbl) ``` ### See Also * [GetMem1](/en/official/Reference/VBA/HiddenModule/GetMem1), [GetMem2](/en/official/Reference/VBA/HiddenModule/GetMem2), [GetMem4](/en/official/Reference/VBA/HiddenModule/GetMem4), [GetMem8](/en/official/Reference/VBA/HiddenModule/GetMem8) procedures * [PutMemPtr](/en/official/Reference/VBA/HiddenModule/PutMemPtr) procedure --- --- url: /zh/official/Reference/VBA/HiddenModule/GetMemPtr.md --- # GetMemPtr 从内存地址读取指针大小的值到**LongPtr**变量中。 语法:**GetMemPtr** *Address* **,** *retVal* *Address* : *必需* **LongPtr**。要读取的地址。 *retVal* : *必需* **LongPtr**。接收从*Address*读取的指针大小值的变量。 读取的字节数与宿主的指针宽度匹配——32位构建中为四个字节,64位构建中为八个字节。字节按宿主的本机字节序解释。直接读取地址,不进行边界或对齐检查。 ### 示例 ```vb ' Read the IUnknown vtable pointer of a Collection instance. Dim c As Collection = New Collection Dim vtbl As LongPtr GetMemPtr ObjPtr(c), vtbl Debug.Print "vtable at "; Hex(vtbl) ``` ### 另请参阅 * [GetMem1](/official/Reference/VBA/HiddenModule/GetMem1)、[GetMem2](/official/Reference/VBA/HiddenModule/GetMem2)、[GetMem4](/official/Reference/VBA/HiddenModule/GetMem4)、[GetMem8](/official/Reference/VBA/HiddenModule/GetMem8)过程 * [PutMemPtr](/official/Reference/VBA/HiddenModule/PutMemPtr)过程 --- --- url: /en/official/Reference/VBA/Interaction/GetObject.md --- # GetObject Returns a reference to a COM/Automation object --- either an already-running instance, or one bound to a file. Syntax: **GetObject(** \[ *pathname* ] \[ **,** *class* ] **)** *pathname* : *optional* **Variant** (**String**). The full path and name of a file containing the object to retrieve. If *pathname* is omitted, *class* is required. *class* : *optional* **Variant** (**String**). The class of the object to retrieve, in the form *appname*.*objecttype* --- for example, `"Excel.Application"`. To assign the returned reference to a variable, use **Set**: ```vb Dim CADObject As Object Set CADObject = GetObject("C:\CAD\SCHEMA.CAD") ``` When the call is made with a *pathname*, the application registered for that file is started (if it isn't already running), and the object inside the file is activated. If *pathname* is a zero-length string (`""`), **GetObject** returns a *new* instance of the type named by *class*. If *pathname* is omitted altogether, **GetObject** attempts to attach to a *currently running* instance of the type named by *class*; if no such instance exists, a run-time error occurs. Some applications support activating a *part* of a file. Append `!` and an application-specific identifier to the file name --- for example, the third layer of a CAD drawing: ```vb Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3") ``` When *class* is not specified, the operating system determines the application to start and the object to activate based on the supplied file name. Some files, however, may support more than one class of object. To be specific, supply both arguments: ```vb Dim MyObject As Object Set MyObject = GetObject("C:\Drawings\Sample.drw", "Figment.Drawing") ``` ::: info **GetObject** attaches to a current instance of the object, or creates the object with a file already loaded. When there is no current instance and the object should not be started with a file loaded, [**CreateObject**](/en/official/Reference/VBA/Interaction/CreateObject) creates a new instance. ::: For an object registered as single-instance, **GetObject** with the zero-length-string syntax always returns the same instance, and the form with *pathname* omitted causes an error. ### Example This example uses **GetObject** to attach to a Microsoft Excel **Worksheet** opened from a file. The first call (without *pathname*) tries to attach to a running Excel; the second call opens the file. If Excel was not already running when the script started, it is closed at the end via **Application.Quit**. ```vb Dim MyXl As Object Dim ExcelWasNotRunning As Boolean On Error Resume Next Set MyXl = GetObject(, "Excel.Application") If Err.Number <> 0 Then ExcelWasNotRunning = True Err.Clear On Error GoTo 0 Set MyXl = GetObject("C:\Reports\MyTest.xls") MyXl.Application.Visible = True MyXl.Parent.Windows(1).Visible = True ' ... work with the workbook through MyXl ... If ExcelWasNotRunning Then MyXl.Application.Quit Set MyXl = Nothing ``` ### See Also * [CreateObject](/en/official/Reference/VBA/Interaction/CreateObject) function --- --- url: /zh/official/Reference/VBA/Interaction/GetObject.md --- # GetObject 返回对COM/Automation对象的引用——可以是已运行的实例,也可以是绑定到文件的实例。 语法:**GetObject(** \[ *pathname* ] \[ **,** *class* ] **)** *pathname* : *可选* **Variant**(**String**)。包含要检索对象的文件的完整路径和名称。如果省略*pathname*,则需要*class*。 *class* : *可选* **Variant**(**String**)。要检索的对象的类,格式为*appname*.*objecttype*——例如`"Excel.Application"`。 要将返回的引用赋给变量,请使用**Set**: ```vb Dim CADObject As Object Set CADObject = GetObject("C:\CAD\SCHEMA.CAD") ``` 使用*pathname*调用时,为该文件注册的应用程序被启动(如果尚未运行),并激活文件内的对象。 如果*pathname*为零长度字符串(`""`),**GetObject**返回*class*指定类型的*新*实例。如果完全省略*pathname*,**GetObject**尝试附加到*class*指定类型的*当前运行中的*实例;如果没有这样的实例,则产生运行时错误。 某些应用程序支持激活文件的*部分*。在文件名后附加`!`和应用程序特定的标识符——例如CAD绘图的第三层: ```vb Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3") ``` 当未指定*class*时,操作系统根据提供的文件名确定要启动的应用程序和要激活的对象。但是,某些文件可能支持不止一种对象类。要明确指定,请提供两个参数: ```vb Dim MyObject As Object Set MyObject = GetObject("C:\Drawings\Sample.drw", "Figment.Drawing") ``` ::: info **GetObject**附加到对象的当前实例,或创建已加载文件的对象。当没有当前实例且不应以加载文件的方式启动对象时,[**CreateObject**](/official/Reference/VBA/Interaction/CreateObject)创建新实例。 ::: 对于注册为单实例的对象,使用零长度字符串语法的**GetObject**始终返回同一实例,省略*pathname*的形式会导致错误。 ### 示例 本示例使用**GetObject**从文件附加到Microsoft Excel **Worksheet**。第一次调用(不带*pathname*)尝试附加到正在运行的Excel;第二次调用打开文件。如果脚本启动时Excel尚未运行,则在最后通过**Application.Quit**关闭。 ```vb Dim MyXl As Object Dim ExcelWasNotRunning As Boolean On Error Resume Next Set MyXl = GetObject(, "Excel.Application") If Err.Number <> 0 Then ExcelWasNotRunning = True Err.Clear On Error GoTo 0 Set MyXl = GetObject("C:\Reports\MyTest.xls") MyXl.Application.Visible = True MyXl.Parent.Windows(1).Visible = True ' ... work with the workbook through MyXl ... If ExcelWasNotRunning Then MyXl.Application.Quit Set MyXl = Nothing ``` ### 另请参阅 * [CreateObject](/official/Reference/VBA/Interaction/CreateObject)函数 --- --- url: /en/official/Reference/VBA/Interaction/GetSetting.md --- # GetSetting Returns a string key setting value from an application's entry in the Windows registry. Syntax: **GetSetting(** *appname* **,** *section* **,** *key* \[ **,** *default* ] **)** *appname* : String expression containing the name of the application or project whose key setting is requested. *section* : String expression containing the name of the section where the key setting is found. *key* : String expression containing the name of the key setting to return. *default* : *optional* Variant expression containing the value to return if no value is set in the key setting. If omitted, *default* is assumed to be a zero-length string (""). If any of the items named in the **GetSetting** arguments don't exist, **GetSetting** returns the value of *default*. The root of these registry settings is: `Computer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings`. ### Example This example first uses the [**SaveSetting**](/en/official/Reference/VBA/Interaction/SaveSetting) statement to make entries in the Windows registry for the application specified as *appname*, and then uses the **GetSetting** function to display one of the settings. Because the *default* argument is specified, some value is guaranteed to be returned. Note that *section* names can't be retrieved with **GetSetting**. Finally, the [**DeleteSetting**](/en/official/Reference/VBA/Interaction/DeleteSetting) statement removes all the application's entries. ```vb ' Variant to hold 2-dimensional array returned by GetSetting. Dim MySettings As Variant ' Place some settings in the registry. SaveSetting "MyApp","Startup", "Top", 75 SaveSetting "MyApp","Startup", "Left", 50 Debug.Print GetSetting(appname := "MyApp", section := "Startup", _ key := "Left", default := "25") DeleteSetting "MyApp", "Startup" ``` --- --- url: /zh/official/Reference/VBA/Interaction/GetSetting.md --- # GetSetting 从Windows注册表中应用程序条目返回字符串键设置值。 语法:**GetSetting(** *appname* **,** *section* **,** *key* \[ **,** *default* ] **)** *appname* : 字符串表达式,包含请求其键设置的应用程序或项目的名称。 *section* : 字符串表达式,包含键设置所在节的名称。 *key* : 字符串表达式,包含要返回的键设置的名称。 *default* : *可选* Variant表达式,包含当键设置中没有设置值时要返回的值。如果省略,*default*假定为零长度字符串("")。 如果**GetSetting**参数中命名的任何项不存在,**GetSetting**返回*default*的值。 这些注册表设置的根路径为:`Computer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings`。 ### 示例 本示例首先使用[**SaveSetting**](/official/Reference/VBA/Interaction/SaveSetting)语句在Windows注册表中为指定为*appname*的应用程序创建条目,然后使用**GetSetting**函数显示其中一个设置。由于指定了*default*参数,保证会返回某个值。注意*section*名称不能用**GetSetting**检索。最后,[**DeleteSetting**](/official/Reference/VBA/Interaction/DeleteSetting)语句删除所有应用程序条目。 ```vb ' Variant to hold 2-dimensional array returned by GetSetting. Dim MySettings As Variant ' Place some settings in the registry. SaveSetting "MyApp","Startup", "Top", 75 SaveSetting "MyApp","Startup", "Left", 50 Debug.Print GetSetting(appname := "MyApp", section := "Startup", _ key := "Left", default := "25") DeleteSetting "MyApp", "Startup" ``` --- --- url: /zh/official/Reference/Core/GetSetting.md --- # GetSetting 函数 getsetting 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/GetSetting.md --- # GetSetting Function Documentation for the getsetting keyword is not yet available. --- --- url: /en/official/Reference/VBA/HiddenModule/GetShortcutTextByEnum.md --- # GetShortcutTextByEnum Returns the localised display text for a built-in keyboard shortcut, given its enumeration ID. Syntax: **GetShortcutTextByEnum(** *ShortcutEnumId* **)** **As String** *ShortcutEnumId* : *required* **Long**. The numeric identifier of the shortcut, as used by the **Shortcut** property of menu and toolbar items. The returned string is the user-facing label for the shortcut --- e.g. `"Ctrl+S"`, `"Ctrl+Shift+P"`, `"F5"` --- formatted in the system UI language. Returns an empty string for an unknown identifier. ### See Also * [RuntimeCreateGetMessageHook](/en/official/Reference/VBA/HiddenModule/RuntimeCreateGetMessageHook) function --- --- url: /zh/official/Reference/VBA/HiddenModule/GetShortcutTextByEnum.md --- # GetShortcutTextByEnum 根据枚举ID返回内置键盘快捷键的本地化显示文本。 语法:**GetShortcutTextByEnum(** *ShortcutEnumId* **)** **As String** *ShortcutEnumId* : *必需* **Long**。快捷键的数字标识符,与菜单和工具栏项的**Shortcut**属性使用的相同。 返回的字符串是快捷键面向用户的标签——例如`"Ctrl+S"`、`"Ctrl+Shift+P"`、`"F5"`——以系统UI语言格式化。未知标识符返回空字符串。 ### 另请参阅 * [RuntimeCreateGetMessageHook](/official/Reference/VBA/HiddenModule/RuntimeCreateGetMessageHook)函数 --- --- url: /en/official/Tutorials/CEF/Getting-started.md --- # Getting Started ## Package requirements To create a project that uses the CEF package, add the right compiler-package reference to your project. The package ships in three flavours --- one per supported Chromium version --- and you pick exactly one: | Reference | Chromium baseline | Supported OS | |-----------------------------------------------------------------|-------------------|---------------| | **twinBASIC - Chromium Embedded Framework Package v49** | Chromium 49 | Windows XP+ | | **twinBASIC - Chromium Embedded Framework Package v109** | Chromium 109 | Windows 7+ | | **twinBASIC - Chromium Embedded Framework Package v145** | Chromium 145 | Windows 10+ | Use **v145** unless you specifically need to support older operating systems. The package source compiles against all three --- picking the reference sets the `CEF_VERSION` compiler constant, which selects the matching API. Add the reference through **Project** → **References** (Ctrl-T) → **TWINPACK PACKAGES**. Tick the desired CEF package, close the dialog, and restart the compiler. Once added, **CefBrowser** appears in the form-designer toolbox. ::: warning Older Chromium versions should not be used for browsing untrusted content from the public Internet --- they carry unpatched security vulnerabilities. v49 and v109 remain appropriate for tightly controlled environments where the browser loads only trusted local or internal content; for general web browsing, use v145. ::: ## Downloading the runtime Unlike [**WebView2**](/en/official/Reference/WebView2/WebView2/), CEF does not rely on a system-installed runtime. The Chromium binaries (`libcef.dll` and friends) ship as a separate download and must be installed alongside the application --- both during development and at deploy time. Download the runtime ZIP that matches both the CEF version and the application bitness: | Version | Win32 | Win64 | | ------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | v49 | [cefRuntime49\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime49_win32.zip) | [cefRuntime49\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime49_win64.zip) | | v109 | [cefRuntime109\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime109_win32.zip) | [cefRuntime109\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime109_win64.zip) | | v145 | [cefRuntime145\_win32.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime145_win32.zip) | [cefRuntime145\_win64.zip](https://github.com/twinbasic/cef-runtimes/releases/download/v1.0.0/cefRuntime145_win64.zip) | See [CEF Runtime Releases](https://github.com/twinbasic/cef-runtimes/releases/) for the full version list and release notes. Extract the ZIP into `%LocalAppData%\twinBASIC_CEF_Runtime\`. The version-stamped folder inside the ZIP --- for example `145_0_7632_160_Win64` --- must be placed directly under that path, containing `libcef.dll` and its sibling files: ```text %LocalAppData%\twinBASIC_CEF_Runtime\145_0_7632_160_Win64\libcef.dll %LocalAppData%\twinBASIC_CEF_Runtime\145_0_7632_160_Win64\chrome_elf.dll %LocalAppData%\twinBASIC_CEF_Runtime\145_0_7632_160_Win64\… ``` At startup, [**CefBrowser**](/en/official/Reference/CEF/CefBrowser/) searches this default location automatically. If `libcef.dll` cannot be found, the [**Error**](/en/official/Reference/CEF/CefBrowser/#error) event fires with the exact path that was searched. To point at a different folder --- for example a portable side-by-side deployment shipped with your installer --- assign [**EnvironmentOptions.BrowserExecutableFolder**](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions#browserexecutablefolder) during the [**Create**](/en/official/Reference/CEF/CefBrowser/#create) event: ```vb Private Sub CefBrowser1_Create() CefBrowser1.EnvironmentOptions.BrowserExecutableFolder = _ App.Path & "\cef145_win64" End Sub ``` ## Bitness must match The runtime bitness must match the application bitness --- a 32-bit twinBASIC build needs the Win32 runtime, a 64-bit build needs the Win64 runtime. Mixing them produces a `libcef.dll` load failure reported through the [**Error**](/en/official/Reference/CEF/CefBrowser/#error) event. ## Create a CefBrowser control on a form With the package reference and runtime in place, **CefBrowser** is available in the form-designer toolbox. Drop it onto a form like any other control: ```vb Private Sub Form_Load() CefBrowser1.Navigate "https://www.twinbasic.com" End Sub ``` The control starts up asynchronously --- the first user-visible event is [**Ready**](/en/official/Reference/CEF/CefBrowser/#ready), which fires once the helper browser process has launched and IPC has connected. Navigation, scripting, and most property accessors raise *"CefBrowser control is not ready"* (run-time error 5) before then. ## CefBrowser control properties Toggle the **Properties** pane to see the design-time-visible properties: [**DocumentURL**](/en/official/Reference/CEF/CefBrowser/#documenturl) (the initial URL the control auto-navigates to once **Ready** fires), [**ZoomFactor**](/en/official/Reference/CEF/CefBrowser/#zoomfactor), [**UserAgent**](/en/official/Reference/CEF/CefBrowser/#useragent), and the standard rect-dockable properties (size, **Anchors**, **Dock**). For the full reference, see the [**CefBrowser** class reference](/en/official/Reference/CEF/CefBrowser/); for what the underlying Chromium runtime supports, consult the [Chromium Embedded Framework documentation](https://bitbucket.org/chromiumembedded/cef/wiki/Home). ## Samples If you prefer to start with a sample, **Sample 1b --- Chromium Embedded Framework Examples** is available in the new-project dialog. It mirrors **Sample 1a --- WebView2 Examples** almost feature-for-feature, with the differences called out where the CEF package doesn't yet expose a WebView2 equivalent. ## Where next * [Customize the UserDataFolder](/en/official/Tutorials/CEF/Customize-the-UserDataFolder) -- relocate the user-profile folder for Office add-ins, kiosks, or portable installs. * [Building a browser shell](/en/official/Tutorials/CEF/Building-a-browser-shell) -- back / forward / reload / zoom / PDF. * [Re-entrancy](/en/official/Tutorials/CEF/Re-entrancy) -- what the package protects you from and the one place you still have to think about. --- --- url: /en/official/Tutorials/WebView2/Getting-started.md --- # Getting Started ## Package requirements To create projects that use WebView2, your projects must include both the `WinNativeForms` package and the `WebView2` package in your projects. Both of these packages can be added through the `Project` > `References` menu option, and selecting the `TWINPACK PACKAGES` button. Ensure both packages are ticked, and then close and save the Settings file and restart the compiler. ![Create Package](/assets/tbWebView2References.DoZJHOfO.png){style="width:45%; height:auto;"} Once you've added the package references, you should find that the WebView2 control is now available to you in the form designer: ![Create Package](/assets/tbWebView2Toolbox.DZ5RpmP2.png){style="width:15%; height:auto;"} ## Create a WebView2 control on a form We use the WebView2 control just like any ordinary control: ![Create Package](/assets/tbWebView2InAForm.CQ8DE8sw.gif){style="width:60%; height:auto;"} ## WebView2 control properties There are lots of WebView2 properties and events to experiment with. ![Create Package](/assets/tbWebView2Properties.BuB786ZA.png){style="width:45%; height:auto;"} Note that toggling any property will show extra information at the bottom of the properties list to give you a little bit more information. For the full reference, see the [WebView2 control class](/en/official/Reference/WebView2/WebView2/); for the underlying browser feature, try searching the official WebView2 documentation ## Samples If you prefer to start with a sample, have a look at `Sample 0. WebView2 Examples`, available in the new-project dialog: ![Create Package](/assets/tbWebView2Sample0.CClG1yTB.png){style="width:45%; height:auto;"} --- --- url: /en/official/Reference/VB/Global.md --- # Global class **Global** is the application's *app object* --- a singleton that the runtime instantiates on startup and whose members are accessible from any code in the project *without qualification*. Writing `App.Path` is in fact a call to `Global.App.Path`; the leading `Global.` is implicit. The class exists so that the language's built-in globals --- the singletons [**App**](/en/official/Reference/VB/App/), [**Clipboard**](/en/official/Reference/VB/Clipboard/), and [**Screen**](/en/official/Reference/VB/Screen/), the [**Forms**](#forms) collection, the **Printer** and **Printers** objects, the resource loaders, and the `Load` / `Unload` form-lifetime helpers --- can be reached uniformly through the same name resolution path. There is exactly one **Global** per process and it is not creatable from user code: no `New Global`, no public coclass to instantiate. The runtime publishes it via the IDE's special `[AppObject]` mechanism, and the compiler maps unqualified references to its members. ```vb ' All four of these resolve to a method/property on Global: Dim p As StdPicture Set p = LoadPicture(App.Path & "\splash.png") Form2.Show Load Form3 ' creates the form without showing it Unload Form1 ``` ## Built-in singletons [**App**](#app), [**Clipboard**](#clipboard), and [**Screen**](#screen) return the corresponding runtime singletons. Each is documented on its own page: * [**App**](/en/official/Reference/VB/App/) -- application metadata, version info, and process state. * [**Clipboard**](/en/official/Reference/VB/Clipboard/) -- system clipboard access. * [**Screen**](/en/official/Reference/VB/Screen/) -- primary-display metrics, active form/control, application-wide mouse pointer. These properties are cached references --- repeated reads return the same object instance for the lifetime of the process. ## Forms collection [**Forms**](#forms) returns the application's collection of currently-loaded [**Form**](/en/official/Reference/VB/Form/) instances --- every form that has been **Load**-ed or **Show**-n but not yet **Unload**-ed. The collection is live: it grows when a form is loaded and shrinks when one is unloaded. The collection supports three operations: * **Forms.Count** --- a **Long** giving the number of currently-loaded forms. * **Forms.Item(** *Index* **)** --- the [**Form**](/en/official/Reference/VB/Form/) at zero-based *Index*. **Item** is the default member, so `Forms(0)` and `Forms.Item(0)` are equivalent. Reading a negative or out-of-range index raises run-time error 9 (*Subscript out of range*). * **Forms.Add(** *Name* **)** --- creates a new instance of the form class named *Name*, adds it to the collection, and returns the new [**Form**](/en/official/Reference/VB/Form/). The form is loaded but not shown. The collection also supports `For Each` enumeration: ```vb Dim f As Form For Each f In Forms Debug.Print f.Name, f.Caption Next ``` A common idiom is closing every open form at shutdown --- note that unloading shrinks the collection, so iterate backwards or by index from the top down: ```vb Dim i As Long For i = Forms.Count - 1 To 0 Step -1 Unload Forms(i) Next ``` ## Resource loaders twinBASIC compiles project-level resources (bitmaps, strings, raw byte blobs) into the final EXE's resource section. The four `LoadRes*` methods retrieve them at run time: * [**LoadResPicture**](#loadrespicture) -- loads a bitmap, icon, or cursor resource into a **StdPicture**. * [**LoadResString**](#loadresstring) -- loads a string resource. * [**LoadResData**](#loadresdata) -- loads a raw byte-array resource. * [**LoadResIdList**](#loadresidlist) -- enumerates the IDs of resources of a given type. [**LoadPicture**](#loadpicture) loads a picture from a *file* rather than from an embedded resource --- typically used at run time for user-chosen content or for resources kept outside the EXE. ## Form lifetime helpers [**Load**](#load) creates a form (or, for control arrays, a control instance) without showing it; [**Unload**](#unload) destroys it. Both are written without parentheses by convention --- `Load Form1`, `Unload Form1` --- and behave as statements, but they are in fact calls to **Global.Load** and **Global.Unload**. The corresponding form-lifecycle events ([**Initialize**](/en/official/Reference/VB/Form/#initialize), [**Load**](/en/official/Reference/VB/Form/#load), [**Unload**](/en/official/Reference/VB/Form/#unload), [**Terminate**](/en/official/Reference/VB/Form/#terminate)) fire at the expected points. ## Printer and Printers The compile-time `FEATURE_PRINTER` flag exposes the **Printer** and **Printers** members. [**Printer**](/en/official/Reference/VB/Printer/) is the currently-selected printer, and [**Printers**](/en/official/Reference/VB/Printers/) is the collection of all installed printers; assigning a different printer object to **Printer** switches the application's current printer. ## Properties ### App The application's singleton [**App**](/en/official/Reference/VB/App/) instance --- its identity, version, and process-state metadata. Read-only. ### Clipboard The application's singleton [**Clipboard**](/en/official/Reference/VB/Clipboard/) instance --- the system clipboard wrapper. Read-only. ### Forms The application's live collection of currently-loaded [**Form**](/en/official/Reference/VB/Form/) instances. Read-only. See [Forms collection](#forms-collection). ### Printer The currently-selected [**Printer**](/en/official/Reference/VB/Printer/). Readable and assignable with `Set` --- assigning a different printer object switches the application's current printer. ### Printers The [**Printers**](/en/official/Reference/VB/Printers/) collection of all installed printers on the system. Read-only. ### Screen The application's singleton [**Screen**](/en/official/Reference/VB/Screen/) instance --- primary-display metrics, active form/control, application-wide mouse pointer. Read-only. ## Methods ### Load Creates an instance of the named form (or a new element of a control array) without showing it. The form's [**Initialize**](/en/official/Reference/VB/Form/#initialize) and [**Load**](/en/official/Reference/VB/Form/#load) events fire. Syntax: **Load** *object* *object* : *required* The default instance of a form class (`Form1`), an explicit form reference, or a control-array element (`Command1(3)`). ```vb Load Form2 ' instantiates and runs Form_Load, but Form2 stays hidden Set frm = Forms("Form2") ' the new instance now exists in Forms ``` ### LoadPicture Loads a picture from a file. Returns a **stdole.IPictureDisp**. Syntax: **LoadPicture**( \[ *FileName* \[, *Size* \[, *ColorDepth* \[, *X* \[, *Y* ] ] ] ] ] ) *FileName* : *optional* A **String** giving the path to a `.bmp`, `.dib`, `.gif`, `.jpg`, `.png`, `.wmf`, `.emf`, `.ico`, or `.cur` file. When omitted, returns an empty picture --- useful for clearing an [**Image**](/en/official/Reference/VB/Image/) or [**PictureBox**](/en/official/Reference/VB/PictureBox/)'s **Picture** property. *Size* : *optional* A member of [**LoadPictureSizeConstants**](/en/official/Reference/VBRUN/Constants/LoadPictureSizeConstants) --- meaningful only for icons and cursors, where it picks among the sizes stored in the file. *ColorDepth* : *optional* A member of [**LoadPictureColorConstants**](/en/official/Reference/VBRUN/Constants/LoadPictureColorConstants) --- meaningful only for icons and cursors, where it picks among the colour depths stored in the file. *X*, *Y* : *optional* Width and height overrides used when *Size* is **vbLPCustom**, in pixels. ```vb Set imgLogo.Picture = LoadPicture(App.Path & "\logo.png") Set imgLogo.Picture = LoadPicture() ' clears the picture ``` ### LoadResData Loads a raw resource --- usually a binary blob --- from the application's resource section, as a **Byte()** array wrapped in a **Variant**. Syntax: **LoadResData**( *id*, *Type* ) *id* : *required* The resource ID, either as a **Long** (numeric ID) or **String** (name). *Type* : *required* The resource type, identifying the resource section to look in. Either a **Long** standard-resource type or a **String** custom-resource type. ### LoadResIdList Returns the list of resource IDs in the resource section of the given type, as a **Variant** array. Syntax: **LoadResIdList**( *Type* ) *Type* : *required* The resource type --- see [**LoadResData**](#loadresdata). ### LoadResPicture Loads a picture, icon, or cursor resource from the application's resource section into a **stdole.IPictureDisp**. Syntax: **LoadResPicture**( *id*, *restype* \[, *width* \[, *height* ] ] ) *id* : *required* The resource ID --- **Long** (numeric) or **String** (name). *restype* : *required* A member of [**LoadResConstants**](/en/official/Reference/VBRUN/Constants/LoadResConstants) --- **vbResBitmap**, **vbResIcon**, or **vbResCursor**. *width*, *height* : *optional* Pixel dimensions for icon/cursor resources; **0** (default) selects the resource's natural size. ### LoadResString Loads a string resource from the application's resource section. Returns a **String**. Syntax: **LoadResString**( *id* ) *id* : *required* The resource ID, as a **Long**. ### Unload Destroys the form (or removes the control-array element). The form's [**QueryUnload**](/en/official/Reference/VB/Form/#queryunload), [**Unload**](/en/official/Reference/VB/Form/#unload), and [**Terminate**](/en/official/Reference/VB/Form/#terminate) events fire in order. Either of the first two can set its *Cancel* argument non-zero to veto the unload, in which case the form remains loaded and visible. Syntax: **Unload** *object* *object* : *required* The default instance of a form class, an explicit form reference, or a control-array element. ```vb Unload Me ' close the current form Unload Forms(0) ' close whichever form is at the head of the list ``` --- --- url: /zh/official/Reference/VB/Global.md --- # Global 类 **Global**是应用程序的*应用对象*——一个由运行时在启动时实例化的单例,其成员可以从项目中的任何代码*无需限定*地访问。编写`App.Path`实际上是调用`Global.App.Path`;前导的`Global.`是隐式的。该类的存在使得语言的内置全局对象——单例[**App**](/official/Reference/VB/App/)、[**Clipboard**](/official/Reference/VB/Clipboard/)和[**Screen**](/official/Reference/VB/Screen/)、[**Forms**](#forms)集合、**Printer**和**Printers**对象、资源加载器,以及`Load`/`Unload`窗体生命周期辅助函数——可以通过同一名称解析路径统一访问。 每个进程恰好有一个**Global**,且不能从用户代码创建:没有`New Global`,也没有可实例化的公共coclass。运行时通过IDE的特殊`[AppObject]`机制发布它,编译器将未限定的引用映射到其成员。 ```vb ' All four of these resolve to a method/property on Global: Dim p As StdPicture Set p = LoadPicture(App.Path & "\splash.png") Form2.Show Load Form3 ' creates the form without showing it Unload Form1 ``` ## 内置单例 [**App**](#app)、[**Clipboard**](#clipboard)和[**Screen**](#screen)返回对应的运行时单例。每个都在各自的页面中有文档: * [**App**](/official/Reference/VB/App/) — 应用程序元数据、版本信息和进程状态。 * [**Clipboard**](/official/Reference/VB/Clipboard/) — 系统剪贴板访问。 * [**Screen**](/official/Reference/VB/Screen/) — 主显示器指标、活动窗体/控件、应用程序范围的鼠标指针。 这些属性是缓存的引用——在进程生命周期内重复读取会返回相同的对象实例。 ## Forms 集合 [**Forms**](#forms)返回应用程序当前已加载的[**Form**](/official/Reference/VB/Form/)实例集合——每个已被**Load**加载或**Show**显示但尚未**Unload**卸载的窗体。集合是实时的:加载窗体时集合增长,卸载窗体时集合缩小。集合支持三种操作: * **Forms.Count** — 一个**Long**,给出当前已加载窗体的数量。 * **Forms.Item(** *Index* **)** — 零基*Index*处的[**Form**](/official/Reference/VB/Form/)。**Item**是默认成员,因此`Forms(0)`和`Forms.Item(0)`是等价的。读取负数或超出范围的索引会引发运行时错误9(*下标越界*)。 * **Forms.Add(** *Name* **)** — 创建名为*Name*的窗体类的新实例,将其添加到集合中,并返回新的[**Form**](/official/Reference/VB/Form/)。窗体已加载但未显示。 该集合还支持`For Each`枚举: ```vb Dim f As Form For Each f In Forms Debug.Print f.Name, f.Caption Next ``` 一个常见的惯用法是在关闭时卸载所有打开的窗体——注意卸载会使集合缩小,因此应反向迭代或从顶部向下按索引迭代: ```vb Dim i As Long For i = Forms.Count - 1 To 0 Step -1 Unload Forms(i) Next ``` ## 资源加载器 twinBASIC将项目级资源(位图、字符串、原始字节块)编译到最终EXE的资源节中。四个`LoadRes*`方法在运行时检索它们: * [**LoadResPicture**](#loadrespicture) — 将位图、图标或光标资源加载到**StdPicture**中。 * [**LoadResString**](#loadresstring) — 加载字符串资源。 * [**LoadResData**](#loadresdata) — 加载原始字节数组资源。 * [**LoadResIdList**](#loadresidlist) — 枚举给定类型资源的ID。 [**LoadPicture**](#loadpicture)从*文件*而非嵌入资源加载图片——通常在运行时用于用户选择的内容或保存在EXE外部的资源。 ## 窗体生命周期辅助函数 [**Load**](#load)创建窗体(或对于控件数组,创建控件实例)但不显示;[**Unload**](#unload)销毁它。两者按约定不使用括号编写——`Load Form1`、`Unload Form1`——其行为如同语句,但实际上是对**Global.Load**和**Global.Unload**的调用。相应的窗体生命周期事件([**Initialize**](/official/Reference/VB/Form/#initialize)、[**Load**](/official/Reference/VB/Form/#load)、[**Unload**](/official/Reference/VB/Form/#unload)、[**Terminate**](/official/Reference/VB/Form/#terminate))在预期的时机触发。 ## Printer 和 Printers 编译时`FEATURE_PRINTER`标志公开**Printer**和**Printers**成员。[**Printer**](/official/Reference/VB/Printer/)是当前选定的打印机,[**Printers**](/official/Reference/VB/Printers/)是所有已安装打印机的集合;将不同的打印机对象赋值给**Printer**会切换应用程序的当前打印机。 ## 属性 ### App 应用程序的单例[**App**](/official/Reference/VB/App/)实例——其标识、版本和进程状态元数据。只读。 ### Clipboard 应用程序的单例[**Clipboard**](/official/Reference/VB/Clipboard/)实例——系统剪贴板封装器。只读。 ### Forms 应用程序当前已加载[**Form**](/official/Reference/VB/Form/)实例的实时集合。只读。参见[Forms 集合](#forms-collection)。 ### Printer 当前选定的[**Printer**](/official/Reference/VB/Printer/)。可读取和用`Set`赋值——赋值不同的打印机对象会切换应用程序的当前打印机。 ### Printers 系统上所有已安装打印机的[**Printers**](/official/Reference/VB/Printers/)集合。只读。 ### Screen 应用程序的单例[**Screen**](/official/Reference/VB/Screen/)实例——主显示器指标、活动窗体/控件、应用程序范围的鼠标指针。只读。 ## 方法 ### Load 创建命名窗体的实例(或控件数组的新元素)但不显示。窗体的[**Initialize**](/official/Reference/VB/Form/#initialize)和[**Load**](/official/Reference/VB/Form/#load)事件将触发。 语法:**Load** *object* *object* : *必需* 窗体类的默认实例(`Form1`)、显式窗体引用或控件数组元素(`Command1(3)`)。 ```vb Load Form2 ' instantiates and runs Form_Load, but Form2 stays hidden Set frm = Forms("Form2") ' the new instance now exists in Forms ``` ### LoadPicture 从文件加载图片。返回**stdole.IPictureDisp**。 语法:**LoadPicture**( \[ *FileName* \[, *Size* \[, *ColorDepth* \[, *X* \[, *Y* ] ] ] ] ] ) *FileName* : *可选* 给出`.bmp`、`.dib`、`.gif`、`.jpg`、`.png`、`.wmf`、`.emf`、`.ico`或`.cur`文件路径的**String**。省略时返回空图片——适用于清除[**Image**](/official/Reference/VB/Image/)或[**PictureBox**](/official/Reference/VB/PictureBox/)的**Picture**属性。 *Size* : *可选* [**LoadPictureSizeConstants**](/official/Reference/VBRUN/Constants/LoadPictureSizeConstants)的成员——仅对图标和光标有意义,用于选择文件中存储的尺寸。 *ColorDepth* : *可选* [**LoadPictureColorConstants**](/official/Reference/VBRUN/Constants/LoadPictureColorConstants)的成员——仅对图标和光标有意义,用于选择文件中存储的颜色深度。 *X*、*Y* : *可选* 当*Size*为**vbLPCustom**时使用的宽度和高度覆盖值,以像素为单位。 ```vb Set imgLogo.Picture = LoadPicture(App.Path & "\logo.png") Set imgLogo.Picture = LoadPicture() ' clears the picture ``` ### LoadResData 从应用程序的资源节加载原始资源——通常是二进制块——返回包装在**Variant**中的\*\*Byte()\*\*数组。 语法:**LoadResData**( *id*, *Type* ) *id* : *必需* 资源ID,可以是**Long**(数字ID)或**String**(名称)。 *Type* : *必需* 资源类型,标识要查找的资源节。可以是**Long**标准资源类型或**String**自定义资源类型。 ### LoadResIdList 返回给定类型的资源节中的资源ID列表,作为**Variant**数组。 语法:**LoadResIdList**( *Type* ) *Type* : *必需* 资源类型——参见[**LoadResData**](#loadresdata)。 ### LoadResPicture 从应用程序的资源节将图片、图标或光标资源加载到**stdole.IPictureDisp**中。 语法:**LoadResPicture**( *id*, *restype* \[, *width* \[, *height* ] ] ) *id* : *必需* 资源ID——**Long**(数字)或**String**(名称)。 *restype* : *必需* [**LoadResConstants**](/official/Reference/VBRUN/Constants/LoadResConstants)的成员——**vbResBitmap**、**vbResIcon**或**vbResCursor**。 *width*、*height* : *可选* 图标/光标资源的像素尺寸;**0**(默认)选择资源的自然尺寸。 ### LoadResString 从应用程序的资源节加载字符串资源。返回**String**。 语法:**LoadResString**( *id* ) *id* : *必需* 资源ID,为**Long**。 ### Unload 销毁窗体(或移除控件数组元素)。窗体的[**QueryUnload**](/official/Reference/VB/Form/#queryunload)、[**Unload**](/official/Reference/VB/Form/#unload)和[**Terminate**](/official/Reference/VB/Form/#terminate)事件按顺序触发。前两个事件中的任意一个可以将其*Cancel*参数设为非零值来否决卸载,此时窗体保持加载和可见状态。 语法:**Unload** *object* *object* : *必需* 窗体类的默认实例、显式窗体引用或控件数组元素。 ```vb Unload Me ' close the current form Unload Forms(0) ' close whichever form is at the head of the list ``` --- --- url: /en/official/IDE/AddIns/GlobalSearch.md --- ## Global Search This AddIn is supplied with the twinBASIC IDE. Latest Release : v1.0.0.0 Developer : twinBASIC The global search add in will contain a [Toolbar](/en/official/IDE/Toolbar) item. ![Global Search (Toolbar)](Images/Toolbar_GlobalSearch.png "Global Search (Toolbar)") ![Global Search](/assets/GlobalSearch.4t0aHh0h.png "Global Search") Options * In packages * Match case * Whole word * Exclude comments Type a search term i.e. Button1 into the text field and a list of matches will be returned. ![Global Search](/assets/GlobalSearch_2.CqKvaBKL.png "Global Search") ## Download This add-in is bundled with twinBASIC. You can download it from [https://github.com/twinbasic/twinbasic/releases][tB] [tB]: https://github.com/twinbasic/twinbasic/releases --- --- url: /en/official/Reference/Glossary.md --- ## accelerator key A single character used as a shortcut for selecting an object. Pressing the ALT key followed by the accelerator key gives focus to the object and initiates one or more events associated with the object. The specific event or events initiated varies from one object to another. If code is associated with an event, it is processed when the event is initiated. Also called *keyboard accelerator*, *shortcut key*, *keyboard shortcut*, or *access key*. ## ActiveX control An object placed on a form to enable or enhance a user's interaction with an application. ActiveX controls have events and can be incorporated into other controls. These controls have an `.ocx` file name extension. ## ActiveX object An object that is exposed to other applications or programming tools through Automation interfaces. Also called an *Automation object*. ## add-in A customized tool that adds capabilities to the twinBASIC development environment. ## ANSI character set The American National Standards Institute (ANSI) 8-bit character set used to represent up to 256 characters (0–255). The first 128 characters (0–127) correspond to the letters and symbols on a standard U.S. keyboard. The second 128 characters (128–255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions. ## application A collection of code and visual elements that work together as a single program. Developers build and run applications within the development environment, while users usually run applications as executable files outside the development environment. ## argument A constant, [variable](#variable), or [expression](#expression) passed to a [procedure](#procedure). ## array A set of sequentially indexed elements having the same intrinsic [data type](#data-type). Each element of an array has a unique identifying index number. Changes made to one element of an array don't affect the other elements. ## ASCII character set The American Standard Code for Information Interchange (ASCII) 7-bit character set used to represent letters and symbols found on a standard U.S. keyboard. The ASCII character set is the same as the first 128 characters (0–127) in the [ANSI character set](#ansi-character-set). ## attribute (twinBASIC) Metadata attached to a [module](#module), procedure, parameter, or other declaration, written in square brackets --- for example, `[Documentation("...")]`. Some attributes control compiler behaviour (such as `[PackingAlignment]` on a [user-defined type](#user-defined-type) or `[VB_UserMemId]` on a member); others are informational. Attributes are a twinBASIC addition; classic VBA exposes only a small fixed set via the `Attribute` directive. ## Automation object See [ActiveX object](#activex-object). ## background color The color of the client region of an empty window or display screen, on which all drawing and color display takes place. ## base class The original class from which other classes can be derived by inheritance. ## bitmap An image represented by pixels and stored as a collection of bits in which each bit corresponds to one pixel. On color systems, more than one bit corresponds to each pixel. A bitmap usually has a `.bmp` file name extension. ## bitwise comparison A bit-by-bit comparison between identically positioned bits in two numeric expressions. ## Boolean data type A [data type](#data-type) with only two possible values, **True** (`-1`) or **False** (`0`). **Boolean** variables are stored as 16-bit (2-byte) numbers. ## Boolean expression An [expression](#expression) that evaluates to either **True** or **False**. ## bound Describes a control whose contents are associated with a particular [data source](#data-source). ## bound control A data-aware control that provides access to a specific field or fields in a data source. When the current record in a data source changes, all bound controls connected to that data source update to display data from fields in the current record. When the user changes data in a bound control and then moves to a different record, the changes are automatically saved. ## break mode Temporary suspension of program execution in the development environment. In break mode, you can examine, debug, reset, step through, or continue program execution. You enter break mode when you: * Encounter a [breakpoint](#breakpoint) during program execution. * Press CTRL+BREAK during program execution. * Encounter a [**Stop**](/en/official/Reference/Core/Stop) statement or untrapped run-time error during program execution. * Add a *Break When True* [watch expression](#watch-expression); execution stops when the value of the watch changes and evaluates to **True**. * Add a *Break When Changed* watch expression; execution stops when the value of the watch changes. ## breakpoint A selected program line at which execution automatically stops. Breakpoints are not saved with your code. ## by reference A way of passing the address of an argument to a procedure instead of passing the value. This allows the procedure to access the actual variable. As a result, the variable's actual value can be changed by the procedure to which it is passed. Unless otherwise specified, arguments are passed by reference. Use the **ByRef** keyword to make this explicit. ## by value A way of passing the value of an argument to a procedure instead of passing the address. This allows the procedure to access a copy of the variable. As a result, the variable's actual value can't be changed by the procedure to which it is passed. Use the **ByVal** keyword to pass an argument by value. ## Byte data type A [data type](#data-type) used to hold positive integer numbers ranging from 0 to 255. **Byte** variables are stored as single, unsigned 8-bit (1-byte) numbers. ## character code A number that represents a particular character in a set, such as the [ANSI character set](#ansi-character-set) or [Unicode](#unicode). ## class The formal definition of an object. The class acts as the template from which an instance of an object is created at run time. The class defines the properties of the object and the methods used to control the object's behavior. ## class level Describes code in the Declarations section of a class. Any code outside a procedure is referred to as class-level code. Declarations must be listed first, followed by procedures. ## class module A [module](#module) that contains the definition of one or more [classes](#class), including their property and method definitions. ## clear To change a setting to "off" or remove a value. ## code module See [standard module](#standard-module). *Code module* is the older term still used in some documentation. ## collection An object that contains a set of related objects. An object's position in the collection can change whenever a change occurs in the collection; therefore, the position of any specific object in the collection can vary. The [**Collection**](/en/official/Reference/VBA/Collection/) class is the standard example; instances of the class are collections. Collections must implement a method called `NewEnum` that accepts no arguments, returns an appropriate **IUnknown** object, and has its [`VB_UserMemId`](#attribute) attribute set to `-4`. ## command line The path, file name, and argument information provided by the user to run a program. ## comment Text added to code that explains how the code works. In twinBASIC, a comment can start with either an apostrophe (`'`) or with the **Rem** keyword followed by a space, and extends to the end of the line. ## comparison operator A symbol or word indicating a relationship between two or more values or expressions. These operators include less than (`<`), less than or equal to (`<=`), greater than (`>`), greater than or equal to (`>=`), not equal (`<>`), and equal (`=`). Additional comparison operators include [**Is**](/en/official/Reference/Core/Is), [**IsNot**](/en/official/Reference/Core/IsNot), and [**Like**](/en/official/Reference/Core/Like). Note that **Is** and **Like** can't be used as comparison operators in a [**Select Case**](/en/official/Reference/Core/Select-Case) statement. See [Comparison Operators](/en/official/Reference/Core/Comparison-Operators). ## compile time The period during which source code is translated to executable code. ## compiler directive A command used to alter the action of the compiler --- for example, the [conditional compilation](#conditional-compiler-constant) directives `#If`, `#Else`, `#ElseIf`, and `#End If`, or the `#Const` directive. See [Preprocessor directives](/en/official/Reference/Core/Topic-Preprocessor). ## conditional compiler constant A twinBASIC identifier defined using the `#Const` compiler directive (or set in the project's compilation conditions) and used by other compiler directives to determine when or if certain blocks of code are compiled. See [Preprocessor directives](/en/official/Reference/Core/Topic-Preprocessor). ## constant A named item that retains a constant value throughout the execution of a program. A constant can be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except [**Is**](/en/official/Reference/Core/Is) and exponentiation. Each host application can define its own set of constants. Additional constants can be defined by the user with the [**Const**](/en/official/Reference/Core/Const) statement. Use constants anywhere in your code in place of actual values. ## container An object that can contain other objects. ## context ID A unique number or string that corresponds to a specific object in an application. Context IDs are used to create links between the application and corresponding Help topics. ## control An object placed on a form that has its own set of recognized properties, methods, and events. Controls are used to receive user input, display output, and trigger event procedures. Most controls can be manipulated using methods. Some controls are interactive (responsive to user actions), while others are static (accessible only through code). See the [VB package](/en/official/Reference/VB/) for the standard set of controls. ## control array A group of controls that share a common name, type, and event procedures. Each control in an array has a unique index number that can be used to determine which control recognizes an event. ## Currency data type A [data type](#data-type) with a range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807. Use this data type for calculations involving money and for fixed-point calculations where accuracy is particularly important. The at sign (`@`) [type-declaration character](#type-declaration-character) represents **Currency**. ## cursor A piece of software that returns rows of data to the application. A cursor on a result set indicates the current position in the result set. ## data format The structure or appearance of a unit of data, such as a file, a database record, a cell in a spreadsheet, or text in a word-processing document. ## data source The location of data to which a control is bound, for example, a cell in a worksheet or a field in a database row. The current value of the data source can be stored in the `Value` property of a control. However, the control does not store the data; it only displays the information that is stored in the data source. ## data type The characteristic of a variable that determines what kind of data it can hold. Intrinsic data types include [**Byte**](#byte-data-type), [**Boolean**](#boolean-data-type), [**Integer**](#integer-data-type), [**Long**](#long-data-type), [**LongLong**](#longlong-data-type), [**LongPtr**](#longptr-data-type), [**Currency**](#currency-data-type), [**Decimal**](#decimal-data-type), [**Single**](#single-data-type), [**Double**](#double-data-type), [**Date**](#date-data-type), [**String**](#string-data-type), [**Object**](#object-data-type), [**Variant**](#variant-data-type) (default), as well as [user-defined types](#user-defined-type) and specific types of objects. ## Date data type A [data type](#data-type) used to store dates and times as a real number. **Date** variables are stored as 64-bit (8-byte) numbers. The value to the left of the decimal represents a date, and the value to the right of the decimal represents a time. ::: info In twinBASIC, [`Date`](/en/official/Reference/VBA/DateTime/Date) and [`Time`](/en/official/Reference/VBA/DateTime/Time) (and their `$` variants) are exposed as **properties**, not statements/functions as in classic VBA. ::: ## date expression Any expression that can be interpreted as a date, including date literals, numbers that look like dates, strings that look like dates, and dates returned from functions. A date expression is limited to numbers or strings, in any combination, that can represent a date from January 1, 100 to December 31, 9999. Dates are stored as part of a real number. Values to the left of the decimal represent the date; values to the right of the decimal represent the time. Negative numbers represent dates prior to December 30, 1899. ## date literal Any sequence of characters with a valid format that is surrounded by number signs (`#`). Valid formats include the date format specified by the locale settings for your code or the [universal date format](#universal-date-format). For example, `#12/31/92#` is the date literal that represents December 31, 1992, where English-U.S. is the locale setting for your application. Use date literals to maximize portability across national languages. ## date separators Characters used to separate the day, month, and year when date values are formatted. The characters are determined by system settings or by the [**Format**](/en/official/Reference/VBA/Strings/Format) function. ## DBCS A character set that uses 1 or 2 bytes to represent a character, allowing more than 256 characters to be represented. ## declaration Nonexecutable code that names a constant, [variable](#variable), or [procedure](#procedure), and specifies its characteristics, such as data type. For DLL procedures, declarations specify names, libraries, and arguments. ## Decimal data type A [data type](#data-type) that contains decimal numbers scaled by a power of 10. For zero-scaled numbers (integers with no fractional part), the range is +/-79,228,162,514,264,337,593,543,950,335. For numbers with 28 decimal places the range is +/-7.9228162514264337593543950335. The smallest non-zero value that can be represented as a **Decimal** is `0.0000000000000000000000000001`. ::: info Unlike classic VBA --- where **Decimal** was usable only as a **Variant** subtype produced by **CDec** --- twinBASIC supports **Decimal** as a first-class declared type. You can write `Dim x As Decimal`. ::: ## designer A visual design surface in the twinBASIC development environment used to design forms, controls, and other classes visually. ## design time The time during which an application is built in the development environment by adding controls, setting control or form properties, and writing code. In contrast, during [run time](#run-time), the application is interacted with as a user. ## development environment The part of the application where you write code, create controls, set control and form properties, and so on. This contrasts with running the application. ## docked window A window that is attached to the frame of the main window. ## document Any self-contained work created with an application and given a unique file name. ## dominant control A reference for the *Align* command and *Make Same Size* command on the *Format* menu. When aligning controls, the selected controls align to the dominant control. When sizing controls, the selected controls are assigned the dimensions of the dominant control. ## Double data type A [data type](#data-type) that holds double-precision floating-point numbers as 64-bit numbers in the range -1.79769313486231E308 to -4.94065645841247E-324 for negative values, and 4.94065645841247E-324 to 1.79769313486232E308 for positive values. The number sign (`#`) [type-declaration character](#type-declaration-character) represents **Double**. ## drop source The selected text or object that is dragged in a drag-and-drop operation. ## dynamic data exchange (DDE) An established protocol for exchanging data through active links between applications that run under Microsoft Windows. ## dynamic-link library (DLL) A library of routines loaded and linked into applications at run time. DLLs are typically created with other programming languages such as C. External DLL procedures are made callable in twinBASIC with the [**Declare**](/en/official/Reference/Core/Declare) statement. ## Empty Indicates that no beginning value has been assigned to a [**Variant**](#variant-data-type) variable. An **Empty** variable is represented as 0 in a numeric context or a zero-length string (`""`) in a string context. ## enumerated constant A named constant whose value is a member of an enumeration type defined with the [**Enum**](/en/official/Reference/Core/Enum) statement. Additional information for an enumerated data item can usually be found in the description of the property, method, or event that uses the enumeration. ## error number A whole number in the range 0 to 65,535 that corresponds to the `Number` property setting of the [**Err**](/en/official/Reference/VBA/Information/Err) object. When combined with the `Description` property setting of the **Err** object, this number represents a particular error message. ## event source object An object that is the source of events that occur in response to an action. An event source object is typically returned by a property. ## executable file A Windows-based application that can run outside the development environment. An executable file has an `.exe` file name extension. ## expression A combination of keywords, operators, variables, and constants that yields a string, number, or object. An expression can be used to perform a calculation, manipulate characters, or test data. ## file number A number used in the [**Open**](/en/official/Reference/Core/Open) statement to open a file. Use file numbers in the range 1–255 (inclusive) for files not accessible to other applications. Use file numbers in the range 256–511 for files accessible from other applications. ## focus The ability to receive mouse clicks or keyboard input at any one time. In the Microsoft Windows environment, only one window, form, or control can have this ability at a time. The object that "has the focus" is normally indicated by a highlighted caption or title bar. The focus can be set by the user or by the application. ## foreground color The color currently selected for drawing or displaying text on screen. In monochrome displays, the foreground color is the color of a bitmap or other graphic. ## form A window or dialog box. Forms are containers for [controls](#control). A multiple-document interface (MDI) form can also act as a container for child forms and some controls. ## form module A file in a twinBASIC project that contains the graphical description of a form along with its controls and their property settings, form-level declarations of constants, variables, and external procedures, and event and general procedures. In twinBASIC source projects, form modules are stored as `.twin` files. ## Function procedure A [procedure](#procedure) that performs a specific task within a program and returns a value. A **Function** procedure begins with a [**Function**](/en/official/Reference/Core/Function) statement and ends with an **End Function** statement. ## general procedure A [procedure](#procedure) that must be explicitly called by another procedure. In contrast, an event procedure is invoked automatically in response to a user or system action. ## graphics method A method that operates on an object such as a **Form**, **PictureBox**, or **Printer**, and performs run-time drawing operations such as animation or simulation. Graphics methods include **Circle**, **Cls**, **Line**, **PaintPicture**, **Point**, **Print**, and **PSet**. ## host application Any application that hosts a twinBASIC project or component, for example, an Office application that loads a compiled twinBASIC COM add-in. ## icon A graphical representation of an object or concept; commonly used to represent minimized applications in Microsoft Windows. An icon is a bitmap with a maximum size of 32 x 32 pixels. Icons have an `.ico` file name extension. ## identifier An element of an expression that refers to a constant, variable, procedure, or other named entity. ## in process Running in the same address space as an application. ## inherited property A property that has acquired the characteristics of another class through inheritance. ## Input Method Editor (IME) An application that translates what you type into characters of a DBCS language, such as Japanese or Chinese. As the user types, the IME displays possible equivalents. The user selects the most appropriate entry. ## insertable object An application object that is a type of custom control, such as a Microsoft Excel worksheet, that can be inserted into a host document. ## Integer data type A [data type](#data-type) that holds integer variables stored as 2-byte whole numbers in the range -32,768 to 32,767. The **Integer** data type is also used to represent enumerated values. The percent sign (`%`) [type-declaration character](#type-declaration-character) represents an **Integer**. ## intrinsic constant A constant provided by the language or a referenced library. Intrinsic constants can be viewed in the IDE's object browser. Because intrinsic constants can't be disabled, a user-defined constant with the same name can't be created. ## keyboard state A return value that identifies which keys are pressed and whether the keyboard modifiers SHIFT, CTRL, and ALT are pressed. ## keyword A word or symbol recognized as part of the twinBASIC programming language; for example, a statement, function name, or operator. ## line-continuation character The combination of a space followed by an underscore (`_`) used in source code to extend a single logical line of code to two or more physical lines. A line-continuation character can't be used to continue a line of code within a string expression. ## line label A label used to identify a single line of code. A line label can be any combination of characters that starts with a letter and ends with a colon (`:`). Line labels are not case sensitive and must begin in the first column. ## line number A number used to identify a single line of code. A line number can be any combination of digits that is unique within the module where it is used. Line numbers must begin in the first column. ## locale The set of information that corresponds to a given language and country/region. The code locale setting affects the language of terms such as keywords and defines locale-specific settings such as the decimal and list separators, date formats, and character sorting order. The system locale setting affects the way locale-aware functionality behaves, for example, when you display numbers or convert strings to dates. You set the system locale using the **Control Panel** utilities provided by the operating system. Although the code locale and system locale are generally set to the same setting, they may differ in some situations. For example, in Visual Basic, Standard Edition and Visual Basic, Professional Edition, the code is not translated from English-U.S. The system locale can be set to the user's language and country/region, but the code locale is always set to English-U.S. and can't be changed. In this case, the English-U.S. separators, format placeholders, and sorting order are used. ## logic error A programming error that can cause code to produce incorrect results or stop execution. For example, a logic error can be caused by incorrect variable names, incorrect variable types, endless loops, flaws in comparisons, or array problems. ## Long data type A 4-byte integer ranging in value from -2,147,483,648 to 2,147,483,647. The ampersand (`&`) [type-declaration character](#type-declaration-character) represents a **Long**. ## LongLong data type (twinBASIC) An 8-byte integer ranging in value from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Valid as a declared type only on 64-bit platforms (or for DLL [**Declare**](/en/official/Reference/Core/Declare) signatures targeting 64-bit). The caret-sign (`^`) [type-declaration character](#type-declaration-character) represents a **LongLong**. ## LongPtr data type (twinBASIC) A platform-dependent integer used to hold pointer or handle values. **LongPtr** is 4 bytes on 32-bit platforms and 8 bytes on 64-bit platforms. Use **LongPtr** rather than **Long** or **LongLong** when declaring DLL parameters that hold pointers or handles, so that the same source compiles correctly on both platforms. ## MDI child A form contained within an MDI form in a multiple-document interface (MDI) application. To create a child form, set the `MDIChild` property of the form to **True**. ## MDI form A window that makes up the background of a multiple-document interface (MDI) application. The MDI form is the container for any MDI child forms in the application. ## member An element of a collection, object, or user-defined type. ## metafile A file that stores an image as graphical objects such as lines, circles, and polygons rather than as pixels. There are two types of metafiles, standard and enhanced. Standard metafiles usually have a `.wmf` file name extension; enhanced metafiles usually have an `.emf` file name extension. Metafiles preserve an image more accurately than pixels when the image is resized. ## method A [procedure](#procedure) that acts on an object. ## module A set of declarations followed by procedures. ## module level Describes code in the Declarations section of a module. Any code outside a procedure is referred to as module-level code. Declarations must be listed first, followed by procedures. This term also includes the [class module](#class-module). ## module variable A variable declared outside [**Function**](/en/official/Reference/Core/Function), [**Sub**](/en/official/Reference/Core/Sub), or [**Property**](/en/official/Reference/Core/Property) procedure code. Module variables must be declared outside any procedures in the module. They exist while the module is loaded and are visible in all procedures in the module. ## named argument An argument that has a name that is predefined in the object library. Instead of providing a value for each argument in a specified order expected by the syntax, named arguments can be used to assign values in any order. For example, suppose a method accepts three arguments: > **DoSomething** *namedarg1, namedarg2, namedarg3* By assigning values to named arguments, you can write: ```vb DoSomething namedarg3 := 4, namedarg2 := 5, namedarg1 := 20 ``` Note that the named arguments don't have to appear in the normal positional order in the syntax. ## Null A value indicating that a variable contains no valid data. **Null** is the result of an explicit assignment of **Null** to a variable or any operation between expressions that contain **Null**. ## numeric data type Any intrinsic numeric [data type](#data-type) (**Byte**, **Boolean**, **Integer**, **Long**, **LongLong**, **LongPtr**, **Currency**, **Decimal**, **Single**, **Double**, or **Date**). ## numeric expression Any [expression](#expression) that can be evaluated as a number. Elements of an expression can include any combination of keywords, variables, constants, and operators that result in a number. ## object A combination of code and data that can be treated as a unit, for example, a control, form, or application component. Each object is defined by a class. ## Object Browser A dialog box in which you can examine the contents of an object library to get information about the objects provided. ## Object data type A [data type](#data-type) that represents any object reference. **Object** variables are stored as pointer-sized addresses that refer to objects (4 bytes on 32-bit platforms, 8 bytes on 64-bit platforms). ## object expression An expression that specifies a particular object and can include any of the object's containers. For example, an application can have an **Application** object that contains a **Document** object that contains a **Text** object. ## object library A file containing standard descriptions of exposed objects, properties, and methods. Object library files typically have an `.olb` or `.tlb` extension. Use the [Object Browser](#object-browser) to examine the contents of an object library to get information about the objects provided. ## object module A module that contains code specific to an object, for example, a class module or form module. Object modules contain the code behind their associated objects. The rules for object modules differ from those for [standard modules](#standard-module). ## object type A type of object exposed by an application through Automation, for example, **Application**, **File**, **Range**, or **Sheet**. Refer to the application's documentation for a complete listing of available objects. ## object variable A variable that contains a reference to an object. ## package A unit of distribution and reference for twinBASIC code. A package bundles modules, classes, types, enums, and other declarations together, and can be referenced from a project as a single dependency. The twinBASIC runtime libraries are delivered this way: the [VBA](/en/official/Reference/VBA/) package mirrors classic VBA's runtime, the [VBRUN](/en/official/Reference/VBRUN/) package provides VB6's runtime objects, and the [VB](/en/official/Reference/VB/) package supplies the standard control classes. Developers can author and publish their own packages. ## parameter A variable name by which an argument passed to a procedure is known within the procedure. This variable receives the argument passed into the procedure. Its scope ends when the procedure ends. ## path A string expression specifying a directory or folder location. The location can include a drive specification. ## pi A mathematical constant equal to approximately 3.1415926535897932. ## placeholder A character that masks or hides another character for security reasons. For example, when a user types a password, an asterisk is displayed on the screen to take the place of each character typed. ## point A point is 1/72 inch. Font sizes are usually measured in points. ## print zone Print zones begin every 14 columns. The width of each column is an average of the width of all characters in the point size for the selected font. ## Private Describes variables, procedures, or types that are visible only to the module in which they are declared. See the [**Private**](/en/official/Reference/Core/Private) statement. ## procedure A named sequence of statements executed as a unit. For example, [**Function**](/en/official/Reference/Core/Function), [**Property**](/en/official/Reference/Core/Property), and [**Sub**](/en/official/Reference/Core/Sub) are types of procedures. A procedure name is always defined at module level. All executable code must be contained in a procedure. Procedures can't be nested within other procedures. ## procedure call A statement in code that tells twinBASIC to execute a procedure. See [**Call**](/en/official/Reference/Core/Call). ## procedure level Describes statements located within a [**Function**](/en/official/Reference/Core/Function), [**Property**](/en/official/Reference/Core/Property), or [**Sub**](/en/official/Reference/Core/Sub) procedure. Declarations are usually listed first, followed by assignments and other executable code. Note that module-level code resides outside a procedure block. ## project A set of modules. ## property A named attribute of an object. Properties define object characteristics such as size, color, and screen location, or the state of an object, such as enabled or disabled. ## property page A grouping of properties presented as a tabbed page of a property sheet. ## Property procedure A [procedure](#procedure) that creates and manipulates properties for a class module. A **Property** procedure begins with a [**Property Let**, **Property Get**, or **Property Set**](/en/official/Reference/Core/Property) statement and ends with an **End Property** statement. ## Public Describes variables declared using the [**Public**](/en/official/Reference/Core/Public) statement, which are visible to all procedures in all modules in all applications unless [**Option Private Module**](/en/official/Reference/Core/Option#Private) is in effect. In that case, the variables are public only within the project in which they reside. ## referenced project A project that is directly linked to from the current project. A project referenced by one of the current project's directly referenced projects is called an *indirectly referenced project*. Its **Public** variables are not accessible to the current project except through qualification with its project name. Any combination of direct and indirect references between projects is valid as long as they don't result in a cycle. ## referencing project The current project. **Public** variables in a directly referenced project are visible to the directly referencing project, but **Public** variables in a directly referencing project are not visible to a directly referenced project. ## registry A central configuration database in Microsoft Windows used for user, application, and computer-specific information. ## resource file A file in a twinBASIC project that can contain bitmaps, text strings, or other data. By storing this data in a separate file, you can change the information without editing your code. ## RGB A color value system used to describe colors as a mixture of red (R), green (G), and blue (B). The color is defined as a set of three integers (R, G, B) where each integer ranges from 0–255. A value of 0 indicates a total absence of a color component; a value of 255 indicates the highest intensity of a color component. See [**RGB**](/en/official/Reference/VBA/Information/RGB) and [**RGBA**](/en/official/Reference/VBA/Information/RGBA). ## run time The time during which code is running. During run time, you can't edit the code. ## run-time error An error that occurs when code is running. A run-time error results when a statement attempts an invalid operation. ## scope Defines the visibility of a variable, procedure, or object. For example, a variable declared as [**Public**](/en/official/Reference/Core/Public) is visible to all procedures in all modules in a directly referencing project unless [**Option Private Module**](/en/official/Reference/Core/Option#Private) is in effect. When **Option Private Module** is in effect, the module itself is private and therefore not visible to referencing projects. Variables declared in a procedure are visible only within the procedure and lose their value between calls unless they are declared [**Static**](/en/official/Reference/Core/Static). ## seed An initial value used to generate pseudorandom numbers. For example, the [**Randomize**](/en/official/Reference/VBA/Math/Randomize) statement creates a seed number used by the [**Rnd**](/en/official/Reference/VBA/Math/Rnd) function to create unique pseudorandom number sequences. ## Single data type A [data type](#data-type) that stores single-precision floating-point variables as 32-bit (4-byte) floating-point numbers, ranging in value from -3.402823E38 to -1.401298E-45 for negative values, and 1.401298E-45 to 3.402823E38 for positive values. The exclamation point (`!`) [type-declaration character](#type-declaration-character) represents a **Single**. ## sort order A sequencing principle used to order data, for example, alphabetic, numeric, ascending, descending, and so on. ## stack A fixed amount of memory used by twinBASIC to preserve local variables and arguments during procedure calls. ## standard module A module containing only procedure, type, and data declarations and definitions. Module-level declarations and definitions in a standard module are **Public** by default. A standard module is sometimes referred to as a *code module*. ## statement A syntactically complete unit that expresses one kind of action, declaration, or definition. A statement generally occupies a single line, although a colon (`:`) can be used to include more than one statement on a line. A [line-continuation character](#line-continuation-character) (`_`) can also be used to continue a single logical line onto a second physical line. ## string comparison A comparison of two sequences of characters. Use [**Option Compare**](/en/official/Reference/Core/Option#Compare) to specify binary or text comparison. In English-U.S., binary comparisons are case sensitive; text comparisons are not. ## string constant Any constant (defined using the [**Const**](/en/official/Reference/Core/Const) keyword) consisting of a sequence of contiguous characters interpreted as the characters themselves rather than as a numeric value. ## String data type A [data type](#data-type) consisting of a sequence of contiguous characters that represent the characters themselves rather than their numeric values. A **String** can include letters, numbers, spaces, and punctuation. The **String** data type can store fixed-length strings ranging in length from 0 to approximately 63K characters and dynamic strings ranging in length from 0 to approximately 2 billion characters. The dollar sign (`$`) [type-declaration character](#type-declaration-character) represents a **String**. ## string expression Any [expression](#expression) that evaluates to a sequence of contiguous characters. Elements of a string expression can include a function that returns a string, a string literal, a string constant, a string variable, a string [**Variant**](#variant-data-type), or a function that returns a string **Variant**. ## string literal Any expression consisting of a sequence of contiguous characters surrounded by quotation marks that is literally interpreted as the characters within the quotation marks. ## Sub procedure A [procedure](#procedure) that performs a specific task within a program, but returns no explicit value. A **Sub** procedure begins with a [**Sub**](/en/official/Reference/Core/Sub) statement and ends with an **End Sub** statement. ## syntax checking A feature that checks code for correct syntax. When the syntax checking feature is enabled, a message is displayed when code containing a syntax error is entered, and the suspect code is highlighted. ## syntax error An error that occurs when a line of code is entered that twinBASIC doesn't recognize. ## system colors Colors that are defined by the operating system for a specific type of monitor and video adapter. In Windows, each color is associated with a specific part of the user interface, such as a window title or a menu. ## tab order The order in which the focus moves from one field to the next as TAB or SHIFT+TAB is pressed. ## target An object onto which the user drops the object being dragged in a drag-and-drop operation. ## time expression Any expression that can be interpreted as a time. This includes any combination of time literals, numbers that look like times, strings that look like times, and times returned from functions. Times are stored as part of a real number. Values to the right of the decimal represent the time. For example, midday (12:00 P.M.) is represented by 0.5. ## transparent Describes the background of the object if the background is not visible. Instead of the background, whatever is behind the object is visible --- for example, an image or picture used as a backdrop in your application. Use the `BackStyle` property to make the background transparent. ## twip A unit of screen measurement equal to 1/20 point. A twip is a screen-independent unit used to ensure that placement and proportion of screen elements in a screen application are the same on all display systems. There are approximately 1440 twips to a logical inch, or 567 twips to a logical centimeter (the length of a screen item measuring one inch or one centimeter when printed). ## type-declaration character A character appended to a variable name indicating the variable's data type. By default, variables are of type [**Variant**](#variant-data-type) unless a corresponding [**Def***type*](/en/official/Reference/Core/Deftype) statement is present in the module. The full set of type-declaration characters is: | Char | Type | |:----:|:----------------| | `%` | **Integer** | | `&` | **Long** | | `^` | **LongLong** | | `@` | **Currency** | | `!` | **Single** | | `#` | **Double** | | `$` | **String** | ## type library A file or component within another file that contains standard descriptions of exposed objects, properties, and methods that are available for Automation. Object library files (`.olb`, `.tlb`) contain type libraries. ## unbound Describes a control that is not related to a [data source](#data-source). In contrast, a [bound control](#bound-control) provides access to a data source for display or editing. ## Unicode International Standards Organization (ISO) character standard. Unicode uses a 16-bit (2-byte) coding scheme that allows for 65,536 distinct character spaces. Unicode includes representations for punctuation marks, mathematical symbols, and dingbats, with substantial room for future expansion. ## universal date format The universal date format is `#yyyy-mm-dd hh:mm:ss#`. Both the date component (`#yyyy-mm-dd#`) and the time component (`#hh:mm:ss#`) can be represented separately. ## user-defined type Any data type defined using the [**Type**](/en/official/Reference/Core/Type) statement. User-defined data types can contain one or more elements of any data type. Arrays of user-defined and other data types are created using the [**Dim**](/en/official/Reference/Core/Dim) statement. Arrays of any type can be included within user-defined types. See [data type](#data-type). ## variable A named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its scope. A data type can be specified or not. Variable names must begin with an alphabetic character, must be unique within the same scope, can't be longer than 255 characters, and can't contain an embedded period or type-declaration character. ## Variant data type A special [data type](#data-type) that can contain numeric, string, or date data as well as user-defined types and the special values [**Empty**](#empty) and [**Null**](#null). The **Variant** data type can contain data up to the range of a **Decimal**, plus character text and the platform-specific storage required for a string. The [**VarType**](/en/official/Reference/VBA/Information/VarType) function defines how the data in a **Variant** is treated. All variables become **Variant** data types if not explicitly declared as some other data type. ## variant expression Any [expression](#expression) that can evaluate to numeric, string, or date data, as well as the special values [**Empty**](#empty) and [**Null**](#null). ## watch expression A user-defined expression that enables observation of the behavior of a variable or expression. Watch expressions appear in the watch window of the development environment and are automatically updated when [break mode](#break-mode) is entered. The watch window displays the value of an expression within a given context. Watch expressions are not saved with code. ## z-order The visual layering of controls on a form along the form's z-axis (depth). The z-order determines which controls are in front of other controls. --- --- url: /en/official/Reference/Core/GoSub-Return.md --- # GoSub ... Return Branches to and returns from a subroutine within a procedure. Syntax: > **GoSub** *line*\ >      ...\ > *line*\ >      ...\ >      **Return** *line* : Any line label or line number. Use **GoSub** and **Return** anywhere in a procedure, but **GoSub** and the corresponding **Return** statement must be in the same procedure. A subroutine can contain more than one **Return** statement, but the first **Return** statement encountered causes the flow of execution to branch back to the statement immediately following the most recently executed **GoSub** statement. ::: info **GoSub...Return** cannot enter or exit [**Sub**](/en/official/Reference/Core/Sub) procedures. ::: ::: tip Creating separate callable procedures may provide a more structured alternative to using **GoSub...Return**. ::: ### Example This example uses **GoSub** to call a subroutine within a **Sub** procedure. The **Return** statement causes the execution to resume at the statement immediately following the **GoSub** statement. The [**Exit Sub**](/en/official/Reference/Core/Exit) statement is used to prevent control from accidentally flowing into the subroutine. ```vb Sub GosubDemo() Dim Num ' Solicit a number from the user. Num = InputBox("Enter a positive number to be divided by 2.") ' Only use routine if user enters a positive number. If Num > 0 Then GoSub MyRoutine Debug.Print Num Exit Sub ' Use Exit to prevent an error. MyRoutine: Num = Num / 2 ' Perform the division. Return ' Return control to statement following the GoSub statement. End Sub ``` ### See Also * [**Return** statement](/en/official/Reference/Core/Return) * [**GoTo** statement](/en/official/Reference/Core/GoTo) * [**On...GoSub** statement](/en/official/Reference/Core/On-GoSub) * [**Sub** statement](/en/official/Reference/Core/Sub) --- --- url: /zh/official/Reference/Core/GoSub-Return.md --- # GoSub ... Return 在过程中分支到子程序并从中返回。 语法: > **GoSub** *line*\ >      ...\ > *line*\ >      ...\ >      **Return** *line* : 任何行标签或行号。 可以在过程中的任何位置使用 **GoSub** 和 **Return**,但 **GoSub** 和对应的 **Return** 语句必须在同一过程中。子程序可以包含多个 **Return** 语句,但遇到第一个 **Return** 语句时,执行流程将分支回最近执行的 **GoSub** 语句之后紧接的语句。 ::: info **GoSub...Return** 不能进入或退出 [**Sub**](/official/Reference/Core/Sub) 过程。 ::: ::: tip 创建单独的可调用过程可能比使用 **GoSub...Return** 提供更具结构化的替代方案。 ::: ### 示例 本示例使用 **GoSub** 在 **Sub** 过程内调用子程序。**Return** 语句使执行恢复到 **GoSub** 语句之后紧接的语句。[**Exit Sub**](/official/Reference/Core/Exit) 语句用于防止控制意外流入子程序。 ```vb Sub GosubDemo() Dim Num ' Solicit a number from the user. Num = InputBox("Enter a positive number to be divided by 2.") ' Only use routine if user enters a positive number. If Num > 0 Then GoSub MyRoutine Debug.Print Num Exit Sub ' Use Exit to prevent an error. MyRoutine: Num = Num / 2 ' Perform the division. Return ' Return control to statement following the GoSub statement. End Sub ``` ### 另请参阅 * [**Return** 语句](/official/Reference/Core/Return) * [**GoTo** 语句](/official/Reference/Core/GoTo) * [**On...GoSub** 语句](/official/Reference/Core/On-GoSub) * [**Sub** 语句](/official/Reference/Core/Sub) --- --- url: /en/official/Reference/Core/GoTo.md --- # GoTo Branches unconditionally to a specified line within a procedure. Syntax: > **GoTo** *line* *line* : Any line label or line number. **GoTo** can branch only to lines within the procedure where it appears. ::: info Too many **GoTo** statements can make code difficult to read and debug. Use structured control statements ([**Do...Loop**](/en/official/Reference/Core/Do-Loop), [**For...Next**](/en/official/Reference/Core/For-Next), [**If...Then...Else**](/en/official/Reference/Core/If-Then-Else), [**Select Case**](/en/official/Reference/Core/Select-Case)) whenever possible. ::: ### Example This example uses the **GoTo** statement to branch to line labels within a procedure. ```vb Sub GotoStatementDemo() Dim Number, MyString Number = 1 ' Initialize variable. ' Evaluate Number and branch to appropriate label. If Number = 1 Then GoTo Line1 Else GoTo Line2 Line1: MyString = "Number equals 1" GoTo LastLine ' Go to LastLine. Line2: ' The following statement never gets executed. MyString = "Number equals 2" LastLine: Debug.Print MyString ' Print "Number equals 1" in the Immediate window. End Sub ``` ### See Also * [**On...GoTo** statement](/en/official/Reference/Core/On-GoTo) * [**GoSub...Return** statement](/en/official/Reference/Core/GoSub-Return) * [**On Error** statement](/en/official/Reference/Core/On-Error) * [**Select Case** statement](/en/official/Reference/Core/Select-Case) --- --- url: /zh/official/Reference/Core/GoTo.md --- # GoTo 无条件分支到过程中指定的行。 语法: > **GoTo** *line* *line* : 任何行标签或行号。 **GoTo** 只能分支到它所在过程中的行。 ::: info 过多的 **GoTo** 语句会使代码难以阅读和调试。尽可能使用结构化控制语句([**Do...Loop**](/official/Reference/Core/Do-Loop)、[**For...Next**](/official/Reference/Core/For-Next)、[**If...Then...Else**](/official/Reference/Core/If-Then-Else)、[**Select Case**](/official/Reference/Core/Select-Case))。 ::: ### 示例 本示例使用 **GoTo** 语句分支到过程中的行标签。 ```vb Sub GotoStatementDemo() Dim Number, MyString Number = 1 ' Initialize variable. ' Evaluate Number and branch to appropriate label. If Number = 1 Then GoTo Line1 Else GoTo Line2 Line1: MyString = "Number equals 1" GoTo LastLine ' Go to LastLine. Line2: ' The following statement never gets executed. MyString = "Number equals 2" LastLine: Debug.Print MyString ' Print "Number equals 1" in the Immediate window. End Sub ``` ### 另请参阅 * [**On...GoTo** 语句](/official/Reference/Core/On-GoTo) * [**GoSub...Return** 语句](/official/Reference/Core/GoSub-Return) * [**On Error** 语句](/official/Reference/Core/On-Error) * [**Select Case** 语句](/official/Reference/Core/Select-Case) --- --- url: /zh/official/Features/GUI-Components.md --- # GUI 组件 twinBASIC 通过增强的窗体、改进的控件和新的控件类型来现代化 GUI 组件。 ## 主题 * [窗体](/official/Features/GUI-Components/Forms) - 窗体增强和功能 * [锚定和停靠](/official/Features/GUI-Components/Anchoring-Docking) - 自动大小和位置管理 * [无窗口控件](/official/Features/GUI-Components/Windowless) - 无窗口与有窗口控件 * [控件现代化](/official/Features/GUI-Components/Modernization) - 控件现代化和 64 位支持 * [新控件](/official/Features/GUI-Components/New) - QR Code、Multiframe 和 CheckMark 控件 * [控件属性](/official/Features/GUI-Components/Control-Properties) - 附加控件属性和增强 * [UserControl 增强](/official/Features/GUI-Components/UserControl) - UserControl 改进 --- --- url: /en/official/Features/GUI-Components.md --- # GUI Components twinBASIC modernizes GUI components with enhanced forms, improved controls, and new control types. ## Topics * [Forms](/en/official/Features/GUI-Components/Forms) - Form enhancements and features * [Anchoring and Docking](/en/official/Features/GUI-Components/Anchoring-Docking) - Automatic size and position management * [Windowless Controls](/en/official/Features/GUI-Components/Windowless) - Windowless vs windowed controls * [Modern Controls](/en/official/Features/GUI-Components/Modernization) - Control modernization and 64-bit support * [New Controls](/en/official/Features/GUI-Components/New) - QR Code, Multiframe, and CheckMark controls * [Control Properties](/en/official/Features/GUI-Components/Control-Properties) - Additional control properties and enhancements * [UserControl Enhancements](/en/official/Features/GUI-Components/UserControl) - UserControl improvements --- --- url: /zh/official/Features/Language/Handlers.md --- # 新的 Handler 类成员语法 你现在可以将方法名与它所应用的类成员分开。 ## 事件 Handles 对于窗体、UserControl 和引发事件的对象上的事件,你可以将任何方法定义为处理程序,而无需将其命名为 `Object_Event()`,只需在其后添加 `Handles Object.Event`。例如,在窗体中,你可以用 `Private Sub OnLoad() Handles Form.Load` 来处理 `Load` 事件,而不是 `Private Sub Form_Load()`。 ```vb Private Sub OnLoad() Handles Form.Load Caption = "Loaded" End Sub Private Sub OnClick() Handles Command1.Click Debug.Print "clicked" End Sub ``` ## 接口 Implements 类似于上述,对于使用 `Implements` 的窗体/UC/类,你可以使用 `Sub Bar() Implements IFoo.Bar`。注意你可以指定多个实现的方法;更多信息请参见 [Implements 增强部分](/official/Features/Language/Interfaces-CoClasses)。 ::: info 这些是可选的。为了兼容性,twinBASIC 将始终继续支持传统的事件处理和 Implements 语法,你不被要求使用此新语法(或本文中描述的*任何*新增功能)。自动创建的原型是否使用此语法通过 IDE 选项控制:"IDE: Use new handles/implements syntax"。 ::: --- --- url: /en/official/Features/Language/Handlers.md --- # New Handler Class Member Syntax You can now separate the name of method from the class member it applies to. ## Handles for Events For events on Forms, UserControls, and event-raising objects, you can define any method as the handler, rather than need to name it as `Object_Event()`, by following it with `Handles Object.Event`. For example, in a form, instead of `Private Sub Form_Load()` you could handle the `Load` event with `Private Sub OnLoad() Handles Form.Load`. ```vb Private Sub OnLoad() Handles Form.Load Caption = "Loaded" End Sub Private Sub OnClick() Handles Command1.Click Debug.Print "clicked" End Sub ``` ## Implements for Interfaces Similar to the above, for forms/UCs/classes that use `Implements`, you can use `Sub Bar() Implements IFoo.Bar`. Note that you can specify more than one implemented method; for more information, see the [Enhancements to Implements section](/en/official/Features/Language/Interfaces-CoClasses). ::: info These are opt-in and optional. For compatibility, twinBASIC will always continue to support the traditional syntax for event handling and Implements, and you're not required to use this new syntax (or *any* of the additions described in this article). Whether or not automatically created prototypes use this syntax is controlled via IDE Options: "IDE: Use new handles/implements syntax". ::: --- --- url: /en/official/Reference/Core/Handles.md --- # Handles A trailing clause on a procedure header that binds the procedure as an event handler for one or more specific events. ::: info The **Handles** clause is a twinBASIC extension. Classic VBA connects event handlers solely by name: a `Sub` called `Form_Load` automatically handles the `Load` event of `Form`. twinBASIC still supports that pattern --- **Handles** decouples the procedure name from the events it handles and lets one body handle several events at once. Whether the IDE inserts the new syntax when auto-generating event prototypes is controlled by the "IDE: Use new handles/implements syntax" option. ::: Syntax: > *procedure-header* **Handles** *object*.*event* \[ **,** *object*.*event* ] … *procedure-header* : A complete [**Sub**](/en/official/Reference/Core/Sub), [**Function**](/en/official/Reference/Core/Function), or [**Property**](/en/official/Reference/Core/Property) header, including any access modifier, name, parameter list, and (for **Function** / **Property Get**) return type. *object* : An identifier naming an event source visible in the enclosing class, form, or user-control: the host's own implicit identifier (`Form`, `UserControl`, `MyClass`), a control declared on a form (`Command1`, `Text1`, …), or a [**WithEvents**](/en/official/Reference/Core/Dim) member variable. *event* : The name of an [**Event**](/en/official/Reference/Core/Event) declared on the type of *object*. The procedure's parameter list must match the signatures of every event it handles. When several events are listed they must all share the same signature, so one body can service them interchangeably. Because **Handles** decouples the procedure's name from the events it handles, the procedure can: * have a descriptive name (`OnLoad`, `SyncOpacity`) instead of the compound `<Object>_<Event>` form; * factor several related event handlers into a single body without duplicating code; and * handle an event from a procedure whose name happens to collide with the implicit naming pattern. The classic naming convention is unaffected: a procedure literally named `*object*_*event*` continues to be auto-wired as a handler for that event, with or without **Handles** clauses elsewhere on the same event. ### Example A descriptively named handler for a form's `Load` event: ```vb Private Sub OnLoad() Handles Form.Load Debug.Print "Form is loading." End Sub ``` A single body responding to several property-change events at once (adapted from the standard `CheckMark` control): ```vb Protected Sub SignificantChange() _ Handles BackColor.OnPropertyLet, _ BackStyle.OnPropertyLet, _ Appearance.OnPropertyLet, _ Value.OnPropertyLet Me.WindowlessRefresh() End Sub ``` For comparison, the equivalent classic-VBA naming-convention form for one of those events: ```vb Private Sub BackColor_OnPropertyLet() Me.WindowlessRefresh() End Sub ``` \--- a separate procedure body would be required per event. ### See Also * [**Sub** statement](/en/official/Reference/Core/Sub) * [**Function** statement](/en/official/Reference/Core/Function) * [**Property** statement](/en/official/Reference/Core/Property) * [**Event** statement](/en/official/Reference/Core/Event) * [**Implements** statement](/en/official/Reference/Core/Implements) * [Handler Method Syntax](/en/official/Features/Language/Handlers) --- --- url: /zh/official/Reference/Core/Handles.md --- # Handles 过程头部上的尾部子句,将过程绑定为一个或多个特定事件的事件处理程序。 ::: info **Handles** 子句是twinBASIC扩展。经典VBA仅通过名称连接事件处理程序:名为 `Form_Load` 的 `Sub` 自动处理 `Form` 的 `Load` 事件。twinBASIC仍然支持该模式——**Handles** 将过程名称与其处理的事件解耦,并允许一个函数体同时处理多个事件。IDE自动生成事件原型时是否插入新语法由"IDE: Use new handles/implements syntax"选项控制。 ::: 语法: > *procedure-header* **Handles** *object*.*event* \[ **,** *object*.*event* ] … *procedure-header* : 完整的 [**Sub**](/official/Reference/Core/Sub)、[**Function**](/official/Reference/Core/Function) 或 [**Property**](/official/Reference/Core/Property) 头部,包括任何访问修饰符、名称、参数列表和(对于 **Function** / **Property Get**)返回类型。 *object* : 命名封闭类、窗体或用户控件中可见的事件源的标识符:宿主的隐式标识符(`Form`、`UserControl`、`MyClass`)、窗体上声明的控件(`Command1`、`Text1`、…)或 [**WithEvents**](/official/Reference/Core/Dim) 成员变量。 *event* : 在 *object* 类型上声明的 [**Event**](/official/Reference/Core/Event) 的名称。 过程的参数列表必须匹配其处理的每个事件的签名。当列出多个事件时,它们必须共享相同的签名,以便一个函数体可以互换地服务它们。 因为 **Handles** 将过程的名称与其处理的事件解耦,过程可以: * 使用描述性名称(`OnLoad`、`SyncOpacity`)而非复合的 `<Object>_<Event>` 形式; * 将多个相关的事件处理程序合并到单个函数体中而无需重复代码; * 处理来自名称恰好与隐式命名模式冲突的过程的事件。 经典命名约定不受影响:字面上命名为 `*object*_*event*` 的过程继续自动连接为该事件的处理程序,无论同一事件上是否有其他 **Handles** 子句。 ### 示例 为窗体的 `Load` 事件使用描述性名称的处理程序: ```vb Private Sub OnLoad() Handles Form.Load Debug.Print "Form is loading." End Sub ``` 单个函数体同时响应多个属性更改事件(改编自标准 `CheckMark` 控件): ```vb Protected Sub SignificantChange() _ Handles BackColor.OnPropertyLet, _ BackStyle.OnPropertyLet, _ Appearance.OnPropertyLet, _ Value.OnPropertyLet Me.WindowlessRefresh() End Sub ``` 作为对比,其中一个事件的等效经典VBA命名约定形式: ```vb Private Sub BackColor_OnPropertyLet() Me.WindowlessRefresh() End Sub ``` ——每个事件需要一个单独的过程体。 ### 另请参阅 * [**Sub** 语句](/official/Reference/Core/Sub) * [**Function** 语句](/official/Reference/Core/Function) * [**Property** 语句](/official/Reference/Core/Property) * [**Event** 语句](/official/Reference/Core/Event) * [**Implements** 语句](/official/Reference/Core/Implements) * [处理程序方法语法](/official/Features/Language/Handlers) --- --- url: /en/official/Tutorials/Hello-World.md --- # Hello World In this tutorial you will create a Standard EXE project, place a button on a form, and write one line of code that shows a message box when the button is clicked. By the end you will have built and run your first twinBASIC application. ## Create the project Open twinBASIC and choose **File → New Project → Standard EXE**. The IDE creates a new project with one form, `Form1`, already open in the designer. Standard EXE is the most common project type. It produces a Windows executable with a form-based user interface --- the same kind of application that VB6 developers have built for decades. ## Add a button Look at the Toolbox panel on the left side of the IDE. It lists every control available in the current project. If the Toolbox is not visible, open it with **View → Toolbox**. Find the **CommandButton** entry in the Toolbox and double-click it. A button appears on `Form1` with the default name `Command1` and the caption `Command1`. You can drag the button to reposition it, or drag its handles to resize it. For this tutorial the default size and position are fine. ## Write the click handler Double-click the button in the designer. The IDE switches to the Code Editor and generates a skeleton for the button's **Click** event: ```vb Private Sub Command1_Click() End Sub ``` Place your cursor on the blank line inside the Sub and type: ```vb MsgBox "Hello, World!" ``` The complete handler looks like this: ```vb Private Sub Command1_Click() MsgBox "Hello, World!" End Sub ``` [**MsgBox**](/en/official/Reference/VBA/Interaction/MsgBox) displays a standard Windows message box with the text you pass to it. It pauses execution until the user dismisses the dialog. ## Run the application Press **F5** (or choose **Run → Start**). The form appears as a regular window on your desktop. Click the **Command1** button. A message box pops up with the text "Hello, World!". Click **OK** to close the message box, then close the form to stop the application and return to the IDE. ## What just happened When you double-clicked the button in the designer, the IDE created an event-handler Sub named after the control and the event --- `Command1_Click`. twinBASIC calls this Sub automatically whenever the button receives a Click message from Windows. **MsgBox** is a function from the [VBA runtime library](/en/official/Reference/VBA/Interaction/MsgBox), which is part of every twinBASIC project by default. It wraps the Win32 `MessageBox` API and handles the dialog lifecycle for you. The form itself is an operating-system window. Controls like **CommandButton** are child windows hosted inside it. The IDE's designer lets you position and configure these controls visually; the Code Editor is where you write the logic that responds to their events. ## Where to go next * [**Forms basics**](/en/official/Tutorials/Forms) --- adding multiple controls, setting properties, writing event handlers, and building a temperature converter. * [**Arrays**](/en/official/Tutorials/Arrays) --- fixed and dynamic arrays, bounds, and multi-dimensional shapes. --- --- url: /zh/official/Tutorials/Hello-World.md --- # Hello World 在本教程中,你将创建一个标准EXE项目,在窗体上放置一个按钮,编写一行代码,使得点击按钮时显示一个消息框。完成后你将构建并运行你的第一个twinBASIC应用程序。 ## 创建项目 打开twinBASIC,选择**文件 → 新建项目 → 标准EXE**。IDE会创建一个新项目,其中包含一个已在设计器中打开的窗体 `Form1`。 标准EXE是最常见的项目类型。它生成一个带有基于窗体用户界面的Windows可执行文件——正是VB6开发者数十年来构建的同类应用程序。 ## 添加按钮 查看IDE左侧的工具箱面板。它列出了当前项目中可用的所有控件。如果工具箱不可见,通过**视图 → 工具箱**打开它。 在工具箱中找到**CommandButton**条目并双击。一个按钮出现在 `Form1` 上,默认名称为 `Command1`,标题为 `Command1`。 你可以拖动按钮来重新定位,或拖动其手柄来调整大小。本教程中使用默认大小和位置即可。 ## 编写点击处理程序 在设计器中双击按钮。IDE切换到代码编辑器,并为按钮的**Click**事件生成一个框架: ```vb Private Sub Command1_Click() End Sub ``` 将光标放在Sub内的空行上,输入: ```vb MsgBox "Hello, World!" ``` 完整的处理程序如下: ```vb Private Sub Command1_Click() MsgBox "Hello, World!" End Sub ``` [**MsgBox**](/official/Reference/VBA/Interaction/MsgBox)显示一个标准的Windows消息框,内容为你传递给它的文本。它会暂停执行,直到用户关闭对话框。 ## 运行应用程序 按**F5**(或选择**运行 → 启动**)。窗体以常规窗口的形式出现在桌面上。点击**Command1**按钮。一个消息框弹出,显示文本"Hello, World!"。 点击**确定**关闭消息框,然后关闭窗体以停止应用程序并返回IDE。 ## 刚才发生了什么 当你在设计器中双击按钮时,IDE创建了一个以控件和事件命名的处理程序Sub——`Command1_Click`。每当按钮收到来自Windows的Click消息时,twinBASIC会自动调用此Sub。 **MsgBox**是[VBA运行时库](/official/Reference/VBA/Interaction/MsgBox)中的函数,默认包含在每个twinBASIC项目中。它封装了Win32 `MessageBox` API并为你处理对话框生命周期。 窗体本身是一个操作系统窗口。**CommandButton**等控件是托管在其中的子窗口。IDE的设计器让你可以可视化地定位和配置这些控件;代码编辑器是你编写响应其事件逻辑的地方。 ## 下一步 * [**窗体基础**](/official/Tutorials/Forms) —— 添加多个控件、设置属性、编写事件处理程序,并构建一个温度转换器。 * [**数组**](/official/Tutorials/Arrays) —— 固定数组和动态数组、边界和多维结构。 --- --- url: /en/official/IDE/Menu/Help.md --- # Help Menu ![Help Menu](/assets/Menu_Help.3Ygys9HS.png "Help Menu") * About twinBASIC... * Licence Agreement... * Automatic IDE Error Reporting... *** * Help & Support (Discord Server)... * Help & Support (GitHub repository)... * Twitter (News Feed)... *** * Purchase A Licence... * Enter Licence Key... * Buy us a Coffee! (Ko-Fi)... *** * Compiler services TRACE mode: Disabled ## About twinBASIC... ![About - Help Menu](/assets/Menu_Help_About.C_mmUuOm.png "About - Help Menu") ## Licence Agreement... ## Automatic IDE Error Reporting... ## Help & Support (Discord Server)... ## Help & Support (GitHub repository)... ## Twitter (News Feed)... ## Purchase A Licence... ## Enter Licence Key... ## Buy us a Coffee! (Ko-Fi)... ## Compiler services TRACE mode: Disabled --- --- url: /en/official/Reference/VBA/ErrObject/HelpContext.md --- # HelpContext Returns or sets a **Long** containing the context ID for a topic in the Help file associated with the active error. Read/write. Syntax: * **Err**.**HelpContext** * **Err**.**HelpContext** **=** *contextID* *contextID* : A **Long** specifying the context ID for the appropriate Help topic. Set to **0** when no specific topic applies. The **HelpContext** property is used to automatically display the Help topic specified in the [**HelpFile**](/en/official/Reference/VBA/ErrObject/HelpFile) property. If both **HelpFile** and **HelpContext** are empty, the value of [**Number**](/en/official/Reference/VBA/ErrObject/Number) is checked. If **Number** corresponds to a built-in run-time error, the Help context ID for that error is used. If the **Number** value doesn't correspond to a built-in error, the contents page of the Help file is displayed. Write routines to handle typical errors. When programming with an object, the object's Help file can improve error handling or display a meaningful message to the user when an error isn't recoverable. ### Example This example uses the **HelpContext** property of the **Err** object to show the Help topic for the `Overflow` error. ```vb Dim msg As String Err.Clear On Error Resume Next Err.Raise 6 ' Generate "Overflow" error. If Err.Number <> 0 Then msg = "Press F1 or HELP to see " & Err.HelpFile & " topic for" & _ " the following HelpContext: " & Err.HelpContext MsgBox msg, , "Error: " & Err.Description, Err.HelpFile, _ Err.HelpContext End If ``` ### See Also * [HelpFile](/en/official/Reference/VBA/ErrObject/HelpFile) property * [Number](/en/official/Reference/VBA/ErrObject/Number) property * [Raise](/en/official/Reference/VBA/ErrObject/Raise) method --- --- url: /zh/official/Reference/VBA/ErrObject/HelpContext.md --- # HelpContext 返回或设置一个 **Long**,包含与活动错误关联的帮助文件中主题的上下文 ID。可读/写。 语法: * **Err**.**HelpContext** * **Err**.**HelpContext** **=** *contextID* *contextID* : 指定相应帮助主题上下文 ID 的 **Long**。当没有特定主题适用时设置为 **0**。 **HelpContext** 属性用于自动显示 [**HelpFile**](/official/Reference/VBA/ErrObject/HelpFile) 属性中指定的帮助主题。 如果 **HelpFile** 和 **HelpContext** 均为空,则检查 [**Number**](/official/Reference/VBA/ErrObject/Number) 的值。如果 **Number** 对应于内置运行时错误,则使用该错误的帮助上下文 ID。如果 **Number** 值不对应于内置错误,则显示帮助文件的内容页。 编写处理典型错误的例程。使用对象编程时,对象的帮助文件可以在错误不可恢复时改善错误处理或向用户显示有意义的消息。 ### 示例 此示例使用 **Err** 对象的 **HelpContext** 属性显示 `Overflow` 错误的帮助主题。 ```vb Dim msg As String Err.Clear On Error Resume Next Err.Raise 6 ' Generate "Overflow" error. If Err.Number <> 0 Then msg = "Press F1 or HELP to see " & Err.HelpFile & " topic for" & _ " the following HelpContext: " & Err.HelpContext MsgBox msg, , "Error: " & Err.Description, Err.HelpFile, _ Err.HelpContext End If ``` ### 另请参阅 * [HelpFile](/official/Reference/VBA/ErrObject/HelpFile) 属性 * [Number](/official/Reference/VBA/ErrObject/Number) 属性 * [Raise](/official/Reference/VBA/ErrObject/Raise) 方法 --- --- url: /en/official/Reference/VBA/ErrObject/HelpFile.md --- # HelpFile Returns or sets a **String** with the fully qualified path to a Help file associated with the active error. Read/write. Syntax: * **Err**.**HelpFile** * **Err**.**HelpFile** **=** *helpFilePath* *helpFilePath* : A **String** with the fully qualified path of the Help file (typically a `.chm` file or a URL) to associate with the active error. If a Help file is specified in **HelpFile**, it is automatically called when the user presses the **Help** button (or **F1**) in the error message dialog box. If the [**HelpContext**](/en/official/Reference/VBA/ErrObject/HelpContext) property contains a valid context ID for the specified file, that topic is displayed automatically. Write routines to handle typical errors. When programming with an object, the object's Help file can improve error handling or display a meaningful message to the user when an error isn't recoverable. ### Example This example uses the **HelpFile** property of the **Err** object to start the Help system. ```vb Dim msg As String Err.Clear On Error Resume Next ' Suppress errors for demonstration purposes. Err.Raise 6 ' Generate "Overflow" error. msg = "Press F1 or HELP to see " & Err.HelpFile & _ " topic for this error." MsgBox msg, , "Error: " & Err.Description, Err.HelpFile ``` ### See Also * [HelpContext](/en/official/Reference/VBA/ErrObject/HelpContext) property * [Number](/en/official/Reference/VBA/ErrObject/Number) property * [Raise](/en/official/Reference/VBA/ErrObject/Raise) method --- --- url: /zh/official/Reference/VBA/ErrObject/HelpFile.md --- # HelpFile 返回或设置一个 **String**,包含与活动错误关联的帮助文件的完全限定路径。可读/写。 语法: * **Err**.**HelpFile** * **Err**.**HelpFile** **=** *helpFilePath* *helpFilePath* : 包含要与活动错误关联的帮助文件(通常为 `.chm` 文件或 URL)完全限定路径的 **String**。 如果在 **HelpFile** 中指定了帮助文件,当用户在错误消息对话框中按**帮助**按钮(或 **F1**)时,将自动调用该文件。如果 [**HelpContext**](/official/Reference/VBA/ErrObject/HelpContext) 属性包含指定文件的有效上下文 ID,则自动显示该主题。 编写处理典型错误的例程。使用对象编程时,对象的帮助文件可以在错误不可恢复时改善错误处理或向用户显示有意义的消息。 ### 示例 此示例使用 **Err** 对象的 **HelpFile** 属性启动帮助系统。 ```vb Dim msg As String Err.Clear On Error Resume Next ' Suppress errors for demonstration purposes. Err.Raise 6 ' Generate "Overflow" error. msg = "Press F1 or HELP to see " & Err.HelpFile & _ " topic for this error." MsgBox msg, , "Error: " & Err.Description, Err.HelpFile ``` ### 另请参阅 * [HelpContext](/official/Reference/VBA/ErrObject/HelpContext) 属性 * [Number](/official/Reference/VBA/ErrObject/Number) 属性 * [Raise](/official/Reference/VBA/ErrObject/Raise) 方法 --- --- url: /en/official/Reference/VBA/Conversion/Hex.md --- # Hex, Hex$ Returns a string representing the hexadecimal value of a number. Syntax: * **Hex$(** *number* **)** * **Hex(** *number* **)** *number* : *required* Any valid numeric or string expression. If *number* is not a whole number, it is rounded to the nearest whole number before being evaluated. The `$`-suffixed form returns a **String**; the unsuffixed form returns a **Variant** (**String**). | If *number* is | Hex returns | |---------------------------------|---------------------------------| | -2,147,483,648 to 2,147,483,647 | Up to eight hexadecimal characters | | **Null** | **Null** (unsuffixed form only) | | **Empty** | Zero (`"0"`) | For the opposite of **Hex**, precede a hexadecimal value with **\&H**. For example, `Hex(255)` returns the string `"FF"` and `&HFF` returns the number 255. ### Example This example uses the **Hex** function to return the hexadecimal value of a number. ```vb Dim MyHex MyHex = Hex(5) ' Returns "5". MyHex = Hex(10) ' Returns "A". MyHex = Hex(459) ' Returns "1CB". ``` ### See Also * [Oct](/en/official/Reference/VBA/Conversion/Oct), [Str](/en/official/Reference/VBA/Conversion/Str) functions --- --- url: /zh/official/Reference/VBA/Conversion/Hex.md --- # Hex, Hex$ 返回表示数字十六进制值的字符串。 语法: * **Hex$(** *number* **)** * **Hex(** *number* **)** *number* : *必需* 任何有效的数值或字符串表达式。如果 *number* 不是整数,则在求值前四舍五入到最接近的整数。 `$` 后缀形式返回 **String**;无后缀形式返回 **Variant** (**String**)。 | 如果 *number* 为 | Hex 返回 | |------------------|----------| | -2,147,483,648 到 2,147,483,647 | 最多八个十六进制字符 | | **Null** | **Null**(仅限无后缀形式) | | **Empty** | 零(`"0"`) | **Hex** 的逆操作:在十六进制值前加 **\&H**。例如,`Hex(255)` 返回字符串 `"FF"`,而 `&HFF` 返回数字 255。 ### 示例 此示例使用 **Hex** 函数返回数字的十六进制值。 ```vb Dim MyHex MyHex = Hex(5) ' Returns "5". MyHex = Hex(10) ' Returns "A". MyHex = Hex(459) ' Returns "1CB". ``` ### 另请参阅 * [Oct](/official/Reference/VBA/Conversion/Oct)、[Str](/official/Reference/VBA/Conversion/Str) 函数 --- --- url: /en/official/IDE/History.md --- # History When a project isn't open this will be empty. ![History](Images/History.png "History") Once you open a project ![History](Images/History_1.png "History") If you hover on an item it will show you the path of the file. ![History](/assets/History_2.CRqTgq_7.png "History") If it's a code file (i.e. `.twin`) it will show the "line: #". ![History](/assets/History_3.B5Ldrdm9.png "History") You can also click on an item to open it. --- --- url: /en/official/Reference/VBRUN/Constants/HitResultConstants.md --- # HitResultConstants Return values from a **UserControl**'s **HitTest** event, telling the host how the supplied point relates to the control. | Constant | Value | Description | |----------|-------|-------------| | **vbHitResultOutside** | 0 | The point is outside the control's hit-test region. | | **vbHitResultTransparent** | 1 | The point is inside the control's bounds but in a transparent area; mouse input passes through to the control behind. | | **vbHitResultClose** | 2 | The point is close to the control. | | **vbHitResultHit** | 3 | The point is inside the control and should be treated as a hit. | --- --- url: /zh/official/Reference/VBRUN/Constants/HitResultConstants.md --- # HitResultConstants **UserControl**的**HitTest**事件的返回值,告诉宿主所提供的点与控件的关系。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbHitResultOutside** | 0 | 该点在控件的点击测试区域之外。 | | **vbHitResultTransparent** | 1 | 该点在控件边界内但在透明区域;鼠标输入传递到后面的控件。 | | **vbHitResultClose** | 2 | 该点靠近控件。 | | **vbHitResultHit** | 3 | 该点在控件内,应视为命中。 | --- --- url: /en/official/Reference/tbIDE/Host.md --- # Host class The root API the IDE passes to every addin. The DLL receives a **Host** as the argument to its [`tbCreateCompilerAddin`](/en/official/Reference/tbIDE/#building-and-loading-an-addin) factory; the addin retains that reference for its lifetime and reaches every other capability through it --- the currently-loaded [**CurrentProject**](#currentproject), the [**ActiveEditors**](#activeeditors), the [**Toolbars**](#toolbars) for adding buttons, the [**ToolWindows**](#toolwindows) for adding HTML-rendered panels, the [**DebugConsole**](#debugconsole) for log output, the virtual [**FileSystem**](#filesystem), the [**KeyboardShortcuts**](#keyboardshortcuts) registry, the [**Themes**](#themes) state, plus the dialog helpers [**ShowMessageBox**](#showmessagebox) / [**ShowNotification**](#shownotification). Typically held via `WithEvents` so the addin can subscribe to lifecycle events: ```vb Private WithEvents Host As Host Public Sub New(ByVal Host As Host) Set Me.Host = Host End Sub Private Sub Host_OnProjectLoaded() With Host.Toolbars(0) .AddSplitter Set MyButton = .AddButton("MyButton", "My Action") End With End Sub ``` Almost every meaningful addin builds its toolbar buttons and tool windows inside the [**OnProjectLoaded**](#onprojectloaded) handler --- that is the first moment the IDE is fully ready to accept extensibility commands. ## Properties ### ActiveEditors The collection of editors currently open in the IDE. `Host.ActiveEditors(0)` returns the active one --- at present the IDE exposes exactly one active editor at a time and `Host.ActiveEditors.Count` is **1** when an editor is open, **0** when none is. **As** [**Editors**](/en/official/Reference/tbIDE/Editors). Read-only. ### CompilerVersion The full compiler-version string of the running IDE, e.g. `"0.15.371"`. **String**, read-only. Useful for diagnostic log lines and for compatibility gates. ### CurrentProject The currently-loaded project. Provides project name and path, lifecycle methods (Save / Close / Build / Clean), the project's [**RootFolder**](/en/official/Reference/tbIDE/Project#rootfolder) into the virtual file system, expression evaluation against the running project context, and persistent meta-data storage inside the `.twinproj` file. **As** [**Project**](/en/official/Reference/tbIDE/Project). Read-only. ### DebugConsole The IDE's DEBUG CONSOLE pane. Print, clear, or set focus. **As** [**DebugConsole**](/en/official/Reference/tbIDE/DebugConsole). Read-only. ### FileSystem The IDE's virtual file system --- the abstraction that lets the addin traverse and read source files without touching the on-disk paths. **As** [**FileSystem**](/en/official/Reference/tbIDE/FileSystem). Read-only. ### IDEProcessID The OS process ID of the running IDE process. **Long**, read-only. Useful for inter-process scenarios --- e.g. an external helper EXE that needs to know which IDE invoked it. ### IDEWindowHandle The Win32 `HWND` of the IDE's main window. **LongPtr**, read-only. Pass to Win32 APIs that need a window owner, or use as the parent handle when displaying owned modal dialogs from the addin. ### KeyboardShortcuts The keyboard-shortcut registry. Call [**KeyboardShortcuts.Add**](/en/official/Reference/tbIDE/KeyboardShortcuts#add) to bind a key combination to a callback. **As** [**KeyboardShortcuts**](/en/official/Reference/tbIDE/KeyboardShortcuts). Read-only. ### Themes The IDE's theme state. Exposes the active theme name and group; pair with the [**OnChangedTheme**](#onchangedtheme) event to react to user theme changes. **As** [**Themes**](/en/official/Reference/tbIDE/Themes). Read-only. ### Toolbars The collection of IDE toolbars. Currently a one-element collection --- `Host.Toolbars(0)` is the only available toolbar. **As** [**Toolbars**](/en/official/Reference/tbIDE/Toolbars). Read-only. ### ToolWindows Factory for HTML-rendered tool windows. Call [**ToolWindows.Add**](/en/official/Reference/tbIDE/ToolWindows#add) to create one. **As** [**ToolWindows**](/en/official/Reference/tbIDE/ToolWindows). Read-only. ## Methods ### ShowMessageBox Displays a modal IDE-styled dialog with a customisable button strip. Returns the zero-based index of the pressed button, or `-1` if the dialog was closed without picking one. Syntax: *host*.**ShowMessageBox**( *Prompt*, *Buttons*, *Title* ) **As Long** *Prompt* : *required* The message to display. **String**. *Buttons* : *required* A **String** of button captions separated by `|`. E.g. `"OK"` for a single OK button, `"Yes|No|Cancel"` for three buttons. *Title* : *required* The dialog's title-bar text. **String**. ```vb Select Case Host.ShowMessageBox("Save changes before closing?", _ "Save|Discard|Cancel", "Confirm") Case 0: ' Save Case 1: ' Discard Case 2, -1: ' Cancel or closed End Select ``` ### ShowNotification Displays a non-modal, discreet notification pop-up in the IDE --- a toast-style transient message that does not require the user to react. Syntax: *host*.**ShowNotification** *Prompt* *Prompt* : *required* The notification text. **String**. [**ShowMessageBox**](#showmessagebox) is for when the user has to answer something; **ShowNotification** is for "the user should know but doesn't have to react". ## Events The **Host** CoClass exposes three events. The third (and any future addition) is tagged with the compile-time `[AllowUnpopulatedVtableEntry]` attribute, which lets a newer addin compile against the newer events interface and still load against an older IDE that does not yet fire the newer event --- older IDEs leave the slot empty and the addin never receives that particular event. ### OnProjectLoaded Fires once the IDE has finished loading the project and is ready to accept extensibility commands. The canonical place to set up toolbar buttons, open tool windows that should be visible by default, register keyboard shortcuts, and log the start-up state to the [**DebugConsole**](/en/official/Reference/tbIDE/DebugConsole). Syntax: *host*\_**OnProjectLoaded**() ```vb Private Sub Host_OnProjectLoaded() With Host.Toolbars(0) .AddSplitter Set MyButton = .AddButton("MyButton", "My Action") End With End Sub ``` ### OnChangedActiveEditor Fires when the user switches the focused editor. The event is the right hook for refreshing any addin UI that depends on the current editor (e.g. a context-aware tool window). Available since IDE BETA 504+; older IDEs do not fire it. Syntax: *host*\_**OnChangedActiveEditor**(*EditorIdx* **As Long**, *Editor* **As** [**Editor**](/en/official/Reference/tbIDE/Editor)) *EditorIdx* : The zero-based index of the newly active editor in the [**ActiveEditors**](#activeeditors) collection. *Editor* : The newly active editor object. Castable to [**CodeEditor**](/en/official/Reference/tbIDE/CodeEditor) for code panes --- see [Editor castability](/en/official/Reference/tbIDE/Editor#castability). ### OnChangedTheme Fires when the user changes the IDE theme. Pair with [**Themes.ActiveThemeName**](/en/official/Reference/tbIDE/Themes#activethemename) / [**Themes.ActiveThemeNameGroup**](/en/official/Reference/tbIDE/Themes#activethemenamegroup) to refresh any colour-sensitive elements the addin draws inside its tool windows. Syntax: *host*\_**OnChangedTheme**(*ThemeName* **As String**) *ThemeName* : The new theme's name --- same value the user now sees in [**Themes.ActiveThemeName**](/en/official/Reference/tbIDE/Themes#activethemename) (e.g. `"Classic"`, `"Dark"`, `"Light"`). ## DebuggerEvaluateOptions A flags enum declared inline on the **Host** interface; consumed by [**Project.Evaluate**](/en/official/Reference/tbIDE/Project#evaluate) (and any future debugger-evaluation API). Currently a single-value placeholder --- additional flags may appear in later IDE versions. | Constant | Value | Description | |----------|-------|-------------| | **NONE** | 0 | No special evaluation options. | --- --- url: /zh/official/Reference/tbIDE/Host.md --- # Host 类 IDE 传递给每个插件的根 API。DLL 在其 [`tbCreateCompilerAddin`](/official/Reference/tbIDE/#构建和加载插件) 工厂函数中接收一个 **Host** 作为参数;插件在其生命周期内保留该引用,并通过它访问所有其他功能——当前加载的 [**CurrentProject**](#currentproject)、[**ActiveEditors**](#activeeditors)、用于添加按钮的 [**Toolbars**](#toolbars)、用于添加 HTML 渲染面板的 [**ToolWindows**](#toolwindows)、用于日志输出的 [**DebugConsole**](#debugconsole)、虚拟 [**FileSystem**](#filesystem)、[**KeyboardShortcuts**](#keyboardshortcuts) 注册表、[**Themes**](#themes) 状态,以及对话框辅助方法 [**ShowMessageBox**](#showmessagebox) / [**ShowNotification**](#shownotification)。 通常通过 `WithEvents` 持有,以便插件可以订阅生命周期事件: ```vb Private WithEvents Host As Host Public Sub New(ByVal Host As Host) Set Me.Host = Host End Sub Private Sub Host_OnProjectLoaded() With Host.Toolbars(0) .AddSplitter Set MyButton = .AddButton("MyButton", "My Action") End With End Sub ``` 几乎所有有意义的插件都在 [**OnProjectLoaded**](#onprojectloaded) 处理程序中构建其工具栏按钮和工具窗口——那是 IDE 完全准备好接受扩展性命令的第一个时刻。 ## 属性 ### ActiveEditors IDE 中当前打开的编辑器集合。`Host.ActiveEditors(0)` 返回活动编辑器——目前 IDE 同一时间只暴露一个活动编辑器,当编辑器打开时 `Host.ActiveEditors.Count` 为 **1**,没有时为 **0**。**As** [**Editors**](/official/Reference/tbIDE/Editors)。只读。 ### CompilerVersion 运行中 IDE 的完整编译器版本字符串,例如 `"0.15.371"`。**String**,只读。适用于诊断日志行和兼容性门控。 ### CurrentProject 当前加载的项目。提供项目名称和路径、生命周期方法(Save / Close / Build / Clean)、项目进入虚拟文件系统的 [**RootFolder**](/official/Reference/tbIDE/Project#rootfolder)、针对运行中项目上下文的表达式求值,以及 `.twinproj` 文件内的持久元数据存储。**As** [**Project**](/official/Reference/tbIDE/Project)。只读。 ### DebugConsole IDE 的调试控制台窗格。打印、清除或设置焦点。**As** [**DebugConsole**](/official/Reference/tbIDE/DebugConsole)。只读。 ### FileSystem IDE 的虚拟文件系统——让插件能够在不触及磁盘路径的情况下遍历和读取源文件的抽象。**As** [**FileSystem**](/official/Reference/tbIDE/FileSystem)。只读。 ### IDEProcessID 运行中 IDE 进程的操作系统进程 ID。**Long**,只读。适用于跨进程场景——例如需要知道是哪个 IDE 调用了它的外部辅助 EXE。 ### IDEWindowHandle IDE 主窗口的 Win32 `HWND`。**LongPtr**,只读。传递给需要窗口所有者的 Win32 API,或用作显示插件拥有的模态对话框时的父句柄。 ### KeyboardShortcuts 键盘快捷键注册表。调用 [**KeyboardShortcuts.Add**](/official/Reference/tbIDE/KeyboardShortcuts#add) 将组合键绑定到回调。**As** [**KeyboardShortcuts**](/official/Reference/tbIDE/KeyboardShortcuts)。只读。 ### Themes IDE 的主题状态。暴露活动主题名称和组;配合 [**OnChangedTheme**](#onchangedtheme) 事件响应用户主题更改。**As** [**Themes**](/official/Reference/tbIDE/Themes)。只读。 ### Toolbars IDE 工具栏集合。当前为单元素集合——`Host.Toolbars(0)` 是唯一可用的工具栏。**As** [**Toolbars**](/official/Reference/tbIDE/Toolbars)。只读。 ### ToolWindows HTML 渲染工具窗口的工厂。调用 [**ToolWindows.Add**](/official/Reference/tbIDE/ToolWindows#add) 创建一个。**As** [**ToolWindows**](/official/Reference/tbIDE/ToolWindows)。只读。 ## 方法 ### ShowMessageBox 显示一个模态的 IDE 风格对话框,带有可自定义的按钮条。返回所按按钮的基于 0 的索引,如果对话框在没有选择按钮的情况下被关闭则返回 `-1`。 语法:*host*.**ShowMessageBox**( *Prompt*, *Buttons*, *Title* ) **As Long** *Prompt* : *必需* 要显示的消息。**String**。 *Buttons* : *必需* 由 `|` 分隔的按钮标题组成的 **String**。例如 `"OK"` 表示单个确定按钮,`"Yes|No|Cancel"` 表示三个按钮。 *Title* : *必需* 对话框标题栏文本。**String**。 ```vb Select Case Host.ShowMessageBox("Save changes before closing?", _ "Save|Discard|Cancel", "Confirm") Case 0: ' 保存 Case 1: ' 丢弃 Case 2, -1: ' 取消或关闭 End Select ``` ### ShowNotification 在 IDE 中显示一个非模态、低调的通知弹出框——一个吐司式瞬态消息,不需要用户做出反应。 语法:*host*.**ShowNotification** *Prompt* *Prompt* : *必需* 通知文本。**String**。 [**ShowMessageBox**](#showmessagebox) 用于用户必须回答某事的场景;**ShowNotification** 用于"用户应该知道但不必做出反应"的信息。 ## 事件 **Host** CoClass 暴露三个事件。第三个(及任何未来新增的)事件标记了编译时属性 `[AllowUnpopulatedVtableEntry]`,这使得较新的插件可以针对较新的事件接口编译,同时仍能在不触发较新事件的旧版 IDE 中加载——旧版 IDE 将该槽位留空,插件永远不会接收那个特定事件。 ### OnProjectLoaded 当 IDE 完成项目加载并准备好接受扩展性命令时触发一次。用于设置工具栏按钮、打开默认可见的工具窗口、注册键盘快捷键以及将启动状态记录到 [**DebugConsole**](/official/Reference/tbIDE/DebugConsole) 的规范位置。 语法:*host*\_**OnProjectLoaded**() ```vb Private Sub Host_OnProjectLoaded() With Host.Toolbars(0) .AddSplitter Set MyButton = .AddButton("MyButton", "My Action") End With End Sub ``` ### OnChangedActiveEditor 当用户切换聚焦的编辑器时触发。此事件是刷新依赖于当前编辑器的任何插件 UI(例如上下文感知的工具窗口)的正确钩子。自 IDE BETA 504+ 起可用;旧版 IDE 不触发此事件。 语法:*host*\_**OnChangedActiveEditor**(*EditorIdx* **As Long**, *Editor* **As** [**Editor**](/official/Reference/tbIDE/Editor)) *EditorIdx* : [**ActiveEditors**](#activeeditors) 集合中新活动编辑器的基于 0 的索引。 *Editor* : 新的活动编辑器对象。对于代码窗格可转换为 [**CodeEditor**](/official/Reference/tbIDE/CodeEditor)——参见[编辑器可转换性](/official/Reference/tbIDE/Editor#可转换性)。 ### OnChangedTheme 当用户更改 IDE 主题时触发。配合 [**Themes.ActiveThemeName**](/official/Reference/tbIDE/Themes#activethemename) / [**Themes.ActiveThemeNameGroup**](/official/Reference/tbIDE/Themes#activethemenamegroup) 刷新插件在其工具窗口内绘制的任何颜色敏感元素。 语法:*host*\_**OnChangedTheme**(*ThemeName* **As String**) *ThemeName* : 新主题的名称——与用户现在在 [**Themes.ActiveThemeName**](/official/Reference/tbIDE/Themes#activethemename) 中看到的值相同(例如 `"Classic"`、`"Dark"`、`"Light"`)。 ## DebuggerEvaluateOptions 在 **Host** 接口上内联声明的标志枚举;由 [**Project.Evaluate**](/official/Reference/tbIDE/Project#evaluate)(及任何未来的调试器求值 API)消费。当前为单值占位符——未来 IDE 版本可能添加更多标志。 | 常量 | 值 | 描述 | |------|-----|------| | **NONE** | 0 | 无特殊求值选项。 | --- --- url: /en/official/Tutorials/CEF/Hosting-local-web-assets.md --- # Hosting local web assets A [**CefBrowser**](/en/official/Reference/CEF/CefBrowser/) control can serve HTML, JavaScript, CSS, and any other assets straight from a folder on disk --- no embedded HTTP server required. Chromium's [**SetVirtualHostNameToFolderMapping**](/en/official/Reference/CEF/CefBrowser/#setvirtualhostnametofoldermapping) routes a virtual `https://` hostname to a local folder so that resources behave as if they came from a real origin: same-origin `fetch`, Content Security Policy, service workers, and so on all work as expected. This tutorial demonstrates the pattern used by *Sample 1b --- Chromium Embedded Framework Examples* (forms *Example 2*, *Example 3*, *Example 4*). ## The three-step pattern 1. **Choose a folder.** It must exist on disk and contain `index.html` (plus whatever assets the page wants --- scripts, styles, images). 2. **Register a virtual host** mapping to that folder. 3. **Navigate** to a URL under the virtual hostname. Hook into the [**Ready**](/en/official/Reference/CEF/CefBrowser/#ready) event so the control is fully initialised before the mapping is installed: ```vb Private Sub WebView_Ready() Handles WebView.Ready Dim folderPath As String = _ Environ$("USERPROFILE") & "\Documents\MyApp" WebView.SetVirtualHostNameToFolderMapping _ "myapp.example", folderPath & "\" WebView.Navigate "https://myapp.example/index.html" End Sub ``` Once mapped, every request to `https://myapp.example/<path>` is served from `folderPath\<path>`. A `<script src="/script.js">` on the page resolves to `folderPath\script.js` exactly as if a real web server were sitting on `myapp.example`. The trailing backslash on the folder path is required --- the runtime concatenates the incoming URL path onto the folder string verbatim, so a missing separator turns `folderPath` + `/index.html` into a nonsense path. ## Picking a hostname The safe convention is to pick a hostname under a TLD that will never resolve on the public Internet: | Recommended | Avoid | |---------------------|-----------------------------| | `myapp.example` | `myapp.com`, `app.local` | | `editor.invalid` | `editor.dev` | | `assets.test` | `assets.io` | The `.example`, `.invalid`, and `.test` TLDs are formally reserved by IANA and will never be allocated to a real domain, so they're safe to use indefinitely. ## Bundling assets in the project's Resources folder Most applications want to ship their HTML / JS / CSS *inside* the executable and drop them onto disk on first run. twinBASIC's `Resources` folder is the right place to keep them. 1. In the IDE's Project explorer, expand **Resources** and add a sub-folder (right-click → *Add new subfolder*). Name it something memorable like `WEB_APP`. 2. Drop the assets in --- `index.html`, `script.js`, `styles.css`, plus any sub-directories you need. At runtime, the helper below copies the contents of a `Resources` sub-folder out to a local path. Drop it into a `.twin` module in your project: ```vb Module Files Private Sub CreateFile(ByVal Path As String, ByRef Data() As Byte) On Error Resume Next : Kill Path : On Error GoTo 0 Dim fileNum As Integer = FreeFile Open Path For Binary As fileNum Put fileNum, 1, Data Close fileNum End Sub Private Sub CreateLocalFileFromResource( _ ByVal OutputLocalFolderPath As String, _ ByVal InputResourceSubFolderName As String, _ ByVal ResourceName As String) Dim splitPath As Variant = Split(ResourceName, "~") On Error Resume Next : MkDir OutputLocalFolderPath : On Error GoTo 0 Dim i As Long For i = 0 To UBound(splitPath) - 1 OutputLocalFolderPath &= "\" & splitPath(i) On Error Resume Next : MkDir OutputLocalFolderPath : On Error GoTo 0 Next Dim Data() As Byte Data = LoadResData(ResourceName, InputResourceSubFolderName) CreateFile(OutputLocalFolderPath & "\" & splitPath(i), Data) End Sub [Description("Copy every file from a Resources subfolder onto disk. " & _ "'~' characters in resource names represent subfolders.")] Public Sub CopyResourcesFolderContentsToLocalPath( _ ByVal InputResourceSubFolderName As String, _ ByVal OutputLocalFolderPath As String) Dim resourceId As Variant For Each resourceId In LoadResIdList(InputResourceSubFolderName) CreateLocalFileFromResource _ OutputLocalFolderPath, InputResourceSubFolderName, resourceId Next End Sub End Module ``` [**LoadResIdList**](/en/official/Reference/VB/Global/#loadresidlist) returns every resource ID under the named sub-folder; [**LoadResData**](/en/official/Reference/VB/Global/#loadresdata) returns the bytes. The helper splits each resource name on `~` to reconstruct the original sub-directory tree on disk --- the twinBASIC IDE flattens nested folders by joining their names with `~` when the resources are compiled in. ## Putting it together The complete deploy-on-`Ready` pattern looks like this: ```vb Private Sub WebView_Ready() Handles WebView.Ready ' Resources/WEB_APP/* is copied here on every launch. Dim folderPath As String = _ Environ$("USERPROFILE") & "\Documents\MyApp" CopyResourcesFolderContentsToLocalPath "WEB_APP", folderPath WebView.SetVirtualHostNameToFolderMapping _ "myapp.example", folderPath & "\" WebView.Navigate "https://myapp.example/index.html" End Sub ``` Once deployed, the application can launch DevTools ([**OpenDevToolsWindow**](/en/official/Reference/CEF/CefBrowser/#opendevtoolswindow)) to inspect the loaded files, and users can edit `index.html` directly on disk and hit **Refresh** --- useful for rapid iteration during development. ## Removing a mapping [**ClearVirtualHostNameToFolderMapping**](/en/official/Reference/CEF/CefBrowser/#clearvirtualhostnametofoldermapping) removes a mapping previously installed by [**SetVirtualHostNameToFolderMapping**](/en/official/Reference/CEF/CefBrowser/#setvirtualhostnametofoldermapping): ```vb WebView.ClearVirtualHostNameToFolderMapping "myapp.example" ``` The browser keeps cached assets until a hard reload, so a navigation that hits the just-removed hostname may still succeed for a short while. ## Where next * [JavaScript interop](/en/official/Tutorials/CEF/JavaScript-interop) -- how a hosted page exchanges values and method calls with the BASIC application. * [Driving Monaco from twinBASIC](/en/official/Tutorials/CEF/Driving-Monaco) -- a full case study built on top of this pattern. * [SetVirtualHostNameToFolderMapping](/en/official/Reference/CEF/CefBrowser/#setvirtualhostnametofoldermapping) -- full reference. --- --- url: /en/official/Tutorials/WebView2/Hosting-local-web-assets.md --- # Hosting local web assets A [**WebView2**](/en/official/Reference/WebView2/WebView2/) control can serve HTML, JavaScript, CSS, and any other assets straight from a folder on disk --- no embedded HTTP server required. Edge's [**SetVirtualHostNameToFolderMapping**](/en/official/Reference/WebView2/WebView2/#setvirtualhostnametofoldermapping) routes a virtual `https://` hostname to a local folder so that resources behave as if they came from a real origin: same-origin `fetch`, Content Security Policy, service workers, and so on all work as expected. This tutorial demonstrates the pattern used by *Sample 0 --- WebView2 Examples* (forms *Example 2*, *Example 3*, *Example 4*). ## The three-step pattern 1. **Choose a folder.** It must exist on disk and contain `index.html` (plus whatever assets the page wants --- scripts, styles, images). 2. **Register a virtual host** mapping to that folder. 3. **Navigate** to a URL under the virtual hostname. Hook into the [**Ready**](/en/official/Reference/WebView2/WebView2/#ready) event so the control is fully initialised before the mapping is installed: ```vb Private Sub WebView_Ready() Handles WebView.Ready Dim folderPath As String = _ Environ$("USERPROFILE") & "\Documents\MyApp" WebView.SetVirtualHostNameToFolderMapping _ "myapp.example", folderPath & "\", wv2ResourceAllow WebView.Navigate "https://myapp.example/index.html" End Sub ``` Once mapped, every request to `https://myapp.example/<path>` is served from `folderPath\<path>`. A `<script src="/script.js">` on the page resolves to `folderPath\script.js` exactly as if a real web server were sitting on `myapp.example`. ## Picking a hostname The Edge runtime resolves the virtual hostname through DNS *before* applying the local override. Hostnames that happen to be resolvable on the public Internet introduce a small (≈2 s) stall on every request --- see [WebView2Feedback#2381](https://github.com/MicrosoftEdge/WebView2Feedback/issues/2381). The safe convention is to pick a name under a TLD that will never resolve, like `.example`, `.invalid`, or `.test`: | Recommended | Avoid | |---------------------|-----------------------------| | `myapp.example` | `myapp.com`, `app.local` | | `editor.invalid` | `editor.dev` | | `assets.test` | `assets.io` | ## Bundling assets in the project's Resources folder Most applications want to ship their HTML / JS / CSS *inside* the executable and drop them onto disk on first run. twinBASIC's `Resources` folder is the right place to keep them. 1. In the IDE's Project explorer, expand **Resources** and add a sub-folder (right-click → *Add new subfolder*). Name it something memorable like `WEB_APP`. 2. Drop the assets in --- `index.html`, `script.js`, `styles.css`, plus any sub-directories you need. At runtime, the helper below copies the contents of a `Resources` sub-folder out to a local path. Drop it into a `.twin` module in your project: ```vb Module Files Private Sub CreateFile(ByVal Path As String, ByRef Data() As Byte) On Error Resume Next : Kill Path : On Error GoTo 0 Dim fileNum As Integer = FreeFile Open Path For Binary As fileNum Put fileNum, 1, Data Close fileNum End Sub Private Sub CreateLocalFileFromResource( _ ByVal OutputLocalFolderPath As String, _ ByVal InputResourceSubFolderName As String, _ ByVal ResourceName As String) Dim splitPath As Variant = Split(ResourceName, "~") On Error Resume Next : MkDir OutputLocalFolderPath : On Error GoTo 0 Dim i As Long For i = 0 To UBound(splitPath) - 1 OutputLocalFolderPath &= "\" & splitPath(i) On Error Resume Next : MkDir OutputLocalFolderPath : On Error GoTo 0 Next Dim Data() As Byte Data = LoadResData(ResourceName, InputResourceSubFolderName) CreateFile(OutputLocalFolderPath & "\" & splitPath(i), Data) End Sub [Description("Copy every file from a Resources subfolder onto disk. " & _ "'~' characters in resource names represent subfolders.")] Public Sub CopyResourcesFolderContentsToLocalPath( _ ByVal InputResourceSubFolderName As String, _ ByVal OutputLocalFolderPath As String) Dim resourceId As Variant For Each resourceId In LoadResIdList(InputResourceSubFolderName) CreateLocalFileFromResource _ OutputLocalFolderPath, InputResourceSubFolderName, resourceId Next End Sub End Module ``` [**LoadResIdList**](/en/official/Reference/VB/Global/#loadresidlist) returns every resource ID under the named sub-folder; [**LoadResData**](/en/official/Reference/VB/Global/#loadresdata) returns the bytes. The helper splits each resource name on `~` to reconstruct the original sub-directory tree on disk --- the twinBASIC IDE flattens nested folders by joining their names with `~` when the resources are compiled in. ## Putting it together The complete deploy-on-`Ready` pattern looks like this: ```vb Private Sub WebView_Ready() Handles WebView.Ready ' Resources/WEB_APP/* is copied here on every launch. Dim folderPath As String = _ Environ$("USERPROFILE") & "\Documents\MyApp" CopyResourcesFolderContentsToLocalPath "WEB_APP", folderPath WebView.SetVirtualHostNameToFolderMapping _ "myapp.example", folderPath & "\", wv2ResourceAllow WebView.Navigate "https://myapp.example/index.html" End Sub ``` Once deployed, the application can launch DevTools ([**OpenDevToolsWindow**](/en/official/Reference/WebView2/WebView2/#opendevtoolswindow)) to inspect the loaded files, and users can edit `index.html` directly on disk and hit **Refresh** --- useful for rapid iteration during development. ## Where next * [JavaScript interop](/en/official/Tutorials/WebView2/JavaScript-interop) -- how a hosted page exchanges values and method calls with the BASIC application. * [Driving Monaco from twinBASIC](/en/official/Tutorials/WebView2/Driving-Monaco) -- a full case study built on top of this pattern. * [SetVirtualHostNameToFolderMapping](/en/official/Reference/WebView2/WebView2/#setvirtualhostnametofoldermapping) -- full reference. --- --- url: /en/packages/vbccr/text/hotkey.md description: >- HotKey Control - VBCCR Development Manual, complete API reference based on source code --- # HotKey Control Provides the Windows standard hot key input control, allowing users to select shortcut key combinations. ## Enumerations ### HkeInvalidKeyCombinationConstants | Constant | Value | Description | |----------|-------|-------------| | HkeInvalidKeyCombinationNone | 1 | Invalid combination: no modifier | | HkeInvalidKeyCombinationShift | 2 | Invalid combination: Shift only | | HkeInvalidKeyCombinationCtrl | 4 | Invalid combination: Ctrl only | | HkeInvalidKeyCombinationAlt | 8 | Invalid combination: Alt only | | HkeInvalidKeyCombinationShiftCtrl | 16 | Invalid combination: Shift+Ctrl | | HkeInvalidKeyCombinationShiftAlt | 32 | Invalid combination: Shift+Alt | | HkeInvalidKeyCombinationCtrlAlt | 64 | Invalid combination: Ctrl+Alt | | HkeInvalidKeyCombinationShiftCtrlAlt | 128 | Invalid combination: Shift+Ctrl+Alt | ## Properties ### Name ```vb Property Get Name() As String ``` Returns the name of the control. ### Tag ```vb Property Get/Let Tag() As String ``` Returns/sets the tag value of the control. ### Parent ```vb Property Get Parent() As Object ``` Returns the parent object of the control. ### Container ```vb Property Get/Set Container() As Object ``` Returns/sets the container of the control. ### Left ```vb Property Get/Let Left() As Single ``` Returns/sets the position of the left edge of the control. ### Top ```vb Property Get/Let Top() As Single ``` Returns/sets the position of the top edge of the control. ### Width ```vb Property Get/Let Width() As Single ``` Returns/sets the width of the control. ### Height ```vb Property Get/Let Height() As Single ``` Returns/sets the height of the control. ### Visible ```vb Property Get/Let Visible() As Boolean ``` Returns/sets whether the control is visible. ### ToolTipText ```vb Property Get/Let ToolTipText() As String ``` Returns/sets the tooltip text of the control. ### HelpContextID ```vb Property Get/Let HelpContextID() As Long ``` Returns/sets the help context ID of the control. ### WhatsThisHelpID ```vb Property Get/Let WhatsThisHelpID() As Long ``` Returns/sets the "What's This" help ID of the control. ### DragIcon ```vb Property Get/Let/Set DragIcon() As IPictureDisp ``` Returns/sets the icon displayed during drag operations. ### DragMode ```vb Property Get/Let DragMode() As Integer ``` Returns/sets the drag mode (manual or automatic). ### hWnd ```vb Property Get hWnd() As LongPtr ``` Returns the window handle of the HotKey control. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Returns the window handle of the UserControl. ### Font ```vb Property Get/Let/Set Font() As StdFont ``` Returns/sets the font used by the control. ### VisualStyles ```vb Property Get/Let VisualStyles() As Boolean ``` Returns/sets whether visual styles are enabled. ### Enabled ```vb Property Get/Let Enabled() As Boolean ``` Returns/sets whether the control is enabled. ### OLEDropMode ```vb Property Get/Let OLEDropMode() As OLEDropModeConstants ``` Returns/sets the OLE drop mode. See common enumerations. ### MousePointer ```vb Property Get/Let MousePointer() As CCMousePointerConstants ``` Returns/sets the mouse pointer type. See common enumerations. ### MouseIcon ```vb Property Get/Let/Set MouseIcon() As IPictureDisp ``` Returns/sets the custom mouse icon. ### MouseTrack ```vb Property Get/Let MouseTrack() As Boolean ``` Returns/sets whether mouse enter/leave tracking is enabled. ### BackColor ```vb Property Get/Let BackColor() As OLE_COLOR ``` Returns/sets the background color of the control. ### BorderStyle ```vb Property Get/Let BorderStyle() As CCBorderStyleConstants ``` Returns/sets the border style of the control. See common enumerations. ### Value ```vb Property Get/Let Value(Optional ByRef Modifiers As Integer) As VBRUN.KeyCodeConstants ``` Returns/sets the key code of the hot key. The Modifiers parameter receives modifier key flags (Shift=1, Ctrl=2, Alt=4). ### RawValue ```vb Property Get/Let RawValue() As Long ``` Returns/sets the raw numeric value of the hot key (low byte is the key code, high byte is the modifier key flags). ### Text ```vb Property Get Text() As String ``` Returns the display text of the hot key. Read-only. ## Methods ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag operation. ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` Starts, ends, or cancels a drag operation. ### SetFocus ```vb Public Sub SetFocus() ``` Moves the focus to the control. ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` Sets the Z-order position of the control within its layer. ### Refresh ```vb Public Sub Refresh() ``` Forces a complete repaint of the control. ### SetRules ```vb Public Sub SetRules(ByVal InvalidKeyCombinations As HkeInvalidKeyCombinationConstants, Optional ByVal DefaultModifiers As VBRUN.ShiftConstants) ``` Sets invalid key combination rules and default modifier keys. InvalidKeyCombinations specifies the modifier key combinations that are not allowed; DefaultModifiers specifies the default modifier key to substitute when the user enters an invalid combination. ### SetApplicationHotKey ```vb Public Function SetApplicationHotKey(Optional ByVal hWnd As LongPtr) As Long ``` Registers the current hot key as the application hot key for a window. The return value is the result of the WM\_SETHOTKEY message. ## Events ### Click ```vb Public Event Click() ``` Occurs when the control is clicked. ### DblClick ```vb Public Event DblClick() ``` Occurs when the control is double-clicked. ### Change ```vb Public Event Change() ``` Occurs when the hot key value changes. ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Occurs before the KeyDown event; IsInputKey can be set to mark whether the key is an input key. ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Occurs before the KeyUp event. ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` Occurs when a keyboard key is pressed. ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` Occurs when a keyboard key is released. ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` Occurs when a character key is pressed and released. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when a mouse button is pressed. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when the mouse is moved. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when a mouse button is released. ### MouseEnter ```vb Public Event MouseEnter() ``` Occurs when the mouse enters the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Occurs when the mouse leaves the control. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` Occurs on the source control after an OLE drag-and-drop operation has been completed or canceled. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when data is dropped onto the control via an OLE drag-and-drop operation. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` Occurs when the mouse moves over the control during an OLE drag-and-drop operation. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` Occurs on the source control when the mouse cursor needs to be changed during an OLE drag-and-drop operation. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` Occurs on the source control when the drop target requests data. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` Occurs when an OLE drag-and-drop operation is initiated. ## Code Examples ### Basic Usage ```vb Private Sub Form_Load() With HotKey1 .SetRules HkeInvalidKeyCombinationNone Or _ HkeInvalidKeyCombinationShift, vbCtrlMask .VisualStyles = True End With End Sub Private Sub HotKey1_Change() Dim Modifiers As Integer Dim KeyCode As VBRUN.KeyCodeConstants KeyCode = HotKey1.Value(Modifiers) Debug.Print "Hot key: " & HotKey1.Text Debug.Print "Raw value: " & HotKey1.RawValue End Sub Private Sub cmdRegisterHotKey_Click() Dim Result As Long Result = HotKey1.SetApplicationHotKey(Me.hWnd) If Result = 1 Then Debug.Print "Hot key registered successfully" Else Debug.Print "Hot key registration failed" End If End Sub ``` --- --- url: /en/official/Reference/VBA/DateTime/Hour.md --- # Hour Returns a **Variant** (**Integer**) specifying a whole number between 0 and 23, inclusive, representing the hour of the day. Syntax: **Hour** ( *time* ) *time* : *required* Any **Variant**, numeric expression, string expression, or any combination that can represent a time. If *time* contains **Null**, **Null** is returned. ### Example This example uses the **Hour** function to obtain the hour from a specified time. ```vb Dim MyTime, MyHour MyTime = #4:35:17 PM# ' Assign a time. MyHour = Hour(MyTime) ' MyHour contains 16. ``` ### See Also * [Minute](/en/official/Reference/VBA/DateTime/Minute), [Second](/en/official/Reference/VBA/DateTime/Second), [DatePart](/en/official/Reference/VBA/DateTime/DatePart) functions --- --- url: /zh/official/Reference/VBA/DateTime/Hour.md --- # Hour 返回一个 **Variant** (**Integer**),指定 0 到 23 之间(含)的整数,表示一天中的小时。 语法:**Hour** ( *time* ) *time* : *必需* 任何可以表示时间的 **Variant**、数值表达式、字符串表达式或其组合。如果 *time* 包含 **Null**,则返回 **Null**。 ### 示例 此示例使用 **Hour** 函数从指定时间获取小时。 ```vb Dim MyTime, MyHour MyTime = #4:35:17 PM# ' Assign a time. MyHour = Hour(MyTime) ' MyHour contains 16. ``` ### 另请参阅 * [Minute](/official/Reference/VBA/DateTime/Minute)、[Second](/official/Reference/VBA/DateTime/Second)、[DatePart](/official/Reference/VBA/DateTime/DatePart) 函数 --- --- url: /en/official/Reference/VB/HScrollBar.md --- # HScrollBar class An **HScrollBar** is a Win32 native horizontal scroll bar exposed as a stand-alone control. Unlike the scroll bars that automatically appear inside a [**ListBox**](/en/official/Reference/VB/ListBox/), [**ComboBox**](/en/official/Reference/VB/ComboBox/), or [**TextBox**](/en/official/Reference/VB/TextBox/), an **HScrollBar** is independent of any other control --- its [**Value**](#value) is whatever code reads or writes. The typical use is to control a numeric setting (a volume level, a paginator, a colour channel, the offset of a custom-drawn surface) by binding the **HScrollBar**'s [**Change**](#change) and [**Scroll**](#scroll) events to whatever the value represents. [**VScrollBar**](/en/official/Reference/VB/VScrollBar/) is the vertical counterpart; the two classes are identical apart from orientation. The default property is [**Value**](#value) and the default event is [**Change**](#change). ```vb Private Sub Form_Load() hsbVolume.Min = 0 hsbVolume.Max = 100 hsbVolume.SmallChange = 1 hsbVolume.LargeChange = 10 hsbVolume.Value = 50 End Sub Private Sub hsbVolume_Change() lblVolume.Caption = "Volume: " & hsbVolume.Value & "%" End Sub Private Sub hsbVolume_Scroll() lblVolume.Caption = "Volume: " & hsbVolume.Value & "%" ' live update during drag End Sub ``` ## Range and value [**Min**](#min) and [**Max**](#max) define the closed range of integer values the scroll bar can represent, and [**Value**](#value) is the position within that range. Defaults are `0`, `32767`, and `0`. Assigning a [**Value**](#value) outside the current `[Min, Max]` interval raises run-time error 380 (*Invalid property value*); assigning the current value is a no-op (no [**Change**](#change) is raised). The two endpoints may be supplied in either order. When **Min** is greater than **Max** the scroll bar runs *inverted* --- moving the thumb to the right decreases [**Value**](#value), and **Max** is the lower bound of the legal range. This is convenient for, for example, a "high-on-the-left" colour or zoom slider: ```vb hsbZoom.Min = 400 ' leftmost == 4.00x hsbZoom.Max = 100 ' rightmost == 1.00x hsbZoom.Value = 100 ``` Changing **Min** or **Max** at run time clips the current [**Value**](#value) into the new range silently --- no [**Change**](#change) event is raised for the implicit clip. ## Increment sizes The scroll bar produces value changes through four kinds of user input: | Input | Increment per step | Event raised | |-------------------------------------|------------------------------|------------------| | Click an end-arrow | [**SmallChange**](#smallchange) | [**Change**](#change) | | Click the track on either side of the thumb | [**LargeChange**](#largechange) | [**Change**](#change) | | Drag the thumb | continuous | [**Scroll**](#scroll) during drag, [**Change**](#change) on release | | Press **Home** / **End** | jumps to **Min** / **Max** | [**Change**](#change) | Both [**SmallChange**](#smallchange) and [**LargeChange**](#largechange) default to `1`. [**LargeChange**](#largechange) also controls the visible width of the thumb relative to the track, so larger values produce a chunkier thumb. ## Change versus Scroll The split between the two events lets the application choose how often it reacts to user input. [**Scroll**](#scroll) fires repeatedly while the user is dragging the thumb, so a handler can update a live preview as the thumb moves. [**Change**](#change) fires once each time the value settles --- after the user releases the thumb, after a click on an arrow or the track, or whenever code assigns a different [**Value**](#value). Many applications wire both events to the same handler so that the bound display updates both during dragging and after. ## Properties ### Anchors The set of edges of the parent that the scroll bar's corresponding edges follow when the parent resizes. Read-only --- assign individual `.Left`, `.Top`, `.Right`, `.Bottom` flags through the returned **Anchors** object. ### CausesValidation Determines whether the previously focused control's [**Validate**](#validate) event runs before this control receives the focus. **Boolean**, default **True**. ### Container The control that hosts this scroll bar --- typically the form, a [**Frame**](/en/official/Reference/VB/Frame/), or a **UserControl**. Read with **Get**, change with **Set**. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a horizontal scroll bar. Always **vbHScrollBar**. ### Dock Where the scroll bar is docked within its container. A member of [**DockModeConstants**](/en/official/Reference/VBRUN/Constants/DockModeConstants): **vbDockNone** (default), **vbDockLeft**, **vbDockTop**, **vbDockRight**, **vbDockBottom**, or **vbDockFill**. Docked scroll bars ignore [**Anchors**](#anchors). ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the scroll bar accepts user input. A disabled scroll bar is greyed out and does not respond to mouse or keyboard interaction. **Boolean**, default **True**. ### Height The scroll bar's height in twips (or in the container's **ScaleMode** units). **Double**. For a horizontal scroll bar this is the small dimension --- typically the OS standard scroll-bar thickness; values larger than that simply enlarge the surrounding hit area. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the control has focus. ### hWnd The Win32 window handle for the underlying scroll bar, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the scroll bar is part of a control array, the **Long** zero-based index of this instance within the array. Reading **Index** on a non-array instance raises run-time error 343 (*Object not an array*). Read-only at run time. ### LargeChange The amount [**Value**](#value) is adjusted when the user clicks the track on either side of the thumb (or presses **Page Up** / **Page Down** while the scroll bar has focus). **Long**, default `1`. Also influences the visible width of the thumb: bigger values produce a wider thumb relative to the track. ### Left The horizontal distance from the left edge of the container to the left edge of the scroll bar. **Double**. ### Max The upper end of the scroll bar's value range. **Long**, default `32767`. May be set lower than [**Min**](#min) to invert the direction of travel --- see [Range and value](#range-and-value). Syntax: *object*.**Max** \[ = *value* ] Changing **Max** clips the current [**Value**](#value) into the new range silently if it now falls outside. ### Min The lower end of the scroll bar's value range. **Long**, default `0`. May be set higher than [**Max**](#max) to invert the direction of travel. Syntax: *object*.**Min** \[ = *value* ] Changing **Min** clips the current [**Value**](#value) into the new range silently if it now falls outside. ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### Opacity The control's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Requires Windows 8 or later for child controls. ### Parent A reference to the [**Form**](/en/official/Reference/VB/Form/) (or **UserControl**) that ultimately contains this scroll bar. Read-only. ### RightToLeft ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. To run the scroll bar in reverse, swap [**Min**](#min) and [**Max**](#max). ::: ### SmallChange The amount [**Value**](#value) is adjusted when the user clicks one of the end-arrows (or presses an arrow key while the scroll bar has focus). **Long**, default `1`. ### TabIndex The position of the control in the form's TAB-key navigation order. **Long**. ### TabStop Whether the user can reach the control by pressing the **TAB** key. **Boolean**, default **True**. A disabled control is skipped regardless of this setting. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### Top The vertical distance from the top of the container to the top of the scroll bar. **Double**. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered control. Default `-1` disables the effect. Requires Windows 8 or later for child controls. ### Value The scroll bar's current position within `[Min, Max]`. **Long**, default `0`. **Default property.** Syntax: *object*.**Value** \[ = *value* ] *value* : A **Long** in the closed interval `[Min, Max]` (or `[Max, Min]` for an inverted scroll bar). Values outside that interval raise run-time error 380 (*Invalid property value*). Assigning a value that differs from the current one moves the thumb and raises a single [**Change**](#change) event. Assigning the current value is a silent no-op. ### Visible Whether the scroll bar is shown. **Boolean**, default **True**. ### VisualStyles Whether the OS theme engine should be used when drawing the scroll bar. **Boolean**, default **True**. ### WhatsThisHelpID A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### Width The scroll bar's width --- i.e., the length of the track. **Double**. ## Methods ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Typically called from code when [**DragMode**](#dragmode) is **vbManual**. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the scroll bar in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### Refresh Forces an immediate repaint of the scroll bar. Syntax: *object*.**Refresh** ### SetFocus Moves the input focus to the scroll bar. The control must be both [**Visible**](#visible) and [**Enabled**](#enabled), or run-time error 5 (*Invalid procedure call or argument*) is raised. Syntax: *object*.**SetFocus** ### ShowWhatsThis Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### SyncScrollBar Re-applies the current [**Min**](#min), [**Max**](#max), [**LargeChange**](#largechange), and [**Value**](#value) to the underlying Win32 scroll bar. Property assignments already do this implicitly --- call **SyncScrollBar** only when external code (typically a Win32 API call) has reached around the control and changed its native state. Syntax: *object*.**SyncScrollBar** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Change Raised after [**Value**](#value) settles on a new value --- when the user releases the thumb after a drag, when the user clicks an arrow or the track, when the user presses **Home**, **End**, or an arrow key with focus on the scroll bar, or when code assigns a different [**Value**](#value). Not raised for the continuous updates that happen during a drag --- see [**Scroll**](#scroll) for that. **Default event.** Syntax: *object*\_**Change**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus Raised when the scroll bar receives the input focus. Syntax: *object*\_**GotFocus**( ) ### Initialize Raised once, after the underlying window has been created and the scroll bar is connected to its Win32 range, but before the scroll bar is first painted. Useful for last-minute setup that needs the underlying handle. Syntax: *object*\_**Initialize**( ) ### KeyDown Raised when the user presses any key while the control has focus. Note that the scroll bar already handles the arrow keys, **Page Up** / **Page Down**, and **Home** / **End** internally --- but **KeyDown** still fires for them in addition to the resulting [**Change**](#change). Syntax: *object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress Raised when the user types a character that produces an ANSI keystroke. Syntax: *object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp Raised when the user releases a key while the control has focus. Syntax: *object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus Raised when the scroll bar loses the input focus. Syntax: *object*\_**LostFocus**( ) ### Scroll Raised continuously while the user is dragging the thumb, once for each tick that produces a different [**Value**](#value). After the user releases the thumb, a single [**Change**](#change) event fires with the final value. **Scroll** is the right event for a live preview while the thumb is moving; [**Change**](#change) fires only the final value. Syntax: *object*\_**Scroll**( ) ### Validate Raised when the focus is moving to another control whose [**CausesValidation**](#causesvalidation) is **True**. Setting *Cancel* to **True** keeps the focus on this control. Syntax: *object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /zh/official/Reference/VB/HScrollBar.md --- # HScrollBar 类 **HScrollBar**是作为独立控件公开的Win32原生水平滚动条。与自动出现在[**ListBox**](/official/Reference/VB/ListBox/)、[**ComboBox**](/official/Reference/VB/ComboBox/)或[**TextBox**](/official/Reference/VB/TextBox/)内部的滚动条不同,**HScrollBar**独立于任何其他控件——其[**Value**](#value)由代码读写。典型用途是通过将**HScrollBar**的[**Change**](#change)和[**Scroll**](#scroll)事件绑定到值所代表的含义来控制数值设置(音量级别、分页器、颜色通道、自定义绘制表面的偏移量)。 [**VScrollBar**](/official/Reference/VB/VScrollBar/)是垂直对应物;两个类除了方向外完全相同。 默认属性是[**Value**](#value),默认事件是[**Change**](#change)。 ```vb Private Sub Form_Load() hsbVolume.Min = 0 hsbVolume.Max = 100 hsbVolume.SmallChange = 1 hsbVolume.LargeChange = 10 hsbVolume.Value = 50 End Sub Private Sub hsbVolume_Change() lblVolume.Caption = "Volume: " & hsbVolume.Value & "%" End Sub Private Sub hsbVolume_Scroll() lblVolume.Caption = "Volume: " & hsbVolume.Value & "%" ' live update during drag End Sub ``` ## 范围和值 [**Min**](#min)和[**Max**](#max)定义滚动条可以表示的整数闭区间,[**Value**](#value)是该范围内的位置。默认值分别为`0`、`32767`和`0`。赋值超出当前`[Min, Max]`区间的[**Value**](#value)会引发运行时错误380(*无效属性值*);赋值当前值是无操作(不引发[**Change**](#change))。 两个端点可以以任意顺序提供。当**Min**大于**Max**时,滚动条*反向*运行——将滑块向右移动会减小[**Value**](#value),**Max**是合法范围的下界。这便于实现例如"左侧为高值"的颜色或缩放滑块: ```vb hsbZoom.Min = 400 ' leftmost == 4.00x hsbZoom.Max = 100 ' rightmost == 1.00x hsbZoom.Value = 100 ``` 在运行时更改**Min**或**Max**会静默地将当前[**Value**](#value)钳制到新范围内——不会为隐式钳制引发[**Change**](#change)事件。 ## 增量大小 滚动条通过四种用户输入产生值变化: | 输入 | 每步增量 | 引发的事件 | |--------------------------------------|------------------------------|------------------| | 点击末端箭头 | [**SmallChange**](#smallchange) | [**Change**](#change) | | 点击滑块两侧的轨道 | [**LargeChange**](#largechange) | [**Change**](#change) | | 拖动滑块 | 连续 | 拖动时[**Scroll**](#scroll),释放时[**Change**](#change) | | 按**Home** / **End** | 跳到**Min** / **Max** | [**Change**](#change) | [**SmallChange**](#smallchange)和[**LargeChange**](#largechange)默认均为`1`。[**LargeChange**](#largechange)还控制滑块相对于轨道的可见宽度,因此更大的值会产生更宽的滑块。 ## Change 与 Scroll 的区别 两个事件的分工让应用程序可以选择对用户输入的响应频率。[**Scroll**](#scroll)在用户拖动滑块时反复触发,因此处理程序可以在滑块移动时更新实时预览。[**Change**](#change)在值稳定后触发一次——用户释放滑块后、点击箭头或轨道后,或代码赋值不同的[**Value**](#value)时。许多应用程序将两个事件连接到同一处理程序,以便绑定显示在拖动期间和之后都更新。 ## 属性 ### Anchors 决定滚动条的哪些边随父级对应边调整的边集合。只读——通过返回的**Anchors**对象设置各个`.Left`、`.Top`、`.Right`、`.Bottom`标志。 ### CausesValidation 决定先前聚焦控件的[**Validate**](#validate)事件是否在此控件获得焦点之前运行。**Boolean**,默认**True**。 ### Container 承载此滚动条的控件——通常是窗体、[**Frame**](/official/Reference/VB/Frame/)或**UserControl**。用**Get**读取,用**Set**更改。 ### ControlType 标识此控件为水平滚动条的只读[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值。始终为**vbHScrollBar**。 ### Dock 滚动条在其容器中的停靠位置。[**DockModeConstants**](/official/Reference/VBRUN/Constants/DockModeConstants)的成员:**vbDockNone**(默认)、**vbDockLeft**、**vbDockTop**、**vbDockRight**、**vbDockBottom**或**vbDockFill**。停靠的滚动条忽略[**Anchors**](#anchors)。 ### DragIcon 在控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自行拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual**(0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic**(1)。 ### Enabled 决定滚动条是否接受用户输入。禁用的滚动条变灰,不响应鼠标或键盘交互。**Boolean**,默认**True**。 ### Height 滚动条的高度,以缇为单位(或以容器的**ScaleMode**单位)。**Double**。对于水平滚动条这是短边——通常为操作系统标准滚动条厚度;大于该值的只会扩大周围的点击区域。 ### HelpContextID 标识应用程序帮助文件中主题的**Long**,当用户在控件有焦点时按**F1**时检索。 ### hWnd 底层滚动条的Win32窗口句柄,作为**LongPtr**。只读。适用于传递给API函数。 ### Index 当滚动条是控件数组的一部分时,此实例在数组中的**Long**零基索引。在非数组实例上读取**Index**会引发运行时错误343(*对象不是数组*)。运行时只读。 ### LargeChange 当用户点击滑块两侧的轨道(或在滚动条有焦点时按**Page Up** / **Page Down**)时[**Value**](#value)的调整量。**Long**,默认`1`。还影响滑块的可见宽度:更大的值在轨道上产生更宽的滑块。 ### Left 从容器左边缘到滚动条左边缘的水平距离。**Double**。 ### Max 滚动条值范围的上端。**Long**,默认`32767`。可以设置得低于[**Min**](#min)以反转移动方向——参见[范围和值](#range-and-value)。 语法:*object*.**Max** \[ = *value* ] 更改**Max**会在当前[**Value**](#value)超出新范围时静默钳制。 ### Min 滚动条值范围的下端。**Long**,默认`0`。可以设置得高于[**Max**](#max)以反转移动方向。 语法:*object*.**Min** \[ = *value* ] 更改**Min**会在当前[**Value**](#value)超出新范围时静默钳制。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针在控件上方时用作鼠标光标的**StdPicture**。 ### MousePointer 指针在控件上方时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### Opacity 控件的不透明度百分比(0--100,默认100)。超出范围的值在**Initialize**时被钳制。子控件需要Windows 8或更高版本。 ### Parent 对最终包含此滚动条的[**Form**](/official/Reference/VB/Form/)(或**UserControl**)的引用。只读。 ### RightToLeft ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。要以反向运行滚动条,交换[**Min**](#min)和[**Max**](#max)。 ::: ### SmallChange 当用户点击末端箭头(或在滚动条有焦点时按箭头键)时[**Value**](#value)的调整量。**Long**,默认`1`。 ### TabIndex 控件在窗体TAB键导航顺序中的位置。**Long**。 ### TabStop 用户是否可以通过按**TAB**键到达控件。**Boolean**,默认**True**。禁用的控件无论此设置如何都会被跳过。 ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### Top 从容器顶部到滚动条顶部的垂直距离。**Double**。 ### TransparencyKey 设置后成为渲染控件中完全透明的**OLE\_COLOR**。默认`-1`禁用效果。子控件需要Windows 8或更高版本。 ### Value 滚动条在`[Min, Max]`内的当前位置。**Long**,默认`0`。**默认属性。** 语法:*object*.**Value** \[ = *value* ] *value* : 闭区间`[Min, Max]`(或反向滚动条的`[Max, Min]`)中的**Long**。超出该区间的值引发运行时错误380(*无效属性值*)。 赋值与当前值不同的值会移动滑块并引发单个[**Change**](#change)事件。赋值当前值为静默无操作。 ### Visible 滚动条是否显示。**Boolean**,默认**True**。 ### VisualStyles 绘制滚动条时是否使用操作系统主题引擎。**Boolean**,默认**True**。 ### WhatsThisHelpID 标识应用程序帮助文件中"这是什么?"帮助弹出主题的**Long**。参见[**ShowWhatsThis**](#showwhatsthis)。 ### Width 滚动条的宽度——即轨道的长度。**Double**。 ## 方法 ### Drag 开始、完成或取消手动拖放操作。通常在[**DragMode**](#dragmode)为**vbManual**时从代码调用。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel**(0)、**vbBeginDrag**(1,默认)或**vbEndDrag**(2)。 ### Move 在单次调用中重新定位并可选地调整滚动条的尺寸。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### Refresh 强制立即重绘滚动条。 语法:*object*.**Refresh** ### SetFocus 将输入焦点移到滚动条。控件必须同时[**Visible**](#visible)和[**Enabled**](#enabled),否则引发运行时错误5(*无效的过程调用或参数*)。 语法:*object*.**SetFocus** ### ShowWhatsThis 以"这是什么?"弹窗形式显示由[**WhatsThisHelpID**](#whatsthishelpid)标识的主题。 语法:*object*.**ShowWhatsThis** ### SyncScrollBar 将当前[**Min**](#min)、[**Max**](#max)、[**LargeChange**](#largechange)和[**Value**](#value)重新应用到底层Win32滚动条。属性赋值已隐式执行此操作——仅当外部代码(通常是Win32 API调用)绕过控件更改了其原生状态时才调用**SyncScrollBar**。 语法:*object*.**SyncScrollBar** ### ZOrder 将控件带到同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront**(0,默认)或**vbSendToBack**(1)。 ## 事件 ### Change 在[**Value**](#value)稳定到新值后引发——用户在拖动后释放滑块时、点击箭头或轨道时、在滚动条有焦点时按**Home**、**End**或箭头键时,或代码赋值不同的[**Value**](#value)时。不会在拖动期间的连续更新时引发——参见[**Scroll**](#scroll)。**默认事件。** 语法:*object*\_**Change**( ) ### DragDrop 当手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 当手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus 当滚动条获得输入焦点时引发。 语法:*object*\_**GotFocus**( ) ### Initialize 在底层窗口已创建且滚动条已连接到其Win32范围后,但滚动条首次绘制之前引发一次。适用于需要底层句柄的最后一刻设置。 语法:*object*\_**Initialize**( ) ### KeyDown 当控件有焦点时用户按下任意键时引发。注意滚动条已在内部处理箭头键、**Page Up** / **Page Down**和**Home** / **End**——但**KeyDown**仍然会为它们触发,除产生[**Change**](#change)外。 语法:*object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress 当用户输入产生ANSI按键的字符时引发。 语法:*object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp 当控件有焦点时用户释放键时引发。 语法:*object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus 当滚动条失去输入焦点时引发。 语法:*object*\_**LostFocus**( ) ### Scroll 在用户拖动滑块期间连续引发,每产生一个不同的[**Value**](#value)一次。用户释放滑块后,会引发单个[**Change**](#change)事件携带最终值。**Scroll**是滑块移动时实时预览的正确事件;[**Change**](#change)仅触发最终值。 语法:*object*\_**Scroll**( ) ### Validate 当焦点移动到[**CausesValidation**](#causesvalidation)为**True**的另一个控件时引发。将*Cancel*设为**True**使焦点保留在此控件上。 语法:*object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /en/official/Reference/tbIDE/HtmlElement.md --- # HtmlElement class One DOM element inside a tool window --- every node in the rendered HTML tree is reachable as an **HtmlElement**, starting from [**ToolWindow.RootDomElement**](/en/official/Reference/tbIDE/ToolWindow#rootdomelement) and traversing down through [**ChildDomElements**](#childdomelements). Inline overlays inside a code pane (created with [**CodeEditor.AddMonacoWidget**](/en/official/Reference/tbIDE/CodeEditor#addmonacowidget)) also appear as **HtmlElement** instances and behave identically. ```vb With myToolWindow.RootDomElement.ChildDomElements.Add("greeting", "h1") With .Properties .style.textAlign = "center" .style.color = "white" .innerText = "Hello, world!" End With End With ``` The element's *properties* --- every CSS-style property, every DOM attribute, every custom-widget extension --- live inside the [**Properties**](#properties) bag, accessed through a dynamic resolution mechanism. See [Dynamic DOM property resolution](/en/official/Reference/tbIDE/#dynamic-dom-property-resolution) on the package overview for the underlying mechanism that makes `.style.textAlign = "center"` work without a statically-declared `style` member. ## Properties ### ChildDomElements The element's child-element collection. Call [**HtmlElements.Add**](/en/official/Reference/tbIDE/HtmlElements#add) to add new children, [**Item**](/en/official/Reference/tbIDE/HtmlElements#item) to look one up by ID. **As** [**HtmlElements**](/en/official/Reference/tbIDE/HtmlElements). Read-only. ### Name The unique ID assigned to the element when it was created via [**HtmlElements.Add**](/en/official/Reference/tbIDE/HtmlElements#add). **String**, read-only. ### Properties The element's dynamic property bag --- every DOM property, every CSS-style property, every custom-widget extension lives here. **As** [**HtmlElementProperties**](/en/official/Reference/tbIDE/HtmlElementProperties). **DefaultMember** --- so `element.<name>` is equivalent to `element.Properties.<name>`. The bag is [`[COMExtensible(True)]`](/en/official/Reference/tbIDE/#dynamic-dom-property-resolution): property names are resolved against the DOM element at run time, so the accepted set is everything the underlying tag supports --- refer to MDN for standard DOM properties, and to the custom-widget documentation (Chart.js, Monaco, …) for the widget-specific properties. ## Methods ### AddEventListener Registers a callback to be invoked when a DOM event fires on the element. Syntax: *element*.**AddEventListener** *DomEventName*, *CallbackFunc* \[, *Data* ] *DomEventName* : *required* The DOM event name. **String**. Standard names (`"click"`, `"keyup"`, `"input"`, `"change"`, `"mouseenter"`, …) and custom event names raised by inline HTML (see below) both work. *CallbackFunc* : *required* The callback. Pass `AddressOf` a sub of signature `Sub(ByVal eventInfo As HtmlEventProperties)`. **LongPtr**. *Data* : *optional* An opaque value to associate with the registration. **Variant**. ```vb With .ChildDomElements.Add("myButton", "div") .Properties.innerText = "Click me" .AddEventListener("click", AddressOf MyButtonClicked) End With ' … Private Sub MyButtonClicked(ByVal eventInfo As HtmlEventProperties) Host.DebugConsole.PrintText "clicked: " & eventInfo.target.id End Sub ``` ::: warning For the four custom-widget tags (`"chartjs"`, `"monaco"`, `"listview"`, `"virtuallistview"`), the widget-specific events (e.g. Monaco's `onDidChangeModelContent`, the listview's `onClickItem`) are registered on the **widget object**, not on the DOM element. So: ```vb ' WRONG --- listener is never reached: monacoDivElement.AddEventListener("onDidChangeModelContent", AddressOf Handler) ' CORRECT --- register on .editor (or .listview / .chart for the other widgets): monacoDivElement.Properties.editor.AddEventListener("onDidChangeModelContent", AddressOf Handler) ``` Standard DOM events (`"click"`, `"keyup"`, …) still attach directly to the DOM element through this method. ::: #### Custom event names from inline HTML Inline HTML rendered inside a tool window can raise arbitrary event names back to the addin through the IDE-side `raiseEvent()` JavaScript helper. The function signature on the JavaScript side is: ```js raiseEvent(eventName, event, stopPropagation, ...customData); ``` \--- pass an event name (any string), the DOM `event` object, a boolean controlling propagation, and any number of trailing custom-data values. The addin then registers a listener with the same event name through **AddEventListener**, and the custom-data values arrive on the [**HtmlEventProperties**](/en/official/Reference/tbIDE/HtmlEventProperties) as `eventInfo.customData0`, `eventInfo.customData1`, … (numerically indexed from zero). This pattern is used heavily in sample 13 (listview) and sample 15 (Global Search) to attach handlers to per-item buttons rendered inside a listview's HTML. ### Remove Removes the element from the DOM. Any child elements are removed with it. Any event listeners registered on this element are released. Syntax: *element*.**Remove** --- --- url: /zh/official/Reference/tbIDE/HtmlElement.md --- # HtmlElement 类 工具窗口内的一个 DOM 元素——渲染 HTML 树中的每个节点都可以作为 **HtmlElement** 访问,从 [**ToolWindow.RootDomElement**](/official/Reference/tbIDE/ToolWindow#rootdomelement) 开始,通过 [**ChildDomElements**](#childdomelements) 向下遍历。代码窗格内的行内覆盖层(通过 [**CodeEditor.AddMonacoWidget**](/official/Reference/tbIDE/CodeEditor#addmonacowidget) 创建)也显示为 **HtmlElement** 实例,行为相同。 ```vb With myToolWindow.RootDomElement.ChildDomElements.Add("greeting", "h1") With .Properties .style.textAlign = "center" .style.color = "white" .innerText = "Hello, world!" End With End With ``` 元素的*属性*——每个 CSS 样式属性、每个 DOM 属性、每个自定义控件扩展——都存在于 [**Properties**](#properties) 包中,通过动态解析机制访问。参见包概述中的[动态 DOM 属性解析](/official/Reference/tbIDE/#动态-dom-属性解析),了解使 `.style.textAlign = "center"` 在没有静态声明 `style` 成员的情况下工作的底层机制。 ## 属性 ### ChildDomElements 元素的子元素集合。调用 [**HtmlElements.Add**](/official/Reference/tbIDE/HtmlElements#add) 添加新子元素,[**Item**](/official/Reference/tbIDE/HtmlElements#item) 按 ID 查找。**As** [**HtmlElements**](/official/Reference/tbIDE/HtmlElements)。只读。 ### Name 通过 [**HtmlElements.Add**](/official/Reference/tbIDE/HtmlElements#add) 创建元素时分配的唯一 ID。**String**,只读。 ### Properties 元素的动态属性包——每个 DOM 属性、每个 CSS 样式属性、每个自定义控件扩展都存在于这里。**As** [**HtmlElementProperties**](/official/Reference/tbIDE/HtmlElementProperties)。**DefaultMember**——因此 `element.<name>` 等同于 `element.Properties.<name>`。 该包是 [`[COMExtensible(True)]`](/official/Reference/tbIDE/#动态-dom-属性解析):属性名在运行时根据 DOM 元素解析,因此可接受的属性集是底层标签支持的所有内容——标准 DOM 属性请参阅 MDN,控件特有属性请参阅自定义控件文档(Chart.js、Monaco 等)。 ## 方法 ### AddEventListener 注册一个在元素上触发 DOM 事件时调用的回调。 语法:*element*.**AddEventListener** *DomEventName*, *CallbackFunc* \[, *Data* ] *DomEventName* : *必需* DOM 事件名称。**String**。标准名称(`"click"`、`"keyup"`、`"input"`、`"change"`、`"mouseenter"` 等)和行内 HTML 触发的自定义事件名称(见下文)均可。 *CallbackFunc* : *必需* 回调。传入签名为 `Sub(ByVal eventInfo As HtmlEventProperties)` 的子过程的 `AddressOf`。**LongPtr**。 *Data* : *可选* 与注册关联的不透明值。**Variant**。 ```vb With .ChildDomElements.Add("myButton", "div") .Properties.innerText = "Click me" .AddEventListener("click", AddressOf MyButtonClicked) End With ' … Private Sub MyButtonClicked(ByVal eventInfo As HtmlEventProperties) Host.DebugConsole.PrintText "clicked: " & eventInfo.target.id End Sub ``` ::: warning 对于四个自定义控件标签(`"chartjs"`、`"monaco"`、`"listview"`、`"virtuallistview"`),控件特有的事件(例如 Monaco 的 `onDidChangeModelContent`、列表视图的 `onClickItem`)注册在**控件对象**上,而非 DOM 元素上。因此: ```vb ' 错误——监听器永远不会被触发: monacoDivElement.AddEventListener("onDidChangeModelContent", AddressOf Handler) ' 正确——在 .editor(或其他控件的 .listview / .chart)上注册: monacoDivElement.Properties.editor.AddEventListener("onDidChangeModelContent", AddressOf Handler) ``` 标准 DOM 事件(`"click"`、`"keyup"` 等)仍然通过此方法直接附加到 DOM 元素。 ::: #### 行内 HTML 的自定义事件名称 工具窗口内渲染的行内 HTML 可以通过 IDE 端的 `raiseEvent()` JavaScript 辅助函数向插件触发任意事件名称。JavaScript 端的函数签名为: ```js raiseEvent(eventName, event, stopPropagation, ...customData); ``` ——传入事件名称(任意字符串)、DOM `event` 对象、控制传播的布尔值,以及任意数量的尾部自定义数据值。然后插件通过 **AddEventListener** 以相同事件名注册监听器,自定义数据值到达 [**HtmlEventProperties**](/official/Reference/tbIDE/HtmlEventProperties) 时为 `eventInfo.customData0`、`eventInfo.customData1` 等(从零开始数字索引)。此模式在示例 13(列表视图)和示例 15(全局搜索)中被大量使用,以将处理程序附加到列表视图 HTML 内渲染的逐项按钮。 ### Remove 从 DOM 中移除元素。任何子元素随之移除。在此元素上注册的任何事件监听器被释放。 语法:*element*.**Remove** --- --- url: /en/official/Reference/tbIDE/HtmlElementProperties.md --- # HtmlElementProperties class The dynamic property bag on an [**HtmlElement**](/en/official/Reference/tbIDE/HtmlElement). Reached through [**HtmlElement.Properties**](/en/official/Reference/tbIDE/HtmlElement#properties). Every CSS property, every DOM attribute, every custom-widget extension is accessed through this bag --- and almost always written in shorthand because [**Properties**](/en/official/Reference/tbIDE/HtmlElement#properties) is the **DefaultMember** of [**HtmlElement**](/en/official/Reference/tbIDE/HtmlElement): ```vb With element ' element.Properties is the default member .style.display = "flex" ' Properties.Item("style").Item("display").Value = "flex" .style.flexDirection = "column" .style.gap = "10px" .innerText = "Hello" End With ``` The shorthand reads at run time as a chain of `Item("name")` lookups against the underlying DOM element --- see [Dynamic DOM property resolution](/en/official/Reference/tbIDE/#dynamic-dom-property-resolution) on the package overview. ::: warning This interface is **`[COMExtensible(True)]`**. Property names are resolved against the live DOM element at run time, not declared statically on the interface. The compiler does not validate names --- a typo (`.innerTxt = "..."` instead of `.innerText = "..."`) fails silently or throws at run time. The accepted set is **every DOM property of the underlying tag**, plus any custom-widget extensions; the reference does not enumerate it. ::: ## Default member The interface's **DefaultMember** is [**Item**](#item) --- so `properties("style")` is equivalent to `properties.Item("style")`. Chains of `.style.color = "red"` thus desugar to `properties.Item("style").Item("color").Value = "red"`. ## Properties ### Item Looks up a property by name. Returns an [**HtmlElementProperty**](/en/official/Reference/tbIDE/HtmlElementProperty), which includes the property's value plus a nested [**Properties**](/en/official/Reference/tbIDE/HtmlElementProperty#properties) for further drill-down. Syntax: *properties*( *DomPropertyName* ) **As** [**HtmlElementProperty**](/en/official/Reference/tbIDE/HtmlElementProperty) *DomPropertyName* : *required* The property name. **String**. Standard DOM property names, CSS-style property names (when looked up under `style`), or custom-widget property names --- all forwarded to the IDE's tool-window renderer. --- --- url: /zh/official/Reference/tbIDE/HtmlElementProperties.md --- # HtmlElementProperties 类 [**HtmlElement**](/official/Reference/tbIDE/HtmlElement) 上的动态属性包。通过 [**HtmlElement.Properties**](/official/Reference/tbIDE/HtmlElement#properties) 访问。每个 CSS 属性、每个 DOM 属性、每个自定义控件扩展都通过此包访问——而且几乎总是以简写形式书写,因为 [**Properties**](/official/Reference/tbIDE/HtmlElement#properties) 是 [**HtmlElement**](/official/Reference/tbIDE/HtmlElement) 的 **DefaultMember**: ```vb With element ' element.Properties 是默认成员 .style.display = "flex" ' Properties.Item("style").Item("display").Value = "flex" .style.flexDirection = "column" .style.gap = "10px" .innerText = "Hello" End With ``` 简写在运行时解析为针对底层 DOM 元素的 `Item("name")` 查找链——参见包概述中的[动态 DOM 属性解析](/official/Reference/tbIDE/#动态-dom-属性解析)。 ::: warning 此接口是 **`[COMExtensible(True)]`**。属性名在运行时根据活动 DOM 元素解析,而非在接口上静态声明。编译器不验证名称——拼写错误(例如 `.innerTxt = "..."` 而非 `.innerText = "..."`)会静默失败或在运行时抛出异常。可接受的属性集是**底层标签的每个 DOM 属性**,加上任何自定义控件扩展;参考文档不逐一列举。 ::: ## 默认成员 接口的 **DefaultMember** 是 [**Item**](#item)——因此 `properties("style")` 等同于 `properties.Item("style")`。`.style.color = "red"` 链因此脱糖为 `properties.Item("style").Item("color").Value = "red"`。 ## 属性 ### Item 按名称查找属性。返回一个 [**HtmlElementProperty**](/official/Reference/tbIDE/HtmlElementProperty),其中包含属性的值加上用于进一步下钻的嵌套 [**Properties**](/official/Reference/tbIDE/HtmlElementProperty#properties)。 语法:*properties*( *DomPropertyName* ) **As** [**HtmlElementProperty**](/official/Reference/tbIDE/HtmlElementProperty) *DomPropertyName* : *必需* 属性名称。**String**。标准 DOM 属性名、CSS 样式属性名(在 `style` 下查找时)或自定义控件属性名——全部转发到 IDE 的工具窗口渲染器。 --- --- url: /en/official/Reference/tbIDE/HtmlElementProperty.md --- # HtmlElementProperty class One settable property on an [**HtmlElement**](/en/official/Reference/tbIDE/HtmlElement) --- returned by [**HtmlElementProperties.Item**](/en/official/Reference/tbIDE/HtmlElementProperties#item). Carries the property's [**Value**](#value) plus a [**Properties**](#properties) accessor that lets the addin drill into nested DOM property structures (`.style.color`, `.chart.data.datasets(0).borderWidth`, …). Almost always written in shorthand --- neither **HtmlElementProperty** nor its parent [**HtmlElementProperties**](/en/official/Reference/tbIDE/HtmlElementProperties) is typically named in addin code; the compiler resolves chains like `.style.color = "red"` through their default-members: ```vb element.style.color = "red" ' ↑ HtmlElement.Properties (HtmlElement's DefaultMember) ' .Item("style") (HtmlElementProperties' DefaultMember) ' .Properties (HtmlElementProperty.Properties — nested bag) ' .Item("color") (the same DefaultMember chain again) ' .Value = "red" (HtmlElementProperty.Value, the leaf) ``` ## Properties ### Properties A nested [**HtmlElementProperties**](/en/official/Reference/tbIDE/HtmlElementProperties) for properties that themselves have sub-properties (the canonical example is `style`, whose sub-properties are the individual CSS-style names). Read-only at the accessor level; the inner bag is mutable. Syntax: *property*.**Properties** **As** [**HtmlElementProperties**](/en/official/Reference/tbIDE/HtmlElementProperties) ### Value The property's value. Read returns the current value as a **Variant**; assigning writes the new value back. **DefaultMember** --- so `propertyObj = "red"` is equivalent to `propertyObj.Value = "red"`. Syntax: *property* \[ = *value* ] The interface is **`[COMExtensible(True)]`** --- see [Dynamic DOM property resolution](/en/official/Reference/tbIDE/#dynamic-dom-property-resolution) on the package overview. Property names that route through [**Properties**](#properties) are resolved against the live DOM at run time, not declared statically. --- --- url: /zh/official/Reference/tbIDE/HtmlElementProperty.md --- # HtmlElementProperty 类 [**HtmlElement**](/official/Reference/tbIDE/HtmlElement) 上的一个可设置属性——由 [**HtmlElementProperties.Item**](/official/Reference/tbIDE/HtmlElementProperties#item) 返回。包含属性的 [**Value**](#value) 加上一个 [**Properties**](#properties) 访问器,使插件能够下钻到嵌套的 DOM 属性结构(`.style.color`、`.chart.data.datasets(0).borderWidth` 等)。 几乎总是以简写形式书写——**HtmlElementProperty** 及其父类 [**HtmlElementProperties**](/official/Reference/tbIDE/HtmlElementProperties) 通常不会在插件代码中被显式命名;编译器通过它们的默认成员解析 `.style.color = "red"` 等链: ```vb element.style.color = "red" ' ↑ HtmlElement.Properties (HtmlElement 的 DefaultMember) ' .Item("style") (HtmlElementProperties 的 DefaultMember) ' .Properties (HtmlElementProperty.Properties — 嵌套包) ' .Item("color") (同样的 DefaultMember 链) ' .Value = "red" (HtmlElementProperty.Value,叶子节点) ``` ## 属性 ### Properties 一个嵌套的 [**HtmlElementProperties**](/official/Reference/tbIDE/HtmlElementProperties),用于本身具有子属性的属性(典型例子是 `style`,其子属性是各个 CSS 样式名称)。在访问器层面只读;内部包可变。 语法:*property*.**Properties** **As** [**HtmlElementProperties**](/official/Reference/tbIDE/HtmlElementProperties) ### Value 属性的值。读取时将当前值作为 **Variant** 返回;赋值时写入新值。**DefaultMember**——因此 `propertyObj = "red"` 等同于 `propertyObj.Value = "red"`。 语法:*property* \[ = *value* ] 此接口是 **`[COMExtensible(True)]`**——参见包概述中的[动态 DOM 属性解析](/official/Reference/tbIDE/#动态-dom-属性解析)。通过 [**Properties**](#properties) 路由的属性名在运行时根据活动 DOM 解析,而非静态声明。 --- --- url: /en/official/Reference/tbIDE/HtmlElements.md --- # HtmlElements class A child-element collection on an [**HtmlElement**](/en/official/Reference/tbIDE/HtmlElement). Reached through [**HtmlElement.ChildDomElements**](/en/official/Reference/tbIDE/HtmlElement#childdomelements). Use [**Add**](#add) to create new children and [**Item**](#item) to look one up by ID after the fact. ```vb With myToolWindow.RootDomElement With .ChildDomElements.Add("header", "h1") .Properties.innerText = "Hello" End With With .ChildDomElements.Add("body", "div") .Properties.style.padding = "10px" With .ChildDomElements.Add("greeting", "p") .Properties.innerText = "World" End With End With End With ``` ## Methods ### Add Creates a new child element under the parent [**HtmlElement**](/en/official/Reference/tbIDE/HtmlElement) and returns the new [**HtmlElement**](/en/official/Reference/tbIDE/HtmlElement). Syntax: *htmlElements*.**Add**( *ElementID*, *TagName* ) **As** [**HtmlElement**](/en/official/Reference/tbIDE/HtmlElement) *ElementID* : *required* A DOM `id` for the new element. **String**. Pick distinct IDs across the tool window --- they double as the key for [**Item**](#item) lookups. *TagName* : *required* The HTML tag name. **String**. Standard tags (`"div"`, `"span"`, `"input"`, `"h1"`, `"label"`, `"img"`, …) work as expected; the IDE additionally accepts four custom-widget tags described in [Tool-window DOM tags](/en/official/Reference/tbIDE/#tool-window-dom-tags) on the package overview: `"chartjs"`, `"monaco"`, `"listview"`, `"virtuallistview"`. ```vb ' Standard DOM tags: Set greeting = .ChildDomElements.Add("greeting", "h1") Set entry = .ChildDomElements.Add("entryBox", "input") ' Custom-widget tags (see sample 11 / 12 / 13 / 14): Set chart = .ChildDomElements.Add("cpuChart", "chartjs") Set editor = .ChildDomElements.Add("myEditor", "monaco") Set listview = .ChildDomElements.Add("itemsList", "listview") Set virtList = .ChildDomElements.Add("bigList", "virtuallistview") ``` ## Properties ### Item Looks up an existing child element by its ID. **DefaultMember** --- so `elements("greeting")` is equivalent to `elements.Item("greeting")`. Syntax: *htmlElements*( *ID* ) **As** [**HtmlElement**](/en/official/Reference/tbIDE/HtmlElement) *ID* : A **Variant** --- typically the **String** ID assigned at [**Add**](#add) time. --- --- url: /zh/official/Reference/tbIDE/HtmlElements.md --- # HtmlElements 类 [**HtmlElement**](/official/Reference/tbIDE/HtmlElement) 上的子元素集合。通过 [**HtmlElement.ChildDomElements**](/official/Reference/tbIDE/HtmlElement#childdomelements) 访问。使用 [**Add**](#add) 创建新子元素,使用 [**Item**](#item) 事后按 ID 查找。 ```vb With myToolWindow.RootDomElement With .ChildDomElements.Add("header", "h1") .Properties.innerText = "Hello" End With With .ChildDomElements.Add("body", "div") .Properties.style.padding = "10px" With .ChildDomElements.Add("greeting", "p") .Properties.innerText = "World" End With End With End With ``` ## 方法 ### Add 在父 [**HtmlElement**](/official/Reference/tbIDE/HtmlElement) 下创建新子元素并返回新的 [**HtmlElement**](/official/Reference/tbIDE/HtmlElement)。 语法:*htmlElements*.**Add**( *ElementID*, *TagName* ) **As** [**HtmlElement**](/official/Reference/tbIDE/HtmlElement) *ElementID* : *必需* 新元素的 DOM `id`。**String**。在工具窗口内选择不同的 ID——它们同时作为 [**Item**](#item) 查找的键。 *TagName* : *必需* HTML 标签名。**String**。标准标签(`"div"`、`"span"`、`"input"`、`"h1"`、`"label"`、`"img"` 等)按预期工作;IDE 额外接受四个自定义控件标签,在包概述的[工具窗口 DOM 标签](/official/Reference/tbIDE/#工具窗口-dom-标签)中描述:`"chartjs"`、`"monaco"`、`"listview"`、`"virtuallistview"`。 ```vb ' 标准 DOM 标签: Set greeting = .ChildDomElements.Add("greeting", "h1") Set entry = .ChildDomElements.Add("entryBox", "input") ' 自定义控件标签(参见示例 11 / 12 / 13 / 14): Set chart = .ChildDomElements.Add("cpuChart", "chartjs") Set editor = .ChildDomElements.Add("myEditor", "monaco") Set listview = .ChildDomElements.Add("itemsList", "listview") Set virtList = .ChildDomElements.Add("bigList", "virtuallistview") ``` ## 属性 ### Item 按 ID 查找现有子元素。**DefaultMember**——因此 `elements("greeting")` 等同于 `elements.Item("greeting")`。 语法:*htmlElements*( *ID* ) **As** [**HtmlElement**](/official/Reference/tbIDE/HtmlElement) *ID* : 一个 **Variant** —— 通常是 [**Add**](#add) 时分配的 **String** ID。 --- --- url: /en/official/Reference/tbIDE/HtmlEventProperties.md --- # HtmlEventProperties class The dynamic event-payload bag passed to every [**HtmlElement.AddEventListener**](/en/official/Reference/tbIDE/HtmlElement#addeventlistener) callback. Conceptually the IDE-side equivalent of the JavaScript `Event` object --- fields like `.key`, `.target.id`, `.target.value`, `.index` are accessed dynamically through the bag's `[COMExtensible(True)]` resolution. ```vb Private Sub MyButtonClicked(ByVal eventInfo As HtmlEventProperties) Host.DebugConsole.PrintText "clicked: " & eventInfo.target.id End Sub Private Sub MyKeyUp(ByVal eventInfo As HtmlEventProperties) If eventInfo.key = "Enter" Then ProcessEntered(eventInfo.target.value) End Sub ``` ::: warning This interface is **`[COMExtensible(True)]`**. Field names are resolved against the underlying event object at run time. The standard DOM event properties (`.target` → the element that fired the event; `.key`, `.code`, `.altKey`, `.ctrlKey`, `.shiftKey` for keyboard events; `.clientX`, `.clientY` for mouse events; `.index` for the IDE's listview events; …) are forwarded as-is to the JavaScript-side event object. See MDN's DOM Event documentation for the standard fields. ::: ## Custom-data fan-out from `raiseEvent()` When inline HTML inside a tool window calls the IDE-side `raiseEvent(eventName, event, stopPropagation, ...customData)` helper, the trailing *customData* values flow through to the addin's listener as `eventInfo.customData0`, `eventInfo.customData1`, …, numerically indexed from zero. This is the mechanism the listview / virtual listview use to attach per-row context (file path, line number, …) to their item events. ```vb ' Inline HTML — sample 15: ' <div class="match" onclick="raiseEvent('onClickMatch', event, true, 'C:/file.twin', 42, 8)">…</div> Private Sub OnClickMatch(ByVal eventInfo As HtmlEventProperties) Dim filePath As String = eventInfo.customData0 Dim lineNum As Long = eventInfo.customData1 Dim colNum As Long = eventInfo.customData2 Host.ActiveEditors.Open filePath, lineNum, colNum End Sub ``` ## Asynchronous events (`setAsyncResult`) Some events --- notably the virtual listview's `onAsyncGetItemHTML` --- are *asynchronous*: the IDE asks the addin to produce content for a specific argument and expects the answer back through the event object itself. The argument arrives on the event as `eventInfo.asyncArgument`, and the listener responds by calling `eventInfo.setAsyncResult(answer)`: ```vb Private Sub OnAsyncGetItemHTML(ByVal eventInfo As HtmlEventProperties) Dim itemIndex As Long = eventInfo.asyncArgument eventInfo.setAsyncResult("<div>Row " & itemIndex & "</div>") End Sub ``` This is the standard `[COMExtensible(True)]` resolution at work --- `setAsyncResult` is not declared on the interface, it is dispatched through the dynamic mechanism just like `.key` or `.target` would be. See sample 14 (`WaynesVirtualListViewAddIn`) for the full pattern, including the cache-invalidation companion call `listview.notifyChangedItem(idx)`. ## Default member The interface's **DefaultMember** is [**Item**](#item) --- so `eventInfo("target")` is equivalent to `eventInfo.Item("target")`. The `.target.id` shorthand desugars accordingly. ## Properties ### Item Looks up a field by name. Returns an [**HtmlEventProperty**](/en/official/Reference/tbIDE/HtmlEventProperty), which includes the field's value plus a nested [**Properties**](/en/official/Reference/tbIDE/HtmlEventProperty#properties) for further drill-down. Syntax: *eventInfo*( *DomPropertyName* ) **As** [**HtmlEventProperty**](/en/official/Reference/tbIDE/HtmlEventProperty) *DomPropertyName* : *required* The field name. **String**. --- --- url: /zh/official/Reference/tbIDE/HtmlEventProperties.md --- # HtmlEventProperties 类 传递给每个 [**HtmlElement.AddEventListener**](/official/Reference/tbIDE/HtmlElement#addeventlistener) 回调的动态事件负载包。概念上是 JavaScript `Event` 对象的 IDE 端等价物——`.key`、`.target.id`、`.target.value`、`.index` 等字段通过包的 `[COMExtensible(True)]` 解析动态访问。 ```vb Private Sub MyButtonClicked(ByVal eventInfo As HtmlEventProperties) Host.DebugConsole.PrintText "clicked: " & eventInfo.target.id End Sub Private Sub MyKeyUp(ByVal eventInfo As HtmlEventProperties) If eventInfo.key = "Enter" Then ProcessEntered(eventInfo.target.value) End Sub ``` ::: warning 此接口是 **`[COMExtensible(True)]`**。字段名在运行时根据底层事件对象解析。标准 DOM 事件属性(`.target` → 触发事件的元素;键盘事件的 `.key`、`.code`、`.altKey`、`.ctrlKey`、`.shiftKey`;鼠标事件的 `.clientX`、`.clientY`;IDE 列表视图事件的 `.index` 等)原样转发自 JavaScript 端事件对象。标准字段请参阅 MDN 的 DOM Event 文档。 ::: ## 来自 `raiseEvent()` 的自定义数据扇出 当工具窗口内的行内 HTML 调用 IDE 端的 `raiseEvent(eventName, event, stopPropagation, ...customData)` 辅助函数时,尾部的 *customData* 值作为 `eventInfo.customData0`、`eventInfo.customData1` 等流向插件的监听器,从零开始数字索引。这是列表视图/虚拟列表视图用于将逐行上下文(文件路径、行号等)附加到其项事件的机制。 ```vb ' 行内 HTML — 示例 15: ' <div class="match" onclick="raiseEvent('onClickMatch', event, true, 'C:/file.twin', 42, 8)">…</div> Private Sub OnClickMatch(ByVal eventInfo As HtmlEventProperties) Dim filePath As String = eventInfo.customData0 Dim lineNum As Long = eventInfo.customData1 Dim colNum As Long = eventInfo.customData2 Host.ActiveEditors.Open filePath, lineNum, colNum End Sub ``` ## 异步事件(`setAsyncResult`) 某些事件——特别是虚拟列表视图的 `onAsyncGetItemHTML`——是*异步的*:IDE 要求插件为特定参数生成内容,并期望通过事件对象本身返回答案。参数以 `eventInfo.asyncArgument` 到达事件,监听器通过调用 `eventInfo.setAsyncResult(answer)` 响应: ```vb Private Sub OnAsyncGetItemHTML(ByVal eventInfo As HtmlEventProperties) Dim itemIndex As Long = eventInfo.asyncArgument eventInfo.setAsyncResult("<div>Row " & itemIndex & "</div>") End Sub ``` 这是标准 `[COMExtensible(True)]` 解析在起作用——`setAsyncResult` 没有在接口上声明,它像 `.key` 或 `.target` 一样通过动态机制分派。完整模式(包括缓存失效配套调用 `listview.notifyChangedItem(idx)`)请参见示例 14(`WaynesVirtualListViewAddIn`)。 ## 默认成员 接口的 **DefaultMember** 是 [**Item**](#item)——因此 `eventInfo("target")` 等同于 `eventInfo.Item("target")`。`.target.id` 简写相应地脱糖。 ## 属性 ### Item 按名称查找字段。返回一个 [**HtmlEventProperty**](/official/Reference/tbIDE/HtmlEventProperty),其中包含字段的值加上用于进一步下钻的嵌套 [**Properties**](/official/Reference/tbIDE/HtmlEventProperty#properties)。 语法:*eventInfo*( *DomPropertyName* ) **As** [**HtmlEventProperty**](/official/Reference/tbIDE/HtmlEventProperty) *DomPropertyName* : *必需* 字段名称。**String**。 --- --- url: /en/official/Reference/tbIDE/HtmlEventProperty.md --- # HtmlEventProperty class One value inside an [**HtmlEventProperties**](/en/official/Reference/tbIDE/HtmlEventProperties) event bag --- returned by [**HtmlEventProperties.Item**](/en/official/Reference/tbIDE/HtmlEventProperties#item). Carries the field's [**Value**](#value) plus a [**Properties**](#properties) accessor for nested drill-down (e.g. `eventInfo.target.id`). Almost always written in shorthand --- neither **HtmlEventProperty** nor its parent [**HtmlEventProperties**](/en/official/Reference/tbIDE/HtmlEventProperties) is typically named in addin code; the compiler resolves chains like `eventInfo.target.id` through their default-members. Unlike [**HtmlElementProperty**](/en/official/Reference/tbIDE/HtmlElementProperty), [**Value**](#value) is **read-only** --- event payloads are an inbound signal from the DOM, not an outbound property setter. ```vb Private Sub MyButtonKeyUp(ByVal eventInfo As HtmlEventProperties) If eventInfo.key = "Enter" Then Dim entered As String = eventInfo.target.value ' … End If End Sub ``` ## Properties ### Properties A nested [**HtmlEventProperties**](/en/official/Reference/tbIDE/HtmlEventProperties) for fields that themselves have sub-fields (the canonical example is `.target`, whose sub-fields are the target element's own properties --- `id`, `value`, `name`, `tagName`, …). Read-only at the accessor level. Syntax: *property*.**Properties** **As** [**HtmlEventProperties**](/en/official/Reference/tbIDE/HtmlEventProperties) ### Value The field's value, as a **Variant**. **DefaultMember** --- so `eventInfo.key` desugars to `eventInfo.Item("key").Value`. Read-only --- event payloads cannot be modified. Syntax: *property* **As Variant** The interface is **`[COMExtensible(True)]`** --- see [Dynamic DOM property resolution](/en/official/Reference/tbIDE/#dynamic-dom-property-resolution) on the package overview. Field names that route through [**Properties**](#properties) are resolved against the live event object at run time, not declared statically. --- --- url: /zh/official/Reference/tbIDE/HtmlEventProperty.md --- # HtmlEventProperty 类 [**HtmlEventProperties**](/official/Reference/tbIDE/HtmlEventProperties) 事件包中的一个值——由 [**HtmlEventProperties.Item**](/official/Reference/tbIDE/HtmlEventProperties#item) 返回。包含字段的 [**Value**](#value) 加上一个 [**Properties**](#properties) 访问器用于嵌套下钻(例如 `eventInfo.target.id`)。 几乎总是以简写形式书写——**HtmlEventProperty** 及其父类 [**HtmlEventProperties**](/official/Reference/tbIDE/HtmlEventProperties) 通常不会在插件代码中被显式命名;编译器通过它们的默认成员解析 `eventInfo.target.id` 等链。与 [**HtmlElementProperty**](/official/Reference/tbIDE/HtmlElementProperty) 不同,[**Value**](#value) 是**只读的**——事件负载是从 DOM 发来的入站信号,而非出站属性设置器。 ```vb Private Sub MyButtonKeyUp(ByVal eventInfo As HtmlEventProperties) If eventInfo.key = "Enter" Then Dim entered As String = eventInfo.target.value ' … End If End Sub ``` ## 属性 ### Properties 一个嵌套的 [**HtmlEventProperties**](/official/Reference/tbIDE/HtmlEventProperties),用于本身具有子字段的字段(典型例子是 `.target`,其子字段是目标元素自身的属性——`id`、`value`、`name`、`tagName` 等)。在访问器层面只读。 语法:*property*.**Properties** **As** [**HtmlEventProperties**](/official/Reference/tbIDE/HtmlEventProperties) ### Value 字段的值,为 **Variant**。**DefaultMember**——因此 `eventInfo.key` 脱糖为 `eventInfo.Item("key").Value`。只读——事件负载不可修改。 语法:*property* **As Variant** 此接口是 **`[COMExtensible(True)]`**——参见包概述中的[动态 DOM 属性解析](/official/Reference/tbIDE/#动态-dom-属性解析)。通过 [**Properties**](#properties) 路由的字段名在运行时根据活动事件对象解析,而非静态声明。 --- --- url: /en/official/Reference/VBRUN/Hyperlink.md --- # Hyperlink class The **Hyperlink** object lets a control or form ask its container to navigate to a target document, the way clicking a link in a browser would. It is used from a control's code through the host's **Hyperlink** property --- for example **UserControl.Hyperlink** --- and works in containers that participate in browser-style navigation (Internet Explorer, Office binders, and a few other hyperlink-aware hosts). When the host does not support hyperlink navigation, the runtime falls back to launching the system's default handler for the target. ```vb Private Sub HelpButton_Click() UserControl.Hyperlink.NavigateTo "https://docs.twinbasic.com/" End Sub ``` ## Members ### GoBack Asks the container to navigate one step backwards in its history list, as if the user had pressed the browser's **Back** button. Syntax: *object*.**GoBack** *object* : *required* An object expression that evaluates to a **Hyperlink** object. If there is no previous entry, or if the host does not maintain a history list, the call has no effect (or raises an error, depending on the host). ### GoForward Asks the container to navigate one step forward in its history list, as if the user had pressed the browser's **Forward** button. Syntax: *object*.**GoForward** *object* : *required* An object expression that evaluates to a **Hyperlink** object. If there is no next entry, or if the host does not maintain a history list, the call has no effect (or raises an error, depending on the host). ### NavigateTo Asks the container to navigate to a target document. Syntax: *object*.**NavigateTo** *Target* \[ **,** *Location* \[ **,** *FrameName* ] ] *object* : *required* An object expression that evaluates to a **Hyperlink** object. *Target* : *required* A **String** giving the destination --- a URL, a UNC path, or a local file path. The container is responsible for resolving the string and dispatching it to the right handler. *Location* : *optional* A **String** naming an anchor or bookmark within *Target* --- for example the fragment after `#` in an HTML URL --- that the container should scroll to once the document has been loaded. *FrameName* : *optional* A **String** naming a frame within an HTML frameset that should receive the navigation, instead of the top-level window. Ignored by hosts that do not understand HTML frames. If the host implements browser-style navigation, the new target is added to the history list so subsequent [**GoBack**](#goback) and [**GoForward**](#goforward) calls work as expected. --- --- url: /zh/official/Reference/VBRUN/Hyperlink.md --- # Hyperlink 类 **Hyperlink**对象允许控件或窗体请求其容器导航到目标文档,就像在浏览器中点击链接一样。它通过宿主的**Hyperlink**属性从控件代码中使用——例如**UserControl.Hyperlink**——在参与浏览器式导航的容器(Internet Explorer、Office绑定器和其他少数支持超链接的宿主)中工作。当宿主不支持超链接导航时,运行时回退到启动目标的系统默认处理器。 `vb Private Sub HelpButton_Click() UserControl.Hyperlink.NavigateTo "https://docs.twinbasic.com/" End Sub ` ## 成员 ### GoBack 请求容器在其历史列表中后退一步,如同用户按下了浏览器的**Back**按钮。 语法:*object*.**GoBack** *object* : *必需* 求值为**Hyperlink**对象的对象表达式。 如果没有前一条目,或宿主不维护历史列表,则调用无效(或引发错误,取决于宿主)。 ### GoForward 请求容器在其历史列表中前进一步,如同用户按下了浏览器的**Forward**按钮。 语法:*object*.**GoForward** *object* : *必需* 求值为**Hyperlink**对象的对象表达式。 如果没有下一条目,或宿主不维护历史列表,则调用无效(或引发错误,取决于宿主)。 ### NavigateTo 请求容器导航到目标文档。 语法:*object*.**NavigateTo** *Target* \[ **,** *Location* \[ **,** *FrameName* ] ] *object* : *必需* 求值为**Hyperlink**对象的对象表达式。 *Target* : *必需* 给出目标的**String**——URL、UNC路径或本地文件路径。容器负责解析字符串并将其分派到正确的处理器。 *Location* : *可选* 命名*Target*内锚点或书签的**String**——例如HTML URL中#后的片段——容器在加载文档后应滚动到该位置。 *FrameName* : *可选* 命名HTML框架集中应接收导航的框架的**String**,代替顶级窗口。不支持HTML框架的宿主将忽略此参数。 如果宿主实现浏览器式导航,新目标将添加到历史列表,使后续的[**GoBack**](#goback)和[**GoForward**](#goforward)调用按预期工作。 --- --- url: /en/official/Reference/CustomControls/Framework/ICustomControl.md --- # ICustomControl interface The interface every custom control implements. The framework calls **Initialize** once after the control has been instantiated and its serialized property values have been deserialized, **Paint** every time the framework needs to redraw the control's area, and **Destroy** once when the control is being released. The eight concrete `Waynes…` classes in the package all implement this interface, alongside an inherited mixin base class for the standard layout / name members. ```vb Class MyControl Implements CustomControls.ICustomControl Private Sub OnInitialize(ByVal Context As CustomControls.CustomControlContext) _ Implements CustomControls.ICustomControl.Initialize ' … End Sub Private Sub OnDestroy() _ Implements CustomControls.ICustomControl.Destroy ' … End Sub Private Sub OnPaint(ByVal Canvas As CustomControls.Canvas) _ Implements CustomControls.ICustomControl.Paint ' … End Sub End Class ``` ## Methods ### Destroy Called once when the control is being released. The implementation should drop any references it holds to objects that themselves hold references back to it, so that the reference graph can collapse without cycles. Syntax: *object*.**Destroy** ( ) ### Initialize Called once after the framework has constructed the control and deserialized any designer-set property values from the form's `.frm` data into the new instance. Syntax: *object*.**Initialize** ( *Context* ) *Context* : *required* The [**CustomControlContext**](/en/official/Reference/CustomControls/Framework/CustomControlContext) for this control instance. Store it (typically as a class field named **ControlContext**) --- it is the only way to request repaints, create timers, or check the runtime mode after **Initialize** returns. A common implementation calls **Context.GetSerializer().RuntimeUISrzDeserialize(Me, False)** to load designer-set property values into the instance; if the call returns **False**, no serialized data was found and the control should apply its own defaults. ### Paint Called every time the framework needs to redraw the control's client area. The implementation builds one or more `ElementDescriptor` records describing the rectangles to draw and passes each to *Canvas*. **RuntimeUICCCanvasAddElement**. Syntax: *object*.**Paint** ( *Canvas* ) *Canvas* : *required* The [**Canvas**](/en/official/Reference/CustomControls/Framework/Canvas) drawing surface for this paint pass. Its **RuntimeUICCGetWidth**, **RuntimeUICCGetHeight**, and **RuntimeUICCGetDpiScaleFactor** methods supply the size and DPI of the area being painted, in device pixels. A descriptor may include event callbacks (`OnClick`, `OnMouseDown`, …) as `AddressOf` pointers; the framework dispatches input back through those pointers without the control needing to subscribe explicitly to anything. A control should request additional repaints by calling [**CustomControlContext.Repaint**](/en/official/Reference/CustomControls/Framework/CustomControlContext#repaint), not by calling **Paint** directly --- the framework controls when to issue the actual paint pass. --- --- url: /zh/official/Reference/CustomControls/Framework/ICustomControl.md --- # ICustomControl 接口 每个自定义控件实现的接口。框架在控件实例化并反序列化其属性值后调用 **Initialize** 一次,每次需要重绘控件区域时调用 **Paint**,控件被释放时调用 **Destroy** 一次。 包中的八个具体 `Waynes…` 类都实现了此接口,同时继承了标准布局/名称成员的混入基类。 ```vb Class MyControl Implements CustomControls.ICustomControl Private Sub OnInitialize(ByVal Context As CustomControls.CustomControlContext) _ Implements CustomControls.ICustomControl.Initialize ' … End Sub Private Sub OnDestroy() _ Implements CustomControls.ICustomControl.Destroy ' … End Sub Private Sub OnPaint(ByVal Canvas As CustomControls.Canvas) _ Implements CustomControls.ICustomControl.Paint ' … End Sub End Class ``` ## 方法 ### Destroy 控件被释放时调用一次。实现应释放其持有的对反向引用自身对象的引用,使引用图可以无环地收缩。 语法:*object*.**Destroy** ( ) ### Initialize 框架构建控件并将窗体 `.frm` 数据中设计器设置的属性值反序列化到新实例后调用一次。 语法:*object*.**Initialize** ( *Context* ) *Context* : *必需* 此控件实例的 [**CustomControlContext**](/official/Reference/CustomControls/Framework/CustomControlContext)。保存它(通常作为名为 **ControlContext** 的类字段)——这是 **Initialize** 返回后请求重绘、创建定时器或检查运行时模式的唯一方式。 常见实现调用 **Context.GetSerializer().RuntimeUISrzDeserialize(Me, False)** 以将设计器属性值加载到实例中;如果调用返回 **False**,则未找到序列化数据,控件应应用自己的默认值。 ### Paint 每次框架需要重绘控件客户区域时调用。实现构建一个或多个 `ElementDescriptor` 记录描述要绘制的矩形,并通过 *Canvas*.**RuntimeUICCCanvasAddElement** 传递每个描述符。 语法:*object*.**Paint** ( *Canvas* ) *Canvas* : *必需* 此绘制过程的 [**Canvas**](/official/Reference/CustomControls/Framework/Canvas) 绘图表面。其 **RuntimeUICCGetWidth**、**RuntimeUICCGetHeight** 和 **RuntimeUICCGetDpiScaleFactor** 方法提供被绘制区域的大小和 DPI,以设备像素为单位。 描述符可以包含事件回调(`OnClick`、`OnMouseDown` 等)作为 `AddressOf` 指针;框架通过这些指针分发输入,控件无需显式订阅任何内容。 控件应通过调用 [**CustomControlContext.Repaint**](/official/Reference/CustomControls/Framework/CustomControlContext#repaint) 请求额外重绘,而非直接调用 **Paint**——框架控制何时发出实际绘制过程。 --- --- url: /en/official/Reference/CustomControls/Framework/ICustomForm.md --- # ICustomForm interface The form-class counterpart to [**ICustomControl**](/en/official/Reference/CustomControls/Framework/ICustomControl). Custom *form* classes --- top-level windows that host other custom controls --- implement this interface instead. The shape is identical to **ICustomControl** except that the **Initialize** callback receives a [**CustomFormContext**](/en/official/Reference/CustomControls/Framework/CustomFormContext) (which extends [**CustomControlContext**](/en/official/Reference/CustomControls/Framework/CustomControlContext) with **Show** and **Close**) rather than a plain **CustomControlContext**. [**WaynesForm**](/en/official/Reference/CustomControls/WaynesForm/), the package's only concrete form class, does in fact implement [**ICustomControl**](/en/official/Reference/CustomControls/Framework/ICustomControl) and cast its context to **CustomFormContext** internally --- the **ICustomForm** interface is published for parity with **ICustomControl** but is not currently consumed by any class shipped with the package. ## Methods ### Destroy Called once when the form is being released. See [**ICustomControl.Destroy**](/en/official/Reference/CustomControls/Framework/ICustomControl#destroy). Syntax: *object*.**Destroy** ( ) ### Initialize Called once after the framework has constructed the form and deserialized any designer-set property values into it. Syntax: *object*.**Initialize** ( *Context* ) *Context* : *required* The [**CustomFormContext**](/en/official/Reference/CustomControls/Framework/CustomFormContext) for this form instance. ### Paint Called every time the framework needs to redraw the form's client area. See [**ICustomControl.Paint**](/en/official/Reference/CustomControls/Framework/ICustomControl#paint). Syntax: *object*.**Paint** ( *Canvas* ) *Canvas* : *required* The [**Canvas**](/en/official/Reference/CustomControls/Framework/Canvas) drawing surface for this paint pass. --- --- url: /zh/official/Reference/CustomControls/Framework/ICustomForm.md --- # ICustomForm 接口 [**ICustomControl**](/official/Reference/CustomControls/Framework/ICustomControl) 的窗体类对应接口。自定义*窗体*类——承载其他自定义控件的顶级窗口——实现此接口。形状与 **ICustomControl** 相同,只是 **Initialize** 回调接收 [**CustomFormContext**](/official/Reference/CustomControls/Framework/CustomFormContext)(它扩展了 [**CustomControlContext**](/official/Reference/CustomControls/Framework/CustomControlContext) 的 **Show** 和 **Close**)而非普通的 **CustomControlContext**。 [**WaynesForm**](/official/Reference/CustomControls/WaynesForm/)——包中唯一的具体窗体类——实际上实现了 [**ICustomControl**](/official/Reference/CustomControls/Framework/ICustomControl) 并在内部将上下文转换为 **CustomFormContext**——**ICustomForm** 接口的发布是为了与 **ICustomControl** 对等,但目前没有被包中任何类使用。 ## 方法 ### Destroy 窗体被释放时调用一次。参见 [**ICustomControl.Destroy**](/official/Reference/CustomControls/Framework/ICustomControl#destroy)。 语法:*object*.**Destroy** ( ) ### Initialize 在框架构建窗体并将设计器设置的属性值反序列化到其中后调用一次。 语法:*object*.**Initialize** ( *Context* ) *Context* : *必需* 此窗体实例的 [**CustomFormContext**](/official/Reference/CustomControls/Framework/CustomFormContext)。 ### Paint 每次框架需要重绘窗体客户区域时调用。参见 [**ICustomControl.Paint**](/official/Reference/CustomControls/Framework/ICustomControl#paint)。 语法:*object*.**Paint** ( *Canvas* ) *Canvas* : *必需* 此绘制过程的 [**Canvas**](/official/Reference/CustomControls/Framework/Canvas) 绘图表面。 --- --- url: /en/official/IDE.md --- # The twinBASIC IDE ![IDE](/assets/IDE.CZ5bEuRw.png "IDE") The IDE consists of several fixed panes and tool windows. The [**Project Explorer**](/en/official/IDE/Project-Explorer) shows the file tree of the open project; the [**Editor**](/en/official/IDE/Editor) is the main code and designer surface; the [**Properties**](/en/official/IDE/Properties) pane shows and edits properties for the selected item; the [**Toolbox**](/en/official/IDE/Toolbox) lists the controls available to drop onto a form. The debug tool windows --- [**Call Stack**](/en/official/IDE/Call-Stack), [**Watches**](/en/official/IDE/Watches), [**Variables**](/en/official/IDE/Variables), [**Debug Console**](/en/official/IDE/Debug-Console), [**Diagnostics**](/en/official/IDE/Diagnostics), [**Outline**](/en/official/IDE/Outline), and [**Memory**](/en/official/IDE/Memory) --- open during a debug session. The [**tbForm**](/en/official/IDE/tbForm) and [**tbReport**](/en/official/IDE/tbReport) designers open when a form or report file is selected in the Project Explorer. Third-party and community [**addins**](/en/official/IDE/AddIns/) extend the IDE with additional commands and tool windows. --- --- url: /zh/official/IDE.md --- # twinBASIC IDE ![IDE](/assets/IDE.CZ5bEuRw.png "IDE") IDE 由几个固定的面板和工具窗口组成。[**项目资源管理器**](/official/IDE/Project-Explorer) 显示打开项目的文件树;[**编辑器**](/official/IDE/Editor) 是主要的代码和设计器界面;[**属性**](/official/IDE/Properties) 面板显示和编辑所选项目的属性;[**工具箱**](/official/IDE/Toolbox) 列出可放置到窗体上的控件。 调试工具窗口——[**调用堆栈**](/official/IDE/Call-Stack)、[**监视**](/official/IDE/Watches)、[**变量**](/official/IDE/Variables)、[**调试控制台**](/official/IDE/Debug-Console)、[**诊断**](/official/IDE/Diagnostics)、[**大纲**](/official/IDE/Outline) 和 **内存**——在调试会话期间打开。 [**tbForm**](/official/IDE/tbForm) 和 [**tbReport**](/official/IDE/tbReport) 设计器在选择窗体或报表文件时在项目资源管理器中打开。第三方和社区[**外接程序**](/official/IDE/AddIns/) 通过附加命令和工具窗口扩展 IDE。 --- --- url: /en/official/Reference/VBA/Interaction/If.md --- # If Returns one of two values depending on a condition, evaluating only the branch it returns. **If** is a twinBASIC addition; in VBA, the closest equivalent is [**IIf**](/en/official/Reference/VBA/Interaction/IIf), which always evaluates both branches. Syntax: * **If(** *expression* **,** *truepart* **,** *falsepart* **)** * **If(** *expressiontruepart* **,** *falsepart* **)** *expression* : *required* Expression evaluated for its truth value. May be any expression that converts to **Boolean**. *truepart* : *required* Value or expression returned when *expression* is **True**. In the three-argument form this is evaluated only when *expression* is **True**. *falsepart* : *required* Value or expression returned when *expression* is **False**, or when *expressiontruepart* is **Null**, **Empty**, or **Nothing**. Evaluated only when actually needed. *expressiontruepart* : *required* (in the two-argument form) Expression that serves as both the test and the value to return when it is "set". The function returns *expressiontruepart* unless it is **Null**, **Empty**, or a **Nothing** object reference, in which case it returns *falsepart*. Useful for null-coalescing --- for example, `If(MaybeNothing, FallbackValue)`. The three-argument form is the inline conditional: it returns *truepart* when *expression* is **True**, *falsepart* otherwise, and only the chosen branch is evaluated. This makes expressions such as `If(Divisor <> 0, 100 / Divisor, "n/a")` safe even when *Divisor* is zero. ::: info **If** uses special internal bindings in the compiler and may not behave exactly like a regular function --- in particular, `Application.Run "If", ...` and other reflective callers will not invoke it. ::: ### Example ```vb Dim Divisor As Long Divisor = 0 ' Three-argument form — short-circuits, so the division never happens when Divisor = 0. Dim Result As Variant Result = If(Divisor <> 0, 100 / Divisor, "n/a") ' "n/a" ' Two-argument form — null-coalescing. Dim MaybeName As Variant MaybeName = Null Debug.Print If(MaybeName, "Anonymous") ' "Anonymous" MaybeName = "Alice" Debug.Print If(MaybeName, "Anonymous") ' "Alice" ``` ### See Also * [IIf](/en/official/Reference/VBA/Interaction/IIf) function * [Choose](/en/official/Reference/VBA/Interaction/Choose) function * [Switch](/en/official/Reference/VBA/Interaction/Switch) function --- --- url: /zh/official/Reference/VBA/Interaction/If.md --- # If 根据条件返回两个值之一,仅评估返回的分支。**If**是twinBASIC新增项;在VBA中,最接近的等价物是[**IIf**](/official/Reference/VBA/Interaction/IIf),它始终评估两个分支。 语法: * **If(** *expression* **,** *truepart* **,** *falsepart* **)** * **If(** *expressiontruepart* **,** *falsepart* **)** *expression* : *必需* 为其真值评估的表达式。可以是任何可转换为**Boolean**的表达式。 *truepart* : *必需* 当*expression*为**True**时返回的值或表达式。在三参数形式中,仅当*expression*为**True**时才评估。 *falsepart* : *必需* 当*expression*为**False**,或*expressiontruepart*为**Null**、**Empty**或**Nothing**时返回的值或表达式。仅在实际需要时评估。 *expressiontruepart* : *必需*(在两参数形式中)同时作为测试和"已设置"时返回值的表达式。函数返回*expressiontruepart*,除非它为**Null**、**Empty**或**Nothing**对象引用,在这种情况下返回*falsepart*。适用于空值合并——例如`If(MaybeNothing, FallbackValue)`。 三参数形式是内联条件:当*expression*为**True**时返回*truepart*,否则返回*falsepart*,仅评估所选分支。这使得诸如`If(Divisor <> 0, 100 / Divisor, "n/a")`的表达式即使*Divisor*为零也是安全的。 ::: info **If**在编译器中使用特殊的内部绑定,可能不像常规函数那样运行——特别是`Application.Run "If", ...`和其他反射调用者不会调用它。 ::: ### 示例 ```vb Dim Divisor As Long Divisor = 0 ' Three-argument form — short-circuits, so the division never happens when Divisor = 0. Dim Result As Variant Result = If(Divisor <> 0, 100 / Divisor, "n/a") ' "n/a" ' Two-argument form — null-coalescing. Dim MaybeName As Variant MaybeName = Null Debug.Print If(MaybeName, "Anonymous") ' "Anonymous" MaybeName = "Alice" Debug.Print If(MaybeName, "Anonymous") ' "Alice" ``` ### 另请参阅 * [IIf](/official/Reference/VBA/Interaction/IIf)函数 * [Choose](/official/Reference/VBA/Interaction/Choose)函数 * [Switch](/official/Reference/VBA/Interaction/Switch)函数 --- --- url: /zh/official/Reference/Core/If.md --- # If 语句 if 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/If.md --- # If Statement Documentation for the if keyword is not yet available. --- --- url: /en/official/Reference/Core/If-Then-Else.md --- # If...Then...Else Conditionally executes a group of statements, depending on the value of an expression. Syntax: * > **If** *condition* **Then** \[ *statements* ] \[ **Else** *elsestatements* ] * > **If** *condition* **Then**\ >     \[ *statements* ]\ > \[ **ElseIf** *condition-n* **Then**\ >     \[ *elseifstatements* ] ]\ > \[ **Else**\ >     \[ *elsestatements* ] ]\ > **End If** *condition* : One or more of the following two types of expressions: * A numeric expression or string expression that evaluates to **True** or **False**. If *condition* is Null, *condition* is treated as **False**. * An expression of the form **TypeOf** *objectname* **Is** *objecttype*. *objectname* is any object reference, and *objecttype* is any valid object type. The expression is **True** if *objectname* is of the object type specified by *objecttype*; otherwise it is **False**. *statements* : Optional in block form; required in single-line form that has no **Else** clause. One or more statements separated by colons; executed if *condition* is **True**. *condition-n* : *optional* Same as *condition*. *elseifstatements* : *optional* One or more statements executed if the associated *condition-n* is **True**. *elsestatements* : *optional* One or more statements executed if no previous *condition* or *condition-n* expression is **True**. Use the single-line form (first syntax) for short, simple tests. The block form (second syntax) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug. ::: info With the single-line form, it is possible to have multiple statements executed as the result of an **If...Then** decision. All statements must be on the same line and separated by colons, as in the following statement: ```vb If A > 10 Then A = A + 1 : B = B + A : C = C + B ``` ::: A block form **If** statement must be the first statement on a line. The **Else**, **ElseIf**, and **End If** parts of the statement can have only a line number or line label preceding them. The block **If** must end with an **End If** statement. To determine whether or not a statement is a block **If**, examine what follows the **Then** keyword. If anything other than a comment appears after **Then** on the same line, the statement is treated as a single-line **If** statement. The **Else** and **ElseIf** clauses are both optional. A block **If** can have any number of **ElseIf** clauses, but none can appear after an **Else** clause. Block **If** statements can be nested; that is, contained within one another. When executing a block **If** (second syntax), *condition* is tested. If *condition* is **True**, the statements following **Then** are executed. If *condition* is **False**, each **ElseIf** condition (if any) is evaluated in turn. When a **True** condition is found, the statements immediately following the associated **Then** are executed. If none of the **ElseIf** conditions are **True** (or if there are no **ElseIf** clauses), the statements following **Else** are executed. After executing the statements following **Then** or **Else**, execution continues with the statement following **End If**. ::: tip [**Select Case**](/en/official/Reference/Core/Select-Case) may be more useful when evaluating a single expression that has several possible actions. However, the **TypeOf** *objectname* **Is** *objecttype* clause can't be used with the **Select Case** statement. ::: ::: info **TypeOf** cannot be used with hard data types such as **Long**, **Integer**, and so forth other than **Object**. ::: ### Example This example shows both the block and single-line forms of the **If...Then...Else** statement. It also illustrates the use of **If TypeOf...Then...Else**. ```vb Dim Number, Digits, MyString Number = 53 ' Initialize variable. If Number < 10 Then Digits = 1 ElseIf Number < 100 Then ' Condition evaluates to True so the next statement is executed. Digits = 2 Else Digits = 3 End If ' Assign a value using the single-line form of syntax. If Digits = 1 Then MyString = "One" Else MyString = "More than one" ``` Use the **If TypeOf** construct to determine whether the Control passed into a procedure is a particular kind of control. ```vb Sub ControlProcessor(MyControl As Control) If TypeOf MyControl Is CommandButton Then Debug.Print "You passed in a " & TypeName(MyControl) ElseIf TypeOf MyControl Is CheckBox Then Debug.Print "You passed in a " & TypeName(MyControl) ElseIf TypeOf MyControl Is TextBox Then Debug.Print "You passed in a " & TypeName(MyControl) End If End Sub ``` ### See Also * [**Select Case** statement](/en/official/Reference/Core/Select-Case) * [**#If...Then...Else** directive](/en/official/Reference/Core/Topic-Preprocessor) --- --- url: /zh/official/Reference/Core/If-Then-Else.md --- # If...Then...Else 根据表达式的值有条件地执行一组语句。 语法: * > **If** *condition* **Then** \[ *statements* ] \[ **Else** *elsestatements* ] * > **If** *condition* **Then**\ >     \[ *statements* ]\ > \[ **ElseIf** *condition-n* **Then**\ >     \[ *elseifstatements* ] ]\ > \[ **Else**\ >     \[ *elsestatements* ] ]\ > **End If** *condition* : 以下两种类型的表达式之一或多个: * 求值为 **True** 或 **False** 的数值表达式或字符串表达式。如果 *condition* 为Null,则 *condition* 被视为 **False**。 * **TypeOf** *objectname* **Is** *objecttype* 形式的表达式。*objectname* 是任何对象引用,*objecttype* 是任何有效的对象类型。如果 *objectname* 是 *objecttype* 指定的对象类型,则表达式为 **True**;否则为 **False**。 *statements* : 块形式中可选;没有 **Else** 子句的单行形式中必需。用冒号分隔的一条或多条语句;当 *condition* 为 **True** 时执行。 *condition-n* : *可选* 与 *condition* 相同。 *elseifstatements* : *可选* 当关联的 *condition-n* 为 **True** 时执行的一条或多条语句。 *elsestatements* : *可选* 当前面没有 *condition* 或 *condition-n* 表达式为 **True** 时执行的一条或多条语句。 对于简短的测试使用单行形式(第一种语法)。块形式(第二种语法)比单行形式提供更多结构和灵活性,通常更容易阅读、维护和调试。 ::: info 使用单行形式时,可以作为 **If...Then** 判断的结果执行多条语句。所有语句必须在同一行并用冒号分隔,如下语句: ```vb If A > 10 Then A = A + 1 : B = B + A : C = C + B ``` ::: 块形式 **If** 语句必须是一行中的第一条语句。语句的 **Else**、**ElseIf** 和 **End If** 部分前面只能有行号或行标签。块 **If** 必须以 **End If** 语句结束。 要确定语句是否是块 **If**,检查 **Then** 关键字后面是什么。如果 **Then** 后面的同一行上出现注释以外的任何内容,该语句被视为单行 **If** 语句。 **Else** 和 **ElseIf** 子句都是可选的。块 **If** 可以有任意数量的 **ElseIf** 子句,但都不能出现在 **Else** 子句之后。块 **If** 语句可以嵌套;即相互包含。 执行块 **If**(第二种语法)时,测试 *condition*。如果 *condition* 为 **True**,执行 **Then** 后面的语句。如果 *condition* 为 **False**,依次评估每个 **ElseIf** 条件(如果有的话)。当找到 **True** 条件时,执行紧接在关联 **Then** 之后的语句。如果没有 **ElseIf** 条件为 **True**(或没有 **ElseIf** 子句),执行 **Else** 之后的语句。执行 **Then** 或 **Else** 之后的语句后,执行继续到 **End If** 之后的语句。 ::: tip 当评估具有多种可能操作的单个表达式时,[**Select Case**](/official/Reference/Core/Select-Case) 可能更有用。但 **TypeOf** *objectname* **Is** *objecttype* 子句不能与 **Select Case** 语句一起使用。 ::: ::: info **TypeOf** 不能与 **Long**、**Integer** 等除 **Object** 之外的硬数据类型一起使用。 ::: ### 示例 本示例展示 **If...Then...Else** 语句的块形式和单行形式。还展示了 **If TypeOf...Then...Else** 的用法。 ```vb Dim Number, Digits, MyString Number = 53 ' Initialize variable. If Number < 10 Then Digits = 1 ElseIf Number < 100 Then ' Condition evaluates to True so the next statement is executed. Digits = 2 Else Digits = 3 End If ' Assign a value using the single-line form of syntax. If Digits = 1 Then MyString = "One" Else MyString = "More than one" ``` 使用 **If TypeOf** 构造确定传入过程的控件是否是特定类型的控件。 ```vb Sub ControlProcessor(MyControl As Control) If TypeOf MyControl Is CommandButton Then Debug.Print "You passed in a " & TypeName(MyControl) ElseIf TypeOf MyControl Is CheckBox Then Debug.Print "You passed in a " & TypeName(MyControl) ElseIf TypeOf MyControl Is TextBox Then Debug.Print "You passed in a " & TypeName(MyControl) End If End Sub ``` ### 另请参阅 * [**Select Case** 语句](/official/Reference/Core/Select-Case) * [**#If...Then...Else** 指令](/official/Reference/Core/Topic-Preprocessor) --- --- url: /en/official/Reference/VBA/Interaction/IIf.md --- # IIf Returns one of two values, depending on the evaluation of an expression. Syntax: **IIf(** *expr* **,** *truepart* **,** *falsepart* **)** *expr* : *required* Expression to evaluate. *truepart* : *required* Value or expression returned if *expr* is **True**. *falsepart* : *required* Value or expression returned if *expr* is **False**. ::: warning **IIf** always evaluates both *truepart* and *falsepart*, even though it returns only one of them. Watch for side effects: if the unused branch would raise an error (for example, division by zero), the error still occurs. Use the short-circuiting [**If**](/en/official/Reference/VBA/Interaction/If) function --- a twinBASIC addition --- to guard against errors in the unused branch. ::: ### Example This example uses **IIf** to return the word "Large" if the amount is greater than 1000, and "Small" otherwise. ```vb Function CheckIt(TestMe As Integer) As String CheckIt = IIf(TestMe > 1000, "Large", "Small") End Function ``` ### See Also * [If](/en/official/Reference/VBA/Interaction/If) function * [Choose](/en/official/Reference/VBA/Interaction/Choose) function * [Switch](/en/official/Reference/VBA/Interaction/Switch) function --- --- url: /zh/official/Reference/VBA/Interaction/IIf.md --- # IIf 根据表达式的求值结果返回两个值之一。 语法:**IIf(** *expr* **,** *truepart* **,** *falsepart* **)** *expr* : *必需* 要评估的表达式。 *truepart* : *必需* 如果*expr*为**True**则返回的值或表达式。 *falsepart* : *必需* 如果*expr*为**False**则返回的值或表达式。 ::: warning **IIf**始终评估*truepart*和*falsepart*,即使它只返回其中一个。注意副作用:如果未使用的分支会引发错误(例如除零),错误仍然会发生。使用短路[**If**](/official/Reference/VBA/Interaction/If)函数——twinBASIC新增项——来防止未使用分支中的错误。 ::: ### 示例 本示例使用**IIf**在金额大于1000时返回"Large",否则返回"Small"。 ```vb Function CheckIt(TestMe As Integer) As String CheckIt = IIf(TestMe > 1000, "Large", "Small") End Function ``` ### 另请参阅 * [If](/official/Reference/VBA/Interaction/If)函数 * [Choose](/official/Reference/VBA/Interaction/Choose)函数 * [Switch](/official/Reference/VBA/Interaction/Switch)函数 --- --- url: /zh/official/Reference/Core/IIf.md --- # IIf 函数 iif 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/IIf.md --- # IIf Function Documentation for the iif keyword is not yet available. --- --- url: /en/official/Reference/VB/Image.md --- # Image class An **Image** is a windowless lightweight control for displaying a picture --- a bitmap, JPEG, GIF, PNG, icon, cursor, or Windows metafile. It is the small, efficient alternative to [**PictureBox**](/en/official/Reference/VB/PictureBox/): no underlying Win32 window, no drawing surface, no child controls, no focus --- just a rectangle on the parent that paints whatever is in [**Picture**](#picture). Image controls are ideal for logos, decorative artwork, custom-drawn buttons, glyph rows, and any other place where a heavy **PictureBox** would be overkill. The default property is [**Picture**](#picture) and the default event is [**Click**](#click). ```vb Private Sub Form_Load() Set imgLogo.Picture = LoadPicture(App.Path & "\logo.png") imgLogo.Stretch = True imgLogo.BorderStyle = vbFixedSingleBorder End Sub Private Sub imgLogo_Click() MsgBox "Logo clicked" End Sub ``` ## Windowless rendering An **Image** has no `hWnd`. The framework paints it directly onto its parent's drawing surface during the parent's paint cycle, so the control is much cheaper than a [**PictureBox**](/en/official/Reference/VB/PictureBox/) and adds no Win32 window of its own. The trade-offs are the same as for any windowless control: * No focus, no keyboard input, no `KeyDown` / `KeyPress` / `KeyUp` / `GotFocus` / `LostFocus` / `Validate`. * No `hWnd` to pass to API functions, and no `SetFocus`. * Cannot host child controls. For anything that needs those, use [**PictureBox**](/en/official/Reference/VB/PictureBox/) instead. ## Stretch and auto-sizing [**Stretch**](#stretch) is the master switch for sizing behaviour: * **Stretch = False** (default): the picture is drawn at its natural pixel size and the **Image** auto-resizes itself to match every time a new [**Picture**](#picture) is assigned. The user may still resize the control manually --- once that happens the picture is clipped or padded around the natural bounds (it is *not* re-stretched). * **Stretch = True**: the picture is scaled to fill the **Image**'s rectangle. The resampling algorithm is chosen by [**StretchMode**](#stretchmode); aspect ratio is *not* preserved. Metafiles (`vbPicTypeMetafile`, `vbPicTypeEMetafile`) are vector --- they always scale to fit and the aspect ratio is preserved regardless of [**Stretch**](#stretch). [**PictureDpiScaling**](#picturedpiscaling), when **True**, multiplies the natural pixel dimensions by the current DPI scale factor before drawing --- useful for keeping a logo the same physical size on a high-DPI monitor as on a 96-DPI one. ## Rotation [**Angle**](#angle) rotates the rendered picture, in degrees, anti-clockwise around the top-left corner of the control's rectangle. `0` is the natural orientation; `90` is a quarter turn anti-clockwise; values between `0` and `360` give arbitrary rotations. The control's bounding rectangle does not change --- large rotation angles can therefore push the visible picture outside the rectangle. Hit-testing for [**Click**](#click), [**MouseDown**](#mousedown), and the other mouse events still uses the unrotated rectangle. ## Border [**BorderStyle**](#borderstyle) chooses between no border (the default) and a single sunken border drawn around the rectangle. When a border is present, [**Appearance**](#appearance) selects between a 3-D and a flat (monochrome) version of it. ## Source-side and destination-side OLE drag-drop The **Image** control supports both ends of an OLE drag-drop operation: * [**OLEDragMode**](#oledragmode) controls the source side. With **vbOLEDragAutomatic**, holding the mouse over the **Image** and beginning a drag automatically copies the current [**Picture**](#picture) into the resulting **DataObject**. With **vbOLEDragManual** (default) drags must be initiated by calling [**OLEDrag**](#oledrag) from a [**MouseDown**](#mousedown) handler. * [**OLEDropMode**](#oledropmode) controls the destination side. With **vbOLEDropManual** the [**OLEDragOver**](#oledragover) and [**OLEDragDrop**](#oledragdrop) events fire and the application decides what to do. **vbOLEDropAutomatic** is not supported on an **Image** and assigning it raises run-time error 5. ## Data binding Setting [**DataSource**](#datasource) and [**DataField**](#datafield) connects the [**Picture**](#picture) to a field of a [**Data**](/en/official/Reference/VB/Data/) control's recordset. The bound field is read as binary picture data on each move; assigning **Nothing** to **Picture** writes a null-equivalent back to the recordset, and any other assignment serialises the picture's bytes back through the bound field. ## Properties ### Anchors The set of edges of the parent that the **Image**'s corresponding edges follow when the parent resizes. Read-only --- assign individual `.Left`, `.Top`, `.Right`, `.Bottom` flags through the returned **Anchors** object. ### Angle The rotation of the rendered picture, in degrees, anti-clockwise around the top-left of the control's rectangle. **Double**, default `0`. ### Appearance The style of the border, as a member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). Only meaningful when [**BorderStyle**](#borderstyle) is **vbFixedSingleBorder**. ### BorderStyle The style of border drawn around the rectangle. A member of [**ControlBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants): **vbNoBorder** (0, default) or **vbFixedSingleBorder** (1). ### Container The control that hosts this **Image** --- typically the form, a [**Frame**](/en/official/Reference/VB/Frame/), or a **UserControl**. Read with **Get**, change with **Set**. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as an image. Always **vbImage**. ### DataChanged Whether the bound [**Picture**](#picture) has been written to since the last save or refresh from the [**DataSource**](#datasource). **Boolean**. Setting **DataChanged** = **True** also marks the bound recordset as dirty. ### DataField The name of the field, in the recordset of the bound [**DataSource**](#datasource), whose binary value is mirrored by [**Picture**](#picture). **String**. ### DataFormat ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### DataMember ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### DataSource A reference to a [**Data**](/en/official/Reference/VB/Data/) control (or other **DataSource** provider) whose recordset supplies the value for [**DataField**](#datafield). Set with **Set**. ### Dock Where the **Image** is docked within its container. A member of [**DockModeConstants**](/en/official/Reference/VBRUN/Constants/DockModeConstants): **vbDockNone** (default), **vbDockLeft**, **vbDockTop**, **vbDockRight**, **vbDockBottom**, or **vbDockFill**. Docked images ignore [**Anchors**](#anchors). ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself (the manual VB-drag form, distinct from OLE drag) when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the control accepts mouse input. A disabled **Image** still paints normally but ignores mouse events. **Boolean**, default **True**. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). **Double**. When [**Stretch**](#stretch) is **False** and a new [**Picture**](#picture) is assigned, the height auto-resizes to the picture's natural pixel height. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Reading **Index** on a non-array instance raises run-time error 343 (*Object not an array*). Read-only at run time. ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Double**. ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### OLEDragMode Whether an OLE drag is started automatically when the user begins dragging the **Image**. A member of [**OLEDragConstants**](/en/official/Reference/VBRUN/Constants/OLEDragConstants): **vbOLEDragManual** (0, default --- application calls [**OLEDrag**](#oledrag)) or **vbOLEDragAutomatic** (1 --- the framework copies the current [**Picture**](#picture) into the resulting **DataObject** automatically). ### OLEDropMode How the **Image** responds to OLE drops arriving on it. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** (0, default) or **vbOLEDropManual** (1). Automatic drop is not supported on an **Image**; assigning **vbOLEDropAutomatic** raises run-time error 5 (*Invalid procedure call or argument*). ### Parent A reference to the [**Form**](/en/official/Reference/VB/Form/) (or **UserControl**) that ultimately contains the control. Read-only. ### Picture The **StdPicture** rendered by the control. **Default property.** Syntax: `Set` *object*.**Picture** = *picture* Assigning **Nothing** restores an empty picture rather than removing the surface. Assigning a new picture while [**Stretch**](#stretch) is **False** auto-resizes the control to the picture's natural pixel dimensions; while [**Stretch**](#stretch) is **True** the existing rectangle is preserved and the new picture is scaled to fit. ### PictureDpiScaling When **True**, the picture's natural pixel dimensions are multiplied by the current DPI scale factor before being drawn (and used by the auto-size logic). **Boolean**, default **False**. ### Stretch Whether the picture is scaled to fill the control's rectangle (**True**) or rendered at its natural size with the control auto-sized to fit (**False**, default). See [Stretch and auto-sizing](#stretch-and-auto-sizing) for the full rules. Metafiles always scale regardless of this setting. ### StretchMode The resampling algorithm used when [**Stretch**](#stretch) is **True** and the picture is scaled. A member of `Image.StretchModeConstants`: | Constant | Value | Algorithm | |---------------------------|-------|--------------------------------------------------------------------------| | **vbStretchHalftone** | 0 | GDI `STRETCH_HALFTONE` (default --- good general-purpose quality). | | **vbStretchColorOnColor** | 1 | GDI `STRETCH_COLORONCOLOR` (fastest, lowest quality --- nearest neighbour). | | **vbStretchLanczos8** | 2 | Custom Lanczos resampler with an 8-lobe kernel (highest quality, slowest). | | **vbStretchLanczos3** | 3 | Custom Lanczos resampler with a 3-lobe kernel (high quality). | | **vbStretchBicubic** | 4 | Custom bicubic resampler. | | **vbStretchBilinear** | 5 | Custom bilinear resampler. | The Lanczos, bicubic, and bilinear modes only apply to bitmaps that actually need resizing --- metafiles and unscaled bitmaps fall back to the GDI mode. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the control. ### Top The vertical distance from the top of the container to the top of the control. **Double**. ### Visible Whether the control is shown. **Boolean**, default **True**. ### WhatsThisHelpID ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. See [**ShowWhatsThis**](#showwhatsthis). ::: ### Width The control's width, in twips by default (or in the container's **ScaleMode** units). **Double**. When [**Stretch**](#stretch) is **False** and a new [**Picture**](#picture) is assigned, the width auto-resizes to the picture's natural pixel width. ## Methods ### Drag Begins, completes, or cancels a manual VB-style drag operation. Distinct from OLE drag --- see [**OLEDrag**](#oledrag). Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from this **Image**, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject** (or, if the source has already been pre-populated, begins the drag immediately). Syntax: *object*.**OLEDrag** ### Refresh Forces an immediate repaint of the **Image**'s rectangle on the parent's drawing surface. Syntax: *object*.**Refresh** ### ShowWhatsThis ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the **Image** to the front or back of the windowless-sibling stack within its container. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Click Raised when the user single-clicks the control's rectangle. **Default event.** Syntax: *object*\_**Click**( ) ### DblClick Raised when the user double-clicks the control's rectangle. Syntax: *object*\_**DblClick**( ) ### DragDrop Raised on the destination control when a manual VB-style drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual VB-style drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### Initialize Raised once, after the control has been connected to its container's paint cycle but before it is first painted. Useful for last-minute setup that depends on container state. Syntax: *object*\_**Initialize**( ) ### MouseDown Raised when the user presses any mouse button over the control. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the control. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the control. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) --- --- url: /zh/official/Reference/VB/Image.md --- # Image 类 **Image**是无窗口轻量级控件,用于显示图片——位图、JPEG、GIF、PNG、图标、光标或Windows图元文件。它是[**PictureBox**](/official/Reference/VB/PictureBox/)的小巧高效替代:没有底层Win32窗口、没有绘图表面、没有子控件、没有焦点——只有父级上的一个矩形,绘制[**Picture**](#picture)中的内容。Image控件非常适合logo、装饰图、自定义绘制按钮、字形行以及任何使用重量级**PictureBox**显得过重的地方。 默认属性是[**Picture**](#picture),默认事件是[**Click**](#click)。 ```vb Private Sub Form_Load() Set imgLogo.Picture = LoadPicture(App.Path & "\logo.png") imgLogo.Stretch = True imgLogo.BorderStyle = vbFixedSingleBorder End Sub Private Sub imgLogo_Click() MsgBox "Logo clicked" End Sub ``` ## 无窗口渲染 **Image**没有`hWnd`。框架在父级的绘制周期中将其直接绘制到父级的绘图表面上,因此控件比[**PictureBox**](/official/Reference/VB/PictureBox/)开销小得多,不添加自己的Win32窗口。其权衡与任何无窗口控件相同: * 无焦点、无键盘输入、无`KeyDown` / `KeyPress` / `KeyUp` / `GotFocus` / `LostFocus` / `Validate`。 * 没有可传递给API函数的`hWnd`,也没有`SetFocus`。 * 不能承载子控件。 对于需要这些功能的场景,请改用[**PictureBox**](/official/Reference/VB/PictureBox/)。 ## 拉伸和自动调整尺寸 [**Stretch**](#stretch)是尺寸行为的主开关: * **Stretch = False**(默认):图片以其自然像素尺寸绘制,每次赋值新的[**Picture**](#picture)时**Image**自动调整自身大小以匹配。用户仍可手动调整控件大小——一旦如此,图片会被裁剪或在自然边界周围填充(*不会*重新拉伸)。 * **Stretch = True**:图片被缩放以填充**Image**的矩形。重采样算法由[**StretchMode**](#stretchmode)选择;不保持宽高比。 图元文件(`vbPicTypeMetafile`、`vbPicTypeEMetafile`)是矢量的——它们始终缩放以适应且无论[**Stretch**](#stretch)设置如何都保持宽高比。 [**PictureDpiScaling**](#picturedpiscaling)为**True**时,在绘制前将自然像素尺寸乘以当前DPI缩放因子——有助于使logo在高DPI显示器上与96-DPI显示器上保持相同的物理尺寸。 ## 旋转 [**Angle**](#angle)以度为单位围绕控件矩形的左上角逆时针旋转渲染图片。`0`为自然方向;`90`为逆时针旋转四分之一圈;`0`到`360`之间的值给出任意旋转。控件的边界矩形不变——因此大旋转角度可能将可见图片推出矩形。[**Click**](#click)、[**MouseDown**](#mousedown)和其他鼠标事件的命中测试仍使用未旋转的矩形。 ## 边框 [**BorderStyle**](#borderstyle)选择无边框(默认)和围绕矩形绘制的单凹陷边框。当边框存在时,[**Appearance**](#appearance)选择3-D和平面(单色)版本。 ## 源端和目标端OLE拖放 **Image**控件支持OLE拖放操作的两端: * [**OLEDragMode**](#oledragmode)控制源端。使用**vbOLEDragAutomatic**时,在**Image**上方按住鼠标并开始拖动会自动将当前[**Picture**](#picture)复制到结果**DataObject**中。使用**vbOLEDragManual**(默认)时,拖动必须通过从[**MouseDown**](#mousedown)处理程序调用[**OLEDrag**](#oledrag)来发起。 * [**OLEDropMode**](#oledropmode)控制目标端。使用**vbOLEDropManual**时,[**OLEDragOver**](#oledragover)和[**OLEDragDrop**](#oledragdrop)事件触发,由应用程序决定如何处理。**vbOLEDropAutomatic**在**Image**上不受支持,赋值它会导致运行时错误5。 ## 数据绑定 设置[**DataSource**](#datasource)和[**DataField**](#datafield)将[**Picture**](#picture)连接到[**Data**](/official/Reference/VB/Data/)控件记录集的字段。绑定字段在每次移动时作为二进制图片数据读取;将**Nothing**赋值给**Picture**会将空值等效写回记录集,任何其他赋值会通过绑定字段序列化图片的字节。 ## 属性 ### Anchors 决定**Image**的哪些边随父级对应边调整的边集合。只读——通过返回的**Anchors**对象设置各个`.Left`、`.Top`、`.Right`、`.Bottom`标志。 ### Angle 渲染图片的旋转角度,以度为单位,围绕控件矩形的左上角逆时针旋转。**Double**,默认`0`。 ### Appearance 边框的样式,作为[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。仅在[**BorderStyle**](#borderstyle)为**vbFixedSingleBorder**时有意义。 ### BorderStyle 绘制在矩形周围的边框样式。[**ControlBorderStyleConstants**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants)的成员:**vbNoBorder**(0,默认)或**vbFixedSingleBorder**(1)。 ### Container 承载此**Image**的控件——通常是窗体、[**Frame**](/official/Reference/VB/Frame/)或**UserControl**。用**Get**读取,用**Set**更改。 ### ControlType 标识此控件为图像的只读[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值。始终为**vbImage**。 ### DataChanged 绑定的[**Picture**](#picture)自上次从[**DataSource**](#datasource)保存或刷新以来是否已被写入。**Boolean**。设置**DataChanged** = **True**也会将绑定记录集标记为脏。 ### DataField 绑定的[**DataSource**](#datasource)记录集中由[**Picture**](#picture)镜像的字段名称。**String**。 ### DataFormat ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: ### DataMember ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: ### DataSource 对[**Data**](/official/Reference/VB/Data/)控件(或其他**DataSource**提供者)的引用,其记录集为[**DataField**](#datafield)提供值。用**Set**设置。 ### Dock **Image**在其容器中的停靠位置。[**DockModeConstants**](/official/Reference/VBRUN/Constants/DockModeConstants)的成员:**vbDockNone**(默认)、**vbDockLeft**、**vbDockTop**、**vbDockRight**、**vbDockBottom**或**vbDockFill**。停靠的图像忽略[**Anchors**](#anchors)。 ### DragIcon 在控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自行拖动(手动VB拖动形式,与OLE拖动不同)。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual**(0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic**(1)。 ### Enabled 决定控件是否接受鼠标输入。禁用的**Image**仍正常绘制但忽略鼠标事件。**Boolean**,默认**True**。 ### Height 控件的高度,默认以缇为单位(或以容器的**ScaleMode**单位)。**Double**。当[**Stretch**](#stretch)为**False**且赋值新[**Picture**](#picture)时,高度自动调整到图片的自然像素高度。 ### Index 当控件是控件数组的一部分时,此实例在数组中的**Long**零基索引。在非数组实例上读取**Index**会引发运行时错误343(*对象不是数组*)。运行时只读。 ### Left 从容器左边缘到控件左边缘的水平距离。**Double**。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针在控件上方时用作鼠标光标的**StdPicture**。 ### MousePointer 指针在控件上方时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### OLEDragMode 当用户开始拖动**Image**时是否自动启动OLE拖动。[**OLEDragConstants**](/official/Reference/VBRUN/Constants/OLEDragConstants)的成员:**vbOLEDragManual**(0,默认——应用程序调用[**OLEDrag**](#oledrag))或**vbOLEDragAutomatic**(1——框架自动将当前[**Picture**](#picture)复制到结果**DataObject**中)。 ### OLEDropMode **Image**如何响应到达其上的OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**(0,默认)或**vbOLEDropManual**(1)。**Image**不支持自动放置;赋值**vbOLEDropAutomatic**会引发运行时错误5(*无效的过程调用或参数*)。 ### Parent 对最终包含此控件的[**Form**](/official/Reference/VB/Form/)(或**UserControl**)的引用。只读。 ### Picture 控件渲染的**StdPicture**。**默认属性。** 语法:`Set` *object*.**Picture** = *picture* 赋值**Nothing**恢复空图片而非移除表面。在[**Stretch**](#stretch)为**False**时赋值新图片会自动调整控件到图片的自然像素尺寸;在[**Stretch**](#stretch)为**True**时保留现有矩形并将新图片缩放以适应。 ### PictureDpiScaling 当**True**时,图片的自然像素尺寸在绘制前(并被自动调整尺寸逻辑使用)乘以当前DPI缩放因子。**Boolean**,默认**False**。 ### Stretch 图片是否被缩放以填充控件矩形(**True**)或以自然尺寸渲染并自动调整控件以适应(**False**,默认)。完整规则见[拉伸和自动调整尺寸](#stretch-and-auto-sizing)。图元文件无论此设置如何始终缩放。 ### StretchMode 当[**Stretch**](#stretch)为**True**且图片被缩放时使用的重采样算法。`Image.StretchModeConstants`的成员: | 常量 | 值 | 算法 | |-------------------------------|----|--------------------------------------------------------------------------| | **vbStretchHalftone** | 0 | GDI `STRETCH_HALFTONE`(默认——良好的通用质量)。 | | **vbStretchColorOnColor** | 1 | GDI `STRETCH_COLORONCOLOR`(最快、最低质量——最近邻)。 | | **vbStretchLanczos8** | 2 | 自定义Lanczos重采样器,8瓣核(最高质量,最慢)。 | | **vbStretchLanczos3** | 3 | 自定义Lanczos重采样器,3瓣核(高质量)。 | | **vbStretchBicubic** | 4 | 自定义双三次重采样器。 | | **vbStretchBilinear** | 5 | 自定义双线性重采样器。 | Lanczos、双三次和双线性模式仅适用于实际需要调整尺寸的位图——图元文件和未缩放的位图回退到GDI模式。 ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### ToolTipText 用户悬停在控件上方时作为工具提示显示的多行**String**。 ### Top 从容器顶部到控件顶部的垂直距离。**Double**。 ### Visible 控件是否显示。**Boolean**,默认**True**。 ### WhatsThisHelpID ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。参见[**ShowWhatsThis**](#showwhatsthis)。 ::: ### Width 控件的宽度,默认以缇为单位(或以容器的**ScaleMode**单位)。**Double**。当[**Stretch**](#stretch)为**False**且赋值新[**Picture**](#picture)时,宽度自动调整到图片的自然像素宽度。 ## 方法 ### Drag 开始、完成或取消手动VB样式拖动操作。与OLE拖动不同——参见[**OLEDrag**](#oledrag)。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel**(0)、**vbBeginDrag**(1,默认)或**vbEndDrag**(2)。 ### Move 在单次调用中重新定位并可选地调整控件的尺寸。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从此**Image**发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**(或者,如果源已被预填充,则立即开始拖动)。 语法:*object*.**OLEDrag** ### Refresh 强制立即重绘**Image**在父级绘图表面上的矩形。 语法:*object*.**Refresh** ### ShowWhatsThis ::: info 保留用于与VB6兼容;目前在twinBASIC中尚未实现。 ::: 语法:*object*.**ShowWhatsThis** ### ZOrder 将**Image**带到容器内无窗口同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront**(0,默认)或**vbSendToBack**(1)。 ## 事件 ### Click 当用户单击控件矩形时引发。**默认事件。** 语法:*object*\_**Click**( ) ### DblClick 当用户双击控件矩形时引发。 语法:*object*\_**DblClick**( ) ### DragDrop 当手动VB样式拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 当手动VB样式拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### Initialize 在控件已连接到其容器的绘制周期但首次绘制之前引发一次。适用于依赖容器状态的最后一刻设置。 语法:*object*\_**Initialize**( ) ### MouseDown 当用户在控件上方按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 当光标在控件上方移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 当用户在控件上方释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag 当OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 当用户在目标控件上放置数据时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver 当OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 在拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的格式的数据时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag 在OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) --- --- url: /en/packages/vbccr/lists/imagecombo.md description: >- ImageCombo Control - VBCCR Development Manual, complete API reference based on source code --- # ImageCombo Control Provides an enhanced combo box control with icon support, where each item can be associated with an icon from an image list. ## Enumerations ### ImcStyleConstants | Constant | Value | Description | |----------|-------|-------------| | ImcStyleDropDownCombo | 0 | Drop-down combo box (editable) | | ImcStyleSimpleCombo | 1 | Simple combo box (list always visible) | | ImcStyleDropDownList | 2 | Drop-down list (selection only) | ### ImcEndEditReasonConstants | Constant | Value | Description | |----------|-------|-------------| | ImcEndEditReasonLostFocus | 1 | End edit reason: lost focus | | ImcEndEditReasonReturn | 2 | End edit reason: Enter key pressed | | ImcEndEditReasonEscape | 3 | End edit reason: Escape key pressed | | ImcEndEditReasonDropDown | 4 | End edit reason: drop-down selection | ### ImcEllipsisFormatConstants | Constant | Value | Description | |----------|-------|-------------| | ImcEllipsisFormatNone | 0 | No ellipsis | | ImcEllipsisFormatEnd | 1 | Ellipsis at the end of text | ## ImcComboItem Object Represents an item in the image combo box. ### ImcComboItem Properties #### Index ```vb Property Get Index() As Long ``` Returns the index of the item in the collection. Read-only. #### Key ```vb Property Get/Let Key() As String ``` Returns/sets the key of the item. #### Tag ```vb Property Get/Let/Set Tag() As Variant ``` Returns/sets the extra data of the item. #### Text ```vb Property Get/Let Text() As String ``` Returns/sets the text of the item. #### Image ```vb Property Get/Let Image() As Variant ``` Returns/sets the associated image index or key of the item. #### ImageIndex ```vb Property Get ImageIndex() As Long ``` Returns the associated image index of the item. Read-only. #### SelImage ```vb Property Get/Let SelImage() As Variant ``` Returns/sets the associated image index or key when the item is selected. #### SelImageIndex ```vb Property Get SelImageIndex() As Long ``` Returns the associated image index when the item is selected. Read-only. #### Indentation ```vb Property Get/Let Indentation() As Long ``` Returns/sets the indentation level of the item (in icon width units). #### Selected ```vb Property Get/Let Selected() As Boolean ``` Returns/sets whether the item is selected. #### Data ```vb Property Get/Let Data() As LongPtr ``` Returns/sets the extra numeric data of the item. ## ImcComboItems Collection Represents the collection of all items in the image combo box. ### ImcComboItems Properties and Methods #### NewEnum ```vb Public Function NewEnum() As IEnumVARIANT ``` Returns an enumerator, supporting For Each syntax. #### Add ```vb Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Text As String, Optional ByVal Image As Variant, Optional ByVal SelImage As Variant, Optional ByVal Indentation As Variant) As ImcComboItem ``` Adds an item to the collection and returns the newly created ImcComboItem object. #### Item ```vb Public Property Get Item(ByVal Index As Variant) As ImcComboItem ``` Returns an item by index or key. #### Exists ```vb Public Function Exists(ByVal Index As Variant) As Boolean ``` Checks whether an item with the specified index or key exists. #### Count ```vb Public Property Get Count() As Long ``` Returns the number of items in the collection. #### Clear ```vb Public Sub Clear() ``` Removes all items from the collection. #### Remove ```vb Public Sub Remove(ByVal Index As Variant) ``` Removes an item by index or key. ## Properties ### ControlsEnum ```vb Property Get ControlsEnum() As VBRUN.ParentControls ``` Returns the parent controls enumerator. ### Name ```vb Property Get Name() As String ``` Returns the name of the control. ### Tag ```vb Property Get/Let Tag() As String ``` Returns/sets the tag value of the control. ### Parent ```vb Property Get Parent() As Object ``` Returns the parent object of the control. ### Container ```vb Property Get/Set Container() As Object ``` Returns/sets the container of the control. ### Left ```vb Property Get/Let Left() As Single ``` Returns/sets the position of the left edge of the control. ### Top ```vb Property Get/Let Top() As Single ``` Returns/sets the position of the top edge of the control. ### Width ```vb Property Get/Let Width() As Single ``` Returns/sets the width of the control. ### Height ```vb Property Get/Let Height() As Single ``` Returns/sets the height of the control. ### Visible ```vb Property Get/Let Visible() As Boolean ``` Returns/sets whether the control is visible. ### ToolTipText ```vb Property Get/Let ToolTipText() As String ``` Returns/sets the tooltip text of the control. ### HelpContextID ```vb Property Get/Let HelpContextID() As Long ``` Returns/sets the help context ID of the control. ### WhatsThisHelpID ```vb Property Get/Let WhatsThisHelpID() As Long ``` Returns/sets the "What's This" help ID of the control. ### DragIcon ```vb Property Get/Let/Set DragIcon() As IPictureDisp ``` Returns/sets the icon displayed during drag operations. ### DragMode ```vb Property Get/Let DragMode() As Integer ``` Returns/sets the drag mode (manual or automatic). ### hWnd ```vb Property Get hWnd() As LongPtr ``` Returns the window handle of the image combo box. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Returns the window handle of the UserControl. ### hWndCombo ```vb Property Get hWndCombo() As LongPtr ``` Returns the window handle of the ComboBoxEx control. ### hWndEdit ```vb Property Get hWndEdit() As LongPtr ``` Returns the window handle of the edit box portion. ### hWndList ```vb Property Get hWndList() As LongPtr ``` Returns the window handle of the list portion. ### Font ```vb Property Get/Let/Set Font() As StdFont ``` Returns/sets the font used by the control. ### VisualStyles ```vb Property Get/Let VisualStyles() As Boolean ``` Returns/sets whether visual styles are enabled. ### Enabled ```vb Property Get/Let Enabled() As Boolean ``` Returns/sets whether the control is enabled. ### OLEDragMode ```vb Property Get/Let OLEDragMode() As VBRUN.OLEDragConstants ``` Returns/sets the OLE drag mode. ### OLEDropMode ```vb Property Get/Let OLEDropMode() As OLEDropModeConstants ``` Returns/sets the OLE drop mode. See common enumerations. ### MousePointer ```vb Property Get/Let MousePointer() As CCMousePointerConstants ``` Returns/sets the mouse pointer type. See common enumerations. ### MouseIcon ```vb Property Get/Let/Set MouseIcon() As IPictureDisp ``` Returns/sets the custom mouse icon. ### MouseTrack ```vb Property Get/Let MouseTrack() As Boolean ``` Returns/sets whether mouse enter/leave tracking is enabled. ### RightToLeft ```vb Property Get/Let RightToLeft() As Boolean ``` Returns/sets whether right-to-left layout is enabled. ### RightToLeftLayout ```vb Property Get/Let RightToLeftLayout() As Boolean ``` Returns/sets whether right-to-left layout mirroring is enabled. ### RightToLeftMode ```vb Property Get/Let RightToLeftMode() As CCRightToLeftModeConstants ``` Returns/sets the right-to-left mode. See common enumerations. ### ImageList ```vb Property Get/Set/Let ImageList() As Variant ``` Returns/sets the associated ImageList control used to provide item icons. ### Style ```vb Property Get/Let Style() As ImcStyleConstants ``` Returns/sets the combo box style. ### Locked ```vb Property Get/Let Locked() As Boolean ``` Returns/sets whether the control is locked (prevents editing and selection). ### Text ```vb Property Get/Let Text() As String ``` Returns/sets the text in the edit box. ### Default ```vb Property Get/Let Default() As String ``` Returns/sets the default value. ### Indentation ```vb Property Get/Let Indentation() As Long ``` Returns/sets the default indentation level for new items. ### ExtendedUI ```vb Property Get/Let ExtendedUI() As Boolean ``` Returns/sets whether extended user interface is used. ### MaxDropDownItems ```vb Property Get/Let MaxDropDownItems() As Integer ``` Returns/sets the maximum number of visible items in the drop-down list. ### ShowImages ```vb Property Get/Let ShowImages() As Boolean ``` Returns/sets whether item icons are displayed. ### MaxLength ```vb Property Get/Let MaxLength() As Long ``` Returns/sets the maximum number of characters that can be entered in the edit box. ### IMEMode ```vb Property Get/Let IMEMode() As CCIMEModeConstants ``` Returns/sets the input method editor mode. See common enumerations. ### EllipsisFormat ```vb Property Get/Let EllipsisFormat() As ImcEllipsisFormatConstants ``` Returns/sets the ellipsis format when text exceeds the width. ### ScrollTrack ```vb Property Get/Let ScrollTrack() As Boolean ``` Returns/sets whether the scroll bar tracks in real time. ### ComboItems ```vb Property Get ComboItems() As ImcComboItems ``` Returns the combo box items collection. Read-only. ### SelStart ```vb Property Get/Let SelStart() As Long ``` Returns/sets the starting position of the selected text. ### SelLength ```vb Property Get/Let SelLength() As Long ``` Returns/sets the length of the selected text. ### SelText ```vb Property Get/Let SelText() As String ``` Returns/sets the currently selected text. ### TopItem ```vb Property Get/Set TopItem() As ImcComboItem ``` Returns/sets the top visible item in the list. ### SelectedItem ```vb Property Get/Set SelectedItem() As ImcComboItem ``` Returns/sets the currently selected item. ### DroppedDown ```vb Property Get/Let DroppedDown() As Boolean ``` Returns/sets whether the drop-down list is expanded. ### DropDownWidth ```vb Property Get/Let DropDownWidth() As Single ``` Returns/sets the width of the drop-down list. Not supported in simple style. ### OLEDraggedItem ```vb Property Get OLEDraggedItem() As ImcComboItem ``` Returns the item currently being dragged in an OLE drag-drop operation. Read-only. ## Methods ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag operation. ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` Starts, ends, or cancels a drag operation. ### SetFocus ```vb Public Sub SetFocus() ``` Moves focus to this control. ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` Sets the control's Z-order position within its layer. ### Refresh ```vb Public Sub Refresh() ``` Forces a complete redraw of the control. ### GetItemHeight ```vb Public Function GetItemHeight() As Single ``` Returns the height of list items (taking icon height into account). ### FindItem ```vb Public Function FindItem(ByVal Text As String, Optional ByVal Index As Long, Optional ByVal Partial As Boolean, Optional ByVal Wrap As Boolean) As ImcComboItem ``` Finds an item in the list and returns a reference to it. When Partial is True, performs partial matching; when Wrap is True, continues searching from the beginning. ## Events ### Click ```vb Public Event Click() ``` Occurs when the control is clicked. ### DblClick ```vb Public Event DblClick() ``` Occurs when the control is double-clicked. ### Scroll ```vb Public Event Scroll() ``` Occurs when the list is scrolled. ### Change ```vb Public Event Change() ``` Occurs when the control content changes. ### DropDown ```vb Public Event DropDown() ``` Occurs when the drop-down list is about to expand. ### CloseUp ```vb Public Event CloseUp() ``` Occurs when the drop-down list closes. ### ItemDrag ```vb Public Event ItemDrag(ByVal Item As ImcComboItem, ByVal Button As Integer) ``` Occurs when an item initiates a drag-drop operation. ### BeginEdit ```vb Public Event BeginEdit() ``` Occurs when the user activates the drop-down list or clicks the edit box. ### EndEdit ```vb Public Event EndEdit(ByVal Changed As Boolean, ByVal NewIndex As Long, ByVal NewText As String, ByVal Reason As ImcEndEditReasonConstants) ``` Occurs when an edit operation ends. Changed indicates whether the text changed, NewIndex is the index of the newly selected item, NewText is the new text, and Reason is the end reason. ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Occurs before the KeyDown event. Set IsInputKey to mark whether the key is an input key. ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Occurs before the KeyUp event. ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` Occurs when a keyboard key is pressed. ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` Occurs when a keyboard key is released. ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` Occurs when a character key is pressed and released. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when a mouse button is pressed. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when the mouse is moved. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when a mouse button is released. ### MouseEnter ```vb Public Event MouseEnter() ``` Occurs when the mouse enters the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Occurs when the mouse leaves the control. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` Occurs on the source control after an OLE drag-drop operation is completed or canceled. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when data is dropped onto the control via an OLE drag-drop operation. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` Occurs when the mouse passes over the control during an OLE drag-drop operation. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` Occurs on the source control when the mouse cursor needs to change during an OLE drag-drop operation. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` Occurs on the source control when the drop target requests data. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` Occurs when an OLE drag-drop operation is started. ## Code Examples ### Basic Usage ```vb Private Sub Form_Load() Set ImageCombo1.ImageList = ImageList1 With ImageCombo1 .Style = ImcStyleDropDownCombo .ShowImages = True .MaxDropDownItems = 10 End With Dim Item As ImcComboItem Set Item = ImageCombo1.ComboItems.Add(, "k1", "Item One", 1, 2) Set Item = ImageCombo1.ComboItems.Add(, "k2", "Item Two", 1, 2) Set Item = ImageCombo1.ComboItems.Add(, "k3", "Sub Item", 3, 4) Item.Indentation = 1 End Sub Private Sub ImageCombo1_Click() If Not ImageCombo1.SelectedItem Is Nothing Then Debug.Print "Selected: " & ImageCombo1.SelectedItem.Text End If End Sub Private Sub ImageCombo1_EndEdit(ByVal Changed As Boolean, ByVal NewIndex As Long, ByVal NewText As String, ByVal Reason As ImcEndEditReasonConstants) If Changed Then Debug.Print "Edit completed: " & NewText End If End Sub ``` --- --- url: /en/official/Reference/WinNativeCommonCtls/ImageList.md --- # ImageList class An **ImageList** is an off-screen container for pictures, all of which are scaled to the same [**ImageWidth**](#imagewidth) × [**ImageHeight**](#imageheight) bitmap size. The control has no visible representation at run time --- its purpose is to feed icons to other controls that consume them through their [**Icons**](/en/official/Reference/WinNativeCommonCtls/ListView/#icons), [**SmallIcons**](/en/official/Reference/WinNativeCommonCtls/ListView/#smallicons), [**ColumnHeaderIcons**](/en/official/Reference/WinNativeCommonCtls/ListView/#columnheadericons), or [**ImageList**](/en/official/Reference/WinNativeCommonCtls/TreeView/#imagelist) properties. ```vb Private Sub Form_Load() ' Load some pictures via the Add method ImageList1.ListImages.Add , "doc", LoadPicture("doc.ico") ImageList1.ListImages.Add , "folder", LoadPicture("folder.ico") ImageList1.ListImages.Add , "image", LoadPicture("image.ico") ' Bind to a TreeView Set TreeView1.ImageList = ImageList1 ' Add nodes that reference images by Key TreeView1.Nodes.Add , , , "My Folder", "folder" TreeView1.Nodes.Add , , , "Report", "doc" End Sub ``` The control inherits the rectangular non-focusable base members from `BaseControlNotFocusable` --- size and position (size is irrelevant at run time since the control isn't drawn), **Name**, **Tag**, **hWnd**. It does not expose **Visible**, **Anchors**, or **Dock** in any meaningful way, and never accepts focus. ## Image size lock-in The first picture added to the list fixes its [**ImageWidth**](#imagewidth) and [**ImageHeight**](#imageheight) --- every subsequent picture is scaled to match those dimensions. The sizes can also be set explicitly *before* any image is added (typically through the design-time properties), in which case the first **Add** call honors the pre-set values rather than measuring the incoming picture. Once any image is in the list, attempting to assign [**ImageWidth**](#imagewidth) or [**ImageHeight**](#imageheight) raises run-time error 35611 with the message *"Property is read-only if image list contains images"*. To resize an image list, call [**ListImages.Clear**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages#clear) first. ## Mask color and transparency When [**UseMaskColor**](#usemaskcolor) is **True** (the default), every bitmap added through [**ListImages.Add**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages#add) is masked: pixels matching [**MaskColor**](#maskcolor) become transparent when the image is rendered into a consuming control. The default [**MaskColor**](#maskcolor) is `&H00C0C0C0` (silver), which matches the classic VB6 transparency convention. Icons (passed as `StdPicture` of type `vbPicTypeIcon`) include their own alpha mask and are unaffected by **MaskColor** / **UseMaskColor**. Setting [**ColorDepth**](#colordepth) to **ColorDepth32Bit** disables masking entirely --- the alpha channel is preserved directly. ## Binding to consumers When an **ImageList** is bound to a [**ListView**](/en/official/Reference/WinNativeCommonCtls/ListView/) (through [**Icons**](/en/official/Reference/WinNativeCommonCtls/ListView/#icons), [**SmallIcons**](/en/official/Reference/WinNativeCommonCtls/ListView/#smallicons), or [**ColumnHeaderIcons**](/en/official/Reference/WinNativeCommonCtls/ListView/#columnheadericons)) or a [**TreeView**](/en/official/Reference/WinNativeCommonCtls/TreeView/) (through [**ImageList**](/en/official/Reference/WinNativeCommonCtls/TreeView/#imagelist)), the consuming control increments the **ImageList**'s internal bound-count. While the bound-count is non-zero, attempts to call [**ListImages.Clear**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages#clear) or [**ListImages.Remove**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages#remove) raise run-time error 35617 (*"ImageList cannot be modified while another control is bound to it"*). To modify the contents, first unbind by setting the consuming control's image-list property to **Nothing**. ## Properties ### BackColor The background color used to render the image list into a target DC via [**ListImage.Draw**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImage#draw) when [**UseBackColor**](#usebackcolor) is **True**. **OLE\_COLOR**. Default: **vbWindowBackground**. ### ColorDepth The pixel depth of the underlying bitmap storage. A member of [**ImageListColorDepth**](#imagelistcolordepth). Default: **ColorDepth32Bit**. Once images have been added, this value is fixed for the life of the list --- to change it, call [**ListImages.Clear**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages#clear) first. ### hImageList The Win32 `HIMAGELIST` handle of the underlying ComCtl32 image list. **LongPtr**, read-only. Useful for advanced interoperability with raw Win32 APIs (e.g. `ImageList_Draw`, custom-draw callbacks); the handle is owned by the **ImageList** control and must not be destroyed by user code. ### ImageHeight The pixel height every image in the list is scaled to. **Long**. Default: `0` (uses the first added image's height). Assigning is allowed only while the list is empty; otherwise run-time error 35611. ### ImageWidth The pixel width every image in the list is scaled to. **Long**. Default: `0`. Same locking semantics as [**ImageHeight**](#imageheight). ### ListImages The [**ListImages**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages) collection holding the pictures. Read-only. ### MaskColor The color treated as transparent when adding bitmap pictures. **OLE\_COLOR**. Default: `&H00C0C0C0` (silver). Only honoured when [**UseMaskColor**](#usemaskcolor) is **True** and [**ColorDepth**](#colordepth) is not **ColorDepth32Bit**. ### UseBackColor Whether the image list reports a fixed background color (via `ImageList_SetBkColor`) to consuming controls. **Boolean**. Default: **False**. When **False**, the consuming control treats masked pixels as transparent. ### UseMaskColor Whether [**MaskColor**](#maskcolor) is treated as transparent when bitmaps are added. **Boolean**. Default: **True**. ## Methods ### Overlay Composes two list-images into a single overlay picture. The first image is drawn, then the second is drawn over the top with its mask applied. Syntax: *object*.**Overlay** ( *Key1*, *Key2* ) **As StdPicture** *Key1* : The **Index** or **Key** of the bottom image. *Key2* : The **Index** or **Key** of the top image. Returns an **StdPicture** of type **vbPicTypeIcon** suitable for direct rendering or for use elsewhere --- note this is a one-off snapshot, not a reference into the image list. The returned icon is destroyed when the **StdPicture** goes out of scope. ## ImageListColorDepth Determines the pixel depth of the bitmap storage in an [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/). Declared on the **ImageList** class. | Member | Value | Description | |-------------------------|-------|--------------------------------------------------------------| | **ColorDepth4Bit** | 4 | 16-color palette. | | **ColorDepth8Bit** | 8 | 256-color palette. | | **ColorDepth16Bit** | 16 | High color (RGB565). | | **ColorDepth24Bit** | 24 | True color (RGB888), no alpha. | | **ColorDepth32Bit** | 32 | True color with full alpha channel; masking is disabled at this depth. | ## See Also * [ListImage](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImage) -- one picture in the list * [ListImages](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages) -- the collection holding the pictures * [ImlDrawConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) -- the *Style* parameter for [**ListImage.Draw**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImage#draw) * [ListView](/en/official/Reference/WinNativeCommonCtls/ListView/) -- a typical consumer through [**Icons**](/en/official/Reference/WinNativeCommonCtls/ListView/#icons), [**SmallIcons**](/en/official/Reference/WinNativeCommonCtls/ListView/#smallicons), [**ColumnHeaderIcons**](/en/official/Reference/WinNativeCommonCtls/ListView/#columnheadericons) * [TreeView](/en/official/Reference/WinNativeCommonCtls/TreeView/) -- a typical consumer through [**ImageList**](/en/official/Reference/WinNativeCommonCtls/TreeView/#imagelist) * [ControlTypeConstants](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) -- where **vbImageList** lives --- --- url: /zh/official/Reference/WinNativeCommonCtls/ImageList.md --- # ImageList 类 **ImageList** 是图片的离屏容器,所有图片缩放到相同的 [**ImageWidth**](#imagewidth) × [**ImageHeight**](#imageheight) 位图尺寸。该控件在运行时没有可见表示 --- 其目的是通过 [**Icons**](/official/Reference/WinNativeCommonCtls/ListView/#icons)、[**SmallIcons**](/official/Reference/WinNativeCommonCtls/ListView/#smallicons)、[**ColumnHeaderIcons**](/official/Reference/WinNativeCommonCtls/ListView/#columnheadericons) 或 [**ImageList**](/official/Reference/WinNativeCommonCtls/TreeView/#imagelist) 属性为消费控件提供图标。 ```vb Private Sub Form_Load() ' Load some pictures via the Add method ImageList1.ListImages.Add , "doc", LoadPicture("doc.ico") ImageList1.ListImages.Add , "folder", LoadPicture("folder.ico") ImageList1.ListImages.Add , "image", LoadPicture("image.ico") ' Bind to a TreeView Set TreeView1.ImageList = ImageList1 ' Add nodes that reference images by Key TreeView1.Nodes.Add , , , "My Folder", "folder" TreeView1.Nodes.Add , , , "Report", "doc" End Sub ``` 控件从 `BaseControlNotFocusable` 继承矩形不可聚焦基类成员 --- 大小和位置(运行时尺寸无关紧要,因为控件不被绘制)、**Name**、**Tag**、**hWnd**。它不以任何有意义的方式暴露 **Visible**、**Anchors** 或 **Dock**,且从不接受焦点。 ## 图像尺寸锁定 添加到列表中的第一张图片固定其 [**ImageWidth**](#imagewidth) 和 [**ImageHeight**](#imageheight) --- 后续每张图片缩放以匹配这些尺寸。尺寸也可以在添加任何图像*之前*显式设置(通常通过设计时属性),在这种情况下第一次 **Add** 调用会遵循预设值而非测量传入图片。 一旦列表中有任何图像,尝试赋值 [**ImageWidth**](#imagewidth) 或 [**ImageHeight**](#imageheight) 会引发运行时错误 35611,消息为 *"Property is read-only if image list contains images"*。要调整图像列表大小,请先调用 [**ListImages.Clear**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages#clear)。 ## 蒙版颜色和透明度 当 [**UseMaskColor**](#usemaskcolor) 为 **True**(默认)时,通过 [**ListImages.Add**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages#add) 添加的每个位图会被蒙版处理:匹配 [**MaskColor**](#maskcolor) 的像素在图像渲染到消费控件时变为透明。默认 [**MaskColor**](#maskcolor) 为 `&H00C0C0C0`(银色),与经典VB6透明约定匹配。图标(以 `vbPicTypeIcon` 类型的 `StdPicture` 传入)包含自己的alpha蒙版,不受 **MaskColor** / **UseMaskColor** 影响。 将 [**ColorDepth**](#colordepth) 设为 **ColorDepth32Bit** 会完全禁用蒙版 --- alpha通道直接保留。 ## 绑定到消费者 当 **ImageList** 绑定到 [**ListView**](/official/Reference/WinNativeCommonCtls/ListView/)(通过 [**Icons**](/official/Reference/WinNativeCommonCtls/ListView/#icons)、[**SmallIcons**](/official/Reference/WinNativeCommonCtls/ListView/#smallicons) 或 [**ColumnHeaderIcons**](/official/Reference/WinNativeCommonCtls/ListView/#columnheadericons))或 [**TreeView**](/official/Reference/WinNativeCommonCtls/TreeView/)(通过 [**ImageList**](/official/Reference/WinNativeCommonCtls/TreeView/#imagelist))时,消费控件递增 **ImageList** 的内部绑定计数。绑定计数非零时,尝试调用 [**ListImages.Clear**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages#clear) 或 [**ListImages.Remove**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages#remove) 引发运行时错误 35617(*"ImageList cannot be modified while another control is bound to it"*)。要修改内容,先将消费控件的图像列表属性设为 **Nothing** 以解除绑定。 ## 属性 ### BackColor 当 [**UseBackColor**](#usebackcolor) 为 **True** 时,通过 [**ListImage.Draw**](/official/Reference/WinNativeCommonCtls/ImageList/ListImage#draw) 将图像列表渲染到目标DC时使用的背景颜色。**OLE\_COLOR**。默认:**vbWindowBackground**。 ### ColorDepth 底层位图存储的像素深度。[**ImageListColorDepth**](#imagelistcolordepth) 的成员。默认:**ColorDepth32Bit**。一旦添加了图像,此值在列表生命周期内固定 --- 要更改,请先调用 [**ListImages.Clear**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages#clear)。 ### hImageList 底层ComCtl32图像列表的Win32 `HIMAGELIST` 句柄。**LongPtr**,只读。用于与原始Win32 API高级互操作(如 `ImageList_Draw`、自定义绘制回调);该句柄由 **ImageList** 控件拥有,不得被用户代码销毁。 ### ImageHeight 列表中每张图像缩放到的像素高度。**Long**。默认:`0`(使用第一张添加图像的高度)。仅在列表为空时允许赋值;否则运行时错误 35611。 ### ImageWidth 列表中每张图像缩放到的像素宽度。**Long**。默认:`0`。与 [**ImageHeight**](#imageheight) 相同的锁定语义。 ### ListImages 持有图片的 [**ListImages**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages) 集合。只读。 ### MaskColor 添加位图图片时视为透明的颜色。**OLE\_COLOR**。默认:`&H00C0C0C0`(银色)。仅在 [**UseMaskColor**](#usemaskcolor) 为 **True** 且 [**ColorDepth**](#colordepth) 不为 **ColorDepth32Bit** 时生效。 ### UseBackColor 图像列表是否通过 `ImageList_SetBkColor` 向消费控件报告固定背景颜色。**Boolean**。默认:**False**。为 **False** 时,消费控件将蒙版像素视为透明。 ### UseMaskColor 添加位图时是否将 [**MaskColor**](#maskcolor) 视为透明。**Boolean**。默认:**True**。 ## 方法 ### Overlay 将两个列表图像合成为单个叠加图片。先绘制第一张图像,然后在其上绘制第二张并应用其蒙版。 语法:*object*.**Overlay**(*Key1*, *Key2*)**As StdPicture** *Key1* : 底层图像的 **Index** 或 **Key**。 *Key2* : 顶层图像的 **Index** 或 **Key**。 返回一个 **vbPicTypeIcon** 类型的 **StdPicture**,适合直接渲染或在其他地方使用 --- 注意这是一次性快照,不是图像列表中的引用。返回的图标在 **StdPicture** 超出作用域时被销毁。 ## ImageListColorDepth 确定 [**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/) 中位图存储的像素深度。在 **ImageList** 类上声明。 | 成员 | 值 | 描述 | |-------------------------|-------|--------------------------------------------------------------| | **ColorDepth4Bit** | 4 | 16色调色板。 | | **ColorDepth8Bit** | 8 | 256色调色板。 | | **ColorDepth16Bit** | 16 | 高彩色(RGB565)。 | | **ColorDepth24Bit** | 24 | 真彩色(RGB888),无alpha。 | | **ColorDepth32Bit** | 32 | 带完整alpha通道的真彩色;此深度下禁用蒙版。 | ## 另见 * [ListImage](/official/Reference/WinNativeCommonCtls/ImageList/ListImage) --- 列表中的一张图片 * [ListImages](/official/Reference/WinNativeCommonCtls/ImageList/ListImages) --- 持有图片的集合 * [ImlDrawConstants](/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) --- [**ListImage.Draw**](/official/Reference/WinNativeCommonCtls/ImageList/ListImage#draw) 的 *Style* 参数 * [ListView](/official/Reference/WinNativeCommonCtls/ListView/) --- 通过 [**Icons**](/official/Reference/WinNativeCommonCtls/ListView/#icons)、[**SmallIcons**](/official/Reference/WinNativeCommonCtls/ListView/#smallicons)、[**ColumnHeaderIcons**](/official/Reference/WinNativeCommonCtls/ListView/#columnheadericons) 的典型消费者 * [TreeView](/official/Reference/WinNativeCommonCtls/TreeView/) --- 通过 [**ImageList**](/official/Reference/WinNativeCommonCtls/TreeView/#imagelist) 的典型消费者 * [ControlTypeConstants](/official/Reference/VBRUN/Constants/ControlTypeConstants) --- **vbImageList** 所在位置 --- --- url: /en/packages/vbccr/system/imagelist.md description: >- ImageList Control - VBCCR Development Manual, Complete API Reference Based on Source Code --- # ImageList Control Wraps the ImageList control, used to store and manage image collections for reference by other controls. ## Enumerations ### ImlImageSizeConstants | Constant | Value | Description | |------|-----|------| | imlSmall | 0 | Small icons (16×16) | | imlLarge | 1 | Large icons (32×32) | | imlCustom | 2 | Custom size | ### CCBackStyleConstants See Common Enumerations. ## Properties ### ImageWidth ```vb Property Get ImageWidth() As Long Property Let ImageWidth(ByVal Value As Long) ``` Image width (pixels). ### ImageHeight ```vb Property Get ImageHeight() As Long Property Let ImageHeight(ByVal Value As Long) ``` Image height (pixels). ### ImageSize ```vb Property Get ImageSize() As ImlImageSizeConstants Property Let ImageSize(ByVal Value As ImlImageSizeConstants) ``` Preset image size. Setting this property automatically adjusts ImageWidth and ImageHeight. ### ColorDepth ```vb Property Get ColorDepth() As Long Property Let ColorDepth(ByVal Value As Long) ``` Color depth. Supports 4, 8, 16, 24, 32 bits. Requires comctl32.dll 6.0 or later. ### MaskColor ```vb Property Get MaskColor() As OLE_COLOR Property Let MaskColor(ByVal Value As OLE_COLOR) ``` Mask color. ### UseMaskColor ```vb Property Get UseMaskColor() As Boolean Property Let UseMaskColor(ByVal Value As Boolean) ``` Whether to use mask color. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### hImageList ```vb Property Get hImageList() As LongPtr ``` Image list handle. Read-only. ### ListImages ```vb Property Get ListImages() As ImlListImages ``` Image collection. ### Name ```vb Property Get Name() As String ``` Control name. Read-only. ### Tag ```vb Property Get Tag() As Variant Property Let Tag(ByVal Value As Variant) Property Set Tag(ByVal Value As Variant) ``` Custom data. ### Parent ```vb Property Get Parent() As Object ``` Parent object. Read-only. ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` Container object. ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` Left margin. ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` Top margin. ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` Width (used at design time). ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` Height (used at design time). ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` Visibility (used at design time). ### hWnd ```vb Property Get hWnd() As LongPtr ``` Window handle. Read-only. ## Methods ### Refresh ```vb Sub Refresh() ``` Forces a repaint. ### CreateIcon ```vb Function CreateIcon(ByVal ImageIndex As Long) As IPictureDisp ``` Creates an icon from the specified image. ### CreateBitmap ```vb Function CreateBitmap(ByVal ImageIndex As Long) As IPictureDisp ``` Creates a bitmap from the specified image. Requires comctl32.dll 6.0 or later. ### Overlay ```vb Function Overlay(ByVal ImageIndex1 As Long, ByVal ImageIndex2 As Long) As IPictureDisp ``` Overlays two images and returns the resulting image. ### AboutBox ```vb Sub AboutBox() ``` Displays the About dialog. ## Sub-objects ### ListImage (ImlListImage) Represents a single image in the image list. #### Properties | Property | Type | Access | Description | |------|------|------|------| | Index | Long | Read-only | Index in the collection | | Key | String | Read/Write | Key in the collection | | Tag | Variant | Read/Write | Custom data | | Picture | IPictureDisp | Read/Write | Image | | MaskPicture | IPictureDisp | Read/Write | Mask image | | Overlay | Boolean | Read/Write | Whether this is an overlay image | | OverlaySourceIndex | Long | Read/Write | Overlay source index | | ExtractIcon | IPictureDisp | Read-only | Extract icon | | ExtractBitmap | IPictureDisp | Read-only | Extract bitmap | ### ListImages (ImlListImages) Image collection object. #### Properties | Property | Type | Access | Description | |------|------|------|------| | Item(ByVal Index As Variant) | ImlListImage | Read-only | Get image by index or key | | Count | Long | Read-only | Number of images | #### Methods | Method | Description | |------|------| | Add(\[Index], \[Key], \[Picture], \[MaskPicture]) As ImlListImage | Add an image | | Exists(ByVal Index As Variant) As Boolean | Check if an image exists | | Clear | Clear all images | | Remove(ByVal Index As Variant) | Remove the specified image | ## Code Examples ```vb ' Set image size and add images With ImageList1 .ImageSize = imlSmall .ListImages.Add , "open", LoadPicture("open.ico") .ListImages.Add , "save", LoadPicture("save.ico") .ListImages.Add , "exit", LoadPicture("exit.ico") End With ' Reference image by key Set cmdOpen.Picture = ImageList1.ListImages("open").ExtractIcon ' Create overlay image ImageList1.ListImages.Add , "overlay1", LoadPicture("ov1.ico") ImageList1.ListImages("overlay1").Overlay = True ImageList1.ListImages("overlay1").OverlaySourceIndex = 1 ' Use Overlay method to overlay two images Set imgOverlay = ImageList1.Overlay(1, 2) ' Iterate through all images Dim img As ImlListImage For Each img In ImageList1.ListImages Debug.Print img.Index; img.Key Next img ``` --- --- url: /en/official/Reference/VBA/Information/IMEStatus.md --- # IMEStatus Returns a [**VbIMEStatus**](/en/official/Reference/VBA/Constants/VbIMEStatus) value specifying the current Input Method Editor (IME) mode of Microsoft Windows; available in East Asian versions only. Syntax: **IMEStatus** \[ **()** ] The return value is one of the [**VbIMEStatus**](/en/official/Reference/VBA/Constants/VbIMEStatus) constants. Locales differ in which constants can be returned: * **Japanese**: any of `vbIMEModeNoControl`, `vbIMEModeOn`, `vbIMEModeOff`, `vbIMEModeDisable`, `vbIMEModeHiragana`, `vbIMEModeKatakana`, `vbIMEModeKatakanaHalf`, `vbIMEModeAlphaFull`, `vbIMEModeAlpha`. * **Korean**: `vbIMEModeNoControl`, `vbIMEModeAlphaFull`, `vbIMEModeAlpha`, `vbIMEModeHangulFull`, `vbIMEModeHangul`. * **Chinese**: `vbIMEModeNoControl`, `vbIMEModeOn`, `vbIMEModeOff`. ### See Also * [VbIMEStatus](/en/official/Reference/VBA/Constants/VbIMEStatus) enumeration --- --- url: /zh/official/Reference/VBA/Information/IMEStatus.md --- # IMEStatus 返回一个[**VbIMEStatus**](/official/Reference/VBA/Constants/VbIMEStatus)值,指定Microsoft Windows当前输入法编辑器(IME)的模式;仅在东亚版本中可用。 语法:**IMEStatus** \[ **()** ] 返回值是[**VbIMEStatus**](/official/Reference/VBA/Constants/VbIMEStatus)常量之一。不同区域设置可返回的常量不同: * **日语**:`vbIMEModeNoControl`、`vbIMEModeOn`、`vbIMEModeOff`、`vbIMEModeDisable`、`vbIMEModeHiragana`、`vbIMEModeKatakana`、`vbIMEModeKatakanaHalf`、`vbIMEModeAlphaFull`、`vbIMEModeAlpha`中的任意一个。 * **韩语**:`vbIMEModeNoControl`、`vbIMEModeAlphaFull`、`vbIMEModeAlpha`、`vbIMEModeHangulFull`、`vbIMEModeHangul`。 * **中文**:`vbIMEModeNoControl`、`vbIMEModeOn`、`vbIMEModeOff`。 ### 另请参阅 * [VbIMEStatus](/official/Reference/VBA/Constants/VbIMEStatus)枚举 --- --- url: /en/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants.md --- # ImlDrawConstants Flag combinations passed to the *Style* parameter of [**ListImage.Draw**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImage#draw). Multiple flags can be **Or**-combined to compose render styles. ```vb ' Draw a small icon with the focus rectangle overlaid: ImageList1.ListImages("doc").Draw _ PictureBox1.hDC, 0, 0, _ ImlDrawTransparent Or ImlDrawFocus ``` | Member | Value | Description | |---------------------------|-------|--------------------------------------------------------------------------| | **ImlDrawNormal** | 1 | Render in the normal state (no overlays). | | **ImlDrawTransparent** | 2 | Honour the image's mask / alpha --- transparent pixels stay transparent. | | **ImlDrawSelected** | 4 | Render with the selection-color overlay (typically a blue tint). | | **ImlDrawFocus** | 8 | Render with the focus-rectangle overlay (dotted border). | | **ImlDrawNoMask** | 16 | Bypass the mask --- draw the entire bitmap including pixels that would normally be transparent. | ## See Also * [ImageList](/en/official/Reference/WinNativeCommonCtls/ImageList/) -- the parent control * [ListImage.Draw](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImage#draw) -- the consuming method --- --- url: /zh/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants.md --- # ImlDrawConstants 传递给 [**ListImage.Draw**](/official/Reference/WinNativeCommonCtls/ImageList/ListImage#draw) 的 *Style* 参数的标志组合。多个标志可通过 **Or** 运算组合以构成渲染样式。 ```vb ' Draw a small icon with the focus rectangle overlaid: ImageList1.ListImages("doc").Draw _ PictureBox1.hDC, 0, 0, _ ImlDrawTransparent Or ImlDrawFocus ``` | 成员 | 值 | 描述 | |---------------------------|-------|--------------------------------------------------------------------------| | **ImlDrawNormal** | 1 | 以正常状态渲染(无覆盖层)。 | | **ImlDrawTransparent** | 2 | 遵循图像的遮罩/Alpha —— 透明像素保持透明。 | | **ImlDrawSelected** | 4 | 以选中颜色覆盖层渲染(通常为蓝色色调)。 | | **ImlDrawFocus** | 8 | 以焦点矩形覆盖层渲染(虚线边框)。 | | **ImlDrawNoMask** | 16 | 忽略遮罩 —— 绘制整个位图,包括通常为透明的像素。 | ## 另见 * [ImageList](/official/Reference/WinNativeCommonCtls/ImageList/) —— 父控件 * [ListImage.Draw](/official/Reference/WinNativeCommonCtls/ImageList/ListImage#draw) —— 使用该枚举的方法 --- --- url: /en/official/Reference/Core/Imp.md --- # Imp operator Used to perform a bitwise implication on two expressions. *expression1* **Imp** *expression2* is **False** only when *expression1* is **True** and *expression2* is **False**; in every other non-**Null** case the result is **True**. Syntax: > *result* **=** *expression1* **Imp** *expression2* *result* : Any numeric variable. *expression1*, *expression2* : Any expressions. The following table illustrates how *result* is determined: | If *expression1* is | And *expression2* is | The *result* is | |:-----|:-----|:-----| | **True** | **True** | **True** | | **True** | **False** | **False** | | **True** | **Null** | **Null** | | **False** | **True** | **True** | | **False** | **False** | **True** | | **False** | **Null** | **True** | | **Null** | **True** | **True** | | **Null** | **False** | **Null** | | **Null** | **Null** | **Null** | The **Imp** operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in *result* according to the following table: | If bit in *expression1* is | And bit in *expression2* is | The *result* is | |:-----:|:-----:|:-----:| | 0 | 0 | 1 | | 0 | 1 | 1 | | 1 | 0 | 0 | | 1 | 1 | 1 | ::: info **Imp** always evaluates *both* operands. ::: ### Example This example uses the **Imp** operator to perform a logical implication on two expressions. ```vb Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B Imp B > C ' Returns True. MyCheck = A > B Imp C > B ' Returns False. MyCheck = B > A Imp C > B ' Returns True. MyCheck = B > A Imp C > D ' Returns True. MyCheck = C > D Imp B > A ' Returns Null. MyCheck = B Imp A ' Returns -1 (bitwise comparison). ``` ### See Also * [**Eqv** operator](/en/official/Reference/Core/Eqv) * [**Xor** operator](/en/official/Reference/Core/Xor) * [**And** operator](/en/official/Reference/Core/And) * [**Or** operator](/en/official/Reference/Core/Or) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Imp.md --- # Imp 运算符 用于对两个表达式执行按位蕴涵运算。*expression1* **Imp** *expression2* 仅当 *expression1* 为 **True** 且 *expression2* 为 **False** 时为 **False**;在所有其他非 **Null** 情况下结果为 **True**。 语法: > *result* **=** *expression1* **Imp** *expression2* *result* : 任意数值变量。 *expression1*, *expression2* : 任意表达式。 下表说明了 *result* 的确定方式: | 如果 *expression1* 为 | 且 *expression2* 为 | 则 *result* 为 | |:-----|:-----|:-----| | **True** | **True** | **True** | | **True** | **False** | **False** | | **True** | **Null** | **Null** | | **False** | **True** | **True** | | **False** | **False** | **True** | | **False** | **Null** | **True** | | **Null** | **True** | **True** | | **Null** | **False** | **Null** | | **Null** | **Null** | **Null** | **Imp** 运算符对两个数值表达式中相同位置的位执行按位比较,并根据下表在 *result* 中设置相应的位: | 如果 *expression1* 中的位为 | 且 *expression2* 中的位为 | 则 *result* 为 | |:-----:|:-----:|:-----:| | 0 | 0 | 1 | | 0 | 1 | 1 | | 1 | 0 | 0 | | 1 | 1 | 1 | ::: info **Imp** 总是求值*两个*操作数。 ::: ### 示例 本示例使用 **Imp** 运算符对两个表达式执行逻辑蕴涵运算。 ```vb Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B Imp B > C ' Returns True. MyCheck = A > B Imp C > B ' Returns False. MyCheck = B > A Imp C > B ' Returns True. MyCheck = B > A Imp C > D ' Returns True. MyCheck = C > D Imp B > A ' Returns Null. MyCheck = B Imp A ' Returns -1 (bitwise comparison). ``` ### 另请参阅 * [**Eqv** 运算符](/official/Reference/Core/Eqv) * [**Xor** 运算符](/official/Reference/Core/Xor) * [**And** 运算符](/official/Reference/Core/And) * [**Or** 运算符](/official/Reference/Core/Or) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Reference/Core/Implements.md --- # Implements Specifies an interface or class that will be implemented in the [class](/en/official/Reference/Core/Class) in which it appears. Syntax: > **Implements** { *InterfaceName* | *ClassName* } \[ **,** { *InterfaceName* | *ClassName* } ]… *InterfaceName* : The name of an interface --- either an [**Interface**](/en/official/Reference/Core/Interface) block defined in twinBASIC, or an interface in a referenced type library --- whose members will be implemented by the corresponding members in the class. *ClassName* : The name of a class whose default interface will be implemented. A single **Implements** statement can list several interfaces or classes separated by commas; this is equivalent to writing one **Implements** statement per name. Classic VBA requires a separate statement for each. An *interface* is a collection of prototypes representing the members (methods and properties) that the interface encapsulates; that is, it contains only the declarations for the member procedures. A *class* provides an implementation of all the methods and properties of one or more interfaces. Classes provide the code used when each function is called by a controller of the class. All classes implement at least one interface, which is considered the default interface of the class. Any member that isn't explicitly a member of an implemented interface is implicitly a member of the default interface. When a class implements an interface, the class provides its own versions of all the **Public** procedures specified in the interface. In addition to providing a mapping between the interface prototypes and the implementing procedures, the **Implements** statement causes the class to accept COM `QueryInterface` calls for the specified interface ID. When implementing an interface or class, all the **Public** procedures involved must be included. A missing member in an implementation of an interface or class causes an error. When code is not placed in one of the implemented procedures, raise the appropriate error (`Const E_NOTIMPL = &H80004001`) so a user of the implementation understands that a member is not implemented. The **Implements** statement can't appear in a standard module --- it is valid only in a [**Class**](/en/official/Reference/Core/Class) block. ### twinBASIC enhancements twinBASIC extends classic VBA's **Implements** in several ways. See [Inheritance](/en/official/Features/Language/Inheritance) for the full discussion; the headline differences: * **Comma-separated list** --- one **Implements** statement can name multiple interfaces or classes, e.g. `Implements IFoo, IBar, IBaz`. Classic VBA requires a separate **Implements** statement for each. * **Inherited interfaces** --- `Implements` works directly on a derived interface (e.g. `Implements IFoo2` where `Interface IFoo2 Extends IFoo`). The class need not name `IFoo` separately; `QueryInterface` for the base is satisfied automatically. Classic VBA does not support implementing derived interfaces. * **Multiple-implementation form** --- a single member can implement methods on several interfaces at once via `Implements <iface1>.<member>, <iface2>.<member>, …` after the procedure header. This is useful when several interfaces declare the same member and one body should satisfy all of them. * **`As Any` parameters** --- interfaces declared with `As Any` parameters can be implemented (substituting `As LongPtr` for `As Any` in the implementing class). Classic VBA rejects this. ::: info Use `Private` (or `Friend`) on the implementing procedures so that the interface methods don't also become part of the implementing class's *default* interface. The conventional naming pattern is `<InterfaceName>_<MemberName>`. ::: ### Example The following example shows how to use the **Implements** statement to make a set of declarations available to multiple classes. By sharing the declarations through the **Implements** statement, neither class has to make any declarations itself. The example also shows how use of an interface supports abstraction: a strongly-typed variable can be declared by using the interface type. It can then be assigned objects of different class types that implement the interface. The interface declarations are in a class called `PersonalData`: ```vb Public Name As String Public Address As String ``` The code supporting the customer data is in a class module called `Customer`. Note that the `PersonalData` interface is implemented with members that are named with the interface name `PersonalData_` as a prefix. ```vb Implements PersonalData ' For PersonalData implementation Private m_name As String Private m_address As String ' Customer-specific Public CustomerAgentId As Long ' PersonalData implementation Private Property Let PersonalData_Name(ByVal RHS As String) m_name = RHS End Property Private Property Get PersonalData_Name() As String PersonalData_Name = m_name End Property Private Property Let PersonalData_Address(ByVal RHS As String) m_address = RHS End Property Private Property Get PersonalData_Address() As String PersonalData_Address = m_address End Property Private Sub Class_Initialize() m_name = "[customer name]" m_address = "[customer address]" CustomerAgentId = 0 End Sub ``` A second class `Supplier` implements the same interface independently, with its own state and `Class_Initialize`. Code that needs name/address access can declare a variable as the interface type and accept either: ```vb Private m_pd As PersonalData Public Property Set PD(Data As PersonalData) Set m_pd = Data End Property ``` `m_pd` can only access the members of `PersonalData`. Customer-specific or Supplier-specific members are not visible through it --- assigning an object to a variable declared by interface type provides polymorphic behavior. ### See Also * [**Interface** statement](/en/official/Reference/Core/Interface) * [**CoClass** statement](/en/official/Reference/Core/CoClass) * [**Class** statement](/en/official/Reference/Core/Class) * [Inheritance](/en/official/Features/Language/Inheritance) * [Interfaces and CoClasses](/en/official/Features/Language/Interfaces-CoClasses) --- --- url: /zh/official/Reference/Core/Implements.md --- # Implements 指定将在其出现的[类](/official/Reference/Core/Class)中实现的接口或类。 语法: > **Implements** { *InterfaceName* | *ClassName* } \[ **,** { *InterfaceName* | *ClassName* } ]… *InterfaceName* : 接口的名称——twinBASIC中定义的 [**Interface**](/official/Reference/Core/Interface) 块,或引用类型库中的接口——其成员将由类中对应的成员实现。 *ClassName* : 将实现其默认接口的类的名称。 单个 **Implements** 语句可以用逗号分隔列出多个接口或类;这等价于为每个名称写一条 **Implements** 语句。经典VBA要求每条语句单独写。 *接口*是表示接口封装的成员(方法和属性)的原型集合;即它只包含成员过程的声明。*类*提供一个或多个接口的所有方法和属性的实现。类提供当每个函数被类控制器调用时使用的代码。所有类至少实现一个接口,该接口被视为类的默认接口。任何未显式为已实现接口成员的成员隐式为默认接口的成员。 当类实现接口时,类提供接口中指定的所有 **Public** 过程的自身版本。除了提供接口原型与实现过程之间的映射外,**Implements** 语句还使类接受指定接口ID的COM `QueryInterface` 调用。 实现接口或类时,必须包含所有 **Public** 过程。接口或类实现中缺少成员会导致错误。当未在某个已实现的过程中放置代码时,应引发适当的错误(`Const E_NOTIMPL = &H80004001`),以便实现的使用者知道某个成员未实现。 **Implements** 语句不能出现在标准模块中——它仅在 [**Class**](/official/Reference/Core/Class) 块中有效。 ### twinBASIC增强功能 twinBASIC以多种方式扩展了经典VBA的 **Implements**。参见[继承](/official/Features/Language/Inheritance)获取完整讨论;主要差异: * **逗号分隔列表**——一条 **Implements** 语句可以命名多个接口或类,如 `Implements IFoo, IBar, IBaz`。经典VBA要求每个接口单独一条 **Implements** 语句。 * **继承的接口**——`Implements` 直接作用于派生接口(如 `Implements IFoo2`,其中 `Interface IFoo2 Extends IFoo`)。类不需要单独命名 `IFoo`;基接口的 `QueryInterface` 自动满足。经典VBA不支持实现派生接口。 * **多重实现形式**——单个成员可以通过过程头部后的 `Implements <iface1>.<member>, <iface2>.<member>, …` 同时实现多个接口的方法。当多个接口声明相同成员且一个函数体应满足所有接口时,这很有用。 * **`As Any` 参数**——使用 `As Any` 参数声明的接口可以被实现(在实现类中用 `As LongPtr` 替换 `As Any`)。经典VBA拒绝此用法。 ::: info 在实现过程中使用 `Private`(或 `Friend`),以便接口方法不会同时成为实现类的*默认*接口的一部分。传统命名模式为 `<InterfaceName>_<MemberName>`。 ::: ### 示例 以下示例展示如何使用 **Implements** 语句使一组声明可用于多个类。通过 **Implements** 语句共享声明,两个类都不需要自己进行任何声明。示例还展示了接口的使用如何支持抽象:可以使用接口类型声明强类型变量。然后可以为其分配实现该接口的不同类类型的对象。 接口声明在一个名为 `PersonalData` 的类中: ```vb Public Name As String Public Address As String ``` 支持客户数据的代码在一个名为 `Customer` 的类模块中。注意 `PersonalData` 接口的实现使用了接口名 `PersonalData_` 作为前缀命名的成员。 ```vb Implements PersonalData ' For PersonalData implementation Private m_name As String Private m_address As String ' Customer-specific Public CustomerAgentId As Long ' PersonalData implementation Private Property Let PersonalData_Name(ByVal RHS As String) m_name = RHS End Property Private Property Get PersonalData_Name() As String PersonalData_Name = m_name End Property Private Property Let PersonalData_Address(ByVal RHS As String) m_address = RHS End Property Private Property Get PersonalData_Address() As String PersonalData_Address = m_address End Property Private Sub Class_Initialize() m_name = "[customer name]" m_address = "[customer address]" CustomerAgentId = 0 End Sub ``` 第二个类 `Supplier` 独立实现相同的接口,拥有自己的状态和 `Class_Initialize`。需要名称/地址访问的代码可以将变量声明为接口类型并接受任一类: ```vb Private m_pd As PersonalData Public Property Set PD(Data As PersonalData) Set m_pd = Data End Property ``` `m_pd` 只能访问 `PersonalData` 的成员。Customer特有或Supplier特有的成员通过它不可见——将对象赋值给按接口类型声明的变量提供了多态行为。 ### 另请参阅 * [**Interface** 语句](/official/Reference/Core/Interface) * [**CoClass** 语句](/official/Reference/Core/CoClass) * [**Class** 语句](/official/Reference/Core/Class) * [继承](/official/Features/Language/Inheritance) * [接口与CoClass](/official/Features/Language/Interfaces-CoClasses) --- --- url: /en/official/Features/Packages/Importing-a-package-from-a-TWINPACK-file.md --- # Importing a package from a TWINPACK file To import a package directly from a TWINPACK file (instead of using TWINSERV), follow these steps. * open the project from which you want to use a package * open the `Settings` file within it * navigate to the References section * select the 'Available Packages' button ![image](/assets/d9f1e4d9-1805-47e5-93aa-251151b4e914.Cqb69x_o.png) * press the 'Import from file...' button: ![image](/assets/e35d5955-9e70-4d6e-abd7-748558da75ba.D3L2kNPh.png) * choose the TWINPACK file you want to import, and then it should appear in the references list (ticked): ![image](/assets/4e4b8e4d-2a1c-42e5-8f4b-5a9b3f523ee8.ZfPs8_0L.png) * Save the `Settings` and if needed restart the compiler Now you're ready to use the package! In the example shown above I added a reference to the CSharpishStringFormater package, and I can now confirm that I can access components from the package in my code: ![image](Images/e9a3fd21-8e6a-4485-b52c-0c041600826b.png) --- --- url: /en/official/Features/Packages/Importing-a-package-from-TWINSERV.md --- # Importing a package from TWINSERV Open the project from which you want to use a package, open the `Settings` file within it and navigate to the References section. Select the 'Available Packages' button, and all packages that are on the server should be shown: ![432410211-d9f1e4d9-1805-47e5-93aa-251151b4e914](Images/e749e10f-e361-4f15-a977-d756fcb3b5dd.png) If you tick one of the available packages, it will be downloaded and imported into the project: ![432416432-4e4b8e4d-2a1c-42e5-8f4b-5a9b3f523ee8](Images/f2fd8374-fe46-40b0-8c66-2443df4dc5b3.png) Once you're finished, save and close the Settings file which will cause the compiler to be restarted. Now you're ready to use the package! In the example shown above I added a reference to the CSharpishStringFormater package, and I can now confirm that I can access components from the package in my code: ![432417844-e9a3fd21-8e6a-4485-b52c-0c041600826b](/assets/e2a65dfe-4a9d-4524-b6d6-7a6d1bc35cdb.Bv2Q-O97.png) Note: If you have any PRIVATE packages that you have published, they are only available when signed in. If you are not already signed in, you will see a warning link that you can click to login: ![image](/assets/0fa1272d-41d6-4d0f-b19c-f47f24a47c4d.CMaXZ-xh.png) After logging in, press the 'Available' button again to refresh the list. --- --- url: /en/official/Reference/VBA/Information.md --- # Information module The **Information** module groups together standalone procedures for asking questions about a value at run time --- its subtype, whether it has been initialised, whether an optional argument was supplied --- together with related utilities for querying array bounds, building **Variant** arrays, taking raw addresses, decomposing colour values, and reaching the current run-time error state. ## Inspecting a value The `Is...` family of functions test whether an expression has a particular state or subtype, returning a **Boolean**: [**IsArray**](/en/official/Reference/VBA/Information/IsArray), [**IsArrayInitialized**](/en/official/Reference/VBA/Information/IsArrayInitialized), [**IsDate**](/en/official/Reference/VBA/Information/IsDate), [**IsEmpty**](/en/official/Reference/VBA/Information/IsEmpty), [**IsError**](/en/official/Reference/VBA/Information/IsError), [**IsMissing**](/en/official/Reference/VBA/Information/IsMissing), [**IsNull**](/en/official/Reference/VBA/Information/IsNull), [**IsNumeric**](/en/official/Reference/VBA/Information/IsNumeric), and [**IsObject**](/en/official/Reference/VBA/Information/IsObject). For richer queries, [**VarType**](/en/official/Reference/VBA/Information/VarType) returns the [**VbVarType**](/en/official/Reference/VBA/Constants/VbVarType) enumeration value identifying the subtype of a **Variant**, and [**TypeName**](/en/official/Reference/VBA/Information/TypeName) returns its name as a **String**. ```vb Dim v As Variant v = "1/1/2000" Debug.Print IsDate(v) ' True Debug.Print VarType(v) ' 8 (vbString) Debug.Print TypeName(v) ' "String" ``` ## Array bounds [**LBound**](/en/official/Reference/VBA/Information/LBound) and [**UBound**](/en/official/Reference/VBA/Information/UBound) return the smallest and largest valid subscript for a chosen dimension of an array. With a single argument they report on the first dimension; pass an explicit *Dimension* index to query a multidimensional array. ```vb Dim Grid(1 To 4, 0 To 9) As Long Debug.Print LBound(Grid) ' 1 — first dimension lower bound Debug.Print UBound(Grid) ' 4 — first dimension upper bound Debug.Print LBound(Grid, 2) ' 0 — second dimension lower bound Debug.Print UBound(Grid, 2) ' 9 — second dimension upper bound ``` ## Building Variant arrays [**Array**](/en/official/Reference/VBA/Information/Array) creates a **Variant** array from a comma-separated list of values; the lower bound follows the source file's **Option Base** setting. As a special form, the same name doubles as a destructuring `Property Let` for unpacking an array on the right-hand side into individual variables on the left. ```vb Dim a As Variant = Array("one", "two", "three") Dim x As Variant, y As Variant, z As Variant Array(x, y, z) = a ' destructuring assignment ``` ## Raw pointers Three functions return raw addresses for use with API calls or unsafe interop: [**ObjPtr**](/en/official/Reference/VBA/Information/ObjPtr) for an object's COM identity, [**StrPtr**](/en/official/Reference/VBA/Information/StrPtr) for the underlying buffer of a **String**, and [**VarPtr**](/en/official/Reference/VBA/Information/VarPtr) for any variable. The result is a **LongPtr** valid only while the underlying object, string, or variable stays alive --- taking a pointer never holds a reference of its own. To read or write the memory at a known address, pair these with the [**GetMem**](/en/official/Reference/VBA/HiddenModule/GetMem4) / [**PutMem**](/en/official/Reference/VBA/HiddenModule/PutMem4) family from the [(Default)](/en/official/Reference/VBA/HiddenModule/) module. ```vb Dim n As Long = &H12345678 Dim Bytes(0 To 3) As Byte vbaCopyBytes 4, VarPtr(Bytes(0)), VarPtr(n) Debug.Print Hex(Bytes(0)) ' "78" — little-endian ``` ## Working with colour values [**RGB**](/en/official/Reference/VBA/Information/RGB) and [**RGBA**](/en/official/Reference/VBA/Information/RGBA) build a 32-bit colour value from individual red, green, blue, and (optionally) alpha components; [**RGB\_R**](/en/official/Reference/VBA/Information/RGB_R), [**RGB\_G**](/en/official/Reference/VBA/Information/RGB_G), [**RGB\_B**](/en/official/Reference/VBA/Information/RGB_B), and [**RGBA\_A**](/en/official/Reference/VBA/Information/RGBA_A) extract those components back out. [**QBColor**](/en/official/Reference/VBA/Information/QBColor) returns the RGB value of one of the sixteen QuickBASIC colour indexes, and [**TranslateColor**](/en/official/Reference/VBA/Information/TranslateColor) converts an OLE colour value (which may reference an entry in the system palette) into a plain RGB colour. ```vb Dim C As Long C = RGB(255, 100, 150) Debug.Print RGB_R(C) ' 255 Debug.Print RGB_G(C) ' 100 Debug.Print RGB_B(C) ' 150 ``` ## Run-time error state [**Err**](/en/official/Reference/VBA/Information/Err) returns the [**ErrObject**](/en/official/Reference/VBA/ErrObject/) describing the run-time error currently in effect --- its number, description, source, and so on. [**Erl**](/en/official/Reference/VBA/Information/Erl) returns the line number of the statement that raised the most recent error, when one was supplied as a numeric label. ## Members * [Array](/en/official/Reference/VBA/Information/Array) -- creates a **Variant** array from a comma-separated list of values, or destructures one when used on the left of an assignment * [Erl](/en/official/Reference/VBA/Information/Erl) -- returns the line number where the most recent run-time error occurred * [Err](/en/official/Reference/VBA/Information/Err) -- returns the [**ErrObject**](/en/official/Reference/VBA/ErrObject/) describing the current run-time error state * [IMEStatus](/en/official/Reference/VBA/Information/IMEStatus) -- returns the status of the Input Method Editor * [IsArray](/en/official/Reference/VBA/Information/IsArray) -- returns whether a variable is an array * [IsArrayInitialized](/en/official/Reference/VBA/Information/IsArrayInitialized) -- returns whether an array has been dimensioned * [IsDate](/en/official/Reference/VBA/Information/IsDate) -- returns whether an expression can be evaluated as a date * [IsEmpty](/en/official/Reference/VBA/Information/IsEmpty) -- returns whether a **Variant** is uninitialised * [IsError](/en/official/Reference/VBA/Information/IsError) -- returns whether an expression is an error subtype * [IsMissing](/en/official/Reference/VBA/Information/IsMissing) -- returns whether an optional argument was supplied * [IsNull](/en/official/Reference/VBA/Information/IsNull) -- returns whether a variable contains a **Null** value * [IsNumeric](/en/official/Reference/VBA/Information/IsNumeric) -- returns whether an expression can be evaluated as a number * [IsObject](/en/official/Reference/VBA/Information/IsObject) -- returns whether a variable refers to an object * [LBound](/en/official/Reference/VBA/Information/LBound) -- returns the smallest valid subscript for a dimension of an array * [ObjPtr](/en/official/Reference/VBA/Information/ObjPtr) -- returns the COM-identity address of an object * [QBColor](/en/official/Reference/VBA/Information/QBColor) -- returns the RGB colour value for a QuickBASIC colour index * [RGB](/en/official/Reference/VBA/Information/RGB) -- builds an RGB colour value from red, green, and blue components * [RGBA](/en/official/Reference/VBA/Information/RGBA) -- builds an RGBA colour value from red, green, blue, and alpha components * [RGBA\_A](/en/official/Reference/VBA/Information/RGBA_A) -- returns the alpha component of an RGBA colour value * [RGB\_B](/en/official/Reference/VBA/Information/RGB_B) -- returns the blue component of an RGB colour value * [RGB\_G](/en/official/Reference/VBA/Information/RGB_G) -- returns the green component of an RGB colour value * [RGB\_R](/en/official/Reference/VBA/Information/RGB_R) -- returns the red component of an RGB colour value * [StrPtr](/en/official/Reference/VBA/Information/StrPtr) -- returns the address of the underlying buffer of a **String** * [TranslateColor](/en/official/Reference/VBA/Information/TranslateColor) -- translates an OLE colour value to a plain RGB colour value * [TypeName](/en/official/Reference/VBA/Information/TypeName) -- returns the name of a variable's data type as a **String** * [UBound](/en/official/Reference/VBA/Information/UBound) -- returns the largest valid subscript for a dimension of an array * [VarPtr](/en/official/Reference/VBA/Information/VarPtr) -- returns the address of a variable * [VarType](/en/official/Reference/VBA/Information/VarType) -- returns the [**VbVarType**](/en/official/Reference/VBA/Constants/VbVarType) enumeration value identifying a variable's subtype --- --- url: /zh/official/Reference/VBA/Information.md --- # Information模块 **Information**模块将运行时查询值状态的独立过程组合在一起——子类型、是否已初始化、是否提供了可选参数——以及相关的用于查询数组边界、构建**Variant**数组、获取原始地址、分解颜色值和获取当前运行时错误状态的工具。 ## 检查值 `Is...`系列函数测试表达式是否具有特定状态或子类型,返回**Boolean**:[**IsArray**](/official/Reference/VBA/Information/IsArray)、[**IsArrayInitialized**](/official/Reference/VBA/Information/IsArrayInitialized)、[**IsDate**](/official/Reference/VBA/Information/IsDate)、[**IsEmpty**](/official/Reference/VBA/Information/IsEmpty)、[**IsError**](/official/Reference/VBA/Information/IsError)、[**IsMissing**](/official/Reference/VBA/Information/IsMissing)、[**IsNull**](/official/Reference/VBA/Information/IsNull)、[**IsNumeric**](/official/Reference/VBA/Information/IsNumeric)和[**IsObject**](/official/Reference/VBA/Information/IsObject)。要获取更丰富的查询,[**VarType**](/official/Reference/VBA/Information/VarType)返回标识**Variant**子类型的[**VbVarType**](/official/Reference/VBA/Constants/VbVarType)枚举值,[**TypeName**](/official/Reference/VBA/Information/TypeName)返回其名称作为**String**。 ```vb Dim v As Variant v = "1/1/2000" Debug.Print IsDate(v) ' True Debug.Print VarType(v) ' 8 (vbString) Debug.Print TypeName(v) ' "String" ``` ## 数组边界 [**LBound**](/official/Reference/VBA/Information/LBound)和[**UBound**](/official/Reference/VBA/Information/UBound)返回数组指定维度的最小和最大有效下标。使用单个参数时报告第一维;传入显式的*Dimension*索引可查询多维数组。 ```vb Dim Grid(1 To 4, 0 To 9) As Long Debug.Print LBound(Grid) ' 1 — first dimension lower bound Debug.Print UBound(Grid) ' 4 — first dimension upper bound Debug.Print LBound(Grid, 2) ' 0 — second dimension lower bound Debug.Print UBound(Grid, 2) ' 9 — second dimension upper bound ``` ## 构建Variant数组 [**Array**](/official/Reference/VBA/Information/Array)从逗号分隔的值列表创建**Variant**数组;下界遵循源文件的**Option Base**设置。作为特殊形式,同一名称还兼作解构`Property Let`,用于将右侧数组解包到左侧的各个变量中。 ```vb Dim a As Variant = Array("one", "two", "three") Dim x As Variant, y As Variant, z As Variant Array(x, y, z) = a ' destructuring assignment ``` ## 原始指针 三个函数返回用于API调用或非安全互操作的原始地址:[**ObjPtr**](/official/Reference/VBA/Information/ObjPtr)用于对象的COM标识,[**StrPtr**](/official/Reference/VBA/Information/StrPtr)用于**String**的底层缓冲区,[**VarPtr**](/official/Reference/VBA/Information/VarPtr)用于任何变量。结果是一个**LongPtr**,仅在底层对象、字符串或变量保持活动期间有效——获取指针不会持有自身的引用。要在已知地址读写内存,请将这些与[(Default)](/official/Reference/VBA/HiddenModule/)模块中的[**GetMem**](/official/Reference/VBA/HiddenModule/GetMem4)/[**PutMem**](/official/Reference/VBA/HiddenModule/PutMem4)系列函数配合使用。 ```vb Dim n As Long = &H12345678 Dim Bytes(0 To 3) As Byte vbaCopyBytes 4, VarPtr(Bytes(0)), VarPtr(n) Debug.Print Hex(Bytes(0)) ' "78" — little-endian ``` ## 处理颜色值 [**RGB**](/official/Reference/VBA/Information/RGB)和[**RGBA**](/official/Reference/VBA/Information/RGBA)从单独的红、绿、蓝和(可选的)Alpha分量构建32位颜色值;[**RGB\_R**](/official/Reference/VBA/Information/RGB_R)、[**RGB\_G**](/official/Reference/VBA/Information/RGB_G)、[**RGB\_B**](/official/Reference/VBA/Information/RGB_B)和[**RGBA\_A**](/official/Reference/VBA/Information/RGBA_A)将这些分量提取出来。[**QBColor**](/official/Reference/VBA/Information/QBColor)返回十六个QuickBASIC颜色索引之一的RGB值,[**TranslateColor**](/official/Reference/VBA/Information/TranslateColor)将OLE颜色值(可能引用系统调色板中的条目)转换为普通RGB颜色。 ```vb Dim C As Long C = RGB(255, 100, 150) Debug.Print RGB_R(C) ' 255 Debug.Print RGB_G(C) ' 100 Debug.Print RGB_B(C) ' 150 ``` ## 运行时错误状态 [**Err**](/official/Reference/VBA/Information/Err)返回描述当前运行时错误状态的[**ErrObject**](/official/Reference/VBA/ErrObject/)——其编号、描述、来源等。[**Erl**](/official/Reference/VBA/Information/Erl)返回引发最近错误的语句的行号(当作为数字标签提供时)。 ## 成员 * [Array](/official/Reference/VBA/Information/Array) -- 从逗号分隔的值列表创建**Variant**数组,或在赋值左侧使用时进行解构 * [Erl](/official/Reference/VBA/Information/Erl) -- 返回最近运行时错误发生的行号 * [Err](/official/Reference/VBA/Information/Err) -- 返回描述当前运行时错误状态的[**ErrObject**](/official/Reference/VBA/ErrObject/) * [IMEStatus](/official/Reference/VBA/Information/IMEStatus) -- 返回输入法编辑器的状态 * [IsArray](/official/Reference/VBA/Information/IsArray) -- 返回变量是否为数组 * [IsArrayInitialized](/official/Reference/VBA/Information/IsArrayInitialized) -- 返回数组是否已分配维度 * [IsDate](/official/Reference/VBA/Information/IsDate) -- 返回表达式是否可求值为日期 * [IsEmpty](/official/Reference/VBA/Information/IsEmpty) -- 返回**Variant**是否未初始化 * [IsError](/official/Reference/VBA/Information/IsError) -- 返回表达式是否为错误子类型 * [IsMissing](/official/Reference/VBA/Information/IsMissing) -- 返回是否提供了可选参数 * [IsNull](/official/Reference/VBA/Information/IsNull) -- 返回变量是否包含**Null**值 * [IsNumeric](/official/Reference/VBA/Information/IsNumeric) -- 返回表达式是否可求值为数字 * [IsObject](/official/Reference/VBA/Information/IsObject) -- 返回变量是否引用对象 * [LBound](/official/Reference/VBA/Information/LBound) -- 返回数组某一维度的最小有效下标 * [ObjPtr](/official/Reference/VBA/Information/ObjPtr) -- 返回对象的COM标识地址 * [QBColor](/official/Reference/VBA/Information/QBColor) -- 返回QuickBASIC颜色索引对应的RGB颜色值 * [RGB](/official/Reference/VBA/Information/RGB) -- 从红、绿、蓝分量构建RGB颜色值 * [RGBA](/official/Reference/VBA/Information/RGBA) -- 从红、绿、蓝和Alpha分量构建RGBA颜色值 * [RGBA\_A](/official/Reference/VBA/Information/RGBA_A) -- 返回RGBA颜色值的Alpha分量 * [RGB\_B](/official/Reference/VBA/Information/RGB_B) -- 返回RGB颜色值的蓝色分量 * [RGB\_G](/official/Reference/VBA/Information/RGB_G) -- 返回RGB颜色值的绿色分量 * [RGB\_R](/official/Reference/VBA/Information/RGB_R) -- 返回RGB颜色值的红色分量 * [StrPtr](/official/Reference/VBA/Information/StrPtr) -- 返回**String**底层缓冲区的地址 * [TranslateColor](/official/Reference/VBA/Information/TranslateColor) -- 将OLE颜色值转换为普通RGB颜色值 * [TypeName](/official/Reference/VBA/Information/TypeName) -- 返回变量数据类型的名称作为**String** * [UBound](/official/Reference/VBA/Information/UBound) -- 返回数组某一维度的最大有效下标 * [VarPtr](/official/Reference/VBA/Information/VarPtr) -- 返回变量的地址 * [VarType](/official/Reference/VBA/Information/VarType) -- 返回标识变量子类型的[**VbVarType**](/official/Reference/VBA/Constants/VbVarType)枚举值 --- --- url: /en/official/Features/Language/Inheritance.md --- # Inheritance twinBASIC provides several mechanisms for inheritance to support both simple and complete object-oriented programming patterns: **Implements**, **Implements Via** and **Inherits**. ## Enhancements to **Implements** `Implements` in twinBASIC has several enhancements: ### Inherited Interfaces `Implements` in twinBASIC is allowed on inherited interfaces -- for instance, if you have `Interface IFoo2 Extends IFoo`, you then use `Implements IFoo2` in a class, where in VBx this would not be allowed. You'll need to provide methods for all inherited interfaces (besides `IDispatch` and `IUnknown`). The class will mark all interfaces as available-- you don't need a separate statement for `IFoo`, it will be passed through `Set` statements (and their underlying `QueryInterface` calls) automatically. ### Multiple Implementations If you have an interface that multiple others extend from, you can write multiple implementations, or specify one implementation for all. For example: ```vb IOleWindow_GetWindow() As LongPtr _ Implements IOleWindow.GetWindow, IShellBrowser.GetWindow, IShellView2.GetWindow ``` ### 'As Any' Parameters in Interfaces `Implements` is allowed on interfaces with 'As Any' parameters: In VBx, you'd get an error if you attempted to use any interface containing a member with an `As Any` argument. With twinBASIC, this is allowed if you substitute `As LongPtr` for `As Any`, for example: ```vb Interface IFoo Extends IUnknown Sub Bar(ppv As Any) End Interface Class MyClass Implements IFoo Private Sub IFoo_Bar(ppv As LongPtr) Implements IFoo.Bar End Sub ``` ## **Implements Via** for Basic Inheritance tB allows simple inheritance among classes. For example, if you have class cVehicle which implements IVehicle containing method Honk, you could create child classes like cCar or cTruck, which inherit the methods of the original, so you could call cCar.Honk without writing a separate implementation. ![image](/assets/b0724fe2-636d-47db-a8fc-531a585ddaf9.BDt0t_fJ.png) You can see that the Honk method is only implemented by the parent class, then called from the child class when you click the CodeLens button to run the sub in place from the IDE. ## **Inherits** for Complete OOP This option supports full inheritance and OOP: `Protected` methods and variables accessible to derived classes (but not outside callers), `Overridable` and `Overrides` syntax, multiple inheritance, and explicit base class constructors. ### Example: Animal Class Hierarchy Starting with a base class: ```vb Private Class Animal Protected _name As String Protected _dob As Date ' date of birth Public Event Spoke(ByVal sound As String) Public Sub New(name As String, dob As Date) _name = name _dob = dob End Sub Public Property Get Name() As String Name = _name End Property Public Property Get DOB() As Date DOB = _dob End Property ' Age in whole years based on DOB and today's date Public Function AgeYears() As Long Dim y As Long y = DateDiff("yyyy", _dob, Date) If DateSerial(Year(Date), Month(_dob), Day(_dob)) > Date Then y = y - 1 AgeYears = y End Function Public Sub Speak() Dim s As String s = GetSound() RaiseEvent Spoke(s) Debug.Print _name & " says: " & s End Sub ' --- Overridable hook for derived classes --- Protected Overridable Function GetSound() As String GetSound = "" End Function End Class ``` Others can inherit: ```vb ' ===== Derived: Dog ===== Private Class Dog Inherits Animal Protected _breed As String Public Sub New(name As String, dob As Date, breed As String) Animal.New(name, dob) ' we can explicitly call base constructors from within our constructor _breed = breed End Sub Public Property Get Breed() As String Breed = _breed End Property ' Override: Protected Overridable Function GetSound() As String Overrides Animal.GetSound GetSound = "woof" End Function End Class ' ===== Further derived: GuardDog (Dog → GuardDog) ===== Private Class GuardDog Inherits Dog Protected _onDuty As Boolean Public Sub New(name As String, dob As Date, breed As String) Dog.New(name, dob, breed) ' we can explicitly call base constructors from within our constructor _onDuty = True End Sub Public Property Get OnDuty() As Boolean OnDuty = _onDuty End Property Public Property Let OnDuty(ByVal v As Boolean) _onDuty = v End Property ' Multi-level override (overriding Dog's override): Protected Function GetSound() As String Overrides Dog.GetSound If _onDuty Then GetSound = "WOOF!" Else GetSound = "woof" End If End Function End Class ``` This is just an excerpt, see the full Sample 23 for additional classes, usage, and information about inheritance in twinBASIC. --- --- url: /en/official/Features/Language/Inline-Initialization.md --- # Inline Variable Initialization You can now set initial values for variables inline, without needing a line-continuation character. ## Examples ```vb Dim i As Long = 1 Dim foo As Boolean = bar() Dim arr As Variant = Array(1, 2, 3) Dim strArr(2) As String = Array("a", "b", "c") Dim cMC As cMyClass = New cMyClass(customConstructorArgs) ``` ## Inline Variable Declaration for For You now no longer need a separate `Dim` statement for counter variables: ```vb For i As Long = 0 To 10 '... Next ``` is now valid syntax. You can use any type, not just `Long`. --- --- url: /en/official/Reference/Core/Input.md --- # Input # statement Reads data from an open sequential file and assigns the data to variables. ::: info This page documents the **Input #** *statement*. The unrelated [**Input** function](/en/official/Reference/VBA/FileSystem/Input) reads a fixed number of characters from any open file. ::: Syntax: > **Input** **#** *filenumber* **,** *varlist* *filenumber* : Any valid file number. *varlist* : Comma-delimited list of variables that are assigned values read from the file. *varlist* can't contain an array variable or an object variable. However, variables that describe an element of an array or user-defined type may be used. Data read with **Input #** is usually written to a file with [**Write #**](/en/official/Reference/Core/Write). Use this statement only with files opened in **Input** or **Binary** mode. When read, standard string or numeric data is assigned to variables without modification. The following table illustrates how other input data is treated: | Data | Value assigned to variable | | :----------------------------- | :----------------------------------------------------------- | | Delimiting comma or blank line | **Empty** | | `#NULL#` | **Null** | | `#TRUE#` or `#FALSE#` | **True** or **False** | | `#`*yyyy-mm-dd hh:mm:ss*`#` | The date and/or time represented by the expression | | `#ERROR `*errornumber*`#` | *errornumber* (variable is a **Variant** tagged as an error) | Double quotation marks (`"`) within input data are ignored. ::: warning Do not write strings that contain embedded quotation marks (for example, `"1,2""X"`) for use with the **Input #** statement; **Input #** parses this string as two complete and separate strings. ::: Data items in a file must appear in the same order as the variables in *varlist* and match variables of the same data type. If a variable is numeric and the data is not numeric, a value of zero is assigned to the variable. If the end of the file is reached while a data item is being read, the input is terminated and an error occurs. ::: info To be able to correctly read data from a file into variables by using **Input #**, use the [**Write #**](/en/official/Reference/Core/Write) statement instead of the [**Print #**](/en/official/Reference/Core/Print) statement to write the data to the files. Using **Write #** ensures that each separate data field is properly delimited. ::: ### Example This example uses the **Input #** statement to read data from a file into two variables. This example assumes that `TESTFILE` is a file with a few lines of data written to it by using the **Write #** statement; that is, each line contains a string in quotations and a number separated by a comma, for example, `"Hello", 234`. ```vb Dim MyString, MyNumber Open "TESTFILE" For Input As #1 ' Open file for input. Do While Not EOF(1) ' Loop until end of file. Input #1, MyString, MyNumber ' Read data into two variables. Debug.Print MyString, MyNumber ' Print data to the Immediate window. Loop Close #1 ' Close file. ``` ### See Also * [**Open** statement](/en/official/Reference/Core/Open) * [**Close** statement](/en/official/Reference/Core/Close) * [**Line Input #** statement](/en/official/Reference/Core/Line-Input) * [**Write #** statement](/en/official/Reference/Core/Write) * [**Print #** statement](/en/official/Reference/Core/Print) * [**Input** function](/en/official/Reference/VBA/FileSystem/Input) * [**EOF** function](/en/official/Reference/VBA/FileSystem/EOF) --- --- url: /zh/official/Reference/Core/Input.md --- # Input # 语句 从打开的顺序文件中读取数据并将数据赋值给变量。 ::: info 本页记录 **Input #** *语句*。不相关的 [**Input** 函数](/official/Reference/VBA/FileSystem/Input) 从任何打开的文件读取固定数量的字符。 ::: 语法: > **Input** **#** *filenumber* **,** *varlist* *filenumber* : 任何有效的文件号。 *varlist* : 逗号分隔的变量列表,从文件读取的值赋给这些变量。*varlist* 不能包含数组变量或对象变量。但描述数组元素或用户自定义类型的变量可以使用。 用 **Input #** 读取的数据通常用 [**Write #**](/official/Reference/Core/Write) 写入文件。此语句仅用于以 **Input** 或 **Binary** 模式打开的文件。读取时,标准字符串或数值数据不经修改赋值给变量。 下表说明了其他输入数据的处理方式: | 数据 | 赋给变量的值 | | :-------------------------- | :---------------------------------------------- | | 分隔逗号或空行 | **Empty** | | `#NULL#` | **Null** | | `#TRUE#` 或 `#FALSE#` | **True** 或 **False** | | `#`*yyyy-mm-dd hh:mm:ss*`#` | 表达式表示的日期和/或时间 | | `#ERROR `*errornumber*`#` | *errornumber*(变量为标记为错误的 **Variant**) | 输入数据中的双引号(`"`)被忽略。 ::: warning 不要为 **Input #** 语句编写包含嵌入引号的字符串(例如 `"1,2""X"`);**Input #** 会将此字符串解析为两个完整独立的字符串。 ::: 文件中的数据项必须以 *varlist* 中变量的相同顺序出现,并与相同数据类型的变量匹配。如果变量是数值类型而数据不是数值类型,则将零值赋给变量。 如果在读取数据项时到达文件末尾,输入终止并发生错误。 ::: info 要能够正确使用 **Input #** 将数据从文件读入变量,请使用 [**Write #**](/official/Reference/Core/Write) 语句而非 [**Print #**](/official/Reference/Core/Print) 语句将数据写入文件。使用 **Write #** 确保每个独立的数据字段被正确分隔。 ::: ### 示例 本示例使用 **Input #** 语句从文件读取数据到两个变量。本示例假设 `TESTFILE` 是使用 **Write #** 语句写入几行数据的文件;即每行包含引号中的字符串和用逗号分隔的数字,如 `"Hello", 234`。 ```vb Dim MyString, MyNumber Open "TESTFILE" For Input As #1 ' Open file for input. Do While Not EOF(1) ' Loop until end of file. Input #1, MyString, MyNumber ' Read data into two variables. Debug.Print MyString, MyNumber ' Print data to the Immediate window. Loop Close #1 ' Close file. ``` ### 另请参阅 * [**Open** 语句](/official/Reference/Core/Open) * [**Close** 语句](/official/Reference/Core/Close) * [**Line Input #** 语句](/official/Reference/Core/Line-Input) * [**Write #** 语句](/official/Reference/Core/Write) * [**Print #** 语句](/official/Reference/Core/Print) * [**Input** 函数](/official/Reference/VBA/FileSystem/Input) * [**EOF** 函数](/official/Reference/VBA/FileSystem/EOF) --- --- url: /en/official/Reference/VBA/FileSystem/Input.md --- # Input, Input$ Returns a fixed number of characters read from a file opened in **Input** or **Binary** mode. Syntax: * **Input(** *Number* **,** \[ **#** ] *FileNumber* **)** --- returns a **Variant**. * **Input$(** *Number* **,** \[ **#** ] *FileNumber* **)** --- returns a **String**. *Number* : *required* The number of characters to return. *FileNumber* : *required* The file number used to open the file with the [**Open**](/en/official/Reference/Core/Open) statement. Data read with **Input** is usually written to a file with **Print #** or **[Put](/en/official/Reference/Core/Put)**. Use this function only with files opened in **Input** or **Binary** mode. Unlike the **Input #** statement, the **Input** function returns all the characters it reads, including commas, carriage returns, linefeeds, quotation marks, and leading spaces. For files opened for **Binary** access, an attempt to read through the file using **Input** until [**EOF**](/en/official/Reference/VBA/FileSystem/EOF) returns **True** generates an error. Use [**LOF**](/en/official/Reference/VBA/FileSystem/LOF) and [**Loc**](/en/official/Reference/VBA/FileSystem/Loc) instead of **EOF** when reading binary files with **Input**, or use **[Get](/en/official/Reference/Core/Get)** when **EOF** is needed. ::: info Use [**InputB**](/en/official/Reference/VBA/FileSystem/InputB) for byte data contained within text files. With **InputB**, *Number* specifies the number of bytes to return rather than the number of characters. ::: ### Example This example uses the **Input** function to read one character at a time from a file and print it to the immediate window. *TESTFILE* is assumed to be a text file with a few lines of sample data. ```vb Dim MyChar As Variant Open "TESTFILE" For Input As #1 ' Open file. Do While Not EOF(1) ' Loop until end of file. MyChar = Input(1, #1) ' Get one character. Debug.Print MyChar ' Print to the immediate window. Loop Close #1 ' Close file. ``` ### See Also * [InputB, InputB$](/en/official/Reference/VBA/FileSystem/InputB) functions * [Open](/en/official/Reference/Core/Open) statement * [EOF](/en/official/Reference/VBA/FileSystem/EOF), [LOF](/en/official/Reference/VBA/FileSystem/LOF), [Loc](/en/official/Reference/VBA/FileSystem/Loc) functions --- --- url: /zh/official/Reference/VBA/FileSystem/Input.md --- # Input, Input$ 返回从以**Input**或**Binary**模式打开的文件中读取的固定数量字符。 语法: * **Input(** *Number* **,** \[ **#** ] *FileNumber* **)** --- 返回**Variant**。 * **Input$(** *Number* **,** \[ **#** ] *FileNumber* **)** --- 返回**String**。 *Number* : *必需* 要返回的字符数。 *FileNumber* : *必需* 用于以[**Open**](/official/Reference/Core/Open)语句打开文件的文件号。 使用**Input**读取的数据通常由**Print #**或**[Put](/official/Reference/Core/Put)**写入文件。此函数仅适用于以**Input**或**Binary**模式打开的文件。 与\*\*Input #\*\*语句不同,**Input**函数返回它读取的所有字符,包括逗号、回车符、换行符、引号和前导空格。 对于以**Binary**访问模式打开的文件,尝试使用**Input**读取文件直到[**EOF**](/official/Reference/VBA/FileSystem/EOF)返回**True**会产生错误。使用**Input**读取二进制文件时,请使用[**LOF**](/official/Reference/VBA/FileSystem/LOF)和[**Loc**](/official/Reference/VBA/FileSystem/Loc)代替**EOF**,或在需要**EOF**时使用\*\*[Get](/official/Reference/Core/Get)\*\*。 ::: info 对文本文件中包含的字节数据使用[**InputB**](/official/Reference/VBA/FileSystem/InputB)。使用**InputB**时,*Number*指定要返回的字节数而非字符数。 ::: ### 示例 本示例使用**Input**函数从文件中逐字符读取并输出到立即窗口。假设*TESTFILE*是一个包含几行示例数据的文本文件。 ```vb Dim MyChar As Variant Open "TESTFILE" For Input As #1 ' Open file. Do While Not EOF(1) ' Loop until end of file. MyChar = Input(1, #1) ' Get one character. Debug.Print MyChar ' Print to the immediate window. Loop Close #1 ' Close file. ``` ### 另请参阅 * [InputB, InputB$](/official/Reference/VBA/FileSystem/InputB)函数 * [Open](/official/Reference/Core/Open)语句 * [EOF](/official/Reference/VBA/FileSystem/EOF)、[LOF](/official/Reference/VBA/FileSystem/LOF)、[Loc](/official/Reference/VBA/FileSystem/Loc)函数 --- --- url: /en/official/Reference/VBA/FileSystem/InputB.md --- # InputB, InputB$ Returns a fixed number of bytes read from a file opened in **Input** or **Binary** mode. Syntax: * **InputB(** *Number* **,** \[ **#** ] *FileNumber* **)** --- returns a **Variant**. * **InputB$(** *Number* **,** \[ **#** ] *FileNumber* **)** --- returns a **String** whose underlying bytes are the bytes that were read. *Number* : *required* The number of bytes to return. *FileNumber* : *required* The file number used to open the file with the [**Open**](/en/official/Reference/Core/Open) statement. **InputB** is the byte-oriented counterpart of [**Input**](/en/official/Reference/VBA/FileSystem/Input). Where **Input** counts and returns characters (two bytes per character in twinBASIC's UTF-16 buffer), **InputB** counts and returns raw bytes --- useful when reading binary data through a textually-opened channel. The bytes are packed into the result without any character-set translation; the **String** form simply reinterprets the byte run as a UTF-16 string for storage. ### Example ```vb Dim Bytes As Variant Open "data.bin" For Binary Access Read As #1 Bytes = InputB(LOF(1), 1) ' Read the whole file as bytes. Close #1 ``` ### See Also * [Input, Input$](/en/official/Reference/VBA/FileSystem/Input) functions * [Open](/en/official/Reference/Core/Open) statement * [LOF](/en/official/Reference/VBA/FileSystem/LOF) function --- --- url: /zh/official/Reference/VBA/FileSystem/InputB.md --- # InputB, InputB$ 返回从以**Input**或**Binary**模式打开的文件中读取的固定数量字节。 语法: * **InputB(** *Number* **,** \[ **#** ] *FileNumber* **)** --- 返回**Variant**。 * **InputB$(** *Number* **,** \[ **#** ] *FileNumber* **)** --- 返回一个**String**,其底层字节即为读取到的字节。 *Number* : *必需* 要返回的字节数。 *FileNumber* : *必需* 用于以[**Open**](/official/Reference/Core/Open)语句打开文件的文件号。 **InputB**是[**Input**](/official/Reference/VBA/FileSystem/Input)的面向字节版本。**Input**计算和返回字符(在twinBASIC的UTF-16缓冲区中每个字符两个字节),而**InputB**计算和返回原始字节——当通过文本方式打开的通道读取二进制数据时非常有用。 字节在打包到结果中时不会进行任何字符集转换;**String**形式只是将字节序列重新解释为UTF-16字符串进行存储。 ### 示例 ```vb Dim Bytes As Variant Open "data.bin" For Binary Access Read As #1 Bytes = InputB(LOF(1), 1) ' Read the whole file as bytes. Close #1 ``` ### 另请参阅 * [Input, Input$](/official/Reference/VBA/FileSystem/Input)函数 * [Open](/official/Reference/Core/Open)语句 * [LOF](/official/Reference/VBA/FileSystem/LOF)函数 --- --- url: /en/official/Reference/VBA/Interaction/InputBox.md --- # InputBox Displays a prompt in a dialog, waits for the user to type text or click a button, and returns a **String** containing the contents of the text box. Syntax: **InputBox(** *prompt* \[ **,** *title* ] \[ **,** *default* ] \[ **,** *xpos* ] \[ **,** *ypos* ] \[ **,** *helpfile* **,** *context* ] **)** *prompt* : *required* String expression displayed as the message in the dialog box. The maximum length of *prompt* is approximately 1024 characters, depending on the width of the characters used. To break *prompt* across multiple lines, separate the lines with a carriage return (`Chr(13)`), a linefeed (`Chr(10)`), or a CR-LF combination (`vbCrLf`). *title* : *optional* String expression displayed in the title bar of the dialog box. If omitted, the application name is used. *default* : *optional* String expression displayed in the text box as the initial response. If omitted, the text box is displayed empty. *xpos* : *optional* Numeric expression specifying, in twips, the horizontal distance of the left edge of the dialog from the left edge of the screen. If omitted, the dialog is horizontally centered. *ypos* : *optional* Numeric expression specifying, in twips, the vertical distance of the top edge of the dialog from the top of the screen. If omitted, the dialog is positioned approximately one-third of the way down the screen. *helpfile* : *optional* String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If *helpfile* is supplied, *context* must also be supplied. *context* : *optional* Numeric expression giving the Help context number assigned to the relevant Help topic. If *context* is supplied, *helpfile* must also be supplied. If the user clicks **OK** or presses ENTER, **InputBox** returns whatever is in the text box. If the user clicks **Cancel**, the function returns a zero-length string (`""`). ::: info A zero-length return value alone cannot distinguish "user cancelled" from "user submitted an empty string". To tell them apart, capture the result in a **Variant** and test the underlying **BSTR** pointer with **StrPtr**: a cancelled dialog returns a null pointer, while an empty submitted string returns a pointer to an allocated zero-length **BSTR**. ```vb Dim Reply As Variant Reply = InputBox("Enter your name:") If StrPtr(Reply) = 0 Then ' User cancelled. ElseIf Reply = "" Then ' User submitted an empty string. Else ' User entered: Reply. End If ``` ::: The text box accepts at most 255 characters; the returned string is truncated to 254 characters. The text box does not accept line breaks (e.g. SHIFT+ENTER); pasted text containing a line break is truncated at the break. When both *helpfile* and *context* are supplied, the user can press F1 to view the relevant Help topic. ### Example This example shows several ways of calling **InputBox**. If *xpos* and *ypos* are omitted the dialog is centered on its respective axis. The variable `MyValue` ends up containing whatever the user typed when **OK** or ENTER was pressed, or a zero-length string when **Cancel** was pressed. ```vb Dim Message As String, Title As String, Default As String, MyValue As String Message = "Enter a value between 1 and 3" Title = "InputBox Demo" Default = "1" ' Display message, title, and default value. MyValue = InputBox(Message, Title, Default) ' Use a Help file and context. The Help button is added automatically. MyValue = InputBox(Message, Title, , , , "DEMO.HLP", 10) ' Display the dialog at screen position (100, 100). MyValue = InputBox(Message, Title, Default, 100, 100) ``` ### See Also * [MsgBox](/en/official/Reference/VBA/Interaction/MsgBox) function --- --- url: /zh/official/Reference/VBA/Interaction/InputBox.md --- # InputBox 在对话框中显示提示,等待用户输入文本或点击按钮,并返回一个包含文本框内容的**String**。 语法:**InputBox(** *prompt* \[ **,** *title* ] \[ **,** *default* ] \[ **,** *xpos* ] \[ **,** *ypos* ] \[ **,** *helpfile* **,** *context* ] **)** *prompt* : *必需* 字符串表达式,在对话框中显示为消息。*prompt*的最大长度约为1024个字符,取决于所使用字符的宽度。要将*prompt*分为多行,请用回车符(`Chr(13)`)、换行符(`Chr(10)`)或CR-LF组合(`vbCrLf`)分隔各行。 *title* : *可选* 字符串表达式,显示在对话框的标题栏中。如果省略,则使用应用程序名称。 *default* : *可选* 字符串表达式,在文本框中显示为初始响应。如果省略,文本框显示为空。 *xpos* : *可选* 数值表达式,以缇为单位指定对话框左边缘与屏幕左边缘的水平距离。如果省略,对话框水平居中。 *ypos* : *可选* 数值表达式,以缇为单位指定对话框上边缘与屏幕顶部的垂直距离。如果省略,对话框位于屏幕大约三分之一处。 *helpfile* : *可选* 字符串表达式,标识用于为对话框提供上下文相关帮助的帮助文件。如果提供了*helpfile*,则还必须提供*context*。 *context* : *可选* 数值表达式,给出分配给相关帮助主题的帮助上下文编号。如果提供了*context*,则还必须提供*helpfile*。 如果用户点击**OK**或按ENTER,**InputBox**返回文本框中的内容。如果用户点击**Cancel**,函数返回零长度字符串(`""`)。 ::: info 仅凭零长度返回值无法区分"用户取消"和"用户提交了空字符串"。要区分它们,请将结果捕获到**Variant**中并使用**StrPtr**测试底层**BSTR**指针:取消的对话框返回空指针,而提交的空字符串返回指向已分配零长度**BSTR**的指针。 ```vb Dim Reply As Variant Reply = InputBox("Enter your name:") If StrPtr(Reply) = 0 Then ' User cancelled. ElseIf Reply = "" Then ' User submitted an empty string. Else ' User entered: Reply. End If ``` ::: 文本框最多接受255个字符;返回字符串截断为254个字符。文本框不接受换行符(例如SHIFT+ENTER);包含换行符的粘贴文本在换行符处截断。 同时提供*helpfile*和*context*时,用户可以按F1查看相关帮助主题。 ### 示例 本示例展示了调用**InputBox**的多种方式。如果省略*xpos*和*ypos*,对话框在相应轴上居中。变量`MyValue`最终包含用户按**OK**或ENTER时键入的内容,或按**Cancel**时的零长度字符串。 ```vb Dim Message As String, Title As String, Default As String, MyValue As String Message = "Enter a value between 1 and 3" Title = "InputBox Demo" Default = "1" ' Display message, title, and default value. MyValue = InputBox(Message, Title, Default) ' Use a Help file and context. The Help button is added automatically. MyValue = InputBox(Message, Title, , , , "DEMO.HLP", 10) ' Display the dialog at screen position (100, 100). MyValue = InputBox(Message, Title, Default, 100, 100) ``` ### 另请参阅 * [MsgBox](/official/Reference/VBA/Interaction/MsgBox)函数 --- --- url: /en/official/Reference/VBA/Strings/InStr.md --- # InStr, InStrB Returns a **Variant** (**Long**) specifying the position of the first occurrence of one string within another. Syntax: * **InStr(** \[ *start* **,** ] *string1*, *string2* \[ **,** *compare* ] **)** * **InStrB(** \[ *start* **,** ] *string1*, *string2* \[ **,** *compare* ] **)** *start* : *optional* Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. If *start* contains **Null**, an error occurs. The *start* argument is required if *compare* is specified. *string1* : *required* String expression being searched. *string2* : *required* String expression sought. *compare* : *optional* Specifies the type of string comparison. If *compare* is **Null**, an error occurs. If *compare* is omitted, the [**Option Compare**](/en/official/Reference/Core/Option) setting determines the type of comparison. Specify a valid LCID (LocaleID) to use locale-specific rules in the comparison. The *compare* argument settings are: | Constant | Value | Description | |------------------------|-------|------------------------------------------------------------------------------------------| | **vbUseCompareOption** | -1 | Performs a comparison by using the setting of the **Option Compare** statement. | | **vbBinaryCompare** | 0 | Performs a binary comparison. | | **vbTextCompare** | 1 | Performs a textual comparison. | **Return values:** | If | **InStr** returns | |-------------------------------------------------|----------------------------------| | *string1* is zero-length | 0 | | *string1* is **Null** | **Null** | | *string2* is zero-length | *start* | | *string2* is **Null** | **Null** | | *string2* is not found | 0 | | *string2* is found within *string1* | Position at which match is found | | *start* > **Len**(*string2*) | 0 | The **InStrB** function is used with byte data contained in a string. Instead of returning the character position of the first occurrence of one string within another, **InStrB** returns the byte position. ### Example This example uses the **InStr** function to return the position of the first occurrence of one string within another. ```vb Dim SearchString, SearchChar, MyPos SearchString = "XXpXXpXXPXXP" ' String to search in. SearchChar = "P" ' Search for "P". ' A textual comparison starting at position 4. Returns 6. MyPos = InStr(4, SearchString, SearchChar, 1) ' A binary comparison starting at position 1. Returns 9. MyPos = InStr(1, SearchString, SearchChar, 0) ' Comparison is binary by default (last argument is omitted). MyPos = InStr(SearchString, SearchChar) ' Returns 9. MyPos = InStr(1, SearchString, "W") ' Returns 0. ``` ### See Also * [InStrRev](/en/official/Reference/VBA/Strings/InStrRev), [Replace](/en/official/Reference/VBA/Strings/Replace), [StrComp](/en/official/Reference/VBA/Strings/StrComp) functions --- --- url: /zh/official/Reference/VBA/Strings/InStr.md --- # InStr, InStrB 返回一个**Variant**(**Long**),指定一个字符串在另一个字符串中首次出现的位置。 语法: * **InStr(** \[ *start* **,** ] *string1*, *string2* \[ **,** *compare* ] **)** * **InStrB(** \[ *start* **,** ] *string1*, *string2* \[ **,** *compare* ] **)** *start* : *可选* 数值表达式,设置每次搜索的起始位置。如果省略,则从第一个字符位置开始搜索。如果*start*包含**Null**,则会出错。如果指定了*compare*,则*start*参数是必需的。 *string1* : *必需* 被搜索的字符串表达式。 *string2* : *必需* 要查找的字符串表达式。 *compare* : *可选* 指定字符串比较的类型。如果*compare*为**Null**,则会出错。如果省略*compare*,则由[**Option Compare**](/official/Reference/Core/Option)设置决定比较类型。指定有效的LCID(LocaleID)可在比较中使用区域特定规则。 *compare*参数的设置为: | 常量 | 值 | 描述 | |------------------------|-----|----------------------------------------------------------| | **vbUseCompareOption** | -1 | 使用**Option Compare**语句的设置进行比较。 | | **vbBinaryCompare** | 0 | 执行二进制比较。 | | **vbTextCompare** | 1 | 执行文本比较。 | **返回值:** | 条件 | **InStr**返回值 | |-------------------------------------------------|-------------------------------| | *string1*为零长度 | 0 | | *string1*为**Null** | **Null** | | *string2*为零长度 | *start* | | *string2*为**Null** | **Null** | | *string2*未找到 | 0 | | 在*string1*中找到了*string2* | 找到匹配的位置 | | *start* > **Len**(*string2*) | 0 | **InStrB**函数用于处理字符串中包含的字节数据。**InStrB**不返回一个字符串在另一个字符串中首次出现的字符位置,而是返回字节位置。 ### 示例 本示例使用**InStr**函数返回一个字符串在另一个字符串中首次出现的位置。 ```vb Dim SearchString, SearchChar, MyPos SearchString = "XXpXXpXXPXXP" ' String to search in. SearchChar = "P" ' Search for "P". ' A textual comparison starting at position 4. Returns 6. MyPos = InStr(4, SearchString, SearchChar, 1) ' A binary comparison starting at position 1. Returns 9. MyPos = InStr(1, SearchString, SearchChar, 0) ' Comparison is binary by default (last argument is omitted). MyPos = InStr(SearchString, SearchChar) ' Returns 9. MyPos = InStr(1, SearchString, "W") ' Returns 0. ``` ### 另请参阅 * [InStrRev](/official/Reference/VBA/Strings/InStrRev)、[Replace](/official/Reference/VBA/Strings/Replace)、[StrComp](/official/Reference/VBA/Strings/StrComp)函数 --- --- url: /en/official/Reference/VBA/Strings/InStrRev.md --- # InStrRev Returns the position of an occurrence of one string within another, from the end of the string. Syntax: **InStrRev(** *stringcheck*, *stringmatch* \[ **,** *start* \[ **,** *compare* ] ] **)** *stringcheck* : *required* String expression being searched. *stringmatch* : *required* String expression being searched for. *start* : *optional* Numeric expression that sets the starting position for each search. If omitted, -1 is used, which means that the search begins at the last character position. If *start* contains **Null**, an error occurs. *compare* : *optional* Numeric value indicating the kind of comparison to use when evaluating substrings. If omitted, a binary comparison is performed. See settings below. The *compare* argument can have the following values: | Constant | Value | Description | |------------------------|-------|------------------------------------------------------------------------------------------| | **vbUseCompareOption** | -1 | Performs a comparison by using the setting of the [**Option Compare**](/en/official/Reference/Core/Option) statement. | | **vbBinaryCompare** | 0 | Performs a binary comparison. | | **vbTextCompare** | 1 | Performs a textual comparison. | **Return values:** | If | **InStrRev** returns | |-----------------------------------------------------|----------------------------------| | *stringcheck* is zero-length | 0 | | *stringcheck* is **Null** | **Null** | | *stringmatch* is zero-length | *start* | | *stringmatch* is **Null** | **Null** | | *stringmatch* is not found | 0 | | *stringmatch* is found within *stringcheck* | Position at which match is found | | *start* > **Len**(*stringcheck*) | 0 | ::: info The syntax for the **InStrRev** function is not the same as the syntax for the [**InStr**](/en/official/Reference/VBA/Strings/InStr) function --- note the swapped order of the search arguments. ::: **InStrRev** will not find an instance of *stringmatch* unless the position of the end character of *stringmatch* is less than or equal to *start*. ### Example This example uses **InStrRev** to find the last occurrence of a substring. ```vb Debug.Print InStrRev("a.b.c", ".") ' 4 — last dot Debug.Print InStrRev("a.b.c", ".", 3) ' 2 — last dot at or before position 3 Debug.Print InStrRev("a.b.c", "x") ' 0 — not found ``` ### See Also * [InStr](/en/official/Reference/VBA/Strings/InStr) function --- --- url: /zh/official/Reference/VBA/Strings/InStrRev.md --- # InStrRev 返回一个字符串在另一个字符串中从字符串末尾开始出现的位置。 语法:**InStrRev(** *stringcheck*, *stringmatch* \[ **,** *start* \[ **,** *compare* ] ] **)** *stringcheck* : *必需* 被搜索的字符串表达式。 *stringmatch* : *必需* 要查找的字符串表达式。 *start* : *可选* 数值表达式,设置每次搜索的起始位置。如果省略,则使用-1,表示从最后一个字符位置开始搜索。如果*start*包含**Null**,则会出错。 *compare* : *可选* 数值,指示在计算子字符串时使用的比较类型。如果省略,则执行二进制比较。参见下面的设置。 *compare*参数可以取以下值: | 常量 | 值 | 描述 | |------------------------|-----|----------------------------------------------------------------------------------| | **vbUseCompareOption** | -1 | 使用[**Option Compare**](/official/Reference/Core/Option)语句的设置进行比较。 | | **vbBinaryCompare** | 0 | 执行二进制比较。 | | **vbTextCompare** | 1 | 执行文本比较。 | **返回值:** | 条件 | **InStrRev**返回值 | |-----------------------------------------------------|--------------------------------| | *stringcheck*为零长度 | 0 | | *stringcheck*为**Null** | **Null** | | *stringmatch*为零长度 | *start* | | *stringmatch*为**Null** | **Null** | | *stringmatch*未找到 | 0 | | 在*stringcheck*中找到了*stringmatch* | 找到匹配的位置 | | *start* > **Len**(*stringcheck*) | 0 | ::: info **InStrRev**函数的语法与[**InStr**](/official/Reference/VBA/Strings/InStr)函数的语法不同——注意搜索参数的顺序不同。 ::: 除非*stringmatch*末尾字符的位置小于或等于*start*,否则**InStrRev**不会找到*stringmatch*的实例。 ### 示例 本示例使用**InStrRev**查找子字符串的最后一次出现。 ```vb Debug.Print InStrRev("a.b.c", ".") ' 4 — last dot Debug.Print InStrRev("a.b.c", ".", 3) ' 2 — last dot at or before position 3 Debug.Print InStrRev("a.b.c", "x") ' 0 — not found ``` ### 另请参阅 * [InStr](/official/Reference/VBA/Strings/InStr)函数 --- --- url: /en/official/Reference/VBA/Conversion/Int.md --- # Int Returns the integer portion of a number, rounding toward negative infinity. Syntax: **Int(** *number* **)** *number* : *required* A **Double** or any valid numeric expression. If *number* contains **Null**, **Null** is returned. **Int** removes the fractional part of *number* and returns the resulting integer value. If *number* is negative, **Int** returns the first negative integer less than or equal to *number*. For example, **Int** converts `-8.4` to `-9`. The return value has the same type as *number*. ::: info The closely related [**Fix**](/en/official/Reference/VBA/Conversion/Fix) function truncates toward zero rather than rounding toward negative infinity. For positive numbers the two are identical; for negative numbers they differ. ::: ### Example This example illustrates how the **Int** function returns the integer portion of a number. For a negative number argument, the **Int** function returns the first negative integer less than or equal to the number. ```vb Dim MyNumber MyNumber = Int(99.8) ' Returns 99. MyNumber = Int(-99.8) ' Returns -100. MyNumber = Int(-99.2) ' Returns -100. ``` ### See Also * [Fix](/en/official/Reference/VBA/Conversion/Fix), [CInt](/en/official/Reference/VBA/Conversion/CInt), [CLng](/en/official/Reference/VBA/Conversion/CLng) functions --- --- url: /zh/official/Reference/VBA/Conversion/Int.md --- # Int 返回数字的整数部分,向负无穷舍入。 语法:**Int(** *number* **)** *number* : *必需* **Double** 或任何有效的数值表达式。如果 *number* 包含 **Null**,则返回 **Null**。 **Int** 移除 *number* 的小数部分并返回结果整数值。如果 *number* 为负数,**Int** 返回小于或等于 *number* 的第一个负整数。例如,**Int** 将 `-8.4` 转换为 `-9`。 返回值的类型与 *number* 相同。 ::: info 密切相关的 [**Fix**](/official/Reference/VBA/Conversion/Fix) 函数向零截断而非向负无穷舍入。对于正数,两者相同;对于负数,它们不同。 ::: ### 示例 此示例说明 **Int** 函数如何返回数字的整数部分。对于负数参数,**Int** 函数返回小于或等于该数的第一个负整数。 ```vb Dim MyNumber MyNumber = Int(99.8) ' Returns 99. MyNumber = Int(-99.8) ' Returns -100. MyNumber = Int(-99.2) ' Returns -100. ``` ### 另请参阅 * [Fix](/official/Reference/VBA/Conversion/Fix)、[CInt](/official/Reference/VBA/Conversion/CInt)、[CLng](/official/Reference/VBA/Conversion/CLng) 函数 --- --- url: /en/official/Reference/VBA/Interaction.md --- # Interaction module The **Interaction** module groups together standalone procedures for everything that happens at the edges of a program --- talking to the user, branching on a value, launching another process, reading the environment or the registry, and creating, calling into, or raising events on COM objects. ## Asking the user something [**MsgBox**](/en/official/Reference/VBA/Interaction/MsgBox) shows a modal dialog with a message, an icon, and a chosen set of buttons; it returns a [**VbMsgBoxResult**](/en/official/Reference/VBA/Constants/VbMsgBoxResult) value identifying the button that was clicked. [**InputBox**](/en/official/Reference/VBA/Interaction/InputBox) shows a similar dialog with a text-entry field and returns the string the user typed (or an empty string if the user cancels). [**Beep**](/en/official/Reference/VBA/Interaction/Beep) sounds the system alert tone --- useful as an audible cue when a long-running operation finishes. ```vb Dim Answer As VbMsgBoxResult Answer = MsgBox("Save changes before closing?", vbYesNoCancel + vbQuestion, "Confirm") ``` ## Choosing a value The module offers four ways to pick one of several values inline: * [**If**](/en/official/Reference/VBA/Interaction/If) is the short-circuiting inline conditional -- a twinBASIC addition. Only the branch matching the condition is evaluated, so `If(Divisor <> 0, 100 / Divisor, "n/a")` is safe even when *Divisor* is zero. * [**IIf**](/en/official/Reference/VBA/Interaction/IIf) is the historical VBA inline conditional. Both *truepart* and *falsepart* are always evaluated, so it cannot guard against errors in the unused branch. * [**Choose**](/en/official/Reference/VBA/Interaction/Choose) returns the *index*-th item from a list of values -- a one-based equivalent of array indexing for a fixed-length argument list. * [**Switch**](/en/official/Reference/VBA/Interaction/Switch) iterates over pairs of *(condition, value)* arguments and returns the value paired with the first **True** condition -- a compact stand-in for an **If...ElseIf** ladder. ```vb Dim Status As Variant Status = Switch(Age < 13, "Child", _ Age < 20, "Teenager", _ Age < 65, "Adult", _ True, "Senior") ``` [**Partition**](/en/official/Reference/VBA/Interaction/Partition) is a related utility: it returns a printable label identifying which of a series of equal-width numeric ranges a value falls into. ## Launching and steering other processes [**Shell**](/en/official/Reference/VBA/Interaction/Shell) starts another program asynchronously and returns the new process's task ID; [**AppActivate**](/en/official/Reference/VBA/Interaction/AppActivate) brings an already-running application's window to the foreground, by title or by task ID. [**SendKeys**](/en/official/Reference/VBA/Interaction/SendKeys) feeds keystrokes to whichever window currently has focus, and [**DoEvents**](/en/official/Reference/VBA/Interaction/DoEvents) yields control back to the message loop so paint, input, and timer events can be dispatched in the middle of a long computation. ## The environment and the command line [**Command$**](/en/official/Reference/VBA/Interaction/Command) and [**Command**](/en/official/Reference/VBA/Interaction/Command) return the command-line arguments passed to the program when it was started. [**Environ$**](/en/official/Reference/VBA/Interaction/Environ) and [**Environ**](/en/official/Reference/VBA/Interaction/Environ) return the value of a process environment variable, looked up either by name or by 1-based index in the environment block. ## Per-user application settings The registry-setting helpers read and write per-user values under `HKEY_CURRENT_USER\Software\VB and VBA Program Settings`, mirroring the storage convention used by VB6. [**SaveSetting**](/en/official/Reference/VBA/Interaction/SaveSetting) writes a single key, [**GetSetting**](/en/official/Reference/VBA/Interaction/GetSetting) reads it back (with an optional default for missing keys), [**GetAllSettings**](/en/official/Reference/VBA/Interaction/GetAllSettings) returns every key-value pair in a section as a two-column **Variant** array, and [**DeleteSetting**](/en/official/Reference/VBA/Interaction/DeleteSetting) removes a key, an entire section, or every setting belonging to an application. ```vb SaveSetting "MyApp", "Window", "Maximised", "True" Debug.Print GetSetting("MyApp", "Window", "Maximised", "False") ' "True" DeleteSetting "MyApp", "Window", "Maximised" ``` ## COM objects and dynamic dispatch [**CreateObject**](/en/official/Reference/VBA/Interaction/CreateObject) instantiates a new COM/Automation object given its ProgID or CLSID --- optionally on a remote machine when a *servername* is supplied. [**GetObject**](/en/official/Reference/VBA/Interaction/GetObject) is the dual: it either binds to a file (loading the application that owns it) or attaches to an already-running instance of an object class. Once an object reference is in hand, [**CallByName**](/en/official/Reference/VBA/Interaction/CallByName) and [**CallByDispId**](/en/official/Reference/VBA/Interaction/CallByDispId) invoke a method or property on it dynamically, when the member to call is only known at run time --- by name in the first case, or by raw IDispatch dispatch ID in the second. [**RaiseEventByName**](/en/official/Reference/VBA/Interaction/RaiseEventByName) and [**RaiseEventByName2**](/en/official/Reference/VBA/Interaction/RaiseEventByName2) raise an event on an object by event-name string --- the run-time equivalent of the **RaiseEvent** statement, useful when the event being raised isn't known at compile time. The two forms differ only in how the event arguments are supplied: as a packed **Variant** array, or as a variable-length argument list. ## Members * [AppActivate](/en/official/Reference/VBA/Interaction/AppActivate) -- activates an application window * [Beep](/en/official/Reference/VBA/Interaction/Beep) -- sounds a tone through the computer's speaker * [CallByDispId](/en/official/Reference/VBA/Interaction/CallByDispId) -- invokes a method or property on an object dynamically by IDispatch dispatch ID * [CallByName](/en/official/Reference/VBA/Interaction/CallByName) -- invokes a method or property on an object dynamically by name * [Choose](/en/official/Reference/VBA/Interaction/Choose) -- returns one value from a list, selected by 1-based index * [Command$, Command](/en/official/Reference/VBA/Interaction/Command) -- returns the command-line arguments passed to the program * [CreateObject](/en/official/Reference/VBA/Interaction/CreateObject) -- creates a new instance of a COM/Automation object * [DeleteSetting](/en/official/Reference/VBA/Interaction/DeleteSetting) -- deletes a section or key setting from an application's entry in the Windows registry * [DoEvents](/en/official/Reference/VBA/Interaction/DoEvents) -- yields control to the message loop so pending events can be processed * [Environ$, Environ](/en/official/Reference/VBA/Interaction/Environ) -- returns the value of a process environment variable * [GetAllSettings](/en/official/Reference/VBA/Interaction/GetAllSettings) -- returns every key/value pair in a section of an application's registry entry * [GetObject](/en/official/Reference/VBA/Interaction/GetObject) -- returns a reference to an Automation object loaded from a file or already running * [GetSetting](/en/official/Reference/VBA/Interaction/GetSetting) -- returns a key setting value from an application's entry in the Windows registry * [If](/en/official/Reference/VBA/Interaction/If) -- evaluates an expression and returns one of two values, with short-circuit evaluation * [IIf](/en/official/Reference/VBA/Interaction/IIf) -- evaluates an expression and returns one of two values; both branches are always evaluated * [InputBox](/en/official/Reference/VBA/Interaction/InputBox) -- prompts the user for a line of text and returns what was entered * [MsgBox](/en/official/Reference/VBA/Interaction/MsgBox) -- displays a modal message dialog and returns the button the user clicked * [Partition](/en/official/Reference/VBA/Interaction/Partition) -- returns a string identifying the range a number falls into * [RaiseEventByName](/en/official/Reference/VBA/Interaction/RaiseEventByName) -- raises an event by name on an object, taking arguments as a **Variant** array * [RaiseEventByName2](/en/official/Reference/VBA/Interaction/RaiseEventByName2) -- raises an event by name on an object, taking a variable-length argument list * [SaveSetting](/en/official/Reference/VBA/Interaction/SaveSetting) -- saves or creates a key setting in an application's entry in the Windows registry * [SendKeys](/en/official/Reference/VBA/Interaction/SendKeys) -- sends keystrokes to the active window * [Shell](/en/official/Reference/VBA/Interaction/Shell) -- runs another program asynchronously and returns its task ID * [Switch](/en/official/Reference/VBA/Interaction/Switch) -- returns the value paired with the first **True** condition in a list of (condition, value) pairs --- --- url: /zh/official/Reference/VBA/Interaction.md --- # Interaction模块 **Interaction**模块将程序边缘发生的所有独立过程组合在一起——与用户交互、根据值分支、启动另一个进程、读取环境变量或注册表、创建/调用/引发COM对象上的事件。 ## 向用户提问 [**MsgBox**](/official/Reference/VBA/Interaction/MsgBox)显示一个包含消息、图标和选定按钮集的模式对话框;它返回一个[**VbMsgBoxResult**](/official/Reference/VBA/Constants/VbMsgBoxResult)值,标识被点击的按钮。[**InputBox**](/official/Reference/VBA/Interaction/InputBox)显示一个带有文本输入字段的类似对话框,返回用户输入的字符串(如果用户取消则返回空字符串)。[**Beep**](/official/Reference/VBA/Interaction/Beep)发出系统提示音——在长时间运行的操作完成时作为声音提示很有用。 ```vb Dim Answer As VbMsgBoxResult Answer = MsgBox("Save changes before closing?", vbYesNoCancel + vbQuestion, "Confirm") ``` ## 选择值 该模块提供四种内联选择值的方式: * [**If**](/official/Reference/VBA/Interaction/If)是短路内联条件——twinBASIC新增。只评估匹配条件的分支,因此`If(Divisor <> 0, 100 / Divisor, "n/a")`即使*Divisor*为零也是安全的。 * [**IIf**](/official/Reference/VBA/Interaction/IIf)是历史VBA内联条件。*truepart*和*falsepart*始终都会被评估,因此无法防止未使用分支中的错误。 * [**Choose**](/official/Reference/VBA/Interaction/Choose)从值列表中返回第*index*项——对于固定长度参数列表,等效于基于1的数组索引。 * [**Switch**](/official/Reference/VBA/Interaction/Switch)遍历\*(条件, 值)\*参数对,返回与第一个**True**条件配对的值——**If...ElseIf**阶梯的紧凑替代。 ```vb Dim Status As Variant Status = Switch(Age < 13, "Child", _ Age < 20, "Teenager", _ Age < 65, "Adult", _ True, "Senior") ``` [**Partition**](/official/Reference/VBA/Interaction/Partition)是相关工具:返回一个可打印标签,标识某个值落入一系列等宽数值范围中的哪一个。 ## 启动和操控其他进程 [**Shell**](/official/Reference/VBA/Interaction/Shell)异步启动另一个程序并返回新进程的任务ID;[**AppActivate**](/official/Reference/VBA/Interaction/AppActivate)通过标题或任务ID将已运行应用程序的窗口带到前台。[**SendKeys**](/official/Reference/VBA/Interaction/SendKeys)向当前具有焦点的窗口发送按键,[**DoEvents**](/official/Reference/VBA/Interaction/DoEvents)将控制权交还给消息循环,以便在长时间计算期间分派绘制、输入和定时器事件。 ## 环境变量和命令行 [**Command$**](/official/Reference/VBA/Interaction/Command)和[**Command**](/official/Reference/VBA/Interaction/Command)返回程序启动时传入的命令行参数。[**Environ$**](/official/Reference/VBA/Interaction/Environ)和[**Environ**](/official/Reference/VBA/Interaction/Environ)返回进程环境变量的值,可按名称或环境块中基于1的索引查找。 ## 每用户应用程序设置 注册表设置辅助函数在`HKEY_CURRENT_USER\Software\VB and VBA Program Settings`下读写每用户的值,映射VB6使用的存储约定。[**SaveSetting**](/official/Reference/VBA/Interaction/SaveSetting)写入单个键,[**GetSetting**](/official/Reference/VBA/Interaction/GetSetting)读回(对缺失键可提供可选默认值),[**GetAllSettings**](/official/Reference/VBA/Interaction/GetAllSettings)返回某个节中所有键值对作为两列**Variant**数组,[**DeleteSetting**](/official/Reference/VBA/Interaction/DeleteSetting)删除一个键、整个节或应用程序的所有设置。 ```vb SaveSetting "MyApp", "Window", "Maximised", "True" Debug.Print GetSetting("MyApp", "Window", "Maximised", "False") ' "True" DeleteSetting "MyApp", "Window", "Maximised" ``` ## COM对象和动态调度 [**CreateObject**](/official/Reference/VBA/Interaction/CreateObject)根据ProgID或CLSID实例化新的COM/Automation对象——当提供*servername*时可选择在远程机器上创建。[**GetObject**](/official/Reference/VBA/Interaction/GetObject)是其对偶:它可以绑定到文件(加载拥有该文件的应用程序)或附加到已运行的对象类实例。 获得对象引用后,[**CallByName**](/official/Reference/VBA/Interaction/CallByName)和[**CallByDispId**](/official/Reference/VBA/Interaction/CallByDispId)在运行时动态调用对象上的方法或属性——前者按名称查找,后者按原始IDispatch调度ID查找。[**RaiseEventByName**](/official/Reference/VBA/Interaction/RaiseEventByName)和[**RaiseEventByName2**](/official/Reference/VBA/Interaction/RaiseEventByName2)按事件名字符串在对象上引发事件——**RaiseEvent**语句的运行时等价物,当引发的事件在编译时未知时非常有用。两种形式的区别仅在于事件参数的提供方式:作为打包的**Variant**数组,或作为可变长度参数列表。 ## 成员 * [AppActivate](/official/Reference/VBA/Interaction/AppActivate) -- 激活应用程序窗口 * [Beep](/official/Reference/VBA/Interaction/Beep) -- 通过计算机扬声器发出提示音 * [CallByDispId](/official/Reference/VBA/Interaction/CallByDispId) -- 通过IDispatch调度ID动态调用对象上的方法或属性 * [CallByName](/official/Reference/VBA/Interaction/CallByName) -- 通过名称动态调用对象上的方法或属性 * [Choose](/official/Reference/VBA/Interaction/Choose) -- 从列表中按基于1的索引返回一个值 * [Command$, Command](/official/Reference/VBA/Interaction/Command) -- 返回传给程序的命令行参数 * [CreateObject](/official/Reference/VBA/Interaction/CreateObject) -- 创建COM/Automation对象的新实例 * [DeleteSetting](/official/Reference/VBA/Interaction/DeleteSetting) -- 从Windows注册表中应用程序条目删除节或键设置 * [DoEvents](/official/Reference/VBA/Interaction/DoEvents) -- 将控制权交还给消息循环以处理挂起事件 * [Environ$, Environ](/official/Reference/VBA/Interaction/Environ) -- 返回进程环境变量的值 * [GetAllSettings](/official/Reference/VBA/Interaction/GetAllSettings) -- 返回应用程序注册表条目某个节中的所有键值对 * [GetObject](/official/Reference/VBA/Interaction/GetObject) -- 返回从文件加载或已运行的Automation对象的引用 * [GetSetting](/official/Reference/VBA/Interaction/GetSetting) -- 从Windows注册表中应用程序条目返回键设置值 * [If](/official/Reference/VBA/Interaction/If) -- 求值表达式并返回两个值之一,采用短路求值 * [IIf](/official/Reference/VBA/Interaction/IIf) -- 求值表达式并返回两个值之一;两个分支始终都被评估 * [InputBox](/official/Reference/VBA/Interaction/InputBox) -- 提示用户输入一行文本并返回所输入内容 * [MsgBox](/official/Reference/VBA/Interaction/MsgBox) -- 显示模式消息对话框并返回用户点击的按钮 * [Partition](/official/Reference/VBA/Interaction/Partition) -- 返回标识数字所属范围的字符串 * [RaiseEventByName](/official/Reference/VBA/Interaction/RaiseEventByName) -- 按名称在对象上引发事件,参数作为**Variant**数组传入 * [RaiseEventByName2](/official/Reference/VBA/Interaction/RaiseEventByName2) -- 按名称在对象上引发事件,接受可变长度参数列表 * [SaveSetting](/official/Reference/VBA/Interaction/SaveSetting) -- 在Windows注册表中应用程序条目保存或创建键设置 * [SendKeys](/official/Reference/VBA/Interaction/SendKeys) -- 向活动窗口发送按键 * [Shell](/official/Reference/VBA/Interaction/Shell) -- 异步运行另一个程序并返回其任务ID * [Switch](/official/Reference/VBA/Interaction/Switch) -- 返回(条件, 值)对列表中与第一个**True**条件配对的值 --- --- url: /en/official/Reference/Core/Interface.md --- # Interface Defines a COM interface using twinBASIC syntax. An interface is a contract: a named set of method and property prototypes, with no implementation. Classes provide implementations of interfaces by using the [**Implements**](/en/official/Reference/Core/Implements) statement. ::: info The **Interface** block is a twinBASIC extension. In classic VBA there is no interface keyword --- interfaces could only be defined indirectly via a referenced type library (IDL/C++) or by using a class with no implementation. ::: Syntax: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Interface** *name* \[ **Extends** *baseinterface* \[ **,** *baseinterface* ] ... ]\ >      \[ *attributes* ]\ >      *member-prototype*\ >      ...\ > **End Interface** *attributes* : *optional* Interface- and member-level attributes. See [Available attributes](#available-attributes) below. *name* : The identifier naming the interface. By convention an interface name begins with an uppercase `I` (`IFoo`, `ICalculator`, ...). *baseinterface* : *optional* One or more interfaces that *name* extends. An implementing class is required to provide bodies for the inherited methods as well; in twinBASIC, a class can `Implements` *name* and rely on the inherited interfaces being satisfied automatically. *member-prototype* : A header-only declaration. May be a [**Sub**](/en/official/Reference/Core/Sub), [**Function**](/en/official/Reference/Core/Function), [**Property Get**](/en/official/Reference/Core/Property), [**Property Let**](/en/official/Reference/Core/Property), or [**Property Set**](/en/official/Reference/Core/Property) signature, with arguments and return type. **Public**/**Private**/**Friend** modifiers are *not* allowed on members. There is no `End Sub` / `End Function` / `End Property` --- the prototype ends at end of line. **Interface** blocks are valid only in `.twin` source files (not legacy `.bas` or `.cls` files), and must appear *before* the [**Class**](/en/official/Reference/Core/Class) or [**Module**](/en/official/Reference/Core/Module) statement in the file. Interfaces always have project-wide scope. ### Available attributes Interface-level attributes: * `[InterfaceId("...")]` --- fixes the IID for the interface (a string GUID). Set this on any public/exported interface so consumers in other projects bind to a stable identity. * `[Description("text")]` --- exposed as the `helpstring` in the type library. * `[Hidden]` --- hides the interface from IntelliSense and similar lists. * `[Restricted]` --- restricts the interface methods from being called in most contexts. * `[OleAutomation(True/False)]` --- controls whether the attribute is applied in the type library. `True` by default. * `[ComImport]` --- declares the interface as an import from an external COM library (e.g., the Windows shell). * `[ComExtensible(True/False)]` --- controls whether dynamically-added members can be invoked through `IDispatch`. `False` by default. Member-level attributes: * `[Description("text")]` * `[PreserveSig]` --- keeps the raw COM signature (returning `HRESULT`) instead of having the runtime translate negative results into errors. Use this when the literal return value is required, or when negative values mean *acceptable failure* (e.g. an enumerator running out of items). * `[DispId(number)]` --- fixes the dispatch ID associated with the member. ### Example ```vb [InterfaceId("E7064791-0E4A-425B-8C8F-08802AAFEE61")] [Description("Defines the IFoo interface")] [OleAutomation(False)] Interface IFoo Extends IUnknown Sub MySub(Arg1 As Long) Function Clone() As IFoo [PreserveSig] Function MyFunc([TypeHint(MyEnum)] Arg1 As Variant) As Boolean End Interface ``` A class that implements `IFoo` provides bodies for every member: ```vb Class FooImpl Implements IFoo Private Sub IFoo_MySub(Arg1 As Long) Implements IFoo.MySub Debug.Print "MySub called with"; Arg1 End Sub Private Function IFoo_Clone() As IFoo Implements IFoo.Clone Set IFoo_Clone = New FooImpl End Function Private Function IFoo_MyFunc(Arg1 As Variant) As Boolean Implements IFoo.MyFunc IFoo_MyFunc = True End Function End Class ``` ### See Also * [**Implements** statement](/en/official/Reference/Core/Implements) * [**CoClass** statement](/en/official/Reference/Core/CoClass) * [**Class** statement](/en/official/Reference/Core/Class) * [Interfaces and CoClasses](/en/official/Features/Language/Interfaces-CoClasses) * [Inheritance](/en/official/Features/Language/Inheritance) --- --- url: /zh/official/Reference/Core/Interface.md --- # Interface 使用twinBASIC语法定义COM接口。接口是契约:一组命名的无实现的方法和属性原型。类通过使用 [**Implements**](/official/Reference/Core/Implements) 语句提供接口的实现。 ::: info **Interface** 块是twinBASIC扩展。在经典VBA中没有interface关键字——接口只能通过引用的类型库(IDL/C++)间接定义,或使用无实现的类。 ::: 语法: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Interface** *name* \[ **Extends** *baseinterface* \[ **,** *baseinterface* ] ... ]\ >      \[ *attributes* ]\ >      *member-prototype*\ >      ...\ > **End Interface** *attributes* : *可选* 接口和成员级别的属性。参见下文[可用属性](#available-attributes)。 *name* : 命名接口的标识符。按照惯例,接口名以大写 `I` 开头(`IFoo`、`ICalculator`、...)。 *baseinterface* : *可选* *name* 扩展的一个或多个接口。实现类需要为继承的方法也提供函数体;在twinBASIC中,类可以 `Implements` *name* 并依赖继承的接口自动满足。 *member-prototype* : 仅头部的声明。可以是 [**Sub**](/official/Reference/Core/Sub)、[**Function**](/official/Reference/Core/Function)、[**Property Get**](/official/Reference/Core/Property)、[**Property Let**](/official/Reference/Core/Property) 或 [**Property Set**](/official/Reference/Core/Property) 签名,包含参数和返回类型。成员上不允许使用 **Public**/**Private**/**Friend** 修饰符。没有 `End Sub` / `End Function` / `End Property`——原型在行尾结束。 **Interface** 块仅在 `.twin` 源文件中有效(不支持传统 `.bas` 或 `.cls` 文件),且必须出现在文件中 [**Class**](/official/Reference/Core/Class) 或 [**Module**](/official/Reference/Core/Module) 语句*之前*。接口始终具有项目范围的作用域。 ### 可用属性 接口级别属性: * `[InterfaceId("...")]`——固定接口的IID(字符串GUID)。在任何公共/导出的接口上设置此项,以便其他项目的使用者绑定到稳定的标识。 * `[Description("text")]`——在类型库中作为 `helpstring` 公开。 * `[Hidden]`——从IntelliSense和类似列表中隐藏接口。 * `[Restricted]`——限制接口方法在大多数上下文中被调用。 * `[OleAutomation(True/False)]`——控制属性是否在类型库中应用。默认为 `True`。 * `[ComImport]`——将接口声明为从外部COM库(如Windows shell)导入。 * `[ComExtensible(True/False)]`——控制是否可以通过 `IDispatch` 调用动态添加的成员。默认为 `False`。 成员级别属性: * `[Description("text")]` * `[PreserveSig]`——保留原始COM签名(返回 `HRESULT`),而不让运行时将负值结果转换为错误。当需要字面返回值,或负值表示*可接受的失败*(如枚举器用尽项目)时使用此属性。 * `[DispId(number)]`——固定与成员关联的调度ID。 ### 示例 ```vb [InterfaceId("E7064791-0E4A-425B-8C8F-08802AAFEE61")] [Description("Defines the IFoo interface")] [OleAutomation(False)] Interface IFoo Extends IUnknown Sub MySub(Arg1 As Long) Function Clone() As IFoo [PreserveSig] Function MyFunc([TypeHint(MyEnum)] Arg1 As Variant) As Boolean End Interface ``` 实现 `IFoo` 的类为每个成员提供函数体: ```vb Class FooImpl Implements IFoo Private Sub IFoo_MySub(Arg1 As Long) Implements IFoo.MySub Debug.Print "MySub called with"; Arg1 End Sub Private Function IFoo_Clone() As IFoo Implements IFoo.Clone Set IFoo_Clone = New FooImpl End Function Private Function IFoo_MyFunc(Arg1 As Variant) As Boolean Implements IFoo.MyFunc IFoo_MyFunc = True End Function End Class ``` ### 另请参阅 * [**Implements** 语句](/official/Reference/Core/Implements) * [**CoClass** 语句](/official/Reference/Core/CoClass) * [**Class** 语句](/official/Reference/Core/Class) * [接口与CoClass](/official/Features/Language/Interfaces-CoClasses) * [继承](/official/Features/Language/Inheritance) --- --- url: /en/official/Features/Language/Interfaces-CoClasses.md --- # Interfaces, CoClasses, and Aliases twinBASIC supports these features as native language syntax where in VBx they were only supported via Type Libraries. ## Defining Interfaces twinBASIC supports defining COM interfaces using BASIC syntax, rather than needing an type library with IDL and C++. These are only supported in .twin files, not in legacy .bas or .cls files. They must appear *before* the `Class` or `Module` statement, and will always have a project-wide scope. The generic form for this is as follows: ```vb [InterfaceId ("00000000-0000-0000-0000-000000000000")] '*<attributes>* Interface name Extends base_interface '*<attributes>* '<method 1> '*<attributes>* '<method 2> '... End Interface ``` Methods can be any of the following: `Sub`, `Function`, `Property Get`, `Property Let`, or `Property Set`, with arguments following the standard syntax, and with the standard attributes available. These cannot be modified with `Public/Private/Friend`. `End <method>` is not used, as these are prototype definitions only. ### Available Attributes for Interfaces * `[Description("text")]` - Provides a description in information popups, and is exported as a `helpstring` attribute in the type library (if applicable). * `[Hidden]` - Hides the interface from certain Intellisense and other lists. * `[Restricted]` - Restricts the interface methods from being called in most contexts. * `[OleAutomation(True/False)]` - Controls whether this attribute is applied in the typelibrary. This attribute is set to **True** by default. * `[ComImport]` - Specifies that an interface is an import from an external COM library, for instance, the Windows shell. * `[ComExtensible(True/False)]` - Specifies whether new members added at runtime can be called by name through an interface implementing IDispatch. This attribute is set to **False** by default. ### Available Attributes for Methods * `[Description("text")]` - Provides a description * `[PreserveSig]` - For COM interfaces, normally methods return an HRESULT that the language hides from you. The `[PreserveSig]` attribute overrides this behavior and defines the function exactly as you provide. This is necessary if you need to define it as returning something other than a 4-byte `Long`, or want to handle the result yourself, bypassing the normal runtime error raised if the return value is negative (this is helpful when a negative value indicates an expected, acceptable failure, rather than a true error, like when an enum interface is out of items). * `[DispId(number)]` - Defines a dispatch ID associated with the method. ### Example ```vb [InterfaceId("E7064791-0E4A-425B-8C8F-08802AAFEE61")] [Description("Defines the IFoo interface")] [OleAutomation(False)] Interface IFoo Extends IUnknown Sub MySub(Arg1 As Long) Function Clone() As IFoo [PreserveSig] Function MyFunc([TypeHint(MyEnum)] Arg1 As Variant) As Boolean End Interface ``` (Where MyEnum is a standard `Enum ... End Enum` block.) ## Defining CoClasses In addition to interfaces, twinBASIC also allows defining coclasses -- creatable classes that implement one or more defined interfaces. Like interfaces, these too must be in .twin files and not legacy .bas/.cls files, and must appear prior to the `Class` or `Module` statement. The generic form is: ```vb [CoClassId("00000000-0000-0000-0000-000000000000")] '<attributes> CoClass name [Default] Interface interface_name [Default, Source] Interface event_interface_name 'additional Interface items> End CoClass ``` Each coclass must specify at least one interface but may have several more. It can optionally mark an interface as default or a source. It is typical and highly recommended that an interface be marked with `[Default]` attribute and in cases where it has events to also specify `[Default, Source]` to indicate the default interface used for events. Each represents a contract that the class will provide an implementation of the given interface. Note that at this time, twinBASIC does not yet support defining `dispinterface` interfaces (aka, dispatch-only interface) the usual form of source interfaces for events. ### Attributes for Coclasses * `[Description("text")]` - Provides a description in info popups and other places. * `[ComCreatable(True/False)]` - Indicates that this coclass can be created with the `New` keyword. This is *True* by default. * `[AppObject]` - Indicates the class is part of the global namespace. You should not include this attribute without a full understanding of the meaning. * `[Hidden]` - Hides the coclass from appearing in certain places. * `[CoClassCustomConstructor("fully qualified path to factory method")]` - Allows custom logic for creating and returning a new instance of the coclass' implementation. ### Example ```vb [CoClassId("52112FA1-FBE4-11CA-B5DD-0020AFE7292D")] CoClass Foo [Default] Interface IFoo Interface IBar End CoClass ``` Where `IFoo` and `IBar` are interfaces defined with the `Interface` syntax described earlier. ## Custom Constructor Example ```vb [InterfaceId("016BC30A-A8E0-4AAF-93AE-13BD838A149E")] Public Interface IFoo Sub Foo() End Interface [InterfaceId("2A20E655-30A4-4534-86BC-6A7E281C425D")] Public Interface IBar Sub Bar() End Interface [CoClassId("7980D953-10BF-478C-93BB-DD0093315D96")] [CoClassCustomConstructor("FooFactory.CreateFoo")] [COMCreatable(True)] Public CoClass Foo [Default] Interface IFoo Interface IBar End CoClass ' The implementation do not have to be exposed. The coclass is a sufficient description ' and we should implement the interfaces that the coclass exposes. Private Class FooImpl Implements IFoo Implements IBar Public Sub Foo() Implements IFoo.Foo Debug.Print "Foo ran" End Sub Public Sub Bar() Implements IBar.Bar Debug.Print "Bar ran" End Sub End Class Public Module FooFactory ' The signature must be "preserved", returning a HRESULT ' and the new instance via the "out" parameter. ' Note that we new up the FooImpl but return the Foo coclass. Public Function CreateFoo(ByRef RHS As Foo) As Long Set RHS = New FooImpl Return 0 ' S_OK End Function End Module Public Module Test Public Sub DoIt() Dim MyFoo As Foo ' create a new instance of coclass Foo ' this implicilty calls the custom constructor ' in the FooFactory. Set MyFoo = New Foo MyFoo.Foo End Sub End Module ``` --- --- url: /en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32.md --- # InterlockedCompareExchange32 Atomically compares a 32-bit value at a memory location with a comparand and replaces it with a new value if they match. Returns the original value either way. Syntax: **InterlockedCompareExchange32(** *Target* **,** *NewValue* **,** *OldValueCompare* **)** **As Long** *Target* : *required* **Long**. The 32-bit variable to update, passed by reference. *NewValue* : *required* **Long**. The value to write into *Target* if the compare succeeds. *OldValueCompare* : *required* **Long**. The expected current value of *Target*. The compare-and-swap happens as one atomic operation. The return value is the value that was in *Target* at the start of the call --- equal to *OldValueCompare* on success, anything else on failure (in which case *Target* is left unchanged). Wraps the Win32 `InterlockedCompareExchange` intrinsic. ### See Also * [InterlockedCompareExchange64](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64) function * [InterlockedCompareExchangePointer](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer) function * [InterlockedIncrement32](/en/official/Reference/VBA/HiddenModule/InterlockedIncrement32), [InterlockedDecrement32](/en/official/Reference/VBA/HiddenModule/InterlockedDecrement32) functions --- --- url: /zh/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32.md --- # InterlockedCompareExchange32 原子地将内存位置的32位值与比较值进行比较,如果匹配则替换为新值。无论哪种情况都返回原始值。 语法:**InterlockedCompareExchange32(** *Target* **,** *NewValue* **,** *OldValueCompare* **)** **As Long** *Target* : *必需* **Long**。要更新的32位变量,按引用传递。 *NewValue* : *必需* **Long**。比较成功时写入*Target*的值。 *OldValueCompare* : *必需* **Long**。*Target*的预期当前值。 比较和交换作为一个原子操作发生。返回值是调用开始时*Target*中的值——成功时等于*OldValueCompare*,失败时为其他值(此时*Target*保持不变)。封装了Win32的`InterlockedCompareExchange`内联函数。 ### 另请参阅 * [InterlockedCompareExchange64](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64)函数 * [InterlockedCompareExchangePointer](/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer)函数 * [InterlockedIncrement32](/official/Reference/VBA/HiddenModule/InterlockedIncrement32)、[InterlockedDecrement32](/official/Reference/VBA/HiddenModule/InterlockedDecrement32)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64.md --- # InterlockedCompareExchange64 Atomically compares a 64-bit value at a memory location with a comparand and replaces it with a new value if they match. Returns the original value either way. Syntax: **InterlockedCompareExchange64(** *Target* **,** *NewValue* **,** *OldValueCompare* **)** **As LongLong** *Target* : *required* **LongLong**. The 64-bit variable to update, passed by reference. *NewValue* : *required* **LongLong**. The value to write into *Target* if the compare succeeds. *OldValueCompare* : *required* **LongLong**. The expected current value of *Target*. The compare-and-swap happens as one atomic operation. The return value is the value that was in *Target* at the start of the call --- equal to *OldValueCompare* on success, anything else on failure (in which case *Target* is left unchanged). Wraps the Win32 `InterlockedCompareExchange64` intrinsic. ### See Also * [InterlockedCompareExchange32](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32) function * [InterlockedCompareExchangePointer](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer) function --- --- url: /zh/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64.md --- # InterlockedCompareExchange64 原子地将内存位置的64位值与比较值进行比较,如果匹配则替换为新值。无论哪种情况都返回原始值。 语法:**InterlockedCompareExchange64(** *Target* **,** *NewValue* **,** *OldValueCompare* **)** **As LongLong** *Target* : *必需* **LongLong**。要更新的64位变量,按引用传递。 *NewValue* : *必需* **LongLong**。比较成功时写入*Target*的值。 *OldValueCompare* : *必需* **LongLong**。*Target*的预期当前值。 比较和交换作为一个原子操作发生。返回值是调用开始时*Target*中的值——成功时等于*OldValueCompare*,失败时为其他值(此时*Target*保持不变)。封装了Win32的`InterlockedCompareExchange64`内联函数。 ### 另请参阅 * [InterlockedCompareExchange32](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32)函数 * [InterlockedCompareExchangePointer](/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer.md --- # InterlockedCompareExchangePointer Atomically compares a pointer-sized value at a memory location with a comparand and replaces it with a new value if they match. Returns the original value either way. Syntax: **InterlockedCompareExchangePointer(** *Target* **,** *NewValue* **,** *OldValueCompare* **)** **As LongPtr** *Target* : *required* **LongPtr**. The pointer-sized variable to update, passed by reference. *NewValue* : *required* **LongPtr**. The value to write into *Target* if the compare succeeds. *OldValueCompare* : *required* **LongPtr**. The expected current value of *Target*. The compare-and-swap happens as one atomic operation. The return value is the value that was in *Target* at the start of the call --- equal to *OldValueCompare* on success, anything else on failure (in which case *Target* is left unchanged). Wraps the Win32 `InterlockedCompareExchangePointer` intrinsic. ### Example ```vb ' Atomically claim ownership of a slot. Dim Slot As LongPtr = 0 Dim NewObj As LongPtr = ObjPtr(New Collection) If InterlockedCompareExchangePointer(Slot, NewObj, 0) = 0 Then ' Won the race — Slot now holds NewObj. End If ``` ### See Also * [InterlockedExchangePointer](/en/official/Reference/VBA/HiddenModule/InterlockedExchangePointer) function * [InterlockedCompareExchange32](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32), [InterlockedCompareExchange64](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64) functions --- --- url: /zh/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer.md --- # InterlockedCompareExchangePointer 原子地将内存位置的指针大小值与比较值进行比较,如果匹配则替换为新值。无论哪种情况都返回原始值。 语法:**InterlockedCompareExchangePointer(** *Target* **,** *NewValue* **,** *OldValueCompare* **)** **As LongPtr** *Target* : *必需* **LongPtr**。要更新的指针大小变量,按引用传递。 *NewValue* : *必需* **LongPtr**。比较成功时写入*Target*的值。 *OldValueCompare* : *必需* **LongPtr**。*Target*的预期当前值。 比较和交换作为一个原子操作发生。返回值是调用开始时*Target*中的值——成功时等于*OldValueCompare*,失败时为其他值(此时*Target*保持不变)。封装了Win32的`InterlockedCompareExchangePointer`内联函数。 ### 示例 ```vb ' Atomically claim ownership of a slot. Dim Slot As LongPtr = 0 Dim NewObj As LongPtr = ObjPtr(New Collection) If InterlockedCompareExchangePointer(Slot, NewObj, 0) = 0 Then ' Won the race — Slot now holds NewObj. End If ``` ### 另请参阅 * [InterlockedExchangePointer](/official/Reference/VBA/HiddenModule/InterlockedExchangePointer)函数 * [InterlockedCompareExchange32](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32)、[InterlockedCompareExchange64](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/InterlockedDecrement32.md --- # InterlockedDecrement32 Atomically decrements a 32-bit value by one and returns the new value. Syntax: **InterlockedDecrement32(** *Target* **)** **As Long** *Target* : *required* **Long**. The 32-bit variable to decrement, passed by reference. The read, subtract, and write happen as one atomic operation. The return value is the post-decrement value of *Target* --- testing against zero is the canonical way to spot the last release of a refcounted resource. Wraps the Win32 `InterlockedDecrement` intrinsic. ### See Also * [InterlockedIncrement32](/en/official/Reference/VBA/HiddenModule/InterlockedIncrement32) function * [InterlockedCompareExchange32](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32) function --- --- url: /zh/official/Reference/VBA/HiddenModule/InterlockedDecrement32.md --- # InterlockedDecrement32 原子地将32位值减一并返回新值。 语法:**InterlockedDecrement32(** *Target* **)** **As Long** *Target* : *必需* **Long**。要递减的32位变量,按引用传递。 读取、减法和写入作为一个原子操作发生。返回值是*Target*递减后的值——与零比较是发现引用计数资源最后一次释放的典型方式。封装了Win32的`InterlockedDecrement`内联函数。 ### 另请参阅 * [InterlockedIncrement32](/official/Reference/VBA/HiddenModule/InterlockedIncrement32)函数 * [InterlockedCompareExchange32](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/InterlockedExchangePointer.md --- # InterlockedExchangePointer Atomically exchanges a pointer-sized value at a memory location and returns the previous value. Syntax: **InterlockedExchangePointer(** *Target* **,** *NewValue* **)** **As LongPtr** *Target* : *required* **LongPtr**. The pointer-sized variable to update, passed by reference. *NewValue* : *required* **LongPtr**. The new value to store at *Target*. The store and the read of the prior value happen as a single atomic operation, observable by other threads as either fully-before or fully-after the call. Wraps the Win32 `InterlockedExchangePointer` intrinsic. ### See Also * [InterlockedCompareExchangePointer](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer) function * [InterlockedCompareExchange32](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32), [InterlockedCompareExchange64](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64) functions --- --- url: /zh/official/Reference/VBA/HiddenModule/InterlockedExchangePointer.md --- # InterlockedExchangePointer 原子地交换内存位置的指针大小值并返回之前的值。 语法:**InterlockedExchangePointer(** *Target* **,** *NewValue* **)** **As LongPtr** *Target* : *必需* **LongPtr**。要更新的指针大小变量,按引用传递。 *NewValue* : *必需* **LongPtr**。要存储在*Target*的新值。 存储和读取之前的值作为单个原子操作发生,其他线程可观测到该操作要么完全在调用之前,要么完全在调用之后。封装了Win32的`InterlockedExchangePointer`内联函数。 ### 另请参阅 * [InterlockedCompareExchangePointer](/official/Reference/VBA/HiddenModule/InterlockedCompareExchangePointer)函数 * [InterlockedCompareExchange32](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32)、[InterlockedCompareExchange64](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange64)函数 --- --- url: /en/official/Reference/VBA/HiddenModule/InterlockedIncrement32.md --- # InterlockedIncrement32 Atomically increments a 32-bit value by one and returns the new value. Syntax: **InterlockedIncrement32(** *Target* **)** **As Long** *Target* : *required* **Long**. The 32-bit variable to increment, passed by reference. The read, add, and write happen as one atomic operation. The return value is the post-increment value of *Target*. Wraps the Win32 `InterlockedIncrement` intrinsic. ### See Also * [InterlockedDecrement32](/en/official/Reference/VBA/HiddenModule/InterlockedDecrement32) function * [InterlockedCompareExchange32](/en/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32) function --- --- url: /zh/official/Reference/VBA/HiddenModule/InterlockedIncrement32.md --- # InterlockedIncrement32 原子地将32位值加一并返回新值。 语法:**InterlockedIncrement32(** *Target* **)** **As Long** *Target* : *必需* **Long**。要递增的32位变量,按引用传递。 读取、加法和写入作为一个原子操作发生。返回值是*Target*递增后的值。封装了Win32的`InterlockedIncrement`内联函数。 ### 另请参阅 * [InterlockedDecrement32](/official/Reference/VBA/HiddenModule/InterlockedDecrement32)函数 * [InterlockedCompareExchange32](/official/Reference/VBA/HiddenModule/InterlockedCompareExchange32)函数 --- --- url: /zh/packages/vbccr/lists/ipaddress.md description: IP 地址控件(IPAddress) - VBCCR 开发手册,基于源码的完整 API 参考 --- # IP 地址控件(IPAddress) 封装 SysIPAddress32 系统控件,用于输入和显示 IPv4 地址。 ## 枚举 ### IPATextConstants | 常量 | 值 | 说明 | |------|-----|------| | IPAEmpty | 0 | 空地址 | | IPAInvalid | -1 | 无效地址 | ### IPAFocusConstants | 常量 | 值 | 说明 | |------|-----|------| | IPAFocusField1 | 0 | 第 1 字段 | | IPAFocusField2 | 1 | 第 2 字段 | | IPAFocusField3 | 2 | 第 3 字段 | | IPAFocusField4 | 3 | 第 4 字段 | ### CCAppearanceConstants 参见通用枚举。 ### CCBorderStyleConstants 参见通用枚举。 ### CCMousePointerConstants 参见通用枚举。 ### CCIMEModeConstants 参见通用枚举。 ### CCRightToLeftModeConstants 参见通用枚举。 ### OLEDropModeConstants 参见通用枚举。 ## 属性 ### Text ```vb Property Get Text() As IPATextConstants Property Let Text(ByVal Value As IPATextConstants) ``` IP 地址的数值表示。IPAEmpty(0)表示空地址,IPAInvalid(-1)表示无效地址。 ### Field1 ```vb Property Get Field1() As Byte Property Let Field1(ByVal Value As Byte) ``` 第 1 字段值(0-255)。 ### Field2 ```vb Property Get Field2() As Byte Property Let Field2(ByVal Value As Byte) ``` 第 2 字段值(0-255)。 ### Field3 ```vb Property Get Field3() As Byte Property Let Field3(ByVal Value As Byte) ``` 第 3 字段值(0-255)。 ### Field4 ```vb Property Get Field4() As Byte Property Let Field4(ByVal Value As Byte) ``` 第 4 字段值(0-255)。 ### Field1RangeMin ```vb Property Get Field1RangeMin() As Byte Property Let Field1RangeMin(ByVal Value As Byte) ``` 第 1 字段最小值。默认 0。 ### Field1RangeMax ```vb Property Get Field1RangeMax() As Byte Property Let Field1RangeMax(ByVal Value As Byte) ``` 第 1 字段最大值。默认 255。 ### Field2RangeMin ```vb Property Get Field2RangeMin() As Byte Property Let Field2RangeMin(ByVal Value As Byte) ``` 第 2 字段最小值。默认 0。 ### Field2RangeMax ```vb Property Get Field2RangeMax() As Byte Property Let Field2RangeMax(ByVal Value As Byte) ``` 第 2 字段最大值。默认 255。 ### Field3RangeMin ```vb Property Get Field3RangeMin() As Byte Property Let Field3RangeMin(ByVal Value As Byte) ``` 第 3 字段最小值。默认 0。 ### Field3RangeMax ```vb Property Get Field3RangeMax() As Byte Property Let Field3RangeMax(ByVal Value As Byte) ``` 第 3 字段最大值。默认 255。 ### Field4RangeMin ```vb Property Get Field4RangeMin() As Byte Property Let Field4RangeMin(ByVal Value As Byte) ``` 第 4 字段最小值。默认 0。 ### Field4RangeMax ```vb Property Get Field4RangeMax() As Byte Property Let Field4RangeMax(ByVal Value As Byte) ``` 第 4 字段最大值。默认 255。 ### FocusField ```vb Property Get FocusField() As IPAFocusConstants Property Let FocusField(ByVal Value As IPAFocusConstants) ``` 当前焦点字段。 ### BorderStyle ```vb Property Get BorderStyle() As CCBorderStyleConstants Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` 边框样式。参见通用枚举。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景颜色。 ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` 前景颜色。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针样式。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 是否启用鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示方向。 ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` 从右到左镜像布局。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### IMEMode ```vb Property Get IMEMode() As CCIMEModeConstants Property Let IMEMode(ByVal Value As CCIMEModeConstants) ``` 输入法编辑器模式。参见通用枚举。 ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE 拖放模式。参见通用枚举。 ### Appearance ```vb Property Get Appearance() As CCAppearanceConstants Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` 外观样式。参见通用枚举。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` IP 地址控件的窗口句柄。只读。 ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 用户控件的窗口句柄。只读。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As Variant Property Let Tag(ByVal Value As Variant) Property Set Tag(ByVal Value As Variant) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度(设计时使用)。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度(设计时使用)。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 可见性。 ## 方法 ### Refresh ```vb Sub Refresh() ``` 强制重绘。 ### Clear ```vb Sub Clear() ``` 清除 IP 地址,将所有字段设为空。 ### SetFocusField ```vb Sub SetFocusField(ByVal FocusField As IPAFocusConstants) ``` 设置焦点到指定字段。 ### AboutBox ```vb Sub AboutBox() ``` 显示关于对话框。 ## 事件 ### Change ```vb Event Change() ``` IP 地址改变时触发。 ### FieldChange ```vb Event FieldChange(ByVal Field As Integer) ``` 指定字段改变时触发。 ### KeyDown ```vb Event KeyDown(KeyCode As Integer, Shift As Integer) ``` 按键按下时触发。 ### KeyUp ```vb Event KeyUp(KeyCode As Integer, Shift As Integer) ``` 按键释放时触发。 ### KeyPress ```vb Event KeyPress(KeyChar As Integer) ``` 按键输入时触发。 ### Click ```vb Event Click() ``` 单击时触发。 ### DblClick ```vb Event DblClick() ``` 双击时触发。 ### MouseDown ```vb Event MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` 鼠标按下时触发。 ### MouseUp ```vb Event MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` 鼠标释放时触发。 ### MouseMove ```vb Event MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` 鼠标移动时触发。 ### MouseEnter ```vb Event MouseEnter() ``` 鼠标进入控件时触发。 ### MouseLeave ```vb Event MouseLeave() ``` 鼠标离开控件时触发。 ### OLEStartDrag ```vb Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 拖拽开始时触发。 ### OLEGiveFeedback ```vb Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 拖拽反馈。 ### OLESetData ```vb Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE 设置数据。 ### OLECompleteDrag ```vb Event OLECompleteDrag(Effect As Long) ``` OLE 拖拽完成。 ### OLEDragOver ```vb Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖拽经过时触发。 ### OLEDragDrop ```vb Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE 拖放时触发。 ## 代码示例 ```vb ' 设置 IP 地址(数值形式) IPAddress1.Text = &H0100007F ' 127.0.0.1 ' 逐字段设置 IPAddress1.Field1 = 192 IPAddress1.Field2 = 168 IPAddress1.Field3 = 1 IPAddress1.Field4 = 100 ' 读取 IP 地址 If IPAddress1.Text <> IPAEmpty Then MsgBox "IP: " & IPAddress1.Field1 & "." & IPAddress1.Field2 & "." & _ IPAddress1.Field3 & "." & IPAddress1.Field4 End If ' 设置字段范围限制 IPAddress1.Field1RangeMin = 10 IPAddress1.Field1RangeMax = 192 ' 监听变化 Private Sub IPAddress1_FieldChange(ByVal Field As Integer) Debug.Print "字段 " & Field & " 已更改" End Sub ``` --- --- url: /en/packages/vbccr/lists/ipaddress.md description: >- IPAddress Control - VBCCR Development Manual, complete API reference based on source code --- # IPAddress Control Wraps the SysIPAddress32 system control for entering and displaying IPv4 addresses. ## Enumerations ### IPATextConstants | Constant | Value | Description | |----------|-------|-------------| | IPAEmpty | 0 | Empty address | | IPAInvalid | -1 | Invalid address | ### IPAFocusConstants | Constant | Value | Description | |----------|-------|-------------| | IPAFocusField1 | 0 | Field 1 | | IPAFocusField2 | 1 | Field 2 | | IPAFocusField3 | 2 | Field 3 | | IPAFocusField4 | 3 | Field 4 | ### CCAppearanceConstants See common enumerations. ### CCBorderStyleConstants See common enumerations. ### CCMousePointerConstants See common enumerations. ### CCIMEModeConstants See common enumerations. ### CCRightToLeftModeConstants See common enumerations. ### OLEDropModeConstants See common enumerations. ## Properties ### Text ```vb Property Get Text() As IPATextConstants Property Let Text(ByVal Value As IPATextConstants) ``` Numeric representation of the IP address. IPAEmpty (0) indicates an empty address, IPAInvalid (-1) indicates an invalid address. ### Field1 ```vb Property Get Field1() As Byte Property Let Field1(ByVal Value As Byte) ``` Field 1 value (0-255). ### Field2 ```vb Property Get Field2() As Byte Property Let Field2(ByVal Value As Byte) ``` Field 2 value (0-255). ### Field3 ```vb Property Get Field3() As Byte Property Let Field3(ByVal Value As Byte) ``` Field 3 value (0-255). ### Field4 ```vb Property Get Field4() As Byte Property Let Field4(ByVal Value As Byte) ``` Field 4 value (0-255). ### Field1RangeMin ```vb Property Get Field1RangeMin() As Byte Property Let Field1RangeMin(ByVal Value As Byte) ``` Minimum value for field 1. Default is 0. ### Field1RangeMax ```vb Property Get Field1RangeMax() As Byte Property Let Field1RangeMax(ByVal Value As Byte) ``` Maximum value for field 1. Default is 255. ### Field2RangeMin ```vb Property Get Field2RangeMin() As Byte Property Let Field2RangeMin(ByVal Value As Byte) ``` Minimum value for field 2. Default is 0. ### Field2RangeMax ```vb Property Get Field2RangeMax() As Byte Property Let Field2RangeMax(ByVal Value As Byte) ``` Maximum value for field 2. Default is 255. ### Field3RangeMin ```vb Property Get Field3RangeMin() As Byte Property Let Field3RangeMin(ByVal Value As Byte) ``` Minimum value for field 3. Default is 0. ### Field3RangeMax ```vb Property Get Field3RangeMax() As Byte Property Let Field3RangeMax(ByVal Value As Byte) ``` Maximum value for field 3. Default is 255. ### Field4RangeMin ```vb Property Get Field4RangeMin() As Byte Property Let Field4RangeMin(ByVal Value As Byte) ``` Minimum value for field 4. Default is 0. ### Field4RangeMax ```vb Property Get Field4RangeMax() As Byte Property Let Field4RangeMax(ByVal Value As Byte) ``` Maximum value for field 4. Default is 255. ### FocusField ```vb Property Get FocusField() As IPAFocusConstants Property Let FocusField(ByVal Value As IPAFocusConstants) ``` Current focus field. ### BorderStyle ```vb Property Get BorderStyle() As CCBorderStyleConstants Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` Border style. See common enumerations. ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` Font. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` Foreground color. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` Mouse pointer style. See common enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` Custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Whether to enable mouse enter/leave tracking. ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` Right-to-left display direction. ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` Right-to-left mirrored layout. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` Right-to-left mode. See common enumerations. ### IMEMode ```vb Property Get IMEMode() As CCIMEModeConstants Property Let IMEMode(ByVal Value As CCIMEModeConstants) ``` Input method editor mode. See common enumerations. ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE drag-drop mode. See common enumerations. ### Appearance ```vb Property Get Appearance() As CCAppearanceConstants Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` Appearance style. See common enumerations. ### hWnd ```vb Property Get hWnd() As LongPtr ``` Window handle of the IP address control. Read-only. ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` Tooltip text. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Window handle of the UserControl. Read-only. ### Name ```vb Property Get Name() As String ``` Control name. Read-only. ### Tag ```vb Property Get Tag() As Variant Property Let Tag(ByVal Value As Variant) Property Set Tag(ByVal Value As Variant) ``` Custom data. ### Parent ```vb Property Get Parent() As Object ``` Parent object. Read-only. ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` Container object. ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` Left position. ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` Top position. ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` Width (used at design time). ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` Height (used at design time). ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` Visibility. ## Methods ### Refresh ```vb Sub Refresh() ``` Forces a redraw. ### Clear ```vb Sub Clear() ``` Clears the IP address, setting all fields to empty. ### SetFocusField ```vb Sub SetFocusField(ByVal FocusField As IPAFocusConstants) ``` Sets focus to the specified field. ### AboutBox ```vb Sub AboutBox() ``` Displays the About dialog. ## Events ### Change ```vb Event Change() ``` Fired when the IP address changes. ### FieldChange ```vb Event FieldChange(ByVal Field As Integer) ``` Fired when a specific field changes. ### KeyDown ```vb Event KeyDown(KeyCode As Integer, Shift As Integer) ``` Fired when a key is pressed. ### KeyUp ```vb Event KeyUp(KeyCode As Integer, Shift As Integer) ``` Fired when a key is released. ### KeyPress ```vb Event KeyPress(KeyChar As Integer) ``` Fired on key input. ### Click ```vb Event Click() ``` Fired on click. ### DblClick ```vb Event DblClick() ``` Fired on double-click. ### MouseDown ```vb Event MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` Fired when a mouse button is pressed. ### MouseUp ```vb Event MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` Fired when a mouse button is released. ### MouseMove ```vb Event MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` Fired when the mouse is moved. ### MouseEnter ```vb Event MouseEnter() ``` Fired when the mouse enters the control. ### MouseLeave ```vb Event MouseLeave() ``` Fired when the mouse leaves the control. ### OLEStartDrag ```vb Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` Fired when an OLE drag starts. ### OLEGiveFeedback ```vb Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE drag feedback. ### OLESetData ```vb Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE set data. ### OLECompleteDrag ```vb Event OLECompleteDrag(Effect As Long) ``` OLE drag completed. ### OLEDragOver ```vb Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` Fired when an OLE drag passes over. ### OLEDragDrop ```vb Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired on OLE drag-drop. ## Code Examples ```vb ' Set IP address (numeric form) IPAddress1.Text = &H0100007F ' 127.0.0.1 ' Set field by field IPAddress1.Field1 = 192 IPAddress1.Field2 = 168 IPAddress1.Field3 = 1 IPAddress1.Field4 = 100 ' Read IP address If IPAddress1.Text <> IPAEmpty Then MsgBox "IP: " & IPAddress1.Field1 & "." & IPAddress1.Field2 & "." & _ IPAddress1.Field3 & "." & IPAddress1.Field4 End If ' Set field range limits IPAddress1.Field1RangeMin = 10 IPAddress1.Field1RangeMax = 192 ' Listen for changes Private Sub IPAddress1_FieldChange(ByVal Field As Integer) Debug.Print "Field " & Field & " changed" End Sub ``` --- --- url: /en/official/Reference/VBA/Financial/IPmt.md --- # IPmt Returns a **Double** specifying the interest payment for a given period of an annuity based on periodic, fixed payments and a fixed interest rate. Syntax: **IPmt(** *rate*, *per*, *nper*, *pv* \[ **,** *fv* \[ **,** *type* ] ] **)** *rate* : *required* **Double** specifying interest rate per period. For example, for a car loan at an annual percentage rate (APR) of 10 percent with monthly payments, the rate per period is 0.1/12, or 0.0083. *per* : *required* **Double** specifying payment period in the range 1 through *nper*. *nper* : *required* **Double** specifying total number of payment periods in the annuity. For example, monthly payments on a four-year car loan total 4 \* 12 (or 48) payment periods. *pv* : *required* **Double** specifying present value, or value today, of a series of future payments or receipts. For example, when borrowing money to buy a car, the loan amount is the present value to the lender of the monthly car payments to be made. *fv* : *optional* **Variant** specifying future value or cash balance remaining after the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, to save $50,000 over 18 years for a child's education, $50,000 is the future value. If omitted, 0 is assumed. *type* : *optional* **Variant** specifying when payments are due. 0 means payments are due at the end of the period; 1 means payments are due at the beginning. If omitted, 0 is assumed. An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan). The *rate* and *nper* arguments must be calculated by using payment periods expressed in the same units. For example, if *rate* is calculated by using months, *nper* must also be calculated by using months. For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers. ### Example This example uses the **IPmt** function to calculate how much of a payment is interest when all the payments are of equal value. Given are the interest percentage rate per period (`APR / 12`), the payment period for which the interest portion is desired (`Period`), the total number of payments (`TotPmts`), the present value or principal of the loan (`PVal`), the future value of the loan (`FVal`), and a number that indicates whether the payment is due at the beginning or end of the payment period (`PayType`). ```vb Dim FVal, Fmt, PVal, APR, TotPmts, PayType, Period, IntPmt, TotInt, Msg Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. FVal = 0 ' Usually 0 for a loan. Fmt = "###,###,##0.00" ' Define money format. PVal = InputBox("How much do you want to borrow?") APR = InputBox("What is the annual percentage rate of your loan?") If APR > 1 Then APR = APR / 100 ' Ensure proper form. TotPmts = InputBox("How many monthly payments?") PayType = MsgBox("Do you make payments at end of the month?", vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD For Period = 1 To TotPmts ' Total all interest. IntPmt = IPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType) TotInt = TotInt + IntPmt Next Period Msg = "You'll pay a total of " & Format(TotInt, Fmt) Msg = Msg & " in interest for this loan." MsgBox Msg ' Display results. ``` ### See Also * [Pmt](/en/official/Reference/VBA/Financial/Pmt), [PPmt](/en/official/Reference/VBA/Financial/PPmt), [Rate](/en/official/Reference/VBA/Financial/Rate) functions --- --- url: /zh/official/Reference/VBA/Financial/IPmt.md --- # IPmt 返回一个 **Double**,基于定期固定付款和固定利率指定年金指定期间的利息付款。 语法:**IPmt(** *rate*, *per*, *nper*, *pv* \[ **,** *fv* \[ **,** *type* ] ] **)** *rate* : *必需* **Double**,指定每期利率。例如,对于年利率 10% 按月还款的汽车贷款,每期利率为 0.1/12,即 0.0083。 *per* : *必需* **Double**,指定 1 到 *nper* 范围内的付款期。 *nper* : *必需* **Double**,指定年金的总付款期数。例如,四年期汽车贷款按月还款共有 4 \* 12(即 48)个付款期。 *pv* : *必需* **Double**,指定一系列未来付款或收入的现值(即当前价值)。例如,借钱买车时,贷款金额就是贷款人将收到的月供的现值。 *fv* : *可选* **Variant**,指定终值或最终付款后的现金余额。例如,贷款的终值为 $0,因为那是最终付款后的价值。但是,如果要在 18 年内为孩子教育储蓄 $50,000,则 $50,000 是终值。如果省略,则假定为 0。 *type* : *可选* **Variant**,指定付款到期时间。0 表示期末到期;1 表示期初到期。如果省略,则假定为 0。 年金是在一段时间内进行的一系列固定现金支付。年金可以是贷款(如住房抵押贷款)或投资(如月度储蓄计划)。 *rate* 和 *nper* 参数必须使用相同单位的付款期计算。例如,如果 *rate* 按月计算,*nper* 也必须按月计算。 对于所有参数,支出的现金(如储蓄存款)用负数表示;收入的现金(如股息支票)用正数表示。 ### 示例 此示例使用 **IPmt** 函数计算所有付款金额相同时某笔付款中利息占多少。给定每期利率百分比(`APR / 12`)、需要利息部分的付款期(`Period`)、总付款次数(`TotPmts`)、贷款的现值或本金(`PVal`)、贷款的终值(`FVal`)以及指示付款是在付款期初还是期末到期的数字(`PayType`)。 ```vb Dim FVal, Fmt, PVal, APR, TotPmts, PayType, Period, IntPmt, TotInt, Msg Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. FVal = 0 ' Usually 0 for a loan. Fmt = "###,###,##0.00" ' Define money format. PVal = InputBox("How much do you want to borrow?") APR = InputBox("What is the annual percentage rate of your loan?") If APR > 1 Then APR = APR / 100 ' Ensure proper form. TotPmts = InputBox("How many monthly payments?") PayType = MsgBox("Do you make payments at end of the month?", vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD For Period = 1 To TotPmts ' Total all interest. IntPmt = IPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType) TotInt = TotInt + IntPmt Next Period Msg = "You'll pay a total of " & Format(TotInt, Fmt) Msg = Msg & " in interest for this loan." MsgBox Msg ' Display results. ``` ### 另请参阅 * [Pmt](/official/Reference/VBA/Financial/Pmt)、[PPmt](/official/Reference/VBA/Financial/PPmt)、[Rate](/official/Reference/VBA/Financial/Rate) 函数 --- --- url: /en/official/Reference/VBA/Financial/IRR.md --- # IRR Returns a **Double** specifying the internal rate of return for a series of periodic cash flows (payments and receipts). Syntax: **IRR(** *values()* \[ **,** *guess* ] **)** *values()* : *required* Array of **Double** specifying cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt). *guess* : *optional* **Variant** specifying an estimate of the value to be returned by **IRR**. If omitted, *guess* is 0.1 (10 percent). The internal rate of return is the interest rate received for an investment consisting of payments and receipts that occur at regular intervals. The **IRR** function uses the order of values within the array to interpret the order of payments and receipts. The payment and receipt values must be in the correct sequence. The cash flow for each period doesn't have to be fixed, as it is for an annuity. **IRR** is calculated by iteration. Starting with the value of *guess*, **IRR** cycles through the calculation until the result is accurate to within 0.00001 percent. If **IRR** can't find a result after 20 tries, it fails. ### Example In this example, the **IRR** function returns the internal rate of return for a series of 5 cash flows contained in the array `Values()`. The first array element is a negative cash flow representing business start-up costs. The remaining four cash flows represent positive cash flows for the subsequent 4 years. `Guess` is the estimated internal rate of return. ```vb Dim Guess, Fmt, RetRate, Msg Static Values(5) As Double ' Set up array. Guess = .1 ' Guess starts at 10 percent. Fmt = "#0.00" ' Define percentage format. Values(0) = -70000 ' Business start-up costs. ' Positive cash flows reflecting income for four successive years. Values(1) = 22000 : Values(2) = 25000 Values(3) = 28000 : Values(4) = 31000 RetRate = IRR(Values(), Guess) * 100 ' Calculate internal rate. Msg = "The internal rate of return for these five cash flows is " Msg = Msg & Format(RetRate, Fmt) & " percent." MsgBox Msg ' Display internal return rate. ``` ### See Also * [MIRR](/en/official/Reference/VBA/Financial/MIRR), [NPV](/en/official/Reference/VBA/Financial/NPV), [Rate](/en/official/Reference/VBA/Financial/Rate) functions --- --- url: /zh/official/Reference/VBA/Financial/IRR.md --- # IRR 返回一个 **Double**,指定一系列定期现金流(付款和收入)的内部收益率。 语法:**IRR(** *values()* \[ **,** *guess* ] **)** *values()* : *必需* **Double** 数组,指定现金流值。数组必须包含至少一个负值(付款)和一个正值(收入)。 *guess* : *可选* **Variant**,指定 **IRR** 返回值的估计。如果省略,*guess* 为 0.1(10%)。 内部收益率是按固定间隔发生的付款和收入投资所获得的利率。 **IRR** 函数使用数组中值的顺序来解释付款和收入的顺序。付款和收入值必须按正确顺序排列。每期的现金流不必像年金那样固定。 **IRR** 通过迭代计算。从 *guess* 的值开始,**IRR** 循环计算直到结果精确到 0.00001% 以内。如果 **IRR** 在 20 次尝试后仍未找到结果,则失败。 ### 示例 在此示例中,**IRR** 函数返回包含在数组 `Values()` 中的 5 个现金流的内部收益率。第一个数组元素是负现金流,代表企业创业成本。其余四个现金流代表随后 4 年的正现金流。`Guess` 是估计的内部收益率。 ```vb Dim Guess, Fmt, RetRate, Msg Static Values(5) As Double ' Set up array. Guess = .1 ' Guess starts at 10 percent. Fmt = "#0.00" ' Define percentage format. Values(0) = -70000 ' Business start-up costs. ' Positive cash flows reflecting income for four successive years. Values(1) = 22000 : Values(2) = 25000 Values(3) = 28000 : Values(4) = 31000 RetRate = IRR(Values(), Guess) * 100 ' Calculate internal rate. Msg = "The internal rate of return for these five cash flows is " Msg = Msg & Format(RetRate, Fmt) & " percent." MsgBox Msg ' Display internal return rate. ``` ### 另请参阅 * [MIRR](/official/Reference/VBA/Financial/MIRR)、[NPV](/official/Reference/VBA/Financial/NPV)、[Rate](/official/Reference/VBA/Financial/Rate) 函数 --- --- url: /en/official/Reference/Core/Is.md --- # Is Used to compare two object references for identity. Syntax: > *result* **=** *object1* **Is** *object2* *result* : Any **Boolean** or numeric variable. *object1*, *object2* : Any object references. If *object1* and *object2* both refer to the same object, *result* is **True**; if they don't, *result* is **False**. **Is** does not compare values inside the objects --- it compares whether the two references point to the same instance. Two variables can be made to refer to the same object in several ways. In the following example, A has been set to refer to the same object as B: ```vb Set A = B ``` The following example makes A and B refer to the same object as C: ```vb Set A = C Set B = C ``` A reference compared against **Nothing** with **Is** tells whether the reference is unassigned: ```vb If MyObject Is Nothing Then Debug.Print "MyObject has not been assigned." End If ``` For the negation of an identity test, twinBASIC also provides the [**IsNot**](/en/official/Reference/Core/IsNot) operator: `If MyObject IsNot Nothing Then` reads more naturally than `If Not (MyObject Is Nothing) Then`. ::: info The **Is** keyword has two unrelated uses elsewhere in the language: * In an **[If...Then...Else](/en/official/Reference/Core/If-Then-Else)** condition of the form **TypeOf** *objectname* **Is** *objecttype*, **Is** introduces a runtime type test. * In a **[Select Case](/en/official/Reference/Core/Select-Case)** clause of the form **Is** *comparisonoperator* *expression*, **Is** introduces a comparison against the **Select Case** test expression. In both of those constructs the surrounding statement provides the meaning; **Is** there is not the object-identity operator described on this page. ::: ### Example This example uses the **Is** operator to compare two object references. ```vb Dim MyObject, YourObject, ThisObject, OtherObject, ThatObject, MyCheck Set YourObject = MyObject ' Assign object references. Set ThisObject = MyObject Set ThatObject = OtherObject MyCheck = YourObject Is ThisObject ' Returns True. MyCheck = ThatObject Is ThisObject ' Returns False. ' Assume MyObject <> OtherObject. MyCheck = MyObject Is ThatObject ' Returns False. ``` ### See Also * [**IsNot** operator](/en/official/Reference/Core/IsNot) * [**Set** statement](/en/official/Reference/Core/Set) * [**If...Then...Else** statement](/en/official/Reference/Core/If-Then-Else) * [**Select Case** statement](/en/official/Reference/Core/Select-Case) --- --- url: /zh/official/Reference/Core/Is.md --- # Is 用于比较两个对象引用的同一性。 语法: > *result* **=** *object1* **Is** *object2* *result* : 任意 **Boolean** 或数值变量。 *object1*, *object2* : 任意对象引用。 如果 *object1* 和 *object2* 引用同一对象,*result* 为 **True**;否则 *result* 为 **False**。**Is** 不比较对象内部的值——它比较两个引用是否指向同一实例。 可以通过多种方式使两个变量引用同一对象。以下示例中,A 被设置为引用与 B 相同的对象: ```vb Set A = B ``` 以下示例使 A 和 B 引用与 C 相同的对象: ```vb Set A = C Set B = C ``` 将引用与 **Nothing** 进行 **Is** 比较可判断引用是否未赋值: ```vb If MyObject Is Nothing Then Debug.Print "MyObject has not been assigned." End If ``` 对于同一性测试的否定,twinBASIC还提供了 [**IsNot**](/official/Reference/Core/IsNot) 运算符:`If MyObject IsNot Nothing Then` 比 `If Not (MyObject Is Nothing) Then` 更自然。 ::: info **Is** 关键字在语言中还有两个不相关的用途: * 在 **[If...Then...Else](/official/Reference/Core/If-Then-Else)** 条件中 **TypeOf** *objectname* **Is** *objecttype* 形式下,**Is** 引入运行时类型测试。 * 在 **[Select Case](/official/Reference/Core/Select-Case)** 子句中 **Is** *comparisonoperator* *expression* 形式下,**Is** 引入与 **Select Case** 测试表达式的比较。 在这两种构造中,周围语句提供了含义;那里 **Is** 不是本页描述的对象同一性运算符。 ::: ### 示例 本示例使用 **Is** 运算符比较两个对象引用。 ```vb Dim MyObject, YourObject, ThisObject, OtherObject, ThatObject, MyCheck Set YourObject = MyObject ' Assign object references. Set ThisObject = MyObject Set ThatObject = OtherObject MyCheck = YourObject Is ThisObject ' Returns True. MyCheck = ThatObject Is ThisObject ' Returns False. ' Assume MyObject <> OtherObject. MyCheck = MyObject Is ThatObject ' Returns False. ``` ### 另请参阅 * [**IsNot** 运算符](/official/Reference/Core/IsNot) * [**Set** 语句](/official/Reference/Core/Set) * [**If...Then...Else** 语句](/official/Reference/Core/If-Then-Else) * [**Select Case** 语句](/official/Reference/Core/Select-Case) --- --- url: /en/official/Reference/VBA/Information/IsArray.md --- # IsArray Returns a **Boolean** indicating whether a variable is an array. Syntax: **IsArray(** *varname* **)** *varname* : *required* An identifier specifying the variable to test. **IsArray** returns **True** if the variable is an array; otherwise, it returns **False**. **IsArray** is especially useful with **Variant**s containing arrays. ### Example This example uses **IsArray** to check whether a variable is an array. ```vb Dim MyArray(1 To 5) As Integer Dim YourArray As Variant Dim MyCheck As Boolean YourArray = Array(1, 2, 3) ' Use the Array function. MyCheck = IsArray(MyArray) ' Returns True. MyCheck = IsArray(YourArray) ' Returns True. ``` ### See Also * [IsArrayInitialized](/en/official/Reference/VBA/Information/IsArrayInitialized) function * [LBound](/en/official/Reference/VBA/Information/LBound), [UBound](/en/official/Reference/VBA/Information/UBound) functions --- --- url: /zh/official/Reference/VBA/Information/IsArray.md --- # IsArray 返回一个**Boolean**,指示变量是否为数组。 语法:**IsArray(** *varname* **)** *varname* : *必需* 指定要测试的变量的标识符。 如果变量是数组,**IsArray**返回**True**;否则返回**False**。**IsArray**对于包含数组的**Variant**特别有用。 ### 示例 本示例使用**IsArray**检查变量是否为数组。 ```vb Dim MyArray(1 To 5) As Integer Dim YourArray As Variant Dim MyCheck As Boolean YourArray = Array(1, 2, 3) ' Use the Array function. MyCheck = IsArray(MyArray) ' Returns True. MyCheck = IsArray(YourArray) ' Returns True. ``` ### 另请参阅 * [IsArrayInitialized](/official/Reference/VBA/Information/IsArrayInitialized)函数 * [LBound](/official/Reference/VBA/Information/LBound)、[UBound](/official/Reference/VBA/Information/UBound)函数 --- --- url: /en/official/Reference/VBA/Information/IsArrayInitialized.md --- # IsArrayInitialized Returns a **Boolean** indicating whether a variable contains an array whose dimensions have been allocated. Syntax: **IsArrayInitialized(** *varname* **)** *varname* : *required* The array variable to test. A dynamic array declared with empty parentheses (`Dim a() As Long`) holds a special "uninitialized" state until **ReDim** allocates storage for it. **IsArrayInitialized** returns **False** in that state and **True** once the array has dimensions. Calling [**LBound**](/en/official/Reference/VBA/Information/LBound) or [**UBound**](/en/official/Reference/VBA/Information/UBound) on an uninitialized array, or accessing any of its elements, raises a run-time error --- so **IsArrayInitialized** is the safe way to test before reading. If *varname* is not an array, **IsArrayInitialized** returns **False**. ### Example This example tests an array before and after **ReDim**, and again after **Erase** releases its storage. ```vb Dim a() As Long Debug.Print IsArrayInitialized(a) ' False — declared but unsized. ReDim a(0 To 9) Debug.Print IsArrayInitialized(a) ' True — dimensions allocated. Erase a Debug.Print IsArrayInitialized(a) ' False — Erase released the storage. ``` ### See Also * [IsArray](/en/official/Reference/VBA/Information/IsArray) function * [IsObject](/en/official/Reference/VBA/Information/IsObject) function * [IsEmpty](/en/official/Reference/VBA/Information/IsEmpty) function * [LBound](/en/official/Reference/VBA/Information/LBound), [UBound](/en/official/Reference/VBA/Information/UBound) functions --- --- url: /zh/official/Reference/VBA/Information/IsArrayInitialized.md --- # IsArrayInitialized 返回一个**Boolean**,指示变量是否包含已分配维度的数组。 语法:**IsArrayInitialized(** *varname* **)** *varname* : *必需* 要测试的数组变量。 以空括号声明的动态数组(`Dim a() As Long`)在**ReDim**为其分配存储空间之前保持特殊的"未初始化"状态。**IsArrayInitialized**在该状态下返回**False**,在数组具有维度后返回**True**。对未初始化的数组调用[**LBound**](/official/Reference/VBA/Information/LBound)或[**UBound**](/official/Reference/VBA/Information/UBound),或访问其任何元素,都会引发运行时错误——因此**IsArrayInitialized**是在读取之前进行安全测试的方式。 如果*varname*不是数组,**IsArrayInitialized**返回**False**。 ### 示例 本示例在**ReDim**前后以及**Erase**释放存储空间后测试数组。 ```vb Dim a() As Long Debug.Print IsArrayInitialized(a) ' False — declared but unsized. ReDim a(0 To 9) Debug.Print IsArrayInitialized(a) ' True — dimensions allocated. Erase a Debug.Print IsArrayInitialized(a) ' False — Erase released the storage. ``` ### 另请参阅 * [IsArray](/official/Reference/VBA/Information/IsArray)函数 * [IsObject](/official/Reference/VBA/Information/IsObject)函数 * [IsEmpty](/official/Reference/VBA/Information/IsEmpty)函数 * [LBound](/official/Reference/VBA/Information/LBound)、[UBound](/official/Reference/VBA/Information/UBound)函数 --- --- url: /en/official/Reference/VBA/Information/IsDate.md --- # IsDate Returns **True** if the expression is a date or is recognizable as a valid date or time; otherwise, **False**. Syntax: **IsDate(** *expression* **)** *expression* : *required* A **Variant** containing a date expression, or a string expression recognizable as a date or time. The range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D. ### Example This example uses **IsDate** to determine whether an expression is recognized as a date or time value. ```vb Dim MyVar As Variant Dim MyCheck As Boolean MyVar = "04/28/2014" ' Valid date. MyCheck = IsDate(MyVar) ' True. MyVar = "April 28, 2014" ' Valid date. MyCheck = IsDate(MyVar) ' True. MyVar = "13/32/2014" ' Invalid date. MyCheck = IsDate(MyVar) ' False. MyVar = "04.28.14" ' Valid time format on some locales. MyCheck = IsDate(MyVar) ' True. ``` ### See Also * [CDate](/en/official/Reference/VBA/Conversion/CDate) function * [DateValue](/en/official/Reference/VBA/DateTime/DateValue) function --- --- url: /zh/official/Reference/VBA/Information/IsDate.md --- # IsDate 如果表达式是日期或可识别为有效日期或时间,则返回**True**;否则返回**False**。 语法:**IsDate(** *expression* **)** *expression* : *必需* **Variant**,包含日期表达式,或可识别为日期或时间的字符串表达式。 有效日期的范围为公元100年1月1日至公元9999年12月31日。 ### 示例 本示例使用**IsDate**确定表达式是否可识别为日期或时间值。 ```vb Dim MyVar As Variant Dim MyCheck As Boolean MyVar = "04/28/2014" ' Valid date. MyCheck = IsDate(MyVar) ' True. MyVar = "April 28, 2014" ' Valid date. MyCheck = IsDate(MyVar) ' True. MyVar = "13/32/2014" ' Invalid date. MyCheck = IsDate(MyVar) ' False. MyVar = "04.28.14" ' Valid time format on some locales. MyCheck = IsDate(MyVar) ' True. ``` ### 另请参阅 * [CDate](/official/Reference/VBA/Conversion/CDate)函数 * [DateValue](/official/Reference/VBA/DateTime/DateValue)函数 --- --- url: /en/official/Reference/VBA/Information/IsEmpty.md --- # IsEmpty Returns a **Boolean** indicating whether a **Variant** has been initialized. Syntax: **IsEmpty(** *expression* **)** *expression* : *required* A **Variant** containing a numeric or string expression. Most often, *expression* is a single variable name, since **IsEmpty** only returns meaningful information for **Variant**s. **IsEmpty** returns **True** if the variable is uninitialized or has been explicitly set to **Empty**; otherwise, it returns **False**. **False** is always returned if *expression* contains more than one variable. ### Example This example uses **IsEmpty** to determine whether a variable has been initialized. ```vb Dim MyVar As Variant Dim MyCheck As Boolean MyCheck = IsEmpty(MyVar) ' True — uninitialised. MyVar = Null MyCheck = IsEmpty(MyVar) ' False — Null is not Empty. MyVar = Empty MyCheck = IsEmpty(MyVar) ' True. ``` ### See Also * [IsNull](/en/official/Reference/VBA/Information/IsNull), [IsMissing](/en/official/Reference/VBA/Information/IsMissing) functions --- --- url: /zh/official/Reference/VBA/Information/IsEmpty.md --- # IsEmpty 返回一个**Boolean**,指示**Variant**是否已初始化。 语法:**IsEmpty(** *expression* **)** *expression* : *必需* **Variant**,包含数值或字符串表达式。大多数情况下,*expression*是单个变量名,因为**IsEmpty**仅对**Variant**返回有意义的信息。 如果变量未初始化或已显式设置为**Empty**,**IsEmpty**返回**True**;否则返回**False**。如果*expression*包含多个变量,则始终返回**False**。 ### 示例 本示例使用**IsEmpty**确定变量是否已初始化。 ```vb Dim MyVar As Variant Dim MyCheck As Boolean MyCheck = IsEmpty(MyVar) ' True — uninitialised. MyVar = Null MyCheck = IsEmpty(MyVar) ' False — Null is not Empty. MyVar = Empty MyCheck = IsEmpty(MyVar) ' True. ``` ### 另请参阅 * [IsNull](/official/Reference/VBA/Information/IsNull)、[IsMissing](/official/Reference/VBA/Information/IsMissing)函数 --- --- url: /en/official/Reference/VBA/Information/IsError.md --- # IsError Returns a **Boolean** indicating whether an expression is an error value. Syntax: **IsError(** *expression* **)** *expression* : *required* Any valid expression. Error values are produced by passing an error number through the [**CVErr**](/en/official/Reference/VBA/Conversion/CVErr) function. **IsError** returns **True** if *expression* indicates an error; otherwise, **False**. ### Example This example uses **IsError** to check whether a value is an error. **CVErr** is used to return an **Error**-subtype **Variant** from a user-defined function. `UserFunction` is assumed to return an error value, for example via `UserFunction = CVErr(32767)`. ```vb Dim ReturnVal As Variant Dim MyCheck As Boolean ReturnVal = UserFunction() MyCheck = IsError(ReturnVal) ' Returns True. ``` ### See Also * [CVErr](/en/official/Reference/VBA/Conversion/CVErr) function * [Err](/en/official/Reference/VBA/Information/Err) property --- --- url: /zh/official/Reference/VBA/Information/IsError.md --- # IsError 返回一个**Boolean**,指示表达式是否为错误值。 语法:**IsError(** *expression* **)** *expression* : *必需* 任何有效的表达式。 错误值通过[**CVErr**](/official/Reference/VBA/Conversion/CVErr)函数传入错误编号产生。如果*expression*指示错误,**IsError**返回**True**;否则返回**False**。 ### 示例 本示例使用**IsError**检查值是否为错误。**CVErr**用于从用户自定义函数返回**Error**子类型的**Variant**。假设`UserFunction`返回错误值,例如通过`UserFunction = CVErr(32767)`。 ```vb Dim ReturnVal As Variant Dim MyCheck As Boolean ReturnVal = UserFunction() MyCheck = IsError(ReturnVal) ' Returns True. ``` ### 另请参阅 * [CVErr](/official/Reference/VBA/Conversion/CVErr)函数 * [Err](/official/Reference/VBA/Information/Err)属性 --- --- url: /en/official/Reference/VBA/Information/IsMissing.md --- # IsMissing Returns a **Boolean** indicating whether an optional **Variant** argument has been passed to a procedure. Syntax: **IsMissing(** *argname* **)** *argname* : *required* The name of an optional **Variant** procedure argument. **IsMissing** returns **True** if no value was supplied for the specified argument; otherwise, **False**. Using a missing argument elsewhere in code may raise a run-time error. If **IsMissing** is used on a **ParamArray** argument, it always returns **False**. To detect an empty **ParamArray**, test whether the array's upper bound is less than its lower bound. **IsMissing** does not work on simple data types such as **Integer** or **Double**: unlike **Variant**s, they have no provision for a "missing" flag. For typed optional arguments, specify a default value instead --- if the argument is omitted, it takes that default. In many cases the default-value form removes the need for a separate **IsMissing** check entirely. ```vb Sub MySub(Optional ByVal MyVar As String = "specialvalue") If MyVar = "specialvalue" Then ' MyVar was omitted. End If End Sub ``` ### Example This example uses **IsMissing** to check whether an optional argument has been passed to a user-defined procedure. ```vb Dim ReturnValue As Variant ReturnValue = ReturnTwice() ' Returns Null. ReturnValue = ReturnTwice(2) ' Returns 4. Function ReturnTwice(Optional A As Variant) As Variant If IsMissing(A) Then ReturnTwice = Null ' Argument missing — return Null. Else ReturnTwice = A * 2 ' Otherwise return twice the value. End If End Function ``` ### See Also * [IsNull](/en/official/Reference/VBA/Information/IsNull), [IsEmpty](/en/official/Reference/VBA/Information/IsEmpty) functions --- --- url: /zh/official/Reference/VBA/Information/IsMissing.md --- # IsMissing 返回一个**Boolean**,指示是否已将可选**Variant**参数传递给过程。 语法:**IsMissing(** *argname* **)** *argname* : *必需* 可选**Variant**过程参数的名称。 如果未为指定参数提供值,**IsMissing**返回**True**;否则返回**False**。在代码的其他位置使用缺失的参数可能会引发运行时错误。 如果对**ParamArray**参数使用**IsMissing**,它始终返回**False**。要检测空的**ParamArray**,请测试数组的上界是否小于其下界。 **IsMissing**不适用于**Integer**或**Double**等简单数据类型:与**Variant**不同,它们没有"缺失"标志的机制。对于有类型的可选参数,请指定默认值——如果省略参数,它将采用该默认值。在许多情况下,默认值形式完全消除了单独的**IsMissing**检查的需要。 ```vb Sub MySub(Optional ByVal MyVar As String = "specialvalue") If MyVar = "specialvalue" Then ' MyVar was omitted. End If End Sub ``` ### 示例 本示例使用**IsMissing**检查是否已将可选参数传递给用户自定义过程。 ```vb Dim ReturnValue As Variant ReturnValue = ReturnTwice() ' Returns Null. ReturnValue = ReturnTwice(2) ' Returns 4. Function ReturnTwice(Optional A As Variant) As Variant If IsMissing(A) Then ReturnTwice = Null ' Argument missing — return Null. Else ReturnTwice = A * 2 ' Otherwise return twice the value. End If End Function ``` ### 另请参阅 * [IsNull](/official/Reference/VBA/Information/IsNull)、[IsEmpty](/official/Reference/VBA/Information/IsEmpty)函数 --- --- url: /en/official/Reference/Core/IsNot.md --- # IsNot Used to compare two object references for non-identity. The logical inverse of the [**Is**](/en/official/Reference/Core/Is) operator. Syntax: > *result* **=** *object1* **IsNot** *object2* *result* : Any **Boolean** or numeric variable. *object1*, *object2* : Any object references. If *object1* and *object2* refer to *different* objects (or one of them is **Nothing** while the other is not), *result* is **True**; if they refer to the same object, *result* is **False**. Like **Is**, the comparison is on the references themselves, not on the values inside the objects. ::: info **IsNot** is a twinBASIC extension. Classic VBA has no **IsNot** operator; the equivalent is `Not (a Is b)`. ::: The most common use is testing that an object reference has been assigned: ```vb If MyObject IsNot Nothing Then ' Use MyObject. End If ``` This reads more naturally than the equivalent `If Not (MyObject Is Nothing) Then` or the older `If (MyObject Is Nothing) = False Then`. ### Example ```vb Dim A As Object, B As Object, C As Object Set A = New Collection Set B = A ' B refers to the same object as A. Set C = New Collection Debug.Print A IsNot B ' False - same object. Debug.Print A IsNot C ' True - different objects. Debug.Print A IsNot Nothing ' True - A is assigned. Set A = Nothing Debug.Print A IsNot Nothing ' False - A is now unassigned. ``` ### See Also * [**Is** operator](/en/official/Reference/Core/Is) * [**Set** statement](/en/official/Reference/Core/Set) --- --- url: /zh/official/Reference/Core/IsNot.md --- # IsNot 用于比较两个对象引用的非同一性。[**Is**](/official/Reference/Core/Is) 运算符的逻辑逆运算。 语法: > *result* **=** *object1* **IsNot** *object2* *result* : 任意 **Boolean** 或数值变量。 *object1*, *object2* : 任意对象引用。 如果 *object1* 和 *object2* 引用*不同*的对象(或其中一个为 **Nothing** 而另一个不是),*result* 为 **True**;如果它们引用同一对象,*result* 为 **False**。与 **Is** 一样,比较的是引用本身,不是对象内部的值。 ::: info **IsNot** 是twinBASIC扩展。经典VBA没有 **IsNot** 运算符;等价写法为 `Not (a Is b)`。 ::: 最常见的用途是测试对象引用是否已赋值: ```vb If MyObject IsNot Nothing Then ' Use MyObject. End If ``` 这比等价的 `If Not (MyObject Is Nothing) Then` 或更旧的 `If (MyObject Is Nothing) = False Then` 更自然。 ### 示例 ```vb Dim A As Object, B As Object, C As Object Set A = New Collection Set B = A ' B refers to the same object as A. Set C = New Collection Debug.Print A IsNot B ' False - same object. Debug.Print A IsNot C ' True - different objects. Debug.Print A IsNot Nothing ' True - A is assigned. Set A = Nothing Debug.Print A IsNot Nothing ' False - A is now unassigned. ``` ### 另请参阅 * [**Is** 运算符](/official/Reference/Core/Is) * [**Set** 语句](/official/Reference/Core/Set) --- --- url: /en/official/Reference/VBA/Information/IsNull.md --- # IsNull Returns a **Boolean** indicating whether an expression contains no valid data (**Null**). Syntax: **IsNull(** *expression* **)** *expression* : *required* A **Variant** containing a numeric or string expression. **IsNull** returns **True** if *expression* is **Null**; otherwise, **False**. If *expression* contains more than one variable, **Null** in any constituent variable causes the whole expression to evaluate to **Null**, and **IsNull** to return **True**. The **Null** value indicates that a **Variant** holds no valid data. **Null** is not the same as [**Empty**](/en/official/Reference/VBA/Information/IsEmpty) (a variable that has not yet been initialized), nor the same as a zero-length string (`""`), which is sometimes called a null string. ::: warning Use **IsNull** to determine whether an expression contains a **Null** value. Comparisons such as `If Var = Null` and `If Var <> Null` are always **False**, because any expression involving **Null** is itself **Null**, and a **Null** comparison is treated as **False**. ::: ### Example This example uses **IsNull** to determine whether a variable contains a **Null**. ```vb Dim MyVar As Variant Dim MyCheck As Boolean MyCheck = IsNull(MyVar) ' False — MyVar is Empty. MyVar = "" MyCheck = IsNull(MyVar) ' False — empty string is not Null. MyVar = Null MyCheck = IsNull(MyVar) ' True. ``` ### See Also * [IsEmpty](/en/official/Reference/VBA/Information/IsEmpty), [IsMissing](/en/official/Reference/VBA/Information/IsMissing) functions * [Nz](/en/official/Reference/VBA/Conversion/Nz) function --- --- url: /zh/official/Reference/VBA/Information/IsNull.md --- # IsNull 返回一个**Boolean**,指示表达式是否不包含有效数据(**Null**)。 语法:**IsNull(** *expression* **)** *expression* : *必需* **Variant**,包含数值或字符串表达式。 如果*expression*为**Null**,**IsNull**返回**True**;否则返回**False**。如果*expression*包含多个变量,任何组成变量中的**Null**都会导致整个表达式求值为**Null**,并使**IsNull**返回**True**。 **Null**值表示**Variant**不包含有效数据。**Null**不同于[**Empty**](/official/Reference/VBA/Information/IsEmpty)(尚未初始化的变量),也不同于零长度字符串(`""`),后者有时被称为空字符串。 ::: warning 使用**IsNull**来确定表达式是否包含**Null**值。诸如`If Var = Null`和`If Var <> Null`的比较始终为**False**,因为任何涉及**Null**的表达式本身也是**Null**,而**Null**比较被视为**False**。 ::: ### 示例 本示例使用**IsNull**确定变量是否包含**Null**。 ```vb Dim MyVar As Variant Dim MyCheck As Boolean MyCheck = IsNull(MyVar) ' False — MyVar is Empty. MyVar = "" MyCheck = IsNull(MyVar) ' False — empty string is not Null. MyVar = Null MyCheck = IsNull(MyVar) ' True. ``` ### 另请参阅 * [IsEmpty](/official/Reference/VBA/Information/IsEmpty)、[IsMissing](/official/Reference/VBA/Information/IsMissing)函数 * [Nz](/official/Reference/VBA/Conversion/Nz)函数 --- --- url: /en/official/Reference/VBA/Information/IsNumeric.md --- # IsNumeric Returns a **Boolean** indicating whether an expression can be evaluated as a number. Syntax: **IsNumeric(** *expression* **)** *expression* : *required* A **Variant** containing a numeric or string expression. **IsNumeric** returns **True** if the entire *expression* is recognized as a number; otherwise, **False**. **IsNumeric** returns **False** if *expression* is a date expression. ### Example This example uses **IsNumeric** to determine whether a variable can be evaluated as a number. ```vb Dim MyVar As Variant Dim MyCheck As Boolean MyVar = "53" MyCheck = IsNumeric(MyVar) ' Returns True. MyVar = "459.95" MyCheck = IsNumeric(MyVar) ' Returns True. MyVar = "45 Help" MyCheck = IsNumeric(MyVar) ' Returns False. ``` ### See Also * [CDbl](/en/official/Reference/VBA/Conversion/CDbl), [CDec](/en/official/Reference/VBA/Conversion/CDec) functions * [IsDate](/en/official/Reference/VBA/Information/IsDate) function * [Val](/en/official/Reference/VBA/Conversion/Val) function --- --- url: /zh/official/Reference/VBA/Information/IsNumeric.md --- # IsNumeric 返回一个**Boolean**,指示表达式是否可求值为数字。 语法:**IsNumeric(** *expression* **)** *expression* : *必需* **Variant**,包含数值或字符串表达式。 如果整个*expression*被识别为数字,**IsNumeric**返回**True**;否则返回**False**。 如果*expression*是日期表达式,**IsNumeric**返回**False**。 ### 示例 本示例使用**IsNumeric**确定变量是否可求值为数字。 ```vb Dim MyVar As Variant Dim MyCheck As Boolean MyVar = "53" MyCheck = IsNumeric(MyVar) ' Returns True. MyVar = "459.95" MyCheck = IsNumeric(MyVar) ' Returns True. MyVar = "45 Help" MyCheck = IsNumeric(MyVar) ' Returns False. ``` ### 另请参阅 * [CDbl](/official/Reference/VBA/Conversion/CDbl)、[CDec](/official/Reference/VBA/Conversion/CDec)函数 * [IsDate](/official/Reference/VBA/Information/IsDate)函数 * [Val](/official/Reference/VBA/Conversion/Val)函数 --- --- url: /en/official/Reference/VBA/Information/IsObject.md --- # IsObject Returns a **Boolean** indicating whether an identifier represents an object variable. Syntax: **IsObject(** *identifier* **)** *identifier* : *required* A variable name. **IsObject** is useful only for determining whether a **Variant** holds **VarType vbObject**. This is the case if the **Variant** actually references --- or once referenced --- an object, or if it contains **Nothing**. **IsObject** returns **True** if *identifier* is a variable declared with **Object** type or any valid class type, or if *identifier* is a **Variant** of **VarType vbObject**, or a user-defined object; otherwise, it returns **False**. **IsObject** returns **True** even if the variable has been set to **Nothing**. Use error trapping to be sure that an object reference is valid before dereferencing it. ::: info twinBASIC also exposes a generic form, **IsObject(Of *T*)**, which is useful for compile-time verification of generic type specifiers. The non-generic call uses special internal bindings and so may not behave like a regular function. ::: ### Example This example uses **IsObject** to determine whether an identifier represents an object variable. *MyObject* and *YourObject* are object variables of the same type, used here for illustration. ```vb Dim MyInt As Integer ' Declare variables. Dim YourObject As Variant, MyCheck As Boolean Dim MyObject As Object Set YourObject = MyObject ' Assign an object reference. MyCheck = IsObject(YourObject) ' Returns True. MyCheck = IsObject(MyInt) ' Returns False. MyCheck = IsObject(Nothing) ' Returns True. MyCheck = IsObject(Empty) ' Returns False. MyCheck = IsObject(Null) ' Returns False. ``` ### See Also * [VarType](/en/official/Reference/VBA/Information/VarType), [TypeName](/en/official/Reference/VBA/Information/TypeName) functions * [IsArray](/en/official/Reference/VBA/Information/IsArray) function --- --- url: /zh/official/Reference/VBA/Information/IsObject.md --- # IsObject 返回一个**Boolean**,指示标识符是否表示对象变量。 语法:**IsObject(** *identifier* **)** *identifier* : *必需* 变量名。 **IsObject**仅用于确定**Variant**是否持有**VarType vbObject**。当**Variant**实际引用——或曾经引用——一个对象,或包含**Nothing**时属于这种情况。 如果*identifier*是用**Object**类型或任何有效类类型声明的变量,或是**VarType vbObject**的**Variant**,或是用户自定义对象,**IsObject**返回**True**;否则返回**False**。 即使变量已设置为**Nothing**,**IsObject**仍返回**True**。在取消引用对象引用之前,请使用错误捕获来确保其有效。 ::: info twinBASIC还公开了泛型形式**IsObject(Of *T*)**,用于泛型类型说明符的编译时验证。非泛型调用使用特殊的内部绑定,因此其行为可能不像常规函数。 ::: ### 示例 本示例使用**IsObject**确定标识符是否表示对象变量。*MyObject*和*YourObject*是相同类型的对象变量,在此用于说明。 ```vb Dim MyInt As Integer ' Declare variables. Dim YourObject As Variant, MyCheck As Boolean Dim MyObject As Object Set YourObject = MyObject ' Assign an object reference. MyCheck = IsObject(YourObject) ' Returns True. MyCheck = IsObject(MyInt) ' Returns False. MyCheck = IsObject(Nothing) ' Returns True. MyCheck = IsObject(Empty) ' Returns False. MyCheck = IsObject(Null) ' Returns False. ``` ### 另请参阅 * [VarType](/official/Reference/VBA/Information/VarType)、[TypeName](/official/Reference/VBA/Information/TypeName)函数 * [IsArray](/official/Reference/VBA/Information/IsArray)函数 --- --- url: /en/official/Reference/WinServicesLib/ITbService.md --- # ITbService interface The contract every service class in a **WinServicesLib** project implements. Three subs, each invoked at a specific point in the service's lifecycle: * [**EntryPoint**](#entrypoint) -- runs the service's actual work. * [**StartupFailed**](#startupfailed) -- invoked when the SCM handshake fails before [**EntryPoint**](#entrypoint) can run. * [**ChangeState**](#changestate) -- invoked when the SCM delivers a control code (*Stop*, *Pause*, *Continue*, …). The package's [**ServiceCreator**](/en/official/Reference/WinServicesLib/ServiceCreator)`(Of T)` factory creates one instance per service start; the dispatcher trampoline holds the instance for the lifetime of the service and routes the three lifecycle subs to it. ```vb [COMCreatable(False)] Class MyService Implements ITbService Public IsStopping As Boolean Sub EntryPoint(ByVal ServiceManager As ServiceManager) _ Implements ITbService.EntryPoint ServiceManager.ReportStatus vbServiceStatusRunning Do Until IsStopping ' ...do work, then yield with WaitForSingleObject / Sleep / etc. Loop ServiceManager.ReportStatus vbServiceStatusStopped End Sub Sub ChangeState(ByVal ServiceManager As ServiceManager, _ ByVal dwControl As ServiceControlCodeConstants, _ ByVal dwEventType As Long, _ ByVal lpEventData As LongPtr) _ Implements ITbService.ChangeState Select Case dwControl Case vbServiceControlStop, vbServiceControlShutdown ServiceManager.ReportStatus vbServiceStatusStopPending IsStopping = True End Select End Sub Sub StartupFailed(ByVal ServiceManager As ServiceManager) _ Implements ITbService.StartupFailed ' …optional failure-reporting hook End Sub End Class ``` ::: warning [**EntryPoint**](#entrypoint) runs on the **service thread**. [**ChangeState**](#changestate) runs on the **dispatcher thread** (the EXE's main thread). The two methods execute concurrently and must coordinate through shared `Public` flags on the class --- see [The two-thread split](/en/official/Reference/WinServicesLib/#two-thread-split) on the package overview. ::: ## Methods ### ChangeState Invoked by the SCM dispatcher thread when a control code is delivered to the service. Syntax: *service*.**ChangeState** *ServiceManager*, *dwControl*, *dwEventType*, *lpEventData* *ServiceManager* : The [**ServiceManager**](/en/official/Reference/WinServicesLib/ServiceManager) for this service --- the same instance passed to [**EntryPoint**](#entrypoint). The implementation calls [**ReportStatus**](/en/official/Reference/WinServicesLib/ServiceManager#reportstatus) on it to acknowledge the pending transition. *dwControl* : A [**ServiceControlCodeConstants**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants) value identifying the control. Standard codes the SCM may deliver include [**vbServiceControlStop**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlStop), [**vbServiceControlShutdown**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlShutdown), [**vbServiceControlPause**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlPause), [**vbServiceControlContinue**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlContinue), [**vbServiceControlInterrogate**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlInterrogate), and the event-bearing codes ([**vbServiceControlSessionChange**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlSessionChange), [**vbServiceControlPowerEvent**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlPowerEvent), [**vbServiceControlDeviceEvent**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlDeviceEvent), [**vbServiceControlHardwareProfileChange**](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlHardwareProfileChange)). User-defined codes in the range 128--255 can also be delivered through [**Services.ControlService**](/en/official/Reference/WinServicesLib/Services#controlservice). *dwEventType* : A **Long** holding the event-type sub-code for the codes that have one. **0** otherwise. See Microsoft's `HandlerEx` documentation for the per-code interpretation. *lpEventData* : A **LongPtr** to an event-specific data structure for the codes that have one. `vbNullPtr` otherwise. The typical pattern is a `Select Case dwControl` that handles the codes the service cares about and ignores the rest. The minimum a service needs to handle is *Stop*: ```vb Select Case dwControl Case vbServiceControlStop, vbServiceControlShutdown ServiceManager.ReportStatus vbServiceStatusStopPending IsStopping = True ' signal the service thread End Select ``` [**ChangeState**](#changestate) **does not stop** [**EntryPoint**](#entrypoint) --- it only delivers the SCM's request. The user's code is responsible for the actual shutdown logic, typically by setting a shared `Public` flag the service thread polls (`IsStopping`) or by calling a signal method on a blocking primitive that [**EntryPoint**](#entrypoint) owns (`NamedPipeServer.ManualMessageLoopLeave`, `SetEvent` on a Win32 event handle, ...). The method runs on a different thread than [**EntryPoint**](#entrypoint); see [The two-thread split](/en/official/Reference/WinServicesLib/#two-thread-split) for the coordination rules. ### EntryPoint The service's main routine. Invoked by the package's dispatcher trampoline on the SCM-spawned service thread once the SCM handshake has completed and the trampoline has reported [**vbServiceStatusStartPending**](/en/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants#vbServiceStatusStartPending). Syntax: *service*.**EntryPoint** *ServiceManager* *ServiceManager* : The [**ServiceManager**](/en/official/Reference/WinServicesLib/ServiceManager) for this service. Contains the configuration that was set during `Sub Main` plus the runtime [**LaunchArgs**](/en/official/Reference/WinServicesLib/ServiceManager#launchargs) the SCM passed in. The implementation calls [**ReportStatus**](/en/official/Reference/WinServicesLib/ServiceManager#reportstatus) on it for every state transition. The body of **EntryPoint** is the service's actual work. The minimum responsibilities: 1. Optionally validate startup conditions (typically by inspecting [**LaunchArgs**](/en/official/Reference/WinServicesLib/ServiceManager#launchargs)). Failure paths should call `ServiceManager.ReportStatus vbServiceStatusStopped, <ExitCode>` and `Exit Sub`. 2. Call `ServiceManager.ReportStatus vbServiceStatusRunning` once steady-state is reached. 3. Run the service's long-running loop. The loop typically blocks on something (a `WaitForSingleObject` on a manual-reset event, a `NamedPipeServer.ManualMessageLoopEnter`, a custom message loop, ...) and breaks out when [**ChangeState**](#changestate) signals shutdown through a shared flag. 4. Call `ServiceManager.ReportStatus vbServiceStatusStopped` before returning. After the **EntryPoint** sub returns, the service thread exits and the SCM marks the service as stopped. ::: warning **EntryPoint** runs on the **service thread**, not the dispatcher thread. The two threads execute concurrently for the lifetime of the service. Shared `Public` flags on the implementing class (`IsStopping`, `IsPaused`, …) coordinate state changes triggered from [**ChangeState**](#changestate). ::: ### StartupFailed Invoked when the SCM handshake fails before [**EntryPoint**](#entrypoint) can run. Syntax: *service*.**StartupFailed** *ServiceManager* *ServiceManager* : The [**ServiceManager**](/en/official/Reference/WinServicesLib/ServiceManager) for this service. This sub fires when `RegisterServiceCtrlHandlerExW` returns a zero handle --- typically because the service was launched outside the SCM context, or the SCM's `RegisterServiceCtrlHandlerExW` rejected the registration. The service has no SCM status handle in this state, so [**ServiceManager.ReportStatus**](/en/official/Reference/WinServicesLib/ServiceManager#reportstatus) cannot be called from inside **StartupFailed** --- calling it raises run-time error 5. The typical implementation is a logging-only hook so the failure is recorded somewhere a developer can find it later: ```vb Sub StartupFailed(ByVal ServiceManager As ServiceManager) _ Implements ITbService.StartupFailed LogFailure service_startup_failed, status_changed, CurrentComponentName End Sub ``` If there is no useful failure-reporting hook to add, an empty implementation is fine --- the SCM has already abandoned the start attempt at this point and no recovery is possible. ## See Also * [WinServicesLib package](/en/official/Reference/WinServicesLib/) -- overview, lifecycle, [the two-thread split](/en/official/Reference/WinServicesLib/#two-thread-split) * [ServiceManager class](/en/official/Reference/WinServicesLib/ServiceManager) -- the per-service object passed into every method * [ServiceCreator(Of T) class](/en/official/Reference/WinServicesLib/ServiceCreator) -- the factory that creates an **ITbService** instance for each service start * [ServiceControlCodeConstants enum](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants) -- the values **ChangeState** dispatches on * [ServiceStatusConstants enum](/en/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants) -- the values **EntryPoint** reports through [**ServiceManager.ReportStatus**](/en/official/Reference/WinServicesLib/ServiceManager#reportstatus) --- --- url: /zh/official/Reference/WinServicesLib/ITbService.md --- # ITbService 接口 每个 **WinServicesLib** 项目中的服务类必须实现的契约。三个子过程,每个在服务生命周期的特定点被调用: * [**EntryPoint**](#entrypoint) -- 运行服务的实际工作。 * [**StartupFailed**](#startupfailed) -- 当SCM握手在 [**EntryPoint**](#entrypoint) 可以运行之前失败时调用。 * [**ChangeState**](#changestate) -- 当SCM传递控制代码(*Stop*、*Pause*、*Continue*、…)时调用。 包的 [**ServiceCreator**](/official/Reference/WinServicesLib/ServiceCreator)`(Of T)` 工厂为每次服务启动创建一个实例;调度器跳板在服务的整个生命周期内持有该实例,并将三个生命周期子过程路由到它。 ```vb [COMCreatable(False)] Class MyService Implements ITbService Public IsStopping As Boolean Sub EntryPoint(ByVal ServiceManager As ServiceManager) _ Implements ITbService.EntryPoint ServiceManager.ReportStatus vbServiceStatusRunning Do Until IsStopping ' ...做工作,然后用 WaitForSingleObject / Sleep 等让出 Loop ServiceManager.ReportStatus vbServiceStatusStopped End Sub Sub ChangeState(ByVal ServiceManager As ServiceManager, _ ByVal dwControl As ServiceControlCodeConstants, _ ByVal dwEventType As Long, _ ByVal lpEventData As LongPtr) _ Implements ITbService.ChangeState Select Case dwControl Case vbServiceControlStop, vbServiceControlShutdown ServiceManager.ReportStatus vbServiceStatusStopPending IsStopping = True End Select End Sub Sub StartupFailed(ByVal ServiceManager As ServiceManager) _ Implements ITbService.StartupFailed ' …可选的失败报告钩子 End Sub End Class ``` ::: warning [**EntryPoint**](#entrypoint) 运行在**服务线程**上。[**ChangeState**](#changestate) 运行在**调度器线程**(EXE的主线程)上。两个方法并发执行,必须通过类上的共享 `Public` 标志进行协调——参见包概述上的[双线程分离](/official/Reference/WinServicesLib/#two-thread-split)。 ::: ## 方法 ### ChangeState 当控制代码传递给服务时,由SCM调度器线程调用。 语法:*service*.**ChangeState** *ServiceManager*, *dwControl*, *dwEventType*, *lpEventData* *ServiceManager* : 此服务的 [**ServiceManager**](/official/Reference/WinServicesLib/ServiceManager)——与传递给 [**EntryPoint**](#entrypoint) 的实例相同。实现在其上调用 [**ReportStatus**](/official/Reference/WinServicesLib/ServiceManager#reportstatus) 以确认待处理的转换。 *dwControl* : 标识控制的 [**ServiceControlCodeConstants**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants) 值。SCM可能传递的标准代码包括 [**vbServiceControlStop**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlStop)、[**vbServiceControlShutdown**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlShutdown)、[**vbServiceControlPause**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlPause)、[**vbServiceControlContinue**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlContinue)、[**vbServiceControlInterrogate**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlInterrogate),以及承载事件的代码([**vbServiceControlSessionChange**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlSessionChange)、[**vbServiceControlPowerEvent**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlPowerEvent)、[**vbServiceControlDeviceEvent**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlDeviceEvent)、[**vbServiceControlHardwareProfileChange**](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants#vbServiceControlHardwareProfileChange))。128--255范围内的用户定义代码也可以通过 [**Services.ControlService**](/official/Reference/WinServicesLib/Services#controlservice) 传递。 *dwEventType* : 包含具有子代码的代码的事件类型子代码的 **Long**。否则为 **0**。参见Microsoft的 `HandlerEx` 文档了解每个代码的解释。 *lpEventData* : 对于具有事件特定数据结构的代码,为指向该结构的 **LongPtr**。否则为 `vbNullPtr`。 典型模式是 `Select Case dwControl` 处理服务关心的代码并忽略其余代码。服务至少需要处理 *Stop*: ```vb Select Case dwControl Case vbServiceControlStop, vbServiceControlShutdown ServiceManager.ReportStatus vbServiceStatusStopPending IsStopping = True ' 向服务线程发出信号 End Select ``` [**ChangeState**](#changestate) **不会停止** [**EntryPoint**](#entrypoint)——它只传递SCM的请求。用户的代码负责实际的关闭逻辑,通常通过设置服务线程轮询的共享 `Public` 标志(`IsStopping`)或调用 [**EntryPoint**](#entrypoint) 拥有的阻塞原语上的信号方法(`NamedPipeServer.ManualMessageLoopLeave`、Win32事件句柄上的 `SetEvent`、…)。 该方法在与 [**EntryPoint**](#entrypoint) 不同的线程上运行;参见[双线程分离](/official/Reference/WinServicesLib/#two-thread-split)了解协调规则。 ### EntryPoint 服务的主例程。在SCM握手完成且跳板已报告 [**vbServiceStatusStartPending**](/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants#vbServiceStatusStartPending) 后,由包的调度器跳板在SCM生成的服务线程上调用。 语法:*service*.**EntryPoint** *ServiceManager* *ServiceManager* : 此服务的 [**ServiceManager**](/official/Reference/WinServicesLib/ServiceManager)。包含在 `Sub Main` 期间设置的配置以及SCM传入的运行时 [**LaunchArgs**](/official/Reference/WinServicesLib/ServiceManager#launchargs)。实现为其调用 [**ReportStatus**](/official/Reference/WinServicesLib/ServiceManager#reportstatus) 进行每个状态转换。 **EntryPoint** 的主体是服务的实际工作。最低职责: 1. 可选地验证启动条件(通常通过检查 [**LaunchArgs**](/official/Reference/WinServicesLib/ServiceManager#launchargs))。失败路径应调用 `ServiceManager.ReportStatus vbServiceStatusStopped, <ExitCode>` 和 `Exit Sub`。 2. 一旦达到稳定状态即调用 `ServiceManager.ReportStatus vbServiceStatusRunning`。 3. 运行服务的长时间运行循环。循环通常阻塞在某个东西上(手动重置事件上的 `WaitForSingleObject`、`NamedPipeServer.ManualMessageLoopEnter`、自定义消息循环、…),当 [**ChangeState**](#changestate) 通过共享标志发出关闭信号时跳出。 4. 返回前调用 `ServiceManager.ReportStatus vbServiceStatusStopped`。 **EntryPoint** 子过程返回后,服务线程退出,SCM将服务标记为已停止。 ::: warning **EntryPoint** 运行在**服务线程**上,而非调度器线程。两个线程在服务生命周期内并发执行。实现类上的共享 `Public` 标志(`IsStopping`、`IsPaused`、…)协调从 [**ChangeState**](#changestate) 触发的状态变更。 ::: ### StartupFailed 当SCM握手在 [**EntryPoint**](#entrypoint) 可以运行之前失败时调用。 语法:*service*.**StartupFailed** *ServiceManager* *ServiceManager* : 此服务的 [**ServiceManager**](/official/Reference/WinServicesLib/ServiceManager)。 此子过程在 `RegisterServiceCtrlHandlerExW` 返回零句柄时触发——通常是因为服务在SCM上下文之外启动,或SCM的 `RegisterServiceCtrlHandlerExW` 拒绝了注册。服务在此状态下没有SCM状态句柄,因此 [**ServiceManager.ReportStatus**](/official/Reference/WinServicesLib/ServiceManager#reportstatus) 不能从 **StartupFailed** 内部调用——调用它会引发运行时错误5。 典型实现是仅记录日志的钩子,以便开发人员稍后可以找到失败: ```vb Sub StartupFailed(ByVal ServiceManager As ServiceManager) _ Implements ITbService.StartupFailed LogFailure service_startup_failed, status_changed, CurrentComponentName End Sub ``` 如果没有有用的失败报告钩子可以添加,空实现也可以——SCM此时已经放弃了启动尝试,无法恢复。 ## 另见 * [WinServicesLib 包](/official/Reference/WinServicesLib/) -- 概述、生命周期、[双线程分离](/official/Reference/WinServicesLib/#two-thread-split) * [ServiceManager 类](/official/Reference/WinServicesLib/ServiceManager) -- 传入每个方法的每服务对象 * [ServiceCreator(Of T) 类](/official/Reference/WinServicesLib/ServiceCreator) -- 为每次服务启动创建 **ITbService** 实例的工厂 * [ServiceControlCodeConstants 枚举](/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants) -- **ChangeState** 分发的值 * [ServiceStatusConstants 枚举](/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants) -- **EntryPoint** 通过 [**ServiceManager.ReportStatus**](/official/Reference/WinServicesLib/ServiceManager#reportstatus) 报告的值 --- --- url: /en/official/Reference/VBA/Collection/Item.md --- # Item Returns a specific member of a **Collection** object, either by position or by key. Syntax: *object*.**Item(** *index* **)** *object* : *required* An object expression that evaluates to a **Collection** object. *index* : *required* An expression that specifies the position of a member of the collection. If a numeric expression, *index* must be a number from 1 to the value of the collection's [**Count**](/en/official/Reference/VBA/Collection/Count) property. If a string expression, *index* must correspond to the *key* argument specified when the member referred to was added to the collection. If *index* doesn't match any existing member of the collection, an error occurs. If *index* is neither a number nor a string, an error also occurs. **Item** is the default member of a **Collection** object. Therefore, the following lines of code are equivalent: ```vb Debug.Print MyCollection(1) Debug.Print MyCollection.Item(1) ``` Key comparison is governed by the [**KeyCompareMode**](/en/official/Reference/VBA/Collection/KeyCompareMode) property. ### Example This example uses the **Item** method to retrieve a reference to an object in a collection. Assuming `Birthdays` is a **Collection** object, the following code retrieves references to the objects representing Bill Smith's birthday and Adam Smith's birthday, using the keys `"SmithBill"` and `"SmithAdam"` as the *index* arguments. The first call explicitly specifies the **Item** method; the second does not. Both calls work because **Item** is the default member of a **Collection** object. ```vb Dim SmithBillBD As Object Dim SmithAdamBD As Object Dim Birthdays As Collection ' ... assume Birthdays has been populated ... Set SmithBillBD = Birthdays.Item("SmithBill") Set SmithAdamBD = Birthdays("SmithAdam") ``` ### See Also * [Add](/en/official/Reference/VBA/Collection/Add) method * [Count](/en/official/Reference/VBA/Collection/Count) property * [Exists](/en/official/Reference/VBA/Collection/Exists) method * [Items](/en/official/Reference/VBA/Collection/Items) method * [Remove](/en/official/Reference/VBA/Collection/Remove) method --- --- url: /zh/official/Reference/VBA/Collection/Item.md --- # Item 按位置或按键返回 **Collection** 对象中的特定成员。 语法:*object*.**Item(** *index* **)** *object* : *必需* 一个计算结果为 **Collection** 对象的对象表达式。 *index* : *必需* 一个指定集合成员位置的表达式。如果是数值表达式,*index* 必须是从 1 到集合的 [**Count**](/official/Reference/VBA/Collection/Count) 属性值之间的数字。如果是字符串表达式,*index* 必须与被引用成员添加到集合时指定的 *key* 参数相对应。 如果 *index* 不匹配集合中的任何现有成员,将发生错误。如果 *index* 既不是数字也不是字符串,也会发生错误。 **Item** 是 **Collection** 对象的默认成员。因此,以下两行代码是等效的: ```vb Debug.Print MyCollection(1) Debug.Print MyCollection.Item(1) ``` 键比较由 [**KeyCompareMode**](/official/Reference/VBA/Collection/KeyCompareMode) 属性控制。 ### 示例 此示例使用 **Item** 方法检索集合中对象的引用。假设 `Birthdays` 是一个 **Collection** 对象,以下代码使用键 `"SmithBill"` 和 `"SmithAdam"` 作为 *index* 参数来检索表示 Bill Smith 生日和 Adam Smith 生日的对象引用。 第一次调用显式指定了 **Item** 方法;第二次没有。两次调用都可以工作,因为 **Item** 是 **Collection** 对象的默认成员。 ```vb Dim SmithBillBD As Object Dim SmithAdamBD As Object Dim Birthdays As Collection ' ... assume Birthdays has been populated ... Set SmithBillBD = Birthdays.Item("SmithBill") Set SmithAdamBD = Birthdays("SmithAdam") ``` ### 另请参阅 * [Add](/official/Reference/VBA/Collection/Add) 方法 * [Count](/official/Reference/VBA/Collection/Count) 属性 * [Exists](/official/Reference/VBA/Collection/Exists) 方法 * [Items](/official/Reference/VBA/Collection/Items) 方法 * [Remove](/official/Reference/VBA/Collection/Remove) 方法 --- --- url: /en/official/Reference/VBA/Collection/Items.md --- # Items Returns a **Variant** array containing all the items in a **Collection** object. The lower bound of the returned array is zero. Syntax: *object*.**Items()** *object* : *required* An object expression that evaluates to a **Collection** object. ::: info **Items** is a twinBASIC extension; the classic VBA **Collection** object has no **Items** method. The same effect in VBA requires iterating the collection with **For Each** and copying each item into an array. ::: If the collection is empty, **Items** returns an empty array. The **Items** method is useful when passing the collection's contents to a procedure expecting an array, or to iterate without holding a reference to the collection. ### Example ```vb Dim col As New Collection col.Add "Athens" col.Add "Belgrade" col.Add "Cairo" Dim a As Variant a = col.Items ' Get all items as a Variant array. Dim i As Long For i = LBound(a) To UBound(a) Debug.Print a(i) Next i ``` ### See Also * [Item](/en/official/Reference/VBA/Collection/Item) method * [Keys](/en/official/Reference/VBA/Collection/Keys) method * [Count](/en/official/Reference/VBA/Collection/Count) property * [Add](/en/official/Reference/VBA/Collection/Add) method --- --- url: /zh/official/Reference/VBA/Collection/Items.md --- # Items 返回一个 **Variant** 数组,包含 **Collection** 对象中的所有项。返回数组的下界为零。 语法:*object*.**Items()** *object* : *必需* 一个计算结果为 **Collection** 对象的对象表达式。 ::: info **Items** 是 twinBASIC 扩展;经典 VBA 的 **Collection** 对象没有 **Items** 方法。在 VBA 中要实现相同效果,需要使用 **For Each** 遍历集合并将每个项复制到数组中。 ::: 如果集合为空,**Items** 返回一个空数组。 **Items** 方法在将集合内容传递给期望数组的过程,或在不持有集合引用的情况下进行迭代时非常有用。 ### 示例 ```vb Dim col As New Collection col.Add "Athens" col.Add "Belgrade" col.Add "Cairo" Dim a As Variant a = col.Items ' Get all items as a Variant array. Dim i As Long For i = LBound(a) To UBound(a) Debug.Print a(i) Next i ``` ### 另请参阅 * [Item](/official/Reference/VBA/Collection/Item) 方法 * [Keys](/official/Reference/VBA/Collection/Keys) 方法 * [Count](/official/Reference/VBA/Collection/Count) 属性 * [Add](/official/Reference/VBA/Collection/Add) 方法 --- --- url: /en/official/Tutorials/CEF/JavaScript-interop.md --- # JavaScript interop The [**CefBrowser**](/en/official/Reference/CEF/CefBrowser/) control offers two complementary bridges between twinBASIC and the JavaScript running in the page: 1. **Messages** --- push a value (string, number, …) in either direction and listen for it on the other side. 2. **Scripted calls** --- call a named JavaScript function from BASIC and (optionally) wait for its return value. ::: info [**WebView2**](/en/official/Reference/WebView2/WebView2/) also exposes a third bridge --- *host objects*, where a BASIC class is published under `chrome.webview.hostObjects.<Name>` for the page to call into. The CEF package does not yet expose an equivalent --- see the [WebView2 parity](/en/official/Reference/CEF/#webview2-parity) section of the reference. ::: This tutorial covers both bridges, with the matching JavaScript side shown next to each BASIC side. The worked code comes from *Sample 1b --- Chromium Embedded Framework Examples* (form *Example 2*). ## Bridge 1 --- Messages Messages are values that travel in either direction. Use them for notifications and ad-hoc payloads where you don't want to define a method signature ahead of time. ### BASIC → page [**PostWebMessage**](/en/official/Reference/CEF/CefBrowser/#postwebmessage) sends a value to the page; the page receives it through a `message` event on `window.chrome.webview`: ```vb WebView.PostWebMessage "Hello from twinBASIC!" ``` ```js window.chrome.webview.addEventListener('message', (e) => { alert("Host sent: " + e.data); }); ``` Strings arrive as JavaScript strings; numerics, **Boolean**, **Null**, and **Empty** are JSON-encoded for the page. Objects and arrays are not currently supported. If [**PostWebMessage**](/en/official/Reference/CEF/CefBrowser/#postwebmessage) is called before the renderer IPC has connected, the call is queued and dispatched once the connection comes up --- there's no need to wait for [**Ready**](/en/official/Reference/CEF/CefBrowser/#ready) explicitly. ### Page → BASIC The page calls `window.chrome.webview.postMessage(value)`; BASIC receives it as the [**JsMessage**](/en/official/Reference/CEF/CefBrowser/#jsmessage) event: ```js function sendHostAMessage() { window.chrome.webview.postMessage("This is a message from JavaScript."); } ``` ```vb Private Sub WebView_JsMessage(ByVal Message As Variant) _ Handles WebView.JsMessage Debug.Print "Page sent: "; Message End Sub ``` The two halves form a request / reply exchange --- the page posts a query string, BASIC processes it and posts a result back: ```vb Private Sub WebView_JsMessage(ByVal Message As Variant) _ Handles WebView.JsMessage If Left$(Message, 6) = "QUERY:" Then WebView.PostWebMessage "ANSWER:" & LookupAnswer(Mid$(Message, 7)) End If End Sub ``` ## Bridge 2 --- Scripted calls When the page exposes named JS functions, BASIC can call them directly. There are three variants: | Method | Returns | Use it when | |-----------------------------------------------------------------------------------|--------------------------------------------------|-------------------------------------------------------------------| | [**JsRun**](/en/official/Reference/CEF/CefBrowser/#jsrun) | **Variant**, synchronously | You need the result inline and the JS is **pure** (no callbacks). | | [**JsRunAsync**](/en/official/Reference/CEF/CefBrowser/#jsrunasync) | nothing; result via `JsAsyncResult` | The JS may take a while and you don't want to block the UI. | | [**ExecuteScript**](/en/official/Reference/CEF/CefBrowser/#executescript) | nothing (fire-and-forget) | You just want to trigger something --- no return value needed. | ### JsRun (synchronous) Given a page-side function: ```js function multiplyTheseNumbers(a, b) { return a * b; } ``` BASIC can call it and read the result on the same line: ```vb Dim product As Long = WebView.JsRun("multiplyTheseNumbers", 5, 6) Debug.Print product ' 30 ``` The call blocks the BASIC thread until the renderer process replies. ::: warning If the JavaScript function calls back into BASIC during the call --- via `window.chrome.webview.postMessage(...)`, for instance --- the result is a deadlock. Use [**JsRun**](/en/official/Reference/CEF/CefBrowser/#jsrun) only for pure functions; reach for [**JsRunAsync**](/en/official/Reference/CEF/CefBrowser/#jsrunasync) the moment that's not true. See the [Re-entrancy tutorial](/en/official/Tutorials/CEF/Re-entrancy) for the full discussion. ::: ### JsRunAsync (asynchronous) ```vb Private Sub btnRun_Click() Handles btnRun.Click WebView.JsRunAsync "multiplyTheseNumbers", 5, 6 End Sub Private Sub WebView_JsAsyncResult( _ ByVal Result As Variant, Token As LongLong, ErrString As String) _ Handles WebView.JsAsyncResult If LenB(ErrString) = 0 Then Debug.Print "Async result: "; Result Else Debug.Print "Async error: "; ErrString End If End Sub ``` The [**JsAsyncResult**](/en/official/Reference/CEF/CefBrowser/#jsasyncresult) event includes a *Token* parameter so a single handler can demultiplex multiple in-flight calls. *ErrString* is empty on success. Calls made before the renderer IPC has connected are queued and dispatched once the connection comes up. ### ExecuteScript (fire-and-forget) ```vb WebView.ExecuteScript "startTimer()" ``` No return value, no event. The simplest way to nudge the page into doing something. ## Re-entrancy The discussion of when calling synchronous JavaScript from BASIC is safe --- and what to do when it isn't --- lives in its own tutorial. The short summary: * **Pure JS** (input → output, no side effects that touch the host): [**JsRun**](/en/official/Reference/CEF/CefBrowser/#jsrun) is fine. * **JS that might post back, await a host object, or otherwise re-enter BASIC**: use [**JsRunAsync**](/en/official/Reference/CEF/CefBrowser/#jsrunasync). See the [Re-entrancy tutorial](/en/official/Tutorials/CEF/Re-entrancy) for the full picture. ## Where next * [Hosting local web assets](/en/official/Tutorials/CEF/Hosting-local-web-assets) -- bundle and serve the JavaScript that talks to the host. * [Driving Monaco from twinBASIC](/en/official/Tutorials/CEF/Driving-Monaco) -- a full case study using both bridges. * [Re-entrancy](/en/official/Tutorials/CEF/Re-entrancy) -- the deeper story behind synchronous vs. asynchronous calls. * [CefBrowser reference](/en/official/Reference/CEF/CefBrowser/) -- every property, method, and event. --- --- url: /en/official/Tutorials/WebView2/JavaScript-interop.md --- # JavaScript interop The [**WebView2**](/en/official/Reference/WebView2/WebView2/) control offers three complementary bridges between twinBASIC and the JavaScript running in the page: 1. **Host objects** --- publish a BASIC COM object to the page so JavaScript can call its methods and read its properties as if it were any other JS object. 2. **Messages** --- push a value (string, number, array, …) in either direction and listen for it on the other side. 3. **Scripted calls** --- call a named JavaScript function from BASIC and (optionally) wait for its return value. This tutorial covers all three, with the matching JavaScript side shown next to each BASIC side. The worked code comes from *Sample 0 --- WebView2 Examples* (form *Example 2*). ## Bridge 1 --- Host objects [**AddObject**](/en/official/Reference/WebView2/WebView2/#addobject) publishes a BASIC class instance under `chrome.webview.hostObjects.<Name>`. Define a small class with public methods or properties: ```vb Class MyCalculator Public Function MultiplyByTen(ByVal Value As Long) As Long Return Value * 10 End Function End Class ``` Register it once the control is ready: ```vb Private Sub WebView_Ready() Handles WebView.Ready WebView.AddObject "myCalculator", New MyCalculator End Sub ``` JavaScript can now call into it --- but the proxy is asynchronous, so the call must be `await`ed inside an `async` function: ```js async function testHostCalculator() { let value = Math.floor(Math.random() * 100000); let result = await chrome.webview.hostObjects.myCalculator.MultiplyByTen(value); alert(`BASIC said ${value} × 10 = ${result}`); } ``` To trigger the JS function from BASIC, call [**ExecuteScript**](/en/official/Reference/WebView2/WebView2/#executescript): ```vb Private Sub btnTest_Click() Handles btnTest.Click WebView.ExecuteScript("testHostCalculator()") End Sub ``` Requires [**AreHostObjectsAllowed**](/en/official/Reference/WebView2/WebView2/#arehostobjectsallowed) (default **True**). See [Re-entrancy](/en/official/Tutorials/WebView2/Re-entrancy) for the trade-off between synchronous calls (default) and the **UseDeferredInvoke:=True** variant. ## Bridge 2 --- Messages Messages are values that travel in either direction. Use them for notifications and ad-hoc payloads where you don't want to define a method signature ahead of time. ### BASIC → page [**PostWebMessage**](/en/official/Reference/WebView2/WebView2/#postwebmessage) sends a value to the page; the page receives it through a `message` event on `window.chrome.webview`: ```vb WebView.PostWebMessage "Hello from twinBASIC!" ``` ```js window.chrome.webview.addEventListener('message', (e) => { alert("Host sent: " + e.data); }); ``` Strings arrive as JavaScript strings; every other type is JSON-encoded before transit. If you already have serialised JSON, [**PostWebMessageJSON**](/en/official/Reference/WebView2/WebView2/#postwebmessagejson) sends it through verbatim. ### Page → BASIC The page calls `window.chrome.webview.postMessage(value)`; BASIC receives it as the [**JsMessage**](/en/official/Reference/WebView2/WebView2/#jsmessage) event: ```js function sendHostAMessage() { window.chrome.webview.postMessage("This is a message from JavaScript."); } ``` ```vb Private Sub WebView_JsMessage(ByVal Message As Variant) _ Handles WebView.JsMessage Debug.Print "Page sent: "; Message End Sub ``` Both directions require [**IsWebMessageEnabled**](/en/official/Reference/WebView2/WebView2/#iswebmessageenabled) (default **True**). ## Bridge 3 --- Scripted calls When the page exposes named JS functions, BASIC can call them directly. There are three variants: | Method | Returns | Use it when | |-----------------------------------------------------------------------------------|--------------------------------------------------|-------------------------------------------------------------------| | [**JsRun**](/en/official/Reference/WebView2/WebView2/#jsrun) | **Variant**, synchronously | You need the result inline and the JS is quick. | | [**JsRunAsync**](/en/official/Reference/WebView2/WebView2/#jsrunasync) | **LongLong** token; result via `JsAsyncResult` | The JS may take a while and you don't want to block the UI. | | [**ExecuteScript**](/en/official/Reference/WebView2/WebView2/#executescript) | nothing (fire-and-forget) | You just want to trigger something --- no return value needed. | ### JsRun (synchronous) Given a page-side function: ```js function multiplyTheseNumbers(a, b) { return a * b; } ``` BASIC can call it and read the result on the same line: ```vb Dim product As Long = WebView.JsRun("multiplyTheseNumbers", 5, 6) Debug.Print product ' 30 ``` The call blocks for up to [**JsCallTimeOutSeconds**](/en/official/Reference/WebView2/WebView2/#jscalltimeoutseconds) (default 0 --- wait forever). ### JsRunAsync (asynchronous) ```vb Private Sub btnRun_Click() Handles btnRun.Click WebView.JsRunAsync "multiplyTheseNumbers", 5, 6 End Sub Private Sub WebView_JsAsyncResult( _ ByVal Result As Variant, Token As LongLong, ErrString As String) _ Handles WebView.JsAsyncResult If LenB(ErrString) = 0 Then Debug.Print "Async result: "; Result Else Debug.Print "Async error: "; ErrString End If End Sub ``` The return value of [**JsRunAsync**](/en/official/Reference/WebView2/WebView2/#jsrunasync) is a token; the [**JsAsyncResult**](/en/official/Reference/WebView2/WebView2/#jsasyncresult) event includes the same token so a single handler can demultiplex multiple in-flight calls. ### ExecuteScript (fire-and-forget) ```vb WebView.ExecuteScript "startTimer()" ``` No return value, no event. The simplest way to nudge the page into doing something. ## Re-entrancy The Edge runtime forbids host code from calling back into the WebView2 object model while a host-object method is still executing --- re-entry deadlocks the browser process. The control protects most events by deferring them through the BASIC message loop ([**UseDeferredEvents**](/en/official/Reference/WebView2/WebView2/#usedeferredevents)), but host-object method calls are synchronous by default. The full discussion lives in the [Re-entrancy tutorial](/en/official/Tutorials/WebView2/Re-entrancy); the short summary is: * **`AddObject(name, obj)`** --- synchronous calls; the page can read return values but the BASIC method **must not** call back into the WebView2 control. * **`AddObject(name, obj, UseDeferredInvoke:=True)`** --- asynchronous calls; the BASIC method is free to call any WebView2 member but the page cannot read a return value. ## Where next * [Hosting local web assets](/en/official/Tutorials/WebView2/Hosting-local-web-assets) -- bundle and serve the JavaScript that talks to the host. * [Driving Monaco from twinBASIC](/en/official/Tutorials/WebView2/Driving-Monaco) -- a full case study using all three bridges. * [Re-entrancy](/en/official/Tutorials/WebView2/Re-entrancy) -- the deeper story behind **UseDeferredInvoke**. * [WebView2 reference](/en/official/Reference/WebView2/WebView2/) -- every property, method, and event. --- --- url: /zh/official/Tutorials/CEF/JavaScript-interop.md --- # JavaScript互操作 [**CefBrowser**](/official/Reference/CEF/CefBrowser/)控件在twinBASIC和页面中运行的JavaScript之间提供两座互补的桥: 1. **消息** —— 在两个方向推送值(字符串、数字……)并在另一侧监听。 2. **脚本调用** —— 从BASIC调用命名的JavaScript函数,并(可选)等待其返回值。 ::: info [**WebView2**](/official/Reference/WebView2/WebView2/)还暴露了第三座桥——*宿主对象*,其中BASIC类发布到 `chrome.webview.hostObjects.<Name>` 供页面调用。CEF包尚未暴露等效功能——参见参考的[WebView2对等](/official/Reference/CEF/#webview2-parity)部分。 ::: 本教程涵盖两座桥,每个BASIC端旁边显示匹配的JavaScript端。工作代码来自*示例1b——Chromium Embedded Framework示例*(窗体*示例2*)。 ## 桥1——消息 消息是在两个方向传递的值。当你不希望提前定义方法签名时,用于通知和临时数据负载。 ### BASIC → 页面 [**PostWebMessage**](/official/Reference/CEF/CefBrowser/#postwebmessage)向页面发送值;页面通过 `window.chrome.webview` 上的 `message` 事件接收它: ```vb WebView.PostWebMessage "Hello from twinBASIC!" ``` ```js window.chrome.webview.addEventListener('message', (e) => { alert("Host sent: " + e.data); }); ``` 字符串以JavaScript字符串到达;数值、**Boolean**、**Null**和**Empty**为页面进行JSON编码。对象和数组目前不支持。 如果在渲染器IPC连接之前调用[**PostWebMessage**](/official/Reference/CEF/CefBrowser/#postwebmessage),调用会排队并在连接建立后分发——无需显式等待[**Ready**](/official/Reference/CEF/CefBrowser/#ready)。 ### 页面 → BASIC 页面调用 `window.chrome.webview.postMessage(value)`;BASIC通过[**JsMessage**](/official/Reference/CEF/CefBrowser/#jsmessage)事件接收它: ```js function sendHostAMessage() { window.chrome.webview.postMessage("This is a message from JavaScript."); } ``` ```vb Private Sub WebView_JsMessage(ByVal Message As Variant) _ Handles WebView.JsMessage Debug.Print "Page sent: "; Message End Sub ``` 两个半部形成请求/响应交换——页面发送查询字符串,BASIC处理它并返回结果: ```vb Private Sub WebView_JsMessage(ByVal Message As Variant) _ Handles WebView.JsMessage If Left$(Message, 6) = "QUERY:" Then WebView.PostWebMessage "ANSWER:" & LookupAnswer(Mid$(Message, 7)) End If End Sub ``` ## 桥2——脚本调用 当页面暴露命名的JS函数时,BASIC可以直接调用它们。有三种变体: | 方法 | 返回值 | 使用场景 | |-----------------------------------------------------------------------------------|--------------------------------------------------|-------------------------------------------------------------------| | [**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun) | **Variant**,同步 | 你需要内联结果且JS是**纯的**(无回调)。 | | [**JsRunAsync**](/official/Reference/CEF/CefBrowser/#jsrunasync) | 无;结果通过 `JsAsyncResult` | JS可能需要一段时间,你不想阻塞UI。 | | [**ExecuteScript**](/official/Reference/CEF/CefBrowser/#executescript) | 无(即发即弃) | 你只想触发某些操作——不需要返回值。 | ### JsRun(同步) 给定一个页面端函数: ```js function multiplyTheseNumbers(a, b) { return a * b; } ``` BASIC可以调用它并在同一行读取结果: ```vb Dim product As Long = WebView.JsRun("multiplyTheseNumbers", 5, 6) Debug.Print product ' 30 ``` 调用会阻塞BASIC线程,直到渲染器进程回复。 ::: warning 如果JavaScript函数在调用期间回调到BASIC——例如通过 `window.chrome.webview.postMessage(...)`——结果是死锁。仅对纯函数使用[**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun);不符合此条件时改用[**JsRunAsync**](/official/Reference/CEF/CefBrowser/#jsrunasync)。完整讨论参见[重入性教程](/official/Tutorials/CEF/Re-entrancy)。 ::: ### JsRunAsync(异步) ```vb Private Sub btnRun_Click() Handles btnRun.Click WebView.JsRunAsync "multiplyTheseNumbers", 5, 6 End Sub Private Sub WebView_JsAsyncResult( _ ByVal Result As Variant, Token As LongLong, ErrString As String) _ Handles WebView.JsAsyncResult If LenB(ErrString) = 0 Then Debug.Print "Async result: "; Result Else Debug.Print "Async error: "; ErrString End If End Sub ``` [**JsAsyncResult**](/official/Reference/CEF/CefBrowser/#jsasyncresult)事件包含*Token*参数,因此单个处理程序可以解复用多个进行中的调用。成功时*ErrString*为空。 在渲染器IPC连接之前进行的调用会排队并在连接建立后分发。 ### ExecuteScript(即发即弃) ```vb WebView.ExecuteScript "startTimer()" ``` 无返回值,无事件。推动页面执行某些操作的最简单方式。 ## 重入性 关于从BASIC调用同步JavaScript何时安全——以及不安全时该怎么做——的讨论在其自己的教程中。简短概述: * **纯JS**(输入→输出,无涉及宿主的副作用):[**JsRun**](/official/Reference/CEF/CefBrowser/#jsrun)可行。 * **可能回发消息、等待宿主对象或以其他方式重入BASIC的JS**:使用[**JsRunAsync**](/official/Reference/CEF/CefBrowser/#jsrunasync)。 完整图景参见[重入性教程](/official/Tutorials/CEF/Re-entrancy)。 ## 下一步 * [托管本地Web资源](/official/Tutorials/CEF/Hosting-local-web-assets) —— 打包并提供与宿主通信的JavaScript。 * [从twinBASIC驱动Monaco](/official/Tutorials/CEF/Driving-Monaco) —— 使用两座桥的完整案例研究。 * [重入性](/official/Tutorials/CEF/Re-entrancy) —— 同步与异步调用背后的深入故事。 * [CefBrowser参考](/official/Reference/CEF/CefBrowser/) —— 每个属性、方法和事件。 --- --- url: /zh/official/Tutorials/WebView2/JavaScript-interop.md --- # JavaScript互操作 [**WebView2**](/official/Reference/WebView2/WebView2/)控件在twinBASIC和页面中运行的JavaScript之间提供三座互补的桥: 1. **宿主对象** —— 将BASIC COM对象发布到页面,使JavaScript可以像调用任何其他JS对象一样调用其方法和读取其属性。 2. **消息** —— 在两个方向推送值(字符串、数字、数组……)并在另一侧监听。 3. **脚本调用** —— 从BASIC调用命名的JavaScript函数,并(可选)等待其返回值。 本教程涵盖所有三种,每个BASIC端旁边显示匹配的JavaScript端。工作代码来自*示例0——WebView2示例*(窗体*示例2*)。 ## 桥1——宿主对象 [**AddObject**](/official/Reference/WebView2/WebView2/#addobject)将BASIC类实例发布到 `chrome.webview.hostObjects.<Name>`。定义一个带有公共方法或属性的小类: ```vb Class MyCalculator Public Function MultiplyByTen(ByVal Value As Long) As Long Return Value * 10 End Function End Class ``` 控件就绪后注册它: ```vb Private Sub WebView_Ready() Handles WebView.Ready WebView.AddObject "myCalculator", New MyCalculator End Sub ``` JavaScript现在可以调用它——但代理是异步的,因此调用必须在 `async` 函数内 `await`: ```js async function testHostCalculator() { let value = Math.floor(Math.random() * 100000); let result = await chrome.webview.hostObjects.myCalculator.MultiplyByTen(value); alert(`BASIC said ${value} × 10 = ${result}`); } ``` 要从BASIC触发JS函数,调用[**ExecuteScript**](/official/Reference/WebView2/WebView2/#executescript): ```vb Private Sub btnTest_Click() Handles btnTest.Click WebView.ExecuteScript("testHostCalculator()") End Sub ``` 需要[**AreHostObjectsAllowed**](/official/Reference/WebView2/WebView2/#arehostobjectsallowed)(默认**True**)。参见[重入性](/official/Tutorials/WebView2/Re-entrancy)了解同步调用(默认)和**UseDeferredInvoke:=True**变体之间的权衡。 ## 桥2——消息 消息是在两个方向传递的值。当你不希望提前定义方法签名时,用于通知和临时数据负载。 ### BASIC → 页面 [**PostWebMessage**](/official/Reference/WebView2/WebView2/#postwebmessage)向页面发送值;页面通过 `window.chrome.webview` 上的 `message` 事件接收它: ```vb WebView.PostWebMessage "Hello from twinBASIC!" ``` ```js window.chrome.webview.addEventListener('message', (e) => { alert("Host sent: " + e.data); }); ``` 字符串以JavaScript字符串到达;其他所有类型在传输前进行JSON编码。如果你已经有序列化的JSON,[**PostWebMessageJSON**](/official/Reference/WebView2/WebView2/#postwebmessagejson)会原样发送。 ### 页面 → BASIC 页面调用 `window.chrome.webview.postMessage(value)`;BASIC通过[**JsMessage**](/official/Reference/WebView2/WebView2/#jsmessage)事件接收它: ```js function sendHostAMessage() { window.chrome.webview.postMessage("This is a message from JavaScript."); } ``` ```vb Private Sub WebView_JsMessage(ByVal Message As Variant) _ Handles WebView.JsMessage Debug.Print "Page sent: "; Message End Sub ``` 两个方向都需要[**IsWebMessageEnabled**](/official/Reference/WebView2/WebView2/#iswebmessageenabled)(默认**True**)。 ## 桥3——脚本调用 当页面暴露命名的JS函数时,BASIC可以直接调用它们。有三种变体: | 方法 | 返回值 | 使用场景 | |-----------------------------------------------------------------------------------|--------------------------------------------------|-------------------------------------------------------------------| | [**JsRun**](/official/Reference/WebView2/WebView2/#jsrun) | **Variant**,同步 | 你需要内联结果且JS很快。 | | [**JsRunAsync**](/official/Reference/WebView2/WebView2/#jsrunasync) | **LongLong**令牌;结果通过 `JsAsyncResult` | JS可能需要一段时间,你不想阻塞UI。 | | [**ExecuteScript**](/official/Reference/WebView2/WebView2/#executescript) | 无(即发即弃) | 你只想触发某些操作——不需要返回值。 | ### JsRun(同步) 给定一个页面端函数: ```js function multiplyTheseNumbers(a, b) { return a * b; } ``` BASIC可以调用它并在同一行读取结果: ```vb Dim product As Long = WebView.JsRun("multiplyTheseNumbers", 5, 6) Debug.Print product ' 30 ``` 调用最多阻塞[**JsCallTimeOutSeconds**](/official/Reference/WebView2/WebView2/#jscalltimeoutseconds)(默认0——永远等待)。 ### JsRunAsync(异步) ```vb Private Sub btnRun_Click() Handles btnRun.Click WebView.JsRunAsync "multiplyTheseNumbers", 5, 6 End Sub Private Sub WebView_JsAsyncResult( _ ByVal Result As Variant, Token As LongLong, ErrString As String) _ Handles WebView.JsAsyncResult If LenB(ErrString) = 0 Then Debug.Print "Async result: "; Result Else Debug.Print "Async error: "; ErrString End If End Sub ``` [**JsRunAsync**](/official/Reference/WebView2/WebView2/#jsrunasync)的返回值是一个令牌;[**JsAsyncResult**](/official/Reference/WebView2/WebView2/#jsasyncresult)事件包含相同的令牌,因此单个处理程序可以解复用多个进行中的调用。 ### ExecuteScript(即发即弃) ```vb WebView.ExecuteScript "startTimer()" ``` 无返回值,无事件。推动页面执行某些操作的最简单方式。 ## 重入性 Edge运行时禁止宿主代码在宿主对象方法仍在执行时回调WebView2对象模型——重入会使浏览器进程死锁。控件通过BASIC消息循环延迟大多数事件来保护它们([**UseDeferredEvents**](/official/Reference/WebView2/WebView2/#usedeferredevents)),但宿主对象方法调用默认是同步的。 完整讨论在[重入性教程](/official/Tutorials/WebView2/Re-entrancy)中;简短概述: * **`AddObject(name, obj)`** —— 同步调用;页面可以读取返回值,但BASIC方法**绝不能**回调WebView2控件。 * **`AddObject(name, obj, UseDeferredInvoke:=True)`** —— 异步调用;BASIC方法可以自由调用任何WebView2成员,但页面无法读取返回值。 ## 下一步 * [托管本地Web资源](/official/Tutorials/WebView2/Hosting-local-web-assets) —— 打包并提供与宿主通信的JavaScript。 * [从twinBASIC驱动Monaco](/official/Tutorials/WebView2/Driving-Monaco) —— 使用所有三座桥的完整案例研究。 * [重入性](/official/Tutorials/WebView2/Re-entrancy) —— **UseDeferredInvoke**背后的深入故事。 * [WebView2参考](/official/Reference/WebView2/WebView2/) —— 每个属性、方法和事件。 --- --- url: /en/official/Reference/VBA/Strings/Join.md --- # Join Returns a string created by joining a number of substrings contained in an array. Syntax: **Join(** *sourcearray* \[ **,** *delimiter* ] **)** *sourcearray* : *required* One-dimensional array containing substrings to be joined. *delimiter* : *optional* String character used to separate the substrings in the returned string. If omitted, the space character (`" "`) is used. If *delimiter* is a zero-length string (`""`), all items in the list are concatenated with no delimiters. ### Example This example uses **Join** to concatenate an array of strings with a delimiter. ```vb Debug.Print Join(Array("one", "two", "three"), ", ") ' "one, two, three" Debug.Print Join(Array("a", "b", "c"), "-") ' "a-b-c" Debug.Print Join(Array("x", "y"), "") ' "xy" ``` ### See Also * [Filter](/en/official/Reference/VBA/Strings/Filter), [Split](/en/official/Reference/VBA/Strings/Split) functions --- --- url: /zh/official/Reference/VBA/Strings/Join.md --- # Join 返回一个通过连接数组中包含的多个子字符串而创建的字符串。 语法:**Join(** *sourcearray* \[ **,** *delimiter* ] **)** *sourcearray* : *必需* 包含要连接的子字符串的一维数组。 *delimiter* : *可选* 用于分隔返回字符串中子字符串的字符串字符。如果省略,则使用空格字符(`" "`)。如果*delimiter*为零长度字符串(`""`),则列表中的所有项不带分隔符连接。 ### 示例 本示例使用**Join**用分隔符连接字符串数组。 ```vb Debug.Print Join(Array("one", "two", "three"), ", ") ' "one, two, three" Debug.Print Join(Array("a", "b", "c"), "-") ' "a-b-c" Debug.Print Join(Array("x", "y"), "") ' "xy" ``` ### 另请参阅 * [Filter](/official/Reference/VBA/Strings/Filter)、[Split](/official/Reference/VBA/Strings/Split)函数 --- --- url: /zh/challenge/2026/202602.md --- # Jump Jump 游戏说明文档 作者:邓伟 邮箱:215879458@qq.com 网站:https://vb6.pro 群号:788160802 ## 1. 游戏概述 **Jump Jump** 是一款采用等距视角(Isometric View)的3D跳跃平台游戏。玩家需要控制角色在不同的平台之间跳跃,考验玩家的蓄力时机判断和空间感知能力。 ![示例截图](/challenges/202602/demo.png) ### 1.1 游戏特色 * **等距3D视角**:采用伪3D渲染技术,提供清晰的空间感 * **蓄力跳跃机制**:按住空格键蓄力,松开跳跃,蓄力时间决定跳跃距离 * **精确落点判定**:根据落点位置判定Perfect/Good/Normal/Miss四种质量 * **连击系统**:连续Perfect可获得Combo加成,大幅提升得分 * **动态平台生成**:平台随机生成,每次游戏体验都不相同 * **粒子特效**:跳跃和着陆时有丰富的粒子效果反馈 * **音效系统**:完整的跳跃、蓄力、着陆、完美等音效 *** ## 2. 游戏操作 ### 2.1 基本控制 | 按键 | 功能 | 说明 | | ---------- | ------------- | -------------------------------------- | | **空格键** | 蓄力/跳跃 | 按住开始蓄力,松开执行跳跃 | | **回车键** | 开始/重新开始 | 在菜单界面开始游戏,游戏结束时重新开始 | | **ESC键** | 返回菜单/退出 | 游戏中返回菜单,菜单界面退出游戏 | ### 2.2 跳跃机制 1. **蓄力阶段**:按住空格键,角色会开始蓄力 * 蓄力时间:0-2秒 * 蓄力期间角色会有压扁变形的视觉效果 * 角色上方会显示蓄力条(绿色→红色渐变) 2. **跳跃阶段**:松开空格键,角色朝当前面向方向跳跃 * 蓄力越久,跳跃距离越远(150-400单位) * 角色自动朝向下一个平台 3. **着陆判定**:角色落下时,系统会判断落点位置 * **Perfect**:落点距离平台中心 < 5% * **Good**:落点距离平台中心 5%-15% * **Normal**:落点距离平台中心 15%-100% * **Miss**:未落在平台上,直接Game Over *** ## 3. 游戏玩法 ### 3.1 游戏流程 ``` 主菜单 ↓ 按回车开始 ↓ 游戏进行中 ├─ 蓄力跳跃 ├─ 平台间移动 └─ 累计分数 ↓ 成功着陆 → 生成新平台 → 继续游戏 ↓ 未着陆 → 掉落 → Game Over ↓ 按回车重新开始 ``` ### 3.2 得分规则 #### 3.2.1 落点基础分 | 落点质量 | 基础分数 | 判定条件 | | -------- | -------- | ----------------- | | Perfect | 4分 | 距离中心 < 5% | | Good | 2分 | 距离中心 5%-15% | | Normal | 1分 | 距离中心 15%-100% | | Miss | 0分 | 未着陆,游戏结束 | #### 3.2.2 Combo加成 连续Perfect可获得Combo加成: | 连击数 | 加成倍率 | | ------------ | -------- | | 1-2次Perfect | 1.0x | | 2次Perfect | 1.5x | | 3次Perfect | 2.0x | | 4次及以上 | 2.5x | **注意**:任何非Perfect的着陆都会重置Combo计数。 #### 3.2.3 得分示例 * 1次Perfect:4分 * 2次Perfect:4 + 4×1.5 = 10分 * 3次Perfect:4 + 4×1.5 + 4×2.0 = 18分 * 4次Perfect:4 + 4×1.5 + 4×2.0 + 4×2.5 = 28分 * Good着陆:2分(Combo重置) * Normal着陆:1分(Combo重置) ### 3.3 平台生成规则 1. **初始平台**:游戏开始时生成2个平台 * 第一个平台位置:(0, 0, 50) * 第二个平台位置随机生成 2. **后续平台**:每次成功着陆后生成新平台 * 新平台与当前平台的距离:150-400(随机) * 生成方向:随机选择X轴或Y轴(确保始终"向前"移动) * 平台尺寸:100×100(可扩展) 3. **平台结构**: * 平台高度:50单位 * 平台宽度:100单位 * 平台深度:100单位 *** ## 4. 游戏界面 ### 4.1 主菜单 * **标题**:"JUMP JUMP"(蓝色大字,居中显示) * **提示**:"Press Enter to Start"(青色文字,居中显示) ### 4.2 游戏界面 #### 4.2.1 HUD显示 * **左上角**: * Score:当前分数(白色) * Best:最高分(白色) * **中央**: * Combo提示(仅当Combo>1时显示) * 格式:"xN combo"(金色) * 位置:屏幕上方中央 * **角色上方**: * 蓄力条(蓄力时显示) * 长度:50×10像素 * 颜色:绿色→红色渐变(随蓄力程度变化) #### 4.2.2 游戏画面 * **背景**:天蓝色渐变(SkyBlue → DeepSkyBlue) * **平台**:米黄色(Wheat)+ 顶部淡黄色(Moccasin) * **角色**:黑色"i"形角色(圆柱身体+球形头部),带有渐变光泽 * **阴影**:半透明黑色圆形,随高度缩放 * **动画效果**:蓄力时角色压扁变形(高度压缩30%,宽度膨胀),跳跃时恢复 ### 4.3 Game Over界面 * **标题**:"GAME OVER"(红色大字,居中显示) * **提示**:"Press Enter to Restart"(白色文字,居中显示) * 保留分数和最高分显示 *** ## 5. 技术实现 ### 5.1 开发环境 * **语言**:TwinBasic * **图形库**:GDI+ (GdiPlusUser) * **分辨率**:800×600像素 * **帧率**:80 FPS(12.5ms刷新间隔) ### 5.2 核心架构 ``` MyForm (主窗体) ↓ cGame (游戏主控制器) ├─ cPlayer (玩家角色) ├─ cPlatform (平台) ├─ cPlatformGenerator (平台生成器) ├─ cCamera (摄像机) ├─ cRenderer (渲染器) ├─ cInput (输入管理) ├─ cAudio (音频系统) ├─ cPhysics (物理系统) ├─ cScoreManager (计分系统) └─ cParticleSystem (粒子系统) ``` ### 5.3 核心类说明 #### cGame * 游戏主控制器,管理游戏状态和所有子系统 * 状态:Menu → Playing → Charging → Jumping → Falling → Game Over * 负责游戏循环、碰撞检测、着陆判定 #### cPlayer * 玩家角色类 * 属性:位置、速度、朝向、状态、蓄力力度 * 外观:黑色"i"形设计(圆柱身体+球形头部),带渐变高光 * 动画:蓄力时压扁变形(高度压缩、宽度膨胀),跳跃时恢复 * 动作:蓄力、跳跃、着陆、下落 #### cPlatform * 平台类 * 属性:位置、尺寸、激活状态 * 方法:点包含检测、落点质量判定 #### cPlatformGenerator * 平台生成器 * 负责生成初始平台和后续平台 * 随机生成距离和方向 #### cCamera * 摄像机类 * 实现等距视角的坐标转换 * WorldToScreen:3D世界坐标 → 2D屏幕坐标 #### cRenderer * 渲染器 * 使用GDI+绘制所有游戏元素 * 支持渐变背景、圆角矩形、椭圆等图形 #### cPhysics * 物理系统 * 计算跳跃初速度(基于蓄力比例) * 更新位置和速度(应用重力) * 落地碰撞检测 #### cScoreManager * 计分管理器 * 处理着陆得分 * 维护Combo计数和最高分记录 #### cInput * 输入管理器 * 使用Win32 API(GetAsyncKeyState)检测按键 * 支持空格、回车、ESC键 #### cAudio * 音频系统 * 使用WinMM API(PlaySound)播放音效 * 加载的音效:Jump、Land、ChargeStart、ChargeLoop、Perfect、GameOver #### cParticleSystem * 粒子系统 * 生成着陆时的爆炸效果 * Perfect:金色粒子 * Normal:灰色尘埃粒子 ### 5.4 技术亮点 #### 图形渲染 * **GDI+ 等距3D渲染** - 完整伪3D等距投影,使用正确的世界坐标到屏幕坐标转换 * **自定义3D平台渲染** - 使用 GDI+ 多边形绘制具有3个可见面(顶面、左面、右面)的菱形平台 * **动态阴影系统** - 基于角色高度实时缩放阴影,带透明效果 * **渐变渲染** - 天空渐变背景(天蓝→深天蓝),角色渐变画笔实现3D外观 * **双缓冲技术** - 流畅80 FPS渲染,无闪烁 #### 物理与碰撞检测 * **基于物理的轨迹计算** - 使用抛体运动物理公式计算跳跃速度:`v_z = sqrt(2 * g * h)` 计算垂直速度,时间控制水平速度 * **高级碰撞检测** - 菱形碰撞边界匹配等距视觉表现,使用公式:`|x|/(w*0.5) + |y|/(d*0.25) <= 1` * **多层次着陆质量检测** - 在菱形坐标系中精确计算与平台中心距离,判定 Perfect(<5%)、Good(5-15%)、Normal(15-100%)、Miss(>100%) * **重力模拟** - 跳跃期间恒定重力应用,速度更新真实 #### 视觉特效与动画 * **粒子系统** - 自定义粒子引擎,支持100+粒子容量,重力物理和生命周期管理 * Perfect 着陆金色爆炸粒子(20个,RGB: 255, 215, 0) * Normal/Good 着陆白色尘埃粒子(10个,RGB: 255, 255, 255) * 基于生命值粒子渐隐,带透明混合 * **挤压拉伸动画** - 角色蓄力时变形(高度压缩,宽度膨胀达30%) * **蓄力条可视化** - 实时蓄力指示器,绿→红渐变色过渡 * **动态相机** - 使用线性插值(Lerp)平滑相机跟随,跟随速度0.1 #### 现代 twinBASIC 特性 * **强类型** - 全程使用 `As` 语法完整类型声明 * **Return 关键字** - 现代函数返回语法(如 `Return velocity`) * **基于类的OOP** - 完整面向对象设计,封装良好 * **枚举类型** - 自定义枚举 GameState、PlayerState、LandingQuality * **UDT(用户定义类型)** - Vector3、Vector2、ColorRGBA、Particle 结构 * **安全数组处理** - 使用 `(Not Not array) <> 0` 模式进行安全数组边界检查 #### 性能优化 * **80 FPS 高性能渲染** - 使用 Timer 控件12.5ms刷新间隔 * **高效粒子渲染** - 画笔复用优化,仅颜色变化时创建新画笔 * **动态数组管理** - 粒子系统动态容量倍增(100 → 200 → 400...) * **提前退出优化** - 渲染管道全程空值检查和边界检查 ### 5.5 游戏常量 ```vb ' 跳跃距离 MIN_JUMP_DISTANCE = 150.0 MAX_JUMP_DISTANCE = 400.0 ' 物理参数 GRAVITY = 0.5 MAX_CHARGE_TIME = 2.0 ' 平台参数 PLATFORM_BASE_SIZE = 100.0 PLATFORM_HEIGHT = 50.0 ' 屏幕参数 SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 ' 摄像机偏移 CAMERA_OFFSET_X = 0.0 CAMERA_OFFSET_Y = -100.0 ``` *** ## 6. 游戏资源 ### 6.1 音频文件 游戏包含以下音效文件(位于 `resources/AUDIO/` 目录): | 文件名 | 用途 | 触发时机 | | ------------ | ------------ | ------------------ | | CHARGE\_START | 蓄力开始音效 | 按下空格键开始蓄力 | | CHARGE\_LOOP | 蓄力循环音效 | 蓄力过程中持续播放 | | JUMP | 跳跃音效 | 松开空格键跳跃时 | | LAND | 普通着陆音效 | Normal/Good着陆时 | | PERFECT | 完美着陆音效 | Perfect着陆时 | | GAMEOVER | 游戏结束音效 | 掉落或错过平台时 | ### 6.2 图标文件 * 游戏图标:`resources/icon/twinbasic.ico` *** ## 7. 游戏技巧 ### 7.1 基础技巧 1. **观察平台距离**:新平台生成后,观察与当前平台的距离 * 较近的平台:蓄力时间短(约0.5-1秒) * 较远的平台:蓄力时间长(约1.5-2秒) 2. **利用蓄力条**:观察角色上方的蓄力条颜色 * 绿色:蓄力程度较低(短跳) * 黄色:蓄力程度中等(中跳) * 红色:蓄力程度较高(长跳) 3. **角色朝向**:角色会自动朝向下一个平台,无需手动调整 ### 7.2 进阶技巧 1. **追求Perfect**: * Perfect可以连击,大幅提升得分 * 尝试在平台正中心着陆 * Perfect会有金色粒子特效和特殊音效 2. **Combo管理**: * 4次Perfect及以上有2.5倍加成 * 如果判断无法Perfect,可以选择Good而不是Miss * Combo重置后,可以重新开始积累 3. **节奏控制**: * 不要急于跳跃,先观察新平台位置 * 保持稳定的节奏,避免连续失误 * 蓄力时不要超过2秒,会自动限制在最大值 4. **空间感知**: * 熟悉跳跃轨迹和落点位置的关系 * 练习后可以更准确地判断蓄力时间 *** ## 8. 常见问题 ### Q1:为什么我总是跳不到平台上? **A**:可能的原因: * 蓄力时间不准确:尝试根据平台距离调整蓄力时间 * 蓄力不足或过度:观察蓄力条颜色,绿→红代表蓄力程度 * 平台太远:游戏会随机生成150-400距离的平台,部分平台可能较难 ### Q2:如何获得高分数? **A**: * 追求Perfect着陆,积累Combo * 4次及以上Perfect有2.5倍加成,能快速提升分数 * 保持冷静,不要为了Perfect而冒险导致Miss * 练习后可以更准确判断蓄力时间 ### Q3:Combo什么时候会重置? **A**: * 任何非Perfect的着陆(Good/Normal)都会重置Combo * Miss(未着陆)直接Game Over,Combo也会重置 ### Q4:游戏有最高分数限制吗? **A**: * 理论上没有,只要能持续成功着陆就可以无限玩下去 * 但随着平台距离随机变化,难度会逐渐增加 ### Q5:为什么有时候角色会直接下落? **A**: * 角色在跳跃过程中,如果没有落到平台上,会继续下落 * 当Z坐标小于-500时,判定为Game Over * 这是因为错过了平台或蓄力过度 *** ## 9. 版本信息 * **游戏名称**:Jump Jump * **版本**:1.0 * **开发语言**:VB6 / TwinBasic * **开发时间**:2026年 * **游戏类型**:等距3D跳跃平台游戏 *** ## 10. 未来改进方向 ### 10.1 游戏内容 * \[ ] 添加更多平台类型(移动平台、消失平台等) * \[ ] 引入障碍物和特殊道具 * \[ ] 添加更多视觉效果(天气、时间变化等) * \[ ] 增加关卡模式和挑战模式 ### 10.2 技术优化 * \[ ] 优化渲染性能 * \[ ] 支持更高分辨率 * \[ ] 添加存档功能(保存最高分到文件) * \[ ] 改进音效系统(支持循环、混音等) ### 10.3 用户体验 * \[ ] 添加操作教程 * \[ ] 提供设置选项(音量、难度等) * \[ ] 添加暂停功能 * \[ ] 支持手柄控制 *** ## 附录:源码文件结构 ``` src3/ ├── Sources/ │ ├── Core/ │ │ ├── cGame.twin # 游戏主控制器 │ │ ├── cPlayer.twin # 玩家角色 │ │ ├── cPlatform.twin # 平台 │ │ ├── cPlatformGenerator.twin # 平台生成器 │ │ ├── cCamera.twin # 摄像机 │ │ ├── cRenderer.twin # 渲染器 │ │ ├── cInput.twin # 输入管理 │ │ ├── cAudio.twin # 音频系统(WinMM PlaySound) │ │ ├── cPhysics.twin # 物理系统 │ │ ├── cScoreManager.twin # 计分系统 │ │ ├── cParticleSystem.twin # 粒子系统 │ │ ├── mTypes.twin # 类型定义和常量 │ │ └── mUtils.twin # 工具函数 │ ├── myform.twin # 主窗体 │ └── myform.tbform # 窗体设计器 ├── resources/ │ ├── AUDIO/ # 音频资源 │ │ ├── CHARGE_START │ │ ├── CHARGE_LOOP │ │ ├── GAMEOVER │ │ ├── JUMP │ │ ├── LAND │ │ └── PERFECT │ ├── icon/ # 图标资源 │ │ └── twinbasic.ico │ └── manifest/ # 清单文件 └── Readme_zh.md # 本文档 ``` *** **祝您游戏愉快!** 🎮 *** ## 视频演示 ## 示例下载(源码) [示例下载](/challenges/202602/Jump-v2.zip) --- --- url: /en/challenge/2026/202602.md --- # Jump Jump Game Documentation ## 1. Game Overview **Jump Jump** is a 3D jumping platform game featuring an isometric view. Players control a character to jump between different platforms, testing their timing judgment and spatial awareness. ![示例截图](/challenges/202602/demo.png) ### 1.1 Game Features * **Isometric 3D View**: Pseudo-3D rendering technology provides clear spatial awareness * **Charge-based Jumping Mechanism**: Hold space to charge, release to jump - charge time determines jump distance * **Precise Landing Detection**: Four landing quality levels based on landing position - Perfect/Good/Normal/Miss * **Combo System**: Consecutive Perfect landings earn combo bonuses, greatly increasing scores * **Dynamic Platform Generation**: Platforms are randomly generated, providing a unique experience each time * **Particle Effects**: Rich particle effects feedback during jumps and landings * **Audio System**: Complete sound effects for jumping, charging, landing, and perfect landings *** ## 2. Game Controls ### 2.1 Basic Controls | Key | Function | Description | | --------- | ---------------- | ------------------------------------------ | | **Space** | Charge/Jump | Hold to start charging, release to jump | | **Enter** | Start/Restart | Start game in menu, restart when game over | | **ESC** | Return Menu/Exit | Return to menu during game, exit from menu | ### 2.2 Jumping Mechanism 1. **Charging Phase**: Hold space bar to charge * Charge time: 0-2 seconds * Character has a squash deformation effect during charging * Charge bar displays above character (green to red gradient) 2. **Jumping Phase**: Release space bar to jump toward current facing direction * Longer charge = farther jump distance (150-400 units) * Character automatically faces the next platform 3. **Landing Detection**: System judges landing position when character lands * **Perfect**: Landing point < 5% from platform center * **Good**: Landing point 5%-15% from platform center * **Normal**: Landing point 15%-100% from platform center * **Miss**: Failed to land on platform, immediate Game Over *** ## 3. Gameplay ### 3.1 Game Flow ``` Main Menu ↓ Press Enter to Start ↓ Game In Progress ├─ Charge and Jump ├─ Move Between Platforms └─ Accumulate Score ↓ Successful Landing → Generate New Platform → Continue ↓ Failed Landing → Fall → Game Over ↓ Press Enter to Restart ``` ### 3.2 Scoring Rules #### 3.2.1 Landing Base Points | Landing Quality | Base Score | Criteria | | --------------- | ---------- | ----------------------------- | | Perfect | 4 points | Distance from center < 5% | | Good | 2 points | Distance from center 5%-15% | | Normal | 1 point | Distance from center 15%-100% | | Miss | 0 points | Failed to land, game over | #### 3.2.2 Combo Multiplier Consecutive Perfect landings earn combo bonuses: | Combo Count | Multiplier | | ----------- | ---------- | | 1-2 Perfect | 1.0x | | 2 Perfect | 1.5x | | 3 Perfect | 2.0x | | 4+ Perfect | 2.5x | **Note**: Any non-Perfect landing resets the combo counter. #### 3.2.3 Scoring Examples * 1 Perfect: 4 points * 2 Perfect: 4 + 4×1.5 = 10 points * 3 Perfect: 4 + 4×1.5 + 4×2.0 = 18 points * 4 Perfect: 4 + 4×1.5 + 4×2.0 + 4×2.5 = 28 points * Good landing: 2 points (combo resets) * Normal landing: 1 point (combo resets) ### 3.3 Platform Generation Rules 1. **Initial Platforms**: 2 platforms generated at game start * First platform position: (0, 0, 50) * Second platform position randomly generated 2. **Subsequent Platforms**: New platform generated after each successful landing * Distance from current platform: 150-400 (random) * Generation direction: Randomly choose X or Y axis (always move "forward") * Platform size: 100×100 (extensible) 3. **Platform Structure**: * Platform height: 50 units * Platform width: 100 units * Platform depth: 100 units *** ## 4. Game Interface ### 4.1 Main Menu * **Title**: "JUMP JUMP" (blue large text, centered) * **Prompt**: "Press Enter to Start" (cyan text, centered) ### 4.2 Game Interface #### 4.2.1 HUD Display * **Top Left**: * Score: Current score (white) * Best: Best score (white) * **Center**: * Combo indicator (only displayed when Combo > 1) * Format: "xN combo" (gold color) * Position: Upper center of screen * **Above Character**: * Charge bar (displayed during charging) * Size: 50×10 pixels * Color: Green to red gradient (changes with charge level) #### 4.2.2 Game Screen * **Background**: Sky blue gradient (SkyBlue → DeepSkyBlue) * **Platform**: Wheat color + Moccasin color top surface * **Character**: Black "i" shaped character (cylindrical body + spherical head) with gradient highlighting * **Shadow**: Semi-transparent black circle, scales with height * **Animation Effects**: Squash and stretch during charging (height compresses, width expands), recovery on jump ### 4.3 Game Over Screen * **Title**: "GAME OVER" (red large text, centered) * **Prompt**: "Press Enter to Restart" (white text, centered) * Score and best score remain displayed *** ## 5. Technical Implementation ### 5.1 Development Environment * **Language**: TwinBasic * **Graphics Library**: GDI+ (GdiPlusUser) * **Resolution**: 800×600 pixels * **Frame Rate**: 80 FPS (12.5ms refresh interval) ### 5.2 Core Architecture ``` MyForm (Main Form) ↓ cGame (Game Controller) ├─ cPlayer (Player Character) ├─ cPlatform (Platform) ├─ cPlatformGenerator (Platform Generator) ├─ cCamera (Camera) ├─ cRenderer (Renderer) ├─ cInput (Input Manager) ├─ cAudio (Audio System) ├─ cPhysics (Physics System) ├─ cScoreManager (Score Manager) └─ cParticleSystem (Particle System) ``` ### 5.3 Core Classes #### cGame * Game main controller, manages game state and all subsystems * States: Menu → Playing → Charging → Jumping → Falling → Game Over * Handles game loop, collision detection, landing judgment #### cPlayer * Player character class * Properties: Position, velocity, facing direction, state, charge power * Appearance: Black "i" shaped design (cylindrical body + spherical head) with gradient highlighting * Animation: Squash deformation during charging (height compresses, width expands), recovery on jump * Actions: Charge, jump, land, fall #### cPlatform * Platform class * Properties: Position, dimensions, active state * Methods: Point containment detection, landing quality judgment #### cPlatformGenerator * Platform generator * Generates initial and subsequent platforms * Randomly generates distance and direction #### cCamera * Camera class * Implements isometric view coordinate conversion * WorldToScreen: 3D world coordinates → 2D screen coordinates #### cRenderer * Renderer * Uses GDI+ to draw all game elements * Supports gradient backgrounds, rounded rectangles, ellipses, etc. #### cPhysics * Physics system * Calculates jump initial velocity (based on charge ratio) * Updates position and velocity (applies gravity) * Landing collision detection #### cScoreManager * Score manager * Handles landing scoring * Maintains combo counter and best score record #### cInput * Input manager * Uses Win32 API (GetAsyncKeyState) for key detection * Supports Space, Enter, and ESC keys #### cAudio * Audio system * Uses WinMM API (PlaySound) to play sound effects * Loaded sounds: Jump, Land, ChargeStart, ChargeLoop, Perfect, GameOver #### cParticleSystem * Particle system * Generates explosion effects on landing * Perfect: Gold particles * Normal: Gray dust particles ### 5.4 Technical Highlights #### Graphics & Rendering * **Isometric 3D rendering using GDI+ graphics library** - Full pseudo-3D isometric projection with proper world-to-screen coordinate transformation * **Custom 3D platform rendering** - Diamond-shaped platforms with 3 visible faces (top, left, right) drawn using GDI+ polygons * **Dynamic shadow system** - Real-time shadow scaling based on player height with transparency effects * **Gradient rendering** - Sky gradient background (SkyBlue → DeepSkyBlue), player gradient brushes for 3D appearance * **Double buffering** - Smooth 80 FPS rendering without flickering #### Physics & Collision Detection * **Physics-based trajectory calculation** - Calculates jump velocity using projectile motion physics: `v_z = sqrt(2 * g * h)` for vertical velocity and time-based horizontal speed * **Advanced collision detection** - Diamond-shaped collision bounds that match the isometric visual representation using the formula: `|x|/(w*0.5) + |y|/(d*0.25) <= 1` * **Multi-tiered landing quality detection** - Precise distance calculation from platform center in diamond coordinates for Perfect (<5%), Good (5-15%), Normal (15-100%), Miss (>100%) * **Gravity simulation** - Constant gravity application during jumps with realistic velocity updates #### Visual Effects & Animation * **Particle system** - Custom particle engine with 100+ particle capacity, gravity physics, and lifecycle management * Gold explosion particles for Perfect landings (20 particles, RGB: 255, 215, 0) * White dust particles for Normal/Good landings (10 particles, RGB: 255, 255, 255) * Particle fading based on life value with alpha blending * **Squash and stretch animation** - Character deforms during charging (height compresses, width expands up to 30%) * **Charge bar visualization** - Real-time charge indicator with green→red gradient color transition * **Dynamic camera** - Smooth camera follow using linear interpolation (Lerp) with 0.1 follow speed #### Modern twinBASIC Features * **Strong typing** - Full type declarations with `As` syntax throughout * **Return keyword** - Modern function return syntax (e.g., `Return velocity`) * **Class-based OOP** - Full object-oriented design with encapsulation * **Enum types** - Custom enums for GameState, PlayerState, LandingQuality * **UDTs (User Defined Types)** - Vector3, Vector2, ColorRGBA, Particle structures * **Safe array handling** - Uses `(Not Not array) <> 0` pattern for safe array bounds checking #### Performance Optimizations * **High-performance rendering at 80 FPS** - 12.5ms refresh interval using Timer control * **Efficient particle rendering** - Brush reuse optimization, only creating new brushes when color changes * **Dynamic array management** - Particle system uses dynamic capacity doubling (100 → 200 → 400...) * **Early exit optimizations** - Null checks and bounds checking throughout rendering pipeline ### 5.5 Game Constants ```vb ' Jump distance MIN_JUMP_DISTANCE = 150.0 MAX_JUMP_DISTANCE = 400.0 ' Physics parameters GRAVITY = 0.5 MAX_CHARGE_TIME = 2.0 ' Platform parameters PLATFORM_BASE_SIZE = 100.0 PLATFORM_HEIGHT = 50.0 ' Screen parameters SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 ' Camera offset CAMERA_OFFSET_X = 0.0 CAMERA_OFFSET_Y = -100.0 ``` *** ## 6. Game Resources ### 6.1 Audio Files The game includes the following sound effect files (located in `resources/AUDIO/` directory): | Filename | Purpose | Trigger | | ------------ | --------------------- | ---------------------------------- | | CHARGE\_START | Charging start sound | Press space to start charging | | CHARGE\_LOOP | Charging loop sound | Continuously plays during charging | | JUMP | Jump sound | Release space to jump | | LAND | Normal landing sound | Normal/Good landing | | PERFECT | Perfect landing sound | Perfect landing | | GAMEOVER | Game over sound | Fall or miss platform | ### 6.2 Icon Files * Game icon: `resources/icon/twinbasic.ico` *** ## 7. Game Tips ### 7.1 Basic Tips 1. **Observe Platform Distance**: After a new platform generates, observe its distance from the current platform * Closer platforms: Short charge time (~0.5-1 second) * Farther platforms: Long charge time (~1.5-2 seconds) 2. **Use Charge Bar**: Watch the charge bar color above the character * Green: Low charge level (short jump) * Yellow: Medium charge level (medium jump) * Red: High charge level (long jump) 3. **Character Facing**: Character automatically faces the next platform, no manual adjustment needed ### 7.2 Advanced Tips 1. **Aim for Perfect**: * Perfect landings can combo, greatly increasing score * Try to land in the exact center of the platform * Perfect landings have gold particle effects and special sound effects 2. **Combo Management**: * 4 or more Perfect landings have a 2.5x multiplier * If you can't achieve Perfect, choose Good over Miss * After combo resets, you can start building again 3. **Rhythm Control**: * Don't rush to jump, first observe the new platform position * Maintain a steady rhythm, avoid consecutive mistakes * Don't charge more than 2 seconds, it will automatically limit to maximum 4. **Spatial Awareness**: * Familiarize yourself with the relationship between jump trajectory and landing position * With practice, you can more accurately judge charge time *** ## 8. FAQ ### Q1: Why can't I seem to land on platforms? **A**: Possible reasons: * Inaccurate charge time: Try adjusting charge time based on platform distance * Insufficient or excessive charge: Watch the charge bar color, green→red represents charge level * Platform too far: Game randomly generates platforms at 150-400 distance, some may be harder ### Q2: How can I get a high score? **A**: * Aim for Perfect landings, build up combos * 4 or more Perfect landings have 2.5x multiplier, quickly increasing score * Stay calm, don't risk Miss for Perfect * With practice, you can more accurately judge charge time ### Q3: When does Combo reset? **A**: * Any non-Perfect landing (Good/Normal) resets the combo * Miss (failed landing) results in immediate Game Over, combo also resets ### Q4: Is there a maximum score limit? **A**: * Theoretically no, as long as you can successfully land continuously, you can play indefinitely * However, as platform distances vary randomly, difficulty gradually increases ### Q5: Why does the character sometimes fall directly? **A**: * During jumping, if the character doesn't land on a platform, it will continue falling * When Z coordinate is less than -500, it's judged as Game Over * This is due to missing the platform or over-charging *** ## 9. Version Information * **Game Name**: Jump Jump * **Version**: 1.0 * **Development Language**: VB6 / TwinBasic * **Development Time**: 2026 * **Game Type**: Isometric 3D Jumping Platform Game *** ## 10. Future Improvements ### 10.1 Game Content * \[ ] Add more platform types (moving platforms, disappearing platforms, etc.) * \[ ] Introduce obstacles and special items * \[ ] Add more visual effects (weather, time changes, etc.) * \[ ] Add level mode and challenge mode ### 10.2 Technical Optimization * \[ ] Optimize rendering performance * \[ ] Support higher resolutions * \[ ] Add save functionality (save best score to file) * \[ ] Improve audio system (support looping, mixing, etc.) ### 10.3 User Experience * \[ ] Add tutorial * \[ ] Provide settings options (volume, difficulty, etc.) * \[ ] Add pause function * \[ ] Support gamepad control *** ## Appendix: Source Code File Structure ``` src3/ ├── Sources/ │ ├── Core/ │ │ ├── cGame.twin # Game Controller │ │ ├── cPlayer.twin # Player Character │ │ ├── cPlatform.twin # Platform │ │ ├── cPlatformGenerator.twin # Platform Generator │ │ ├── cCamera.twin # Camera │ │ ├── cRenderer.twin # Renderer │ │ ├── cInput.twin # Input Manager │ │ ├── cAudio.twin # Audio System (WinMM PlaySound) │ │ ├── cPhysics.twin # Physics System │ │ ├── cScoreManager.twin # Score Manager │ │ ├── cParticleSystem.twin # Particle System │ │ ├── mTypes.twin # Type Definitions and Constants │ │ └── mUtils.twin # Utility Functions │ ├── myform.twin # Main Form │ └── myform.tbform # Form Designer ├── resources/ │ ├── AUDIO/ # Audio Resources │ │ ├── CHARGE_START │ │ ├── CHARGE_LOOP │ │ ├── GAMEOVER │ │ ├── JUMP │ │ ├── LAND │ │ └── PERFECT │ ├── icon/ # Icon Resources │ │ └── twinbasic.ico │ └── manifest/ # Manifest Files ├── Readme_zh.md # Chinese Documentation └── README.md # This Document ``` *** **Enjoy the game!** 🎮 ## Video Demo ## Download (open source) [示例下载](/challenges/202602/Jump-v2.zip) --- --- url: /en/official/Reference/tbIDE/KeyboardShortcuts.md --- # KeyboardShortcuts class The IDE's keyboard-shortcut registry --- reached through [**Host.KeyboardShortcuts**](/en/official/Reference/tbIDE/Host#keyboardshortcuts). Call [**Add**](#add) to bind a key combination to a callback. There is no removal API; the registration is released when the addin is unloaded. ```vb Private Sub Host_OnProjectLoaded() Host.KeyboardShortcuts.Add "{CTRL}{SHIFT}d", AddressOf ToggleDebugMode End Sub Private Sub ToggleDebugMode() debugMode = Not debugMode Host.DebugConsole.PrintText "Debug mode " & If(debugMode, "ON", "OFF") End Sub ``` The shortcut is global to the IDE and fires regardless of which pane has focus, as long as the IDE itself has the OS-level focus. The callback runs on the IDE's UI thread. ## Methods ### Add Registers a new keyboard shortcut. Syntax: *keyboardShortcuts*.**Add** *keyString*, *Callback* *keyString* : *required* The key combination, as a **String**. The literal key character is preceded by zero or more modifier prefixes from the set `{CTRL}`, `{SHIFT}`, `{ALT}`. The prefixes are case-insensitive; the trailing key character matches the same key the user would press. | Example | Combination | |-----------------|---------------------------| | `"{CTRL}d"` | Ctrl + D | | `"{CTRL}{SHIFT}d"` | Ctrl + Shift + D | | `"{ALT}f"` | Alt + F | | `"f1"` | F1 (no modifier) | *Callback* : *required* The callback. Pass `AddressOf` a sub of signature `Sub()` (no arguments). **LongPtr**. The callback runs on the IDE's UI thread. Long-running work inside the callback will block the IDE until it returns --- keep the callback short and offload heavy work to a background mechanism when needed. --- --- url: /zh/official/Reference/tbIDE/KeyboardShortcuts.md --- # KeyboardShortcuts 类 IDE 的键盘快捷键注册表——通过 [**Host.KeyboardShortcuts**](/official/Reference/tbIDE/Host#keyboardshortcuts) 访问。调用 [**Add**](#add) 将组合键绑定到回调。没有移除 API;当插件卸载时注册被释放。 ```vb Private Sub Host_OnProjectLoaded() Host.KeyboardShortcuts.Add "{CTRL}{SHIFT}d", AddressOf ToggleDebugMode End Sub Private Sub ToggleDebugMode() debugMode = Not debugMode Host.DebugConsole.PrintText "Debug mode " & If(debugMode, "ON", "OFF") End Sub ``` 快捷键对 IDE 全局有效,只要 IDE 本身拥有操作系统级焦点,无论哪个窗格获得焦点都会触发。回调在 IDE 的 UI 线程上运行。 ## 方法 ### Add 注册新的键盘快捷键。 语法:*keyboardShortcuts*.**Add** *keyString*, *Callback* *keyString* : *必需* 组合键,为 **String**。字面键字符前有零个或多个来自 `{CTRL}`、`{SHIFT}`、`{ALT}` 集合的修饰符前缀。前缀不区分大小写;尾部键字符与用户按下的键相匹配。 | 示例 | 组合键 | |-----------------|---------------------------| | `"{CTRL}d"` | Ctrl + D | | `"{CTRL}{SHIFT}d"` | Ctrl + Shift + D | | `"{ALT}f"` | Alt + F | | `"f1"` | F1(无修饰符) | *Callback* : *必需* 回调。传入签名为 `Sub()`(无参数)的子过程的 `AddressOf`。**LongPtr**。 回调在 IDE 的 UI 线程上运行。回调中的长时间运行工作会阻塞 IDE 直到其返回——保持回调简短,需要时将繁重工作卸载到后台机制。 --- --- url: /en/official/Reference/VBRUN/Constants/KeyCodeConstants.md --- # KeyCodeConstants Virtual-key codes reported in the *KeyCode* argument of **KeyDown** and **KeyUp** events. The values match the underlying Windows virtual-key codes (`VK_*`). ::: info In classic VBA, `KeyCodeConstants` is a module of standalone constants; in VB6 and twinBASIC it is an enumeration. ::: ## Mouse buttons and modifiers | Constant | Value | Description | |----------|-------|-------------| | **vbKeyLButton** | 1 | Left mouse button. | | **vbKeyRButton** | 2 | Right mouse button. | | **vbKeyMButton** | 4 | Middle mouse button. | | **vbKeyShift** | 16 | **Shift**. | | **vbKeyControl** | 17 | **Ctrl**. | | **vbKeyMenu** | 18 | **Alt**. | ## Editing and navigation | Constant | Value | Description | |----------|-------|-------------| | **vbKeyCancel** | 3 | **Ctrl**+**Break**. | | **vbKeyBack** | 8 | **Backspace**. | | **vbKeyTab** | 9 | **Tab**. | | **vbKeyClear** | 12 | **Clear** (numeric pad **5** without **Num Lock**). | | **vbKeyReturn** | 13 | **Enter**. | | **vbKeyPause** | 19 | **Pause**. | | **vbKeyCapital** | 20 | **Caps Lock**. | | **vbKeyEscape** | 27 | **Esc**. | | **vbKeySpace** | 32 | **Space**. | | **vbKeyPageUp** | 33 | **Page Up**. | | **vbKeyPageDown** | 34 | **Page Down**. | | **vbKeyEnd** | 35 | **End**. | | **vbKeyHome** | 36 | **Home**. | | **vbKeyLeft** | 37 | **Left arrow**. | | **vbKeyUp** | 38 | **Up arrow**. | | **vbKeyRight** | 39 | **Right arrow**. | | **vbKeyDown** | 40 | **Down arrow**. | | **vbKeySelect** | 41 | **Select**. | | **vbKeyPrint** | 42 | **Print**. | | **vbKeyExecute** | 43 | **Execute**. | | **vbKeySnapshot** | 44 | **Print Screen**. | | **vbKeyInsert** | 45 | **Insert**. | | **vbKeyDelete** | 46 | **Delete**. | | **vbKeyHelp** | 47 | **Help**. | | **vbKeyNumlock** | 144 | **Num Lock**. | | **vbKeyScrollLock** | 145 | **Scroll Lock**. | ## Letter keys | Constant | Value | Description | |----------|-------|-------------| | **vbKeyA** -- **vbKeyZ** | 65 -- 90 | The letters **A** through **Z**. | ## Number keys | Constant | Value | Description | |----------|-------|-------------| | **vbKey0** -- **vbKey9** | 48 -- 57 | The digits **0** through **9** on the main keyboard. | ## Numeric keypad | Constant | Value | Description | |----------|-------|-------------| | **vbKeyNumpad0** -- **vbKeyNumpad9** | 96 -- 105 | The digits **0** through **9** on the numeric keypad. | | **vbKeyMultiply** | 106 | **\*** on the numeric keypad. | | **vbKeyAdd** | 107 | **+** on the numeric keypad. | | **vbKeySeparator** | 108 | Numeric-keypad separator. | | **vbKeySubtract** | 109 | **-** on the numeric keypad. | | **vbKeyDecimal** | 110 | **.** on the numeric keypad. | | **vbKeyDivide** | 111 | **/** on the numeric keypad. | ## Function keys | Constant | Value | Description | |----------|-------|-------------| | **vbKeyF1** -- **vbKeyF16** | 112 -- 127 | The function keys **F1** through **F16**. | --- --- url: /zh/official/Reference/VBRUN/Constants/KeyCodeConstants.md --- # KeyCodeConstants **KeyDown**和**KeyUp**事件的*KeyCode*参数中报告的虚拟键代码。值与底层Windows虚拟键代码(`VK_*`)匹配。 ::: info 在经典VBA中,`KeyCodeConstants`是独立常量模块;在VB6和twinBASIC中它是一个枚举。 ::: ## 鼠标按钮和修饰键 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbKeyLButton** | 1 | 鼠标左键。 | | **vbKeyRButton** | 2 | 鼠标右键。 | | **vbKeyMButton** | 4 | 鼠标中键。 | | **vbKeyShift** | 16 | **Shift**。 | | **vbKeyControl** | 17 | **Ctrl**。 | | **vbKeyMenu** | 18 | **Alt**。 | ## 编辑和导航 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbKeyCancel** | 3 | **Ctrl**+**Break**。 | | **vbKeyBack** | 8 | **Backspace**。 | | **vbKeyTab** | 9 | **Tab**。 | | **vbKeyClear** | 12 | **Clear**(数字小键盘**5**,不按**Num Lock**)。 | | **vbKeyReturn** | 13 | **Enter**。 | | **vbKeyPause** | 19 | **Pause**。 | | **vbKeyCapital** | 20 | **Caps Lock**。 | | **vbKeyEscape** | 27 | **Esc**。 | | **vbKeySpace** | 32 | **空格**。 | | **vbKeyPageUp** | 33 | **Page Up**。 | | **vbKeyPageDown** | 34 | **Page Down**。 | | **vbKeyEnd** | 35 | **End**。 | | **vbKeyHome** | 36 | **Home**。 | | **vbKeyLeft** | 37 | **左箭头**。 | | **vbKeyUp** | 38 | **上箭头**。 | | **vbKeyRight** | 39 | **右箭头**。 | | **vbKeyDown** | 40 | **下箭头**。 | | **vbKeySelect** | 41 | **Select**。 | | **vbKeyPrint** | 42 | **Print**。 | | **vbKeyExecute** | 43 | **Execute**。 | | **vbKeySnapshot** | 44 | **Print Screen**。 | | **vbKeyInsert** | 45 | **Insert**。 | | **vbKeyDelete** | 46 | **Delete**。 | | **vbKeyHelp** | 47 | **Help**。 | | **vbKeyNumlock** | 144 | **Num Lock**。 | | **vbKeyScrollLock** | 145 | **Scroll Lock**。 | ## 字母键 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbKeyA** -- **vbKeyZ** | 65 -- 90 | 字母**A**到**Z**。 | ## 数字键 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbKey0** -- **vbKey9** | 48 -- 57 | 主键盘上的数字**0**到**9**。 | ## 数字小键盘 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbKeyNumpad0** -- **vbKeyNumpad9** | 96 -- 105 | 数字小键盘上的数字**0**到**9**。 | | **vbKeyMultiply** | 106 | 数字小键盘上的\*\*\***。 | | **vbKeyAdd** | 107 | 数字小键盘上的**+**。 | | **vbKeySeparator** | 108 | 数字小键盘分隔符。 | | **vbKeySubtract** | 109 | 数字小键盘上的**-**。 | | **vbKeyDecimal** | 110 | 数字小键盘上的**.**。 | | **vbKeyDivide** | 111 | 数字小键盘上的**/\*\*。 | ## 功能键 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbKeyF1** -- **vbKeyF16** | 112 -- 127 | 功能键**F1**到**F16**。 | --- --- url: /en/official/Reference/VBA/Collection/KeyCompareMode.md --- # KeyCompareMode Returns or sets the comparison mode used when matching string keys in a **Collection** object. Read/write. Syntax: * *object*.**KeyCompareMode** * *object*.**KeyCompareMode** **=** *compare* *object* : *required* An object expression that evaluates to a **Collection** object. *compare* : A **VbCompareMethod** value specifying the comparison mode used by [**Add**](/en/official/Reference/VBA/Collection/Add), [**Item**](/en/official/Reference/VBA/Collection/Item), [**Remove**](/en/official/Reference/VBA/Collection/Remove) and [**Exists**](/en/official/Reference/VBA/Collection/Exists) when looking up keys. The *compare* argument settings are: | Constant | Value | Description | |---------------------|-------|--------------------------------------| | **vbBinaryCompare** | 0 | Performs a case-sensitive binary comparison. | | **vbTextCompare** | 1 | Performs a case-insensitive textual comparison. | ::: info **KeyCompareMode** is a twinBASIC extension; the classic VBA **Collection** object always uses case-insensitive comparison and does not expose this property. ::: The default comparison mode is **vbTextCompare**. Changing the comparison mode rehashes the existing keys, so for large collections it is most efficient to set **KeyCompareMode** before adding items. ### Example ```vb Dim col As New Collection ' Default mode is binary (case-sensitive). col.Add "first", Key:="A" col.Add "second", Key:="a" ' Distinct from "A" — succeeds. Dim col2 As New Collection col2.KeyCompareMode = vbTextCompare col2.Add "first", Key:="A" ' col2.Add "second", Key:="a" ' Would raise an error — same key as "A". ``` ### See Also * [Add](/en/official/Reference/VBA/Collection/Add) method * [Exists](/en/official/Reference/VBA/Collection/Exists) method * [KeyCountHint](/en/official/Reference/VBA/Collection/KeyCountHint) property * [StrComp](/en/official/Reference/VBA/Strings/StrComp) function * [Option Compare](/en/official/Reference/Core/Option) statement --- --- url: /zh/official/Reference/VBA/Collection/KeyCompareMode.md --- # KeyCompareMode 返回或设置 **Collection** 对象中匹配字符串键时使用的比较模式。可读写。 语法: * *object*.**KeyCompareMode** * *object*.**KeyCompareMode** **=** *compare* *object* : *必需* 一个计算结果为 **Collection** 对象的对象表达式。 *compare* : 一个 **VbCompareMethod** 值,指定 [**Add**](/official/Reference/VBA/Collection/Add)、[**Item**](/official/Reference/VBA/Collection/Item)、[**Remove**](/official/Reference/VBA/Collection/Remove) 和 [**Exists**](/official/Reference/VBA/Collection/Exists) 在查找键时使用的比较模式。 *compare* 参数设置如下: | 常量 | 值 | 描述 | |------|-----|------| | **vbBinaryCompare** | 0 | 执行区分大小写的二进制比较。 | | **vbTextCompare** | 1 | 执行不区分大小写的文本比较。 | ::: info **KeyCompareMode** 是 twinBASIC 扩展;经典 VBA 的 **Collection** 对象始终使用不区分大小写的比较,并且不公开此属性。 ::: 默认比较模式为 **vbTextCompare**。更改比较模式会对现有键重新哈希,因此对于大型集合,最有效的做法是在添加项之前设置 **KeyCompareMode**。 ### 示例 ```vb Dim col As New Collection ' Default mode is binary (case-sensitive). col.Add "first", Key:="A" col.Add "second", Key:="a" ' Distinct from "A" — succeeds. Dim col2 As New Collection col2.KeyCompareMode = vbTextCompare col2.Add "first", Key:="A" ' col2.Add "second", Key:="a" ' Would raise an error — same key as "A". ``` ### 另请参阅 * [Add](/official/Reference/VBA/Collection/Add) 方法 * [Exists](/official/Reference/VBA/Collection/Exists) 方法 * [KeyCountHint](/official/Reference/VBA/Collection/KeyCountHint) 属性 * [StrComp](/official/Reference/VBA/Strings/StrComp) 函数 * [Option Compare](/official/Reference/Core/Option) 语句 --- --- url: /en/official/Reference/VBA/Collection/KeyCountHint.md --- # KeyCountHint Returns or sets a hint to a **Collection** object about the number of keyed items it is expected to hold, allowing the underlying hash table to be sized accordingly. Read/write. Syntax: * *object*.**KeyCountHint** * *object*.**KeyCountHint** **=** *hint* *object* : *required* An object expression that evaluates to a **Collection** object. *hint* : A **Long** value giving the estimated number of keyed items that will be added to the collection. ::: info **KeyCountHint** is a twinBASIC extension and has no equivalent in the classic VBA **Collection** object. ::: Setting **KeyCountHint** is optional. It is most effective when set before any items are added to the collection: the hint is used to pre-allocate the hash table and avoid repeated resizing as items are inserted. If the actual number of keyed items exceeds the hint, the collection still functions correctly, but performance may be reduced while the hash table grows. The hint affects only keyed items (those added with a **Key** argument); items added without a key are unaffected. ### Example ```vb Dim Big As New Collection Big.KeyCountHint = 100000 ' We expect about 100k keyed items. Dim i As Long For i = 1 To 100000 Big.Add i, Key:=CStr(i) Next ``` ### See Also * [Add](/en/official/Reference/VBA/Collection/Add) method * [Exists](/en/official/Reference/VBA/Collection/Exists) method * [KeyCompareMode](/en/official/Reference/VBA/Collection/KeyCompareMode) property --- --- url: /zh/official/Reference/VBA/Collection/KeyCountHint.md --- # KeyCountHint 返回或设置向 **Collection** 对象提示预期持有的键控项数量,使底层哈希表可以相应地调整大小。可读写。 语法: * *object*.**KeyCountHint** * *object*.**KeyCountHint** **=** *hint* *object* : *必需* 一个计算结果为 **Collection** 对象的对象表达式。 *hint* : 一个 **Long** 值,给出预计将添加到集合中的键控项数量。 ::: info **KeyCountHint** 是 twinBASIC 扩展,在经典 VBA 的 **Collection** 对象中没有等效项。 ::: 设置 **KeyCountHint** 是可选的。在向集合添加任何项之前设置最为有效:该提示用于预分配哈希表,避免在插入项时反复调整大小。如果实际的键控项数量超过提示值,集合仍能正常工作,但哈希表增长时性能可能会降低。 该提示仅影响键控项(使用 **Key** 参数添加的项);不使用键添加的项不受影响。 ### 示例 ```vb Dim Big As New Collection Big.KeyCountHint = 100000 ' We expect about 100k keyed items. Dim i As Long For i = 1 To 100000 Big.Add i, Key:=CStr(i) Next ``` ### 另请参阅 * [Add](/official/Reference/VBA/Collection/Add) 方法 * [Exists](/official/Reference/VBA/Collection/Exists) 方法 * [KeyCompareMode](/official/Reference/VBA/Collection/KeyCompareMode) 属性 --- --- url: /en/official/Reference/VBA/Collection/Keys.md --- # Keys Returns a **String** array containing all the keys associated with items in a **Collection** object. Syntax: *object*.**Keys()** *object* : *required* An object expression that evaluates to a **Collection** object. ::: info **Keys** is a twinBASIC extension; the classic VBA **Collection** object has no **Keys** method. ::: Only items that were added with a **Key** argument appear in the returned array. If no items have keys, the array is empty. ### Example ```vb Dim col As New Collection col.Add "Athens", Key:="a" col.Add "Belgrade", Key:="b" col.Add "Cairo", Key:="c" Dim k() As String k = col.Keys Dim i As Long For i = LBound(k) To UBound(k) Debug.Print k(i), col(k(i)) Next i ``` ### See Also * [Add](/en/official/Reference/VBA/Collection/Add) method * [Exists](/en/official/Reference/VBA/Collection/Exists) method * [Item](/en/official/Reference/VBA/Collection/Item) method * [Items](/en/official/Reference/VBA/Collection/Items) method * [Count](/en/official/Reference/VBA/Collection/Count) property --- --- url: /zh/official/Reference/VBA/Collection/Keys.md --- # Keys 返回一个 **String** 数组,包含 **Collection** 对象中与项关联的所有键。 语法:*object*.**Keys()** *object* : *必需* 一个计算结果为 **Collection** 对象的对象表达式。 ::: info **Keys** 是 twinBASIC 扩展;经典 VBA 的 **Collection** 对象没有 **Keys** 方法。 ::: 只有使用 **Key** 参数添加的项才会出现在返回的数组中。如果没有项具有键,则数组为空。 ### 示例 ```vb Dim col As New Collection col.Add "Athens", Key:="a" col.Add "Belgrade", Key:="b" col.Add "Cairo", Key:="c" Dim k() As String k = col.Keys Dim i As Long For i = LBound(k) To UBound(k) Debug.Print k(i), col(k(i)) Next i ``` ### 另请参阅 * [Add](/official/Reference/VBA/Collection/Add) 方法 * [Exists](/official/Reference/VBA/Collection/Exists) 方法 * [Item](/official/Reference/VBA/Collection/Item) 方法 * [Items](/official/Reference/VBA/Collection/Items) 方法 * [Count](/official/Reference/VBA/Collection/Count) 属性 --- --- url: /en/official/Reference/VBA/FileSystem/Kill.md --- # Kill Deletes files from a disk. Syntax: **Kill** *pathname* *pathname* : *required* String expression that specifies one or more file names to be deleted. The *pathname* may include the directory or folder, and the drive. **Kill** supports the use of multiple-character (`*`) and single-character (`?`) wildcards to specify multiple files. An error occurs when **Kill** is used to delete an open file. ::: info To delete directories, use the [**RmDir**](/en/official/Reference/VBA/FileSystem/RmDir) statement. ::: ### Example This example uses the **Kill** statement to delete a file from a disk. ```vb ' Assume TESTFILE is a file containing some data. Kill "TestFile" ' Delete file. ' Delete all *.TXT files in current directory. Kill "*.TXT" ``` ### See Also * [Dir](/en/official/Reference/VBA/FileSystem/Dir) function * [RmDir](/en/official/Reference/VBA/FileSystem/RmDir), [MkDir](/en/official/Reference/VBA/FileSystem/MkDir) statements --- --- url: /zh/official/Reference/VBA/FileSystem/Kill.md --- # Kill 从磁盘删除文件。 语法:**Kill** *pathname* *pathname* : *必需* 字符串表达式,指定要删除的一个或多个文件名。*pathname*可以包含目录或文件夹以及驱动器。 **Kill**支持使用多字符(`*`)和单字符(`?`)通配符指定多个文件。 使用**Kill**删除打开的文件时会产生错误。 ::: info 要删除目录,请使用[**RmDir**](/official/Reference/VBA/FileSystem/RmDir)语句。 ::: ### 示例 本示例使用**Kill**语句从磁盘删除文件。 ```vb ' Assume TESTFILE is a file containing some data. Kill "TestFile" ' Delete file. ' Delete all *.TXT files in current directory. Kill "*.TXT" ``` ### 另请参阅 * [Dir](/official/Reference/VBA/FileSystem/Dir)函数 * [RmDir](/official/Reference/VBA/FileSystem/RmDir)、[MkDir](/official/Reference/VBA/FileSystem/MkDir)语句 --- --- url: /zh/official/Reference/Core/Kill.md --- # Kill 语句 kill 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/Kill.md --- # Kill Statement Documentation for the kill keyword is not yet available. --- --- url: /en/official/Reference/VB/Label.md --- # Label class A **Label** is a windowless lightweight control for displaying read-only text. Labels are typically used as static captions next to input controls ("Name:", "Email:"), as status displays that code keeps up to date, or as keyboard-mnemonic anchors that route **Alt+** keystrokes to the next focusable control. Because the **Label** has no `hWnd` of its own, it is much cheaper than a [**TextBox**](/en/official/Reference/VB/TextBox/) configured to be read-only --- but it is also non-interactive in the keyboard sense: it cannot take focus, raise key events, or be selected with the **TAB** key. The default property is [**Caption**](#caption) and the default event is [**Click**](#click). ```vb Private Sub Form_Load() lblName.Caption = "&Name:" ' Alt+N forwards focus to the next control lblName.AutoSize = True txtName.Text = "" ' the TextBox that receives Alt+N End Sub Private Sub Timer1_Timer() lblClock.Caption = Format$(Now, "hh:mm:ss") End Sub ``` ## Windowless rendering Like [**Image**](/en/official/Reference/VB/Image/), a **Label** has no `hWnd`. The framework paints it directly onto its parent's drawing surface during the parent's paint cycle. The trade-offs are the same: * No focus, no keyboard input, no `KeyDown` / `KeyPress` / `KeyUp` / `GotFocus` / `LostFocus` / `Validate`. * No `hWnd` to pass to API functions, and no `SetFocus`. * Cannot host child controls. For text the user can edit (or that needs to take focus), use [**TextBox**](/en/official/Reference/VB/TextBox/) with `Locked = True` instead. ## Mnemonics and access keys Labels do not take focus themselves, but they participate in keyboard-mnemonic routing. With [**UseMnemonic**](#usemnemonic) **True** (the default), an ampersand in [**Caption**](#caption) marks the next character as a mnemonic --- pressing **Alt+** that character moves the focus to the *next focusable control in tab order* after the label. Use `&&` to display a literal ampersand. Set [**UseMnemonic**](#usemnemonic) to **False** to disable the special handling and have ampersands rendered verbatim. ```vb lblName.Caption = "&Name:" ' Alt+N → next control (typically txtName) lblHelp.Caption = "Use && to escape" ' renders as: Use & to escape ``` The convention is to place the **Label** immediately before the control it captions in tab order, so the mnemonic naturally targets that control. ## Caption layout [**Alignment**](#alignment) and [**VerticalAlignment**](#verticalalignment) together position the caption within the label's rectangle: | Property | Members | |------------------------------------------|------------------------------------------------------------------------------------------------------------------| | [**Alignment**](#alignment) | **vbLeftJustify** (0, default), **vbRightJustify** (1), **vbCenter** (2) | | [**VerticalAlignment**](#verticalalignment) | **vbVerticalAlignTop** (0, default), **vbVerticalAlignMiddle** (1), **vbVerticalAlignBottom** (2) | [**WordWrap**](#wordwrap), when **True**, breaks the caption into multiple lines at white-space whenever it would otherwise exceed [**Width**](#width). [**LineSpacing**](#linespacing) inserts extra vertical gap (in twips) between lines. [**AutoSize**](#autosize), when **True**, resizes the label to fit its caption every time the caption, font, border, or word-wrap setting changes. Auto-sizing measures the current font in the parent's device context, so it produces correct results on high-DPI displays. When **AutoSize** is **False**, the caption is clipped to the label's rectangle (still respecting [**WordWrap**](#wordwrap) and the alignment settings). ## Rotation [**Angle**](#angle) rotates the rendered caption, in degrees, anti-clockwise around the top-left of the control's rectangle. `0` is the natural orientation, `90` is a quarter-turn anti-clockwise, and so on. The control's bounding rectangle does not change --- large rotation angles can therefore push the visible text outside the rectangle. Hit-testing for [**Click**](#click) and the mouse events still uses the unrotated rectangle. ## Border styles [**BorderStyle**](#borderstyle) chooses between three styles: | Constant | Value | Description | |---------------------------|-------|--------------------------------------------------------------------------------------------| | **vbNoBorder** | 0 | No border (default). | | **vbFixedSingleBorder** | 1 | A sunken Win32-style border. [**Appearance**](#appearance) selects 3-D or flat. | | **vbCustomBorder** | 2 | Per-edge custom border configured through [**BorderCustomOptions**](#bordercustomoptions). | With **vbCustomBorder**, [**BorderCustomOptions**](#bordercustomoptions) returns an object whose `.Left`, `.Top`, `.Right`, and `.Bottom` properties each have independent **Size** (line thickness, in twips), **Padding** (inset between the border and the caption, in twips), and **Color** values: ```vb lblBox.BorderStyle = vbCustomBorder With lblBox.BorderCustomOptions .Top.Size = 30 : .Top.Color = vbRed : .Top.Padding = 60 .Bottom.Size = 30 : .Bottom.Color = vbRed : .Bottom.Padding = 60 End With ``` ## Background [**BackStyle**](#backstyle) chooses between **vbBFOpaque** (default --- paint [**BackColor**](#backcolor) under the caption) and **vbBFTransparent** (don't paint a background --- whatever the parent has drawn shows through). Transparent labels are essential when overlaying captions on a [**PictureBox**](/en/official/Reference/VB/PictureBox/), an [**Image**](/en/official/Reference/VB/Image/), or a custom-painted form background. New labels created in *report mode* default to **vbBFTransparent**. ## Data binding Setting [**DataSource**](#datasource) and [**DataField**](#datafield) connects [**Caption**](#caption) to a field of a [**Data**](/en/official/Reference/VB/Data/) control's recordset. The bound field is read as a string on each move, and assigning to [**Caption**](#caption) marks the recordset as dirty. [**DataFieldAggregate**](#datafieldaggregate) and [**DataFieldAggregateValue**](#datafieldaggregatevalue) are used by the report engine to display running totals. ## Properties ### Alignment The horizontal placement of [**Caption**](#caption) within the label's rectangle. A member of [**AlignmentConstants**](/en/official/Reference/VBRUN/Constants/AlignmentConstants): **vbLeftJustify** (0, default), **vbRightJustify** (1), or **vbCenter** (2). ### Anchors The set of edges of the parent that the label's corresponding edges follow when the parent resizes. Read-only --- assign individual `.Left`, `.Top`, `.Right`, `.Bottom` flags through the returned **Anchors** object. ### Angle The rotation of the rendered caption, in degrees, anti-clockwise around the top-left of the control's rectangle. **Double**, default `0`. ### Appearance The style of the border, as a member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). Only meaningful when [**BorderStyle**](#borderstyle) is **vbFixedSingleBorder**. ### AutoSize Whether the label resizes itself to fit its [**Caption**](#caption), [**Font**](#font), border, and word-wrap settings. **Boolean**, default **False**. When **True**, the resize happens whenever any of those inputs change. ### BackColor The colour painted behind the caption when [**BackStyle**](#backstyle) is **vbBFOpaque**. **OLE\_COLOR**, defaults to the system 3-D face colour. ### BackStyle Whether the label paints a background. A member of [**BackFillStyleConstants**](/en/official/Reference/VBRUN/Constants/BackFillStyleConstants): **vbBFOpaque** (1, default --- paint [**BackColor**](#backcolor)) or **vbBFTransparent** (0 --- let whatever the parent has drawn show through). ### BorderCustomOptions Per-edge configuration for the **vbCustomBorder** style. Read-only; the returned object exposes `.Left`, `.Top`, `.Right`, `.Bottom` sub-objects, each with `Size`, `Padding`, and `Color` properties. See [Border styles](#border-styles). ### BorderStyle The style of border drawn around the label. A member of [**ControlBorderStyleConstantsCustom**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstantsCustom): **vbNoBorder** (0, default), **vbFixedSingleBorder** (1), or **vbCustomBorder** (2). See [Border styles](#border-styles). ### Caption The text rendered by the label. **String**. **Default property.** Syntax: *object*.**Caption** \[ = *string* ] An ampersand marks the next character as a mnemonic when [**UseMnemonic**](#usemnemonic) is **True**; `&&` produces a literal ampersand. Assigning a value that differs from the current one raises a [**Change**](#change) event; assigning the current value is a silent no-op. ### Container The control that hosts this label --- typically the form, a [**Frame**](/en/official/Reference/VB/Frame/), or a **UserControl**. Read with **Get**, change with **Set**. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a label. Always **vbLabel**. ### DataChanged Whether the bound [**Caption**](#caption) has been written to since the last save or refresh from the [**DataSource**](#datasource). **Boolean**. Setting **DataChanged** = **True** also marks the bound recordset as dirty. ### DataField The name of the field, in the recordset of the bound [**DataSource**](#datasource), whose value is mirrored by [**Caption**](#caption). **String**. ### DataFieldAggregate The kind of running aggregate the report engine should accumulate into [**DataFieldAggregateValue**](#datafieldaggregatevalue). A member of `Label.AggregateConstants`: | Constant | Value | Description | |---------------------|-------|----------------------------------------------------------------------| | **vbAggregateNone** | 0 | No aggregation (default). | | **vbAggregateSum** | 1 | Sum the bound numeric value across the rows visited by the report. | Used only when the label is rendered inside a [**Report**](/en/official/Reference/VB/Report/) section. ### DataFieldAggregateValue The accumulated aggregate value computed by the report engine, exposed as a **Decimal**. Updated by the engine while a report is being generated; user code can read it from event handlers but does not normally write to it. ### DataFormat ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### DataMember ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### DataSource A reference to a [**Data**](/en/official/Reference/VB/Data/) control (or other **DataSource** provider) whose recordset supplies the value for [**DataField**](#datafield). Set with **Set**. ### Dock Where the label is docked within its container. A member of [**DockModeConstants**](/en/official/Reference/VBRUN/Constants/DockModeConstants): **vbDockNone** (default), **vbDockLeft**, **vbDockTop**, **vbDockRight**, **vbDockBottom**, or **vbDockFill**. Docked labels ignore [**Anchors**](#anchors). ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Whether the label accepts mouse input and renders [**Caption**](#caption) in the normal text colour. A disabled label still paints, but in the system grey-text colour, and ignores mouse events. **Boolean**, default **True**. ### Font The **StdFont** used to render [**Caption**](#caption). The convenience properties **FontBold**, **FontItalic**, **FontName**, **FontSize**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. Defaults to Segoe UI, 8 pt. ### FontBold Shortcut for `Font.Bold`. **Boolean**. ### FontItalic Shortcut for `Font.Italic`. **Boolean**. ### FontName Shortcut for `Font.Name`. **String**, default `"Segoe UI"`. ### FontSize Shortcut for `Font.Size`. **Single**, in points. Default `8`. ### FontStrikethru Shortcut for `Font.Strikethrough`. **Boolean**. ### FontUnderline Shortcut for `Font.Underline`. **Boolean**. ### ForeColor The text colour for [**Caption**](#caption), as an **OLE\_COLOR**. Defaults to the system button-text colour. Replaced with the system grey-text colour when [**Enabled**](#enabled) is **False**. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). **Double**. Computed automatically while [**AutoSize**](#autosize) is **True**. ### Index When the label is part of a control array, the **Long** zero-based index of this instance within the array. Reading **Index** on a non-array instance raises run-time error 343 (*Object not an array*). Read-only at run time. ### Left The horizontal distance from the left edge of the container to the left edge of the label. **Double**. ### LineSpacing Extra vertical space inserted between lines of a wrapped or multi-line caption, in twips. **Long**, default `0`. ### LinkItem ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: ### LinkMode ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: ### LinkTimeout ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: ### LinkTopic ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### OLEDropMode How the label responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** (0, default) or **vbOLEDropManual** (1). Automatic drop is not supported on a Label; assigning **vbOLEDropAutomatic** raises run-time error 5 (*Invalid procedure call or argument*). ### Parent A reference to the [**Form**](/en/official/Reference/VB/Form/) (or **UserControl**) that ultimately contains the control. Read-only. ### RightToLeft ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. Use [**Alignment**](#alignment) `vbRightJustify` to right-align the caption. ::: ### TabIndex ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. The label is non-focusable, so the value would only affect mnemonic-routing --- that is currently controlled by the design-time Z-order instead. ::: ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the label. ### Top The vertical distance from the top of the container to the top of the label. **Double**. ### UseMnemonic Whether `&` in [**Caption**](#caption) marks the next character as a keyboard mnemonic. **Boolean**, default **True**. With **False**, ampersands are rendered verbatim. ### VerticalAlignment The vertical placement of the caption within the label's rectangle. A member of [**VerticalAlignmentConstants**](/en/official/Reference/VBRUN/Constants/VerticalAlignmentConstants): **vbVerticalAlignTop** (0, default), **vbVerticalAlignMiddle** (1), or **vbVerticalAlignBottom** (2). ### Visible Whether the label is shown. **Boolean**, default **True**. ### WhatsThisHelpID ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. See [**ShowWhatsThis**](#showwhatsthis). ::: ### Width The control's width, in twips by default (or in the container's **ScaleMode** units). **Double**. Computed automatically while [**AutoSize**](#autosize) is **True**. ### WordWrap Whether the caption breaks into multiple lines at white-space when it would otherwise exceed [**Width**](#width). **Boolean**, default **False**. ## Methods ### Drag Begins, completes, or cancels a manual VB-style drag operation. Distinct from OLE drag --- see [**OLEDrag**](#oledrag). Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### LinkExecute ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: Syntax: *object*.**LinkExecute** *Command* ### LinkPoke ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: Syntax: *object*.**LinkPoke** ### LinkRequest ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: Syntax: *object*.**LinkRequest** ### LinkSend ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: Syntax: *object*.**LinkSend** ### Move Repositions and optionally resizes the label in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the label, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Forces an immediate repaint of the label's rectangle on the parent's drawing surface. Syntax: *object*.**Refresh** ### ShowWhatsThis ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the label to the front or back of the windowless-sibling stack within its container. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Change Raised when [**Caption**](#caption) is assigned a value that differs from its current contents. Syntax: *object*\_**Change**( ) ### Click Raised when the user single-clicks the label's rectangle. **Default event.** Syntax: *object*\_**Click**( ) ### DblClick Raised when the user double-clicks the label's rectangle. Syntax: *object*\_**DblClick**( ) ### DragDrop Raised on the destination control when a manual VB-style drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual VB-style drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### Initialize Raised once, after the label has been connected to its container's paint cycle but before it is first painted. Useful for last-minute setup that depends on container state. Syntax: *object*\_**Initialize**( ) ### LinkClose ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### LinkError ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### LinkNotify ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### LinkOpen ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### MouseDown Raised when the user presses any mouse button over the label. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the label. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the label. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) --- --- url: /zh/official/Reference/VB/Label.md --- # Label 类 **Label**是一个无窗口轻量级控件,用于显示只读文本。标签通常用作输入控件旁边的静态标题("姓名:"、"邮箱:"),由代码保持更新的状态显示,或作为键盘助记锚点将**Alt+**按键路由到下一个可聚焦控件。因为**Label**没有自己的`hWnd`,所以比配置为只读的[**TextBox**](/official/Reference/VB/TextBox/)开销小得多——但它在键盘意义上也是非交互的:不能获取焦点、引发键事件或通过**TAB**键选择。 默认属性是[**Caption**](#caption),默认事件是[**Click**](#click)。 ```vb Private Sub Form_Load() lblName.Caption = "&Name:" ' Alt+N将焦点转发到下一个控件 lblName.AutoSize = True txtName.Text = "" ' 接收Alt+N的TextBox End Sub Private Sub Timer1_Timer() lblClock.Caption = Format$(Now, "hh:mm:ss") End Sub ``` ## 无窗口渲染 与[**Image**](/official/Reference/VB/Image/)一样,**Label**没有`hWnd`。框架在父控件的绘制周期中将其直接绘制到父控件的绘图表面上。权衡是相同的: * 无焦点、无键盘输入、无`KeyDown` / `KeyPress` / `KeyUp` / `GotFocus` / `LostFocus` / `Validate`。 * 无`hWnd`可传递给API函数,无`SetFocus`。 * 不能承载子控件。 对于用户可编辑(或需要获取焦点)的文本,改用`Locked = True`的[**TextBox**](/official/Reference/VB/TextBox/)。 ## 助记符和访问键 标签本身不获取焦点,但参与键盘助记符路由。当[**UseMnemonic**](#usemnemonic)为**True**(默认)时,[**Caption**](#caption)中的&符号将下一个字符标记为助记符——按**Alt+**该字符将焦点移到标签之后*按TAB顺序的下一个可聚焦控件*。使用`&&`显示字面&符号。将[**UseMnemonic**](#usemnemonic)设置为**False**可禁用特殊处理并按原样渲染&符号。 ```vb lblName.Caption = "&Name:" ' Alt+N → 下一个控件(通常是txtName) lblHelp.Caption = "Use && to escape" ' 显示为: Use & to escape ``` 约定是将**Label**在TAB顺序中紧接在其标题的控件之前,这样助记符自然指向该控件。 ## Caption布局 [**Alignment**](#alignment)和[**VerticalAlignment**](#verticalalignment)共同定位标签矩形内的标题: | 属性 | 成员 | |------------------------------------------------|---------------------------------------------------------------------------------------------------| | [**Alignment**](#alignment) | **vbLeftJustify** (0,默认)、**vbRightJustify** (1)、**vbCenter** (2) | | [**VerticalAlignment**](#verticalalignment) | **vbVerticalAlignTop** (0,默认)、**vbVerticalAlignMiddle** (1)、**vbVerticalAlignBottom** (2) | [**WordWrap**](#wordwrap)为**True**时,当标题否则会超出[**Width**](#width)时在空白处将标题分成多行。[**LineSpacing**](#linespacing)在行间插入额外的垂直间距(以缇为单位)。 [**AutoSize**](#autosize)为**True**时,每当标题、字体、边框或自动换行设置更改时,标签会重新调整大小以适应其标题。自动调整大小在父控件的设备上下文中测量当前字体,因此在高DPI显示器上产生正确结果。当**AutoSize**为**False**时,标题被裁剪到标签的矩形内(仍遵循[**WordWrap**](#wordwrap)和对齐设置)。 ## 旋转 [**Angle**](#angle)以度为单位逆时针绕控件矩形左上角旋转渲染的标题。`0`为自然方向,`90`为逆时针四分之一转,以此类推。控件的边界矩形不变——因此大旋转角度可能将可见文本推到矩形之外。[**Click**](#click)和鼠标事件的点击测试仍使用未旋转的矩形。 ## 边框样式 [**BorderStyle**](#borderstyle)在三种样式之间选择: | 常量 | 值 | 描述 | |---------------------------|-----|-----------------------------------------------------------------------------------------| | **vbNoBorder** | 0 | 无边框(默认)。 | | **vbFixedSingleBorder** | 1 | 凹陷的Win32风格边框。[**Appearance**](#appearance)选择3D或平面。 | | **vbCustomBorder** | 2 | 通过[**BorderCustomOptions**](#bordercustomoptions)配置的逐边自定义边框。 | 使用**vbCustomBorder**时,[**BorderCustomOptions**](#bordercustomoptions)返回一个对象,其`.Left`、`.Top`、`.Right`和`.Bottom`属性各自有独立的**Size**(线粗,以缇为单位)、**Padding**(边框与标题之间的内边距,以缇为单位)和**Color**值: ```vb lblBox.BorderStyle = vbCustomBorder With lblBox.BorderCustomOptions .Top.Size = 30 : .Top.Color = vbRed : .Top.Padding = 60 .Bottom.Size = 30 : .Bottom.Color = vbRed : .Bottom.Padding = 60 End With ``` ## 背景 [**BackStyle**](#backstyle)在**vbBFOpaque**(默认——在标题下绘制[**BackColor**](#backcolor))和**vbBFTransparent**(不绘制背景——父控件绘制的内容会透过来)之间选择。在[**PictureBox**](/official/Reference/VB/PictureBox/)、[**Image**](/official/Reference/VB/Image/)或自定义绘制的窗体背景上叠加标题时,透明标签是必不可少的。在*报表模式*下创建的新标签默认为**vbBFTransparent**。 ## 数据绑定 设置[**DataSource**](#datasource)和[**DataField**](#datafield)将[**Caption**](#caption)连接到[**Data**](/official/Reference/VB/Data/)控件记录集的字段。每次移动时绑定字段作为字符串读取,对[**Caption**](#caption)赋值会将记录集标记为已修改。[**DataFieldAggregate**](#datafieldaggregate)和[**DataFieldAggregateValue**](#datafieldaggregatevalue)由报表引擎用于显示运行汇总。 ## 属性 ### Alignment [**Caption**](#caption)在标签矩形内的水平放置。[**AlignmentConstants**](/official/Reference/VBRUN/Constants/AlignmentConstants)的成员:**vbLeftJustify** (0,默认)、**vbRightJustify** (1)或**vbCenter** (2)。 ### Anchors 标签的对应边缘跟随父控件调整大小时所依据的父控件边缘集合。只读——通过返回的**Anchors**对象分配单独的`.Left`、`.Top`、`.Right`、`.Bottom`标志。 ### Angle 渲染标题的旋转角度,以度为单位,逆时针绕控件矩形左上角旋转。**Double**,默认`0`。 ### Appearance 边框的样式,[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。仅在[**BorderStyle**](#borderstyle)为**vbFixedSingleBorder**时有意义。 ### AutoSize 标签是否重新调整大小以适应其[**Caption**](#caption)、[**Font**](#font)、边框和自动换行设置。**Boolean**,默认**False**。当为**True**时,每当这些输入中的任何一个更改时都会重新调整大小。 ### BackColor 当[**BackStyle**](#backstyle)为**vbBFOpaque**时绘制在标题后面的颜色。**OLE\_COLOR**,默认为系统3D面色。 ### BackStyle 标签是否绘制背景。[**BackFillStyleConstants**](/official/Reference/VBRUN/Constants/BackFillStyleConstants)的成员:**vbBFOpaque** (1,默认——绘制[**BackColor**](#backcolor))或**vbBFTransparent** (0——让父控件绘制的内容透过来)。 ### BorderCustomOptions **vbCustomBorder**样式的逐边配置。只读;返回的对象公开`.Left`、`.Top`、`.Right`、`.Bottom`子对象,每个都有`Size`、`Padding`和`Color`属性。参见[边框样式](#border-styles)。 ### BorderStyle 标签周围绘制的边框样式。[**ControlBorderStyleConstantsCustom**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstantsCustom)的成员:**vbNoBorder** (0,默认)、**vbFixedSingleBorder** (1)或**vbCustomBorder** (2)。参见[边框样式](#border-styles)。 ### Caption 标签渲染的文本。**String**。**默认属性。** 语法:*object*.**Caption** \[ = *string* ] 当[**UseMnemonic**](#usemnemonic)为**True**时,&符号将下一个字符标记为助记符;`&&`产生字面&符号。赋值与当前值不同的值会引发[**Change**](#change)事件;赋值当前值为静默空操作。 ### Container 承载此标签的控件——通常是窗体、[**Frame**](/official/Reference/VB/Frame/)或**UserControl**。使用**Get**读取,使用**Set**更改。 ### ControlType 只读的[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值,将此控件标识为标签。始终为**vbLabel**。 ### DataChanged 绑定的[**Caption**](#caption)自上次保存或从[**DataSource**](#datasource)刷新以来是否已被写入。**Boolean**。设置**DataChanged** = **True**也会将绑定记录集标记为已修改。 ### DataField 绑定[**DataSource**](#datasource)记录集中由[**Caption**](#caption)镜像的字段名称。**String**。 ### DataFieldAggregate 报表引擎应累积到[**DataFieldAggregateValue**](#datafieldaggregatevalue)中的运行聚合类型。`Label.AggregateConstants`的成员: | 常量 | 值 | 描述 | |-----------------------|-----|-------------------------------------------------------------------| | **vbAggregateNone** | 0 | 无聚合(默认)。 | | **vbAggregateSum** | 1 | 对报表访问的行中的绑定数值求和。 | 仅在标签在[**Report**](/official/Reference/VB/Report/)节中渲染时使用。 ### DataFieldAggregateValue 报表引擎计算的累积聚合值,公开为**Decimal**。在生成报表时由引擎更新;用户代码可从事件处理程序中读取但通常不写入。 ### DataFormat ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: ### DataMember ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: ### DataSource 对[**Data**](/official/Reference/VB/Data/)控件(或其他**DataSource**提供程序)的引用,其记录集为[**DataField**](#datafield)提供值。使用**Set**设置。 ### Dock 标签在其容器中的停靠位置。[**DockModeConstants**](/official/Reference/VBRUN/Constants/DockModeConstants)的成员:**vbDockNone**(默认)、**vbDockLeft**、**vbDockTop**、**vbDockRight**、**vbDockBottom**或**vbDockFill**。停靠标签忽略[**Anchors**](#anchors)。 ### DragIcon 控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自动拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual** (0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic** (1)。 ### Enabled 标签是否接受鼠标输入并以正常文本颜色渲染[**Caption**](#caption)。禁用的标签仍会绘制,但使用系统灰色文本色并忽略鼠标事件。**Boolean**,默认**True**。 ### Font 用于渲染[**Caption**](#caption)的**StdFont**。便捷属性**FontBold**、**FontItalic**、**FontName**、**FontSize**、**FontStrikethru**和**FontUnderline**读写此对象的相应成员。默认为Segoe UI, 8磅。 ### FontBold `Font.Bold`的快捷方式。**Boolean**。 ### FontItalic `Font.Italic`的快捷方式。**Boolean**。 ### FontName `Font.Name`的快捷方式。**String**,默认`"Segoe UI"`。 ### FontSize `Font.Size`的快捷方式。**Single**,以磅为单位。默认`8`。 ### FontStrikethru `Font.Strikethrough`的快捷方式。**Boolean**。 ### FontUnderline `Font.Underline`的快捷方式。**Boolean**。 ### ForeColor [**Caption**](#caption)的文本颜色,类型为**OLE\_COLOR**。默认为系统按钮文本色。当[**Enabled**](#enabled)为**False**时替换为系统灰色文本色。 ### Height 控件的高度,默认以缇为单位(或使用容器的**ScaleMode**单位)。**Double**。当[**AutoSize**](#autosize)为**True**时自动计算。 ### Index 当标签是控件数组的一部分时,此实例在数组中的从零开始的**Long**索引。在非数组实例上读取**Index**会引发运行时错误343(*Object not an array*)。运行时只读。 ### Left 从容器的左边缘到标签左边缘的水平距离。**Double**。 ### LineSpacing 在自动换行或多行标题的行间插入的额外垂直间距,以缇为单位。**Long**,默认`0`。 ### LinkItem ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中未实现。 ::: ### LinkMode ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中未实现。 ::: ### LinkTimeout ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中未实现。 ::: ### LinkTopic ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中未实现。 ::: ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针位于控件上时用作鼠标光标的**StdPicture**。 ### MousePointer 指针位于控件上时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### OLEDropMode 标签如何响应OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone** (0,默认)或**vbOLEDropManual** (1)。Label不支持自动放置;赋值**vbOLEDropAutomatic**会引发运行时错误5(*Invalid procedure call or argument*)。 ### Parent 对最终包含此控件的[**Form**](/official/Reference/VB/Form/)(或**UserControl**)的引用。只读。 ### RightToLeft ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。使用[**Alignment**](#alignment)的`vbRightJustify`来右对齐标题。 ::: ### TabIndex ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。标签不可聚焦,因此该值仅影响助记符路由——目前由设计时Z顺序控制。 ::: ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### ToolTipText 当用户将鼠标悬停在标签上时作为工具提示显示的多行**String**。 ### Top 从容器顶部到标签顶部的垂直距离。**Double**。 ### UseMnemonic [**Caption**](#caption)中的`&`是否将下一个字符标记为键盘助记符。**Boolean**,默认**True**。为**False**时,&符号按原样渲染。 ### VerticalAlignment 标题在标签矩形内的垂直放置。[**VerticalAlignmentConstants**](/official/Reference/VBRUN/Constants/VerticalAlignmentConstants)的成员:**vbVerticalAlignTop** (0,默认)、**vbVerticalAlignMiddle** (1)或**vbVerticalAlignBottom** (2)。 ### Visible 标签是否显示。**Boolean**,默认**True**。 ### WhatsThisHelpID ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。参见[**ShowWhatsThis**](#showwhatsthis)。 ::: ### Width 控件的宽度,默认以缇为单位(或使用容器的**ScaleMode**单位)。**Double**。当[**AutoSize**](#autosize)为**True**时自动计算。 ### WordWrap 当标题否则会超出[**Width**](#width)时是否在空白处分成多行。**Boolean**,默认**False**。 ## 方法 ### Drag 开始、完成或取消手动VB风格拖动操作。与OLE拖动不同——参见[**OLEDrag**](#oledrag)。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel** (0)、**vbBeginDrag** (1,默认)或**vbEndDrag** (2)。 ### LinkExecute ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中未实现。 ::: 语法:*object*.**LinkExecute** *Command* ### LinkPoke ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中未实现。 ::: 语法:*object*.**LinkPoke** ### LinkRequest ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中未实现。 ::: 语法:*object*.**LinkRequest** ### LinkSend ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中未实现。 ::: 语法:*object*.**LinkSend** ### Move 在单次调用中重新定位并可选地调整标签大小。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**值。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从标签发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### Refresh 强制立即重绘父控件绘图表面上的标签矩形。 语法:*object*.**Refresh** ### ShowWhatsThis ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: 语法:*object*.**ShowWhatsThis** ### ZOrder 将标签置于其容器内无窗口同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront** (0,默认)或**vbSendToBack** (1)。 ## 事件 ### Change 当[**Caption**](#caption)被赋值与当前内容不同的值时引发。 语法:*object*\_**Change**( ) ### Click 用户单击标签矩形时引发。**默认事件。** 语法:*object*\_**Click**( ) ### DblClick 用户双击标签矩形时引发。 语法:*object*\_**DblClick**( ) ### DragDrop 手动VB风格拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 手动VB风格拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### Initialize 在标签连接到其容器的绘制周期后但首次绘制前引发一次。用于依赖容器状态的最后时刻设置。 语法:*object*\_**Initialize**( ) ### LinkClose ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中不会引发。 ::: ### LinkError ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中不会引发。 ::: ### LinkNotify ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中不会引发。 ::: ### LinkOpen ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中不会引发。 ::: ### MouseDown 用户在标签上按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 光标在标签上移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 用户在标签上释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 用户将数据放置到目标控件上时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的数据格式时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) --- --- url: /en/packages/vbccr/text/labelw.md description: >- LabelW Control - VBCCR Development Manual, complete API reference based on source code --- # LabelW Control Enhanced Unicode label control, replacing the standard VB6 Label control, providing text effects, border effects, mouse tracking, and other enhanced features. ## Enumerations ### LblTextEffectsConstants | Constant | Value | Description | |----------|-------|-------------| | LblTextEffectNone | 0 | No effect | | LblTextEffectShadow | 1 | Shadow | | LblTextEffectEmboss | 2 | Emboss | | LblTextEffectEngrave | 3 | Engrave | ### LblBorderEffectsConstants | Constant | Value | Description | |----------|-------|-------------| | LblBorderEffectNone | 0 | No border effect | | LblBorderEffectSoftEdge | 1 | Soft edge | | LblBorderEffectEtched | 2 | Etched | ### CCBackStyleConstants See common enumerations. ### CCAppearanceConstants See common enumerations. ### CCBorderStyleConstants See common enumerations. ### CCMousePointerConstants See common enumerations. ### CCVerticalAlignmentConstants See common enumerations. ### CCRightToLeftModeConstants See common enumerations. ## Properties ### Alignment ```vb Property Get Alignment() As Long Property Let Alignment(ByVal Value As Long) ``` Text alignment. 0 = Left-aligned, 1 = Right-aligned, 2 = Centered. ### AutoSize ```vb Property Get AutoSize() As Boolean Property Let AutoSize(ByVal Value As Boolean) ``` Whether to automatically resize to fit the content. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` The background color. ### BackStyle ```vb Property Get BackStyle() As CCBackStyleConstants Property Let BackStyle(ByVal Value As CCBackStyleConstants) ``` The background style. See common enumerations. ### BorderStyle ```vb Property Get BorderStyle() As CCBorderStyleConstants Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` The border style. See common enumerations. ### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` The display text. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` The font. ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` The foreground color. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` The mouse pointer style. See common enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` The custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Whether mouse enter/leave tracking is enabled. ### UseMnemonic ```vb Property Get UseMnemonic() As Boolean Property Let UseMnemonic(ByVal Value As Boolean) ``` Whether the & character is interpreted as an accelerator prefix. ### TextEffect ```vb Property Get TextEffect() As LblTextEffectsConstants Property Let TextEffect(ByVal Value As LblTextEffectsConstants) ``` The text effect. ### TextEffectColor ```vb Property Get TextEffectColor() As OLE_COLOR Property Let TextEffectColor(ByVal Value As OLE_COLOR) ``` The text effect color. ### BorderEffect ```vb Property Get BorderEffect() As LblBorderEffectsConstants Property Let BorderEffect(ByVal Value As LblBorderEffectsConstants) ``` The border effect. ### BorderEffectColor ```vb Property Get BorderEffectColor() As OLE_COLOR Property Let BorderEffectColor(ByVal Value As OLE_COLOR) ``` The border effect color. ### WordWrap ```vb Property Get WordWrap() As Boolean Property Let WordWrap(ByVal Value As Boolean) ``` Whether text wraps automatically. ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` The right-to-left display direction. ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` The right-to-left mirrored layout. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` The right-to-left mode. See common enumerations. ### Appearance ```vb Property Get Appearance() As CCAppearanceConstants Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` The appearance style. See common enumerations. ### VerticalAlignment ```vb Property Get VerticalAlignment() As CCVerticalAlignmentConstants Property Let VerticalAlignment(ByVal Value As CCVerticalAlignmentConstants) ``` The vertical alignment. See common enumerations. ### hWnd ```vb Property Get hWnd() As LongPtr ``` The window handle. Read-only. ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` The tooltip text. ### Name ```vb Property Get Name() As String ``` The control name. Read-only. ### Tag ```vb Property Get Tag() As Variant Property Let Tag(ByVal Value As Variant) Property Set Tag(ByVal Value As Variant) ``` Custom data. ### Parent ```vb Property Get Parent() As Object ``` The parent object. Read-only. ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` The container object. ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` The left margin. ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` The top margin. ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` The width. ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` The height. ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` The visibility. ## Methods ### Refresh ```vb Sub Refresh() ``` Forces a repaint. ### AboutBox ```vb Sub AboutBox() ``` Displays the About dialog. ## Events ### Click ```vb Event Click() ``` Occurs when the control is clicked. ### DblClick ```vb Event DblClick() ``` Occurs when the control is double-clicked. ### MouseDown ```vb Event MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` Occurs when a mouse button is pressed. ### MouseUp ```vb Event MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` Occurs when a mouse button is released. ### MouseMove ```vb Event MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` Occurs when the mouse is moved. ### MouseEnter ```vb Event MouseEnter() ``` Occurs when the mouse enters the control. ### MouseLeave ```vb Event MouseLeave() ``` Occurs when the mouse leaves the control. ### OLEStartDrag ```vb Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` Occurs when an OLE drag operation starts. ### OLEGiveFeedback ```vb Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE drag feedback. ### OLESetData ```vb Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE set data. ### OLECompleteDrag ```vb Event OLECompleteDrag(Effect As Long) ``` OLE drag completed. ### OLEDragOver ```vb Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` Occurs when data is dragged over during an OLE drag operation. ### OLEDragDrop ```vb Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Occurs when data is dropped during an OLE drag-and-drop operation. ## Code Examples ```vb ' Label with shadow effect With LabelW1 .Caption = "Welcome to VBCCR" .TextEffect = LblTextEffectShadow .TextEffectColor = vbGrayText .Font.Size = 14 .Font.Bold = True End With ' Respond to mouse enter/leave Private Sub LabelW1_MouseEnter() LabelW1.ForeColor = vbBlue End Sub Private Sub LabelW1_MouseLeave() LabelW1.ForeColor = vbWindowText End Sub ' Vertically centered label with etched border With LabelW2 .Caption = "Settings" .VerticalAlignment = ccVCenter .BorderEffect = LblBorderEffectEtched .BorderEffectColor = vb3DShadow End With ``` --- --- url: /en/official/Features/Language.md --- # Language Syntax twinBASIC introduces numerous enhancements to VBx language syntax, including new data types, improved type systems, and modern programming constructs. ## Topics * [Alias Types](/en/official/Features/Language/Alias-Types) - alias types, similar to **typedef** in C and **using** in C++ * [Data Types](/en/official/Features/Language/Data-Types) - New data types (**LongPtr**, **LongLong**, **Decimal**) * [Interfaces and Coclasses](/en/official/Features/Language/Interfaces-CoClasses) - Native interface and coclass definitions * [Inheritance](/en/official/Features/Language/Inheritance) - **Implements Via** and **Inherits** keywords * [Delegates](/en/official/Features/Language/Delegates) - Function pointers, also called delegates * [Generics](/en/official/Features/Language/Generics) - Generic type support * [Overloading](/en/official/Features/Language/Overloading) - Method overloading capabilities * [Operators](/en/official/Features/Language/Operators) - New operators and syntax * [Literals](/en/official/Features/Language/Literals) - Binary literals and digit grouping * [Type Inference](/en/official/Features/Language/Type-Inference) - **As Any** type inference * [Pointers](/en/official/Features/Language/Pointers) - Enhanced pointer functionality * [UDT Enhancements](/en/official/Features/Language/UDTs) - User-defined type improvements * [Loop Control](/en/official/Features/Language/Loop-Control) - **Continue ...** and **Exit While** * [Return Syntax](/en/official/Features/Language/Return) - Modern **Return** statement * [Inline Initialization](/en/official/Features/Language/Inline-Initialization) - Variable initialization * [Handler Methods](/en/official/Features/Language/Handlers) - **Handles** and **Implements** syntax * [Module Organization](/en/official/Features/Language/Module-Organization) - Code placement flexibility * [Comments](/en/official/Features/Language/Comments) - New code comment syntax --- --- url: /en/official/Reference/VBA/ErrObject/LastDllError.md --- # LastDllError Returns the last system error code produced by a call into a dynamic-link library (DLL). Read-only. Syntax: **Err**.**LastDllError** The **LastDllError** property applies to DLL calls made through a [**Declare**](/en/official/Reference/Core/Declare) statement. When such a call is made, the called function usually returns a code indicating success or failure, and **LastDllError** is filled with the value of the operating system's last-error code (`GetLastError`). No exception is raised when **LastDllError** is set. The value is preserved only until the next external call. Read it immediately after the failing call to be sure of the result. ::: info **LastDllError** is Windows-specific. ::: Check the documentation for the DLL's functions to determine the return values that indicate success or failure. Whenever a failure code is returned, the application should immediately check the **LastDllError** property. ### Example The following code calls a DLL function with an invalid argument so that the call fails. The code following the call checks the return value, and then displays the **LastDllError** property of the **Err** object to reveal the OS error code. ```vb Private Declare PtrSafe Function SQLCancel Lib "ODBC32.dll" _ (ByVal hstmt As LongPtr) As Integer Private Sub Demo() Dim retVal As Integer ' Call with invalid handle. retVal = SQLCancel(0) If retVal = -2 Then ' Display the underlying OS error code. MsgBox "Error code is: " & Err.LastDllError End If End Sub ``` ### See Also * [LastHresult](/en/official/Reference/VBA/ErrObject/LastHresult) property * [Number](/en/official/Reference/VBA/ErrObject/Number) property --- --- url: /zh/official/Reference/VBA/ErrObject/LastDllError.md --- # LastDllError 返回调用动态链接库 (DLL) 时产生的最后一个系统错误代码。只读。 语法:**Err**.**LastDllError** **LastDllError** 属性适用于通过 [**Declare**](/official/Reference/Core/Declare) 语句进行的 DLL 调用。当进行此类调用时,被调用函数通常返回一个指示成功或失败的代码,而 **LastDllError** 填充为操作系统的最后错误代码(`GetLastError`)的值。设置 **LastDllError** 时不会引发异常。 该值仅保留到下一次外部调用。应在失败的调用之后立即读取,以确保结果正确。 ::: info **LastDllError** 是 Windows 特有的。 ::: 请查阅 DLL 函数的文档以确定指示成功或失败的返回值。每当返回失败代码时,应用程序应立即检查 **LastDllError** 属性。 ### 示例 以下代码使用无效参数调用 DLL 函数以使调用失败。调用后的代码检查返回值,然后显示 **Err** 对象的 **LastDllError** 属性以揭示操作系统错误代码。 ```vb Private Declare PtrSafe Function SQLCancel Lib "ODBC32.dll" _ (ByVal hstmt As LongPtr) As Integer Private Sub Demo() Dim retVal As Integer ' Call with invalid handle. retVal = SQLCancel(0) If retVal = -2 Then ' Display the underlying OS error code. MsgBox "Error code is: " & Err.LastDllError End If End Sub ``` ### 另请参阅 * [LastHresult](/official/Reference/VBA/ErrObject/LastHresult) 属性 * [Number](/official/Reference/VBA/ErrObject/Number) 属性 --- --- url: /en/official/Reference/VBA/ErrObject/LastHresult.md --- # LastHresult Returns the last **HRESULT** returned from a COM object method call. Read-only. Syntax: **Err**.**LastHresult** **LastHresult** allows examination of return values from COM object method calls that do not necessarily trigger an error in the runtime. Negative HRESULT values correspond to failures and are the ones that raise a run-time error inside twinBASIC, which can then be captured through the **Err** object. Positive HRESULT values, which indicate success or non-failure status, do not raise an error and so do not interrupt normal program flow. To inspect both success and non-failure status codes, read **LastHresult** immediately after the object method call; subsequent calls may overwrite its value. ### Example ```vb ' Assume comObject exposes a method whose HRESULT contains status information. Sub CheckHresult() comObject.SomeMethod Dim status As Long status = Err.LastHresult If status > 0 Then ' Handle a non-failure HRESULT (success with status). End If End Sub ``` ### See Also * [ReturnHResult](/en/official/Reference/VBA/ErrObject/ReturnHResult) property * [LastDllError](/en/official/Reference/VBA/ErrObject/LastDllError) property * [Number](/en/official/Reference/VBA/ErrObject/Number) property * [Raise](/en/official/Reference/VBA/ErrObject/Raise) method --- --- url: /zh/official/Reference/VBA/ErrObject/LastHresult.md --- # LastHresult 返回从 COM 对象方法调用返回的最后一个 **HRESULT**。只读。 语法:**Err**.**LastHresult** **LastHresult** 允许检查 COM 对象方法调用的返回值,这些返回值不一定在运行时触发错误。负的 HRESULT 值对应于失败,会在 twinBASIC 内部引发运行时错误,然后可以通过 **Err** 对象捕获。正的 HRESULT 值表示成功或非失败状态,不会引发错误,因此不会中断正常程序流程。 要检查成功和非失败状态代码,请在对象方法调用之后立即读取 **LastHresult**;后续调用可能会覆盖其值。 ### 示例 ```vb ' Assume comObject exposes a method whose HRESULT contains status information. Sub CheckHresult() comObject.SomeMethod Dim status As Long status = Err.LastHresult If status > 0 Then ' Handle a non-failure HRESULT (success with status). End If End Sub ``` ### 另请参阅 * [ReturnHResult](/official/Reference/VBA/ErrObject/ReturnHResult) 属性 * [LastDllError](/official/Reference/VBA/ErrObject/LastDllError) 属性 * [Number](/official/Reference/VBA/ErrObject/Number) 属性 * [Raise](/official/Reference/VBA/ErrObject/Raise) 方法 --- --- url: /en/official/Reference/VBA/Information/LBound.md --- # LBound Returns a **Long** containing the smallest available subscript for the indicated dimension of an array. Syntax: **LBound(** *arrayname* \[ **,** *dimension* ] **)** *arrayname* : *required* The name of the array variable; follows standard variable naming conventions. *dimension* : *optional* A **Long** indicating which dimension's lower bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If *dimension* is omitted, 1 is assumed. **LBound** is used together with [**UBound**](/en/official/Reference/VBA/Information/UBound) to determine the size of an array. For an array `Dim A(1 To 100, 0 To 3, -3 To 4)`, **LBound** returns: | Statement | Return value | |-----------|--------------| | `LBound(A, 1)` | 1 | | `LBound(A, 2)` | 0 | | `LBound(A, 3)` | -3 | The default lower bound for any dimension is either 0 or 1, depending on the **Option Base** setting. Arrays created with the [**Array**](/en/official/Reference/Core/Array) function are zero-based regardless of **Option Base**. Arrays whose dimensions are set with the **To** clause in **Dim**, **Private**, **Public**, **ReDim**, or **Static** can have any integer lower bound. ### Example This example uses **LBound** to return the smallest available subscript for the indicated dimension of an array. ```vb Dim Lower As Long Dim MyArray(1 To 10, 5 To 15, 10 To 20) ' Multidimensional array. Dim AnyArray(10) Lower = LBound(MyArray, 1) ' Returns 1. Lower = LBound(MyArray, 3) ' Returns 10. Lower = LBound(AnyArray) ' Returns 0 or 1, per Option Base. ``` ### See Also * [UBound](/en/official/Reference/VBA/Information/UBound) function * [IsArray](/en/official/Reference/VBA/Information/IsArray), [IsArrayInitialized](/en/official/Reference/VBA/Information/IsArrayInitialized) functions --- --- url: /zh/official/Reference/VBA/Information/LBound.md --- # LBound 返回一个**Long**,包含数组指定维度的最小可用下标。 语法:**LBound(** *arrayname* \[ **,** *dimension* ] **)** *arrayname* : *必需* 数组变量的名称;遵循标准变量命名约定。 *dimension* : *可选* **Long**,指示返回哪个维度的下界。1表示第一维,2表示第二维,以此类推。如果省略*dimension*,则假定为1。 **LBound**与[**UBound**](/official/Reference/VBA/Information/UBound)一起用于确定数组的大小。 对于数组`Dim A(1 To 100, 0 To 3, -3 To 4)`,**LBound**返回: | 语句 | 返回值 | |------|--------| | `LBound(A, 1)` | 1 | | `LBound(A, 2)` | 0 | | `LBound(A, 3)` | -3 | 任何维度的默认下界为0或1,取决于**Option Base**设置。使用[**Array**](/official/Reference/Core/Array)函数创建的数组无论**Option Base**如何,下界都为零。使用**Dim**、**Private**、**Public**、**ReDim**或**Static**中的**To**子句设置维度的数组可以具有任何整数下界。 ### 示例 本示例使用**LBound**返回数组指定维度的最小可用下标。 ```vb Dim Lower As Long Dim MyArray(1 To 10, 5 To 15, 10 To 20) ' Multidimensional array. Dim AnyArray(10) Lower = LBound(MyArray, 1) ' Returns 1. Lower = LBound(MyArray, 3) ' Returns 10. Lower = LBound(AnyArray) ' Returns 0 or 1, per Option Base. ``` ### 另请参阅 * [UBound](/official/Reference/VBA/Information/UBound)函数 * [IsArray](/official/Reference/VBA/Information/IsArray)、[IsArrayInitialized](/official/Reference/VBA/Information/IsArrayInitialized)函数 --- --- url: /zh/official/Reference/Core/LBound.md --- # LBound 函数 lbound 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/LBound.md --- # LBound Function Documentation for the lbound keyword is not yet available. --- --- url: /en/official/Reference/VBA/Strings/LCase.md --- # LCase Returns a **String** that has been converted to lowercase. Syntax: **LCase$(** *string* **)**, **LCase(** *string* **)** *string* : *required* Any valid string expression. If *string* contains **Null**, **Null** is returned. The `$`-suffixed form returns a **String**; the unsuffixed form returns a **Variant** (**String**). Only uppercase letters are converted to lowercase; all lowercase letters and nonletter characters remain unchanged. ### Example This example uses the **LCase** function to return a lowercase version of a string. ```vb Dim UpperCase, LowerCase UpperCase = "Hello World 1234" ' String to convert. LowerCase = LCase(UpperCase) ' Returns "hello world 1234". ``` ### See Also * [StrConv](/en/official/Reference/VBA/Strings/StrConv), [UCase](/en/official/Reference/VBA/Strings/UCase) functions --- --- url: /zh/official/Reference/VBA/Strings/LCase.md --- # LCase 返回已转换为小写的**String**。 语法:**LCase$(** *string* **)**, **LCase(** *string* **)** *string* : *必需* 任意有效的字符串表达式。如果*string*包含**Null**,则返回**Null**。 带`$`后缀的形式返回**String**;不带后缀的形式返回**Variant**(**String**)。 仅大写字母被转换为小写;所有小写字母和非字母字符保持不变。 ### 示例 本示例使用**LCase**函数返回字符串的小写版本。 ```vb Dim UpperCase, LowerCase UpperCase = "Hello World 1234" ' String to convert. LowerCase = LCase(UpperCase) ' Returns "hello world 1234". ``` ### 另请参阅 * [StrConv](/official/Reference/VBA/Strings/StrConv)、[UCase](/official/Reference/VBA/Strings/UCase)函数 --- --- url: /en/official/Reference/VBA/Strings/Left.md --- # Left, LeftB Returns a **String** containing a specified number of characters from the left side of a string. Syntax: * **Left$(** *string*, *length* **)**, **Left(** *string*, *length* **)** * **LeftB$(** *string*, *length* **)**, **LeftB(** *string*, *length* **)** *string* : *required* String expression from which the leftmost characters are returned. If *string* contains **Null**, **Null** is returned. *length* : *required* **Variant** (**Long**). Numeric expression indicating how many characters to return. If 0, a zero-length string (`""`) is returned. If greater than or equal to the number of characters in *string*, the entire string is returned. The `$`-suffixed forms return a **String**; the unsuffixed forms return a **Variant** (**String**). To determine the number of characters in *string*, use the [**Len**](/en/official/Reference/VBA/Strings/Len) function. ::: info Use the **LeftB** function with byte data contained in a string. Instead of specifying the number of characters to return, *length* specifies the number of bytes. ::: ### Example This example uses the **Left** function to return a specified number of characters from the left side of a string. ```vb Dim AnyString, MyStr AnyString = "Hello World" ' Define string. MyStr = Left(AnyString, 1) ' Returns "H". MyStr = Left(AnyString, 7) ' Returns "Hello W". MyStr = Left(AnyString, 20) ' Returns "Hello World". ``` ### See Also * [Len](/en/official/Reference/VBA/Strings/Len), [Mid](/en/official/Reference/VBA/Strings/Mid), [Right](/en/official/Reference/VBA/Strings/Right) functions --- --- url: /zh/official/Reference/VBA/Strings/Left.md --- # Left, LeftB 返回一个**String**,包含从字符串左侧开始的指定数量的字符。 语法: * **Left$(** *string*, *length* **)**, **Left(** *string*, *length* **)** * **LeftB$(** *string*, *length* **)**, **LeftB(** *string*, *length* **)** *string* : *必需* 从中返回最左侧字符的字符串表达式。如果*string*包含**Null**,则返回**Null**。 *length* : *必需* **Variant**(**Long**)。数值表达式,指示要返回的字符数。如果为0,则返回零长度字符串(`""`)。如果大于或等于*string*中的字符数,则返回整个字符串。 带`$`后缀的形式返回**String**;不带后缀的形式返回**Variant**(**String**)。 要确定*string*中的字符数,请使用[**Len**](/official/Reference/VBA/Strings/Len)函数。 ::: info 使用**LeftB**函数处理字符串中包含的字节数据。*length*指定的是字节数而非字符数。 ::: ### 示例 本示例使用**Left**函数从字符串左侧返回指定数量的字符。 ```vb Dim AnyString, MyStr AnyString = "Hello World" ' Define string. MyStr = Left(AnyString, 1) ' Returns "H". MyStr = Left(AnyString, 7) ' Returns "Hello W". MyStr = Left(AnyString, 20) ' Returns "Hello World". ``` ### 另请参阅 * [Len](/official/Reference/VBA/Strings/Len)、[Mid](/official/Reference/VBA/Strings/Mid)、[Right](/official/Reference/VBA/Strings/Right)函数 --- --- url: /en/official/Reference/VBA/Strings/Len.md --- # Len, LenB Returns a **Long** containing the number of characters in a string or the number of bytes required to store a variable. Syntax: * **Len(** *string* **)**, **Len(** *varname* **)** * **LenB(** *string* **)**, **LenB(** *varname* **)** *string* : Any valid string expression. If *string* contains **Null**, **Null** is returned. *varname* : Any valid variable name. If *varname* contains **Null**, **Null** is returned. If *varname* is a **Variant**, **Len** treats it the same as a **String** and always returns the number of characters it contains. One (and only one) of the two possible arguments must be specified. With user-defined types, **Len** returns the size as it will be written to the file. ::: info Use the **LenB** function with byte data contained in a string, as in double-byte character set (DBCS) languages. Instead of returning the number of characters in a string, **LenB** returns the number of bytes used to represent that string. With user-defined types, **LenB** returns the in-memory size, including any padding between elements. ::: ::: info **Len** may not be able to determine the actual number of storage bytes required when used with variable-length strings in user-defined data types. ::: ### Example This example uses **Len** to return the number of characters in a string or the number of bytes required to store a variable. The `Type...End Type` block defining `CustomerRecord` must be preceded by the keyword **Private** if it appears in a class module. In a standard module, a **Type** statement can be **Public**. ```vb Type CustomerRecord ' Define user-defined type. ID As Integer ' Place this definition in a Name As String * 10 ' standard module. Address As String * 30 End Type Dim Customer As CustomerRecord ' Declare variables. Dim MyInt As Integer, MyCur As Currency Dim MyString, MyLen MyString = "Hello World" ' Initialize variable. MyLen = Len(MyInt) ' Returns 2. MyLen = Len(Customer) ' Returns 42. MyLen = Len(MyString) ' Returns 11. MyLen = Len(MyCur) ' Returns 8. ``` ### See Also * [Left](/en/official/Reference/VBA/Strings/Left), [Mid](/en/official/Reference/VBA/Strings/Mid), [Right](/en/official/Reference/VBA/Strings/Right) functions --- --- url: /zh/official/Reference/VBA/Strings/Len.md --- # Len, LenB 返回一个**Long**,包含字符串中的字符数或存储变量所需的字节数。 语法: * **Len(** *string* **)**, **Len(** *varname* **)** * **LenB(** *string* **)**, **LenB(** *varname* **)** *string* : 任意有效的字符串表达式。如果*string*包含**Null**,则返回**Null**。 *varname* : 任意有效的变量名。如果*varname*包含**Null**,则返回**Null**。如果*varname*是**Variant**,**Len**将其视为**String**,始终返回其包含的字符数。 必须指定两个可能参数中的一个(且仅一个)。对于用户定义类型,**Len**返回写入文件时的大小。 ::: info 使用**LenB**函数处理字符串中包含的字节数据,如双字节字符集(DBCS)语言。**LenB**不返回字符串中的字符数,而是返回用于表示该字符串的字节数。对于用户定义类型,**LenB**返回内存中的大小,包括元素之间的任何填充。 ::: ::: info 当在用户定义数据类型中使用可变长度字符串时,**Len**可能无法确定所需的实际存储字节数。 ::: ### 示例 本示例使用**Len**返回字符串中的字符数或存储变量所需的字节数。如果在类模块中出现,定义`CustomerRecord`的`Type...End Type`块前面必须加上**Private**关键字。在标准模块中,**Type**语句可以是**Public**。 ```vb Type CustomerRecord ' Define user-defined type. ID As Integer ' Place this definition in a Name As String * 10 ' standard module. Address As String * 30 End Type Dim Customer As CustomerRecord ' Declare variables. Dim MyInt As Integer, MyCur As Currency Dim MyString, MyLen MyString = "Hello World" ' Initialize variable. MyLen = Len(MyInt) ' Returns 2. MyLen = Len(Customer) ' Returns 42. MyLen = Len(MyString) ' Returns 11. MyLen = Len(MyCur) ' Returns 8. ``` ### 另请参阅 * [Left](/official/Reference/VBA/Strings/Left)、[Mid](/official/Reference/VBA/Strings/Mid)、[Right](/official/Reference/VBA/Strings/Right)函数 --- --- url: /en/official/Reference/Core/Let.md --- # Let Assigns the value of an expression to a variable or property. Syntax: > \[ **Let** ] *varname* **=** *expression* **Let** : *optional* Explicit use of the **Let** keyword is a matter of style; it is usually omitted. *varname* : Name of the variable or property; follows standard variable naming conventions. *expression* : Value assigned to the variable or property. A value expression can be assigned to a variable or property only if it is of a data type that is compatible with the variable. String expressions cannot be assigned to numeric variables, and numeric expressions cannot be assigned to string variables. Such an assignment raises an error at compile time. **Variant** variables can be assigned to either string or numeric expressions. However, the reverse is not always true. Any **Variant** except a **Null** can be assigned to a string variable, but only a **Variant** whose value can be interpreted as a number can be assigned to a numeric variable. Use the **IsNumeric** function to determine if the **Variant** can be converted to a number. Assigning an expression of one numeric type to a variable of a different numeric type coerces the value of the expression into the numeric type of the resulting variable. **Let** statements can be used to assign one record variable to another only when both variables are of the same user-defined type. Use the **LSet** statement to assign record variables of different user-defined types. Use the [**Set**](/en/official/Reference/Core/Set) statement to assign object references to variables. ### Example This example assigns the values of expressions to variables by using the explicit **Let** statement. ```vb Dim MyStr, MyInt ' The following variable assignments use the Let statement. Let MyStr = "Hello World" Let MyInt = 5 ``` The following are the same assignments without the **Let** statement. ```vb Dim MyStr, MyInt MyStr = "Hello World" MyInt = 5 ``` ### See Also * [**Set** statement](/en/official/Reference/Core/Set) * [**LSet** statement](/en/official/Reference/Core/LSet) * [**Property** statement](/en/official/Reference/Core/Property) --- --- url: /zh/official/Reference/Core/Let.md --- # Let 将表达式的值赋给变量或属性。 语法: > \[ **Let** ] *varname* **=** *expression* **Let** : *可选* 显式使用 **Let** 关键字是风格问题;通常省略。 *varname* : 变量或属性的名称;遵循标准变量命名约定。 *expression* : 赋给变量或属性的值。 值表达式只有在与变量数据类型兼容时才能赋给变量或属性。字符串表达式不能赋给数值变量,数值表达式不能赋给字符串变量。此类赋值在编译时引发错误。 **Variant** 变量可以赋给字符串或数值表达式。但反过来并不总是成立。除 **Null** 外的任何 **Variant** 都可以赋给字符串变量,但只有值可以解释为数字的 **Variant** 才能赋给数值变量。使用 **IsNumeric** 函数确定 **Variant** 是否可以转换为数字。 将一种数值类型的表达式赋给不同数值类型的变量时,表达式的值被强制转换为结果变量的数值类型。 **Let** 语句只能在两个变量为相同用户自定义类型时用于将一个记录变量赋给另一个。使用 **LSet** 语句赋值不同用户自定义类型的记录变量。使用 [**Set**](/official/Reference/Core/Set) 语句将对象引用赋给变量。 ### 示例 本示例使用显式 **Let** 语句将表达式的值赋给变量。 ```vb Dim MyStr, MyInt ' The following variable assignments use the Let statement. Let MyStr = "Hello World" Let MyInt = 5 ``` 以下是不使用 **Let** 语句的相同赋值。 ```vb Dim MyStr, MyInt MyStr = "Hello World" MyInt = 5 ``` ### 另请参阅 * [**Set** 语句](/official/Reference/Core/Set) * [**LSet** 语句](/official/Reference/Core/LSet) * [**Property** 语句](/official/Reference/Core/Property) --- --- url: /en/official/Documentation/Fixes.md --- # Library Patches Several third-party libraries carry in-tree modifications. `book/lib/paged.browser.js` is a patched copy of paged.js v0.4.3 (MIT); the thirteen `fast-*.mjs` files there are side-effecting shims applied to pdf-lib's live exports before each PDF process phase; and `builder/scripts/patch-dagre.mjs` is a `postinstall` hook that rewrites mermaid's bundled dagre adapter to fix per-cluster layout. This section documents every change: what the upstream behaviour was, why it was unsuitable for the build pipeline, and what was changed. ## Sub-pages * [Paged.js Patches](/en/official/Documentation/Fixes-PagedJS) --- changes to `book/lib/paged.browser.js`: the synchronous execution chain, hook dispatch fast-paths, DOM lookup optimizations, layout correctness fixes, and miscellaneous headless-specific changes. * [pdf-lib Patches](/en/official/Documentation/Fixes-PDFLib) --- the thirteen `fast-*.mjs` shims and `parallel-deflate.mjs` that retune pdf-lib's parser, object model, and serializer for the process phase. * [Mermaid Dagre Patches](/en/official/Documentation/Fixes-Dagre) --- five patches to `node_modules/mermaid/dist/chunks/mermaid.esm/dagre-ZXKKJJHT.mjs` that make `direction LR` subgraphs work correctly when they have cross-cluster edges or no internal edges at all. --- --- url: /en/official/Reference/Core/Like.md --- # Like operator Used to compare a string against a wildcard pattern. Syntax: > *result* **=** *string* **Like** *pattern* *result* : Any numeric variable. *string* : Any string expression. *pattern* : Any string expression conforming to the pattern-matching conventions described below. If *string* matches *pattern*, *result* is **True**; if there is no match, *result* is **False**. If either *string* or *pattern* is **Null**, *result* is **Null**. The behavior of the **Like** operator depends on the [**Option Compare**](/en/official/Reference/Core/Option) statement. The default for each module is **Option Compare Binary**, which compares characters by their internal binary representation (case-sensitive, ordinal). **Option Compare Text** performs a case-insensitive, locale-sensitive comparison. For example, under **Option Compare Binary** a typical sort order is: `A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø` Under **Option Compare Text** the same characters compare equal up to case and accent: `(A=a) < (À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)` The pattern-matching syntax supports wildcards, character lists, and character ranges. The following characters in *pattern* have special meaning: | In *pattern* | Matches in *string* | |:-------------------|:-----------------------------------------------------| | `?` | Any single character. | | `*` | Zero or more characters. | | `#` | Any single digit (`0`--`9`). | | `[`*charlist*`]` | Any single character in *charlist*. | | `[!`*charlist*`]` | Any single character *not* in *charlist*. | A group of one or more characters (*charlist*) enclosed in brackets can match any single character in *string* and may include almost any character code, including digits. ::: info To match the special characters left bracket (`[`), question mark (`?`), number sign (`#`), or asterisk (`*`), enclose them in brackets. The right bracket (`]`) cannot be used inside a group to match itself, but it can be used outside a group as a literal character. ::: A hyphen (`-`) inside *charlist* separates the upper and lower bounds of a character range --- for example, `[A-Z]` matches any uppercase letter. Multiple ranges are placed adjacently inside the same brackets, with no delimiter. The meaning of a range depends on the active **Option Compare** mode and the system locale. Under **Option Compare Binary** the range `[A-E]` matches `A`, `B`, `E`; under **Option Compare Text** it matches `A`, `a`, `À`, `à`, `B`, `b`, `E`, `e` (but not `Ê`/`ê`, which sort after the basic letters). Other rules: * An exclamation point (`!`) at the beginning of *charlist* negates the class. Outside brackets, `!` matches itself. * A hyphen (`-`) at the start (after `!`, if present) or end of *charlist* matches itself; elsewhere it identifies a range. * Ranges must be specified low-to-high: `[A-Z]` is valid; `[Z-A]` is not. * The character sequence `[]` is treated as a zero-length string. In some languages a single character represents two graphemes (e.g. `æ` for `a`+`e`). When the system locale specifies such a language, **Like** treats the single character and the equivalent 2-character sequence as interchangeable, both as `*string*` and inside a *charlist*. ### Example ```vb Dim MyCheck MyCheck = "aBBBa" Like "a*a" ' Returns True. MyCheck = "F" Like "[A-Z]" ' Returns True. MyCheck = "F" Like "[!A-Z]" ' Returns False. MyCheck = "a2a" Like "a#a" ' Returns True. MyCheck = "aM5b" Like "a[L-P]#[!c-e]" ' Returns True. MyCheck = "BAT123khg" Like "B?T*" ' Returns True. MyCheck = "CAT123khg" Like "B?T*" ' Returns False. MyCheck = "ab" Like "a*b" ' Returns True. MyCheck = "a*b" Like "a[*]b" ' Returns True (literal asterisk). MyCheck = "axxxxxb" Like "a[*]b" ' Returns False. MyCheck = "a[xyz" Like "a[[]*" ' Returns True. ``` ### See Also * [Comparison operators](/en/official/Reference/Core/Comparison-Operators) * [**Option** statement](/en/official/Reference/Core/Option) * [**InStr** function](/en/official/Reference/VBA/Strings/InStr) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Like.md --- # Like 运算符 用于将字符串与通配符模式进行比较。 语法: > *result* **=** *string* **Like** *pattern* *result* : 任意数值变量。 *string* : 任意字符串表达式。 *pattern* : 符合以下描述的模式匹配约定的任意字符串表达式。 如果 *string* 匹配 *pattern*,*result* 为 **True**;如果不匹配,*result* 为 **False**。如果 *string* 或 *pattern* 为 **Null**,则 *result* 为 **Null**。 **Like** 运算符的行为取决于 [**Option Compare**](/official/Reference/Core/Option) 语句。每个模块默认为 **Option Compare Binary**,按内部二进制表示比较字符(区分大小写,按序比较)。**Option Compare Text** 执行不区分大小写、受区域设置影响的比较。 例如,在 **Option Compare Binary** 下,典型的排序顺序为: `A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø` 在 **Option Compare Text** 下,相同字符在不区分大小写和重音时比较相等: `(A=a) < (À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)` 模式匹配语法支持通配符、字符列表和字符范围。*pattern* 中的以下字符具有特殊含义: | *pattern* 中的 | *string* 中的匹配 | |:-------------------|:-----------------------------------------------------| | `?` | 任意单个字符。 | | `*` | 零个或多个字符。 | | `#` | 任意单个数字(`0`--`9`)。 | | `[`*charlist*`]` | *charlist* 中的任意单个字符。 | | `[!`*charlist*`]` | 不在 *charlist* 中的任意单个字符。 | 方括号中包含的一个或多个字符组(*charlist*)可以匹配 *string* 中的任意单个字符,几乎可以包含任何字符代码,包括数字。 ::: info 要匹配特殊字符左方括号(`[`)、问号(`?`)、数字符号(`#`)或星号(`*`),请将它们括在方括号中。右方括号(`]`)不能在组内用于匹配自身,但可以在组外作为字面字符使用。 ::: *charlist* 中的连字符(`-`)分隔字符范围的上界和下界——例如,`[A-Z]` 匹配任何大写字母。多个范围放置在相同方括号内,没有分隔符。 范围的含义取决于活动的 **Option Compare** 模式和系统区域设置。在 **Option Compare Binary** 下,范围 `[A-E]` 匹配 `A`、`B`、`E`;在 **Option Compare Text** 下,它匹配 `A`、`a`、`À`、`à`、`B`、`b`、`E`、`e`(但不匹配 `Ê`/`ê`,它们排在基本字母之后)。 其他规则: * *charlist* 开头的感叹号(`!`)取反字符类。方括号外,`!` 匹配自身。 * *charlist* 开头(如果有 `!` 则在其后)或末尾的连字符(`-`)匹配自身;其他位置标识范围。 * 范围必须从低到高指定:`[A-Z]` 有效;`[Z-A]` 无效。 * 字符序列 `[]` 被视为零长度字符串。 在某些语言中,单个字符表示两个字位(如 `æ` 表示 `a`+`e`)。当系统区域设置指定此类语言时,**Like** 将单个字符和等效的2字符序列视为可互换的,无论作为 *string* 还是在 *charlist* 中。 ### 示例 ```vb Dim MyCheck MyCheck = "aBBBa" Like "a*a" ' Returns True. MyCheck = "F" Like "[A-Z]" ' Returns True. MyCheck = "F" Like "[!A-Z]" ' Returns False. MyCheck = "a2a" Like "a#a" ' Returns True. MyCheck = "aM5b" Like "a[L-P]#[!c-e]" ' Returns True. MyCheck = "BAT123khg" Like "B?T*" ' Returns True. MyCheck = "CAT123khg" Like "B?T*" ' Returns False. MyCheck = "ab" Like "a*b" ' Returns True. MyCheck = "a*b" Like "a[*]b" ' Returns True (literal asterisk). MyCheck = "axxxxxb" Like "a[*]b" ' Returns False. MyCheck = "a[xyz" Like "a[[]*" ' Returns True. ``` ### 另请参阅 * [比较运算符](/official/Reference/Core/Comparison-Operators) * [**Option** 语句](/official/Reference/Core/Option) * [**InStr** 函数](/official/Reference/VBA/Strings/InStr) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Reference/CustomControls/Styles/Line.md --- # Line class A single stroke used to draw a grid line, divider, or resizer bar --- simpler than a full [**Border**](/en/official/Reference/CustomControls/Styles/Borders#border-class) (no blend-with-background flag, no surrounding **Elements** array). Accessed as [**WaynesGrid.VerticalLineOptions**](/en/official/Reference/CustomControls/WaynesGrid/#verticallineoptions), [**HorizontalLineOptions**](/en/official/Reference/CustomControls/WaynesGrid/#horizontallineoptions), and [**ResizerBar**](/en/official/Reference/CustomControls/WaynesGrid/#resizerbar). ```vb With WaynesGrid1.VerticalLineOptions .StrokeSize = 1 .Fill.ColorPoints.SetSolidColor &HD0D0D0 ' pale grey End With ``` ## Properties ### Fill The [**Fill**](/en/official/Reference/CustomControls/Styles/Fill) that supplies the colour or gradient used to draw the line. ### StrokeSize The stroke thickness in pixels. [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount). Default: 0 (the line is not drawn until a non-zero size is assigned). ## Events ### OnChanged Raised when [**StrokeSize**](#strokesize) or [**Fill**](#fill) is assigned, or when the contained [**Fill**](#fill) raises its own **OnChanged**. --- --- url: /en/official/Reference/VB/Line.md --- # Line class A **Line** is a windowless lightweight control that draws a single straight line segment from one point to another on its container. It exists purely for visual presentation --- to divide regions of a form, underline a heading, draw a leader to an annotation --- and has no interactive elements of its own: no mouse events, no focus, no caption. A **Line** is positioned by its two endpoints, [**X1**](#x1) / [**Y1**](#y1) and [**X2**](#x2) / [**Y2**](#y2), rather than by a `Left` / `Top` / `Width` / `Height` rectangle. The default property is [**Visible**](#visible) and the default event is [**Initialize**](#initialize). ```vb Private Sub Form_Load() linUnderHeading.X1 = 120 : linUnderHeading.Y1 = 320 linUnderHeading.X2 = 4800 : linUnderHeading.Y2 = 320 linUnderHeading.BorderColor = vbBlue linUnderHeading.BorderWidth = 2 End Sub ``` ## Endpoints [**X1**](#x1) / [**Y1**](#y1) is one endpoint of the line; [**X2**](#x2) / [**Y2**](#y2) is the other. Coordinates are in the container's **ScaleMode** units (twips by default) and are measured from the top-left corner of the container's client area. The line is drawn between the two points regardless of which is "earlier" --- swapping the endpoints does not change the result. The control has no `Width` or `Height` of its own; the bounding rectangle is derived from the two endpoints. Resizing a **Line** at design time moves whichever endpoint is being dragged. ## Pen The line is drawn with a Win32 GDI pen whose appearance is controlled by: * [**BorderColor**](#bordercolor) -- the colour of the pen (defaults to the system window-text colour). * [**BorderWidth**](#borderwidth) -- the pen width in pixels (default `1`). * [**BorderStyle**](#borderstyle) -- the pen pattern, as a member of [**BorderStyleConstants**](/en/official/Reference/VBRUN/Constants/BorderStyleConstants): **vbTransparent** (0), **vbBSSolid** (1, default), **vbBSDash** (2), **vbBSDot** (3), **vbBSDashDot** (4), **vbBSDashDotDot** (5), or **vbBSInsideSolid** (6). GDI applies a hard limitation here: when [**BorderWidth**](#borderwidth) is greater than `1`, the OS forces a solid pen even if [**BorderStyle**](#borderstyle) requests a dashed or dotted pattern. Use width `1` if the pattern matters. ## Draw mode [**DrawMode**](#drawmode) selects the raster operation that combines the pen with the destination pixels. A member of [**DrawModeConstants**](/en/official/Reference/VBRUN/Constants/DrawModeConstants): **vbCopyPen** (default --- opaque drawing) or one of the XOR / AND / NOT / merge variants. Non-default modes are mainly useful for "rubber-band" feedback drawn over an existing background --- the same XOR applied twice cancels itself out, restoring the original pixels. ## No interaction Unlike most other controls, a **Line** does not raise mouse, keyboard, or focus events of any kind, and has no [**Caption**](/en/official/Reference/VB/Label/#caption), [**Enabled**](/en/official/Reference/VB/Label/#enabled), or **ToolTipText**. To make a region clickable, place a transparent [**Label**](/en/official/Reference/VB/Label/) on top. ## Properties ### BorderColor The colour of the line, as an **OLE\_COLOR**. Defaults to the system window-text colour. ### BorderStyle The pen pattern. A member of [**BorderStyleConstants**](/en/official/Reference/VBRUN/Constants/BorderStyleConstants): **vbTransparent** (0), **vbBSSolid** (1, default), **vbBSDash** (2), **vbBSDot** (3), **vbBSDashDot** (4), **vbBSDashDotDot** (5), or **vbBSInsideSolid** (6). Forced to **vbBSSolid** by Win32 whenever [**BorderWidth**](#borderwidth) is greater than `1`. ### BorderWidth The pen width, in pixels. **Long**, default `1`. Widths greater than `1` ignore [**BorderStyle**](#borderstyle) and always draw solid. ### Container The control that hosts this line --- typically the form, a [**Frame**](/en/official/Reference/VB/Frame/), or a **UserControl**. Read with **Get**, change with **Set**. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control. The **Line** shares the **vbShape** constant with the [**Shape**](/en/official/Reference/VB/Shape/) control --- both are windowless, points-based geometric primitives with no dedicated control-type identifier. ### DrawMode The raster operation that the line drawing applies when combining the pen with the destination. A member of [**DrawModeConstants**](/en/official/Reference/VBRUN/Constants/DrawModeConstants): **vbCopyPen** (default) is normal opaque drawing; other values produce XOR, AND, NOT, and other pixel-mixing effects. ### Index When the line is part of a control array, the **Long** zero-based index of this instance within the array. Reading **Index** on a non-array instance raises run-time error 343 (*Object not an array*). Read-only at run time. ### Name The unique design-time name of the control on its parent. Read-only at run time. ### Parent A reference to the [**Form**](/en/official/Reference/VB/Form/) (or **UserControl**) that ultimately contains the line. Read-only. ### Tag A free-form **String** the application can use to associate custom data with the line. Ignored by the framework. ### Visible Whether the line is shown. **Boolean**, default **True**. **Default property.** ### X1 The horizontal position of the first endpoint, in the container's **ScaleMode** units. **Double**. ### X2 The horizontal position of the second endpoint, in the container's **ScaleMode** units. **Double**. ### Y1 The vertical position of the first endpoint, in the container's **ScaleMode** units. **Double**. ### Y2 The vertical position of the second endpoint, in the container's **ScaleMode** units. **Double**. ## Methods ### ZOrder Brings the line to the front or back of the windowless-sibling stack within its container. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Initialize Raised once, after the line has been connected to its container's paint cycle but before it is first painted. **Default event.** Syntax: *object*\_**Initialize**( ) --- --- url: /zh/official/Reference/CustomControls/Styles/Line.md --- # Line 类 用于绘制网格线、分隔线或调整条的单条笔触——比完整 [**Border**](/official/Reference/CustomControls/Styles/Borders#border-class) 更简单(无背景混合标志、无包围 **Elements** 数组)。通过 [**WaynesGrid.VerticalLineOptions**](/official/Reference/CustomControls/WaynesGrid/#verticallineoptions)、[**HorizontalLineOptions**](/official/Reference/CustomControls/WaynesGrid/#horizontallineoptions) 和 [**ResizerBar**](/official/Reference/CustomControls/WaynesGrid/#resizerbar) 访问。 ```vb With WaynesGrid1.VerticalLineOptions .StrokeSize = 1 .Fill.ColorPoints.SetSolidColor &HD0D0D0 ' pale grey End With ``` ## 属性 ### Fill 提供用于绘制线条的颜色或渐变的 [**Fill**](/official/Reference/CustomControls/Styles/Fill)。 ### StrokeSize 笔触粗细(像素)。[**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount)。默认:0(在赋非零值之前不绘制线条)。 ## 事件 ### OnChanged [**StrokeSize**](#strokesize) 或 [**Fill**](#fill) 被赋值时,或包含的 [**Fill**](#fill) 触发其自身的 **OnChanged** 时触发。 --- --- url: /zh/official/Reference/VB/Line.md --- # Line 类 **Line**是无窗口轻量级控件,在其容器上从一个点到另一个点绘制单一直线段。它纯粹用于视觉呈现——分隔窗体区域、为标题加下划线、绘制注释引导线——没有自身的交互元素:没有鼠标事件、没有焦点、没有标题。 **Line**通过其两个端点[**X1**](#x1) / [**Y1**](#y1)和[**X2**](#x2) / [**Y2**](#y2)定位,而非`Left` / `Top` / `Width` / `Height`矩形。默认属性为[**Visible**](#visible),默认事件为[**Initialize**](#initialize)。 ```vb Private Sub Form_Load() linUnderHeading.X1 = 120 : linUnderHeading.Y1 = 320 linUnderHeading.X2 = 4800 : linUnderHeading.Y2 = 320 linUnderHeading.BorderColor = vbBlue linUnderHeading.BorderWidth = 2 End Sub ``` ## 端点 [**X1**](#x1) / [**Y1**](#y1)是直线的一个端点;[**X2**](#x2) / [**Y2**](#y2)是另一个端点。坐标以容器的**ScaleMode**单位(默认为缇)表示,从容器的客户区左上角测量。直线在两点之间绘制,无论哪个点"在前"——交换端点不改变结果。 控件没有自身的`Width`或`Height`;边界矩形由两个端点派生。在设计时调整**Line**大小会移动被拖动的端点。 ## 画笔 直线使用Win32 GDI画笔绘制,其外观由以下属性控制: * [**BorderColor**](#bordercolor)——画笔颜色(默认为系统窗口文本颜色)。 * [**BorderWidth**](#borderwidth)——画笔宽度,以像素为单位(默认`1`)。 * [**BorderStyle**](#borderstyle)——画笔模式,作为[**BorderStyleConstants**](/official/Reference/VBRUN/Constants/BorderStyleConstants)的成员:**vbTransparent** (0)、**vbBSSolid** (1, 默认)、**vbBSDash** (2)、**vbBSDot** (3)、**vbBSDashDot** (4)、**vbBSDashDotDot** (5)或**vbBSInsideSolid** (6)。 GDI在此有硬性限制:当[**BorderWidth**](#borderwidth)大于`1`时,即使[**BorderStyle**](#borderstyle)请求虚线或点线模式,操作系统也强制使用实线画笔。如果模式重要,请使用宽度`1`。 ## 绘制模式 [**DrawMode**](#drawmode)选择将画笔与目标像素组合的光栅操作。作为[**DrawModeConstants**](/official/Reference/VBRUN/Constants/DrawModeConstants)的成员:**vbCopyPen**(默认——不透明绘制)或XOR / AND / NOT / 合并变体之一。非默认模式主要用于在现有背景上绘制的"橡皮筋"反馈——两次应用相同的XOR会抵消自身,恢复原始像素。 ## 无交互 与大多数其他控件不同,**Line**不引发任何类型的鼠标、键盘或焦点事件,也没有[**Caption**](/official/Reference/VB/Label/#caption)、[**Enabled**](/official/Reference/VB/Label/#enabled)或**ToolTipText**。要使区域可点击,请在上面放置一个透明的[**Label**](/official/Reference/VB/Label/)。 ## 属性 ### BorderColor 线条颜色,类型为**OLE\_COLOR**。默认为系统窗口文本颜色。 ### BorderStyle 画笔模式。作为[**BorderStyleConstants**](/official/Reference/VBRUN/Constants/BorderStyleConstants)的成员:**vbTransparent** (0)、**vbBSSolid** (1, 默认)、**vbBSDash** (2)、**vbBSDot** (3)、**vbBSDashDot** (4)、**vbBSDashDotDot** (5)或**vbBSInsideSolid** (6)。当[**BorderWidth**](#borderwidth)大于`1`时被Win32强制为**vbBSSolid**。 ### BorderWidth 画笔宽度,以像素为单位。**Long**,默认`1`。大于`1`的宽度忽略[**BorderStyle**](#borderstyle)并始终绘制实线。 ### Container 承载此线条的控件——通常是窗体、[**Frame**](/official/Reference/VB/Frame/)或**UserControl**。使用**Get**读取,使用**Set**更改。 ### ControlType 标识此控件的只读[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值。**Line**与[**Shape**](/official/Reference/VB/Shape/)控件共享**vbShape**常量——两者都是无窗口、基于点的几何图元,没有专用的控件类型标识符。 ### DrawMode 线条绘制将画笔与目标组合时应用的光栅操作。作为[**DrawModeConstants**](/official/Reference/VBRUN/Constants/DrawModeConstants)的成员:**vbCopyPen**(默认)为正常不透明绘制;其他值产生XOR、AND、NOT和其他像素混合效果。 ### Index 当线条是控件数组的一部分时,此实例在数组中从0开始的**Long**索引。在非数组实例上读取**Index**会引发运行时错误343(*对象不是数组*)。运行时只读。 ### Name 控件在其父级上的唯一设计时名称。运行时只读。 ### Parent 对最终包含此线条的[**Form**](/official/Reference/VB/Form/)(或**UserControl**)的引用。只读。 ### Tag 应用程序可用于将自定义数据与线条关联的自由格式**String**。框架忽略。 ### Visible 线条是否显示。**Boolean**,默认**True**。**默认属性。** ### X1 第一个端点的水平位置,以容器的**ScaleMode**单位。**Double**。 ### X2 第二个端点的水平位置,以容器的**ScaleMode**单位。**Double**。 ### Y1 第一个端点的垂直位置,以容器的**ScaleMode**单位。**Double**。 ### Y2 第二个端点的垂直位置,以容器的**ScaleMode**单位。**Double**。 ## 方法 ### ZOrder 将线条移到其容器内无窗口同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront** (0, 默认)或**vbSendToBack** (1)。 ## 事件 ### Initialize 在线条连接到其容器的绘制周期后、首次绘制前引发一次。**默认事件。** 语法:*object*\_**Initialize**( ) --- --- url: /en/official/Reference/Core/Line-Input.md --- # Line Input # statement Reads a single line from an open sequential file and assigns it to a **String** variable. Syntax: > **Line Input** **#** *filenumber* **,** *varname* *filenumber* : Any valid file number. *varname* : Valid **Variant** or **String** variable name. Data read with **Line Input #** is usually written to a file with [**Print #**](/en/official/Reference/Core/Print). The **Line Input #** statement reads from a file one character at a time until it encounters a carriage return (**Chr**(13)) or carriage return-linefeed (**Chr**(13) + **Chr**(10)) sequence. Carriage return-linefeed sequences are skipped rather than appended to the character string. ### Example This example uses the **Line Input #** statement to read a line from a sequential file and assign it to a variable. This example assumes that `TESTFILE` is a text file with a few lines of sample data. ```vb Dim TextLine Open "TESTFILE" For Input As #1 ' Open file. Do While Not EOF(1) ' Loop until end of file. Line Input #1, TextLine ' Read line into variable. Debug.Print TextLine ' Print to the Immediate window. Loop Close #1 ' Close file. ``` ### See Also * [**Open** statement](/en/official/Reference/Core/Open) * [**Close** statement](/en/official/Reference/Core/Close) * [**Input #** statement](/en/official/Reference/Core/Input) * [**Print #** statement](/en/official/Reference/Core/Print) * [**Write #** statement](/en/official/Reference/Core/Write) * [**EOF** function](/en/official/Reference/VBA/FileSystem/EOF) --- --- url: /zh/official/Reference/Core/Line-Input.md --- # Line Input # 语句 从打开的顺序文件中读取一行并赋值给 **String** 变量。 语法: > **Line Input** **#** *filenumber* **,** *varname* *filenumber* : 任何有效的文件号。 *varname* : 有效的 **Variant** 或 **String** 变量名。 用 **Line Input #** 读取的数据通常用 [**Print #**](/official/Reference/Core/Print) 写入文件。 **Line Input #** 语句从文件中逐字符读取,直到遇到回车符(**Chr**(13))或回车换行序列(**Chr**(13) + **Chr**(10))。回车换行序列被跳过而非附加到字符串中。 ### 示例 本示例使用 **Line Input #** 语句从顺序文件读取一行并赋值给变量。本示例假设 `TESTFILE` 是包含几行示例数据的文本文件。 ```vb Dim TextLine Open "TESTFILE" For Input As #1 ' Open file. Do While Not EOF(1) ' Loop until end of file. Line Input #1, TextLine ' Read line into variable. Debug.Print TextLine ' Print to the Immediate window. Loop Close #1 ' Close file. ``` ### 另请参阅 * [**Open** 语句](/official/Reference/Core/Open) * [**Close** 语句](/official/Reference/Core/Close) * [**Input #** 语句](/official/Reference/Core/Input) * [**Print #** 语句](/official/Reference/Core/Print) * [**Write #** 语句](/official/Reference/Core/Write) * [**EOF** 函数](/official/Reference/VBA/FileSystem/EOF) --- --- url: /en/official/Features/Packages/Linked-Packages.md --- # Linked Packages In addition to the standard usage described so far in this section, a package may also be **linked**. When a package is linked, it is not embedded in the .twinproj file-- it is instead stored in a common location accessible to all projects. This has multiple benefits. Some packages are very large, so not storing a copy in every .twinproj file makes them easier to share. Additionally, it allows multiple projects to share the same files, at least in read-only form.\ While built in compiler packages are linked, this article concerns 3rd party packages. ## Downloading a package for the first time When you check the box for a package for the first time on the current machine, it is **Embedded** by default. You'll see a column with that name next to the package name: Uncheck the Embedded column and it will be converted to a linked package. A .twinpack file for the package is created in `%APPDATA%\Roaming\twinBASIC\packages`, where it can remain available across tB IDE updates. ## Adding a package that has been linked Once you've performed the steps above in one project, the linked package is available to all projects. You add the reference in the same way, through Available Packages, only now you'll be prompted to ask if you want the linked version already on your system, or to redownload it from TWINSERV: This prompt provides the versions of both, which allows for updating the package if desired. If you do choose to download it again, you'll need to uncheck Embed again to keep it as a linked package. When you do, you'll be prompted to confirm you want to overwrite the local linked copy with the version newly downloaded from the package server: ## Opening a project with missing linked package Sometimes you may want to open a .twinproj that refers to a linked package you do not currently have a copy of. If this happens, you'll see the standard missing reference message: And it's handled in the same way. **Uncheck the reference** -- "Fix" is not currently implemented. Then, go to the Available Packages tab and select the package-- and as described above, uncheck Embed to convert to a linked package. ## Manual management You can make packages available, delete them, back them up, etc, via the linked packages folder: `%APPDATA%\Roaming\twinBASIC\packages` If you copy a .twinpack file (or a .twinproj) to that location, it will be available as a linked package without needing to be downloaded from the package server. It does not need to exist on the server at all, allowing fully private, local linked packages. --- --- url: /en/packages/vbccr/text/linklabel.md description: >- LinkLabel Control - VBCCR Development Manual, complete API reference based on source code --- # LinkLabel Control Enhanced link label control, supporting hyperlink display and custom link collections. ## Enumerations ### LlbLinkBehaviorConstants | Constant | Value | Description | |----------|-------|-------------| | LlbLinkBehaviorSystemDefault | 0 | System default | | LlbLinkBehaviorAlwaysUnderline | 1 | Always underline | | LlbLinkBehaviorHoverUnderline | 2 | Underline on hover | | LlbLinkBehaviorNeverUnderline | 3 | Never underline | ### CCAppearanceConstants See common enumerations. ### CCBorderStyleConstants See common enumerations. ### CCBackStyleConstants See common enumerations. ### CCMousePointerConstants See common enumerations. ### CCVerticalAlignmentConstants See common enumerations. ### CCRightToLeftModeConstants See common enumerations. ## Properties ### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` The display text. ### ActiveLinkColor ```vb Property Get ActiveLinkColor() As OLE_COLOR Property Let ActiveLinkColor(ByVal Value As OLE_COLOR) ``` The active link color. ### LinkColor ```vb Property Get LinkColor() As OLE_COLOR Property Let LinkColor(ByVal Value As OLE_COLOR) ``` The link color. ### VisitedLinkColor ```vb Property Get VisitedLinkColor() As OLE_COLOR Property Let VisitedLinkColor(ByVal Value As OLE_COLOR) ``` The visited link color. ### DisabledLinkColor ```vb Property Get DisabledLinkColor() As OLE_COLOR Property Let DisabledLinkColor(ByVal Value As OLE_COLOR) ``` The disabled link color. ### LinkBehavior ```vb Property Get LinkBehavior() As LlbLinkBehaviorConstants Property Let LinkBehavior(ByVal Value As LlbLinkBehaviorConstants) ``` The link behavior style. ### Text ```vb Property Get Text() As String Property Let Text(ByVal Value As String) ``` The complete text content of the control, including link markup. ### Links ```vb Property Get Links() As LlbLinks ``` The link collection. ### AutoSize ```vb Property Get AutoSize() As Boolean Property Let AutoSize(ByVal Value As Boolean) ``` Whether to automatically resize to fit the content. ### BorderStyle ```vb Property Get BorderStyle() As CCBorderStyleConstants Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` The border style. See common enumerations. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` The background color. ### BackStyle ```vb Property Get BackStyle() As CCBackStyleConstants Property Let BackStyle(ByVal Value As CCBackStyleConstants) ``` The background style. See common enumerations. ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` The foreground color. ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` The font. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` The mouse pointer style. See common enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` The custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Whether mouse enter/leave tracking is enabled. ### WordWrap ```vb Property Get WordWrap() As Boolean Property Let WordWrap(ByVal Value As Boolean) ``` Whether text wraps automatically. ### UseMnemonic ```vb Property Get UseMnemonic() As Boolean Property Let UseMnemonic(ByVal Value As Boolean) ``` Whether the & character is interpreted as an accelerator prefix. ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` The right-to-left display direction. ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` The right-to-left mirrored layout. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` The right-to-left mode. See common enumerations. ### Appearance ```vb Property Get Appearance() As CCAppearanceConstants Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` The appearance style. See common enumerations. ### VerticalAlignment ```vb Property Get VerticalAlignment() As CCVerticalAlignmentConstants Property Let VerticalAlignment(ByVal Value As CCVerticalAlignmentConstants) ``` The vertical alignment. See common enumerations. ### hWnd ```vb Property Get hWnd() As LongPtr ``` The window handle. Read-only. ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` The tooltip text. ### Name ```vb Property Get Name() As String ``` The control name. Read-only. ### Tag ```vb Property Get Tag() As Variant Property Let Tag(ByVal Value As Variant) Property Set Tag(ByVal Value As Variant) ``` Custom data. ### Parent ```vb Property Get Parent() As Object ``` The parent object. Read-only. ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` The container object. ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` The left margin. ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` The top margin. ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` The width. ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` The height. ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` The visibility. ## Methods ### Refresh ```vb Sub Refresh() ``` Forces a repaint. ### AboutBox ```vb Sub AboutBox() ``` Displays the About dialog. ## Events ### LinkClick ```vb Event LinkClick(ByVal Link As LlbLink) ``` Occurs when a link is clicked. ### Click ```vb Event Click() ``` Occurs when the control is clicked. ### DblClick ```vb Event DblClick() ``` Occurs when the control is double-clicked. ### MouseDown ```vb Event MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` Occurs when a mouse button is pressed. ### MouseUp ```vb Event MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` Occurs when a mouse button is released. ### MouseMove ```vb Event MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) ``` Occurs when the mouse is moved. ### MouseEnter ```vb Event MouseEnter() ``` Occurs when the mouse enters the control. ### MouseLeave ```vb Event MouseLeave() ``` Occurs when the mouse leaves the control. ## Sub-objects ### Link (LlbLink) Represents a single link within the link label. #### Properties | Property | Type | Access | Description | |----------|------|--------|-------------| | Start As Long | Long | Read/Write | Starting position of the link text (0-based) | | Length As Long | Long | Read/Write | Length of the link text | | Visited As Boolean | Boolean | Read/Write | Whether the link has been visited | | Key As String | String | Read/Write | Link key | | Tag As Variant | Variant | Read/Write | Custom data | ### Links (LlbLinks) The link collection object. #### Properties | Property | Type | Access | Description | |----------|------|--------|-------------| | Item(ByVal Index As Variant) As LlbLink | LlbLink | Read-only | Gets a link by index | | Count As Long | Long | Read-only | Number of links | #### Methods | Method | Description | |--------|-------------| | Add(ByVal Start As Long, ByVal Length As Long, Optional ByVal Key As String) As LlbLink | Adds a link | | Clear() | Clears all links | | Remove(ByVal Index As Variant) | Removes the specified link | ## Code Examples ```vb ' Set up text with links With LinkLabel1 .Caption = "Visit the VBCCR project homepage for more information" .LinkColor = vbBlue .VisitedLinkColor = vbPurple .LinkBehavior = LlbLinkBehaviorHoverUnderline ' Add links .Links.Add 2, 7, "url_main" .Links.Add 15, 4, "url_more" End With ' Handle link clicks Private Sub LinkLabel1_LinkClick(ByVal Link As LlbLink) Select Case Link.Key Case "url_main" ShellExecute 0, "open", "https://github.com/Kr00l/VBCCR", vbNullString, vbNullString, 1 Case "url_more" MsgBox "More information..." End Select Link.Visited = True End Sub ' Create multi-link text With LinkLabel2 .Caption = "Please read the License Agreement and Privacy Policy" .Links.Clear .Links.Add 3, 4, "license" .Links.Add 10, 4, "privacy" End With ``` --- --- url: /en/official/Reference/VBRUN/Constants/LinkModeConstants.md --- # LinkModeConstants DDE link-mode values for the **LinkMode** property of forms and supported controls. | Constant | Value | Description | |----------|-------|-------------| | **vbLinkNone** | 0 | No DDE link is active. | | **vbLinkAutomatic** | 1 | The control updates whenever the source data changes. (Same value as **vbLinkSource**.) | | **vbLinkSource** | 1 | The form acts as a DDE source: changes to its controls notify any client that has linked to them. | | **vbLinkManual** | 2 | The control updates only when **LinkRequest** is called. | | **vbLinkNotify** | 3 | A **LinkNotify** event is raised when the source data changes; the control updates only on demand. | --- --- url: /zh/official/Reference/VBRUN/Constants/LinkModeConstants.md --- # LinkModeConstants 窗体和支持控件的**LinkMode**属性的DDE链接模式值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbLinkNone** | 0 | 无活动DDE链接。 | | **vbLinkAutomatic** | 1 | 源数据更改时控件自动更新。(与**vbLinkSource**值相同。) | | **vbLinkSource** | 1 | 窗体作为DDE源:其控件更改时通知已链接的客户端。 | | **vbLinkManual** | 2 | 仅在调用**LinkRequest**时更新。 | | **vbLinkNotify** | 3 | 源数据更改时引发**LinkNotify**事件;控件仅按需更新。 | --- --- url: /en/official/Reference/VB/ListBox.md --- # ListBox class A **ListBox** is a Win32 native control that displays a vertically-scrolling list of items, optionally laid out in multiple columns, from which the user picks one item --- or any number of items, when [**MultiSelect**](#multiselect) is non-zero. Each item is a string, with an optional **LongPtr** value the application can store alongside it through [**ItemData**](#itemdata). The control is normally placed on a **Form** or **UserControl** at design time. The default property is [**Text**](#text) and the default event is [**Click**](#click). ```vb Private Sub Form_Load() With List1 .AddItem "Apple" .AddItem "Banana" .AddItem "Cherry" .ItemData(0) = 100 .ItemData(1) = 200 .ItemData(2) = 300 .ListIndex = 0 End With End Sub Private Sub List1_Click() Debug.Print "Picked: " & List1.Text & " (data = " & List1.ItemData(List1.ListIndex) & ")" End Sub ``` ## Style [**Style**](#style) selects one of three rendering modes ([**ListBoxConstants**](/en/official/Reference/VBRUN/Constants/ListBoxConstants)): | Constant | Value | Layout | |---------------------------|-------|----------------------------------------------------------------------------------------------| | **vbListBoxStandard** | 0 | Plain text items, the default. | | **vbListBoxCheckbox** | 1 | Each item shows an independent check box that the user can toggle without changing the selection. | | **vbListBoxColorSwatch** | 2 | Each item shows a colour swatch in front of its text, drawn in the colour stored in [**ItemData**](#itemdata). | Changing **Style** at run time recreates the underlying window, preserving the items, [**ItemData**](#itemdata) values, current selection, scroll position, and (in checkbox mode) check states. [**Sorted**](#sorted), [**MultiSelect**](#multiselect), [**IntegralHeight**](#integralheight), and [**UseTabStops**](#usetabstops) recreate the window the same way. [**MultiSelect**](#multiselect) is meaningful only with **vbListBoxStandard**. The other styles always behave as if **MultiSelect** were **vbMultiSelectNone** --- the per-item toggle of **vbListBoxCheckbox** replaces the multi-selection feature, and the colour swatch is purely a display variant. ## Editing the list Items are held inside the OS list-box control; the [**List**](#list) and [**ItemData**](#itemdata) arrays are projections onto that storage. Items are added with [**AddItem**](#additem), removed with [**RemoveItem**](#removeitem), and the whole list is cleared with [**Clear**](#clear). After each [**AddItem**](#additem) call, [**NewIndex**](#newindex) reports the position the item was inserted at --- useful when [**Sorted**](#sorted) is **True** and the position is not predictable from the call. ```vb List1.Sorted = True List1.AddItem "Cherry" List1.AddItem "Apple" ' Inserted at index 0 — List1.NewIndex = 0 List1.ItemData(List1.NewIndex) = 42 ``` Indexing past the end of the list raises run-time error 5 (*Invalid procedure call or argument*). Out of range or otherwise rejected calls to [**AddItem**](#additem) and [**RemoveItem**](#removeitem) raise the same error. ## Selection [**ListIndex**](#listindex) is the zero-based index of the focused item, or `-1` when nothing is focused. [**Text**](#text) returns the text at that index. In single-select mode (**vbMultiSelectNone**) the focused item is also the selected item, and assigning to [**ListIndex**](#listindex) selects it and raises [**Click**](#click) if the value actually changes. In **vbMultiSelectSimple** and **vbMultiSelectExtended** the focused item is independent of the selection set; use [**Selected**](#selected) to read or write the selection state of any individual item, and [**SelCount**](#selcount) to count them. [**SelectedIndices**](#selectedindices) returns the selected indices as a **Collection** for convenient iteration. ```vb Dim idx As Variant For Each idx In List1.SelectedIndices() Debug.Print List1.List(idx) Next ``` Assigning a string to [**Text**](#text) searches the list with an exact, case-insensitive match (using `LB_FINDSTRINGEXACT`) and selects that entry if found; if no entry matches, [**ListIndex**](#listindex) is set to `-1` and the current selection is cleared. Reading [**Text**](#text) when [**ListIndex**](#listindex) is `-1` raises run-time error 5. ## Multi-column display When [**Columns**](#columns) is greater than zero, the OS lays the items out in that many side-by-side columns and gives the control a horizontal scroll bar instead of the usual vertical one. The column width is automatically set to the control's pixel width divided by [**Columns**](#columns) --- assigning a new [**Width**](#width) does not re-divide the columns; reassign [**Columns**](#columns) to refresh the layout. The single-column / multi-column distinction is fixed at the moment the underlying window is created. At run time, [**Columns**](#columns) can be raised or lowered between non-zero values to re-divide the same control, but switching between zero and non-zero raises run-time error 380 (*Invalid property value*). A multi-column layout requires [**Columns**](#columns) to be assigned its non-zero value at design time. ## Checkbox style In **vbListBoxCheckbox** mode each item draws a small check box in front of its text, sized from [**MaxCheckboxSize**](#maxcheckboxsize) (in pixels at 96 DPI; scaled by the system DPI). The user toggles a check box by clicking it, by clicking the item and pressing **Space**, or by clicking the item itself when it is already the focused item. Each toggle raises [**ItemCheck**](#itemcheck) with the affected index. [**Selected**](#selected) reads or writes the per-item check state in this mode (instead of the selection state). The focused item is still tracked through [**ListIndex**](#listindex), and the standard [**Click**](#click) event still fires when the focus moves between items. The check states are kept in an internal array that is preserved across [**AddItem**](#additem) and [**RemoveItem**](#removeitem) calls (existing items keep their state; new items start unchecked). ## Data binding Setting [**DataSource**](#datasource) and [**DataField**](#datafield) connects the control's [**Text**](#text) to a field of a [**Data**](/en/official/Reference/VB/Data/) control's recordset. The bound field is read as a string on each move, and assigning to [**Text**](#text) marks the recordset as dirty by setting [**DataChanged**](#datachanged) to **True**. A field whose value cannot be coerced to a string is treated as an empty string rather than raising. ## OLE drag and drop When [**OLEDragMode**](#oledragmode) is set to **vbOLEDragAutomatic**, dragging an item from the list starts an OLE drag whose **Text** data is either the dragged item's string (in single-select mode) or every selected item's text concatenated, separated by **vbCrLf** (in **vbMultiSelectSimple** or **vbMultiSelectExtended**). [**OLEDropMode**](#oledropmode) controls drop-target behaviour and is restricted to **vbOLEDropNone** or **vbOLEDropManual**. ## Properties ### Anchors The set of edges of the parent that the list box's corresponding edges follow when the parent resizes. Read-only --- assign individual `.Left`, `.Top`, `.Right`, `.Bottom` flags through the returned **Anchors** object. ### Appearance Determines how the control's border is drawn by the OS. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). Combined with [**BorderStyle**](#borderstyle): a 3-D appearance plus single border yields the standard sunken client edge; flat appearance plus single border yields a one-pixel outline. ### BackColor The background colour of the list area, as an **OLE\_COLOR**. Defaults to the system window-background colour. Items drawn in the selected state ignore **BackColor** in favour of the system highlight colour. ### BorderStyle A member of [**ControlBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants): **vbNoBorder** (0) or **vbFixedSingleBorder** (1, default). Changing it at run time re-syncs the border without recreating the window. ### CausesValidation Determines whether the previously focused control's [**Validate**](#validate) event runs before this control receives the focus. **Boolean**, default **True**. ### Columns The number of columns in a multi-column layout, or `0` for a single-column list with a vertical scroll bar. **Long**, default `0`. See [Multi-column display](#multi-column-display). Syntax: *object*.**Columns** \[ = *value* ] Switching between zero and non-zero at run time raises run-time error 380 (*Invalid property value*). Re-assigning between two non-zero values is allowed and re-divides the visible area. ### Container The control that hosts this list box --- typically the form, a [**Frame**](/en/official/Reference/VB/Frame/), or a **UserControl**. Read with **Get**, change with **Set**. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a list box. Always **vbListBox**. ### DataChanged Whether the bound [**Text**](#text) has been written to since the last save or refresh from the [**DataSource**](#datasource). **Boolean**. Setting **DataChanged** = **True** also marks the bound recordset as dirty. ### DataField The name of the field, in the recordset of the bound [**DataSource**](#datasource), whose value is mirrored by [**Text**](#text). **String**. ### DataFormat ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### DataMember ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### DataSource A reference to a [**Data**](/en/official/Reference/VB/Data/) control (or other **DataSource** provider) whose recordset supplies the value for [**DataField**](#datafield). Set with **Set**. ### Dock Where the list box is docked within its container. A member of [**DockModeConstants**](/en/official/Reference/VBRUN/Constants/DockModeConstants): **vbDockNone** (default), **vbDockLeft**, **vbDockTop**, **vbDockRight**, **vbDockBottom**, or **vbDockFill**. Docked list boxes ignore [**Anchors**](#anchors). ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the control accepts user input. A disabled list box still shows its contents but is dimmed and ignores keyboard and mouse interaction. **Boolean**, default **True**. ### Font The **StdFont** used to render item text. The convenience properties **FontName**, **FontSize**, **FontBold**, **FontItalic**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. Changing the font rescales each item's row height when [**IntegralHeight**](#integralheight) is **True**, and forces a recalculation of the row height in **vbListBoxCheckbox** and **vbListBoxColorSwatch** modes. ### ForeColor The text colour for entries that are not currently selected, as an **OLE\_COLOR**. Defaults to the system window-text colour. Disabled entries draw in the system grey-text colour, and selected entries draw in the system highlight-text colour, regardless of this setting. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). When [**IntegralHeight**](#integralheight) is **True**, the OS quantises this on **Initialize** to a whole number of rows. **Single**. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the control has focus. ### hWnd The Win32 window handle for the underlying list box, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Reading **Index** on a non-array instance raises run-time error 343 (*Object not an array*). Read-only at run time. ### IntegralHeight When **True** (default), the OS adjusts the control's height so that the visible portion shows whole rows rather than partial ones. When **False**, the control honours [**Height**](#height) exactly and the bottom row may be clipped. **Boolean**. Changing this at run time recreates the underlying window. ### ItemData A **LongPtr** that the application can associate with each item. Indexed by the same zero-based position used by [**List**](#list). Syntax: *object*.**ItemData**( *Index* ) \[ = *value* ] *Index* : *required* A **Long** zero-based item position. In **vbListBoxColorSwatch** mode, **ItemData** is read by the painting code as the **OLE\_COLOR** to draw in the swatch --- a typical use is to fill it with a list of palette colours from which the user selects one. In the other styles **ItemData** is purely application-defined. ```vb List1.AddItem "Highlight" List1.ItemData(List1.NewIndex) = vbYellow ``` Values stored at design time through the form designer are kept as **Long** rather than **LongPtr** so that designed forms remain platform-agnostic; at run time the property is **LongPtr**, sign-extending the design-time value where necessary. ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Single**. ### List The text of an item, indexed by zero-based position. Setting **List(*Index*)** removes the existing item at that position and reinserts the new value at the same index --- note that this can change the resulting position when [**Sorted**](#sorted) is **True**. Syntax: *object*.**List**( *Index* ) \[ = *string* ] *Index* : *required* A **Long** zero-based item position. Out-of-range indices raise run-time error 5. ### ListCount The number of items in the list, as a **Long**. Read-only. ### ListIndex The zero-based index of the focused item, or `-1` if no item is focused. **Long**. In multi-select modes the focused item and the selected items are independent --- see [**Selected**](#selected). Assigning a value that differs from the current one focuses that item and raises [**Click**](#click). ### MaxCheckboxSize The maximum size of the per-item check box drawn in **vbListBoxCheckbox** mode, in pixels at 96 DPI. **Long**, default `15`. The actual size used is the smaller of this value (scaled by the system DPI) and the row height computed from the current font, so the box never exceeds a row. ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### MultiSelect The selection mode. A member of [**MultiSelectConstants**](/en/official/Reference/VBRUN/Constants/MultiSelectConstants): **vbMultiSelectNone** (0, default --- single selection), **vbMultiSelectSimple** (1 --- each click toggles), or **vbMultiSelectExtended** (2 --- **Shift** for ranges, **Ctrl** for individual toggles). Changing this at run time recreates the underlying window; the items, [**ItemData**](#itemdata) values, focused item, and (in **vbListBoxCheckbox** mode) check states are restored, but multi-item selections are not. Effective only in **vbListBoxStandard** mode --- see [Style](#style). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### NewIndex The zero-based index at which the most recent [**AddItem**](#additem) call inserted its item, or `-1` if no item has been added since the control was created. Particularly useful when [**Sorted**](#sorted) is **True** and the resulting position cannot be predicted from the call. **Long**, read-only. ### OLEDragMode Whether the control acts as an automatic OLE drag source. A member of [**OLEDragConstants**](/en/official/Reference/VBRUN/Constants/OLEDragConstants): **vbOLEDragManual** (0, default --- call [**OLEDrag**](#oledrag) from code) or **vbOLEDragAutomatic** (1 --- dragging an item starts an OLE drag whose **Text** data is the dragged item's text in single-select mode, or every selected item's text separated by **vbCrLf** in multi-select mode). ### OLEDropMode How the control responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on a ListBox. ### Opacity The control's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Requires Windows 8 or later for child controls. ### Parent A reference to the [**Form**](/en/official/Reference/VB/Form/) (or **UserControl**) that ultimately contains this list box. Read-only. ### RightToLeft ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### SelCount The number of items currently selected, as a **Long**. Read-only. Always `0` or `1` when [**MultiSelect**](#multiselect) is **vbMultiSelectNone** or when [**Style**](#style) is non-standard. ### Selected The selection state of an individual item --- or, in **vbListBoxCheckbox** mode, the check state. Syntax: *object*.**Selected**( *Index* ) \[ = *boolean* ] *Index* : *required* A **Long** zero-based item position. In **vbListBoxStandard** mode, reading **Selected(*Index*)** returns **True** when that item is selected, and assigning a value updates the selection. In single-select mode (**vbMultiSelectNone**), assigning **True** selects that item; assigning **False** has no observable effect. In multi-select modes, assignments toggle the corresponding item's membership in the selection set independently of the focused item. Each assignment that changes the state raises [**Click**](#click). In **vbListBoxCheckbox** mode, **Selected(*Index*)** reads or writes the per-item check state. Each assignment that changes the state raises [**ItemCheck**](#itemcheck). In **vbListBoxColorSwatch** mode, **Selected(*Index*)** behaves as in single-select standard mode (the swatch styling is purely a display variant). ### Sorted When **True**, items added with [**AddItem**](#additem) are inserted in alphabetical order regardless of the *Index* argument; when **False** (default), they are inserted at the requested position (or appended). **Boolean**. Changing this at run time recreates the underlying window with the existing items re-added. ### Style Selects one of the three rendering modes. A member of [**ListBoxConstants**](/en/official/Reference/VBRUN/Constants/ListBoxConstants): **vbListBoxStandard** (0, default), **vbListBoxCheckbox** (1), or **vbListBoxColorSwatch** (2). See [Style](#style) above for the layout and behaviour differences. Changing **Style** at run time recreates the underlying window. ### TabIndex The position of the control in the form's TAB-key navigation order. **Long**. ### TabStop Whether the user can reach the control by pressing the **TAB** key. **Boolean**, default **True**. A disabled control is skipped regardless of this setting. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### Text The text of the focused item, or an empty string when [**ListIndex**](#listindex) is `-1`. **Default property.** Syntax: *object*.**Text** \[ = *string* ] Reading **Text** returns `List(ListIndex)` --- reading it when no item is focused raises run-time error 5 (*Invalid procedure call or argument*). Setting **Text** searches the list for an exact, case-insensitive match (using `LB_FINDSTRINGEXACT`) and selects the matching item if found; if no item matches, [**ListIndex**](#listindex) is set to `-1` and the current selection is cleared. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the control. ### Top The vertical distance from the top of the container to the top of the control. **Single**. ### TopIndex The zero-based index of the item shown at the top of the visible area. **Long**. Assigning a value scrolls the list so that item is at the top; the [**Scroll**](#scroll) event is raised when the value actually changes. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered control. Default `-1` disables the effect. Requires Windows 8 or later for child controls. ### UseTabStops When **True** (default), `vbTab` characters embedded in item text are expanded to the OS's standard list-box tab stops, so multi-column-aligned text can be rendered in a single-column list. When **False**, tab characters are drawn literally. **Boolean**. Changing this at run time recreates the underlying window. ### Visible Whether the control is shown. **Boolean**, default **True**. ### VisualStyles Whether the OS theme engine should be used when drawing the control. **Boolean**, default **True**. Affects the rendering of the per-item check box in **vbListBoxCheckbox** mode (themed vs. classic flat-style box). ### WhatsThisHelpID A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### WheelScrollEvent When **True** (default), mouse-wheel notifications over the control raise the [**Scroll**](#scroll) event; when **False**, the wheel still scrolls the list but [**Scroll**](#scroll) is suppressed. **Boolean**. VB6 never raised **Scroll** for wheel events; set this to **False** to match that behaviour exactly. ### Width The control's width. **Single**. In a multi-column layout, also determines the column width --- see [Multi-column display](#multi-column-display). ## Methods ### AddItem Inserts a new item into the list and stores the resulting position in [**NewIndex**](#newindex). In **vbListBoxCheckbox** mode the new item is unchecked; existing items keep their check state. Syntax: *object*.**AddItem** *Value* \[, *Index* ] *Value* : *required* A **String** giving the text of the new item. *Index* : *optional* A **Long** zero-based position to insert at. Omit to append to the end. Out-of-range indices raise run-time error 5. Ignored when [**Sorted**](#sorted) is **True**. ### Clear Removes every item from the list, including any associated [**ItemData**](#itemdata) values and check states. Syntax: *object*.**Clear** ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Typically called from a [**MouseDown**](#mousedown) handler when [**DragMode**](#dragmode) is **vbManual**. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the control, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Forces an immediate repaint of the control. Syntax: *object*.**Refresh** ### RemoveItem Removes the item at the given zero-based position, along with its [**ItemData**](#itemdata) value. Items below it shift up by one, and (in **vbListBoxCheckbox** mode) their check states shift up with them. Syntax: *object*.**RemoveItem** *Index* *Index* : *required* A **Long** zero-based position. ### SelectedIndices Returns the zero-based indices of every currently-selected item as a **Collection** of **Long** values, in ascending order. Useful for iterating multi-selections without scanning [**Selected**](#selected) for every index. Syntax: *object*.**SelectedIndices** ```vb Dim idx As Variant For Each idx In List1.SelectedIndices() Debug.Print idx & ": " & List1.List(idx) Next ``` ### SetFocus Moves the input focus to the control. The control must be both [**Visible**](#visible) and [**Enabled**](#enabled), or run-time error 5 (*Invalid procedure call or argument*) is raised. Syntax: *object*.**SetFocus** ### ShowWhatsThis Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Click Raised after the focused item changes --- whether the user clicked a different entry, used the keyboard to move the focus, or code assigned a different value to [**ListIndex**](#listindex) or [**Selected**](#selected). Also raised when the previously selected item is cancelled (`LBN_SELCANCEL`). **Default event.** Syntax: *object*\_**Click**( ) ### DblClick Raised when the user double-clicks an entry. Typically used to act on the highlighted item --- for example, opening it. Syntax: *object*\_**DblClick**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus Raised when the control receives the input focus. Syntax: *object*\_**GotFocus**( ) ### Initialize Raised once, immediately after the underlying window is created and the design-time items have been added. New in twinBASIC --- VB6 had no equivalent on this control. Syntax: *object*\_**Initialize**( ) ### ItemCheck Raised in **vbListBoxCheckbox** mode each time the check state of an item changes --- whether the user clicked its check box, pressed **Space**, or code assigned to [**Selected**](#selected). Not raised in the other styles. Syntax: *object*\_**ItemCheck**( *Item* **As Integer** ) *Item* : The zero-based index of the toggled item. ::: info Items beyond index 32768 do not raise **ItemCheck** because the event signature uses **Integer**. Read [**Selected**](#selected) directly to inspect higher-indexed items. ::: ### KeyDown Raised when the user presses any key while the control has focus. Syntax: *object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress Raised when the user types a character that produces an ANSI keystroke. Syntax: *object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp Raised when the user releases a key while the control has focus. Syntax: *object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus Raised when the control loses the input focus. Syntax: *object*\_**LostFocus**( ) ### MouseDown Raised when the user presses any mouse button over the control. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the control. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the control. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Fires whether the drag was initiated automatically (with [**OLEDragMode**](#oledragmode) set to **vbOLEDragAutomatic**) or by an explicit [**OLEDrag**](#oledrag) call. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Scroll Raised when the visible portion of the list scrolls --- by the scroll bar, the keyboard, or (when [**WheelScrollEvent**](#wheelscrollevent) is **True**) the mouse wheel. The new offset can be read from [**TopIndex**](#topindex). Syntax: *object*\_**Scroll**( ) ### Validate Raised when the focus is moving to another control whose [**CausesValidation**](#causesvalidation) is **True**. Setting *Cancel* to **True** keeps the focus on this control. Syntax: *object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /zh/official/Reference/VB/ListBox.md --- # ListBox 类 **ListBox**是一个Win32原生控件,显示垂直滚动的条目列表,可选多列布局,用户从中选择一个条目——或[**MultiSelect**](#multiselect)非零时选择任意数量的条目。每个条目是一个字符串,带有可选的**LongPtr**值,应用程序可通过[**ItemData**](#itemdata)与条目一起存储。该控件通常在设计时放置在**Form**或**UserControl**上。默认属性是[**Text**](#text),默认事件是[**Click**](#click)。 ```vb Private Sub Form_Load() With List1 .AddItem "Apple" .AddItem "Banana" .AddItem "Cherry" .ItemData(0) = 100 .ItemData(1) = 200 .ItemData(2) = 300 .ListIndex = 0 End With End Sub Private Sub List1_Click() Debug.Print "Picked: " & List1.Text & " (data = " & List1.ItemData(List1.ListIndex) & ")" End Sub ``` ## 样式 [**Style**](#style)选择三种渲染模式之一([**ListBoxConstants**](/official/Reference/VBRUN/Constants/ListBoxConstants)): | 常量 | 值 | 布局 | |-----------------------------|-----|--------------------------------------------------------------------------------------------| | **vbListBoxStandard** | 0 | 纯文本条目,默认。 | | **vbListBoxCheckbox** | 1 | 每个条目显示独立的复选框,用户可切换而不更改选择。 | | **vbListBoxColorSwatch** | 2 | 每个条目在其文本前显示颜色色板,以[**ItemData**](#itemdata)中存储的颜色绘制。 | 在运行时更改**Style**会重新创建底层窗口,保留条目、[**ItemData**](#itemdata)值、当前选择、滚动位置和(复选框模式下)选中状态。[**Sorted**](#sorted)、[**MultiSelect**](#multiselect)、[**IntegralHeight**](#integralheight)和[**UseTabStops**](#usetabstops)以相同方式重新创建窗口。 [**MultiSelect**](#multiselect)仅在**vbListBoxStandard**下有意义。其他样式始终表现为**vbMultiSelectNone**——**vbListBoxCheckbox**的逐项切换取代了多选功能,色板纯粹是显示变体。 ## 编辑列表 条目保存在操作系统列表框控件内部;[**List**](#list)和[**ItemData**](#itemdata)数组是对该存储的映射。条目通过[**AddItem**](#additem)添加,通过[**RemoveItem**](#removeitem)移除,整个列表通过[**Clear**](#clear)清空。每次[**AddItem**](#additem)调用后,[**NewIndex**](#newindex)报告条目插入的位置——当[**Sorted**](#sorted)为**True**且位置无法从调用预测时非常有用。 ```vb List1.Sorted = True List1.AddItem "Cherry" List1.AddItem "Apple" ' 插入到索引0 — List1.NewIndex = 0 List1.ItemData(List1.NewIndex) = 42 ``` 对超出列表末尾的索引进行索引会引发运行时错误5(*Invalid procedure call or argument*)。对[**AddItem**](#additem)和[**RemoveItem**](#removeitem)的超出范围或其他被拒绝的调用会引发相同错误。 ## 选择 [**ListIndex**](#listindex)是焦点条目的从零开始的索引,无焦点时为`-1`。[**Text**](#text)返回该索引处的文本。在单选模式(**vbMultiSelectNone**)下,焦点条目也是选中条目,对[**ListIndex**](#listindex)赋值会选中它并在值实际更改时引发[**Click**](#click)。在**vbMultiSelectSimple**和**vbMultiSelectExtended**下,焦点条目独立于选择集;使用[**Selected**](#selected)读取或写入任何单个条目的选择状态,使用[**SelCount**](#selcount)计算数量。[**SelectedIndices**](#selectedindices)以**Collection**返回选中索引,方便迭代。 ```vb Dim idx As Variant For Each idx In List1.SelectedIndices() Debug.Print List1.List(idx) Next ``` 为[**Text**](#text)赋值字符串会以不区分大小写的精确匹配搜索列表(使用`LB_FINDSTRINGEXACT`),找到则选中该条目;如果无匹配条目,[**ListIndex**](#listindex)设为`-1`并清除当前选择。当[**ListIndex**](#listindex)为`-1`时读取[**Text**](#text)会引发运行时错误5。 ## 多列显示 当[**Columns**](#columns)大于零时,操作系统将条目布局为多个并排列,并为控件提供水平滚动条而非通常的垂直滚动条。列宽自动设置为控件的像素宽度除以[**Columns**](#columns)——赋值新[**Width**](#width)不会重新划分列;重新赋值[**Columns**](#columns)以刷新布局。 单列/多列的区别在底层窗口创建时固定。在运行时,[**Columns**](#columns)可以在非零值之间升高或降低以重新划分同一控件,但在零和非零之间切换会引发运行时错误380(*Invalid property value*)。多列布局要求在设计时为[**Columns**](#columns)赋非零值。 ## 复选框样式 在**vbListBoxCheckbox**模式下,每个条目在其文本前绘制小复选框,大小由[**MaxCheckboxSize**](#maxcheckboxsize)决定(96 DPI下的像素值;由系统DPI缩放)。用户通过点击复选框、点击条目后按**空格**或点击已是焦点条目的条目本身来切换复选框。每次切换引发[**ItemCheck**](#itemcheck),带有受影响的索引。[**Selected**](#selected)在此模式下读取或写入逐项选中状态(而非选择状态)。焦点条目仍通过[**ListIndex**](#listindex)跟踪,当焦点在条目之间移动时标准[**Click**](#click)事件仍会引发。 选中状态保存在内部数组中,在[**AddItem**](#additem)和[**RemoveItem**](#removeitem)调用之间保留(现有条目保持其状态;新条目从未选中开始)。 ## 数据绑定 设置[**DataSource**](#datasource)和[**DataField**](#datafield)将控件的[**Text**](#text)连接到[**Data**](/official/Reference/VB/Data/)控件记录集的字段。每次移动时绑定字段作为字符串读取,对[**Text**](#text)赋值通过将[**DataChanged**](#datachanged)设置为**True**将记录集标记为已修改。无法强制转换为字符串的字段值被视为空字符串而非引发错误。 ## OLE拖放 当[**OLEDragMode**](#oledragmode)设置为**vbOLEDragAutomatic**时,从列表拖动条目会启动OLE拖动,其**Text**数据为拖动条目的字符串(单选模式)或每个选中条目的文本以**vbCrLf**分隔连接(**vbMultiSelectSimple**或**vbMultiSelectExtended**模式下)。[**OLEDropMode**](#oledropmode)控制放置目标行为,仅限于**vbOLEDropNone**或**vbOLEDropManual**。 ## 属性 ### Anchors 列表框的对应边缘跟随父控件调整大小时所依据的父控件边缘集合。只读——通过返回的**Anchors**对象分配单独的`.Left`、`.Top`、`.Right`、`.Bottom`标志。 ### Appearance 确定操作系统如何绘制控件的边框。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。与[**BorderStyle**](#borderstyle)组合使用:3D外观加单线边框产生标准凹陷客户端边缘;平面外观加单线边框产生一像素轮廓线。 ### BackColor 列表区域的背景颜色,类型为**OLE\_COLOR**。默认为系统窗口背景色。选中状态绘制的条目忽略**BackColor**而使用系统高亮色。 ### BorderStyle [**ControlBorderStyleConstants**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants)的成员:**vbNoBorder** (0)或**vbFixedSingleBorder** (1,默认)。在运行时更改会重新同步边框而不重新创建窗口。 ### CausesValidation 确定先前获得焦点的控件的[**Validate**](#validate)事件是否在此控件获得焦点之前运行。**Boolean**,默认**True**。 ### Columns 多列布局中的列数,或`0`表示带垂直滚动条的单列列表。**Long**,默认`0`。参见[多列显示](#multi-column-display)。 语法:*object*.**Columns** \[ = *value* ] 在运行时在零和非零之间切换会引发运行时错误380(*Invalid property value*)。在两个非零值之间重新赋值是允许的并重新划分可见区域。 ### Container 承载此列表框的控件——通常是窗体、[**Frame**](/official/Reference/VB/Frame/)或**UserControl**。使用**Get**读取,使用**Set**更改。 ### ControlType 只读的[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值,将此控件标识为列表框。始终为**vbListBox**。 ### DataChanged 绑定的[**Text**](#text)自上次保存或从[**DataSource**](#datasource)刷新以来是否已被写入。**Boolean**。设置**DataChanged** = **True**也会将绑定记录集标记为已修改。 ### DataField 绑定[**DataSource**](#datasource)记录集中由[**Text**](#text)镜像的字段名称。**String**。 ### DataFormat ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: ### DataMember ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: ### DataSource 对[**Data**](/official/Reference/VB/Data/)控件(或其他**DataSource**提供程序)的引用,其记录集为[**DataField**](#datafield)提供值。使用**Set**设置。 ### Dock 列表框在其容器中的停靠位置。[**DockModeConstants**](/official/Reference/VBRUN/Constants/DockModeConstants)的成员:**vbDockNone**(默认)、**vbDockLeft**、**vbDockTop**、**vbDockRight**、**vbDockBottom**或**vbDockFill**。停靠列表框忽略[**Anchors**](#anchors)。 ### DragIcon 控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自动拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual** (0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic** (1)。 ### Enabled 确定控件是否接受用户输入。禁用的列表框仍显示其内容但变暗并忽略键盘和鼠标交互。**Boolean**,默认**True**。 ### Font 用于渲染条目文本的**StdFont**。便捷属性**FontName**、**FontSize**、**FontBold**、**FontItalic**、**FontStrikethru**和**FontUnderline**读写此对象的相应成员。当[**IntegralHeight**](#integralheight)为**True**时更改字体会重新缩放每项的行高,并在**vbListBoxCheckbox**和**vbListBoxColorSwatch**模式下强制重新计算行高。 ### ForeColor 未选中条目的文本颜色,类型为**OLE\_COLOR**。默认为系统窗口文本色。禁用条目使用系统灰色文本色绘制,选中条目使用系统高亮文本色绘制,不受此设置影响。 ### Height 控件的高度,默认以缇为单位(或使用容器的**ScaleMode**单位)。当[**IntegralHeight**](#integralheight)为**True**时,操作系统在**Initialize**时将其量化为整行数。**Single**。 ### HelpContextID 标识应用程序帮助文件中主题的**Long**值,当用户在控件具有焦点时按**F1**时检索。 ### hWnd 底层列表框的Win32窗口句柄,类型为**LongPtr**。只读。可用于传递给API函数。 ### Index 当控件是控件数组的一部分时,此实例在数组中的从零开始的**Long**索引。在非数组实例上读取**Index**会引发运行时错误343(*Object not an array*)。运行时只读。 ### IntegralHeight 当为**True**(默认)时,操作系统调整控件高度使可见部分显示完整行而非部分行。当为**False**时,控件精确遵循[**Height**](#height),底部行可能被裁剪。**Boolean**。在运行时更改此属性会重新创建底层窗口。 ### ItemData 应用程序可关联到每个条目的**LongPtr**。使用与[**List**](#list)相同的从零开始的位置索引。 语法:*object*.**ItemData**( *Index* ) \[ = *value* ] *Index* : *必需* 从零开始的**Long**条目位置。 在**vbListBoxColorSwatch**模式下,**ItemData**由绘制代码读取为色板中绘制的**OLE\_COLOR**——典型用途是用调色板颜色列表填充它供用户选择。在其他样式中**ItemData**纯粹由应用程序定义。 ```vb List1.AddItem "Highlight" List1.ItemData(List1.NewIndex) = vbYellow ``` 设计时通过窗体设计器存储的值保持为**Long**而非**LongPtr**,以便设计的窗体保持平台无关;运行时属性为**LongPtr**,必要时符号扩展设计时值。 ### Left 从容器的左边缘到控件左边缘的水平距离。**Single**。 ### List 条目的文本,按从零开始的位置索引。设置**List(*Index*)**会移除该位置的现有条目并在同一索引重新插入新值——注意当[**Sorted**](#sorted)为**True**时这可能改变最终位置。 语法:*object*.**List**( *Index* ) \[ = *string* ] *Index* : *必需* 从零开始的**Long**条目位置。超出范围的索引引发运行时错误5。 ### ListCount 列表中的条目数,类型为**Long**。只读。 ### ListIndex 焦点条目的从零开始的索引,无焦点条目时为`-1`。**Long**。在多选模式下焦点条目和选中条目是独立的——参见[**Selected**](#selected)。赋值与当前值不同的值会聚焦该条目并引发[**Click**](#click)。 ### MaxCheckboxSize **vbListBoxCheckbox**模式下绘制的逐项复选框的最大大小,96 DPI下的像素值。**Long**,默认`15`。实际使用的大小为此值(由系统DPI缩放)和从当前字体计算的行高中较小者,因此复选框从不超过一行。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针位于控件上时用作鼠标光标的**StdPicture**。 ### MousePointer 指针位于控件上时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### MultiSelect 选择模式。[**MultiSelectConstants**](/official/Reference/VBRUN/Constants/MultiSelectConstants)的成员:**vbMultiSelectNone** (0,默认——单项选择)、**vbMultiSelectSimple** (1——每次单击切换)或**vbMultiSelectExtended** (2——**Shift**选择范围,**Ctrl**切换单项)。在运行时更改此属性会重新创建底层窗口;条目、[**ItemData**](#itemdata)值、焦点条目和(**vbListBoxCheckbox**模式下)选中状态会恢复,但多项选择不会。仅在**vbListBoxStandard**模式下有效——参见[样式](#style)。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### NewIndex 最近一次[**AddItem**](#additem)调用插入条目的从零开始的索引,如果自控件创建以来未添加条目则为`-1`。当[**Sorted**](#sorted)为**True**且最终位置无法从调用预测时特别有用。**Long**,只读。 ### OLEDragMode 控件是否作为自动OLE拖动源。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDragConstants)的成员:**vbOLEDragManual** (0,默认——从代码调用[**OLEDrag**](#oledrag))或**vbOLEDragAutomatic** (1——拖动条目会启动OLE拖动,其**Text**数据为单选模式下拖动条目的文本,或多选模式下以**vbCrLf**分隔的每个选中条目的文本)。 ### OLEDropMode 控件如何响应OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**或**vbOLEDropManual**。ListBox不支持自动放置模式。 ### Opacity 控件的不透明度百分比(0--100,默认100)。超出范围的值在**Initialize**时被钳制。子控件需要Windows 8或更高版本。 ### Parent 对最终包含此列表框的[**Form**](/official/Reference/VB/Form/)(或**UserControl**)的引用。只读。 ### RightToLeft ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: ### SelCount 当前选中的条目数,类型为**Long**。只读。当[**MultiSelect**](#multiselect)为**vbMultiSelectNone**或[**Style**](#style)为非标准时始终为`0`或`1`。 ### Selected 单个条目的选择状态——或在**vbListBoxCheckbox**模式下的选中状态。 语法:*object*.**Selected**( *Index* ) \[ = *boolean* ] *Index* : *必需* 从零开始的**Long**条目位置。 在**vbListBoxStandard**模式下,读取**Selected(*Index*)**在该条目被选中时返回**True**,赋值会更新选择。在单选模式(**vbMultiSelectNone**)下,赋值**True**选中该条目;赋值**False**无明显效果。在多选模式下,赋值独立于焦点条目切换相应条目在选择集中的成员资格。每次更改状态的赋值引发[**Click**](#click)。 在**vbListBoxCheckbox**模式下,\*\*Selected(*Index*)\*\*读取或写入逐项选中状态。每次更改状态的赋值引发[**ItemCheck**](#itemcheck)。 在**vbListBoxColorSwatch**模式下,\*\*Selected(*Index*)\*\*表现为与单选标准模式相同(色板样式纯粹是显示变体)。 ### Sorted 当为**True**时,通过[**AddItem**](#additem)添加的条目按字母顺序插入,不考虑*Index*参数;当为**False**(默认)时,条目插入到请求的位置(或追加到末尾)。**Boolean**。在运行时更改此属性会重新创建底层窗口并重新添加现有条目。 ### Style 选择三种渲染模式之一。[**ListBoxConstants**](/official/Reference/VBRUN/Constants/ListBoxConstants)的成员:**vbListBoxStandard** (0,默认)、**vbListBoxCheckbox** (1)或**vbListBoxColorSwatch** (2)。参见上方的[样式](#style)部分了解布局和行为差异。在运行时更改**Style**会重新创建底层窗口。 ### TabIndex 控件在窗体TAB键导航顺序中的位置。**Long**。 ### TabStop 用户是否可以通过按**TAB**键到达控件。**Boolean**,默认**True**。禁用的控件无论此设置如何都会被跳过。 ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### Text 焦点条目的文本,或当[**ListIndex**](#listindex)为`-1`时的空字符串。**默认属性。** 语法:*object*.**Text** \[ = *string* ] 读取**Text**返回`List(ListIndex)`——无焦点条目时读取会引发运行时错误5(*Invalid procedure call or argument*)。设置**Text**会搜索列表进行精确的不区分大小写匹配(使用`LB_FINDSTRINGEXACT`),找到则选中匹配条目;如果无匹配条目,[**ListIndex**](#listindex)设为`-1`并清除当前选择。 ### ToolTipText 当用户将鼠标悬停在控件上时作为工具提示显示的多行**String**。 ### Top 从容器顶部到控件顶部的垂直距离。**Single**。 ### TopIndex 可见区域顶部显示条目的从零开始的索引。**Long**。赋值会滚动列表使该条目位于顶部;当值实际改变时引发[**Scroll**](#scroll)事件。 ### TransparencyKey 一个**OLE\_COLOR**值,设置后在渲染的控件中变为完全透明。默认`-1`禁用此效果。子控件需要Windows 8或更高版本。 ### UseTabStops 当为**True**(默认)时,条目文本中嵌入的`vbTab`字符扩展为操作系统标准列表框制表位,因此可以在单列列表中渲染多列对齐的文本。当为**False**时,制表符按原样绘制。**Boolean**。在运行时更改此属性会重新创建底层窗口。 ### Visible 控件是否显示。**Boolean**,默认**True**。 ### VisualStyles 绘制控件时是否使用操作系统主题引擎。**Boolean**,默认**True**。影响**vbListBoxCheckbox**模式下逐项复选框的渲染(主题化 vs. 经典平面样式框)。 ### WhatsThisHelpID 标识应用程序帮助文件中"这是什么?"弹出帮助主题的**Long**值。参见[**ShowWhatsThis**](#showwhatsthis)。 ### WheelScrollEvent 当为**True**(默认)时,控件上的鼠标滚轮通知引发[**Scroll**](#scroll)事件;当为**False**时,滚轮仍会滚动列表但[**Scroll**](#scroll)被抑制。**Boolean**。VB6从不为滚轮事件引发**Scroll**;将此设置为**False**可完全匹配该行为。 ### Width 控件的宽度。**Single**。在多列布局中,也决定列宽——参见[多列显示](#multi-column-display)。 ## 方法 ### AddItem 向列表插入新条目并将结果位置存储在[**NewIndex**](#newindex)中。在**vbListBoxCheckbox**模式下新条目未选中;现有条目保持其选中状态。 语法:*object*.**AddItem** *Value* \[, *Index* ] *Value* : *必需* 新条目文本的**String**。 *Index* : *可选* 要插入的从零开始的**Long**位置。省略则追加到末尾。超出范围的索引引发运行时错误5。当[**Sorted**](#sorted)为**True**时忽略。 ### Clear 移除列表中的所有条目,包括任何关联的[**ItemData**](#itemdata)值和选中状态。 语法:*object*.**Clear** ### Drag 开始、完成或取消手动拖放操作。通常在[**DragMode**](#dragmode)为**vbManual**时从[**MouseDown**](#mousedown)处理程序中调用。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel** (0)、**vbBeginDrag** (1,默认)或**vbEndDrag** (2)。 ### Move 在单次调用中重新定位并可选地调整控件大小。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**值。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从控件发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### Refresh 强制控件立即重绘。 语法:*object*.**Refresh** ### RemoveItem 移除给定从零开始位置处的条目及其[**ItemData**](#itemdata)值。其下方的条目上移一位,且(**vbListBoxCheckbox**模式下)它们的选中状态随之上移。 语法:*object*.**RemoveItem** *Index* *Index* : *必需* 从零开始的**Long**位置。 ### SelectedIndices 以升序**Long**值的**Collection**返回每个当前选中条目的从零开始的索引。用于迭代多选而无需扫描每个索引的[**Selected**](#selected)。 语法:*object*.**SelectedIndices** ```vb Dim idx As Variant For Each idx In List1.SelectedIndices() Debug.Print idx & ": " & List1.List(idx) Next ``` ### SetFocus 将输入焦点移至控件。控件必须同时[**Visible**](#visible)和[**Enabled**](#enabled),否则引发运行时错误5(*Invalid procedure call or argument*)。 语法:*object*.**SetFocus** ### ShowWhatsThis 以"这是什么?"弹出的方式显示由[**WhatsThisHelpID**](#whatsthishelpid)标识的主题。 语法:*object*.**ShowWhatsThis** ### ZOrder 将控件置于其同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront** (0,默认)或**vbSendToBack** (1)。 ## 事件 ### Click 焦点条目更改后引发——无论用户点击了不同的条目、使用键盘移动焦点,还是代码赋值了不同的[**ListIndex**](#listindex)或[**Selected**](#selected)值。先前选中条目被取消时也会引发(`LBN_SELCANCEL`)。**默认事件。** 语法:*object*\_**Click**( ) ### DblClick 用户双击条目时引发。通常用于对高亮条目执行操作——例如打开它。 语法:*object*\_**DblClick**( ) ### DragDrop 手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus 控件获得输入焦点时引发。 语法:*object*\_**GotFocus**( ) ### Initialize 在底层窗口创建且设计时条目已添加后立即引发一次。twinBASIC新增——VB6在此控件上没有等效功能。 语法:*object*\_**Initialize**( ) ### ItemCheck 在**vbListBoxCheckbox**模式下,每当条目的选中状态更改时引发——无论用户点击了其复选框、按了**空格**还是代码赋值了[**Selected**](#selected)。在其他样式中不引发。 语法:*object*\_**ItemCheck**( *Item* **As Integer** ) *Item* : 被切换条目的从零开始的索引。 ::: info 索引超过32768的条目不会引发**ItemCheck**,因为事件签名使用**Integer**。请直接读取[**Selected**](#selected)来检查更高索引的条目。 ::: ### KeyDown 用户在控件具有焦点时按下任意键引发。 语法:*object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress 用户键入产生ANSI击键的字符时引发。 语法:*object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp 用户在控件具有焦点时释放键引发。 语法:*object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus 控件失去输入焦点时引发。 语法:*object*\_**LostFocus**( ) ### MouseDown 用户在控件上按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 光标在控件上移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 用户在控件上释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 用户将数据放置到目标控件上时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的数据格式时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。无论拖动是自动启动的([**OLEDragMode**](#oledragmode)设置为**vbOLEDragAutomatic**)还是通过显式[**OLEDrag**](#oledrag)调用都会引发。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Scroll 列表的可见部分滚动时引发——通过滚动条、键盘或(当[**WheelScrollEvent**](#wheelscrollevent)为**True**时)鼠标滚轮。新偏移量可从[**TopIndex**](#topindex)读取。 语法:*object*\_**Scroll**( ) ### Validate 焦点移动到另一个[**CausesValidation**](#causesvalidation)为**True**的控件时引发。将*Cancel*设置为**True**可使焦点保留在此控件上。 语法:*object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /en/official/Reference/VBRUN/Constants/ListBoxConstants.md --- # ListBoxConstants Style values for the **Style** property of a list-box control. | Constant | Value | Description | |----------|-------|-------------| | **vbListBoxStandard** | 0 | Standard list box: each item is a string. | | **vbListBoxCheckbox** | 1 | Each item shows a check box that the user can toggle independently of the selection. | | **vbListBoxColorSwatch** | 2 | Each item shows a colour swatch alongside its text. | --- --- url: /zh/official/Reference/VBRUN/Constants/ListBoxConstants.md --- # ListBoxConstants 列表框控件的**Style**属性的样式值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbListBoxStandard** | 0 | 标准列表框:每项为字符串。 | | **vbListBoxCheckbox** | 1 | 每项显示复选框,用户可以独立于选择切换。 | | **vbListBoxColorSwatch** | 2 | 每项在文本旁显示色块。 | --- --- url: /en/packages/vbccr/lists/listboxw.md description: >- ListBoxW Control - VBCCR Development Manual, complete API reference based on source code --- # ListBoxW Control Wraps the Win32 native list box control with support for checkbox/radio styles, owner-draw, insertion marks, and multi-column display. ## Enumerations ### LstStyleConstants | Constant | Value | Description | |----------|-------|-------------| | LstStyleStandard | 0 | Standard list box | | LstStyleCheckbox | 1 | Checkbox style | | LstStyleOption | 2 | Option button style | ### LstDrawModeConstants | Constant | Value | Description | |----------|-------|-------------| | LstDrawModeNormal | 0 | System-drawn | | LstDrawModeOwnerDrawFixed | 1 | Owner-draw fixed height | | LstDrawModeOwnerDrawVariable | 2 | Owner-draw variable height | ### CCBorderStyleConstants See common enumerations. ### CCMousePointerConstants See common enumerations. ### CCRightToLeftModeConstants See common enumerations. ## Properties ### Text ```vb Property Get Text() As String Property Let Text(ByVal Value As String) ``` Text of the currently selected item. ### List ```vb Property Get List(ByVal Index As Long) As String Property Let List(ByVal Index As Long, ByVal Value As String) ``` Gets or sets list item text by index. ### ItemData ```vb Property Get ItemData(ByVal Index As Long) As LongPtr Property Let ItemData(ByVal Index As Long, ByVal Value As LongPtr) ``` Gets or sets item-associated data by index. ### ItemChecked ```vb Property Get ItemChecked(ByVal Index As Long) As Boolean Property Let ItemChecked(ByVal Index As Long, ByVal Value As Boolean) ``` Gets or sets the checked state of an item by index (effective when Style is Checkbox or Option). ### ListCount ```vb Property Get ListCount() As Long ``` Total number of list items. Read-only. ### ListIndex ```vb Property Get ListIndex() As Long Property Let ListIndex(ByVal Value As Long) ``` Index of the currently selected item. ### NewIndex ```vb Property Get NewIndex() As Long ``` Index of the most recently added item. Read-only. ### TopIndex ```vb Property Get TopIndex() As Long Property Let TopIndex(ByVal Value As Long) ``` Index of the first visible item in the list. ### AnchorIndex ```vb Property Get AnchorIndex() As Long Property Let AnchorIndex(ByVal Value As Long) ``` Index of the selection anchor. ### SelCount ```vb Property Get SelCount() As Long ``` Number of selected items. Read-only. ### Selected ```vb Property Get Selected(ByVal Index As Long) As Boolean Property Let Selected(ByVal Index As Long, ByVal Value As Boolean) ``` Gets or sets the selected state of an item by index. ### ItemHeight ```vb Property Get ItemHeight(Optional ByVal Index As Long) As Single Property Let ItemHeight(Optional ByVal Index As Long, ByVal Value As Single) ``` Item height. In variable-height owner-draw mode, it can be set per index. ### InsertMark ```vb Property Get InsertMark(Optional ByRef After As Boolean) As Long Property Let InsertMark(Optional ByRef After As Boolean, ByVal Value As Long) ``` Index of the insertion mark. ### OptionIndex ```vb Property Get OptionIndex() As Long Property Let OptionIndex(ByVal Value As Long) ``` Index of the selected item in option button style. ### OLEDraggedItem ```vb Property Get OLEDraggedItem() As Long ``` Index of the dragged item in an OLE drag-drop operation. Read-only. ### Style ```vb Property Get Style() As LstStyleConstants Property Let Style(ByVal Value As LstStyleConstants) ``` List box style. Read-only at design time. ### DrawMode ```vb Property Get DrawMode() As LstDrawModeConstants Property Let DrawMode(ByVal Value As LstDrawModeConstants) ``` Drawing mode. Read-only at design time. ### MultiSelect ```vb Property Get MultiSelect() As VBRUN.MultiSelectConstants Property Let MultiSelect(ByVal Value As VBRUN.MultiSelectConstants) ``` Multi-selection mode. ### Sorted ```vb Property Get Sorted() As Boolean Property Let Sorted(ByVal Value As Boolean) ``` Whether to automatically sort items. ### MultiColumn ```vb Property Get MultiColumn() As Boolean Property Let MultiColumn(ByVal Value As Boolean) ``` Whether to enable multi-column display. ### IntegralHeight ```vb Property Get IntegralHeight() As Boolean Property Let IntegralHeight(ByVal Value As Boolean) ``` Whether to show only complete items. Can be set at design time. ### AllowSelection ```vb Property Get AllowSelection() As Boolean Property Let AllowSelection(ByVal Value As Boolean) ``` Whether to allow item selection. ### UseTabStops ```vb Property Get UseTabStops() As Boolean Property Let UseTabStops(ByVal Value As Boolean) ``` Whether to recognize and expand tab characters. ### DisableNoScroll ```vb Property Get DisableNoScroll() As Boolean Property Let DisableNoScroll(ByVal Value As Boolean) ``` Whether to disable (instead of hide) the scroll bar when scrolling is not needed. ### HorizontalExtent ```vb Property Get HorizontalExtent() As Single Property Let HorizontalExtent(ByVal Value As Single) ``` Horizontal scroll width. ### InsertMarkColor ```vb Property Get InsertMarkColor() As OLE_COLOR Property Let InsertMarkColor(ByVal Value As OLE_COLOR) ``` Color of the insertion mark. ### ScrollTrack ```vb Property Get ScrollTrack() As Boolean Property Let ScrollTrack(ByVal Value As Boolean) ``` Whether to scroll content in real time while dragging the scroll bar. ### Redraw ```vb Property Get Redraw() As Boolean Property Let Redraw(ByVal Value As Boolean) ``` Whether to redraw the list box when items change. Disabling can speed up batch additions. ### BorderStyle ```vb Property Get BorderStyle() As CCBorderStyleConstants Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` Border style. See common enumerations. ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` Whether to enable visual styles. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` Foreground color. ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` Font. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### AllowDropFiles ```vb Property Get AllowDropFiles() As Boolean Property Let AllowDropFiles(ByVal Value As Boolean) ``` Whether to allow file drop. ### OLEDragMode ```vb Property Get OLEDragMode() As VBRUN.OLEDragConstants Property Let OLEDragMode(ByVal Value As VBRUN.OLEDragConstants) ``` OLE drag mode. ### OLEDragDropScroll ```vb Property Get OLEDragDropScroll() As Boolean Property Let OLEDragDropScroll(ByVal Value As Boolean) ``` Whether to auto-scroll during OLE drag-drop. ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE drop mode. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` Mouse pointer style. See common enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` Custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Whether to enable mouse enter/leave tracking. ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` Right-to-left display direction. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` Right-to-left mode. See common enumerations. ### hWnd ```vb Property Get hWnd() As LongPtr ``` Window handle of the list box control. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Window handle of the UserControl. ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` Tooltip text. ### Name ```vb Property Get Name() As String ``` Control name. Read-only. ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` Custom data. ### Parent ```vb Property Get Parent() As Object ``` Parent object. Read-only. ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` Container object. ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` Left position. ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` Top position. ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` Width. ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` Height. ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` Whether the control is visible. ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` Help context ID. ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "What's This" help ID. ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` Drag icon. ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` Drag mode. ## Methods ### AddItem ```vb Public Sub AddItem(ByVal Item As String, Optional ByVal Index As Variant) ``` Adds a list item. ### RemoveItem ```vb Public Sub RemoveItem(ByVal Index As Long) ``` Removes the list item at the specified index. ### Clear ```vb Public Sub Clear() ``` Clears all list items. ### Refresh ```vb Public Sub Refresh() ``` Forces a redraw of the control. ### SetSelRange ```vb Public Sub SetSelRange(ByVal StartIndex As Long, ByVal EndIndex As Long) ``` Sets the selection range (in multi-select mode). ### SetColumnWidth ```vb Public Sub SetColumnWidth(ByVal Value As Single) ``` Sets the column width in multi-column mode. ### SelectItem ```vb Public Function SelectItem(ByVal Text As String, Optional ByVal Index As Long = -1) As Long ``` Selects an item matching the text and returns the selected item index. ### FindItem ```vb Public Function FindItem(ByVal Text As String, Optional ByVal Index As Long = -1, Optional ByVal Partial As Boolean) As Long ``` Finds an item matching the text and returns its index. ### HitTest ```vb Public Function HitTest(ByVal X As Single, ByVal Y As Single) As Long ``` Hit test, returns the item index at the specified coordinates. ### HitTestInsertMark ```vb Public Function HitTestInsertMark(ByVal X As Single, ByVal Y As Single, Optional ByRef After As Boolean) As Long ``` Insertion mark hit test, returns the insertion position index. ### ItemsPerColumn ```vb Public Function ItemsPerColumn() As Long ``` Gets the number of items per column. ### SelectedIndices ```vb Public Function SelectedIndices() As Collection ``` Returns a collection of all selected item indices. ### CheckedIndices ```vb Public Function CheckedIndices() As Collection ``` Returns a collection of all checked item (checkbox/radio) indices. ### GetIdealHorizontalExtent ```vb Public Function GetIdealHorizontalExtent() As Single ``` Gets the ideal horizontal scroll width. ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag-drop operation. ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` Starts, ends, or cancels a drag operation. ### SetFocus ```vb Public Sub SetFocus() ``` Sets focus. ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` Adjusts the Z-order. ### Move ```vb Public Sub Move(ByVal Left As Single, Optional ByVal Top As Variant, Optional ByVal Width As Variant, Optional ByVal Height As Variant) ``` Moves and resizes the control. ## Events ### Click ```vb Public Event Click() ``` Click. ### DblClick ```vb Public Event DblClick() ``` Double-click. ### Scroll ```vb Public Event Scroll() ``` Fired when scrolling. ### ItemCheck ```vb Public Event ItemCheck(ByVal Item As Long) ``` Fired when an item is checked or unchecked. ### ItemBeforeCheck ```vb Public Event ItemBeforeCheck(ByVal Item As Long, ByRef Cancel As Boolean) ``` Fired before an item is checked or unchecked, can be canceled. ### ItemMeasure ```vb Public Event ItemMeasure(ByVal Item As Long, ByRef ItemHeight As Long) ``` Fired when measuring item height in variable-height owner-draw mode. ### ItemDraw ```vb Public Event ItemDraw(ByVal Item As Long, ByVal ItemAction As Long, ByVal ItemState As Long, ByVal hDC As Long, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` Fired when drawing an item in owner-draw mode. ### DropFiles ```vb Public Event DropFiles(ByRef FileList As Variant, ByVal X As Single, ByVal Y As Single) ``` Fired when files are dropped onto the control. ### ContextMenu ```vb Public Event ContextMenu(ByVal X As Single, ByVal Y As Single) ``` Fired when a context menu is requested. ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Preview key down event, fired before KeyDown. ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Preview key up event, fired before KeyUp. ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` Key pressed. ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` Key released. ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` Key character. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Mouse button pressed. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Mouse moved. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Mouse button released. ### MouseEnter ```vb Public Event MouseEnter() ``` Mouse entered the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Mouse left the control. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE drag-drop completed. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE drag-drop dropped. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE drag-drop hover. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE give feedback. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE set data. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE drag started. ## Code Examples ### Basic Usage ```vb ' Add list items ListBoxW1.AddItem "Item 1" ListBoxW1.AddItem "Item 2", 0 ' Set the currently selected item ListBoxW1.ListIndex = 0 ' Get selected item text Dim s As String s = ListBoxW1.Text ``` ### Checkbox and Option Styles ```vb ' Checkbox style (set at design time) ' ListBoxW1.Style = LstStyleCheckbox ' Get checked items Dim i As Long For i = 0 To ListBoxW1.ListCount - 1 If ListBoxW1.ItemChecked(i) Then Debug.Print ListBoxW1.List(i) End If Next i ``` ### Owner-Draw ```vb ' Variable-height owner-draw (set DrawMode = LstDrawModeOwnerDrawVariable at design time) Private Sub ListBoxW1_ItemMeasure(ByVal Item As Long, ByRef ItemHeight As Long) ItemHeight = 30 End Sub Private Sub ListBoxW1_ItemDraw(ByVal Item As Long, ByVal ItemAction As Long, _ ByVal ItemState As Long, ByVal hDC As Long, _ ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ' Custom drawing logic End Sub ``` ### Batch Addition ```vb ' Disable redraw to speed up batch addition ListBoxW1.Redraw = False Dim i As Long For i = 1 To 1000 ListBoxW1.AddItem "Item " & i Next i ListBoxW1.Redraw = True ``` --- --- url: /en/official/Reference/WinNativeCommonCtls/ImageList/ListImage.md --- # ListImage class A **ListImage** is one picture inside an [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/)'s [**ListImages**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages) collection. Returned from [**ListImages.Add**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages#add) and from [**ListImages.Item**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages#item). The class is tagged `[COMCreatable(False)]` --- user code never instantiates a **ListImage** directly; the [**ListImages**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages) collection creates them as part of its **Add** method. ```vb Dim img As ListImage = ImageList1.ListImages.Add(, "open", LoadPicture("open.ico")) img.Tag = "Open document command" ``` ## Properties ### Index The 1-based position of the image within the parent collection. **Long**, read-only. Equals [**ListImages.Item**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages#item)(*key*).Index for the same image. ### Key The string key the image was added under. **String**. Default: empty string. Lookups through [**ListImages.Item**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages#item) accept either the numeric **Index** or the string **Key**. ### Picture The original `StdPicture` that was passed to [**ListImages.Add**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages#add). **StdPicture**. The image list also keeps an internal scaled bitmap copy; modifying the returned **Picture** does not change what the list renders. ### Tag Arbitrary data the application can attach to the image. **Variant**. ## Methods ### Draw Renders the image into a Win32 device context at a given position. Useful for owner-draw scenarios where the application needs to paint the icon itself rather than going through a consumer control. Syntax: *object*.**Draw** *hDC* \[, *x* \[, *y* \[, *Style* ] ] ] *hDC* : An **OLE\_HANDLE** to the destination device context. *x* : *optional* A **Variant** containing the horizontal pixel offset. Default: 0. *y* : *optional* A **Variant** containing the vertical pixel offset. Default: 0. *Style* : *optional* A combination of [**ImlDrawConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) flags controlling the draw mode (normal, transparent, masked, selected, focused). Multiple flags can be **Or**-combined. ```vb Private Sub PictureBox1_Paint() ImageList1.ListImages("doc").Draw _ PictureBox1.hDC, 0, 0, _ ImlDrawTransparent Or ImlDrawSelected End Sub ``` ### ExtractIcon Returns a fresh `StdPicture` containing the image rendered as an `HICON`. Distinct from the [**Picture**](#picture) property, which returns the original bitmap; **ExtractIcon** is a new icon built from the cached bitmap with transparency applied. Syntax: *object*.**ExtractIcon** **As IPictureDisp** The returned **IPictureDisp** owns its icon handle and destroys it when it goes out of scope. ## See Also * [ImageList](/en/official/Reference/WinNativeCommonCtls/ImageList/) -- the parent control * [ListImages](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages) -- the collection holding **ListImage** instances * [ImlDrawConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) -- the *Style* flag combinations for [**Draw**](#draw) --- --- url: /zh/official/Reference/WinNativeCommonCtls/ImageList/ListImage.md --- # ListImage 类 **ListImage** 是 [**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/) 的 [**ListImages**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages) 集合中的一张图片。从 [**ListImages.Add**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages#add) 和 [**ListImages.Item**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages#item) 返回。 该类标记为 `[COMCreatable(False)]` --- 用户代码从不直接实例化 **ListImage**;[**ListImages**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages) 集合在 **Add** 方法中创建它们。 ```vb Dim img As ListImage = ImageList1.ListImages.Add(, "open", LoadPicture("open.ico")) img.Tag = "Open document command" ``` ## 属性 ### Index 图像在父集合中基于1的位置。**Long**,只读。等于同一图像的 [**ListImages.Item**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages#item)(*key*).Index。 ### Key 图像添加时的字符串键。**String**。默认:空字符串。通过 [**ListImages.Item**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages#item) 查找接受数字 **Index** 或字符串 **Key**。 ### Picture 传入 [**ListImages.Add**](/official/Reference/WinNativeCommonCtls/ImageList/ListImages#add) 的原始 `StdPicture`。**StdPicture**。图像列表还保留内部缩放位图副本;修改返回的 **Picture** 不会更改列表渲染的内容。 ### Tag 应用程序可附加到图像的任意数据。**Variant**。 ## 方法 ### Draw 将图像渲染到给定位置的Win32设备上下文中。适用于自绘场景,应用程序需要自行绘制图标而非通过消费控件。 语法:*object*.**Draw** *hDC* \[, *x* \[, *y* \[, *Style* ] ] ] *hDC* : 目标设备上下文的 **OLE\_HANDLE**。 *x* : *可选* 包含水平像素偏移的 **Variant**。默认:0。 *y* : *可选* 包含垂直像素偏移的 **Variant**。默认:0。 *Style* : *可选* [**ImlDrawConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) 标志的组合,控制绘制模式(普通、透明、蒙版、选中、聚焦)。多个标志可用 **Or** 组合。 ```vb Private Sub PictureBox1_Paint() ImageList1.ListImages("doc").Draw _ PictureBox1.hDC, 0, 0, _ ImlDrawTransparent Or ImlDrawSelected End Sub ``` ### ExtractIcon 返回一个包含以 `HICON` 渲染的图像的新 `StdPicture`。与返回原始位图的 [**Picture**](#picture) 属性不同;**ExtractIcon** 是从缓存位图构建并应用透明度的新图标。 语法:*object*.**ExtractIcon** **As IPictureDisp** 返回的 **IPictureDisp** 拥有其图标句柄并在超出作用域时销毁它。 ## 另见 * [ImageList](/official/Reference/WinNativeCommonCtls/ImageList/) --- 父控件 * [ListImages](/official/Reference/WinNativeCommonCtls/ImageList/ListImages) --- 持有 **ListImage** 实例的集合 * [ImlDrawConstants](/official/Reference/WinNativeCommonCtls/Enumerations/ImlDrawConstants) --- [**Draw**](#draw) 的 *Style* 标志组合 --- --- url: /en/official/Reference/WinNativeCommonCtls/ImageList/ListImages.md --- # ListImages class The **ListImages** collection is the entry point for managing the pictures inside an [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/). Accessed as `<imageList>.ListImages`; supports adding, removing, indexed access, and `For Each` iteration. The class is tagged `[COMCreatable(False)]` --- user code accesses **ListImages** through the parent [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/) control's [**ListImages**](/en/official/Reference/WinNativeCommonCtls/ImageList/#listimages) property, never by direct instantiation. ```vb With ImageList1.ListImages .Add , "doc", LoadPicture(App.Path & "\doc.ico") .Add , "folder", LoadPicture(App.Path & "\folder.ico") Debug.Print .Count ' 2 End With Dim img As ListImage For Each img In ImageList1.ListImages Debug.Print img.Index, img.Key Next ``` ## Modification while bound If the parent [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/) is bound to a consuming control (a [**ListView**](/en/official/Reference/WinNativeCommonCtls/ListView/) or [**TreeView**](/en/official/Reference/WinNativeCommonCtls/TreeView/) has it set as their image-list property), [**Clear**](#clear) and [**Remove**](#remove) raise run-time error 35617 (*"ImageList cannot be modified while another control is bound to it"*). [**Add**](#add) is unaffected --- new pictures can always be added. To rebuild a bound image list, first unbind by setting the consuming control's image-list property to **Nothing**. ## Properties ### Count The number of images in the collection. **Long**, read-only. ### Item Returns the [**ListImage**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImage) at the given index or with the given key. The default member, so `ImageList1.ListImages("doc")` works without writing `.Item("doc")`. Syntax: *object*.**Item** ( *Index* ) **As ListImage** *Index* : A **Variant** that is either a 1-based **Long** position in the collection or a **String** key (case-sensitive --- the collection uses `vbBinaryCompare`). ## Methods ### Add Adds a picture to the collection. Syntax: *object*.**Add** ( \[ *Index* ] \[, *Key* ] \[, *Picture* ] \[, *Tag* ] ) **As ListImage** *Index* : *optional* A **Long** giving the 1-based position at which to insert the new image. When omitted, the image is appended at the end. Out-of-range values raise run-time error 35600. *Key* : *optional* A **String** name under which the image can be looked up. When omitted, the image has no key. Numeric strings are rejected with run-time error 35603. Keys must be unique within the collection. *Picture* : *required* A **StdPicture** to add. Bitmaps (`vbPicTypeBitmap`) are scaled and masked according to [**MaskColor**](/en/official/Reference/WinNativeCommonCtls/ImageList/#maskcolor) / [**UseMaskColor**](/en/official/Reference/WinNativeCommonCtls/ImageList/#usemaskcolor). Icons (`vbPicTypeIcon`) are added directly with their own alpha mask. Omitting *Picture* raises run-time error 35607. *Tag* : *optional* Arbitrary data attached to the new image; available as [**ListImage.Tag**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImage#tag). Returns the newly-created [**ListImage**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImage). The first call to **Add** fixes [**ImageWidth**](/en/official/Reference/WinNativeCommonCtls/ImageList/#imagewidth) and [**ImageHeight**](/en/official/Reference/WinNativeCommonCtls/ImageList/#imageheight) (unless those were pre-set in the property sheet); all subsequent pictures are scaled to match. ### Clear Removes every picture from the collection. Resets [**ImageWidth**](/en/official/Reference/WinNativeCommonCtls/ImageList/#imagewidth) and [**ImageHeight**](/en/official/Reference/WinNativeCommonCtls/ImageList/#imageheight) to `0`, unlocking them for reassignment. Syntax: *object*.**Clear** Raises run-time error 35617 if the parent [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/) is currently bound to a consuming control. ### Exists Returns whether a picture with the given key exists in the collection. Syntax: *object*.**Exists** ( *Index* ) **As Boolean** *Index* : A **Variant**, coerced to a **String** for the lookup. Case-sensitive. ### Remove Removes a picture from the collection. The remaining pictures' [**Index**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImage#index) values are recomputed so subsequent lookups by index still work. Syntax: *object*.**Remove** ( *Index* ) *Index* : A **Variant** --- either a 1-based **Long** position or a **String** key. Out-of-range / non-existent values raise run-time error 35601. Non-string non-numeric values raise run-time error 35603. Raises run-time error 35617 if the parent [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/) is currently bound to a consuming control. ### \_NewEnum Returns the enumerator used by `For Each img In imageList.ListImages`. Iterates the pictures in **Index** order. Syntax: *object*.**\_NewEnum** **As Object** ## See Also * [ImageList](/en/official/Reference/WinNativeCommonCtls/ImageList/) -- the parent control * [ListImage](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImage) -- one picture in the collection --- --- url: /zh/official/Reference/WinNativeCommonCtls/ImageList/ListImages.md --- # ListImages 类 **ListImages** 集合是管理 [**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/) 内图片的入口。通过 `<imageList>.ListImages` 访问;支持添加、删除、索引访问和 `For Each` 迭代。 该类标记为 `[COMCreatable(False)]` --- 用户代码通过父级 [**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/) 控件的 [**ListImages**](/official/Reference/WinNativeCommonCtls/ImageList/#listimages) 属性访问 **ListImages**,从不直接实例化。 ```vb With ImageList1.ListImages .Add , "doc", LoadPicture(App.Path & "\doc.ico") .Add , "folder", LoadPicture(App.Path & "\folder.ico") Debug.Print .Count ' 2 End With Dim img As ListImage For Each img In ImageList1.ListImages Debug.Print img.Index, img.Key Next ``` ## 绑定时修改 如果父级 [**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/) 绑定到了消费控件([**ListView**](/official/Reference/WinNativeCommonCtls/ListView/) 或 [**TreeView**](/official/Reference/WinNativeCommonCtls/TreeView/) 已将其设为图像列表属性),[**Clear**](#clear) 和 [**Remove**](#remove) 引发运行时错误 35617(*"ImageList cannot be modified while another control is bound to it"*)。[**Add**](#add) 不受影响 --- 始终可以添加新图片。 要重建绑定的图像列表,先将消费控件的图像列表属性设为 **Nothing** 以解除绑定。 ## 属性 ### Count 集合中的图像数。**Long**,只读。 ### Item 返回给定索引或键的 [**ListImage**](/official/Reference/WinNativeCommonCtls/ImageList/ListImage)。默认成员,因此 `ImageList1.ListImages("doc")` 无须写 `.Item("doc")`。 语法:*object*.**Item**(*Index*)**As ListImage** *Index* : 一个 **Variant**,可以是集合中基于1的 **Long** 位置或 **String** 键(区分大小写 --- 集合使用 `vbBinaryCompare`)。 ## 方法 ### Add 向集合添加一张图片。 语法:*object*.**Add**(\[*Index*] \[, *Key*] \[, *Picture*] \[, *Tag*])**As ListImage** *Index* : *可选* 给出插入新图像基于1位置的 **Long**。省略时,图像追加到末尾。超出范围的值引发运行时错误 35600。 *Key* : *可选* 可用于查找图像的 **String** 名称。省略时,图像没有键。数字字符串会被拒绝并引发运行时错误 35603。键在集合内必须唯一。 *Picture* : *必需* 要添加的 **StdPicture**。位图(`vbPicTypeBitmap`)根据 [**MaskColor**](/official/Reference/WinNativeCommonCtls/ImageList/#maskcolor) / [**UseMaskColor**](/official/Reference/WinNativeCommonCtls/ImageList/#usemaskcolor) 进行缩放和蒙版。图标(`vbPicTypeIcon`)直接以其自身alpha蒙版添加。省略 *Picture* 引发运行时错误 35607。 *Tag* : *可选* 附加到新图像的任意数据;可通过 [**ListImage.Tag**](/official/Reference/WinNativeCommonCtls/ImageList/ListImage#tag) 访问。 返回新创建的 [**ListImage**](/official/Reference/WinNativeCommonCtls/ImageList/ListImage)。 第一次 **Add** 调用固定 [**ImageWidth**](/official/Reference/WinNativeCommonCtls/ImageList/#imagewidth) 和 [**ImageHeight**](/official/Reference/WinNativeCommonCtls/ImageList/#imageheight)(除非在属性表中预设);后续所有图片缩放以匹配。 ### Clear 从集合中移除所有图片。将 [**ImageWidth**](/official/Reference/WinNativeCommonCtls/ImageList/#imagewidth) 和 [**ImageHeight**](/official/Reference/WinNativeCommonCtls/ImageList/#imageheight) 重置为 `0`,解锁以供重新赋值。 语法:*object*.**Clear** 如果父级 [**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/) 当前绑定到消费控件,引发运行时错误 35617。 ### Exists 返回集合中是否存在具有给定键的图片。 语法:*object*.**Exists**(*Index*)**As Boolean** *Index* : 一个 **Variant**,强制转换为 **String** 进行查找。区分大小写。 ### Remove 从集合中移除一张图片。剩余图片的 [**Index**](/official/Reference/WinNativeCommonCtls/ImageList/ListImage#index) 值会重新计算,以便后续按索引查找仍然有效。 语法:*object*.**Remove**(*Index*) *Index* : 一个 **Variant** --- 可以是基于1的 **Long** 位置或 **String** 键。超出范围/不存在的值引发运行时错误 35601。非字符串非数值的值引发运行时错误 35603。 如果父级 [**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/) 当前绑定到消费控件,引发运行时错误 35617。 ### \_NewEnum 返回 `For Each img In imageList.ListImages` 使用的枚举器。按 **Index** 顺序迭代图片。 语法:*object*.**\_NewEnum** **As Object** ## 另见 * [ImageList](/official/Reference/WinNativeCommonCtls/ImageList/) --- 父控件 * [ListImage](/official/Reference/WinNativeCommonCtls/ImageList/ListImage) --- 集合中的一张图片 --- --- url: /en/official/Reference/WinNativeCommonCtls/ListView/ListItem.md --- # ListItem class A **ListItem** is a single row in a [**ListView**](/en/official/Reference/WinNativeCommonCtls/ListView/). Returned from [**ListItems.Add**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItems#add) and from [**ListItems.Item**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItems#item). In **lvwReport** view, the first column is the main label ([**Text**](#text)); subsequent columns are exposed through [**SubItems**](#subitemsindex)(*index*). The class is tagged `[COMCreatable(False)]` --- user code accesses **ListItem** instances through the parent [**ListView**](/en/official/Reference/WinNativeCommonCtls/ListView/)'s [**ListItems**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItems) collection, never by direct instantiation. ```vb Dim item As ListItem = ListView1.ListItems.Add(, "doc1", "Report.docx", "doc") item.SubItems(1) = "Word document" item.SubItems(2) = "24 KB" item.Bold = True item.ForeColor = vbBlue ``` ## Properties ### BackColor The background color used to render this row. **OLE\_COLOR**. Default: `-1` (transparent --- defer to [**ListView.BackColor**](#backcolor)). ### Bold Whether the row is rendered in a bold font. **Boolean**. Default: **False**. ### Checked Whether the row's checkbox is checked. **Boolean**. Only meaningful when [**ListView.CheckBoxes**](/en/official/Reference/WinNativeCommonCtls/ListView/#checkboxes) is **True**. ### EnsureVisible Scrolls the listview so this row is visible. Available as a method (not a property --- listed in the methods section below). ### ForeColor The text color used to render this row. **OLE\_COLOR**. Default: **vbWindowText**. ### Ghosted Whether the row is rendered as ghosted / cut (typically half-transparent). **Boolean**. The visual mirrors the Win32 `LVIS_CUT` state. ### Height The pixel height of the row's selection rectangle. **Single**, read-only. ### Icon The large icon for the row in [**lvwIcon**](/en/official/Reference/WinNativeCommonCtls/ListView/#listviewconstants) view. **Variant** --- either a 1-based **Long** index into [**ListView.Icons**](/en/official/Reference/WinNativeCommonCtls/ListView/#icons), or a **String** key. Assignment validates against the bound image list and raises run-time error 35601 (*"Element not found"*) for an unknown key, 35600 (*"Index out of bounds"*) for an out-of-range index, or 35613 (*"ImageList must be initialized before it can be used"*) if no image list is bound. ### Index The 1-based position of the row in the parent collection. **Long**, read-only. Attempting to assign raises run-time error 383. ### Key The string key the row was added under. **String**, read/write. Re-assignment moves the row inside the collection's internal index, preserving its position. ### Left The row's horizontal pixel position inside the listview. **Single**, read/write. Useful in [**lvwIcon**](/en/official/Reference/WinNativeCommonCtls/ListView/#listviewconstants) view for repositioning items. ### Selected Whether the row is selected. **Boolean**, read/write. Setting **Selected = True** also sets the focused state. ### SmallIcon The small icon for the row in non-icon views. **Variant** --- either an index or a key into [**ListView.SmallIcons**](/en/official/Reference/WinNativeCommonCtls/ListView/#smallicons). Same validation as [**Icon**](#icon). ### SubItems(Index) The sub-item text at the given 1-based column index in [**lvwReport**](/en/official/Reference/WinNativeCommonCtls/ListView/#listviewconstants) view. **String**, read/write. The main text is accessed through [**Text**](#text); **SubItems**(1) is the second column, **SubItems**(2) is the third, and so on. Index `0` is rejected with run-time error 380. Syntax: *object*.**SubItems**( *Index* ) \[ **=** *value* ] ### Tag Arbitrary data the application can attach to the row. **Variant**. ### Text The row's main label text. **String**, read/write. The default member. Maps to the listview item's column-0 text. ### ToolTipText A tooltip string shown when the user hovers over this row. **String**. Exposed through the listview's `LVS_EX_INFOTIP` extended style. ### Top The row's vertical pixel position inside the listview. **Single**, read/write. ### Width The pixel width of the row's selection rectangle. **Single**, read-only. ## Methods ### CreateDragImage ::: info **CreateDragImage** is tagged `[Unimplemented]` in the current source. Calling it has no useful effect --- the body is empty. ::: ### EnsureVisible Scrolls the listview so this row is visible. Syntax: *object*.**EnsureVisible** ## See Also * [ListView](/en/official/Reference/WinNativeCommonCtls/ListView/) -- the parent control * [ListItems](/en/official/Reference/WinNativeCommonCtls/ListView/ListItems) -- the collection holding **ListItem** instances * [ColumnHeader](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader) -- a column header (defines what [**SubItems**](#subitemsindex) align to) --- --- url: /zh/official/Reference/WinNativeCommonCtls/ListView/ListItem.md --- # ListItem 类 **ListItem** 是 [**ListView**](/official/Reference/WinNativeCommonCtls/ListView/) 中的单行。从 [**ListItems.Add**](/official/Reference/WinNativeCommonCtls/ListView/ListItems#add) 和 [**ListItems.Item**](/official/Reference/WinNativeCommonCtls/ListView/ListItems#item) 返回。在 **lvwReport** 视图中,第一列是主标签([**Text**](#text));后续列通过 [**SubItems**](#subitemsindex)(*index*) 暴露。 该类标记为 `[COMCreatable(False)]` --- 用户代码通过父级 [**ListView**](/official/Reference/WinNativeCommonCtls/ListView/) 的 [**ListItems**](/official/Reference/WinNativeCommonCtls/ListView/ListItems) 集合访问 **ListItem** 实例,从不直接实例化。 ```vb Dim item As ListItem = ListView1.ListItems.Add(, "doc1", "Report.docx", "doc") item.SubItems(1) = "Word document" item.SubItems(2) = "24 KB" item.Bold = True item.ForeColor = vbBlue ``` ## 属性 ### BackColor 用于渲染此行的背景颜色。**OLE\_COLOR**。默认:`-1`(透明 --- 延迟到 [**ListView.BackColor**](#backcolor))。 ### Bold 此行是否以粗体渲染。**Boolean**。默认:**False**。 ### Checked 此行的复选框是否选中。**Boolean**。仅在 [**ListView.CheckBoxes**](/official/Reference/WinNativeCommonCtls/ListView/#checkboxes) 为 **True** 时有意义。 ### EnsureVisible 滚动列表视图使此行可见。作为方法可用(不是属性 --- 在下方方法部分列出)。 ### ForeColor 用于渲染此行的文本颜色。**OLE\_COLOR**。默认:**vbWindowText**。 ### Ghosted 此行是否渲染为半透明/剪切状态。**Boolean**。视觉效果镜像Win32 `LVIS_CUT` 状态。 ### Height 行选择矩形的像素高度。**Single**,只读。 ### Icon [**lvwIcon**](/official/Reference/WinNativeCommonCtls/ListView/#listviewconstants) 视图中行的大图标。**Variant** --- 可以是基于1的 **Long** 索引指向 [**ListView.Icons**](/official/Reference/WinNativeCommonCtls/ListView/#icons),或 **String** 键。赋值对照绑定图像列表验证,未知键引发运行时错误 35601(*"Element not found"*),超出范围的索引引发 35600(*"Index out of bounds"*),无绑定图像列表引发 35613(*"ImageList must be initialized before it can be used"*)。 ### Index 此行在父集合中基于1的位置。**Long**,只读。尝试赋值引发运行时错误 383。 ### Key 此行添加时的字符串键。**String**,读/写。重新赋值会在集合的内部索引中移动行,保持其位置。 ### Left 行在列表视图内的水平像素位置。**Single**,读/写。在 [**lvwIcon**](/official/Reference/WinNativeCommonCtls/ListView/#listviewconstants) 视图中用于重新定位项。 ### Selected 此行是否选中。**Boolean**,读/写。设置 **Selected = True** 也会设置聚焦状态。 ### SmallIcon 非图标视图中行的小图标。**Variant** --- 可以是索引或指向 [**ListView.SmallIcons**](/official/Reference/WinNativeCommonCtls/ListView/#smallicons) 的键。与 [**Icon**](#icon) 相同的验证。 ### SubItems(Index) [**lvwReport**](/official/Reference/WinNativeCommonCtls/ListView/#listviewconstants) 视图中给定基于1的列索引的子项文本。**String**,读/写。主文本通过 [**Text**](#text) 访问;**SubItems**(1) 是第二列,**SubItems**(2) 是第三列,以此类推。索引 `0` 会被拒绝并引发运行时错误 380。 语法:*object*.**SubItems**(*Index*)\[ **=** *value* ] ### Tag 应用程序可附加到此行的任意数据。**Variant**。 ### Text 此行的主标签文本。**String**,读/写。默认成员。映射到列表视图项的第0列文本。 ### ToolTipText 用户悬停在此行上时显示的工具提示字符串。**String**。通过列表视图的 `LVS_EX_INFOTIP` 扩展样式暴露。 ### Top 行在列表视图内的垂直像素位置。**Single**,读/写。 ### Width 行选择矩形的像素宽度。**Single**,只读。 ## 方法 ### CreateDragImage ::: info **CreateDragImage** 在当前源码中标记为 `[Unimplemented]`。调用它没有实际效果 --- 方法体为空。 ::: ### EnsureVisible 滚动列表视图使此行可见。 语法:*object*.**EnsureVisible** ## 另见 * [ListView](/official/Reference/WinNativeCommonCtls/ListView/) --- 父控件 * [ListItems](/official/Reference/WinNativeCommonCtls/ListView/ListItems) --- 持有 **ListItem** 实例的集合 * [ColumnHeader](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader) --- 列标题(定义 [**SubItems**](#subitemsindex) 对齐的对象) --- --- url: /en/official/Reference/WinNativeCommonCtls/ListView/ListItems.md --- # ListItems class The **ListItems** collection is the entry point for managing the rows of a [**ListView**](/en/official/Reference/WinNativeCommonCtls/ListView/). Accessed as `<listView>.ListItems`; supports adding, removing, indexed access, and `For Each` iteration. The class is tagged `[COMCreatable(False)]` --- user code accesses **ListItems** through the parent [**ListView**](/en/official/Reference/WinNativeCommonCtls/ListView/) control's [**ListItems**](/en/official/Reference/WinNativeCommonCtls/ListView/#listitems) property. ```vb With ListView1.ListItems .Add , "doc1", "Report.docx" .Add , "doc2", "Budget.xlsx" .Add , "doc3", "Photos.zip" Debug.Print .Count ' 3 End With Dim item As ListItem For Each item In ListView1.ListItems Debug.Print item.Index, item.Key, item.Text Next ``` ## Properties ### Count The number of rows in the collection. **Long**, read-only. ### Item Returns the [**ListItem**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem) at the given index or with the given key. The default member, so `ListView1.ListItems("doc1")` works without writing `.Item("doc1")`. Syntax: *object*.**Item** ( *Index* ) **As ListItem** *Index* : A **Variant** --- either a 1-based **Long** position or a **String** key. ## Methods ### Add Adds a row to the listview. Syntax: *object*.**Add** ( \[ *Index* ] \[, *Key* ] \[, *Text* ] \[, *Icon* ] \[, *SmallIcon* ] ) **As ListItem** *Index* : *optional* A **Long** giving the 1-based position at which to insert the new row. When omitted, the row is appended at the end. Out-of-range values raise run-time error 35600. *Key* : *optional* A **String** name under which the row can be looked up. When omitted, the row has no key. Keys must be unique within the collection (otherwise run-time error 35602). *Text* : *optional* A **String** giving the row's main label. *Icon* : *optional* A **Variant** identifying the row's large icon --- either a 1-based **Long** index into [**ListView.Icons**](/en/official/Reference/WinNativeCommonCtls/ListView/#icons), or a **String** key. Validated against the bound image list. *SmallIcon* : *optional* A **Variant** identifying the row's small icon, against [**ListView.SmallIcons**](/en/official/Reference/WinNativeCommonCtls/ListView/#smallicons). Returns the newly-created [**ListItem**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem). ### Clear Removes every row from the listview. Syntax: *object*.**Clear** ### Remove Removes a row from the listview. The remaining rows' [**Index**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem#index) values are renumbered. Syntax: *object*.**Remove** ( *Index* ) *Index* : A **Variant** --- either a 1-based **Long** position or a **String** key. ### \_NewEnum Returns the enumerator used by `For Each item In listView.ListItems`. Iterates rows in **Index** order. Syntax: *object*.**\_NewEnum** **As stdole.IUnknown** ## See Also * [ListView](/en/official/Reference/WinNativeCommonCtls/ListView/) -- the parent control * [ListItem](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem) -- one row in the collection --- --- url: /zh/official/Reference/WinNativeCommonCtls/ListView/ListItems.md --- # ListItems 类 **ListItems** 集合是管理 [**ListView**](/official/Reference/WinNativeCommonCtls/ListView/) 行的入口。通过 `<listView>.ListItems` 访问;支持添加、删除、索引访问和 `For Each` 迭代。 该类标记为 `[COMCreatable(False)]` --- 用户代码通过父级 [**ListView**](/official/Reference/WinNativeCommonCtls/ListView/) 控件的 [**ListItems**](/official/Reference/WinNativeCommonCtls/ListView/#listitems) 属性访问 **ListItems**。 ```vb With ListView1.ListItems .Add , "doc1", "Report.docx" .Add , "doc2", "Budget.xlsx" .Add , "doc3", "Photos.zip" Debug.Print .Count ' 3 End With Dim item As ListItem For Each item In ListView1.ListItems Debug.Print item.Index, item.Key, item.Text Next ``` ## 属性 ### Count 集合中的行数。**Long**,只读。 ### Item 返回给定索引或键的 [**ListItem**](/official/Reference/WinNativeCommonCtls/ListView/ListItem)。默认成员,因此 `ListView1.ListItems("doc1")` 无须写 `.Item("doc1")`。 语法:*object*.**Item**(*Index*)**As ListItem** *Index* : 一个 **Variant** --- 可以是基于1的 **Long** 位置或 **String** 键。 ## 方法 ### Add 向列表视图添加一行。 语法:*object*.**Add**(\[*Index*] \[, *Key*] \[, *Text*] \[, *Icon*] \[, *SmallIcon*])**As ListItem** *Index* : *可选* 给出插入新行基于1位置的 **Long**。省略时,行追加到末尾。超出范围的值引发运行时错误 35600。 *Key* : *可选* 可用于查找行的 **String** 名称。省略时,行没有键。键在集合内必须唯一(否则运行时错误 35602)。 *Text* : *可选* 给出行的主标签的 **String**。 *Icon* : *可选* 标识行大图标的 **Variant** --- 可以是基于1的 **Long** 索引指向 [**ListView.Icons**](/official/Reference/WinNativeCommonCtls/ListView/#icons),或 **String** 键。对照绑定图像列表验证。 *SmallIcon* : *可选* 标识行小图标的 **Variant**,对照 [**ListView.SmallIcons**](/official/Reference/WinNativeCommonCtls/ListView/#smallicons)。 返回新创建的 [**ListItem**](/official/Reference/WinNativeCommonCtls/ListView/ListItem)。 ### Clear 从列表视图中移除所有行。 语法:*object*.**Clear** ### Remove 从列表视图中移除一行。剩余行的 [**Index**](/official/Reference/WinNativeCommonCtls/ListView/ListItem#index) 值会重新编号。 语法:*object*.**Remove**(*Index*) *Index* : 一个 **Variant** --- 可以是基于1的 **Long** 位置或 **String** 键。 ### \_NewEnum 返回 `For Each item In listView.ListItems` 使用的枚举器。按 **Index** 顺序迭代行。 语法:*object*.**\_NewEnum** **As stdole.IUnknown** ## 另见 * [ListView](/official/Reference/WinNativeCommonCtls/ListView/) --- 父控件 * [ListItem](/official/Reference/WinNativeCommonCtls/ListView/ListItem) --- 集合中的一行 --- --- url: /en/official/Reference/WinNativeCommonCtls/ListView.md --- # ListView class A **ListView** is a flexible multi-column / icon list with four distinct visual modes selected through the [**View**](#view) property: | [**View**](#view) | Description | |--------------------------------|------------------------------------------------------------------------------------| | **lvwIcon** | Large icons in a wrapping grid; each item shows an icon plus its label. | | **lvwSmallIcon** | Small icons in a wrapping grid. | | **lvwList** | A single column of small-icon-plus-label entries, wrapped into multiple columns to fit. | | **lvwReport** | Multi-column table view with header row; columns are defined through [**ColumnHeaders**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders). | The two main collections are accessed through properties: [**ListItems**](#listitems) for the rows, and [**ColumnHeaders**](#columnheaders) for the **Report**-view column headers. ```vb Private Sub Form_Load() ' Bind an image list and configure the view Set ListView1.SmallIcons = ImageList1 ListView1.View = lvwReport ' Define columns ListView1.ColumnHeaders.Add , "name", "Name", 150 ListView1.ColumnHeaders.Add , "type", "Type", 80 ListView1.ColumnHeaders.Add , "size", "Size", 80, lvwColumnRight ' Add rows Dim item As ListItem Set item = ListView1.ListItems.Add(, "doc1", "Report.docx", "doc") item.SubItems(1) = "Word document" item.SubItems(2) = "24 KB" End Sub Private Sub ListView1_ItemClick(Item As ListItem) Debug.Print "Clicked: " & Item.Text End Sub ``` The control inherits the focusable rect-dockable members from `BaseControlFocusable` --- size, position, **Anchors**, **Dock**, **Font**, **Appearance**, **MousePointer** / **MouseIcon**, **ToolTipText**, **DragMode** / **DragIcon**, **Drag**, **Refresh**, **SetFocus**, **TabIndex** / **TabStop**, **ZOrder**, **CausesValidation**, **VisualStyles**, **hWnd**, **HelpContextID** / **WhatsThisHelpID**. ## Image lists A **ListView** can bind to three independent [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/) instances, one per role: * **[Icons](#icons)** --- large icons rendered in **lvwIcon** view. * **[SmallIcons](#smallicons)** --- small icons rendered in **lvwSmallIcon**, **lvwList**, and **lvwReport** views. * **[ColumnHeaderIcons](#columnheadericons)** --- small icons rendered inside the report-view column headers, addressed per-column through [**ColumnHeader.Icon**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader#icon). A [**ListItem**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem) selects its icons through its **Icon** and **SmallIcon** properties, which can be either a 1-based **Long** index or a **String** key into the respective image list. ## Selection and label editing Selection is single-row by default; setting [**MultiSelect**](#multiselect) to **True** lets the user **Ctrl**-click and **Shift**-click multiple items. The currently focused item is exposed as [**SelectedItem**](#selecteditem) (a [**ListItem**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem)) and [**SelectedItemIndex**](#selecteditemindex) (a **Long**). [**ListItem.Selected**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem#selected) reads / writes selection on an individual row. [**LabelEdit**](#labeledit) controls inline label editing: * **lvwAutomatic** --- clicking an already-selected item starts an edit (after a short delay; this is the F2 / single-click-and-pause pattern). * **lvwManual** --- only programmatic [**StartLabelEdit**](#startlabeledit) calls open an editor. * **lvwDisabled** --- labels cannot be edited. Edit start fires [**BeforeLabelEdit**](#beforelabeledit) (cancellable), and edit end fires [**AfterLabelEdit**](#afterlabeledit) (cancellable, with the proposed new text). ## Sorting, column reordering, and the header In **lvwReport** view, clicking a column header fires [**ColumnClick**](#columnclick), letting the application implement sorting (the package does not auto-sort). When [**AllowColumnReorder**](#allowcolumnreorder) is **True** in **lvwReport** view, the user can drag column headers to reorder them; the resulting order is reflected through [**ColumnHeader.Position**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader#position). [**hWndHeader**](#hwndheader) is the Win32 handle of the embedded `SysHeader32` window, exposed for raw Win32 customization. ## Properties ### AllowColumnReorder Whether the user can drag column headers to reorder them. **Boolean**. Default: **False**. Only effective in **lvwReport** view. ### Appearance How the control's border is drawn. A [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants) member. Default: **vbAppear3d**. Inherited. ### Arrange How items are arranged in icon / small-icon view. A member of [**ListArrangeConstants**](#listarrangeconstants). Default: **lvwNone**. ### BackColor The background color of the list area. **OLE\_COLOR**. Default: **vbWindowBackground**. ### BorderStyle The control's border style. A [**TreeBorderStyleConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeBorderStyleConstants) member: **ccNone** or **ccFixedSingle**. Default: **ccFixedSingle**. The enum is shared with [**TreeView**](/en/official/Reference/WinNativeCommonCtls/TreeView/). ### CheckBoxes Whether each row has a leading checkbox. **Boolean**. Default: **False**. When **True**, fires [**ItemCheck**](#itemcheck) on click. ### ColumnHeaderIcons The [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/) used for column-header icons in **lvwReport** view. Individual columns reference an icon by setting [**ColumnHeader.Icon**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader#icon). ### ColumnHeaders The [**ColumnHeaders**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders) collection. Read-only. ### FlatScrollBar Whether the control uses flat (rather than 3D) scrollbars. **Boolean**. Default: **False**. ### FullRowSelect Whether clicking on any cell in a row selects the entire row (as opposed to clicking only on the first column's text). **Boolean**. Default: **False**. Only meaningful in **lvwReport** view. ### GridLines Whether gridlines are drawn between rows and columns. **Boolean**. Default: **False**. Only meaningful in **lvwReport** view. ### HideColumnHeaders Whether the column header row is hidden in **lvwReport** view. **Boolean**. Default: **False**. ### HideSelection Whether selection highlight is hidden when the control does not have focus. **Boolean**. Default: **True**. ### HotTracking Whether items are highlighted as the mouse hovers over them (and tracked-click selection is enabled). **Boolean**. Default: **False**. ### hWnd The Win32 handle of the listview window. **LongPtr**, read-only. ### hWndHeader The Win32 handle of the embedded column-header window (`SysHeader32`). **LongPtr**, read-only. Tagged `[Hidden]` `[NonBrowsable]` --- exposed only for advanced Win32 customization (e.g. subclassing the header). ### Icons The [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/) used for large icons in **lvwIcon** view. Assignment increments the bound-count on the **ImageList** (and decrements the previous one's); see the [bound-count caveat](/en/official/Reference/WinNativeCommonCtls/ImageList/#binding-to-consumers). ### LabelEdit How inline label editing is triggered. A member of [**ListLabelEditConstants**](#listlabeleditconstants). Default: **lvwAutomatic**. ### LabelWrap Whether item labels wrap to multiple lines in **lvwIcon** view. **Boolean**. Default: **True**. ### ListItems The [**ListItems**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItems) collection --- the rows of the list. Read-only. ### MultiSelect Whether the user can select multiple items. **Boolean**. Default: **False**. ### SelectedItem The currently focused [**ListItem**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem), or **Nothing** if no row is focused. Read-only --- to change selection, assign to [**ListItem.Selected**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem#selected). ### SelectedItemIndex The 1-based index of the currently focused row, or `-1` if no row is focused. **Long**, read-only. ### SmallIcons The [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/) used for small icons in **lvwSmallIcon**, **lvwList**, and **lvwReport** views. ### TextBackground Whether item-label text has an opaque background. A member of [**ListTextBackgroundConstants**](#listtextbackgroundconstants). Default: **lvwTransparent**. ### View The visual mode. A member of [**ListViewConstants**](#listviewconstants). Default: **lvwIcon**. ## Methods ### GetFirstVisible Returns the first [**ListItem**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem) currently visible in the viewport. Useful for virtualized scenarios where the application updates row content based on what the user is looking at. Syntax: *object*.**GetFirstVisible** **As ListItem** ### StartLabelEdit Opens the inline editor on the currently selected row. Used when [**LabelEdit**](#labeledit) is **lvwManual**. Syntax: *object*.**StartLabelEdit** ## Events ### AfterLabelEdit Raised when an inline label edit completes. Set *Cancel* to **True** to revert; *NewString* holds the user's proposed new text. Syntax: *object*\_**AfterLabelEdit**( *Cancel* **As Boolean**, *NewString* **As String** ) ### BeforeLabelEdit Raised when an inline label edit is about to start. Set *Cancel* to **True** to block the edit. Syntax: *object*\_**BeforeLabelEdit**( *Cancel* **As Boolean** ) ### Click Raised on a mouse click inside the control. Distinct from [**ItemClick**](#itemclick), which fires only when the click hits a row. Syntax: *object*\_**Click**( ) ### ColumnClick Raised when the user clicks a column header in **lvwReport** view. Syntax: *object*\_**ColumnClick**( *ColumnHeader* **As ColumnHeader** ) ### DblClick Raised on a double-click inside the control. Syntax: *object*\_**DblClick**( ) ### DragDrop, DragOver Inherited drag-drop events. ### Initialize Raised after the control's window has been created. ### ItemCheck Raised when the user toggles the checkbox on a row (only when [**CheckBoxes**](#checkboxes) is **True**). Syntax: *object*\_**ItemCheck**( *Item* **As ListItem** ) ### ItemClick Raised when a row becomes selected (via mouse click or keyboard navigation). Syntax: *object*\_**ItemClick**( *Item* **As ListItem** ) ### KeyDown, KeyPress, KeyUp Inherited keyboard events. ### MouseDown, MouseMove, MouseUp Inherited mouse events. ### OLECompleteDrag, OLEDragDrop, OLEDragOver, OLEGiveFeedback, OLESetData, OLEStartDrag Inherited OLE drag-and-drop events. ### Scroll ::: info The **Scroll** event is declared on the control but tagged `[Unimplemented]` in the current source. It is reserved for a future release; do not rely on it. ::: ### Validate Inherited validation event. ## ListViewConstants Determines the visual mode of a **ListView**. Declared on the **ListView** class. | Member | Value | Description | |-----------------------|-------|----------------------------------------------------------------------| | **lvwIcon** | 0 | Large icons in a wrapping grid. | | **lvwSmallIcon** | 1 | Small icons in a wrapping grid. | | **lvwList** | 2 | Single-column list (wrapping into multiple columns). | | **lvwReport** | 3 | Multi-column report view with header row. | ## ListArrangeConstants Determines how items are auto-arranged in icon / small-icon view. Declared on the **ListView** class. | Member | Value | Description | |------------------------|-------|--------------------------------------------------------| | **lvwNone** | 0 | No auto-arrangement; items stay where they were placed. | | **lvwAutoLeft** | 1 | Items auto-flow left-to-right. | | **lvwAutoTop** | 2 | Items auto-flow top-to-bottom. | ## ListTextBackgroundConstants Determines whether item-label text has an opaque or transparent background. Declared on the **ListView** class. | Member | Value | Description | |-----------------------|-------|-------------------------------------------------------------------| | **lvwTransparent** | 0 | Item text overlays the list background unchanged. | | **lvwOpaque** | 1 | Item text is drawn with an opaque background matching [**BackColor**](#backcolor). | ## ListLabelEditConstants Determines when inline label editing is triggered. Declared on the **ListView** class. | Member | Value | Description | |--------------------|-------|----------------------------------------------------------------------------| | **lvwAutomatic** | 0 | F2 or click-and-pause on a selected row starts an edit. | | **lvwManual** | 1 | Only [**StartLabelEdit**](#startlabeledit) opens an editor. | | **lvwDisabled** | 2 | Label editing is disabled entirely. | ## See Also * [ListItem](/en/official/Reference/WinNativeCommonCtls/ListView/ListItem) -- a single row * [ListItems](/en/official/Reference/WinNativeCommonCtls/ListView/ListItems) -- the collection of rows * [ColumnHeader](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader) -- a single column header (Report view) * [ColumnHeaders](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders) -- the column header collection * [ImageList](/en/official/Reference/WinNativeCommonCtls/ImageList/) -- the picture source for [**Icons**](#icons), [**SmallIcons**](#smallicons), and [**ColumnHeaderIcons**](#columnheadericons) * [TreeBorderStyleConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeBorderStyleConstants) -- the [**BorderStyle**](#borderstyle) enum shared with [**TreeView**](/en/official/Reference/WinNativeCommonCtls/TreeView/) * [ControlTypeConstants](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) -- where **vbListView** lives --- --- url: /zh/official/Reference/WinNativeCommonCtls/ListView.md --- # ListView 类 **ListView** 是一个灵活的多列/图标列表,通过 [**View**](#view) 属性选择四种不同的视觉模式: | [**View**](#view) | 描述 | |--------------------------------|------------------------------------------------------------------------------------| | **lvwIcon** | 换行网格中的大图标;每项显示图标加标签。 | | **lvwSmallIcon** | 换行网格中的小图标。 | | **lvwList** | 单列小图标加标签条目,换行成多列以适应宽度。 | | **lvwReport** | 带标题行的多列表格视图;列通过 [**ColumnHeaders**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders) 定义。 | 两个主要集合通过属性访问:[**ListItems**](#listitems) 用于行,[**ColumnHeaders**](#columnheaders) 用于 **Report** 视图的列标题。 ```vb Private Sub Form_Load() ' Bind an image list and configure the view Set ListView1.SmallIcons = ImageList1 ListView1.View = lvwReport ' Define columns ListView1.ColumnHeaders.Add , "name", "Name", 150 ListView1.ColumnHeaders.Add , "type", "Type", 80 ListView1.ColumnHeaders.Add , "size", "Size", 80, lvwColumnRight ' Add rows Dim item As ListItem Set item = ListView1.ListItems.Add(, "doc1", "Report.docx", "doc") item.SubItems(1) = "Word document" item.SubItems(2) = "24 KB" End Sub Private Sub ListView1_ItemClick(Item As ListItem) Debug.Print "Clicked: " & Item.Text End Sub ``` 控件从 `BaseControlFocusable` 继承可聚焦矩形可停靠成员 --- 大小、位置、**Anchors**、**Dock**、**Font**、**Appearance**、**MousePointer** / **MouseIcon**、**ToolTipText**、**DragMode** / **DragIcon**、**Drag**、**Refresh**、**SetFocus**、**TabIndex** / **TabStop**、**ZOrder**、**CausesValidation**、**VisualStyles**、**hWnd**、**HelpContextID** / **WhatsThisHelpID**。 ## 图像列表 **ListView** 可以绑定到三个独立的 [**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/) 实例,每个角色一个: * **[Icons](#icons)** --- 在 **lvwIcon** 视图中渲染的大图标。 * **[SmallIcons](#smallicons)** --- 在 **lvwSmallIcon**、**lvwList** 和 **lvwReport** 视图中渲染的小图标。 * **[ColumnHeaderIcons](#columnheadericons)** --- 在报告视图列标题内渲染的小图标,按列通过 [**ColumnHeader.Icon**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader#icon) 寻址。 [**ListItem**](/official/Reference/WinNativeCommonCtls/ListView/ListItem) 通过其 **Icon** 和 **SmallIcon** 属性选择图标,可以是基于1的 **Long** 索引或各自图像列表的 **String** 键。 ## 选择和标签编辑 默认为单行选择;将 [**MultiSelect**](#multiselect) 设为 **True** 允许用户 **Ctrl**-点击和 **Shift**-点击多项选择。当前聚焦项暴露为 [**SelectedItem**](#selecteditem)([**ListItem**](/official/Reference/WinNativeCommonCtls/ListView/ListItem))和 [**SelectedItemIndex**](#selecteditemindex)(**Long**)。[**ListItem.Selected**](/official/Reference/WinNativeCommonCtls/ListView/ListItem#selected) 读写单行的选中状态。 [**LabelEdit**](#labeledit) 控制内联标签编辑: * **lvwAutomatic** --- 点击已选中项开始编辑(短暂延迟后;即F2 / 单击并暂停模式)。 * **lvwManual** --- 仅编程调用 [**StartLabelEdit**](#startlabeledit) 打开编辑器。 * **lvwDisabled** --- 标签不可编辑。 编辑开始触发 [**BeforeLabelEdit**](#beforelabeledit)(可取消),编辑结束触发 [**AfterLabelEdit**](#afterlabeledit)(可取消,带有建议的新文本)。 ## 排序、列重排和标题 在 **lvwReport** 视图中,点击列标题触发 [**ColumnClick**](#columnclick),让应用程序实现排序(包不会自动排序)。当 [**AllowColumnReorder**](#allowcolumnreorder) 在 **lvwReport** 视图中为 **True** 时,用户可以拖动列标题重新排序;结果顺序通过 [**ColumnHeader.Position**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader#position) 反映。 [**hWndHeader**](#hwndheader) 是嵌入的 `SysHeader32` 窗口的Win32句柄,暴露用于原始Win32自定义。 ## 属性 ### AllowColumnReorder 用户是否可以拖动列标题重新排序。**Boolean**。默认:**False**。仅在 **lvwReport** 视图中有效。 ### Appearance 控件边框的绘制方式。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants) 的成员。默认:**vbAppear3d**。继承。 ### Arrange 在图标/小图标视图中如何排列项。[**ListArrangeConstants**](#listarrangeconstants) 的成员。默认:**lvwNone**。 ### BackColor 列表区域的背景颜色。**OLE\_COLOR**。默认:**vbWindowBackground**。 ### BorderStyle 控件的边框样式。[**TreeBorderStyleConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeBorderStyleConstants) 的成员:**ccNone** 或 **ccFixedSingle**。默认:**ccFixedSingle**。该枚举与 [**TreeView**](/official/Reference/WinNativeCommonCtls/TreeView/) 共享。 ### CheckBoxes 每行是否有前导复选框。**Boolean**。默认:**False**。为 **True** 时,点击触发 [**ItemCheck**](#itemcheck)。 ### ColumnHeaderIcons 在 **lvwReport** 视图中用于列标题图标的 [**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/)。各列通过 [**ColumnHeader.Icon**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader#icon) 引用图标。 ### ColumnHeaders [**ColumnHeaders**](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders) 集合。只读。 ### FlatScrollBar 控件是否使用平面(而非3D)滚动条。**Boolean**。默认:**False**。 ### FullRowSelect 点击行中任何单元格是否选中整行(而非仅点击第一列的文本)。**Boolean**。默认:**False**。仅在 **lvwReport** 视图中有意义。 ### GridLines 行和列之间是否绘制网格线。**Boolean**。默认:**False**。仅在 **lvwReport** 视图中有意义。 ### HideColumnHeaders 在 **lvwReport** 视图中列标题行是否隐藏。**Boolean**。默认:**False**。 ### HideSelection 控件没有焦点时选择高亮是否隐藏。**Boolean**。默认:**True**。 ### HotTracking 鼠标悬停时项是否高亮(并启用跟踪点击选择)。**Boolean**。默认:**False**。 ### hWnd 列表视图窗口的Win32句柄。**LongPtr**,只读。 ### hWndHeader 嵌入的列标题窗口(`SysHeader32`)的Win32句柄。**LongPtr**,只读。标记为 `[Hidden]` `[NonBrowsable]` --- 仅为高级Win32自定义(如子类化标题)暴露。 ### Icons 在 **lvwIcon** 视图中用于大图标的 [**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/)。赋值递增 **ImageList** 的绑定计数(并递减前一个的);参见[绑定计数注意事项](/official/Reference/WinNativeCommonCtls/ImageList/#binding-to-consumers)。 ### LabelEdit 内联标签编辑如何触发。[**ListLabelEditConstants**](#listlabeleditconstants) 的成员。默认:**lvwAutomatic**。 ### LabelWrap 在 **lvwIcon** 视图中项标签是否换行到多行。**Boolean**。默认:**True**。 ### ListItems [**ListItems**](/official/Reference/WinNativeCommonCtls/ListView/ListItems) 集合 --- 列表的行。只读。 ### MultiSelect 用户是否可以选择多个项。**Boolean**。默认:**False**。 ### SelectedItem 当前聚焦的 [**ListItem**](/official/Reference/WinNativeCommonCtls/ListView/ListItem),如果没有行聚焦则为 **Nothing**。只读 --- 要更改选择,赋值给 [**ListItem.Selected**](/official/Reference/WinNativeCommonCtls/ListView/ListItem#selected)。 ### SelectedItemIndex 当前聚焦行的基于1的索引,如果没有行聚焦则为 `-1`。**Long**,只读。 ### SmallIcons 在 **lvwSmallIcon**、**lvwList** 和 **lvwReport** 视图中用于小图标的 [**ImageList**](/official/Reference/WinNativeCommonCtls/ImageList/)。 ### TextBackground 项标签文本是否有不透明背景。[**ListTextBackgroundConstants**](#listtextbackgroundconstants) 的成员。默认:**lvwTransparent**。 ### View 视觉模式。[**ListViewConstants**](#listviewconstants) 的成员。默认:**lvwIcon**。 ## 方法 ### GetFirstVisible 返回当前视口中可见的第一个 [**ListItem**](/official/Reference/WinNativeCommonCtls/ListView/ListItem)。适用于虚拟化场景,应用程序根据用户正在查看的内容更新行内容。 语法:*object*.**GetFirstVisible** **As ListItem** ### StartLabelEdit 在当前选中的行上打开内联编辑器。当 [**LabelEdit**](#labeledit) 为 **lvwManual** 时使用。 语法:*object*.**StartLabelEdit** ## 事件 ### AfterLabelEdit 内联标签编辑完成时触发。将 *Cancel* 设为 **True** 以恢复;*NewString* 保存用户建议的新文本。 语法:*object*\_**AfterLabelEdit**(*Cancel* **As Boolean**,*NewString* **As String**) ### BeforeLabelEdit 内联标签编辑即将开始时触发。将 *Cancel* 设为 **True** 以阻止编辑。 语法:*object*\_**BeforeLabelEdit**(*Cancel* **As Boolean**) ### Click 在控件内鼠标点击时触发。与 [**ItemClick**](#itemclick) 不同,后者仅在点击命中行时触发。 语法:*object*\_**Click**( ) ### ColumnClick 用户在 **lvwReport** 视图中点击列标题时触发。 语法:*object*\_**ColumnClick**(*ColumnHeader* **As ColumnHeader**) ### DblClick 在控件内双击时触发。 语法:*object*\_**DblClick**( ) ### DragDrop, DragOver 继承的拖放事件。 ### Initialize 控件窗口创建后触发。 ### ItemCheck 用户切换行上的复选框时触发(仅在 [**CheckBoxes**](#checkboxes) 为 **True** 时)。 语法:*object*\_**ItemCheck**(*Item* **As ListItem**) ### ItemClick 当行被选中时触发(通过鼠标点击或键盘导航)。 语法:*object*\_**ItemClick**(*Item* **As ListItem**) ### KeyDown, KeyPress, KeyUp 继承的键盘事件。 ### MouseDown, MouseMove, MouseUp 继承的鼠标事件。 ### OLECompleteDrag, OLEDragDrop, OLEDragOver, OLEGiveFeedback, OLESetData, OLEStartDrag 继承的OLE拖放事件。 ### Scroll ::: info **Scroll** 事件在控件上声明但当前源码中标记为 `[Unimplemented]`。保留用于未来版本;请勿依赖它。 ::: ### Validate 继承的验证事件。 ## ListViewConstants 确定 **ListView** 的视觉模式。在 **ListView** 类上声明。 | 成员 | 值 | 描述 | |-----------------------|-------|----------------------------------------------------------------------| | **lvwIcon** | 0 | 换行网格中的大图标。 | | **lvwSmallIcon** | 1 | 换行网格中的小图标。 | | **lvwList** | 2 | 单列列表(换行成多列)。 | | **lvwReport** | 3 | 带标题行的多列报告视图。 | ## ListArrangeConstants 确定在图标/小图标视图中如何自动排列项。在 **ListView** 类上声明。 | 成员 | 值 | 描述 | |------------------------|-------|--------------------------------------------------------| | **lvwNone** | 0 | 无自动排列;项保持放置位置。 | | **lvwAutoLeft** | 1 | 项自动从左到右流动。 | | **lvwAutoTop** | 2 | 项自动从上到下流动。 | ## ListTextBackgroundConstants 确定项标签文本是否具有不透明或透明背景。在 **ListView** 类上声明。 | 成员 | 值 | 描述 | |-----------------------|-------|-------------------------------------------------------------------| | **lvwTransparent** | 0 | 项文本直接叠加在列表背景上。 | | **lvwOpaque** | 1 | 项文本以匹配 [**BackColor**](#backcolor) 的不透明背景绘制。 | ## ListLabelEditConstants 确定何时触发内联标签编辑。在 **ListView** 类上声明。 | 成员 | 值 | 描述 | |--------------------|-------|----------------------------------------------------------------------------| | **lvwAutomatic** | 0 | F2或点击并暂停选中行开始编辑。 | | **lvwManual** | 1 | 仅 [**StartLabelEdit**](#startlabeledit) 打开编辑器。 | | **lvwDisabled** | 2 | 完全禁用标签编辑。 | ## 另见 * [ListItem](/official/Reference/WinNativeCommonCtls/ListView/ListItem) --- 单行 * [ListItems](/official/Reference/WinNativeCommonCtls/ListView/ListItems) --- 行集合 * [ColumnHeader](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeader) --- 单个列标题(Report视图) * [ColumnHeaders](/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders) --- 列标题集合 * [ImageList](/official/Reference/WinNativeCommonCtls/ImageList/) --- [**Icons**](#icons)、[**SmallIcons**](#smallicons) 和 [**ColumnHeaderIcons**](#columnheadericons) 的图片来源 * [TreeBorderStyleConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeBorderStyleConstants) --- 与 [**TreeView**](/official/Reference/WinNativeCommonCtls/TreeView/) 共享的 [**BorderStyle**](#borderstyle) 枚举 * [ControlTypeConstants](/official/Reference/VBRUN/Constants/ControlTypeConstants) --- **vbListView** 所在位置 --- --- url: /en/packages/vbccr/views/listview.md description: >- ListView Control - VBCCR Developer Reference, complete API documentation based on source code --- # ListView Control Wraps the SysListView32 system list view control, supporting large icon, small icon, list, report, and tile views, as well as grouping, virtual mode, column filtering, and other advanced features. ## Enumerations ### LvwViewConstants | Constant | Value | Description | |----------|-------|-------------| | LvwViewIcon | 0 | Large icon view | | LvwViewSmallIcon | 1 | Small icon view | | LvwViewList | 2 | List view | | LvwViewReport | 3 | Report view | | LvwViewTile | 4 | Tile view | ### LvwArrangeConstants | Constant | Value | Description | |----------|-------|-------------| | LvwArrangeNone | 0 | No arrangement | | LvwArrangeAutoLeft | 1 | Auto arrange left | | LvwArrangeAutoTop | 2 | Auto arrange top | | LvwArrangeLeft | 3 | Arrange left | | LvwArrangeTop | 4 | Arrange top | ### LvwColumnHeaderAlignmentConstants | Constant | Value | Description | |----------|-------|-------------| | LvwColumnHeaderAlignmentLeft | 0 | Left aligned | | LvwColumnHeaderAlignmentRight | 1 | Right aligned | | LvwColumnHeaderAlignmentCenter | 2 | Centered | ### LvwColumnHeaderSortArrowConstants | Constant | Value | Description | |----------|-------|-------------| | LvwColumnHeaderSortArrowNone | 0 | No sort arrow | | LvwColumnHeaderSortArrowDown | 1 | Down arrow (ascending) | | LvwColumnHeaderSortArrowUp | 2 | Up arrow (descending) | ### LvwColumnHeaderAutoSizeConstants | Constant | Value | Description | |----------|-------|-------------| | LvwColumnHeaderAutoSizeToItems | 0 | Auto size to items | | LvwColumnHeaderAutoSizeToHeader | 1 | Auto size to header | ### LvwColumnHeaderFilterTypeConstants | Constant | Value | Description | |----------|-------|-------------| | LvwColumnHeaderFilterTypeText | 0 | Text filter | | LvwColumnHeaderFilterTypeNumber | 1 | Number filter | ### LvwLabelEditConstants | Constant | Value | Description | |----------|-------|-------------| | LvwLabelEditAutomatic | 0 | Automatic label edit | | LvwLabelEditManual | 1 | Manual label edit | | LvwLabelEditDisabled | 2 | Label edit disabled | ### LvwSortOrderConstants | Constant | Value | Description | |----------|-------|-------------| | LvwSortOrderAscending | 0 | Ascending order | | LvwSortOrderDescending | 1 | Descending order | ### LvwSortTypeConstants | Constant | Value | Description | |----------|-------|-------------| | LvwSortTypeBinary | 0 | Binary sort | | LvwSortTypeText | 1 | Text sort | | LvwSortTypeNumeric | 2 | Numeric sort | | LvwSortTypeCurrency | 3 | Currency sort | | LvwSortTypeDate | 4 | Date sort | | LvwSortTypeLogical | 5 | Logical sort | ### LvwPictureAlignmentConstants | Constant | Value | Description | |----------|-------|-------------| | LvwPictureAlignmentTopLeft | 0 | Top left | | LvwPictureAlignmentTopRight | 1 | Top right | | LvwPictureAlignmentBottomLeft | 2 | Bottom left | | LvwPictureAlignmentBottomRight | 3 | Bottom right | | LvwPictureAlignmentCenter | 4 | Centered | | LvwPictureAlignmentTile | 5 | Tiled | ### LvwGroupHeaderAlignmentConstants | Constant | Value | Description | |----------|-------|-------------| | LvwGroupHeaderAlignmentLeft | 0 | Left aligned | | LvwGroupHeaderAlignmentRight | 1 | Right aligned | | LvwGroupHeaderAlignmentCenter | 2 | Centered | ### LvwGroupFooterAlignmentConstants | Constant | Value | Description | |----------|-------|-------------| | LvwGroupFooterAlignmentLeft | 0 | Left aligned | | LvwGroupFooterAlignmentRight | 1 | Right aligned | | LvwGroupFooterAlignmentCenter | 2 | Centered | ### LvwVisualThemeConstants | Constant | Value | Description | |----------|-------|-------------| | LvwVisualThemeStandard | 0 | Standard theme | | LvwVisualThemeExplorer | 1 | Explorer theme | ### LvwVirtualPropertyConstants | Constant | Value | Description | |----------|-------|-------------| | LvwVirtualPropertyText | 1 | Text property | | LvwVirtualPropertyIcon | 2 | Icon property | | LvwVirtualPropertyIndentation | 4 | Indentation property | | LvwVirtualPropertyToolTipText | 8 | ToolTip text property | | LvwVirtualPropertyBold | 16 | Bold property | | LvwVirtualPropertyForeColor | 32 | Fore color property | | LvwVirtualPropertyChecked | 64 | Checked property | ### LvwFindDirectionConstants | Constant | Value | Description | |----------|-------|-------------| | LvwFindDirectionUndefined | 0 | Undefined | | LvwFindDirectionPrior | vbKeyPageUp | Page up direction | | LvwFindDirectionNext | vbKeyPageDown | Page down direction | | LvwFindDirectionEnd | vbKeyEnd | End direction | | LvwFindDirectionHome | vbKeyHome | Home direction | | LvwFindDirectionLeft | vbKeyLeft | Left direction | | LvwFindDirectionUp | vbKeyUp | Up direction | | LvwFindDirectionRight | vbKeyRight | Right direction | | LvwFindDirectionDown | vbKeyDown | Down direction | ### CCBorderStyleConstants See common enumerations. ### CCAppearanceConstants See common enumerations. ### CCMousePointerConstants See common enumerations. ### CCIMEModeConstants See common enumerations. ### CCBackStyleConstants See common enumerations. ### CCRightToLeftModeConstants See common enumerations. ### CCScrollOrientationConstants See common enumerations. ### OLEDropModeConstants See common enumerations. ## Properties ### View ```vb Property Get View() As LvwViewConstants Property Let View(ByVal Value As LvwViewConstants) ``` View mode. ### Arrange ```vb Property Get Arrange() As LvwArrangeConstants Property Let Arrange(ByVal Value As LvwArrangeConstants) ``` Icon arrangement. ### SortKey ```vb Property Get SortKey() As Integer Property Let SortKey(ByVal Value As Integer) ``` Sort key column index. ### SortOrder ```vb Property Get SortOrder() As LvwSortOrderConstants Property Let SortOrder(ByVal Value As LvwSortOrderConstants) ``` Sort order. ### SortType ```vb Property Get SortType() As LvwSortTypeConstants Property Let SortType(ByVal Value As LvwSortTypeConstants) ``` Sort type. ### Sorted ```vb Property Get Sorted() As Boolean Property Let Sorted(ByVal Value As Boolean) ``` Whether sorting is enabled. ### LabelEdit ```vb Property Get LabelEdit() As LvwLabelEditConstants Property Let LabelEdit(ByVal Value As LvwLabelEditConstants) ``` Label edit mode. ### LabelWrap ```vb Property Get LabelWrap() As Boolean Property Let LabelWrap(ByVal Value As Boolean) ``` Whether label text wrapping is allowed. ### MultiSelect ```vb Property Get MultiSelect() As Boolean Property Let MultiSelect(ByVal Value As Boolean) ``` Whether multiple selection is allowed. ### FullRowSelect ```vb Property Get FullRowSelect() As Boolean Property Let FullRowSelect(ByVal Value As Boolean) ``` Whether full row selection is enabled. ### GridLines ```vb Property Get GridLines() As Boolean Property Let GridLines(ByVal Value As Boolean) ``` Whether grid lines are displayed. ### Checkboxes ```vb Property Get Checkboxes() As Boolean Property Let Checkboxes(ByVal Value As Boolean) ``` Whether checkboxes are displayed. ### HideSelection ```vb Property Get HideSelection() As Boolean Property Let HideSelection(ByVal Value As Boolean) ``` Whether the selection is hidden when the control loses focus. ### HideColumnHeaders ```vb Property Get HideColumnHeaders() As Boolean Property Let HideColumnHeaders(ByVal Value As Boolean) ``` Whether column headers are hidden. ### AllowColumnReorder ```vb Property Get AllowColumnReorder() As Boolean Property Let AllowColumnReorder(ByVal Value As Boolean) ``` Whether column reordering by dragging is allowed. ### AllowColumnCheckboxes ```vb Property Get AllowColumnCheckboxes() As Boolean Property Let AllowColumnCheckboxes(ByVal Value As Boolean) ``` Whether column checkboxes are allowed. ### AllowDropFiles ```vb Property Get AllowDropFiles() As Boolean Property Let AllowDropFiles(ByVal Value As Boolean) ``` Whether dropping files is allowed. ### ShowInfoTips ```vb Property Get ShowInfoTips() As Boolean Property Let ShowInfoTips(ByVal Value As Boolean) ``` Whether info tips are displayed. ### ShowLabelTips ```vb Property Get ShowLabelTips() As Boolean Property Let ShowLabelTips(ByVal Value As Boolean) ``` Whether label tips are displayed. ### ShowColumnTips ```vb Property Get ShowColumnTips() As Boolean Property Let ShowColumnTips(ByVal Value As Boolean) ``` Whether column tips are displayed. ### DoubleBuffer ```vb Property Get DoubleBuffer() As Boolean Property Let DoubleBuffer(ByVal Value As Boolean) ``` Whether double buffering is enabled. ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` Whether visual styles are enabled. ### VisualTheme ```vb Property Get VisualTheme() As LvwVisualThemeConstants Property Let VisualTheme(ByVal Value As LvwVisualThemeConstants) ``` Visual theme. ### HoverSelection ```vb Property Get HoverSelection() As Boolean Property Let HoverSelection(ByVal Value As Boolean) ``` Whether hover selection is enabled. ### HoverSelectionTime ```vb Property Get HoverSelectionTime() As Long Property Let HoverSelectionTime(ByVal Value As Long) ``` Hover selection delay time (milliseconds). ### HotTracking ```vb Property Get HotTracking() As Boolean Property Let HotTracking(ByVal Value As Boolean) ``` Whether hot tracking is enabled. ### HighlightHot ```vb Property Get HighlightHot() As Boolean Property Let HighlightHot(ByVal Value As Boolean) ``` Whether hot items are highlighted. ### UnderlineHot ```vb Property Get UnderlineHot() As Boolean Property Let UnderlineHot(ByVal Value As Boolean) ``` Whether hot items are underlined. ### InsertMarkColor ```vb Property Get InsertMarkColor() As OLE_COLOR Property Let InsertMarkColor(ByVal Value As OLE_COLOR) ``` Insert mark color. ### TextBackground ```vb Property Get TextBackground() As CCBackStyleConstants Property Let TextBackground(ByVal Value As CCBackStyleConstants) ``` Text background style. See common enumerations. ### ClickableColumnHeaders ```vb Property Get ClickableColumnHeaders() As Boolean Property Let ClickableColumnHeaders(ByVal Value As Boolean) ``` Whether column headers are clickable. ### HighlightColumnHeaders ```vb Property Get HighlightColumnHeaders() As Boolean Property Let HighlightColumnHeaders(ByVal Value As Boolean) ``` Whether column headers are highlighted. ### TrackSizeColumnHeaders ```vb Property Get TrackSizeColumnHeaders() As Boolean Property Let TrackSizeColumnHeaders(ByVal Value As Boolean) ``` Whether column header size tracking is enabled. ### ResizableColumnHeaders ```vb Property Get ResizableColumnHeaders() As Boolean Property Let ResizableColumnHeaders(ByVal Value As Boolean) ``` Whether column headers are resizable. ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` Background picture. ### PictureAlignment ```vb Property Get PictureAlignment() As LvwPictureAlignmentConstants Property Let PictureAlignment(ByVal Value As LvwPictureAlignmentConstants) ``` Background picture alignment. ### PictureWatermark ```vb Property Get PictureWatermark() As Boolean Property Let PictureWatermark(ByVal Value As Boolean) ``` Whether the background picture is used as a watermark. ### TileViewLines ```vb Property Get TileViewLines() As Long Property Let TileViewLines(ByVal Value As Long) ``` Number of text lines in tile view. ### SnapToGrid ```vb Property Get SnapToGrid() As Boolean Property Let SnapToGrid(ByVal Value As Boolean) ``` Whether snap to grid is enabled. ### GroupView ```vb Property Get GroupView() As Boolean Property Let GroupView(ByVal Value As Boolean) ``` Whether group view is enabled. ### GroupSubsetCount ```vb Property Get GroupSubsetCount() As Long Property Let GroupSubsetCount(ByVal Value As Long) ``` Number of items displayed in a group subset. ### UseColumnChevron ```vb Property Get UseColumnChevron() As Boolean Property Let UseColumnChevron(ByVal Value As Boolean) ``` Whether column chevrons are used. ### UseColumnFilterBar ```vb Property Get UseColumnFilterBar() As Boolean Property Let UseColumnFilterBar(ByVal Value As Boolean) ``` Whether the column filter bar is used. ### AutoSelectFirstItem ```vb Property Get AutoSelectFirstItem() As Boolean Property Let AutoSelectFirstItem(ByVal Value As Boolean) ``` Whether the first item is automatically selected. ### IMEMode ```vb Property Get IMEMode() As CCIMEModeConstants Property Let IMEMode(ByVal Value As CCIMEModeConstants) ``` Input method editor mode. See common enumerations. ### VirtualMode ```vb Property Get VirtualMode() As Boolean Property Let VirtualMode(ByVal Value As Boolean) ``` Whether virtual mode is enabled. ### VirtualItemCount ```vb Property Get VirtualItemCount() As Long Property Let VirtualItemCount(ByVal Value As Long) ``` Total item count in virtual mode. ### VirtualDisabledInfos ```vb Property Get VirtualDisabledInfos() As LvwVirtualPropertyConstants Property Let VirtualDisabledInfos(ByVal Value As LvwVirtualPropertyConstants) ``` Disabled property mask in virtual mode. ### ListItems ```vb Property Get ListItems() As LvwListItems ``` List items collection. Read-only. ### VirtualListItems ```vb Property Get VirtualListItems() As LvwVirtualListItems ``` Virtual list items collection. Read-only. ### ColumnHeaders ```vb Property Get ColumnHeaders() As LvwColumnHeaders ``` Column headers collection. Read-only. ### Groups ```vb Property Get Groups() As LvwGroups ``` Groups collection. Read-only. ### WorkAreas ```vb Property Get WorkAreas() As LvwWorkAreas ``` Work areas collection. Read-only. ### TopItem ```vb Property Get TopItem() As LvwListItem ``` First visible item. Read-only. ### SelectedItem ```vb Property Get SelectedItem() As LvwListItem Property Let SelectedItem(ByVal Value As LvwListItem) Property Set SelectedItem(ByVal Value As LvwListItem) ``` Currently selected item. ### HotItem ```vb Property Get HotItem() As LvwListItem Property Let HotItem(ByVal Value As LvwListItem) Property Set HotItem(ByVal Value As LvwListItem) ``` Hot item (the item under the mouse cursor). ### SelectionMark ```vb Property Get SelectionMark() As LvwListItem Property Let SelectionMark(ByVal Value As LvwListItem) Property Set SelectionMark(ByVal Value As LvwListItem) ``` Selection mark item. ### DropHighlight ```vb Property Get DropHighlight() As LvwListItem Property Let DropHighlight(ByVal Value As LvwListItem) Property Set DropHighlight(ByVal Value As LvwListItem) ``` Drop highlight item. ### InsertMark ```vb Property Get InsertMark(Optional ByRef After As Boolean) As LvwListItem Property Let InsertMark(Optional ByRef After As Boolean, ByVal Value As LvwListItem) Property Set InsertMark(Optional ByRef After As Boolean, ByVal Value As LvwListItem) ``` Insert mark item. ### OLEDraggedItem ```vb Property Get OLEDraggedItem() As LvwListItem ``` The item being dragged during an OLE drag-and-drop operation. Read-only. ### SelectedGroup ```vb Property Get SelectedGroup() As LvwGroup Property Let SelectedGroup(ByVal Value As LvwGroup) Property Set SelectedGroup(ByVal Value As LvwGroup) ``` Currently selected group. ### SelectedColumn ```vb Property Get SelectedColumn() As LvwColumnHeader Property Let SelectedColumn(ByVal Value As LvwColumnHeader) Property Set SelectedColumn(ByVal Value As LvwColumnHeader) ``` Currently selected column. ### ColumnOrder ```vb Property Get ColumnOrder() As Variant Property Let ColumnOrder(ByVal ArgList As Variant) ``` Column order array. ### ColumnWidth ```vb Property Get ColumnWidth() As Single Property Let ColumnWidth(ByVal Value As Single) ``` Current column width. ### ColumnFilterChangedTimeout ```vb Property Get ColumnFilterChangedTimeout() As Long Property Let ColumnFilterChangedTimeout(ByVal Value As Long) ``` Column filter change timeout. ### IconSpacingWidth ```vb Property Get IconSpacingWidth() As Single Property Let IconSpacingWidth(ByVal Value As Single) ``` Icon spacing width. ### IconSpacingHeight ```vb Property Get IconSpacingHeight() As Single Property Let IconSpacingHeight(ByVal Value As Single) ``` Icon spacing height. ### IncrementalSearchString ```vb Property Get IncrementalSearchString() As String ``` Incremental search string. Read-only. ### Redraw ```vb Property Get Redraw() As Boolean Property Let Redraw(ByVal Value As Boolean) ``` Whether redrawing is enabled. ### BorderStyle ```vb Property Get BorderStyle() As CCBorderStyleConstants Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` Border style. See common enumerations. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` Foreground color. ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` Font. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### Icons ```vb Property Get Icons() As Variant Property Set Icons(ByVal Value As Variant) Property Let Icons(ByVal Value As Variant) ``` Large icon image list. ### SmallIcons ```vb Property Get SmallIcons() As Variant Property Set SmallIcons(ByVal Value As Variant) Property Let SmallIcons(ByVal Value As Variant) ``` Small icon image list. ### ColumnHeaderIcons ```vb Property Get ColumnHeaderIcons() As Variant Property Set ColumnHeaderIcons(ByVal Value As Variant) Property Let ColumnHeaderIcons(ByVal Value As Variant) ``` Column header image list. ### GroupIcons ```vb Property Get GroupIcons() As Variant Property Set GroupIcons(ByVal Value As Variant) Property Let GroupIcons(ByVal Value As Variant) ``` Group header image list. ### OLEDragMode ```vb Property Get OLEDragMode() As VBRUN.OLEDragConstants Property Let OLEDragMode(ByVal Value As VBRUN.OLEDragConstants) ``` OLE drag mode. ### OLEDragDropScroll ```vb Property Get OLEDragDropScroll() As Boolean Property Let OLEDragDropScroll(ByVal Value As Boolean) ``` Whether automatic scrolling is enabled during OLE drag-and-drop. ### OLEDragDropScrollOrientation ```vb Property Get OLEDragDropScrollOrientation() As CCScrollOrientationConstants Property Let OLEDragDropScrollOrientation(ByVal Value As CCScrollOrientationConstants) ``` OLE drag-and-drop auto-scroll orientation. See common enumerations. ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE drop mode. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` Mouse pointer style. See common enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` Custom mouse icon. ### HotMousePointer ```vb Property Get HotMousePointer() As CCMousePointerConstants Property Let HotMousePointer(ByVal Value As CCMousePointerConstants) ``` Hot item mouse pointer style. See common enumerations. ### HotMouseIcon ```vb Property Get HotMouseIcon() As IPictureDisp Property Let HotMouseIcon(ByVal Value As IPictureDisp) Property Set HotMouseIcon(ByVal Value As IPictureDisp) ``` Hot item custom mouse icon. ### HeaderMousePointer ```vb Property Get HeaderMousePointer() As CCMousePointerConstants Property Let HeaderMousePointer(ByVal Value As CCMousePointerConstants) ``` Column header mouse pointer style. See common enumerations. ### HeaderMouseIcon ```vb Property Get HeaderMouseIcon() As IPictureDisp Property Let HeaderMouseIcon(ByVal Value As IPictureDisp) Property Set HeaderMouseIcon(ByVal Value As IPictureDisp) ``` Column header custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Whether mouse enter/leave tracking is enabled. ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` Right-to-left display direction. ### RightToLeftLayout ```vb Property Get RightToLeftLayout() As Boolean Property Let RightToLeftLayout(ByVal Value As Boolean) ``` Right-to-left mirrored layout. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` Right-to-left mode. See common enumerations. ### hWnd ```vb Property Get hWnd() As LongPtr ``` Window handle of the list view control. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Window handle of the user control. ### hWndHeader ```vb Property Get hWndHeader() As LongPtr ``` Window handle of the column header control. ### hWndLabelEdit ```vb Property Get hWndLabelEdit() As LongPtr ``` Window handle of the label edit box. ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` ToolTip text. ### Name ```vb Property Get Name() As String ``` Control name. Read-only. ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` Custom data. ### Parent ```vb Property Get Parent() As Object ``` Parent object. Read-only. ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` Container object. ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` Left edge distance. ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` Top edge distance. ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` Width. ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` Height. ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` Whether the control is visible. ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` Help context ID. ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "What's This" help ID. ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` Drag icon. ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` Drag mode. ## Methods ### Refresh ```vb Public Sub Refresh() ``` Forces a redraw of the control. ### HitTest ```vb Public Function HitTest(ByVal X As Single, ByVal Y As Single, Optional ByRef SubItemIndex As Variant) As LvwListItem ``` Hit test; returns the list item at the specified coordinates. ### HitTestInsertMark ```vb Public Function HitTestInsertMark(ByVal X As Single, ByVal Y As Single, Optional ByRef After As Boolean) As LvwListItem ``` Insert mark hit test; returns the list item at the insertion position. ### FindItem ```vb Public Function FindItem(ByVal Text As String, Optional ByVal Index As Long, Optional ByVal Partial As Boolean, Optional ByVal Wrap As Boolean) As LvwListItem ``` Finds a list item matching the specified text. ### FindNearestItem ```vb Public Function FindNearestItem(ByVal X As Single, ByVal Y As Single, Optional ByVal Direction As LvwFindDirectionConstants) As LvwListItem ``` Finds the nearest list item in the specified direction. ### FindSubItem ```vb Public Function FindSubItem(ByVal Text As String, Optional ByVal Index As Long, Optional ByRef SubItemIndex As Long, Optional ByVal Partial As Boolean, Optional ByVal Wrap As Boolean) As LvwListItem ``` Finds a sub-item matching the specified text. ### GetVisibleCount ```vb Public Function GetVisibleCount() As Long ``` Returns the number of visible items. ### GetSelectedCount ```vb Public Function GetSelectedCount() As Long ``` Returns the number of selected items. ### GetHeaderHeight ```vb Public Function GetHeaderHeight() As Single ``` Returns the column header height. ### StartLabelEdit ```vb Public Sub StartLabelEdit() ``` Starts label editing. ### EndLabelEdit ```vb Public Sub EndLabelEdit() ``` Ends label editing. ### Scroll ```vb Public Sub Scroll(ByVal X As Single, ByVal Y As Single) ``` Scrolls the list view content. ### ResetEmptyMarkup ```vb Public Sub ResetEmptyMarkup() ``` Resets the empty markup text. ### ComputeControlSize ```vb Public Sub ComputeControlSize(ByVal VisibleCount As Long, ByRef Width As Single, ByRef Height As Single, Optional ByVal ProposedWidth As Single, Optional ByVal ProposedHeight As Single) ``` Calculates the control size needed to display the specified number of items. ### TextWidth ```vb Public Function TextWidth(ByVal Text As String) As Single ``` Calculates the text width. ### ResetForeColors ```vb Public Sub ResetForeColors() ``` Resets the foreground color of all list items and sub-items. ### SelectedIndices ```vb Public Function SelectedIndices() As Collection ``` Returns a collection of all selected item indices. ### GhostedIndices ```vb Public Function GhostedIndices() As Collection ``` Returns a collection of all ghosted item indices. ### CheckedIndices ```vb Public Function CheckedIndices() As Collection ``` Returns a collection of all checked item indices. ### ResetIconSpacing ```vb Public Sub ResetIconSpacing() ``` Resets icon spacing to the default value. ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag-and-drop operation. ### Drag ```vb Public Sub Drag(Optional ByRef Action As Variant) ``` Starts, ends, or cancels a drag operation. ### SetFocus ```vb Public Sub SetFocus() ``` Sets focus to the control. ### ZOrder ```vb Public Sub ZOrder(Optional ByRef Position As Variant) ``` Adjusts the Z-order. ### Move ```vb Public Sub Move(ByVal Left As Single, Optional ByVal Top As Variant, Optional ByVal Width As Variant, Optional ByVal Height As Variant) ``` Moves and resizes the control. ## Events ### Click ```vb Public Event Click() ``` Click. ### DblClick ```vb Public Event DblClick() ``` Double-click. ### ItemClick ```vb Public Event ItemClick(ByVal Item As LvwListItem, ByVal Button As Integer) ``` A list item was clicked. ### ItemDblClick ```vb Public Event ItemDblClick(ByVal Item As LvwListItem, ByVal Button As Integer) ``` A list item was double-clicked. ### ItemFocus ```vb Public Event ItemFocus(ByVal Item As LvwListItem) ``` A list item received focus. ### ItemActivate ```vb Public Event ItemActivate(ByVal Item As LvwListItem, ByVal SubItemIndex As Long, ByVal Shift As Integer) ``` A list item was activated. ### ItemSelect ```vb Public Event ItemSelect(ByVal Item As LvwListItem, ByVal Selected As Boolean) ``` A list item's selection state changed. ### ItemCheck ```vb Public Event ItemCheck(ByVal Item As LvwListItem, ByVal Checked As Boolean) ``` A list item's checkbox state changed. ### ItemDrag ```vb Public Event ItemDrag(ByVal Item As LvwListItem, ByVal Button As Integer) ``` A drag-and-drop operation was initiated on a list item. ### ItemBkColor ```vb Public Event ItemBkColor(ByVal Item As LvwListItem, ByRef RGBColor As Long) ``` List item background color request (report view); allows providing an alternate background color. ### GetVirtualItem ```vb Public Event GetVirtualItem(ByVal ItemIndex As Long, ByVal SubItemIndex As Long, ByVal VirtualProperty As LvwVirtualPropertyConstants, ByRef Value As Variant) ``` Requests item properties in virtual mode. ### FindVirtualItem ```vb Public Event FindVirtualItem(ByVal StartIndex As Long, ByVal SearchText As String, ByVal Partial As Boolean, ByVal Wrap As Boolean, ByRef FoundIndex As Long) ``` Finds an item in virtual mode. ### CacheVirtualItems ```vb Public Event CacheVirtualItems(ByVal FromIndex As Long, ByVal ToIndex As Long) ``` Requests caching of an item range in virtual mode. ### BeforeLabelEdit ```vb Public Event BeforeLabelEdit(ByRef Cancel As Boolean) ``` Raised before label editing begins; can be canceled. ### AfterLabelEdit ```vb Public Event AfterLabelEdit(ByRef Cancel As Boolean, ByRef NewString As String) ``` Raised after label editing ends. ### ColumnClick ```vb Public Event ColumnClick(ByVal ColumnHeader As LvwColumnHeader) ``` A column header was clicked. ### ColumnDblClick ```vb Public Event ColumnDblClick(ByVal ColumnHeader As LvwColumnHeader) ``` A column header was double-clicked. ### ColumnCheck ```vb Public Event ColumnCheck(ByVal ColumnHeader As LvwColumnHeader) ``` A column header's checkbox state changed. ### ColumnBeforeResize ```vb Public Event ColumnBeforeResize(ByVal ColumnHeader As LvwColumnHeader, ByRef Cancel As Boolean) ``` Column width is about to change; can be canceled. ### ColumnAfterResize ```vb Public Event ColumnAfterResize(ByVal ColumnHeader As LvwColumnHeader, ByRef NewWidth As Single) ``` Column width change completed. ### ColumnDividerDblClick ```vb Public Event ColumnDividerDblClick(ByVal ColumnHeader As LvwColumnHeader, ByRef Cancel As Boolean) ``` A column divider was double-clicked. ### ColumnBeforeDrag ```vb Public Event ColumnBeforeDrag(ByVal ColumnHeader As LvwColumnHeader) ``` A column header drag is starting. ### ColumnAfterDrag ```vb Public Event ColumnAfterDrag(ByVal ColumnHeader As LvwColumnHeader, ByVal NewPosition As Long, ByRef Cancel As Boolean) ``` A column header drag completed. ### ColumnDropDown ```vb Public Event ColumnDropDown(ByVal ColumnHeader As LvwColumnHeader) ``` A column header dropdown button was clicked. ### ColumnChevronPushed ```vb Public Event ColumnChevronPushed(ByVal ColumnHeader As LvwColumnHeader) ``` A column chevron button was clicked. ### ColumnFilterChanged ```vb Public Event ColumnFilterChanged(ByVal ColumnHeader As LvwColumnHeader) ``` Column filter criteria changed. ### ColumnFilterButtonClick ```vb Public Event ColumnFilterButtonClick(ByVal ColumnHeader As LvwColumnHeader, ByRef RaiseFilterChanged As Boolean, ByVal ButtonLeft As Long, ByVal ButtonTop As Long, ByVal ButtonRight As Long, ByVal ButtonBottom As Long) ``` A column filter button was clicked. ### BeforeFilterEdit ```vb Public Event BeforeFilterEdit(ByVal ColumnHeader As LvwColumnHeader, ByVal hWndFilterEdit As LongPtr) ``` Raised before a column filter edit begins. ### AfterFilterEdit ```vb Public Event AfterFilterEdit(ByVal ColumnHeader As LvwColumnHeader) ``` Raised after a column filter edit ends. ### GetEmptyMarkup ```vb Public Event GetEmptyMarkup(ByRef Text As String, ByRef Center As Boolean) ``` Requests markup text when the list is empty. ### GroupCollapsedChanged ```vb Public Event GroupCollapsedChanged(ByVal Group As LvwGroup) ``` A group's collapsed state changed. ### GroupSelectedChanged ```vb Public Event GroupSelectedChanged(ByVal Group As LvwGroup) ``` A group's selection state changed. ### GroupLinkClick ```vb Public Event GroupLinkClick(ByVal Group As LvwGroup) ``` A group link was clicked. ### BeginMarqueeSelection ```vb Public Event BeginMarqueeSelection(ByRef Cancel As Boolean) ``` Marquee selection is starting; can be canceled. ### BeforeScroll ```vb Public Event BeforeScroll(ByVal DeltaX As Single, ByVal DeltaY As Single) ``` Raised before scrolling begins. ### AfterScroll ```vb Public Event AfterScroll(ByVal DeltaX As Single, ByVal DeltaY As Single) ``` Raised after scrolling completes. ### DropFiles ```vb Public Event DropFiles(ByRef FileList As Variant, ByVal X As Single, ByVal Y As Single) ``` Raised when files are dropped onto the control. ### ContextMenu ```vb Public Event ContextMenu(ByVal X As Single, ByVal Y As Single) ``` Raised when a context menu is requested. ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Key preview event; raised before KeyDown. ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Key release preview event; raised before KeyUp. ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` Key pressed. ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` Key released. ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` Key character. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Mouse button pressed. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Mouse moved. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Mouse button released. ### MouseEnter ```vb Public Event MouseEnter() ``` Mouse entered the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Mouse left the control. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE drag-and-drop completed. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE drag-and-drop drop. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE drag-and-drop hover. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE give feedback. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE set data. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE start drag. ## Sub-Objects ### LvwColumnHeader Column header object. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Index | `Property Get Index() As Long` | Index. Read-only | | Key | `Property Get Key() As String` / `Property Let Key(ByVal Value As String)` | Key value | | Tag | `Property Get Tag() As Variant` / `Property Let Tag(ByVal Value As Variant)` / `Property Set Tag(ByVal Value As Variant)` | Custom data | | Text | `Property Get Text() As String` / `Property Let Text(ByVal Value As String)` | Header text | | Icon | `Property Get Icon() As Variant` / `Property Let Icon(ByVal Value As Variant)` | Icon | | IconIndex | `Property Get IconIndex() As Long` | Icon index. Read-only | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | Column width | | Alignment | `Property Get Alignment() As LvwColumnHeaderAlignmentConstants` / `Property Let Alignment(ByVal Value As LvwColumnHeaderAlignmentConstants)` | Alignment | | Position | `Property Get Position() As Long` / `Property Let Position(ByVal Value As Long)` | Position | | SortArrow | `Property Get SortArrow() As LvwColumnHeaderSortArrowConstants` / `Property Let SortArrow(ByVal Value As LvwColumnHeaderSortArrowConstants)` | Sort arrow | | IconOnRight | `Property Get IconOnRight() As Boolean` / `Property Let IconOnRight(ByVal Value As Boolean)` | Icon on right | | Resizable | `Property Get Resizable() As Boolean` / `Property Let Resizable(ByVal Value As Boolean)` | Whether resizable | | SplitButton | `Property Get SplitButton() As Boolean` / `Property Let SplitButton(ByVal Value As Boolean)` | Whether split button is shown | | CheckBox | `Property Get CheckBox() As Boolean` / `Property Let CheckBox(ByVal Value As Boolean)` | Whether checkbox is shown | | Checked | `Property Get Checked() As Boolean` / `Property Let Checked(ByVal Value As Boolean)` | Checkbox checked state | | Bold | `Property Get Bold() As Boolean` / `Property Let Bold(ByVal Value As Boolean)` | Whether bold | | ForeColor | `Property Get ForeColor() As OLE_COLOR` / `Property Let ForeColor(ByVal Value As OLE_COLOR)` | Foreground color | | ToolTipText | `Property Get ToolTipText() As String` / `Property Let ToolTipText(ByVal Value As String)` | ToolTip text | | ToolTipTextFilterBtn | `Property Get ToolTipTextFilterBtn() As String` / `Property Let ToolTipTextFilterBtn(ByVal Value As String)` | Filter button ToolTip | | ToolTipTextDropDown | `Property Get ToolTipTextDropDown() As String` / `Property Let ToolTipTextDropDown(ByVal Value As String)` | Dropdown button ToolTip | | FilterType | `Property Get FilterType() As LvwColumnHeaderFilterTypeConstants` / `Property Let FilterType(ByVal Value As LvwColumnHeaderFilterTypeConstants)` | Filter type | | FilterValue | `Property Get FilterValue() As Variant` / `Property Let FilterValue(ByVal Value As Variant)` | Filter value | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | Left edge distance | #### Methods | Name | Signature | Description | |------|-----------|-------------| | AutoSize | `Public Sub AutoSize(ByVal Value As LvwColumnHeaderAutoSizeConstants)` | Auto size column width | | EditFilter | `Public Sub EditFilter()` | Edit filter criteria | | ClearFilter | `Public Sub ClearFilter()` | Clear filter criteria | | SubItemIndex | `Public Function SubItemIndex() As Long` | Get the corresponding sub-item index | ### LvwColumnHeaders Column headers collection. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Item | `Property Get Item(ByVal Index As Variant) As LvwColumnHeader` | Get column header by index | | ItemFromPosition | `Property Get ItemFromPosition(ByVal Position As Long) As LvwColumnHeader` | Get column header by position | | Count | `Property Get Count() As Long` | Column header count. Read-only | #### Methods | Name | Signature | Description | |------|-----------|-------------| | Add | `Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Text As String, Optional ByVal Width As Variant, Optional ByVal Alignment As LvwColumnHeaderAlignmentConstants, Optional ByVal Icon As Variant) As LvwColumnHeader` | Add column header | | Exists | `Public Function Exists(ByVal Index As Variant) As Boolean` | Check if column header exists | | Clear | `Public Sub Clear()` | Clear all column headers | | Remove | `Public Sub Remove(ByVal Index As Variant)` | Remove column header | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | Enumerator | ### LvwListItem List item object. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Index | `Property Get Index() As Long` | Index. Read-only | | Key | `Property Get Key() As String` / `Property Let Key(ByVal Value As String)` | Key value | | Tag | `Property Get Tag() As Variant` / `Property Let Tag(ByVal Value As Variant)` / `Property Set Tag(ByVal Value As Variant)` | Custom data | | Text | `Property Get Text() As String` / `Property Let Text(ByVal Value As String)` | Text | | Icon | `Property Get Icon() As Variant` / `Property Let Icon(ByVal Value As Variant)` | Large icon | | IconIndex | `Property Get IconIndex() As Long` | Large icon index. Read-only | | SmallIcon | `Property Get SmallIcon() As Variant` / `Property Let SmallIcon(ByVal Value As Variant)` | Small icon | | SmallIconIndex | `Property Get SmallIconIndex() As Long` | Small icon index. Read-only | | Indentation | `Property Get Indentation() As Long` / `Property Let Indentation(ByVal Value As Long)` | Indentation | | Selected | `Property Get Selected() As Boolean` / `Property Let Selected(ByVal Value As Boolean)` | Whether selected | | Checked | `Property Get Checked() As Boolean` / `Property Let Checked(ByVal Value As Boolean)` | Checkbox state | | Ghosted | `Property Get Ghosted() As Boolean` / `Property Let Ghosted(ByVal Value As Boolean)` | Whether ghosted | | Hot | `Property Get Hot() As Boolean` / `Property Let Hot(ByVal Value As Boolean)` | Whether hot | | Bold | `Property Get Bold() As Boolean` / `Property Let Bold(ByVal Value As Boolean)` | Whether bold | | ForeColor | `Property Get ForeColor() As OLE_COLOR` / `Property Let ForeColor(ByVal Value As OLE_COLOR)` | Foreground color | | ToolTipText | `Property Get ToolTipText() As String` / `Property Let ToolTipText(ByVal Value As String)` | ToolTip text | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | Left edge distance | | Top | `Property Get Top() As Single` / `Property Let Top(ByVal Value As Single)` | Top edge distance | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | Width | | Height | `Property Get Height() As Single` / `Property Let Height(ByVal Value As Single)` | Height | | Visible | `Property Get Visible() As Boolean` | Whether visible. Read-only | | TileViewIndices | `Property Get TileViewIndices() As Variant` / `Property Let TileViewIndices(ByVal ArgList As Variant)` | Tile view sub-item column indices | | Group | `Property Get Group() As LvwGroup` / `Property Let Group(ByVal Value As LvwGroup)` / `Property Set Group(ByVal Value As LvwGroup)` | Owning group | | WorkArea | `Property Get WorkArea() As LvwWorkArea` | Owning work area. Read-only | | ListSubItems | `Property Get ListSubItems() As LvwListSubItems` | Sub-items collection. Read-only | | SubItems | `Property Get SubItems(ByVal Index As Integer) As String` / `Property Let SubItems(ByVal Index As Integer, ByVal Value As String)` | Get or set sub-item text by index | #### Methods | Name | Signature | Description | |------|-----------|-------------| | EnsureVisible | `Public Sub EnsureVisible()` | Ensure item is visible | | CreateDragImage | `Public Function CreateDragImage(Optional ByRef X As Single, Optional ByRef Y As Single) As LongPtr` | Create drag image | ### LvwListItems List items collection. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Item | `Property Get Item(ByVal Index As Variant) As LvwListItem` | Get list item by index | | Count | `Property Get Count() As Long` | List item count. Read-only | #### Methods | Name | Signature | Description | |------|-----------|-------------| | Add | `Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Text As String, Optional ByVal Icon As Variant, Optional ByVal SmallIcon As Variant) As LvwListItem` | Add list item | | Exists | `Public Function Exists(ByVal Index As Variant) As Boolean` | Check if list item exists | | Clear | `Public Sub Clear()` | Clear all list items | | Remove | `Public Sub Remove(ByVal Index As Variant)` | Remove list item | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | Enumerator | ### LvwListSubItem List sub-item object. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Index | `Property Get Index() As Long` | Index. Read-only | | Key | `Property Get Key() As String` | Key value. Read-only | | Tag | `Property Get Tag() As Variant` / `Property Let Tag(ByVal Value As Variant)` / `Property Set Tag(ByVal Value As Variant)` | Custom data | | Text | `Property Get Text() As String` / `Property Let Text(ByVal Value As String)` | Text | | ReportIcon | `Property Get ReportIcon() As Variant` / `Property Let ReportIcon(ByVal Value As Variant)` | Report view icon | | ReportIconIndex | `Property Get ReportIconIndex() As Long` | Report view icon index. Read-only | | Bold | `Property Get Bold() As Boolean` / `Property Let Bold(ByVal Value As Boolean)` | Whether bold | | ForeColor | `Property Get ForeColor() As OLE_COLOR` / `Property Let ForeColor(ByVal Value As OLE_COLOR)` | Foreground color | | ToolTipText | `Property Get ToolTipText() As String` / `Property Let ToolTipText(ByVal Value As String)` | ToolTip text | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | Left edge distance | | Top | `Property Get Top() As Single` / `Property Let Top(ByVal Value As Single)` | Top edge distance | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | Width | | Height | `Property Get Height() As Single` / `Property Let Height(ByVal Value As Single)` | Height | ### LvwListSubItems List sub-items collection. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Item | `Property Get Item(ByVal Index As Variant) As LvwListSubItem` | Get sub-item by index | | Count | `Property Get Count() As Long` | Sub-item count. Read-only | #### Methods | Name | Signature | Description | |------|-----------|-------------| | Add | `Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Text As String, Optional ByVal ReportIcon As Variant, Optional ByVal ToolTipText As String) As LvwListSubItem` | Add sub-item | | Exists | `Public Function Exists(ByVal Index As Variant) As Boolean` | Check if sub-item exists | | Clear | `Public Sub Clear()` | Clear all sub-items | | Remove | `Public Sub Remove(ByVal Index As Variant)` | Remove sub-item | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | Enumerator | ### LvwGroup Group object. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Index | `Property Get Index() As Long` | Index. Read-only | | Key | `Property Get Key() As String` / `Property Let Key(ByVal Value As String)` | Key value | | Tag | `Property Get Tag() As Variant` / `Property Let Tag(ByVal Value As Variant)` / `Property Set Tag(ByVal Value As Variant)` | Custom data | | ID | `Property Get ID() As Long` | Group ID. Read-only | | Header | `Property Get Header() As String` / `Property Let Header(ByVal Value As String)` | Group header | | HeaderAlignment | `Property Get HeaderAlignment() As LvwGroupHeaderAlignmentConstants` / `Property Let HeaderAlignment(ByVal Value As LvwGroupHeaderAlignmentConstants)` | Header alignment | | Footer | `Property Get Footer() As String` / `Property Let Footer(ByVal Value As String)` | Group footer | | FooterAlignment | `Property Get FooterAlignment() As LvwGroupFooterAlignmentConstants` / `Property Let FooterAlignment(ByVal Value As LvwGroupFooterAlignmentConstants)` | Footer alignment | | Hint | `Property Get Hint() As String` / `Property Let Hint(ByVal Value As String)` | Hint text | | Link | `Property Get Link() As String` / `Property Let Link(ByVal Value As String)` | Link text | | SubsetLink | `Property Get SubsetLink() As String` / `Property Let SubsetLink(ByVal Value As String)` | Subset link text | | Collapsible | `Property Get Collapsible() As Boolean` / `Property Let Collapsible(ByVal Value As Boolean)` | Whether collapsible | | Collapsed | `Property Get Collapsed() As Boolean` / `Property Let Collapsed(ByVal Value As Boolean)` | Whether collapsed | | ShowHeader | `Property Get ShowHeader() As Boolean` / `Property Let ShowHeader(ByVal Value As Boolean)` | Whether header is shown | | Selected | `Property Get Selected() As Boolean` / `Property Let Selected(ByVal Value As Boolean)` | Whether selected | | Subseted | `Property Get Subseted() As Boolean` / `Property Let Subseted(ByVal Value As Boolean)` | Whether subsetted | | SubsetLinkSelected | `Property Get SubsetLinkSelected() As Boolean` / `Property Let SubsetLinkSelected(ByVal Value As Boolean)` | Whether subset link is selected | | Icon | `Property Get Icon() As Variant` / `Property Let Icon(ByVal Value As Variant)` | Icon | | IconIndex | `Property Get IconIndex() As Long` | Icon index. Read-only | | Position | `Property Get Position() As Long` / `Property Let Position(ByVal Value As Long)` | Position | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | Left edge distance | | Top | `Property Get Top() As Single` / `Property Let Top(ByVal Value As Single)` | Top edge distance | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | Width | | Height | `Property Get Height() As Single` / `Property Let Height(ByVal Value As Single)` | Height | | ListItemCount | `Property Get ListItemCount() As Long` | List item count. Read-only | | ListItemIndices | `Property Get ListItemIndices() As Collection` | List item index collection. Read-only | ### LvwGroups Groups collection. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Item | `Property Get Item(ByVal Index As Variant) As LvwGroup` | Get group by index | | Count | `Property Get Count() As Long` | Group count. Read-only | | Sorted | `Property Get Sorted() As Boolean` / `Property Let Sorted(ByVal Value As Boolean)` | Whether sorted | | SortOrder | `Property Get SortOrder() As LvwSortOrderConstants` / `Property Let SortOrder(ByVal Value As LvwSortOrderConstants)` | Sort order | | SortType | `Property Get SortType() As LvwSortTypeConstants` / `Property Let SortType(ByVal Value As LvwSortTypeConstants)` | Sort type | #### Methods | Name | Signature | Description | |------|-----------|-------------| | Add | `Public Function Add(Optional ByVal Index As Long, Optional ByVal Key As String, Optional ByVal Header As String, Optional ByVal HeaderAlignment As LvwGroupHeaderAlignmentConstants, Optional ByVal Footer As String, Optional ByVal FooterAlignment As LvwGroupFooterAlignmentConstants) As LvwGroup` | Add group | | Exists | `Public Function Exists(ByVal Index As Variant) As Boolean` | Check if group exists | | Clear | `Public Sub Clear()` | Clear all groups | | Remove | `Public Sub Remove(ByVal Index As Variant)` | Remove group | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | Enumerator | ### LvwVirtualListItem Virtual list item object. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Index | `Property Get Index() As Long` | Index. Read-only | | Text | `Property Get Text() As String` | Text. Read-only | | Indentation | `Property Get Indentation() As Long` | Indentation. Read-only | | Selected | `Property Get Selected() As Boolean` / `Property Let Selected(ByVal Value As Boolean)` | Whether selected | | Checked | `Property Get Checked() As Boolean` | Checkbox state. Read-only | | Hot | `Property Get Hot() As Boolean` / `Property Let Hot(ByVal Value As Boolean)` | Whether hot | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | Left edge distance | | Top | `Property Get Top() As Single` / `Property Let Top(ByVal Value As Single)` | Top edge distance | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | Width | | Height | `Property Get Height() As Single` / `Property Let Height(ByVal Value As Single)` | Height | | Visible | `Property Get Visible() As Boolean` | Whether visible. Read-only | | SubItems | `Property Get SubItems(ByVal Index As Integer) As String` | Get sub-item text by index. Read-only | #### Methods | Name | Signature | Description | |------|-----------|-------------| | EnsureVisible | `Public Sub EnsureVisible()` | Ensure item is visible | | CreateDragImage | `Public Function CreateDragImage(Optional ByRef X As Single, Optional ByRef Y As Single) As LongPtr` | Create drag image | ### LvwVirtualListItems Virtual list items collection. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Item | `Property Get Item(ByVal Index As Long) As LvwVirtualListItem` | Get virtual list item by index | | Count | `Property Get Count() As Long` | Virtual list item count. Read-only | #### Methods | Name | Signature | Description | |------|-----------|-------------| | Exists | `Public Function Exists(ByVal Index As Long) As Boolean` | Check if virtual list item exists | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | Enumerator | ### LvwWorkArea Work area object. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Index | `Property Get Index() As Long` | Index. Read-only | | Left | `Property Get Left() As Single` / `Property Let Left(ByVal Value As Single)` | Left edge distance | | Top | `Property Get Top() As Single` / `Property Let Top(ByVal Value As Single)` | Top edge distance | | Width | `Property Get Width() As Single` / `Property Let Width(ByVal Value As Single)` | Width | | Height | `Property Get Height() As Single` / `Property Let Height(ByVal Value As Single)` | Height | | ListItemIndices | `Property Get ListItemIndices() As Collection` | List item index collection in the work area. Read-only | ### LvwWorkAreas Work areas collection. #### Properties | Name | Signature | Description | |------|-----------|-------------| | Item | `Property Get Item(ByVal Index As Long) As LvwWorkArea` | Get work area by index | | Count | `Property Get Count() As Long` | Work area count. Read-only | #### Methods | Name | Signature | Description | |------|-----------|-------------| | Add | `Public Function Add(ByVal Left As Single, ByVal Top As Single, ByVal Width As Single, ByVal Height As Single, Optional ByVal Index As Long) As LvwWorkArea` | Add work area | | Exists | `Public Function Exists(ByVal Index As Long) As Boolean` | Check if work area exists | | Clear | `Public Sub Clear()` | Clear all work areas | | Remove | `Public Sub Remove(ByVal Index As Long)` | Remove work area | | NewEnum | `Public Function NewEnum() As IEnumVARIANT` | Enumerator | ## Code Examples ### Report View Basic Usage ```vb ' Set report view ListView1.View = LvwViewReport ' Add column headers With ListView1.ColumnHeaders .Add , , "Name", 120 .Add , , "Age", 60, LvwColumnHeaderAlignmentCenter .Add , , "City", 100 End With ' Add list items Dim li As LvwListItem Set li = ListView1.ListItems.Add(, , "Zhang San") li.SubItems(1) = "28" li.SubItems(2) = "Beijing" Set li = ListView1.ListItems.Add(, , "Li Si") li.SubItems(1) = "35" li.SubItems(2) = "Shanghai" ``` ### Group View ```vb ' Enable grouping ListView1.GroupView = True ListView1.View = LvwViewReport ' Add groups Dim grp1 As LvwGroup, grp2 As LvwGroup Set grp1 = ListView1.Groups.Add(, , "Group 1") Set grp2 = ListView1.Groups.Add(, , "Group 2") ' Assign items to groups Set ListView1.ListItems(1).Group = grp1 Set ListView1.ListItems(2).Group = grp2 ``` ### Virtual Mode ```vb ' Enable virtual mode ListView1.VirtualMode = True ListView1.VirtualItemCount = 10000 ' Provide data in the GetVirtualItem event Private Sub ListView1_GetVirtualItem(ByVal ItemIndex As Long, _ ByVal SubItemIndex As Long, _ ByVal VirtualProperty As LvwVirtualPropertyConstants, _ ByRef Value As Variant) If VirtualProperty = LvwVirtualPropertyText Then If SubItemIndex = 0 Then Value = "Item " & ItemIndex Else Value = "Sub " & SubItemIndex End If End If End Sub ``` ### Sorting and Filtering ```vb ' Sort ListView1.SortKey = 0 ListView1.SortOrder = LvwSortOrderAscending ListView1.SortType = LvwSortTypeText ListView1.Sorted = True ' Set sort arrow ListView1.ColumnHeaders(1).SortArrow = LvwColumnHeaderSortArrowDown ' Enable column filtering ListView1.UseColumnFilterBar = True ``` --- --- url: /en/official/Features/Language/Literals.md --- # New Literals Notation twinBASIC provides new options for writing numeric literals. ## Binary Literals In addition to `&H` for hexadecimal literals and `&O` for octal notation, twinBASIC also provides `&B` for binary notation. For example, `Dim b As Long = &B010110` is valid syntax, and b = 22. ## Digit Grouping The `&H`, `&O`, and `&B` literals can all be grouped using an underscore, for example, grouping a `Long` by it's constituent binary byte groups: `&B10110101_10100011_10000011_01101110`, or grouping a `LongLong` as two `Long` groups: `&H01234567_89ABCDEF`. ## Example ```vb Dim flags As Long = &B1010 ' 10 in decimal Dim perms As Long = &O17 ' 15 in decimal Dim colour As Long = &HFF ' 255 in decimal Dim mask As Long = &B10110101_10100011 ' grouped binary bytes Dim wide As LongLong = &H01234567_89ABCDEF ' grouped hex halves ``` --- --- url: /en/official/Reference/Core/Load.md --- # Load Loads an object --- typically a form --- into memory but does not show it. Syntax: > **Load** *object* *object* : An object expression that evaluates to a loadable object (commonly a form or a control array element). When an object is loaded, it is placed in memory but is not visible. Use the **Show** method to make it visible. Until an object is visible, the user can't interact with it; the object can be manipulated programmatically inside its **Initialize** event handler. Use [**Unload**](/en/official/Reference/Core/Unload) to remove the object from memory once it is no longer needed. ### Example In the following example, `UserForm2` is loaded during `UserForm1`'s **Initialize** event. Subsequent clicking on `UserForm2` reveals `UserForm1`. ```vb ' This is the Initialize event procedure for UserForm1. Private Sub UserForm_Initialize() Load UserForm2 UserForm2.Show End Sub ' This is the Click event of UserForm2. Private Sub UserForm_Click() UserForm2.Hide End Sub ' This is the Click event for UserForm1. Private Sub UserForm_Click() UserForm2.Show End Sub ``` ### See Also * [**Unload** statement](/en/official/Reference/Core/Unload) --- --- url: /zh/official/Reference/Core/Load.md --- # Load 将对象——通常是窗体——加载到内存但不在屏幕上显示。 语法: > **Load** *object* *object* : 求值为可加载对象的对象表达式(通常是窗体或控件数组元素)。 对象加载后,被放入内存但不可见。使用 **Show** 方法使其可见。对象在可见之前,用户不能与它交互;可以在其 **Initialize** 事件处理程序中以编程方式操作对象。 当不再需要对象时,使用 [**Unload**](/official/Reference/Core/Unload) 将其从内存中移除。 ### 示例 以下示例中,`UserForm2` 在 `UserForm1` 的 **Initialize** 事件期间加载。随后点击 `UserForm2` 会显示 `UserForm1`。 ```vb ' This is the Initialize event procedure for UserForm1. Private Sub UserForm_Initialize() Load UserForm2 UserForm2.Show End Sub ' This is the Click event of UserForm2. Private Sub UserForm_Click() UserForm2.Hide End Sub ' This is the Click event for UserForm1. Private Sub UserForm_Click() UserForm2.Show End Sub ``` ### 另请参阅 * [**Unload** 语句](/official/Reference/Core/Unload) --- --- url: /en/official/Reference/VBRUN/Constants/LoadPictureColorConstants.md --- # LoadPictureColorConstants Colour-depth selectors for the *vbLPColor* argument of **LoadPicture**. | Constant | Value | Description | |----------|-------|-------------| | **vbLPDefault** | 0 | Use the source image's native colour depth. | | **vbLPMonochrome** | 1 | Load as a monochrome (1-bit) image. | | **vbLPVGAColor** | 2 | Load as a 16-colour (4-bit) image. | | **vbLPColor** | 3 | Load as a full-colour image. | --- --- url: /zh/official/Reference/VBRUN/Constants/LoadPictureColorConstants.md --- # LoadPictureColorConstants **LoadPicture**的*vbLPColor*参数的颜色深度选择器。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbLPDefault** | 0 | 使用源图像的本机颜色深度。 | | **vbLPMonochrome** | 1 | 加载为单色(1位)图像。 | | **vbLPVGAColor** | 2 | 加载为16色(4位)图像。 | | **vbLPColor** | 3 | 加载为全彩图像。 | --- --- url: /en/official/Reference/VBRUN/Constants/LoadPictureSizeConstants.md --- # LoadPictureSizeConstants Size selectors for the *vbLPSize* argument of **LoadPicture**, used when a source file (typically an icon) contains several sizes. | Constant | Value | Description | |----------|-------|-------------| | **vbLPSmall** | 0 | Use the standard small system size (typically 16×16). | | **vbLPLarge** | 1 | Use the standard large system size (typically 32×32). | | **vbLPSmallShell** | 2 | Use the small shell size (the size used in Windows Explorer's small-icon view). | | **vbLPLargeShell** | 3 | Use the large shell size. | | **vbLPCustom** | 4 | Use a custom size supplied alongside the call. | --- --- url: /zh/official/Reference/VBRUN/Constants/LoadPictureSizeConstants.md --- # LoadPictureSizeConstants **LoadPicture**的*vbLPSize*参数的大小选择器,当源文件(通常是图标)包含多种大小时使用。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbLPSmall** | 0 | 使用标准小系统尺寸(通常为16×16)。 | | **vbLPLarge** | 1 | 使用标准大系统尺寸(通常为32×32)。 | | **vbLPSmallShell** | 2 | 使用小型外壳尺寸(Windows资源管理器小图标视图中使用的尺寸)。 | | **vbLPLargeShell** | 3 | 使用大型外壳尺寸。 | | **vbLPCustom** | 4 | 使用随调用提供的自定义尺寸。 | --- --- url: /en/official/Reference/VBRUN/Constants/LoadResConstants.md --- # LoadResConstants Resource-type values for the *Format* argument of the **LoadResPicture** function. | Constant | Value | Description | |----------|-------|-------------| | **vbResBitmap** | 0 | Load a bitmap resource. | | **vbResIcon** | 1 | Load an icon resource. | | **vbResCursor** | 2 | Load a cursor resource. | | **vbResBitmapFromIcon** | 3 | Load an icon resource and convert it to a bitmap. *(twinBASIC addition.)* | --- --- url: /zh/official/Reference/VBRUN/Constants/LoadResConstants.md --- # LoadResConstants **LoadResPicture**函数的*Format*参数的资源类型值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbResBitmap** | 0 | 加载位图资源。 | | **vbResIcon** | 1 | 加载图标资源。 | | **vbResCursor** | 2 | 加载光标资源。 | | **vbResBitmapFromIcon** | 3 | 加载图标资源并转换为位图。*(twinBASIC新增)* | --- --- url: /en/official/Reference/VBA/FileSystem/Loc.md --- # Loc Returns a **Long** specifying the current read/write position within an open file. Syntax: **Loc(** *filenumber* **)** *filenumber* : *required* **Integer** containing a valid file number. ### Remarks The return value depends on the file access mode: | Mode | Return value | |----------------|-------------------------------------------------------------| | **Random** | Number of the last record read from or written to the file. | | **Sequential** | Current byte position in the file divided by 128. | | **Binary** | Position of the last byte read or written. | ### Example This example uses the **Loc** function to return the current read/write position within an open file. This example assumes that `TESTFILE` is a text file with a few lines of sample data. ```vb Dim MyLocation, MyLine Open "TESTFILE" For Binary As #1 ' Open file. Do While MyLocation < LOF(1) ' Loop until end of file. MyLine = MyLine & Input(1, #1) ' Read character into variable. MyLocation = Loc(1) ' Get current position within file. Debug.Print MyLine; Tab; MyLocation Loop Close #1 ' Close file. ``` ### See Also * [LOF](/en/official/Reference/VBA/FileSystem/LOF) function * [Seek](/en/official/Reference/VBA/FileSystem/Seek) function * [EOF](/en/official/Reference/VBA/FileSystem/EOF) function --- --- url: /zh/official/Reference/VBA/FileSystem/Loc.md --- # Loc 返回一个**Long**,指定打开文件中当前的读/写位置。 语法:**Loc(** *filenumber* **)** *filenumber* : *必需* **Integer**,包含有效的文件号。 ### 备注 返回值取决于文件访问模式: | 模式 | 返回值 | |---------------|------------------------------------------------| | **Random** | 从文件读取或写入的最后一条记录的编号。 | | **Sequential**| 文件中当前字节位置除以128。 | | **Binary** | 最后读取或写入的字节位置。 | ### 示例 本示例使用**Loc**函数返回打开文件中当前的读/写位置。本示例假设`TESTFILE`是一个包含几行示例数据的文本文件。 ```vb Dim MyLocation, MyLine Open "TESTFILE" For Binary As #1 ' Open file. Do While MyLocation < LOF(1) ' Loop until end of file. MyLine = MyLine & Input(1, #1) ' Read character into variable. MyLocation = Loc(1) ' Get current position within file. Debug.Print MyLine; Tab; MyLocation Loop Close #1 ' Close file. ``` ### 另请参阅 * [LOF](/official/Reference/VBA/FileSystem/LOF)函数 * [Seek](/official/Reference/VBA/FileSystem/Seek)函数 * [EOF](/official/Reference/VBA/FileSystem/EOF)函数 --- --- url: /en/official/Reference/VBRUN/AmbientProperties/LocaleID.md --- # LocaleID Returns the Locale ID of the container, as a **Long**. Read-only. Syntax: *object*.**LocaleID** *object* : *required* An object expression that evaluates to an **AmbientProperties** object. The Locale ID (LCID) is a 32-bit Windows identifier that names a language and a regional formatting convention --- for example `&H0409&` for English (United States) or `&H0407&` for German (Germany). A control should use this value when formatting numbers, dates, currencies, and message text, so that its output matches the language and conventions the host application is presenting to the user. ### Example This example caches the ambient **LocaleID** for use when formatting numbers and dates. ```vb Private mLocaleID As Long Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "LocaleID" mLocaleID = Ambient.LocaleID End Select End Sub ``` ### See Also * [DisplayName](/en/official/Reference/VBRUN/AmbientProperties/DisplayName) property * [RightToLeft](/en/official/Reference/VBRUN/AmbientProperties/RightToLeft) property --- --- url: /zh/official/Reference/VBRUN/AmbientProperties/LocaleID.md --- # LocaleID 返回容器的区域设置ID,类型为**Long**。只读。 语法:*object*.**LocaleID** *object* : *必需* 求值为**AmbientProperties**对象的对象表达式。 区域设置ID(LCID)是命名语言和区域格式约定的32位Windows标识符——例如`&H0409&`表示英语(美国),`&H0407&`表示德语(德国)。控件在格式化数字、日期、货币和消息文本时应使用此值,使其输出与宿主应用程序呈现给用户的语言和约定匹配。 ### 示例 此示例缓存环境**LocaleID**,用于格式化数字和日期。 ```vb Private mLocaleID As Long Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "LocaleID" mLocaleID = Ambient.LocaleID End Select End Sub ``` ### 另见 * [DisplayName](/official/Reference/VBRUN/AmbientProperties/DisplayName) 属性 * [RightToLeft](/official/Reference/VBRUN/AmbientProperties/RightToLeft) 属性 --- --- url: /en/official/Reference/Core/Lock.md --- # Lock, Unlock Controls access by other processes to all or part of a file opened with the [**Open**](/en/official/Reference/Core/Open) statement. Syntax: * > **Lock** \[ **#** ] *filenumber* **,** \[ *recordrange* ] * > **Unlock** \[ **#** ] *filenumber* **,** \[ *recordrange* ] *filenumber* : Any valid file number. *recordrange* : *optional* The range of records to lock or unlock. The *recordrange* settings are: > *recnumber* | \[ *start* ] **To** *end* *recnumber* : Record number (**Random** mode files) or byte number (**Binary** mode files) at which locking or unlocking begins. *start* : Number of the first record or byte to lock or unlock. *end* : Number of the last record or byte to lock or unlock. The **Lock** and **Unlock** statements are used in environments where several processes might need access to the same file. **Lock** and **Unlock** statements are always used in pairs. The arguments to **Lock** and **Unlock** must match exactly. The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. When just one record is specified, only that record is locked or unlocked. When a range of records is specified and a starting record (*start*) is omitted, all records from the first record to the end of the range (*end*) are locked or unlocked. Using **Lock** without *recnumber* locks the entire file; using **Unlock** without *recnumber* unlocks the entire file. If the file has been opened for sequential input or output, **Lock** and **Unlock** affect the entire file, regardless of the range specified by *start* and *end*. ::: warning Be sure to remove all locks with an **Unlock** statement before closing a file or quitting the program. Failure to remove locks produces unpredictable results. ::: ### Example This example illustrates the use of the **Lock** and **Unlock** statements. While a record is being modified, access by other processes to the record is denied. This example assumes that `TESTFILE` is a file containing five records of the user-defined type `Record`. ```vb Type Record ' Define user-defined type. ID As Integer Name As String * 20 End Type Dim MyRecord As Record, RecordNumber ' Declare variables. ' Open sample file for random access. Open "TESTFILE" For Random Shared As #1 Len = Len(MyRecord) RecordNumber = 4 ' Define record number. Lock #1, RecordNumber ' Lock record. Get #1, RecordNumber, MyRecord ' Read record. MyRecord.ID = 234 ' Modify record. MyRecord.Name = "John Smith" Put #1, RecordNumber, MyRecord ' Write modified record. Unlock #1, RecordNumber ' Unlock current record. Close #1 ' Close file. ``` ### See Also * [**Open** statement](/en/official/Reference/Core/Open) * [**Close** statement](/en/official/Reference/Core/Close) * [**Get** statement](/en/official/Reference/Core/Get) * [**Put** statement](/en/official/Reference/Core/Put) --- --- url: /zh/official/Reference/Core/Lock.md --- # Lock, Unlock 控制其他进程对使用 [**Open**](/official/Reference/Core/Open) 语句打开的文件的全部或部分的访问。 语法: * > **Lock** \[ **#** ] *filenumber* **,** \[ *recordrange* ] * > **Unlock** \[ **#** ] *filenumber* **,** \[ *recordrange* ] *filenumber* : 任何有效的文件号。 *recordrange* : *可选* 要锁定或解锁的记录范围。*recordrange* 设置为: > *recnumber* | \[ *start* ] **To** *end* *recnumber* : 开始锁定或解锁的记录号(**Random** 模式文件)或字节号(**Binary** 模式文件)。 *start* : 要锁定或解锁的第一条记录或字节的编号。 *end* : 要锁定或解锁的最后一条记录或字节的编号。 **Lock** 和 **Unlock** 语句用于多个进程可能需要访问同一文件的环境。 **Lock** 和 **Unlock** 语句总是成对使用。**Lock** 和 **Unlock** 的参数必须完全匹配。 文件中的第一条记录或字节位于位置1,第二条位于位置2,依此类推。当只指定一条记录时,仅锁定或解锁该记录。当指定记录范围且省略起始记录(*start*)时,从第一条记录到范围末尾(*end*)的所有记录被锁定或解锁。使用不带 *recnumber* 的 **Lock** 锁定整个文件;使用不带 *recnumber* 的 **Unlock** 解锁整个文件。 如果文件已为顺序输入或输出打开,**Lock** 和 **Unlock** 影响整个文件,无论 *start* 和 *end* 指定的范围如何。 ::: warning 在关闭文件或退出程序之前,务必用 **Unlock** 语句移除所有锁定。未能移除锁定会产生不可预测的结果。 ::: ### 示例 本示例说明 **Lock** 和 **Unlock** 语句的使用。当记录被修改时,其他进程对该记录的访问被拒绝。本示例假设 `TESTFILE` 是包含用户自定义类型 `Record` 的五条记录的文件。 ```vb Type Record ' Define user-defined type. ID As Integer Name As String * 20 End Type Dim MyRecord As Record, RecordNumber ' Declare variables. ' Open sample file for random access. Open "TESTFILE" For Random Shared As #1 Len = Len(MyRecord) RecordNumber = 4 ' Define record number. Lock #1, RecordNumber ' Lock record. Get #1, RecordNumber, MyRecord ' Read record. MyRecord.ID = 234 ' Modify record. MyRecord.Name = "John Smith" Put #1, RecordNumber, MyRecord ' Write modified record. Unlock #1, RecordNumber ' Unlock current record. Close #1 ' Close file. ``` ### 另请参阅 * [**Open** 语句](/official/Reference/Core/Open) * [**Close** 语句](/official/Reference/Core/Close) * [**Get** 语句](/official/Reference/Core/Get) * [**Put** 语句](/official/Reference/Core/Put) --- --- url: /en/official/Reference/VBA/FileSystem/LOF.md --- # LOF Returns a **Long** representing the size, in bytes, of a file opened by using the **Open** statement. Syntax: **LOF(** *filenumber* **)** *filenumber* : *required* **Integer** containing a valid file number. ::: info Use the **FileLen** function to obtain the length of a file that is not open. ::: ### Example This example uses the **LOF** function to determine the size of an open file. This example assumes that `TESTFILE` is a text file containing sample data. ```vb Dim FileLength Open "TESTFILE" For Input As #1 ' Open file. FileLength = LOF(1) ' Get length of file. Close #1 ' Close file. ``` ### See Also * [EOF](/en/official/Reference/VBA/FileSystem/EOF) function --- --- url: /zh/official/Reference/VBA/FileSystem/LOF.md --- # LOF 返回一个**Long**,表示使用**Open**语句打开的文件的大小(字节)。 语法:**LOF(** *filenumber* **)** *filenumber* : *必需* **Integer**,包含有效的文件号。 ::: info 使用**FileLen**函数获取未打开文件的长度。 ::: ### 示例 本示例使用**LOF**函数确定打开文件的大小。本示例假设`TESTFILE`是一个包含示例数据的文本文件。 ```vb Dim FileLength Open "TESTFILE" For Input As #1 ' Open file. FileLength = LOF(1) ' Get length of file. Close #1 ' Close file. ``` ### 另请参阅 * [EOF](/official/Reference/VBA/FileSystem/EOF)函数 --- --- url: /en/official/Reference/VBA/Math/Log.md --- # Log Returns a **Double** specifying the natural logarithm of a number. Syntax: **Log(** *number* **)** *number* : *required* A **Double** or any valid numeric expression greater than zero. The natural logarithm is the logarithm to the base *e*. The constant *e* is approximately 2.718282. Base-*n* logarithms for any number *x* can be calculated by dividing the natural logarithm of *x* by the natural logarithm of *n* as follows: Log*n*(*x*) = **Log(** *x* **)** / **Log(** *n* **)** The following example illustrates a custom **Function** that calculates base-10 logarithms: ```vb Static Function Log10(X) Log10 = Log(X) / Log(10#) End Function ``` ### Example This example uses the **Log** function to return the natural logarithm of a number. ```vb Dim MyAngle, MyLog ' Define angle in radians. MyAngle = 1.3 ' Calculate inverse hyperbolic sine. MyLog = Log(MyAngle + Sqr(MyAngle * MyAngle + 1)) ``` ### See Also * [Exp](/en/official/Reference/VBA/Math/Exp) function * [Sqr](/en/official/Reference/VBA/Math/Sqr) function --- --- url: /zh/official/Reference/VBA/Math/Log.md --- # Log 返回一个 **Double**,指定数字的自然对数。 语法:**Log(** *number* **)** *number* : *必需* **Double** 或任何大于零的有效数值表达式。 自然对数是以 *e* 为底的对数。常量 *e* 约为 2.718282。 对于任意数字 *x* 的以 *n* 为底的对数,可以通过将 *x* 的自然对数除以 *n* 的自然对数来计算: Log*n*(*x*) = **Log(** *x* **)** / **Log(** *n* **)** 以下示例演示了一个计算以 10 为底对数的自定义 **Function**: ```vb Static Function Log10(X) Log10 = Log(X) / Log(10#) End Function ``` ### 示例 此示例使用 **Log** 函数返回数字的自然对数。 ```vb Dim MyAngle, MyLog ' Define angle in radians. MyAngle = 1.3 ' Calculate inverse hyperbolic sine. MyLog = Log(MyAngle + Sqr(MyAngle * MyAngle + 1)) ``` ### 另请参阅 * [Exp](/official/Reference/VBA/Math/Exp) 函数 * [Sqr](/official/Reference/VBA/Math/Sqr) 函数 --- --- url: /en/official/Reference/VBRUN/Constants/LogEventTypeConstants.md --- # LogEventTypeConstants Severity values for the *EventType* argument of the **LogEvent** method. | Constant | Value | Description | |----------|-------|-------------| | **vbLogEventTypeError** | 1 | The entry describes an error. | | **vbLogEventTypeWarning** | 2 | The entry describes a warning. | | **vbLogEventTypeInformation** | 4 | The entry is informational. | --- --- url: /zh/official/Reference/VBRUN/Constants/LogEventTypeConstants.md --- # LogEventTypeConstants **LogEvent**方法的*EventType*参数的严重级别值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbLogEventTypeError** | 1 | 条目描述一个错误。 | | **vbLogEventTypeWarning** | 2 | 条目描述一个警告。 | | **vbLogEventTypeInformation** | 4 | 条目为信息性内容。 | --- --- url: /en/official/Reference/VBRUN/Constants/LogModeConstants.md --- # LogModeConstants Destination and behaviour flags for the application log, used with **App.StartLogging**. | Constant | Value | Description | |----------|-------|-------------| | **vbLogAuto** | 0 | Choose a destination automatically based on the platform. | | **vbLogOff** | 1 | Disable logging. | | **vbLogToFile** | 2 | Log to a file. | | **vbLogToNT** | 3 | Log to the Windows Event Log. | | **vbLogOverwrite** | 16 | When logging to a file, truncate it first instead of appending. | | **vbLogThreadID** | 32 | Include the thread ID in each log entry. | --- --- url: /zh/official/Reference/VBRUN/Constants/LogModeConstants.md --- # LogModeConstants 应用程序日志的目标和行为标志,与**App.StartLogging**一起使用。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbLogAuto** | 0 | 根据平台自动选择目标。 | | **vbLogOff** | 1 | 禁用日志。 | | **vbLogToFile** | 2 | 记录到文件。 | | **vbLogToNT** | 3 | 记录到Windows事件日志。 | | **vbLogOverwrite** | 16 | 记录到文件时,先截断而非追加。 | | **vbLogThreadID** | 32 | 在每条日志项中包含线程ID。 | --- --- url: /en/official/Features/Language/Loop-Control.md --- # Loop Control The following new statements are available for controlling the procession of loops: * `Continue For` - Proceed to the next iteration (or end) of `For` loop. * `Continue While` - Proceed to the next iteration (or end) of `While` loop. * `Continue Do` - Proceed to the next iteration of `Do` loop. * `Exit While` - Exit a `While` loop immediately. ## Example ```vb Dim i As Long For i = 1 To 10 If i Mod 2 = 0 Then Continue For ' skip even numbers If i > 7 Then Exit For ' stop before reaching 8 Debug.Print i Next ' prints: 1, 3, 5, 7 ``` --- --- url: /en/official/Reference/Core/LSet.md --- # LSet Left-aligns a string within a string variable, or copies a variable of one user-defined type to another variable of a different user-defined type. Syntax: * > **LSet** *stringvar* **=** *string* * > **LSet** *varname1* **=** *varname2* *stringvar* : Name of a string variable. *string* : String expression to be left-aligned within *stringvar*. *varname1* : Variable name of the user-defined type being copied to. *varname2* : Variable name of the user-defined type being copied from. **LSet** replaces any leftover characters in *stringvar* with spaces. If *string* is longer than *stringvar*, **LSet** places only the leftmost characters, up to the length of the *stringvar*, in *stringvar*. ::: warning Using **LSet** to copy a variable of one user-defined type into a variable of a different user-defined type is not recommended. Copying data of one data type into space reserved for a different data type can cause unpredictable results. When a variable is copied from one user-defined type to another, the binary data from one variable is copied into the memory space of the other, without regard for the data types specified for the elements. ::: ### Example This example uses the **LSet** statement to left-align a string within a string variable. Although **LSet** can also be used to copy a variable of one user-defined type to another variable of a different but compatible user-defined type, this practice is not recommended; due to the varying implementations of data structures among platforms, such a use of **LSet** can't be guaranteed to be portable. ```vb Dim MyString MyString = "0123456789" ' Initialize string. LSet MyString = "<-Left" ' MyString contains "<-Left ". ``` ### See Also * [**RSet** statement](/en/official/Reference/Core/RSet) * [**Mid =** statement](/en/official/Reference/Core/Mid-equals) * [**Let** statement](/en/official/Reference/Core/Let) --- --- url: /zh/official/Reference/Core/LSet.md --- # LSet 在字符串变量中左对齐字符串,或将一个用户自定义类型的变量复制到另一个不同用户自定义类型的变量。 语法: * > **LSet** *stringvar* **=** *string* * > **LSet** *varname1* **=** *varname2* *stringvar* : 字符串变量的名称。 *string* : 要在 *stringvar* 中左对齐的字符串表达式。 *varname1* : 被复制到的用户自定义类型的变量名。 *varname2* : 从中复制的用户自定义类型的变量名。 **LSet** 用空格替换 *stringvar* 中的剩余字符。 如果 *string* 比 *stringvar* 长,**LSet** 只将最左边的字符(最多到 *stringvar* 的长度)放入 *stringvar*。 ::: warning 使用 **LSet** 将一种用户自定义类型的变量复制到另一种不同用户自定义类型的变量不推荐。将一种数据类型的数据复制到为不同数据类型保留的空间中可能导致不可预测的结果。当变量从一个用户自定义类型复制到另一个时,一个变量的二进制数据被复制到另一个的内存空间,而不考虑为元素指定的数据类型。 ::: ### 示例 本示例使用 **LSet** 语句在字符串变量中左对齐字符串。虽然 **LSet** 也可以用于将一种用户自定义类型的变量复制到另一种兼容但不同的用户自定义类型的变量,但不推荐这种做法;由于数据结构在不同平台上的实现不同,这种 **LSet** 的用法无法保证可移植性。 ```vb Dim MyString MyString = "0123456789" ' Initialize string. LSet MyString = "<-Left" ' MyString contains "<-Left ". ``` ### 另请参阅 * [**RSet** 语句](/official/Reference/Core/RSet) * [**Mid =** 语句](/official/Reference/Core/Mid-equals) * [**Let** 语句](/official/Reference/Core/Let) --- --- url: /en/official/Reference/VBA/Strings/LTrim.md --- # LTrim Returns a **String** containing a copy of a specified string without leading spaces. Syntax: **LTrim$(** *string* **)**, **LTrim(** *string* **)** *string* : *required* Any valid string expression. If *string* contains **Null**, **Null** is returned. The `$`-suffixed form returns a **String**; the unsuffixed form returns a **Variant** (**String**). ### Example This example uses the **LTrim** function to strip leading spaces from a string variable. ```vb Dim MyString, TrimString MyString = " <-Trim-> " ' Initialize string. TrimString = LTrim(MyString) ' TrimString = "<-Trim-> ". ``` ### See Also * [RTrim](/en/official/Reference/VBA/Strings/RTrim), [Trim](/en/official/Reference/VBA/Strings/Trim) functions --- --- url: /zh/official/Reference/VBA/Strings/LTrim.md --- # LTrim 返回一个**String**,包含指定字符串的副本,不带前导空格。 语法:**LTrim$(** *string* **)**, **LTrim(** *string* **)** *string* : *必需* 任意有效的字符串表达式。如果*string*包含**Null**,则返回**Null**。 带`$`后缀的形式返回**String**;不带后缀的形式返回**Variant**(**String**)。 ### 示例 本示例使用**LTrim**函数去除字符串变量的前导空格。 ```vb Dim MyString, TrimString MyString = " <-Trim-> " ' Initialize string. TrimString = LTrim(MyString) ' TrimString = "<-Trim-> ". ``` ### 另请参阅 * [RTrim](/official/Reference/VBA/Strings/RTrim)、[Trim](/official/Reference/VBA/Strings/Trim)函数 --- --- url: /en/official/Reference/VBA/Conversion/MacID.md --- # MacID Used on the Macintosh to convert a 4-character constant to a value that may be used by [**Dir**](/en/official/Reference/VBA/FileSystem/Dir), [**Kill**](/en/official/Reference/VBA/FileSystem/Kill), **Shell**, and [**AppActivate**](/en/official/Reference/VBA/Interaction/AppActivate). Syntax: **MacID(** *constant* **)** *constant* : *required* A **String** of 4 characters used to specify a resource type, file type, application signature, or Apple Event --- for example, `"TEXT"`, `"OBIN"`, `"XLS5"` for Excel files (`"XLS8"` for Excel 97); Microsoft Word uses `"W6BN"` (`"W8BN"` for Word 97). The return type is **Long**. **MacID** is used with **Dir** and **Kill** to specify a Macintosh file type. Because the Macintosh does not support `*` and `?` as wildcards, a four-character constant identifies groups of files instead. For example, the following statement returns `TEXT`-type files from the current folder: ```vb Dir("SomePath", MacID("TEXT")) ``` **MacID** is used with **Shell** and **AppActivate** to specify an application by using the application's unique signature. ::: info twinBASIC currently targets Windows. **MacID** is provided for source compatibility with VBA code originally written for the Macintosh; on Windows, the value it returns has no special meaning to the file-system or shell functions. ::: --- --- url: /zh/official/Reference/VBA/Conversion/MacID.md --- # MacID 在 Macintosh 上用于将 4 字符常量转换为可供 [**Dir**](/official/Reference/VBA/FileSystem/Dir)、[**Kill**](/official/Reference/VBA/FileSystem/Kill)、**Shell** 和 [**AppActivate**](/official/Reference/VBA/Interaction/AppActivate) 使用的值。 语法:**MacID(** *constant* **)** *constant* : *必需* 一个 4 字符的 **String**,用于指定资源类型、文件类型、应用程序签名或 Apple Event——例如,`"TEXT"`、`"OBIN"`、Excel 文件用 `"XLS5"`(Excel 97 用 `"XLS8"`);Microsoft Word 使用 `"W6BN"`(Word 97 用 `"W8BN"`)。 返回类型为 **Long**。 **MacID** 与 **Dir** 和 **Kill** 一起使用以指定 Macintosh 文件类型。由于 Macintosh 不支持 `*` 和 `?` 作为通配符,因此改用四字符常量来标识文件组。例如,以下语句返回当前文件夹中的 `TEXT` 类型文件: ```vb Dir("SomePath", MacID("TEXT")) ``` **MacID** 与 **Shell** 和 **AppActivate** 一起使用,通过应用程序的唯一签名来指定应用程序。 ::: info twinBASIC 目前面向 Windows。提供 **MacID** 是为了与最初为 Macintosh 编写的 VBA 代码保持源代码兼容性;在 Windows 上,它返回的值对文件系统或 shell 函数没有特殊含义。 ::: --- --- url: /zh/official/Reference/VBA/Math.md --- # Math 模块 **Math** 模块将标准数值函数组合在一起——符号和绝对值、三角函数、指数和对数、平方根、按指定小数位数舍入以及伪随机数生成。大多数成员返回 **Double**,因此中间结果在写回较窄的变量之前保持浮点形式。 ## 符号和绝对值 [**Abs**](/official/Reference/VBA/Math/Abs) 返回其参数的绝对值——与零的距离,丢弃符号——并保留参数的数据类型,因此 `Abs(-3#)` 是 **Double**,`Abs(-3)` 是 **Integer**。[**Sgn**](/official/Reference/VBA/Math/Sgn) 是其补充:丢弃绝对值,仅返回符号,为 `-1`、`0` 或 `+1`。两者共同将一个数分解为符号和绝对值。 ```vb Debug.Print Abs(-7.5) ' 7.5 Debug.Print Sgn(-7.5) ' -1 ``` ## 三角函数 [**Sin**](/official/Reference/VBA/Math/Sin)、[**Cos**](/official/Reference/VBA/Math/Cos) 和 [**Tan**](/official/Reference/VBA/Math/Tan) 接受以弧度表示的角度,返回其正弦、余弦和正切。[**Atn**](/official/Reference/VBA/Math/Atn) 反向操作——给定正切值,返回该正切值对应的角度,范围为 `-pi/2` 到 `pi/2`。这四个函数均以弧度工作;将角度乘以 `pi / 180` 转换为弧度,或将弧度乘以 `180 / pi` 转换回角度。 ```vb Const Pi As Double = 3.14159265358979 Debug.Print Sin(Pi / 2) ' 1 Debug.Print Atn(1) * 4 ' 3.14159265358979 — pi ``` 其他反三角函数(反正弦、反余弦)和双曲函数未直接提供,但每个都可以从 **Atn**、**Log**、**Exp** 和 **Sqr** 用几行代码推导——参见 [**Atn**](/official/Reference/VBA/Math/Atn)、[**Log**](/official/Reference/VBA/Math/Log) 和 [**Cos**](/official/Reference/VBA/Math/Cos) 的详细示例。 ## 指数和对数 [**Exp**](/official/Reference/VBA/Math/Exp) 将 *e*(≈ 2.71828)提升到指定幂次,[**Log**](/official/Reference/VBA/Math/Log) 是其逆运算,返回自然(以 *e* 为底)对数。要计算其他底数的对数,除以该底数的 **Log**:`Log(x) / Log(10)` 为以 10 为底,`Log(x) / Log(2)` 为以 2 为底,依此类推。 ```vb Debug.Print Exp(1) ' 2.71828182845905 — e Debug.Print Log(100) / Log(10) ' 2 — base-10 log of 100 ``` ## 平方根 [**Sqr**](/official/Reference/VBA/Math/Sqr) 返回非负数的平方根,以 **Double** 表示。传入负值会引发运行时错误而非返回复数或 **NaN** 结果;如果计算可能合法地产生负输入,请用 [**Sgn**](/official/Reference/VBA/Math/Sgn) 或与零的比较来保护调用。 ## 舍入 [**Round**](/official/Reference/VBA/Math/Round) 使用*银行家舍入法*将数字舍入到指定小数位数——当值恰好位于两个可能结果的中间时,舍入到最接近的**偶数**数字,因此 `Round(0.5, 0)` 为 `0`,`Round(1.5, 0)` 为 `2`。这避免了始终向上舍入的系统偏差,与 VBA 的行为一致。对于*截断*而非舍入,参见 [**Conversion**](/official/Reference/VBA/Conversion/) 模块中的 [**Int**](/official/Reference/VBA/Conversion/Int) 和 [**Fix**](/official/Reference/VBA/Conversion/Fix);对于舍入到特定整数类型的窄化转换,参见 [**CInt**](/official/Reference/VBA/Conversion/CInt) 和 [**CLng**](/official/Reference/VBA/Conversion/CLng)。 ## 随机数 [**Randomize**](/official/Reference/VBA/Math/Randomize) 为伪随机数生成器设定种子,[**Rnd**](/official/Reference/VBA/Math/Rnd) 从中提取,返回半开区间 `[0, 1)` 内的 **Single**。如果不显式调用 **Randomize**,每次程序运行时 **Rnd** 都会生成相同的序列——便于可重复测试;对于不可预测的输出,在启动时不带参数调用一次 **Randomize**,以便使用系统计时器作为种子。 在 *lower* 和 *upper*(含)之间均匀分布整数的标准惯用法结合了 **Rnd** 和 [**Int**](/official/Reference/VBA/Conversion/Int): ```vb Randomize Dim Roll As Long Roll = Int((6 - 1 + 1) * Rnd + 1) ' a die roll, 1..6 ``` ## 成员 * [Abs](/official/Reference/VBA/Math/Abs) -- 返回数字的绝对值 * [Atn](/official/Reference/VBA/Math/Atn) -- 返回数字的反正切值(弧度) * [Cos](/official/Reference/VBA/Math/Cos) -- 返回角度的余弦值 * [Exp](/official/Reference/VBA/Math/Exp) -- 返回 *e* 的指定幂次 * [Log](/official/Reference/VBA/Math/Log) -- 返回数字的自然(以 *e* 为底)对数 * [Randomize](/official/Reference/VBA/Math/Randomize) -- 初始化随机数生成器 * [Rnd](/official/Reference/VBA/Math/Rnd) -- 返回 `[0, 1)` 范围内的伪随机数 * [Round](/official/Reference/VBA/Math/Round) -- 使用银行家舍入法将数字舍入到指定小数位数 * [Sgn](/official/Reference/VBA/Math/Sgn) -- 返回数字的符号 * [Sin](/official/Reference/VBA/Math/Sin) -- 返回角度的正弦值 * [Sqr](/official/Reference/VBA/Math/Sqr) -- 返回数字的平方根 * [Tan](/official/Reference/VBA/Math/Tan) -- 返回角度的正切值 --- --- url: /en/official/Reference/VBA/Math.md --- # Math module The **Math** module groups together the standard numeric functions --- sign and magnitude, trigonometry, exponentials and logarithms, the square root, rounding to a chosen number of decimal places, and pseudo-random number generation. Most members return a **Double**, so intermediate results stay in floating point until they are written back to a narrower variable. ## Sign and magnitude [**Abs**](/en/official/Reference/VBA/Math/Abs) returns the absolute value of its argument --- its distance from zero, with the sign discarded --- and preserves the argument's data type, so `Abs(-3#)` is a **Double** and `Abs(-3)` an **Integer**. [**Sgn**](/en/official/Reference/VBA/Math/Sgn) is the complement: it discards the magnitude and returns just the sign, as `-1`, `0`, or `+1`. Together they decompose a number into its sign and magnitude. ```vb Debug.Print Abs(-7.5) ' 7.5 Debug.Print Sgn(-7.5) ' -1 ``` ## Trigonometry [**Sin**](/en/official/Reference/VBA/Math/Sin), [**Cos**](/en/official/Reference/VBA/Math/Cos), and [**Tan**](/en/official/Reference/VBA/Math/Tan) take an angle in radians and return its sine, cosine, and tangent. [**Atn**](/en/official/Reference/VBA/Math/Atn) goes the other way --- given a tangent, it returns the angle whose tangent that is, in the range `-pi/2` to `pi/2`. All four work exclusively in radians; multiply degrees by `pi / 180` to convert to radians, or radians by `180 / pi` to convert back. ```vb Const Pi As Double = 3.14159265358979 Debug.Print Sin(Pi / 2) ' 1 Debug.Print Atn(1) * 4 ' 3.14159265358979 — pi ``` The other inverse trigonometric functions (arcsine, arccosine) and the hyperbolic functions are not provided directly, but each can be derived from **Atn**, **Log**, **Exp**, and **Sqr** in a couple of lines --- see the worked examples on [**Atn**](/en/official/Reference/VBA/Math/Atn), [**Log**](/en/official/Reference/VBA/Math/Log), and [**Cos**](/en/official/Reference/VBA/Math/Cos). ## Exponentials and logarithms [**Exp**](/en/official/Reference/VBA/Math/Exp) raises *e* (≈ 2.71828) to a chosen power, and [**Log**](/en/official/Reference/VBA/Math/Log) is its inverse, returning the natural (base-*e*) logarithm. To compute a logarithm in another base, divide by **Log** of that base: `Log(x) / Log(10)` for base 10, `Log(x) / Log(2)` for base 2, and so on. ```vb Debug.Print Exp(1) ' 2.71828182845905 — e Debug.Print Log(100) / Log(10) ' 2 — base-10 log of 100 ``` ## Square root [**Sqr**](/en/official/Reference/VBA/Math/Sqr) returns the square root of a non-negative number as a **Double**. Passing a negative value raises a run-time error rather than returning a complex or **NaN** result; if a calculation may legitimately produce a negative input, guard the call with [**Sgn**](/en/official/Reference/VBA/Math/Sgn) or a comparison to zero. ## Rounding [**Round**](/en/official/Reference/VBA/Math/Round) rounds a number to a chosen number of decimal places using *banker's rounding* --- when the value lies exactly half-way between two possible results, it rounds toward the nearest **even** digit, so `Round(0.5, 0)` is `0` and `Round(1.5, 0)` is `2`. This avoids the systematic upward bias of always-round-half-up and matches VBA's behaviour. For *truncation* rather than rounding, see [**Int**](/en/official/Reference/VBA/Conversion/Int) and [**Fix**](/en/official/Reference/VBA/Conversion/Fix) in the [**Conversion**](/en/official/Reference/VBA/Conversion/) module; for narrowing-with-rounding to a specific integer type, see [**CInt**](/en/official/Reference/VBA/Conversion/CInt) and [**CLng**](/en/official/Reference/VBA/Conversion/CLng). ## Random numbers [**Randomize**](/en/official/Reference/VBA/Math/Randomize) seeds the pseudo-random number generator, and [**Rnd**](/en/official/Reference/VBA/Math/Rnd) draws from it, returning a **Single** in the half-open range `[0, 1)`. Without an explicit call to **Randomize**, **Rnd** produces the same sequence every time the program runs --- convenient for reproducible tests; for unpredictable output, call **Randomize** once at startup with no argument so the system timer is used as the seed. The standard idiom for a uniformly distributed integer between *lower* and *upper* (inclusive) combines **Rnd** with [**Int**](/en/official/Reference/VBA/Conversion/Int): ```vb Randomize Dim Roll As Long Roll = Int((6 - 1 + 1) * Rnd + 1) ' a die roll, 1..6 ``` ## Members * [Abs](/en/official/Reference/VBA/Math/Abs) -- returns the absolute value of a number * [Atn](/en/official/Reference/VBA/Math/Atn) -- returns the arctangent of a number, in radians * [Cos](/en/official/Reference/VBA/Math/Cos) -- returns the cosine of an angle * [Exp](/en/official/Reference/VBA/Math/Exp) -- returns *e* raised to a power * [Log](/en/official/Reference/VBA/Math/Log) -- returns the natural (base-*e*) logarithm of a number * [Randomize](/en/official/Reference/VBA/Math/Randomize) -- initialises the random-number generator * [Rnd](/en/official/Reference/VBA/Math/Rnd) -- returns a pseudo-random number in the range `[0, 1)` * [Round](/en/official/Reference/VBA/Math/Round) -- rounds a number to a chosen number of decimal places, using banker's rounding * [Sgn](/en/official/Reference/VBA/Math/Sgn) -- returns the sign of a number * [Sin](/en/official/Reference/VBA/Math/Sin) -- returns the sine of an angle * [Sqr](/en/official/Reference/VBA/Math/Sqr) -- returns the square root of a number * [Tan](/en/official/Reference/VBA/Math/Tan) -- returns the tangent of an angle --- --- url: /zh/packages/vbccr/system/mciwnd.md description: MCIWnd 控件(MCIWnd) - VBCCR 开发手册,基于源码的完整 API 参考 --- # MCIWnd 控件(MCIWnd) 封装 MCIWnd 窗口类,提供多媒体设备控制和音视频播放功能。 ## 枚举 ### MciFormatConstants | 常量 | 值 | 说明 | |------|-----|------| | MciFormatMpeg | 0 | MPEG 格式 | | MciFormatAvi | 1 | AVI 格式 | | MciFormatMidi | 2 | MIDI 格式 | | MciFormatWave | 3 | Wave 格式 | | MciFormatOle | 4 | OLE 存储 | | MciFormatOleStream | 5 | OLE 流 | | MciFormatRiff | 6 | RIFF 格式 | | MciFormatExif | 7 | Exif 格式 | | MciFormatJpeg | 8 | JPEG 格式 | | MciFormatPng | 9 | PNG 格式 | | MciFormatGif | 10 | GIF 格式 | ### MciModeConstants | 常量 | 值 | 说明 | |------|-----|------| | MciModeNotOpen | 524 | 设备未打开 | | MciModeStop | 525 | 设备已停止 | | MciModePlay | 526 | 设备正在播放 | | MciModeRecord | 527 | 设备正在录制 | | MciModeSeek | 528 | 设备正在定位 | | MciModePause | 529 | 设备已暂停 | | MciModeReady | 530 | 设备就绪 | ### MciNotifyConstants | 常量 | 值 | 说明 | |------|-----|------| | MciNotifyAborted | \&H4 | 操作被中止 | | MciNotifySuperseded | \&H8 | 操作被替代 | | MciNotifySuccessful | \&H1 | 操作成功完成 | | MciNotifyFailure | \&H2 | 操作失败 | ### MciCaptionConstants | 常量 | 值 | 说明 | |------|-----|------| | MciCaptionOff | 0 | 不显示标题 | | MciCaptionFileName | 1 | 显示文件名 | | MciCaptionDevice | 2 | 显示设备名称 | | MciCaptionMode | 3 | 显示当前模式 | | MciCaptionPosition | 4 | 显示当前位置 | | MciCaptionLength | 5 | 显示媒体长度 | | MciCaptionError | 6 | 显示错误信息 | | MciCaptionInfo | 7 | 显示所有信息 | ### CCBorderStyleConstants 参见通用枚举。 ### CCMousePointerConstants 参见通用枚举。 ## 属性 ### Command ```vb Property Let Command(ByVal Value As String) ``` 向 MCI 设备发送命令字符串。 ### CommandReturn ```vb Property Get CommandReturn() As String ``` 返回最后一次 MCI 命令的返回结果。只读。 ### FileName ```vb Property Get FileName() As String Property Let FileName(ByVal Value As String) ``` 要打开或加载的媒体文件名。 ### DeviceAlias ```vb Property Get DeviceAlias() As String ``` 返回设备的别名。只读。 ### DeviceID ```vb Property Get DeviceID() As Long ``` 返回设备的 ID。只读。 ### Device ```vb Property Get Device() As String ``` 返回当前设备类型。只读。 ### NewDevice ```vb Property Let NewDevice(ByVal Value As String) ``` 设置要打开的新设备类型。只写。 ### Error ```vb Property Get Error() As Long ``` 返回最近的 MCI 错误代码。只读。 ### ErrorString ```vb Property Get ErrorString() As String ``` 返回最近的 MCI 错误描述字符串。只读。 ### TimeFormat ```vb Property Get TimeFormat() As MciFormatConstants Property Let TimeFormat(ByVal Value As MciFormatConstants) ``` 时间格式。 ### Mode ```vb Property Get Mode() As MciModeConstants ``` 返回当前设备模式。只读。 ### ModeString ```vb Property Get ModeString() As String ``` 返回当前设备模式的字符串描述。只读。 ### Position ```vb Property Get Position() As Long ``` 返回当前位置。只读。 ### PositionString ```vb Property Get PositionString() As String ``` 返回当前位置的字符串表示。只读。 ### StartPosition ```vb Property Get StartPosition() As Long ``` 返回起始位置。只读。 ### Length ```vb Property Get Length() As Long ``` 返回媒体总长度。只读。 ### EndPosition ```vb Property Get EndPosition() As Long ``` 返回结束位置。只读。 ### Volume ```vb Property Get Volume() As Long Property Let Volume(ByVal Value As Long) ``` 音量。 ### Speed ```vb Property Get Speed() As Long Property Let Speed(ByVal Value As Long) ``` 播放速度。 ### Repeat ```vb Property Get Repeat() As Boolean Property Let Repeat(ByVal Value As Boolean) ``` 是否循环播放。 ### ErrorDlg ```vb Property Get ErrorDlg() As Boolean Property Let ErrorDlg(ByVal Value As Boolean) ``` 是否显示错误对话框。 ### Record ```vb Property Get Record() As Boolean Property Let Record(ByVal Value As Boolean) ``` 是否处于录制模式。 ### Playbar ```vb Property Get Playbar() As Boolean Property Let Playbar(ByVal Value As Boolean) ``` 是否显示播放条。 ### Menu ```vb Property Get Menu() As Boolean Property Let Menu(ByVal Value As Boolean) ``` 是否显示菜单。 ### AllowOpen ```vb Property Get AllowOpen() As Boolean Property Let AllowOpen(ByVal Value As Boolean) ``` 是否允许通过用户界面打开文件。 ### AutoSizeWindow ```vb Property Get AutoSizeWindow() As Boolean Property Let AutoSizeWindow(ByVal Value As Boolean) ``` 是否自动调整窗口大小以适应媒体。 ### AutoSizeMovie ```vb Property Get AutoSizeMovie() As Boolean Property Let AutoSizeMovie(ByVal Value As Boolean) ``` 是否自动调整媒体大小以适应窗口。 ### TimerFreq ```vb Property Get TimerFreq() As Long Property Let TimerFreq(ByVal Value As Long) ``` 计时器频率。 ### Zoom ```vb Property Get Zoom() As Long Property Let Zoom(ByVal Value As Long) ``` 缩放比例。 ### Caption ```vb Property Get Caption() As MciCaptionConstants Property Let Caption(ByVal Value As MciCaptionConstants) ``` 标题显示模式。 ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` 背景颜色。 ### BorderStyle ```vb Property Get BorderStyle() As CCBorderStyleConstants Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` 边框样式。参见通用枚举。 ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` 是否启用视觉样式。 ### hWnd ```vb Property Get hWnd() As LongPtr ``` MCIWnd 控件的窗口句柄。 ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` 用户控件的窗口句柄。 ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` 字体。 ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` 是否可用。 ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` 鼠标指针样式。参见通用枚举。 ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` 自定义鼠标图标。 ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` 是否启用鼠标进入/离开跟踪。 ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` 从右到左显示方向。 ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` 从右到左模式。参见通用枚举。 ### Name ```vb Property Get Name() As String ``` 控件名称。只读。 ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` 自定义数据。 ### Parent ```vb Property Get Parent() As Object ``` 父对象。只读。 ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` 容器对象。 ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` 左边距。 ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` 顶边距。 ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` 宽度。 ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` 高度。 ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` 是否可见。 ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` 工具提示文本。 ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` 帮助上下文 ID。 ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "这是什么"帮助 ID。 ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` 拖拽图标。 ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` 拖拽模式。 ## 方法 ### ShowOpen ```vb Public Sub ShowOpen() ``` 显示打开文件对话框。 ### ShowSave ```vb Public Sub ShowSave() ``` 显示保存文件对话框。 ### CanSave ```vb Public Function CanSave() As Boolean ``` 判断是否可以保存当前媒体。 ### Eject ```vb Public Sub Eject() ``` 弹出当前媒体。 ### CanEject ```vb Public Function CanEject() As Boolean ``` 判断设备是否支持弹出操作。 ### PlayFrom ```vb Public Sub PlayFrom(ByVal StartPosition As Long) ``` 从指定位置开始播放。 ### PlayTo ```vb Public Sub PlayTo(ByVal EndPosition As Long) ``` 播放到指定位置后停止。 ### PlayReverse ```vb Public Sub PlayReverse() ``` 反向播放。 ### CanPlay ```vb Public Function CanPlay() As Boolean ``` 判断设备是否支持播放。 ### CanRecord ```vb Public Function CanRecord() As Boolean ``` 判断设备是否支持录制。 ### CanConfig ```vb Public Function CanConfig() As Boolean ``` 判断设备是否支持配置。 ### CanWindow ```vb Public Function CanWindow() As Boolean ``` 判断设备是否支持窗口显示。 ### Drag ```vb Public Sub Drag([ByRef Action As Variant]) ``` 开始、结束或取消拖放操作。 ### SetFocus ```vb Public Sub SetFocus() ``` 将焦点移至控件。 ### ZOrder ```vb Public Sub ZOrder([ByRef Position As Variant]) ``` 设置控件的 Z 顺序。 ### OLEDrag ```vb Public Sub OLEDrag() ``` 启动 OLE 拖放操作。 ### Refresh ```vb Public Sub Refresh() ``` 强制重绘控件。 ## 事件 ### ModeChange ```vb Public Event ModeChange() ``` 设备模式发生改变时触发。 ### PositionChange ```vb Public Event PositionChange() ``` 当前位置发生改变时触发。 ### MediaChange ```vb Public Event MediaChange() ``` 当前媒体发生改变时触发。 ### Error ```vb Public Event Error() ``` 发生 MCI 错误时触发。 ### Notify ```vb Public Event Notify() ``` MCI 操作完成通知。 ### Signal ```vb Public Event Signal() ``` 收到信号时触发。 ### Click ```vb Public Event Click() ``` 单击控件时触发。 ### DblClick ```vb Public Event DblClick() ``` 双击控件时触发。 ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 按下鼠标按钮时触发。 ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 释放鼠标按钮时触发。 ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` 移动鼠标时触发。 ### MouseEnter ```vb Public Event MouseEnter() ``` 鼠标进入控件时触发。 ### MouseLeave ```vb Public Event MouseLeave() ``` 鼠标离开控件时触发。 ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` OLE 拖放完成时触发。 ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` OLE 拖放经过控件时触发。 ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` OLE 拖放需要更改光标时触发。 ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` OLE 拖放开始时触发。 ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` OLE 拖放完成时触发。 ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` OLE 放置目标请求数据时触发。 ## 代码示例 ```vb ' 打开并播放 AVI 文件 MCIWnd1.FileName = "C:\video.avi" MCIWnd1.Playbar = True MCIWnd1.Command = "play" ' 录制音频 MCIWnd1.NewDevice = "waveaudio" MCIWnd1.Command = "open new" MCIWnd1.Record = True MCIWnd1.Command = "record" ``` --- --- url: /en/packages/vbccr/system/mciwnd.md description: >- MCIWnd Control - VBCCR Development Manual, Complete API Reference Based on Source Code --- # MCIWnd Control Wraps the MCIWnd window class, providing multimedia device control and audio/video playback functionality. ## Enumerations ### MciFormatConstants | Constant | Value | Description | |------|-----|------| | MciFormatMpeg | 0 | MPEG format | | MciFormatAvi | 1 | AVI format | | MciFormatMidi | 2 | MIDI format | | MciFormatWave | 3 | Wave format | | MciFormatOle | 4 | OLE storage | | MciFormatOleStream | 5 | OLE stream | | MciFormatRiff | 6 | RIFF format | | MciFormatExif | 7 | Exif format | | MciFormatJpeg | 8 | JPEG format | | MciFormatPng | 9 | PNG format | | MciFormatGif | 10 | GIF format | ### MciModeConstants | Constant | Value | Description | |------|-----|------| | MciModeNotOpen | 524 | Device not open | | MciModeStop | 525 | Device stopped | | MciModePlay | 526 | Device playing | | MciModeRecord | 527 | Device recording | | MciModeSeek | 528 | Device seeking | | MciModePause | 529 | Device paused | | MciModeReady | 530 | Device ready | ### MciNotifyConstants | Constant | Value | Description | |------|-----|------| | MciNotifyAborted | \&H4 | Operation aborted | | MciNotifySuperseded | \&H8 | Operation superseded | | MciNotifySuccessful | \&H1 | Operation completed successfully | | MciNotifyFailure | \&H2 | Operation failed | ### MciCaptionConstants | Constant | Value | Description | |------|-----|------| | MciCaptionOff | 0 | No caption displayed | | MciCaptionFileName | 1 | Display file name | | MciCaptionDevice | 2 | Display device name | | MciCaptionMode | 3 | Display current mode | | MciCaptionPosition | 4 | Display current position | | MciCaptionLength | 5 | Display media length | | MciCaptionError | 6 | Display error information | | MciCaptionInfo | 7 | Display all information | ### CCBorderStyleConstants See Common Enumerations. ### CCMousePointerConstants See Common Enumerations. ## Properties ### Command ```vb Property Let Command(ByVal Value As String) ``` Sends a command string to the MCI device. ### CommandReturn ```vb Property Get CommandReturn() As String ``` Returns the result of the last MCI command. Read-only. ### FileName ```vb Property Get FileName() As String Property Let FileName(ByVal Value As String) ``` Media file name to open or load. ### DeviceAlias ```vb Property Get DeviceAlias() As String ``` Returns the device alias. Read-only. ### DeviceID ```vb Property Get DeviceID() As Long ``` Returns the device ID. Read-only. ### Device ```vb Property Get Device() As String ``` Returns the current device type. Read-only. ### NewDevice ```vb Property Let NewDevice(ByVal Value As String) ``` Sets the new device type to open. Write-only. ### Error ```vb Property Get Error() As Long ``` Returns the most recent MCI error code. Read-only. ### ErrorString ```vb Property Get ErrorString() As String ``` Returns the most recent MCI error description string. Read-only. ### TimeFormat ```vb Property Get TimeFormat() As MciFormatConstants Property Let TimeFormat(ByVal Value As MciFormatConstants) ``` Time format. ### Mode ```vb Property Get Mode() As MciModeConstants ``` Returns the current device mode. Read-only. ### ModeString ```vb Property Get ModeString() As String ``` Returns the string description of the current device mode. Read-only. ### Position ```vb Property Get Position() As Long ``` Returns the current position. Read-only. ### PositionString ```vb Property Get PositionString() As String ``` Returns the string representation of the current position. Read-only. ### StartPosition ```vb Property Get StartPosition() As Long ``` Returns the start position. Read-only. ### Length ```vb Property Get Length() As Long ``` Returns the total media length. Read-only. ### EndPosition ```vb Property Get EndPosition() As Long ``` Returns the end position. Read-only. ### Volume ```vb Property Get Volume() As Long Property Let Volume(ByVal Value As Long) ``` Volume level. ### Speed ```vb Property Get Speed() As Long Property Let Speed(ByVal Value As Long) ``` Playback speed. ### Repeat ```vb Property Get Repeat() As Boolean Property Let Repeat(ByVal Value As Boolean) ``` Whether to loop playback. ### ErrorDlg ```vb Property Get ErrorDlg() As Boolean Property Let ErrorDlg(ByVal Value As Boolean) ``` Whether to display error dialogs. ### Record ```vb Property Get Record() As Boolean Property Let Record(ByVal Value As Boolean) ``` Whether in recording mode. ### Playbar ```vb Property Get Playbar() As Boolean Property Let Playbar(ByVal Value As Boolean) ``` Whether to display the playbar. ### Menu ```vb Property Get Menu() As Boolean Property Let Menu(ByVal Value As Boolean) ``` Whether to display the menu. ### AllowOpen ```vb Property Get AllowOpen() As Boolean Property Let AllowOpen(ByVal Value As Boolean) ``` Whether to allow opening files through the user interface. ### AutoSizeWindow ```vb Property Get AutoSizeWindow() As Boolean Property Let AutoSizeWindow(ByVal Value As Boolean) ``` Whether to automatically resize the window to fit the media. ### AutoSizeMovie ```vb Property Get AutoSizeMovie() As Boolean Property Let AutoSizeMovie(ByVal Value As Boolean) ``` Whether to automatically resize the media to fit the window. ### TimerFreq ```vb Property Get TimerFreq() As Long Property Let TimerFreq(ByVal Value As Long) ``` Timer frequency. ### Zoom ```vb Property Get Zoom() As Long Property Let Zoom(ByVal Value As Long) ``` Zoom ratio. ### Caption ```vb Property Get Caption() As MciCaptionConstants Property Let Caption(ByVal Value As MciCaptionConstants) ``` Caption display mode. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### BorderStyle ```vb Property Get BorderStyle() As CCBorderStyleConstants Property Let BorderStyle(ByVal Value As CCBorderStyleConstants) ``` Border style. See Common Enumerations. ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` Whether visual styles are enabled. ### hWnd ```vb Property Get hWnd() As LongPtr ``` Window handle of the MCIWnd control. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Window handle of the user control. ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` Font. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` Mouse pointer style. See Common Enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` Custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Whether mouse enter/leave tracking is enabled. ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` Right-to-left display direction. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` Right-to-left mode. See Common Enumerations. ### Name ```vb Property Get Name() As String ``` Control name. Read-only. ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` Custom data. ### Parent ```vb Property Get Parent() As Object ``` Parent object. Read-only. ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` Container object. ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` Left margin. ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` Top margin. ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` Width. ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` Height. ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` Whether the control is visible. ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` Tooltip text. ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` Help context ID. ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "What's This" Help ID. ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` Drag icon. ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` Drag mode. ## Methods ### ShowOpen ```vb Public Sub ShowOpen() ``` Displays the Open File dialog. ### ShowSave ```vb Public Sub ShowSave() ``` Displays the Save File dialog. ### CanSave ```vb Public Function CanSave() As Boolean ``` Determines whether the current media can be saved. ### Eject ```vb Public Sub Eject() ``` Ejects the current media. ### CanEject ```vb Public Function CanEject() As Boolean ``` Determines whether the device supports the eject operation. ### PlayFrom ```vb Public Sub PlayFrom(ByVal StartPosition As Long) ``` Starts playback from the specified position. ### PlayTo ```vb Public Sub PlayTo(ByVal EndPosition As Long) ``` Plays to the specified position and stops. ### PlayReverse ```vb Public Sub PlayReverse() ``` Plays in reverse. ### CanPlay ```vb Public Function CanPlay() As Boolean ``` Determines whether the device supports playback. ### CanRecord ```vb Public Function CanRecord() As Boolean ``` Determines whether the device supports recording. ### CanConfig ```vb Public Function CanConfig() As Boolean ``` Determines whether the device supports configuration. ### CanWindow ```vb Public Function CanWindow() As Boolean ``` Determines whether the device supports window display. ### Drag ```vb Public Sub Drag([ByRef Action As Variant]) ``` Starts, ends, or cancels a drag operation. ### SetFocus ```vb Public Sub SetFocus() ``` Moves focus to the control. ### ZOrder ```vb Public Sub ZOrder([ByRef Position As Variant]) ``` Sets the Z-order of the control. ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag-and-drop operation. ### Refresh ```vb Public Sub Refresh() ``` Forces a repaint of the control. ## Events ### ModeChange ```vb Public Event ModeChange() ``` Fired when the device mode changes. ### PositionChange ```vb Public Event PositionChange() ``` Fired when the current position changes. ### MediaChange ```vb Public Event MediaChange() ``` Fired when the current media changes. ### Error ```vb Public Event Error() ``` Fired when an MCI error occurs. ### Notify ```vb Public Event Notify() ``` MCI operation completion notification. ### Signal ```vb Public Event Signal() ``` Fired when a signal is received. ### Click ```vb Public Event Click() ``` Fired when the control is clicked. ### DblClick ```vb Public Event DblClick() ``` Fired when the control is double-clicked. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when a mouse button is pressed. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when a mouse button is released. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when the mouse is moved. ### MouseEnter ```vb Public Event MouseEnter() ``` Fired when the mouse enters the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Fired when the mouse leaves the control. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when an OLE drag-and-drop operation is completed. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` Fired when an OLE drag-and-drop operation passes over the control. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` Fired when the cursor needs to be changed during an OLE drag-and-drop operation. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` Fired when an OLE drag-and-drop operation starts. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` Fired when an OLE drag-and-drop operation is completed. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` Fired when the OLE drop target requests data. ## Code Examples ```vb ' Open and play an AVI file MCIWnd1.FileName = "C:\video.avi" MCIWnd1.Playbar = True MCIWnd1.Command = "play" ' Record audio MCIWnd1.NewDevice = "waveaudio" MCIWnd1.Command = "open new" MCIWnd1.Record = True MCIWnd1.Command = "record" ``` --- --- url: /en/official/Reference/VB/MDIForm.md --- # MDIForm class An **MDIForm** is a top-level Win32 window that hosts an *MDI client area* --- a recessed working surface in which one or more [**Form**](/en/official/Reference/VB/Form/) instances marked as MDI children appear, each with its own caption bar inside the parent. A twinBASIC project may contain at most one MDI form. Unlike an ordinary [**Form**](/en/official/Reference/VB/Form/), an MDIForm has no drawing surface, no font properties, and no graphics primitives --- it is purely a frame for its children, plus a host for menus, toolbars, and (optionally) a single background [**Picture**](#picture) drawn behind the children. The default property is [**Controls**](#controls) and the default event is [**Load**](#load). ```vb ' In MDIForm1's code-behind: Private Sub MDIForm_Load() Caption = "Editor" AutoShowChildren = True End Sub Private Sub mnuWindowCascade_Click() Arrange vbCascade End Sub ' In a child form (Form1) marked MDIChild = True: Private Sub Form_Load() Caption = "Untitled" End Sub ' In a startup module: Sub Main() MDIForm1.Show Form1.Show ' opens inside MDIForm1's client area End Sub ``` ## Lifecycle The MDIForm goes through the same six events as a regular [**Form**](/en/official/Reference/VB/Form/) from creation to destruction: | Event | When | |----------------------------------|-------------------------------------------------------------------------------------| | [**Initialize**](#initialize) | Before the underlying window exists. The form's children and controls do not yet exist. | | [**Load**](#load) | After the window has been created and the child controls (toolbar bands, status bars, menus) have been instantiated, before the form first appears. | | [**Activate**](#activate) | When the MDI parent or one of its child forms becomes active. | | [**Deactivate**](#deactivate) | When activation moves to another window outside the MDI group. | | [**QueryUnload**](#queryunload) | Before unload. Setting *Cancel* to non-zero keeps the form open. Closing the MDI parent first runs **QueryUnload** on every open MDI child, then on the parent itself. | | [**Unload**](#unload) | After **QueryUnload** approves. Setting *Cancel* to non-zero keeps the form open. | | [**Terminate**](#terminate) | After the window has been destroyed and the class instance is released. | ## MDI children An MDI child is any [**Form**](/en/official/Reference/VB/Form/) whose **MDIChild** property is **True** (set at design time). Showing or unhiding such a form parents it to the MDI client area: its [**Left**](/en/official/Reference/VB/Form/#left) and [**Top**](/en/official/Reference/VB/Form/#top) become relative to the client area's upper-left corner, its title bar is drawn inside the parent rather than on the desktop, and maximising it merges its system menu and minimise/maximise buttons into the parent's title bar. [**ActiveForm**](#activeform) returns the currently focused child, or **Nothing** when no child is open. [**Activate**](#activate) and [**Deactivate**](#deactivate) on the MDI parent fire only when activation crosses the MDI group's outer boundary; activation moves *within* the group fire **Activate** / **Deactivate** on the affected child forms instead. [**AutoShowChildren**](#autoshowchildren) decides what happens when an MDI child class is loaded but not explicitly shown --- when **True** (default), the child is made visible automatically; when **False**, the child stays hidden until code calls **Show** on it. [**Arrange**](#arrange) lays the open children out in a single call: cascade, tile horizontally, tile vertically, or arrange the icons of minimised children along the bottom edge. ```vb mnuWindowCascade.Click => Me.Arrange vbCascade mnuWindowTileH.Click => Me.Arrange vbTileHorizontal mnuWindowTileV.Click => Me.Arrange vbTileVertical mnuWindowArrangeIcons.Click => Me.Arrange vbArrangeIcons ``` ## Window appearance An MDIForm always uses the sizable border style --- there is no [**BorderStyle**](/en/official/Reference/VB/Form/#borderstyle) property, the title bar is always present, the system menu and minimise / maximise buttons are always shown, and the form always appears in the taskbar. [**Caption**](#caption) sets the title-bar text. [**Icon**](#icon) supplies the small/large icon used by the system menu, the taskbar, and Alt-Tab. [**WindowState**](#windowstate) ([**FormWindowStateConstants**](/en/official/Reference/VBRUN/Constants/FormWindowStateConstants)) reads or sets normal / minimised / maximised state at run time. [**MinWidth**](#minwidth), [**MinHeight**](#minheight), [**MaxWidth**](#maxwidth), and [**MaxHeight**](#maxheight) constrain the *client area* in twips during interactive resizing. [**Moveable**](#moveable) decides whether the user can drag the form by its title bar. [**Opacity**](#opacity) and [**TransparencyKey**](#transparencykey) enable Windows' layered-window features for translucent forms and cut-out shapes. [**BackColor**](#backcolor) paints the MDI client area's background --- defaults to the system **vbApplicationWorkspace** colour rather than 3-D face. [**Picture**](#picture), when set, is drawn over **BackColor** as the client-area backdrop, scaled to fill the area for metafiles and centred at its natural size for bitmaps. [**PictureDpiScaling**](#picturedpiscaling) scales bitmaps by the current DPI factor before drawing. There is no on-screen drawing API on an MDIForm --- the [**Cls**](/en/official/Reference/VB/Form/#cls), [**Circle**](/en/official/Reference/VB/Form/#circle), [**Line**](/en/official/Reference/VB/Form/#line), [**PSet**](/en/official/Reference/VB/Form/#pset), [**PaintPicture**](/en/official/Reference/VB/Form/#paintpicture), and **Print** members of the **Form** interface raise run-time error 438 (*Object doesn't support this property or method*) when called on an MDIForm. A vertical and a horizontal scroll bar appear automatically when an MDI child is moved or sized so that its rectangle extends beyond the visible client area; this is fixed at design time through the **ScrollBars** property of the MDI parent and is not exposed at run time. ## Menus and pop-ups Menu structures designed at form-design time appear automatically in the MDIForm's title bar. When an MDI child is maximised, the child's own menu (if any) is merged into the parent's menu bar, replacing it for as long as the child stays maximised. The classic VB6 *window-list* feature --- a menu sub-tree that lists every open MDI child for quick switching --- is supported automatically when a [**Menu**](/en/official/Reference/VB/Menu/) on the MDIForm has its **WindowList** property set. [**PopUpMenu**](#popupmenu) displays one of the form's menus as a context-menu pop-up at a specified location, raising the menu's **Click** event when the user picks an item. ```vb Private Sub MDIForm_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) If Button = vbRightButton Then PopUpMenu mnuContext End Sub ``` ## Differences from Form Because the MDIForm is a frame, not a drawing surface, the following members of the **Form** interface are *not* supported on it --- accessing them raises run-time error 380 (properties) or 438 (methods): | Category | Members | |------------------------------|--------------------------------------------------------------------------------------| | Drawing | **AutoRedraw**, **ClipControls**, **HasDC**, **hDC**, **Image**, **CurrentX**, **CurrentY**, **DrawMode**, **DrawStyle**, **DrawWidth**, **FillColor**, **FillStyle**, **ForeColor**, **FontTransparent**, **Cls**, **Circle**, **Line**, **PSet**, **PaintPicture** | | Font | **Font**, **FontName**, **FontSize**, **FontBold**, **FontItalic**, **FontStrikethru**, **FontUnderline**, **TextWidth** | | Geometry | **ScaleLeft**, **ScaleTop**, **ScaleMode**, **Scale**, **ScaleX**, **ScaleY** ([**ScaleWidth**](#scalewidth) and [**ScaleHeight**](#scaleheight) are supported but read-only) | | Window chrome | **BorderStyle**, **ControlBox**, **MaxButton**, **MinButton**, **ShowInTaskbar**, **WhatsThisButton** | | Other | **KeyPreview** (and the [**Form**](/en/official/Reference/VB/Form/)'s **KeyDown** / **KeyUp** / **KeyPress** events do not exist on **MDIForm**), **MDIChild**, **NegotiateMenus**, **Palette**, **PaletteMode**, **PrintForm**, **Point**, **Refresh** (raises 438 on an MDIForm even though it works on a regular Form) | | Behaviour quirk | **TextHeight** returns `0` instead of raising. (VB6 bug retained for compatibility.) | ## Properties ### ActiveControl The control on the active MDI child that currently has the input focus, as a **Control** object, or **Nothing** when no child is focused. Read-only. ### ActiveForm The currently active MDI child form, as an **Object**, or **Nothing** when no child is open. Read-only. Updated each time activation moves between children, just before the corresponding [**Activate**](#activate) and [**Deactivate**](#deactivate) events fire on the child forms. ### AlwaysShowKeyboardCues When **True**, the form always shows underlines on access-key characters in [**Caption**](#caption)s and menu items, instead of only displaying them after the user presses **Alt**. **Boolean**, read-only at run time. Set at design time. ### Appearance A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). ::: info Retained for VB6 compatibility; the property has no observable effect on an MDI form. ::: ### AutoShowChildren When **True** (default), loading an MDI child class also shows it; when **False**, child classes can be loaded into memory without becoming visible until code calls **Show** on them. **Boolean**. ### BackColor The colour painted in the MDI client area, as an **OLE\_COLOR**. Defaults to the system **vbApplicationWorkspace** colour. Used as the canvas behind [**Picture**](#picture) and behind every MDI child's title bar and outer border. ### Caption The title-bar text. **String**. Syntax: *object*.**Caption** \[ = *string* ] When an MDI child is maximised, Windows decorates **Caption** with the child's caption in square brackets --- `Editor - [Untitled]` --- and the application normally lets that decoration stay automatic by leaving **Caption** alone. ### Controls The collection of every control hosted by this form, indexable by control name or zero-based position. **Default property.** Read-only --- controls are added to the collection by the runtime, not by user code. The collection contains the form's menus, toolbars, status bars, and any aligned controls; MDI children are *not* members of this collection (they are independent top-level forms hosted in the MDI client area, accessible through [**ActiveForm**](#activeform) and the runtime's **Forms** collection). ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a form. Always **vbForm**. ### Count The number of controls in [**Controls**](#controls), as a **Long**. Read-only. Equivalent to `Me.Controls.Count`. ### DpiScaleFactorX The horizontal DPI scale factor of the monitor the form is currently on, as a **Double**. `1.0` at 96 DPI, `1.25` at 120 DPI, `1.5` at 144 DPI, and so on. Read-only. ### DpiScaleFactorY The vertical DPI scale factor of the monitor the form is currently on. Currently always equal to [**DpiScaleFactorX**](#dpiscalefactorx). Read-only. ### Enabled Determines whether the form accepts user input. A disabled MDI parent ignores keyboard and mouse input, dims its title bar, and disables every open MDI child. **Boolean**, default **True**. ### Height The form's outer height, in twips (or in the calling code's **ScaleMode** units). **Double**. Constrained at run time by [**MinHeight**](#minheight) and [**MaxHeight**](#maxheight) when those are non-zero. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the form has focus. ### hWnd The Win32 window handle for the MDI parent frame, as a **LongPtr**. Read-only. Useful for passing to API functions. The MDI client area is a separate child window with its own handle, accessible through Win32 calls only. ### Icon The icon shown on the title bar, in the taskbar, and in Alt-Tab. A **StdPicture** of type **vbPicTypeIcon**. Assigning a non-icon picture leaves the icon unchanged. ### Left The horizontal position of the form's outer rectangle, in twips (or the calling code's **ScaleMode** units), measured from the left edge of the screen. **Double**. ### LinkMode ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: ### LinkTopic ::: info Reserved for compatibility with VB6's DDE feature; not currently implemented in twinBASIC. ::: ### MaxHeight The maximum height of the form's *client area*, in twips. **Double**, default `0` (no limit). Honoured during interactive resizing. ### MaxWidth The maximum width of the form's *client area*, in twips. **Double**, default `0` (no limit). Honoured during interactive resizing. ### MinHeight The minimum height of the form's *client area*, in twips. **Double**, default `0` (no limit). Honoured during interactive resizing. ### MinWidth The minimum width of the form's *client area*, in twips. **Double**, default `0` (no limit). Honoured during interactive resizing. ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the form's frame or client area (and not over a child form's own surface). ### MousePointer The mouse cursor shown when the pointer is over the form's frame or client area. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Moveable Whether the user can drag the form by its title bar. **Boolean**, default **True**. ### Name The unique design-time name of the form. Read-only at run time. Also the class name of the generated form class. ### NegotiateToolbars ::: info Reserved for compatibility with VB6's ActiveX-document menu negotiation feature; not currently implemented in twinBASIC. ::: ### OLEDropMode How the form responds to OLE drops over its frame and client area. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on an MDIForm. ### Opacity The form's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Values below 100 cause the form to become a layered window; the open MDI children become translucent along with the parent. ### Picture A **StdPicture** drawn as the MDI client area's background. Painted over [**BackColor**](#backcolor), behind every MDI child. Bitmaps are drawn at their natural size from the upper-left corner; metafiles are stretched to fill the entire client area. Assigning **Nothing** removes the background. ### PictureDpiScaling When **True**, [**Picture**](#picture) is scaled by the current DPI factor before drawing. **Boolean**, default **False**. Has no effect on metafile pictures (they are stretched regardless). ### RightToLeft ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### ScaleHeight The height of the MDI *client area* (the inset region that hosts the children), in twips. **Double**, read-only --- assigning to it raises run-time error 383 (*'ScaleHeight' property is read-only*). ### ScaleWidth The width of the MDI *client area*, in twips. **Double**, read-only --- assigning to it raises run-time error 383. ### StartUpPosition How the form's initial position is determined the first time it is shown. A member of [**StartUpPositionConstants**](/en/official/Reference/VBRUN/Constants/StartUpPositionConstants): **vbStartUpManual**, **vbStartUpOwner**, **vbStartUpScreen**, or **vbStartUpWindowsDefault** (default). Read-only at run time --- set at design time. ### TabFocusAutoSelect When **True**, a [**TextBox**](/en/official/Reference/VB/TextBox/) on this form (or on any of its MDI children) whose own **TabFocusAutoSelect** is also **True** auto-selects its content when the focus enters it via the **TAB** key. **Boolean**, default **False**. ### Tag A free-form **String** the application can use to associate custom data with the form. Ignored by the framework. ### Top The vertical position of the form's outer rectangle, in twips (or the calling code's **ScaleMode** units), measured from the top edge of the screen. **Double**. ### TopMost Whether the form sits in the always-on-top z-order layer. **Boolean**, read-only at run time. Set at design time. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered form --- clicks pass through to whatever is underneath, and the corresponding pixels do not paint. Default `-1` disables the effect. ### Visible Whether the form is shown. **Boolean**, default **True**. Setting **Visible** to **True** when the form was hidden is equivalent to calling [**Show**](#show) **vbModeless**; setting it to **False** is equivalent to calling [**Hide**](#hide). MDI children remain bound to the parent regardless of visibility --- hiding the parent hides every child as well. ### WhatsThisHelp When **True**, [**WhatsThisMode**](#whatsthismode) enters Windows' "What's This?" cursor mode. **Boolean**, default **False**. The title-bar help-button feature is not available on an MDIForm. ### Width The form's outer width, in twips (or in the calling code's **ScaleMode** units). **Double**. Constrained at run time by [**MinWidth**](#minwidth) and [**MaxWidth**](#maxwidth) when those are non-zero. ### WindowState The window's normal/minimised/maximised state. A member of [**FormWindowStateConstants**](/en/official/Reference/VBRUN/Constants/FormWindowStateConstants): **vbNormal** (0, default), **vbMinimized** (1), or **vbMaximized** (2). Setting it at run time updates the window placement immediately if the form is visible. ## Methods ### Arrange Lays the open MDI children out in a single call. Syntax: *object*.**Arrange** *Arrangement* *Arrangement* : *required* A member of [**FormArrangeConstants**](/en/official/Reference/VBRUN/Constants/FormArrangeConstants): **vbCascade** (0), **vbTileHorizontal** (1), **vbTileVertical** (2), or **vbArrangeIcons** (3 --- line up the icons of minimised children along the bottom of the client area). Other values raise run-time error 5 (*Invalid procedure call or argument*). ### Close Initiates the form's unload sequence --- [**QueryUnload**](#queryunload), then [**Unload**](#unload), then [**Terminate**](#terminate) --- preceded by the same sequence on every open MDI child. Either of the first two events on either the parent or any child can cancel the close by setting *Cancel* to non-zero. Equivalent to the language statement `Unload Me`. Syntax: *object*.**Close** ### Hide Hides the form without unloading it. The class instance, its children, and its controls are preserved; calling [**Show**](#show) (or assigning [**Visible**](#visible) = **True**) brings it back. Equivalent to assigning **Visible** = **False**. Syntax: *object*.**Hide** ### Move Repositions and optionally resizes the form in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the form, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### PopUpMenu Displays a [**Menu**](/en/official/Reference/VB/Menu/) as a context-menu pop-up at the specified location. Syntax: *object*.**PopUpMenu** *Menu* \[, *Flags* \[, *X* \[, *Y* \[, *DefaultMenu* ] ] ] ] *Menu* : *required* The **Menu** control to display. The menu must already exist on the form. *Flags* : *optional* A combination of [**MenuControlConstants**](/en/official/Reference/VBRUN/Constants/MenuControlConstants) controlling alignment and which mouse buttons trigger the menu items. *X*, *Y* : *optional* The screen-relative position to anchor the menu at, in twips. Defaults to the current mouse position. *DefaultMenu* : *optional* The **Menu** sub-item to render in bold as the default action. ### SetFocus Activates the form. If an MDI child is open, focus moves to whichever control on that child last held it; otherwise focus moves to the parent's frame. Syntax: *object*.**SetFocus** ### Show Makes the form visible. Triggers [**Load**](#load) on the first call. Syntax: *object*.**Show** \[ *Modal* \[, *OwnerForm* ] ] *Modal* : *optional* A member of [**FormShowConstants**](/en/official/Reference/VBRUN/Constants/FormShowConstants): **vbModeless** (0, default --- the call returns immediately) or **vbModal** (1). MDI parents are normally shown modeless; modal display is accepted but unusual. *OwnerForm* : *optional* For modal shows, the form that is disabled while this form is up; defaults to the currently active form. ### ValidateControls Fires the **Validate** event of the currently active control on the active MDI child. If the handler sets *Cancel* to **True**, **ValidateControls** raises run-time error 380 (*Invalid property value*); the caller can wrap this with `On Error` to detect a failed validation. Syntax: *object*.**ValidateControls** ### WhatsThisMode Enters Windows' "What's This?" cursor mode --- the next click on a control raises that control's help instead of activating it. [**WhatsThisHelp**](#whatsthishelp) must be **True**. Syntax: *object*.**WhatsThisMode** ### ZOrder Brings the form to the front or back of the top-level z-order. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Activate Raised when the MDI parent or any of its child forms becomes the active window in the application --- typically right after [**Load**](#load) for the first show, and whenever activation returns to the MDI group from another window. Syntax: *object*\_**Activate**( ) ### Click Raised when the user single-clicks the MDI parent's frame area (i.e. the title bar's hit-test area or directly on the client-area background, with no MDI child covering the spot). Syntax: *object*\_**Click**( ) ### DblClick Raised when the user double-clicks the MDI parent's frame area. Syntax: *object*\_**DblClick**( ) ### Deactivate Raised when the MDI parent loses activation to another window outside the MDI group. Activation moving between the parent and its own children does not raise **Deactivate** on the parent. Syntax: *object*\_**Deactivate**( ) ### DPIChange Raised when the form moves to a monitor with a different DPI scale, *but only* when the application is per-monitor DPI aware (`PROCESS_PER_MONITOR_DPI_AWARE`). The event's *NewDPI* argument gives the new effective DPI; child controls and MDI children re-scale themselves automatically. New in twinBASIC. Syntax: *object*\_**DPIChange**( *NewDPI* **As Long** ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### Initialize Raised once, before the underlying window is created and before any of the form's child controls (or MDI children) exist. Useful for setting initial values on form-level fields. The form's controls cannot be referenced from this event. Syntax: *object*\_**Initialize**( ) ### LinkClose ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### LinkError ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### LinkExecute ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### LinkOpen ::: info Reserved for compatibility with VB6's DDE feature; not currently raised in twinBASIC. ::: ### Load Raised after the MDI parent's window and all aligned child controls (toolbars, status bars, menus) have been created, just before the form first appears on screen. The classic place to populate menus dynamically and perform any initialisation that needs the controls to exist. **Default event.** Syntax: *object*\_**Load**( ) ### MouseDown Raised when the user presses any mouse button over the MDI parent's client area (i.e. not over an MDI child). Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the MDI parent's client area. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the MDI parent's client area. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseWheel Raised when the mouse wheel turns over the MDI parent's client area. New in twinBASIC. Syntax: *object*\_**MouseWheel**( *Delta* **As Integer**, *Horizontal* **As Boolean** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### QueryUnload Raised before the form unloads, giving the application a chance to confirm or cancel the close. Setting *Cancel* to non-zero keeps the form (and all its open MDI children) open. When the MDI parent is closing, **QueryUnload** is raised on every open MDI child *before* it is raised on the parent --- any child cancelling stops the cascade. Syntax: *object*\_**QueryUnload**( *Cancel* **As Integer**, *UnloadMode* **As Integer** ) *Cancel* : Set to non-zero (any non-zero value, conventionally **1**) to cancel the close. *UnloadMode* : A member of [**QueryUnloadConstants**](/en/official/Reference/VBRUN/Constants/QueryUnloadConstants) identifying what triggered the close --- the close button, code, Windows shutdown, or the MDI parent closing. ### Resize Raised when the MDI parent is resized --- by the user, by code, by the OS following a [**WindowState**](#windowstate) change, or by initial layout during the first show. The event fires on the parent only; MDI children receive their own **Resize** events when the client-area resize cascades to them. Syntax: *object*\_**Resize**( ) ### Terminate Raised after the form's window has been destroyed and the class instance is about to be released. The controls and MDI children are no longer accessible at this point. Syntax: *object*\_**Terminate**( ) ### Unload Raised after [**QueryUnload**](#queryunload) approves and before the form's window is destroyed. Setting *Cancel* to non-zero keeps the form open and prevents the unload. Syntax: *object*\_**Unload**( *Cancel* **As Integer** ) *Cancel* : Set to non-zero (any non-zero value, conventionally **1**) to cancel the unload. --- --- url: /zh/official/Reference/VB/MDIForm.md --- # MDIForm 类 **MDIForm**是一个顶级Win32窗口,承载一个*MDI客户区*——一个凹陷的工作表面,其中出现一个或多个标记为MDI子窗体的[**Form**](/official/Reference/VB/Form/)实例,每个都在父窗口内有自己的标题栏。twinBASIC项目最多可包含一个MDI窗体。与普通[**Form**](/official/Reference/VB/Form/)不同,MDIForm没有绘图表面、没有字体属性、没有图形原语——它纯粹是其子窗体的框架,加上菜单、工具栏和(可选)绘制在子窗体后面的单个背景[**Picture**](#picture)的宿主。 默认属性是[**Controls**](#controls),默认事件是[**Load**](#load)。 ```vb ' 在MDIForm1的代码隐藏中: Private Sub MDIForm_Load() Caption = "Editor" AutoShowChildren = True End Sub Private Sub mnuWindowCascade_Click() Arrange vbCascade End Sub ' 在标记MDIChild = True的子窗体(Form1)中: Private Sub Form_Load() Caption = "Untitled" End Sub ' 在启动模块中: Sub Main() MDIForm1.Show Form1.Show ' 在MDIForm1的客户区内打开 End Sub ``` ## 生命周期 MDIForm从创建到销毁经历与普通[**Form**](/official/Reference/VB/Form/)相同的六个事件: | 事件 | 时机 | |----------------------------------|-------------------------------------------------------------------------------------| | [**Initialize**](#initialize) | 底层窗口存在之前。窗体的子窗体和控件尚不存在。 | | [**Load**](#load) | 窗口创建且子控件(工具栏带、状态栏、菜单)实例化后,窗体首次显示之前。 | | [**Activate**](#activate) | MDI父窗体或其某个子窗体变为活动窗口时。 | | [**Deactivate**](#deactivate) | 激活移动到MDI组外的另一个窗口时。 | | [**QueryUnload**](#queryunload) | 卸载之前。将*Cancel*设置为非零值保持窗体打开。关闭MDI父窗体时首先在每个打开的MDI子窗体上运行**QueryUnload**,然后在父窗体自身上运行。 | | [**Unload**](#unload) | **QueryUnload**批准后。将*Cancel*设置为非零值保持窗体打开。 | | [**Terminate**](#terminate) | 窗口销毁且类实例释放后。 | ## MDI子窗体 MDI子窗体是任何**MDIChild**属性为**True**(在设计时设置)的[**Form**](/official/Reference/VB/Form/)。显示或取消隐藏此类窗体会将其父级设为MDI客户区:其[**Left**](/official/Reference/VB/Form/#left)和[**Top**](/official/Reference/VB/Form/#top)变为相对于客户区左上角,其标题栏绘制在父窗口内部而非桌面上,最大化时其系统菜单和最小化/最大化按钮合并到父窗口的标题栏中。 [**ActiveForm**](#activeform)返回当前获得焦点的子窗体,无子窗体打开时返回**Nothing**。MDI父窗体上的[**Activate**](#activate)和[**Deactivate**](#deactivate)仅在激活跨过MDI组的外部边界时引发;激活在组*内部*移动时在受影响的子窗体上引发**Activate** / **Deactivate**。 [**AutoShowChildren**](#autoshowchildren)决定MDI子窗体类被加载但未显式显示时发生什么——当为**True**(默认)时,子窗体自动变为可见;当为**False**时,子窗体保持隐藏直到代码对其调用**Show**。 [**Arrange**](#arrange)在单次调用中布局打开的子窗体:层叠、水平平铺、垂直平铺或沿底部边缘排列最小化子窗体的图标。 ```vb mnuWindowCascade.Click => Me.Arrange vbCascade mnuWindowTileH.Click => Me.Arrange vbTileHorizontal mnuWindowTileV.Click => Me.Arrange vbTileVertical mnuWindowArrangeIcons.Click => Me.Arrange vbArrangeIcons ``` ## 窗口外观 MDIForm始终使用可调整大小的边框样式——没有[**BorderStyle**](/official/Reference/VB/Form/#borderstyle)属性,标题栏始终存在,系统菜单和最小化/最大化按钮始终显示,窗体始终出现在任务栏中。[**Caption**](#caption)设置标题栏文本。[**Icon**](#icon)提供系统菜单、任务栏和Alt-Tab使用的小/大图标。[**WindowState**](#windowstate)([**FormWindowStateConstants**](/official/Reference/VBRUN/Constants/FormWindowStateConstants))在运行时读取或设置正常/最小化/最大化状态。 [**MinWidth**](#minwidth)、[**MinHeight**](#minheight)、[**MaxWidth**](#maxwidth)和[**MaxHeight**](#maxheight)在交互式调整大小期间以缇为单位约束*客户区*。[**Moveable**](#moveable)决定用户是否可以通过标题栏拖动窗体。 [**Opacity**](#opacity)和[**TransparencyKey**](#transparencykey)启用Windows的分层窗口功能,用于半透明窗体和裁剪形状。 [**BackColor**](#backcolor)绘制MDI客户区的背景——默认为系统**vbApplicationWorkspace**颜色而非3D面色。[**Picture**](#picture)设置后绘制在**BackColor**之上作为客户区背景,元文件缩放以填充区域,位图以其自然大小居中。[**PictureDpiScaling**](#picturedpiscaling)在绘制前按当前DPI因子缩放位图。MDIForm上没有屏幕绘图API——在MDIForm上调用**Form**接口的[**Cls**](/official/Reference/VB/Form/#cls)、[**Circle**](/official/Reference/VB/Form/#circle)、[**Line**](/official/Reference/VB/Form/#line)、[**PSet**](/official/Reference/VB/Form/#pset)、[**PaintPicture**](/official/Reference/VB/Form/#paintpicture)和**Print**成员会引发运行时错误438(*Object doesn't support this property or method*)。 当MDI子窗体被移动或调整大小使其矩形超出可见客户区时,垂直和水平滚动条自动出现;这通过MDI父窗体的**ScrollBars**属性在设计时固定,运行时不公开。 ## 菜单和弹出菜单 在窗体设计时设计的菜单结构自动出现在MDIForm的标题栏中。当MDI子窗体最大化时,子窗体自己的菜单(如果有)合并到父窗体的菜单栏中,在子窗体保持最大化期间替换父菜单。经典的VB6*窗口列表*功能——列出每个打开的MDI子窗体以便快速切换的菜单子树——在MDIForm上的[**Menu**](/official/Reference/VB/Menu/)设置了**WindowList**属性时自动支持。 [**PopUpMenu**](#popupmenu)在指定位置将窗体的某个菜单显示为上下文菜单弹出窗口,当用户选择项目时引发菜单的**Click**事件。 ```vb Private Sub MDIForm_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) If Button = vbRightButton Then PopUpMenu mnuContext End Sub ``` ## 与Form的区别 由于MDIForm是框架而非绘图表面,**Form**接口的以下成员在其上*不受支持*——访问它们会引发运行时错误380(属性)或438(方法): | 类别 | 成员 | |------------------------------|--------------------------------------------------------------------------------------| | 绘图 | **AutoRedraw**、**ClipControls**、**HasDC**、**hDC**、**Image**、**CurrentX**、**CurrentY**、**DrawMode**、**DrawStyle**、**DrawWidth**、**FillColor**、**FillStyle**、**ForeColor**、**FontTransparent**、**Cls**、**Circle**、**Line**、**PSet**、**PaintPicture** | | 字体 | **Font**、**FontName**、**FontSize**、**FontBold**、**FontItalic**、**FontStrikethru**、**FontUnderline**、**TextWidth** | | 几何 | **ScaleLeft**、**ScaleTop**、**ScaleMode**、**Scale**、**ScaleX**、**ScaleY**([**ScaleWidth**](#scalewidth)和[**ScaleHeight**](#scaleheight)受支持但只读) | | 窗口装饰 | **BorderStyle**、**ControlBox**、**MaxButton**、**MinButton**、**ShowInTaskbar**、**WhatsThisButton** | | 其他 | **KeyPreview**(且[**Form**](/official/Reference/VB/Form/)的**KeyDown** / **KeyUp** / **KeyPress**事件在**MDIForm**上不存在)、**MDIChild**、**NegotiateMenus**、**Palette**、**PaletteMode**、**PrintForm**、**Point**、**Refresh**(在MDIForm上引发438,尽管在普通Form上正常工作) | | 行为特殊 | **TextHeight**返回`0`而非引发错误。(保留VB6错误以兼容。) | ## 属性 ### ActiveControl 活动MDI子窗体上当前拥有输入焦点的控件,类型为**Control**对象,无子窗体获得焦点时为**Nothing**。只读。 ### ActiveForm 当前活动的MDI子窗体,类型为**Object**,无子窗体打开时为**Nothing**。只读。每次激活在子窗体之间移动时更新,就在子窗体上相应的[**Activate**](#activate)和[**Deactivate**](#deactivate)事件引发之前。 ### AlwaysShowKeyboardCues 当为**True**时,窗体始终在[**Caption**](#caption)和菜单项的访问键字符上显示下划线,而非仅在用户按**Alt**后显示。**Boolean**,运行时只读。在设计时设置。 ### Appearance [**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。 ::: info 保留用于VB6兼容;此属性在MDI窗体上无可观察效果。 ::: ### AutoShowChildren 当为**True**(默认)时,加载MDI子窗体类也会显示它;当为**False**时,子窗体类可加载到内存中而不变为可见,直到代码对其调用**Show**。**Boolean**。 ### BackColor MDI客户区中绘制的颜色,类型为**OLE\_COLOR**。默认为系统**vbApplicationWorkspace**颜色。用作[**Picture**](#picture)和每个MDI子窗体标题栏及外边框后面的画布。 ### Caption 标题栏文本。**String**。 语法:*object*.**Caption** \[ = *string* ] 当MDI子窗体最大化时,Windows用方括号中的子窗体标题装饰**Caption**——`Editor - [Untitled]`——应用程序通常通过不修改**Caption**来让装饰保持自动。 ### Controls 此窗体承载的每个控件的集合,可按控件名称或从零开始的位置索引。**默认属性。**只读——控件由运行时添加到集合中,而非用户代码。集合包含窗体的菜单、工具栏、状态栏和任何对齐控件;MDI子窗体*不是*此集合的成员(它们是托管在MDI客户区中的独立顶级窗体,可通过[**ActiveForm**](#activeform)和运行时的**Forms**集合访问)。 ### ControlType 只读的[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值,将此控件标识为窗体。始终为**vbForm**。 ### Count [**Controls**](#controls)中的控件数,类型为**Long**。只读。等同于`Me.Controls.Count`。 ### DpiScaleFactorX 窗体当前所在显示器的水平DPI缩放因子,类型为**Double**。96 DPI时为`1.0`,120 DPI时为`1.25`,144 DPI时为`1.5`,以此类推。只读。 ### DpiScaleFactorY 窗体当前所在显示器的垂直DPI缩放因子。当前始终等于[**DpiScaleFactorX**](#dpiscalefactorx)。只读。 ### Enabled 确定窗体是否接受用户输入。禁用的MDI父窗体忽略键盘和鼠标输入,标题栏变暗,并禁用每个打开的MDI子窗体。**Boolean**,默认**True**。 ### Height 窗体的外部高度,以缇为单位(或使用调用代码的**ScaleMode**单位)。**Double**。运行时受[**MinHeight**](#minheight)和[**MaxHeight**](#maxheight)约束(当它们非零时)。 ### HelpContextID 标识应用程序帮助文件中主题的**Long**值,当用户在窗体具有焦点时按**F1**时检索。 ### hWnd MDI父框架的Win32窗口句柄,类型为**LongPtr**。只读。可用于传递给API函数。MDI客户区是一个单独的子窗口,有自己的句柄,只能通过Win32调用访问。 ### Icon 标题栏、任务栏和Alt-Tab中显示的图标。**vbPicTypeIcon**类型的**StdPicture**。赋值非图标图片会使图标保持不变。 ### Left 窗体外部矩形的水平位置,以缇为单位(或使用调用代码的**ScaleMode**单位),从屏幕左边缘测量。**Double**。 ### LinkMode ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中未实现。 ::: ### LinkTopic ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中未实现。 ::: ### MaxHeight 窗体*客户区*的最大高度,以缇为单位。**Double**,默认`0`(无限制)。在交互式调整大小时遵守。 ### MaxWidth 窗体*客户区*的最大宽度,以缇为单位。**Double**,默认`0`(无限制)。在交互式调整大小时遵守。 ### MinHeight 窗体*客户区*的最小高度,以缇为单位。**Double**,默认`0`(无限制)。在交互式调整大小时遵守。 ### MinWidth 窗体*客户区*的最小宽度,以缇为单位。**Double**,默认`0`(无限制)。在交互式调整大小时遵守。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针位于窗体框架或客户区(而非子窗体自身表面)上时用作鼠标光标的**StdPicture**。 ### MousePointer 指针位于窗体框架或客户区上时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Moveable 用户是否可以通过标题栏拖动窗体。**Boolean**,默认**True**。 ### Name 窗体的唯一设计时名称。运行时只读。也是生成的窗体类的类名。 ### NegotiateToolbars ::: info 保留用于与VB6的ActiveX文档菜单协商功能兼容;目前在twinBASIC中未实现。 ::: ### OLEDropMode 窗体如何响应其框架和客户区上的OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**或**vbOLEDropManual**。MDIForm不支持自动放置模式。 ### Opacity 窗体的不透明度百分比(0--100,默认100)。超出范围的值在**Initialize**时被钳制。低于100的值会使窗体变为分层窗口;打开的MDI子窗体随父窗体一起变为半透明。 ### Picture 作为MDI客户区背景绘制的**StdPicture**。绘制在[**BackColor**](#backcolor)之上,每个MDI子窗体之后。位图从左上角以其自然大小绘制;元文件拉伸以填充整个客户区。赋值**Nothing**移除背景。 ### PictureDpiScaling 当为**True**时,[**Picture**](#picture)在绘制前按当前DPI因子缩放。**Boolean**,默认**False**。对元文件图片无效(它们始终拉伸)。 ### RightToLeft ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: ### ScaleHeight MDI*客户区*的高度(承载子窗体的凹陷区域),以缇为单位。**Double**,只读——赋值会引发运行时错误383(*'ScaleHeight' property is read-only*)。 ### ScaleWidth MDI*客户区*的宽度,以缇为单位。**Double**,只读——赋值会引发运行时错误383。 ### StartUpPosition 窗体首次显示时其初始位置的确定方式。[**StartUpPositionConstants**](/official/Reference/VBRUN/Constants/StartUpPositionConstants)的成员:**vbStartUpManual**、**vbStartUpOwner**、**vbStartUpScreen**或**vbStartUpWindowsDefault**(默认)。运行时只读——在设计时设置。 ### TabFocusAutoSelect 当为**True**时,此窗体(或其任何MDI子窗体)上自身**TabFocusAutoSelect**也为**True**的[**TextBox**](/official/Reference/VB/TextBox/)在焦点通过**TAB**键进入时自动选择其内容。**Boolean**,默认**False**。 ### Tag 应用程序可用于将自定义数据与窗体关联的自由格式**String**。框架忽略此属性。 ### Top 窗体外部矩形的垂直位置,以缇为单位(或使用调用代码的**ScaleMode**单位),从屏幕上边缘测量。**Double**。 ### TopMost 窗体是否位于始终置顶的Z顺序层。**Boolean**,运行时只读。在设计时设置。 ### TransparencyKey 一个**OLE\_COLOR**值,设置后在渲染的窗体中变为完全透明——点击穿透到下方的内容,对应像素不绘制。默认`-1`禁用此效果。 ### Visible 窗体是否显示。**Boolean**,默认**True**。当窗体隐藏时设置**Visible**为**True**等同于调用[**Show**](#show) **vbModeless**;设置为**False**等同于调用[**Hide**](#hide)。MDI子窗体无论可见性如何都绑定到父窗体——隐藏父窗体也会隐藏所有子窗体。 ### WhatsThisHelp 当为**True**时,[**WhatsThisMode**](#whatsthismode)进入Windows的"这是什么?"光标模式。**Boolean**,默认**False**。标题栏帮助按钮功能在MDIForm上不可用。 ### Width 窗体的外部宽度,以缇为单位(或使用调用代码的**ScaleMode**单位)。**Double**。运行时受[**MinWidth**](#minwidth)和[**MaxWidth**](#maxwidth)约束(当它们非零时)。 ### WindowState 窗口的正常/最小化/最大化状态。[**FormWindowStateConstants**](/official/Reference/VBRUN/Constants/FormWindowStateConstants)的成员:**vbNormal** (0,默认)、**vbMinimized** (1)或**vbMaximized** (2)。在运行时设置时,如果窗体可见则立即更新窗口位置。 ## 方法 ### Arrange 在单次调用中布局打开的MDI子窗体。 语法:*object*.**Arrange** *Arrangement* *Arrangement* : *必需* [**FormArrangeConstants**](/official/Reference/VBRUN/Constants/FormArrangeConstants)的成员:**vbCascade** (0)、**vbTileHorizontal** (1)、**vbTileVertical** (2)或**vbArrangeIcons** (3——沿客户区底部排列最小化子窗体的图标)。其他值引发运行时错误5(*Invalid procedure call or argument*)。 ### Close 启动窗体的卸载序列——[**QueryUnload**](#queryunload),然后[**Unload**](#unload),然后[**Terminate**](#terminate)——在之前对每个打开的MDI子窗体执行相同序列。父窗体或任何子窗体上前两个事件中的任何一个都可以通过将*Cancel*设置为非零值来取消关闭。等同于语言语句`Unload Me`。 语法:*object*.**Close** ### Hide 隐藏窗体而不卸载。类实例、其子窗体和控件被保留;调用[**Show**](#show)(或赋值[**Visible**](#visible) = **True**)将其带回。等同于赋值**Visible** = **False**。 语法:*object*.**Hide** ### Move 在单次调用中重新定位并可选地调整窗体大小。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**值。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从窗体发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### PopUpMenu 在指定位置将[**Menu**](/official/Reference/VB/Menu/)显示为上下文菜单弹出窗口。 语法:*object*.**PopUpMenu** *Menu* \[, *Flags* \[, *X* \[, *Y* \[, *DefaultMenu* ] ] ] ] *Menu* : *必需* 要显示的**Menu**控件。菜单必须已存在于窗体上。 *Flags* : *可选* [**MenuControlConstants**](/official/Reference/VBRUN/Constants/MenuControlConstants)的组合,控制对齐和哪些鼠标按钮触发菜单项。 *X*, *Y* : *可选* 锚定菜单的屏幕相对位置,以缇为单位。默认为当前鼠标位置。 *DefaultMenu* : *可选* 以粗体渲染为默认操作的**Menu**子项。 ### SetFocus 激活窗体。如果MDI子窗体打开,焦点移到该子窗体上最后持有焦点的控件;否则焦点移到父窗体的框架。 语法:*object*.**SetFocus** ### Show 使窗体可见。首次调用时触发[**Load**](#load)。 语法:*object*.**Show** \[ *Modal* \[, *OwnerForm* ] ] *Modal* : *可选* [**FormShowConstants**](/official/Reference/VBRUN/Constants/FormShowConstants)的成员:**vbModeless** (0,默认——调用立即返回)或**vbModal** (1)。MDI父窗体通常以无模式方式显示;模态显示被接受但不常见。 *OwnerForm* : *可选* 对于模态显示,此窗体打开时被禁用的窗体;默认为当前活动窗体。 ### ValidateControls 在活动MDI子窗体上引发当前活动控件的**Validate**事件。如果处理程序将*Cancel*设置为**True**,**ValidateControls**会引发运行时错误380(*Invalid property value*);调用者可以用`On Error`包装以检测验证失败。 语法:*object*.**ValidateControls** ### WhatsThisMode 进入Windows的"这是什么?"光标模式——下一次点击控件会引发该控件的帮助而非激活它。[**WhatsThisHelp**](#whatsthishelp)必须为**True**。 语法:*object*.**WhatsThisMode** ### ZOrder 将窗体置于顶级Z顺序的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront** (0,默认)或**vbSendToBack** (1)。 ## 事件 ### Activate 当MDI父窗体或其任何子窗体成为应用程序中的活动窗口时引发——通常在首次显示后[**Load**](#load)之后,以及每当激活从另一个窗口返回到MDI组时。 语法:*object*\_**Activate**( ) ### Click 用户单击MDI父窗体的框架区域(即标题栏点击测试区域或直接在客户区背景上,没有MDI子窗体覆盖的位置)时引发。 语法:*object*\_**Click**( ) ### DblClick 用户双击MDI父窗体的框架区域时引发。 语法:*object*\_**DblClick**( ) ### Deactivate 当MDI父窗体的激活移动到MDI组外的另一个窗口时引发。激活在父窗体与其自身子窗体之间移动不会在父窗体上引发**Deactivate**。 语法:*object*\_**Deactivate**( ) ### DPIChange 当窗体移动到具有不同DPI比例的显示器时引发,*但仅当*应用程序是每显示器DPI感知的(`PROCESS_PER_MONITOR_DPI_AWARE`)。事件的*NewDPI*参数给出新的有效DPI;子控件和MDI子窗体自动重新缩放。twinBASIC新增。 语法:*object*\_**DPIChange**( *NewDPI* **As Long** ) ### DragDrop 手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### Initialize 在底层窗口创建之前且窗体的任何子控件(或MDI子窗体)存在之前引发一次。用于设置窗体级字段的初始值。不能从此事件引用窗体的控件。 语法:*object*\_**Initialize**( ) ### LinkClose ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中不会引发。 ::: ### LinkError ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中不会引发。 ::: ### LinkExecute ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中不会引发。 ::: ### LinkOpen ::: info 保留用于与VB6的DDE功能兼容;目前在twinBASIC中不会引发。 ::: ### Load 在MDI父窗体的窗口和所有对齐子控件(工具栏、状态栏、菜单)创建后,窗体首次出现在屏幕上之前引发。动态填充菜单和执行需要控件存在的任何初始化的经典位置。**默认事件。** 语法:*object*\_**Load**( ) ### MouseDown 用户在MDI父窗体的客户区(即非MDI子窗体上方)按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 光标在MDI父窗体的客户区上移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 用户在MDI父窗体的客户区上释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseWheel 鼠标滚轮在MDI父窗体的客户区上滚动时引发。twinBASIC新增。 语法:*object*\_**MouseWheel**( *Delta* **As Integer**, *Horizontal* **As Boolean** ) ### OLECompleteDrag OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 用户将数据放置到目标控件上时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的数据格式时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### QueryUnload 在窗体卸载之前引发,给应用程序确认或取消关闭的机会。将*Cancel*设置为非零值保持窗体(及所有打开的MDI子窗体)打开。当MDI父窗体关闭时,**QueryUnload**在每个打开的MDI子窗体上引发*之后*才在父窗体上引发——任何子窗体取消都会停止级联。 语法:*object*\_**QueryUnload**( *Cancel* **As Integer**, *UnloadMode* **As Integer** ) *Cancel* : 设置为非零值(任何非零值,约定为**1**)以取消关闭。 *UnloadMode* : [**QueryUnloadConstants**](/official/Reference/VBRUN/Constants/QueryUnloadConstants)的成员,标识触发关闭的原因——关闭按钮、代码、Windows关机或MDI父窗体关闭。 ### Resize 当MDI父窗体调整大小时引发——由用户、代码、操作系统在[**WindowState**](#windowstate)更改后或首次显示时的初始布局。事件仅在父窗体上引发;当客户区调整大小级联到MDI子窗体时,子窗体接收自己的**Resize**事件。 语法:*object*\_**Resize**( ) ### Terminate 在窗体的窗口销毁且类实例即将释放后引发。此时控件和MDI子窗体不再可访问。 语法:*object*\_**Terminate**( ) ### Unload 在[**QueryUnload**](#queryunload)批准后且窗体窗口销毁之前引发。将*Cancel*设置为非零值保持窗体打开并阻止卸载。 语法:*object*\_**Unload**( *Cancel* **As Integer** ) *Cancel* : 设置为非零值(任何非零值,约定为**1**)以取消卸载。 --- --- url: /en/official/IDE/Memory.md --- # Memory ![Memory](Images/Memory.png "Memory") The Memory pane displays the raw contents of process memory during a paused debugging session, with addresses in the left column and byte values on the right. It is useful for inspecting data structures at the byte level. --- --- url: /en/official/IDE/Menu.md --- # Menu ![Menu](Images/Menu.png "Menu") --- --- url: /en/official/Reference/VB/Menu.md --- # Menu class A **Menu** is an item in a Win32 native menu --- either a top-level entry on a [**Form**](/en/official/Reference/VB/Form/)'s or [**MDIForm**](/en/official/Reference/VB/MDIForm/)'s menu bar, an entry in a drop-down sub-menu, or a separator bar between groups of related commands. Menus are a non-windowed control: they have no [**Left**](#) / [**Top**](#) / [**Width**](#) / [**Height**](#), no font, and no mouse or keyboard events of their own --- they are populated, structured, and bound to handlers at design time through the form's menu editor. The default property is [**Enabled**](#enabled) and the default event is [**Click**](#click). ```vb Private Sub Form_Load() mnuFileSave.Enabled = False ' grey out until there is something to save End Sub Private Sub mnuFileSave_Click() SaveDocument End Sub Private Sub mnuViewToolbar_Click() mnuViewToolbar.Checked = Not mnuViewToolbar.Checked Toolbar1.Visible = mnuViewToolbar.Checked End Sub ``` ## Caption and separators [**Caption**](#caption) supplies the text drawn for the menu item. Two Caption values have special meaning: * An ampersand (`&`) marks the next character as a keyboard mnemonic --- pressing **Alt + that letter** while the menu is open invokes the item, and the letter is underlined in the rendered menu. Use `&&` to display a literal ampersand. * A Caption consisting of a single hyphen (`"-"`) renders the item as a horizontal separator bar between the surrounding entries. Separator items still receive their own [**Click**](#click) events if invoked programmatically, but the user cannot reach them with the keyboard or mouse. ```vb mnuFileNew.Caption = "&New" ' Alt+N while File is open mnuFileSep1.Caption = "-" ' separator bar mnuFileSaveAs.Caption = "Save &As..." ' Alt+A ``` ## Shortcut keys [**ShortcutId**](#shortcutid) binds a keyboard accelerator to the menu item. It is typed as [**ShortcutConstants**](/en/official/Reference/VBRUN/Constants/ShortcutConstants) --- **vbShortcutNone** disables the accelerator, **vbShortcutCtrlS** binds **Ctrl+S**, and so on across the function-key, **Shift+**, and **Ctrl+** ranges. When set, the Win32 runtime appends the corresponding text after a tab character in the rendered Caption --- `Save\tCtrl+S` --- so the shortcut appears right-aligned in the menu, the conventional way. ```vb mnuFileSave.ShortcutId = vbShortcutCtrlS mnuFilePrint.ShortcutId = vbShortcutCtrlP ``` ::: info The hidden [**Shortcut**](#shortcut) **String** property exists only to round-trip the raw text imported from VB6 `.frm` files; it is not consulted at run time. New code should use [**ShortcutId**](#shortcutid). ::: ## Menu icons twinBASIC extends the classic VB6 menu with optional 16×16 (or arbitrary-sized) icons drawn beside the caption. Assign a **StdPicture** to [**Picture**](#picture) and the bitmap is rendered to the left of the caption text. When the supplied picture is a multi-resolution `.ico`, [**IconSizeX**](#iconsizex) and [**IconSizeY**](#iconsizey) pick which embedded image to use; left at `0` (the default), the picture is loaded at its natural size. ```vb Set mnuFileSave.Picture = LoadResPicture("MNU_SAVE", vbResBitmap) mnuFileSave.IconSizeX = 16 mnuFileSave.IconSizeY = 16 ``` ## Control arrays A control array of menus is the standard way to build a *most-recently-used* file list, a dynamic *Window* sub-menu, or a list of plug-in commands. The array is declared at design time on the first item; further items are added at run time with **Load** and removed with **Unload**, exactly as for a windowed control. Inside a [**Click**](#click) handler shared by every item in the array, [**Index**](#index) identifies which one was picked. ```vb Private Sub mnuRecent_Click(Index As Integer) OpenDocument mnuRecent(Index).Tag ' Tag holds the file path End Sub ``` [**Index**](#index) raises run-time error 343 (*Object not an array*) when read on a menu that is not part of a control array. ## Window list (MDI) When the form hosting the menu is an [**MDIForm**](/en/official/Reference/VB/MDIForm/), setting [**WindowList**](#windowlist) to **True** at design time turns this menu into the application's *Window* sub-menu --- the runtime auto-populates it with one entry per open MDI child, marks the active child with a checkmark, and routes a click on any of those entries to **SetFocus** on the corresponding child. The application typically combines this with an explicit *Cascade* / *Tile* sub-menu that calls [**Arrange**](/en/official/Reference/VB/MDIForm/#arrange) on the parent. ## Properties ### Caption The text drawn for the menu item. **String**. An ampersand marks the next character as a mnemonic; `&&` produces a literal ampersand. A Caption of `"-"` renders the item as a horizontal separator. Assignments are reflected immediately in any visible menu bar or pop-up. Syntax: *object*.**Caption** \[ = *string* ] ### Checked Whether a checkmark is drawn next to the item. **Boolean**, default **False**. Setting it on a top-level (menu-bar) item is supported but visually unusual; the conventional use is on drop-down items that toggle a setting. Syntax: *object*.**Checked** \[ = *boolean* ] ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as a menu. Always **vbMenuControl**. ### Enabled Whether the user can pick the item. A disabled menu item is drawn greyed out and ignores mouse and keyboard activation, including its [**ShortcutId**](#shortcutid) accelerator. **Boolean**, default **True**. **Default property.** Syntax: *object*.**Enabled** \[ = *boolean* ] Disabling a top-level menu-bar item disables its entire drop-down. The runtime rebuilds the menu state when **Enabled** changes, so the change is visible immediately. ### HelpContextID ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A **Long** that, in VB6, identified a topic in the application's help file shown when the user pressed **F1** with the menu item highlighted. ### IconSizeX When [**Picture**](#picture) is a multi-resolution `.ico`, the horizontal size in pixels of the embedded image to load. **Long**, default `0` (use the picture's natural size). Pair with [**IconSizeY**](#iconsizey). ### IconSizeY The vertical counterpart to [**IconSizeX**](#iconsizex). **Long**, default `0`. ### Index When the menu is part of a control array, the **Long** zero-based index of this instance within the array. Read-only at run time. Raises run-time error 343 (*Object not an array*) on a menu that is not part of an array. ### Name The unique design-time name of the menu on its parent form. **String**, read-only at run time. Inherited from the base control class. ### NegotiatePosition ::: info Reserved for compatibility with VB6's ActiveX-document menu negotiation feature; not currently implemented in twinBASIC. ::: Typed as [**NegotiatePositionConstants**](/en/official/Reference/VBRUN/Constants/NegotiatePositionConstants) (**vbNoNegotiate**, **vbLeft**, **vbMiddle**, **vbRight**) --- VB6 used this to decide where a top-level menu should appear in the host application's menu bar when an ActiveX document was activated. ### Parent A reference to the [**Form**](/en/official/Reference/VB/Form/) (or [**MDIForm**](/en/official/Reference/VB/MDIForm/) / **UserControl**) that contains this menu. Read-only. ### Picture A **StdPicture** drawn to the left of the caption. **twinBASIC extension** --- VB6 menus could not display icons. Assigning **Nothing** removes the icon. Icons are converted to bitmaps internally; pass a bitmap directly to skip the conversion. Pair with [**IconSizeX**](#iconsizex) / [**IconSizeY**](#iconsizey) for multi-resolution `.ico` files. Syntax: * *object*.**Picture** \[ = *picture* ] * **Set** *object*.**Picture** = *picture* ### Shortcut ::: info Hidden, read-only, and unused at run time --- exists only to round-trip the raw shortcut text imported from VB6 `.frm` files. Use [**ShortcutId**](#shortcutid) to bind an accelerator. ::: ### ShortcutId The keyboard accelerator bound to this menu item. A member of [**ShortcutConstants**](/en/official/Reference/VBRUN/Constants/ShortcutConstants) --- **vbShortcutNone** (no accelerator, default), **vbShortcutCtrlA** through **vbShortcutCtrlZ**, **vbShortcutF1** through **vbShortcutF12**, and the **Shift+**, **Ctrl+**, and **Shift+Ctrl+** function-key variants. When set, the matching shortcut text is appended to [**Caption**](#caption) (after a tab) when the menu is rendered. Syntax: *object*.**ShortcutId** \[ = *value* ] ### Tag A free-form **String** the application can use to associate custom data with the menu item. Ignored by the framework. Inherited from the base control class. Useful for control arrays --- e.g. holding the file path that an MRU-list entry should open. ### Visible Whether the menu item is shown. **Boolean**, default **True**. Setting it to **False** removes the entry from the menu without unloading it; setting it back to **True** restores it in its original position. Hiding a top-level menu-bar item rebuilds the menu bar so the surrounding items close the gap. Syntax: *object*.**Visible** \[ = *boolean* ] ### WindowList When **True** on a menu hosted by an [**MDIForm**](/en/official/Reference/VB/MDIForm/), turns this menu into the application's *Window* sub-menu --- the runtime auto-populates it with one entry per open MDI child and routes the resulting click to **SetFocus** on the corresponding child. **Boolean**, read-only at run time --- set at design time. At most one menu per MDI form should have **WindowList** set. ## Methods ### Container Returns a reference to the **Control** that hosts this menu --- typically the [**Form**](/en/official/Reference/VB/Form/) or [**MDIForm**](/en/official/Reference/VB/MDIForm/) that owns the menu structure. Equivalent to traversing [**Parent**](#parent) for a top-level menu, but defined on every menu (including sub-items) so it can be called uniformly. Syntax: *object*.**Container** ## Events ### Click Raised when the user picks the menu item --- by clicking it, pressing its mnemonic while the menu is open, or pressing its [**ShortcutId**](#shortcutid) accelerator. Also raised when [**PopUpMenu**](/en/official/Reference/VB/Form/#popupmenu) selects an item. **Default event.** Syntax: *object*\_**Click**( ) For a menu that is part of a control array, the handler receives the array [**Index**](#index) of the picked item: Syntax: *object*\_**Click**( *Index* **As Integer** ) --- --- url: /zh/official/Reference/VB/Menu.md --- # Menu 类 **Menu**是Win32原生菜单中的项目——可以是[**Form**](/official/Reference/VB/Form/)或[**MDIForm**](/official/Reference/VB/MDIForm/)菜单栏上的顶级条目、下拉子菜单中的条目,或相关命令组之间的分隔条。菜单是非窗口化控件:它们没有[**Left**](#) / [**Top**](#) / [**Width**](#) / [**Height**](#),没有字体,也没有自己的鼠标或键盘事件——它们在设计时通过窗体的菜单编辑器进行填充、结构化和绑定到处理程序。 默认属性是[**Enabled**](#enabled),默认事件是[**Click**](#click)。 ```vb Private Sub Form_Load() mnuFileSave.Enabled = False ' grey out until there is something to save End Sub Private Sub mnuFileSave_Click() SaveDocument End Sub Private Sub mnuViewToolbar_Click() mnuViewToolbar.Checked = Not mnuViewToolbar.Checked Toolbar1.Visible = mnuViewToolbar.Checked End Sub ``` ## 标题和分隔符 [**Caption**](#caption)提供为菜单项绘制的文本。两个Caption值具有特殊含义: * 和号(`&`)将下一个字符标记为键盘助记符——在菜单打开时按**Alt + 该字母**可调用该项目,该字母在渲染菜单中会加下划线显示。使用`&&`可显示字面和号。 * 由单个连字符(`"-"`)组成的Caption将项目渲染为周围条目之间的水平分隔条。分隔项被程序化调用时仍会收到自己的[**Click**](#click)事件,但用户无法通过键盘或鼠标到达。 ```vb mnuFileNew.Caption = "&New" ' Alt+N while File is open mnuFileSep1.Caption = "-" ' separator bar mnuFileSaveAs.Caption = "Save &As..." ' Alt+A ``` ## 快捷键 [**ShortcutId**](#shortcutid)将键盘加速键绑定到菜单项。其类型为[**ShortcutConstants**](/official/Reference/VBRUN/Constants/ShortcutConstants)——**vbShortcutNone**禁用加速键,**vbShortcutCtrlS**绑定**Ctrl+S**,依此类推涵盖功能键、\*\*Shift+**和**Ctrl+\*\*范围。设置后,Win32运行时会在渲染的Caption中的制表符后附加相应文本——`Save\tCtrl+S`——使快捷键以常规方式右对齐显示在菜单中。 ```vb mnuFileSave.ShortcutId = vbShortcutCtrlS mnuFilePrint.ShortcutId = vbShortcutCtrlP ``` ::: info 隐藏的[**Shortcut**](#shortcut)**String**属性仅用于往返导入自VB6 `.frm`文件的原始文本;运行时不使用它。新代码应使用[**ShortcutId**](#shortcutid)。 ::: ## 菜单图标 twinBASIC扩展了经典VB6菜单,支持在标题旁绘制可选的16×16(或任意尺寸)图标。将**StdPicture**赋值给[**Picture**](#picture),位图将渲染在标题文本的左侧。当提供的图片是多分辨率`.ico`时,[**IconSizeX**](#iconsizex)和[**IconSizeY**](#iconsizey)选择要使用的嵌入图像;保持为`0`(默认),图片以自然尺寸加载。 ```vb Set mnuFileSave.Picture = LoadResPicture("MNU_SAVE", vbResBitmap) mnuFileSave.IconSizeX = 16 mnuFileSave.IconSizeY = 16 ``` ## 控件数组 菜单的控件数组是构建*最近使用*文件列表、动态*窗口*子菜单或插件命令列表的标准方式。数组在设计时在第一个项目上声明;其他项目在运行时用**Load**添加、用**Unload**移除,与窗口化控件完全相同。在数组中所有项目共享的[**Click**](#click)处理程序内部,[**Index**](#index)标识被选中的项。 ```vb Private Sub mnuRecent_Click(Index As Integer) OpenDocument mnuRecent(Index).Tag ' Tag holds the file path End Sub ``` [**Index**](#index)在非控件数组的菜单上读取时会引发运行时错误343(*对象不是数组*)。 ## 窗口列表(MDI) 当承载菜单的窗体是[**MDIForm**](/official/Reference/VB/MDIForm/)时,在设计时将[**WindowList**](#windowlist)设为**True**可将此菜单变为应用程序的*窗口*子菜单——运行时自动为每个打开的MDI子窗体填充一个条目,用复选标记标记活动子窗体,并将点击其中任一条路由到相应子窗体的**SetFocus**。应用程序通常将此与显式的*层叠*/*平铺*子菜单组合使用,后者调用父窗体的[**Arrange**](/official/Reference/VB/MDIForm/#arrange)。 ## 属性 ### Caption 为菜单项绘制的文本。**String**。和号将下一个字符标记为助记符;`&&`产生字面和号。Caption为`"-"`将项目渲染为水平分隔符。赋值会立即反映在任何可见的菜单栏或弹出菜单中。 语法:*object*.**Caption** \[ = *string* ] ### Checked 是否在项目旁边绘制复选标记。**Boolean**,默认**False**。在顶级(菜单栏)项目上设置是支持的但在视觉上较少见;常规用法是在切换设置的下拉菜单项上。 语法:*object*.**Checked** \[ = *boolean* ] ### ControlType 只读[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值,将此控件标识为菜单。始终为**vbMenuControl**。 ### Enabled 用户是否可以选择该项目。禁用的菜单项以灰色绘制,忽略鼠标和键盘激活,包括其[**ShortcutId**](#shortcutid)加速键。**Boolean**,默认**True**。**默认属性。** 语法:*object*.**Enabled** \[ = *boolean* ] 禁用顶级菜单栏项目会禁用其整个下拉菜单。**Enabled**更改时运行时会重建菜单状态,因此更改会立即可见。 ### HelpContextID ::: info 保留用于VB6兼容;目前在twinBASIC中尚未实现。 ::: 一个**Long**,在VB6中标识当用户在菜单项高亮时按**F1**时显示的应用程序帮助文件中的主题。 ### IconSizeX 当[**Picture**](#picture)是多分辨率`.ico`时,要加载的嵌入图像的水平像素尺寸。**Long**,默认`0`(使用图片的自然尺寸)。与[**IconSizeY**](#iconsizey)配对使用。 ### IconSizeY 与[**IconSizeX**](#iconsizex)对应的垂直属性。**Long**,默认`0`。 ### Index 当菜单是控件数组的一部分时,此实例在数组中的**Long**零基索引。运行时只读。在非数组菜单上读取会引发运行时错误343(*对象不是数组*)。 ### Name 菜单在其父窗体上的唯一设计时名称。**String**,运行时只读。继承自基控件类。 ### NegotiatePosition ::: info 保留用于与VB6的ActiveX文档菜单协商功能兼容;目前在twinBASIC中尚未实现。 ::: 类型为[**NegotiatePositionConstants**](/official/Reference/VBRUN/Constants/NegotiatePositionConstants)(**vbNoNegotiate**、**vbLeft**、**vbMiddle**、**vbRight**)——VB6使用此属性决定当ActiveX文档被激活时顶级菜单应出现在宿主应用程序菜单栏的何处。 ### Parent 对包含此菜单的[**Form**](/official/Reference/VB/Form/)(或[**MDIForm**](/official/Reference/VB/MDIForm/) / **UserControl**)的引用。只读。 ### Picture 绘制在标题左侧的**StdPicture**。**twinBASIC扩展**——VB6菜单无法显示图标。赋值**Nothing**移除图标。图标在内部转换为位图;直接传递位图可跳过转换。对于多分辨率`.ico`文件,与[**IconSizeX**](#iconsizex) / [**IconSizeY**](#iconsizey)配对使用。 语法: * *object*.**Picture** \[ = *picture* ] * **Set** *object*.**Picture** = *picture* ### Shortcut ::: info 隐藏、只读,运行时未使用——仅用于往返导入自VB6 `.frm`文件的原始快捷键文本。使用[**ShortcutId**](#shortcutid)绑定加速键。 ::: ### ShortcutId 绑定到此菜单项的键盘加速键。[**ShortcutConstants**](/official/Reference/VBRUN/Constants/ShortcutConstants)的成员——**vbShortcutNone**(无加速键,默认)、**vbShortcutCtrlA**到**vbShortcutCtrlZ**、**vbShortcutF1**到**vbShortcutF12**,以及**Shift+**、\*\*Ctrl+**和**Shift+Ctrl+\*\*功能键变体。设置后,渲染菜单时匹配的快捷键文本会附加到[**Caption**](#caption)(制表符后)。 语法:*object*.**ShortcutId** \[ = *value* ] ### Tag 应用程序可用于将自定义数据与菜单项关联的自由格式**String**。框架忽略此属性。继承自基控件类。对于控件数组很有用——例如保存MRU列表条目应打开的文件路径。 ### Visible 菜单项是否显示。**Boolean**,默认**True**。设为**False**会从菜单中移除条目而不卸载;设回**True**会将其恢复到原始位置。隐藏顶级菜单栏项目会重建菜单栏使周围条目关闭间隙。 语法:*object*.**Visible** \[ = *boolean* ] ### WindowList 当[**MDIForm**](/official/Reference/VB/MDIForm/)承载的菜单上为**True**时,将此菜单变为应用程序的*窗口*子菜单——运行时自动为每个打开的MDI子窗体填充一个条目,并将结果点击路由到相应子窗体的**SetFocus**。**Boolean**,运行时只读——在设计时设置。每个MDI窗体最多只能有一个菜单设置**WindowList**。 ## 方法 ### Container 返回承载此菜单的**Control**的引用——通常是拥有菜单结构的[**Form**](/official/Reference/VB/Form/)或[**MDIForm**](/official/Reference/VB/MDIForm/)。对于顶级菜单等效于遍历[**Parent**](#parent),但在每个菜单(包括子项)上定义,因此可以统一调用。 语法:*object*.**Container** ## 事件 ### Click 当用户选择菜单项时引发——通过点击、在菜单打开时按助记符,或按其[**ShortcutId**](#shortcutid)加速键。当[**PopUpMenu**](/official/Reference/VB/Form/#popupmenu)选择项目时也会引发。**默认事件。** 语法:*object*\_**Click**( ) 对于属于控件数组的菜单,处理程序接收被选项目的数组[**Index**](#index): 语法:*object*\_**Click**( *Index* **As Integer** ) --- --- url: /en/official/Reference/VBRUN/Constants/MenuAccelConstants.md --- # MenuAccelConstants Keyboard-accelerator codes for the **Shortcut** property of menu items, identifying which key combination triggers a given menu command. ## Ctrl + letter | Constant | Value | Description | |----------|-------|-------------| | **vbMenuAccelCtrlA** -- **vbMenuAccelCtrlZ** | 1 -- 26 | **Ctrl** + **A** through **Ctrl** + **Z**. | ## Function keys | Constant | Value | Description | |----------|-------|-------------| | **vbMenuAccelF1** -- **vbMenuAccelF9** | 27 -- 35 | **F1** through **F9**. | | **vbMenuAccelF11** | 36 | **F11**. | | **vbMenuAccelF12** | 37 | **F12**. | ## Ctrl + function | Constant | Value | Description | |----------|-------|-------------| | **vbMenuAccelCtrlF1** -- **vbMenuAccelCtrlF9** | 38 -- 46 | **Ctrl** + **F1** through **Ctrl** + **F9**. | | **vbMenuAccelCtrlF11** | 47 | **Ctrl** + **F11**. | | **vbMenuAccelCtrlF12** | 48 | **Ctrl** + **F12**. | ## Shift + function | Constant | Value | Description | |----------|-------|-------------| | **vbMenuAccelShiftF1** | 49 | **Shift** + **F1**. | | **vbMenuAccelShfitF2** | 50 | **Shift** + **F2**. *(Spelling preserved as in source.)* | | **vbMenuAccelShiftF3** -- **vbMenuAccelShiftF9** | 51 -- 57 | **Shift** + **F3** through **Shift** + **F9**. | | **vbMenuAccelShiftF11** | 58 | **Shift** + **F11**. | | **vbMenuAccelShiftF12** | 59 | **Shift** + **F12**. | ## Shift + Ctrl + function | Constant | Value | Description | |----------|-------|-------------| | **vbMenuAccelShiftCtrlF1** -- **vbMenuAccelShiftCtrlF9** | 60 -- 68 | **Shift** + **Ctrl** + **F1** through **Shift** + **Ctrl** + **F9**. | | **vbMenuAccelShiftCtrlF11** | 69 | **Shift** + **Ctrl** + **F11**. | | **vbMenuAccelShiftCtrlF12** | 70 | **Shift** + **Ctrl** + **F12**. | ## Editing keys | Constant | Value | Description | |----------|-------|-------------| | **vbMenuAccelCtrlIns** | 71 | **Ctrl** + **Insert**. | | **vbMenuAccelShiftIns** | 72 | **Shift** + **Insert**. | | **vbMenuAccelDel** | 73 | **Delete**. | | **vbMenuAccelShiftDel** | 74 | **Shift** + **Delete**. | | **vbMenuAccelAltBksp** | 75 | **Alt** + **Backspace**. | --- --- url: /zh/official/Reference/VBRUN/Constants/MenuAccelConstants.md --- # MenuAccelConstants 菜单项**Shortcut**属性的键盘快捷键代码,标识哪个组合键触发给定菜单命令。 ## Ctrl + 字母 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbMenuAccelCtrlA** -- **vbMenuAccelCtrlZ** | 1 -- 26 | **Ctrl** + **A**到**Ctrl** + **Z**。 | ## 功能键 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbMenuAccelF1** -- **vbMenuAccelF9** | 27 -- 35 | **F1**到**F9**。 | | **vbMenuAccelF11** | 36 | **F11**。 | | **vbMenuAccelF12** | 37 | **F12**。 | ## Ctrl + 功能键 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbMenuAccelCtrlF1** -- **vbMenuAccelCtrlF9** | 38 -- 46 | **Ctrl** + **F1**到**Ctrl** + **F9**。 | | **vbMenuAccelCtrlF11** | 47 | **Ctrl** + **F11**。 | | **vbMenuAccelCtrlF12** | 48 | **Ctrl** + **F12**。 | ## Shift + 功能键 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbMenuAccelShiftF1** | 49 | **Shift** + **F1**。 | | **vbMenuAccelShfitF2** | 50 | **Shift** + **F2**。*(拼写按源代码原样保留。)* | | **vbMenuAccelShiftF3** -- **vbMenuAccelShiftF9** | 51 -- 57 | **Shift** + **F3**到**Shift** + **F9**。 | | **vbMenuAccelShiftF11** | 58 | **Shift** + **F11**。 | | **vbMenuAccelShiftF12** | 59 | **Shift** + **F12**。 | ## Shift + Ctrl + 功能键 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbMenuAccelShiftCtrlF1** -- **vbMenuAccelShiftCtrlF9** | 60 -- 68 | **Shift** + **Ctrl** + **F1**到**Shift** + **Ctrl** + **F9**。 | | **vbMenuAccelShiftCtrlF11** | 69 | **Shift** + **Ctrl** + **F11**。 | | **vbMenuAccelShiftCtrlF12** | 70 | **Shift** + **Ctrl** + **F12**。 | ## 编辑键 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbMenuAccelCtrlIns** | 71 | **Ctrl** + **Insert**。 | | **vbMenuAccelShiftIns** | 72 | **Shift** + **Insert**。 | | **vbMenuAccelDel** | 73 | **Delete**。 | | **vbMenuAccelShiftDel** | 74 | **Shift** + **Delete**。 | | **vbMenuAccelAltBksp** | 75 | **Alt** + **Backspace**。 | --- --- url: /en/official/Reference/VBRUN/Constants/MenuControlConstants.md --- # MenuControlConstants Alignment and trigger-button flags for the **PopupMenu** method. ## Alignment | Constant | Value | Description | |----------|-------|-------------| | **vbPopupMenuLeftAlign** | 0 | The popup is positioned with its left edge at *x*. | | **vbPopupMenuCenterAlign** | 4 | The popup is positioned centred on *x*. | | **vbPopupMenuRightAlign** | 8 | The popup is positioned with its right edge at *x*. | ## Activation button | Constant | Value | Description | |----------|-------|-------------| | **vbPopupMenuLeftButton** | 0 | Items are selected with the left mouse button only. | | **vbPopupMenuRightButton** | 2 | Items can be selected with either the left or the right mouse button. | --- --- url: /zh/official/Reference/VBRUN/Constants/MenuControlConstants.md --- # MenuControlConstants **PopupMenu**方法的对齐和触发按钮标志。 ## 对齐 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbPopupMenuLeftAlign** | 0 | 弹出菜单左边缘定位在*x*处。 | | **vbPopupMenuCenterAlign** | 4 | 弹出菜单居中定位在*x*处。 | | **vbPopupMenuRightAlign** | 8 | 弹出菜单右边缘定位在*x*处。 | ## 激活按钮 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbPopupMenuLeftButton** | 0 | 仅用鼠标左键选择菜单项。 | | **vbPopupMenuRightButton** | 2 | 可用鼠标左键或右键选择菜单项。 | --- --- url: /zh/official/Documentation/Fixes-Dagre.md --- # Mermaid Dagre 补丁 `node_modules/mermaid/dist/chunks/mermaid.esm/dagre-ZXKKJJHT.mjs` 是 mermaid 流程图解析器与 dagre 分层图布局算法之间的适配器。`builder/scripts/patch-dagre.mjs` 对其应用了五处补丁,作为仓库根 `package.json` 上的 npm `postinstall` 钩子连接,因此新的 `npm install` 会自动重新应用。本页记录了每个补丁 --- dagre 上游做什么、为何破坏了构建管线图表、以及做了哪些改动。 所有补丁都针对同一个捆绑文件。Mermaid(精确锁定在 11.15.0 以保持块文件名中的指纹哈希稳定)将 dagre 内联到 `dagre-ZXKKJJHT.mjs` 中,npm 包的加载路径直接导入该块,因此修补 `node_modules/dagre-d3-es/` 下的原始 `dagre-d3-es` 源在运行时无效。 ## 带跨集群边的每集群方向(补丁 A) **问题。** Mermaid 的 `extractor()` 仅当集群没有跨越其边界的边时才会将带 `direction LR`(或 `RL`)的子图提取到自己的布局过程 --- 当集群有跨边界边时,留在父图中作为复合节点,dagre 的主布局静默忽略其每集群的 `rankdir`。结果是:任何连接到自身外部内容的 `direction LR` 子图都会以从上到下方式渲染。 这是[构建管线图](/assets/images/mmd/build-phases.svg)背后的布局问题。`row1` 和 `row2` 是 LR 子图,但 `row1` 的最后一个节点连接到 `row2` 的第一个节点,这使两行都有外部连接,因此两者都未被提取,都渲染为垂直堆栈。 **修复。** 扩展 `extractor()` 中的 else 分支,使同时有外部连接和显式 `clusterData.dir` 的集群仍被提取到自己的子图中。在 `copy()` 移出子节点之前,每条跨越集群边界的边被重新路由为使用集群占位节点本身;原始端点节点 ID 保留在重新路由边上作为 `_patchOrigV` 和 `_patchOrigW`,以便补丁 B 稍后修复渲染路径。 ```js for (const { e: _e, child: _c, other: _other } of _patchEdges) { const _eData = graph.edge(_e); if (!_eData._patchOrigV) _eData._patchOrigV = _e.v; if (!_eData._patchOrigW) _eData._patchOrigW = _e.w; graph.removeEdge(_e.v, _e.w, _e.name); if (_e.v === _c) { graph.setEdge(node, _other, _eData, _e.name); } else { graph.setEdge(_other, node, _eData, _e.name); } } ``` 重新路由后,父图的跨集群边变为 `Cluster → ExternalCluster`,子图仅携带其内部边。Dagre 然后作为两次独立的遍历布局父图(此处为从上到下)和子图(从左到右)。 ## 跨集群边端点(补丁 B) **问题。** 一旦补丁 A 将跨集群边从 `Child → ExternalNode` 重新路由为 `Cluster → ExternalCluster`,dagre 将其布局为两个集群边界框中心之间的直线残段。视觉上那是两行框之间间隙中的短垂直线 --- 原始源和目标节点无从寻觅。 **修复。** 在 `recursiveRender()` 内,父图布局定位集群框后,跨集群边的路点被替换为从原始端点节点实际渲染位置计算的 L 形路由: ```js const _sx = (_srcC.x - _srcC.width / 2 - _srcMx) + _srcN.x; const _dx = (_dstC.x - _dstC.width / 2 - _dstMx) + _dstN.x; const _srcEdgeY = (_srcC.y - _srcC.height / 2 - _srcMy) + _srcN.y + _srcN.height / 2; const _dstEdgeY = (_dstC.y - _dstC.height / 2 - _dstMy) + _dstN.y - _dstN.height / 2; const _srcBot = _srcC.y + _srcC.height / 2; const _dstTop = _dstC.y - _dstC.height / 2; const _gapY = (_srcBot + _dstTop) / 2; edge.points = [ { x: _sx, y: _srcEdgeY }, // exit source on its bottom edge { x: _sx, y: _srcBot }, // straight down past the source cluster rect { x: _sx, y: _gapY }, // into the gap between cluster rows { x: _dx, y: _gapY }, // across the gap to the destination column { x: _dx, y: _dstTop }, // down to the destination cluster rect { x: _dx, y: _dstEdgeY } // enter destination on its top edge ]; ``` `_Mx` / `_My` 减法考虑了 mermaid 的 `updateNodeBounds` 中一个微妙的簿记差异:它存储集群节点的 `x`/`y` 为边界框中心,但 `width`/`height` 为集群矩形尺寸(即不包含子图的 `marginx`/`marginy`),因此 `(_srcC.x - _srcC.width/2)` 给出矩形左边缘而非 SVG 组原点。减去子图边距恢复真实的组原点,使绝对坐标正确映射回来。 使用 mermaid 默认的 `curveBasis` 插值器,六个路点渲染为平滑曲线,从源节点底边出发,扫过两个集群行之间的间隙,进入目标节点顶边。 ## 跨集群箭头 z 顺序(补丁 C) **问题。** Mermaid 以固定声明顺序渲染顶层 SVG 子元素:`clusters`、`edgePaths`、`edgeLabels`、`nodes`。跨集群边的路径位于顶层 `edgePaths` 组中,在 `nodes` 之前渲染。集群子图(及其集群矩形)位于 `nodes` 内。因此集群矩形绘制在跨集群箭头之上。 **修复。** 在 `recursiveRender` 完成插入父图中的所有边后,如果其中任何边是跨集群边(携带补丁 A 的 `_patchOrigV`/`_patchOrigW`),整个顶层 `edgePaths` 组通过 d3 的 `selection.raise()` 移动到父元素的末尾: ```js if (graph.edges().some(_re => { const _red = graph.edge(_re); return _red && _red._patchOrigV && _red._patchOrigW; })) { edgePaths.raise(); } ``` 集群子图内的内边位于其自己的 SVG 组中,因此保持其自然的组内排序,不受影响。 ## 无边 LR 子图(补丁 D) **问题。** Dagre 的 `rank` 步骤基于节点之间的边分配每个节点的排名;在 LR 布局中,排名成为 x 坐标列。当子图的子节点之间没有边时,dagre 将每个节点放在排名 0,排名 0 是单列 --- 因此子节点无论声明了 `direction LR` 与否都垂直堆叠。 [`pdf-render-pipeline.mmd` PHASE8 子图](/assets/images/mmd/pdf-render-pipeline.svg)就遇到这个问题:它列出了从 `pdf.mjs` 调用的三个兄弟函数,不是序列,因此 `ASM`、`CSS` 和 `IMG` 之间没有箭头。没有补丁它们在垂直列中渲染。 **修复。** 在 `recursiveRender` 内 `layout(graph)` 运行之前,按父节点分组每个节点,并在连续的孤立兄弟对之间注入仅布局链式边 --- 两端都没有兄弟间边的对: ```js const _patchSiblingMap = new Map(); for (const _n of graph.nodes()) { const _p = graph.parent(_n) || "__root__"; if (!_patchSiblingMap.has(_p)) _patchSiblingMap.set(_p, []); _patchSiblingMap.get(_p).push(_n); } for (const _siblings of _patchSiblingMap.values()) { if (_siblings.length < 2) continue; const _siblingSet = new Set(_siblings); const _isolated = new Set(); for (const _s of _siblings) { let _hasSiblingEdge = false; const _ne = graph.nodeEdges(_s) || []; for (const _e of _ne) { const _other = _e.v === _s ? _e.w : _e.v; if (_siblingSet.has(_other)) { _hasSiblingEdge = true; break; } } if (!_hasSiblingEdge) _isolated.add(_s); } for (let _pi = 0; _pi < _siblings.length - 1; _pi++) { const _u = _siblings[_pi]; const _v = _siblings[_pi + 1]; if (_isolated.has(_u) && _isolated.has(_v)) { graph.setEdge(_u, _v, { _patchInvisible: true, weight: 1, minlen: 1 }); } } } ``` 两个值得指出的设计选择: * **按父节点分组,而非叶子过滤。** 当 `recursiveRender` 递归进入子图时,它会将父集群作为节点重新添加并将子节点重新挂载到它下面,因此此时的 `graph.nodes()` 返回 `[ASM, CSS, IMG, PHASE8]`。按 `graph.parent()` 分组将叶子放入 `"PHASE8"` 组,`PHASE8` 本身放入 `"__root__"` 组,因此子节点永远不会被链接到自己的父节点。(早期版本使用 `children().length === 0` 叶子过滤器;当嵌套子图中的两个复合兄弟需要链接时,这破坏了 dagre 的排名步骤。) * **仅孤立对。** 当一个兄弟的边没有一条指向同组中另一个兄弟时,该兄弟是"孤立的"。仅当两个兄弟都是孤立的时候才添加链式边。这保留了扇出拓扑:在 `build-phases.mmd` 的 row3 中,`P7` 和 `P8` 都有来自兄弟 `P6` 的入边,因此两者都不是孤立的,不添加 `P7 → P8` --- 扇出保持为扇出。 **行为示例。** | 子图(`direction LR`) | 无补丁 D 时 dagre 的行为 | 补丁 D 添加了什么 | 结果 | |---|---|---|---| | `A; B; C`(无边) | 全部排名 0,单列 | `A → B`、`B → C` | 三列,按声明顺序 | | `A → B; C; D` | A、C、D 在排名 0;B 在排名 1 | 仅 `C → D`(A 和 B 不是孤立的) | A 和 B 在自己的行,C 和 D 在下方行,分两列 | | `P6 → P7; P6 → P8` | P6 在排名 0;P7、P8 共享排名 1 | 无(P7 和 P8 各有来自 P6 的兄弟边) | 扇出:P6 在列 0,P7 在 P8 上方在列 1 | ::: info 链式边反映 mermaid 解析子节点的顺序。对于精细控制或复杂拓扑,作者仍应编写显式 `-->` 边(或 `~~~` 不可见边);补丁 D 仅自动排列严格孤立相邻兄弟。 ::: ## 渲染时的不可见边(补丁 E) **问题。** 补丁 D 的链式边仅用于 dagre 的布局 --- 它们没有视觉意义,会在兄弟框之间绘制为令人困惑的箭头。 **修复。** 在 `recursiveRender` 中布局后边循环顶部的守卫跳过任何标记了 `_patchInvisible` 的边: ```js graph.edges().forEach(function(e) { const edge = graph.edge(e); if (edge._patchInvisible) return; log.info("Edge " + e.v + " -> " + e.w + ": " + JSON.stringify(edge), edge); edge.points.forEach((point) => point.y += subGraphTitleTotalMargin / 2); ... }); ``` `processEdges()` 在 `recursiveRender` 中在 `layout()` 之前运行,因此补丁 D 注入的不可见边在 `insertEdgeLabel` 迭代时尚未在图中 --- 它们仅存在于补丁 D 的 setEdge 调用和补丁 E 的跳过之间,中间隔着 `layout()`。补丁 D 和 E 共同检测 dagre 会处理不当的拓扑,并修补布局而不改变用户的可见图表。 ## 补丁应用 `builder/scripts/patch-dagre.mjs` 作为仓库根 npm `postinstall` 钩子运行(依赖整合后仓库根只有一个 `package.json`;不再有 `builder/` 下的单独安装)。在新的 `npm install` 上,脚本按顺序应用所有五个补丁;重新运行时它检测已应用的补丁(通过检查每个补丁独有的标记字符串)并跳过。脚本还携带早期补丁版本的迁移路径:它检测进行中的升级并将先前版本的文本转换为当前版本,而非使 `postinstall` 失败。 仓库根 `package.json` 中对 `mermaid` 的精确锁定保持 `ZXKKJJHT` 指纹稳定:mermaid 在每次发布时重新生成其包哈希,因此浮动的 `^11.15.0` 可能在补丁更新时漂移块文件名并破坏 postinstall 目标路径。精确锁定以手动 mermaid 更新的少量 lockfile 变更为代价换取构建确定性。 如果 mermaid 升级到更改 `dagre-ZXKKJJHT.mjs` 结构的版本,脚本将以 `target not found` 明确失败,`patch-dagre.mjs` 中的补丁文本需要针对新源重新生成 --- 补丁是精确的字符串替换,而非正则匹配。 > AI生成 --- --- url: /en/official/Documentation/Fixes-Dagre.md --- # Mermaid Dagre Patches `node_modules/mermaid/dist/chunks/mermaid.esm/dagre-ZXKKJJHT.mjs` is mermaid's adapter between the flowchart parser and dagre, the layered-graph layout algorithm. Five patches are applied to it by `builder/scripts/patch-dagre.mjs`, wired in as an npm `postinstall` hook on the repo-root `package.json` so a fresh `npm install` re-applies them automatically. This page documents each patch --- what dagre does upstream, why it broke the build-pipeline diagrams, and what was changed. The patches all target the same bundled file. Mermaid (pinned at exactly 11.15.0 to keep the fingerprint hash in the chunk filename stable) ships dagre inlined into `dagre-ZXKKJJHT.mjs` and the npm bundle's load path imports the chunk directly, so patching the original `dagre-d3-es` source under `node_modules/dagre-d3-es/` has no effect at runtime. ## Per-cluster direction with cross-cluster edges (Patch A) **Problem.** Mermaid's `extractor()` extracts a subgraph with `direction LR` (or `RL`) into its own layout pass --- but only when the cluster has no edges crossing its boundary. Clusters that do have a cross-boundary edge stay in the parent graph as compound nodes, and dagre's main layout silently ignores their per-cluster `rankdir`. The result: any `direction LR` subgraph that connects to anything outside itself renders top-to-bottom anyway. This is the layout problem behind the [build-pipeline diagram](/assets/images/mmd/build-phases.svg). `row1` and `row2` are LR subgraphs, but `row1`'s last node connects to `row2`'s first node, which gives both rows external connections, so neither was extracted and both rendered as vertical stacks. **Fix.** Extend the else-branch in `extractor()` so a cluster with both external connections and an explicit `clusterData.dir` is still extracted into its own sub-graph. Before `copy()` moves the children out, every edge that crosses the cluster boundary is rerouted to use the cluster placeholder node itself; the original endpoint node IDs are preserved on the rerouted edge as `_patchOrigV` and `_patchOrigW` so Patch B can fix up the rendered path later. ```js for (const { e: _e, child: _c, other: _other } of _patchEdges) { const _eData = graph.edge(_e); if (!_eData._patchOrigV) _eData._patchOrigV = _e.v; if (!_eData._patchOrigW) _eData._patchOrigW = _e.w; graph.removeEdge(_e.v, _e.w, _e.name); if (_e.v === _c) { graph.setEdge(node, _other, _eData, _e.name); } else { graph.setEdge(_other, node, _eData, _e.name); } } ``` After the rerouting, the parent graph's cross-cluster edge is `Cluster → ExternalCluster`, and the sub-graph carries only its internal edges. Dagre then lays out the parent (here, top-to-bottom) and the sub-graph (left-to-right) as two separate passes. ## Cross-cluster edge endpoints (Patch B) **Problem.** Once Patch A reroutes a cross-cluster edge from `Child → ExternalNode` to `Cluster → ExternalCluster`, dagre lays it out as a straight stub between the two cluster bounding-box centres. Visually that's a short vertical line in the gap between the two rows of boxes --- the original source and destination nodes are nowhere in sight. **Fix.** Inside `recursiveRender()`, after the parent-graph layout positions the cluster boxes, the cross-cluster edge's waypoints are replaced with an L-shape routing computed from the original endpoint nodes' actual rendered positions: ```js const _sx = _srcC.x - _srcC.width / 2 - _srcMx + _srcN.x; const _dx = _dstC.x - _dstC.width / 2 - _dstMx + _dstN.x; const _srcEdgeY = _srcC.y - _srcC.height / 2 - _srcMy + _srcN.y + _srcN.height / 2; const _dstEdgeY = _dstC.y - _dstC.height / 2 - _dstMy + _dstN.y - _dstN.height / 2; const _srcBot = _srcC.y + _srcC.height / 2; const _dstTop = _dstC.y - _dstC.height / 2; const _gapY = (_srcBot + _dstTop) / 2; edge.points = [ { x: _sx, y: _srcEdgeY }, // exit source on its bottom edge { x: _sx, y: _srcBot }, // straight down past the source cluster rect { x: _sx, y: _gapY }, // into the gap between cluster rows { x: _dx, y: _gapY }, // across the gap to the destination column { x: _dx, y: _dstTop }, // down to the destination cluster rect { x: _dx, y: _dstEdgeY }, // enter destination on its top edge ]; ``` The `_Mx` / `_My` subtractions account for a subtle bookkeeping difference in mermaid's `updateNodeBounds`: it stores the cluster node's `x`/`y` as the bounding-box centre but `width`/`height` as the cluster *rect* dimensions (i.e. without the sub-graph's `marginx`/`marginy`), so `(_srcC.x - _srcC.width/2)` gives the rect left edge, not the SVG group origin. Subtracting the sub-graph margins recovers the true group origin so the absolute coordinate maps back correctly. With mermaid's default `curveBasis` interpolator, the six waypoints render as a smooth curve that exits the source node's bottom edge, sweeps across the gap between the two cluster rows, and enters the destination node's top edge. ## Cross-cluster arrow z-order (Patch C) **Problem.** Mermaid renders the top-level SVG children in fixed declaration order: `clusters`, `edgePaths`, `edgeLabels`, `nodes`. The cross-cluster edge's path lives in the top-level `edgePaths` group, rendered *before* `nodes`. The cluster sub-graphs (with their cluster rects) live inside `nodes`. So the cluster rect is painted on top of the cross-cluster arrow. **Fix.** After `recursiveRender` finishes inserting all edges in the parent graph, if any of those edges is a cross-cluster edge (carries `_patchOrigV`/`_patchOrigW` from Patch A), the entire top-level `edgePaths` group is moved to the end of the parent via d3's `selection.raise()`: ```js if ( graph.edges().some((_re) => { const _red = graph.edge(_re); return _red && _red._patchOrigV && _red._patchOrigW; }) ) { edgePaths.raise(); } ``` Internal edges inside cluster sub-graphs are inside their own SVG groups, so they keep their natural in-group ordering and are unaffected. ## Edge-less LR subgraphs (Patch D) **Problem.** Dagre's `rank` step assigns each node a rank based on the edges between them; in an LR layout the rank becomes the x-coordinate column. When a subgraph's children have no edges between them, dagre puts every node in rank 0, and rank 0 is a single column --- so the children stack vertically regardless of the declared `direction LR`. The [`pdf-render-pipeline.mmd` PHASE8 subgraph](/assets/images/mmd/pdf-render-pipeline.svg) runs into this: it lists three sibling functions called from `pdf.mjs`, not a sequence, so there are no arrows between `ASM`, `CSS`, and `IMG`. Without the patch they render in a vertical column. **Fix.** Immediately before `layout(graph)` runs inside `recursiveRender`, group every node by its parent and inject layout-only chain edges between consecutive *isolated* siblings --- pairs where neither side has any sibling-to-sibling edge: ```js const _patchSiblingMap = new Map(); for (const _n of graph.nodes()) { const _p = graph.parent(_n) || "__root__"; if (!_patchSiblingMap.has(_p)) _patchSiblingMap.set(_p, []); _patchSiblingMap.get(_p).push(_n); } for (const _siblings of _patchSiblingMap.values()) { if (_siblings.length < 2) continue; const _siblingSet = new Set(_siblings); const _isolated = new Set(); for (const _s of _siblings) { let _hasSiblingEdge = false; const _ne = graph.nodeEdges(_s) || []; for (const _e of _ne) { const _other = _e.v === _s ? _e.w : _e.v; if (_siblingSet.has(_other)) { _hasSiblingEdge = true; break; } } if (!_hasSiblingEdge) _isolated.add(_s); } for (let _pi = 0; _pi < _siblings.length - 1; _pi++) { const _u = _siblings[_pi]; const _v = _siblings[_pi + 1]; if (_isolated.has(_u) && _isolated.has(_v)) { graph.setEdge(_u, _v, { _patchInvisible: true, weight: 1, minlen: 1 }); } } } ``` Two design choices worth calling out: * **Group by parent, not by leaf filter.** When `recursiveRender` recurses into a sub-graph it re-adds the parent cluster as a node and reparents the children to it, so `graph.nodes()` at this point returns `[ASM, CSS, IMG, PHASE8]`. Grouping by `graph.parent()` puts the leaves into the `"PHASE8"` group and `PHASE8` itself into the `"__root__"` group, so a child can never get chained to its own parent. (An earlier version used a `children().length === 0` leaf filter; that broke dagre's rank step the moment two compound siblings needed chaining inside a nested subgraph.) * **Isolated pairs only.** A sibling is "isolated" when none of its edges go to another sibling in the same group. Only pairs where *both* siblings are isolated get a chain edge. This preserves fan-out topologies: in `build-phases.mmd` row3, `P7` and `P8` both have an incoming edge from sibling `P6`, so neither is isolated and `P7 → P8` is not added --- the fan-out stays a fan-out. **Behaviour by example.** | Subgraph (`direction LR`) | What dagre does without Patch D | What Patch D adds | Result | | ------------------------- | --------------------------------- | ---------------------------------------------------- | ------------------------------------------------------------------ | | `A; B; C` (no edges) | All rank 0, single column | `A → B`, `B → C` | Three columns, declaration order | | `A → B; C; D` | A, C, D in rank 0; B in rank 1 | `C → D` only (A and B are not isolated) | A and B in their own row, C and D in the row below, in two columns | | `P6 → P7; P6 → P8` | P6 in rank 0; P7, P8 share rank 1 | Nothing (P7 and P8 each have a sibling edge from P6) | Fan-out: P6 in column 0, P7 above P8 in column 1 | ::: info The chain reflects the order mermaid parsed the children in. For fine-grained control or complex topologies the author should still write explicit `-->` edges (or `~~~` invisible edges); Patch D only auto-orders strictly-orphan adjacent siblings. ::: ## Invisible edges at render time (Patch E) **Problem.** Patch D's chain edges exist for dagre's benefit only --- they have no visual meaning and would draw as confusing arrows between sibling boxes. **Fix.** A guard at the top of the post-layout edges loop in `recursiveRender` skips any edge tagged `_patchInvisible`: ```js graph.edges().forEach(function(e) { const edge = graph.edge(e); if (edge._patchInvisible) return; log.info("Edge " + e.v + " -> " + e.w + ": " + JSON.stringify(edge), edge); edge.points.forEach((point) => point.y += subGraphTitleTotalMargin / 2); ... }); ``` `processEdges()` runs *before* `layout()` in `recursiveRender`, so the invisible edges injected by Patch D are not yet in the graph when `insertEdgeLabel` iterates --- they only exist between Patch D's setEdge calls and Patch E's skip, with `layout()` in the middle. Patches D and E together detect a topology dagre would mishandle and patch the layout without altering the user's visible diagram. ## Patch application `builder/scripts/patch-dagre.mjs` runs as the repo-root npm `postinstall` hook (single `package.json` at the repo root after the dependency consolidation; there is no per-`builder/` install any more). On a fresh `npm install`, the script applies all five patches in order; on a re-run it detects already-applied patches (by checking for marker strings unique to each one) and skips them. The script also carries migration paths from earlier patch versions: it spots an in-progress upgrade and transforms the prior version's text into the current one rather than failing the `postinstall`. The exact-pin on `mermaid` in the root `package.json` keeps the `ZXKKJJHT` fingerprint stable: mermaid regenerates its bundle hashes on each release, so a floated `^11.15.0` could drift the chunk filename on a patch bump and break the postinstall target path. The pin trades the small lockfile churn of manual mermaid bumps for build determinism. If mermaid is upgraded to a release that changes the structure of `dagre-ZXKKJJHT.mjs`, the script will fail loudly with `target not found` and the patch text in `patch-dagre.mjs` needs to be regenerated against the new source --- the patches are precise string replacements, not regex matches. --- --- url: /en/official/Reference/VBRUN/AmbientProperties/MessageReflect.md --- # MessageReflect Returns whether the container reflects window messages back to the control, as a **Boolean**. Read-only. Syntax: *object*.**MessageReflect** *object* : *required* An object expression that evaluates to an **AmbientProperties** object. Some Windows notification messages --- such as **WM\_COMMAND**, **WM\_NOTIFY**, and the **WM\_CTLCOLOR\*** family --- are by default delivered to the parent window of the control that produced them. When **MessageReflect** is **True**, the container reflects those notifications back to the control's own window procedure as **OCM\_\*** messages, so the control can handle them itself; when **False**, the container handles them and the control will not see them. ### Example This example caches the ambient **MessageReflect** flag so the control knows whether to handle reflected messages. ```vb Private mMessageReflect As Boolean Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "MessageReflect" mMessageReflect = Ambient.MessageReflect End Select End Sub ``` ### See Also * [SupportsMnemonics](/en/official/Reference/VBRUN/AmbientProperties/SupportsMnemonics) property * [UserMode](/en/official/Reference/VBRUN/AmbientProperties/UserMode) property --- --- url: /zh/official/Reference/VBRUN/AmbientProperties/MessageReflect.md --- # MessageReflect 返回容器是否将窗口消息反射回控件,类型为**Boolean**。只读。 语法:*object*.**MessageReflect** *object* : *必需* 求值为**AmbientProperties**对象的对象表达式。 某些Windows通知消息——如**WM\_COMMAND**、**WM\_NOTIFY**和**WM\_CTLCOLOR\***系列——默认传递给产生它们的控件的父窗口。当**MessageReflect**为**True**时,容器将这些通知作为**OCM\_\***消息反射回控件自身的窗口过程,使控件可以自行处理;当为**False**时,容器处理它们,控件不会看到。 ### 示例 此示例缓存环境**MessageReflect**标志,使控件知道是否需要处理反射消息。 ```vb Private mMessageReflect As Boolean Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "MessageReflect" mMessageReflect = Ambient.MessageReflect End Select End Sub ``` ### 另见 * [SupportsMnemonics](/official/Reference/VBRUN/AmbientProperties/SupportsMnemonics) 属性 * [UserMode](/official/Reference/VBRUN/AmbientProperties/UserMode) 属性 --- --- url: /en/official/Reference/VBA/Strings/Mid.md --- # Mid, MidB Returns a **String** containing a specified number of characters from a string. Syntax: * **Mid$(** *string*, *start* \[ **,** *length* ] **)**, **Mid(** *string*, *start* \[ **,** *length* ] **)** * **MidB$(** *string*, *start* \[ **,** *length* ] **)**, **MidB(** *string*, *start* \[ **,** *length* ] **)** *string* : *required* String expression from which characters are returned. If *string* contains **Null**, **Null** is returned. *start* : *required* **Long**. Character position in *string* at which the part to be taken begins. If *start* is greater than the number of characters in *string*, **Mid** returns a zero-length string (`""`). *length* : *optional* **Variant** (**Long**). Number of characters to return. If omitted or if there are fewer than *length* characters in the text (including the character at *start*), all characters from the *start* position to the end of the string are returned. The `$`-suffixed forms return a **String**; the unsuffixed forms return a **Variant** (**String**). To determine the number of characters in *string*, use the [**Len**](/en/official/Reference/VBA/Strings/Len) function. ::: info Use the **MidB** function with byte data contained in a string, as in double-byte character set languages. Instead of specifying the number of characters, the arguments specify numbers of bytes. ::: ::: tip Use the [**Mid =**](/en/official/Reference/Core/Mid-equals) statement to replace characters within a string. ::: ### Example This example uses the **Mid** function to return a specified number of characters from a string. ```vb Dim MyString, FirstWord, LastWord, MidWords MyString = "Mid Function Demo" ' Create text string. FirstWord = Mid(MyString, 1, 3) ' Returns "Mid". LastWord = Mid(MyString, 14, 4) ' Returns "Demo". MidWords = Mid(MyString, 5) ' Returns "Function Demo". ``` ### See Also * [Left](/en/official/Reference/VBA/Strings/Left), [Len](/en/official/Reference/VBA/Strings/Len), [Right](/en/official/Reference/VBA/Strings/Right) functions * [Mid =](/en/official/Reference/Core/Mid-equals) statement --- --- url: /zh/official/Reference/VBA/Strings/Mid.md --- # Mid, MidB 返回一个**String**,包含从字符串中指定数量的字符。 语法: * **Mid$(** *string*, *start* \[ **,** *length* ] **)**, **Mid(** *string*, *start* \[ **,** *length* ] **)** * **MidB$(** *string*, *start* \[ **,** *length* ] **)**, **MidB(** *string*, *start* \[ **,** *length* ] **)** *string* : *必需* 从中返回字符的字符串表达式。如果*string*包含**Null**,则返回**Null**。 *start* : *必需* **Long**。*string*中开始提取部分的字符位置。如果*start*大于*string*中的字符数,**Mid**返回零长度字符串(`""`)。 *length* : *可选* **Variant**(**Long**)。要返回的字符数。如果省略或文本中(包括*start*位置的字符)的字符数少于*length*,则返回从*start*位置到字符串末尾的所有字符。 带`$`后缀的形式返回**String**;不带后缀的形式返回**Variant**(**String**)。 要确定*string*中的字符数,请使用[**Len**](/official/Reference/VBA/Strings/Len)函数。 ::: info 使用**MidB**函数处理字符串中包含的字节数据,如双字节字符集语言。参数指定的是字节数而非字符数。 ::: ::: tip 使用[**Mid =**](/official/Reference/Core/Mid-equals)语句替换字符串中的字符。 ::: ### 示例 本示例使用**Mid**函数从字符串中返回指定数量的字符。 ```vb Dim MyString, FirstWord, LastWord, MidWords MyString = "Mid Function Demo" ' Create text string. FirstWord = Mid(MyString, 1, 3) ' Returns "Mid". LastWord = Mid(MyString, 14, 4) ' Returns "Demo". MidWords = Mid(MyString, 5) ' Returns "Function Demo". ``` ### 另请参阅 * [Left](/official/Reference/VBA/Strings/Left)、[Len](/official/Reference/VBA/Strings/Len)、[Right](/official/Reference/VBA/Strings/Right)函数 * [Mid =](/official/Reference/Core/Mid-equals)语句 --- --- url: /en/official/Reference/Core/Mid-equals.md --- # Mid = statement Replaces a specified number of characters in a **Variant** (**String**) variable with characters from another string. ::: info This page documents the **Mid =** *statement* (string mutation). The unrelated [**Mid** function](/en/official/Reference/VBA/Strings/Mid) returns a substring without modifying its argument. ::: Syntax: > **Mid(** *stringvar* **,** *start* \[ **,** *length* ] **) =** *string* *stringvar* : Name of the string variable to modify. *start* : **Variant** (**Long**). Character position in *stringvar* where the replacement of text begins. *length* : *optional* **Variant** (**Long**). Number of characters to replace. If omitted, all of *string* is used. *string* : String expression that replaces part of *stringvar*. The number of characters replaced is always less than or equal to the number of characters in *stringvar*. ::: info Use the [**MidB =**](/en/official/Reference/Core/MidB-equals) statement with byte data contained in a string. In the **MidB =** statement, *start* specifies the byte position within *stringvar* where replacement begins, and *length* specifies the number of bytes to replace. ::: ### Example This example uses the **Mid =** statement to replace a specified number of characters in a string variable with characters from another string. ```vb Dim MyString MyString = "The dog jumps" ' Initialize string. Mid(MyString, 5, 3) = "fox" ' MyString = "The fox jumps". Mid(MyString, 5) = "cow" ' MyString = "The cow jumps". Mid(MyString, 5) = "cow jumped over" ' MyString = "The cow jumpe". Mid(MyString, 5, 3) = "duck" ' MyString = "The duc jumpe". ``` ### See Also * [**MidB =** statement](/en/official/Reference/Core/MidB-equals) * [**Mid** function](/en/official/Reference/VBA/Strings/Mid) * [**LSet** statement](/en/official/Reference/Core/LSet) * [**RSet** statement](/en/official/Reference/Core/RSet) --- --- url: /zh/official/Reference/Core/Mid-equals.md --- # Mid = 语句 用另一个字符串的字符替换 **Variant** (**String**) 变量中指定数量的字符。 ::: info 本页记录 **Mid =** *语句*(字符串修改)。不相关的 [**Mid** 函数](/official/Reference/VBA/Strings/Mid) 返回子字符串而不修改其参数。 ::: 语法: > **Mid(** *stringvar* **,** *start* \[ **,** *length* ] **) =** *string* *stringvar* : 要修改的字符串变量的名称。 *start* : **Variant** (**Long**)。*stringvar* 中开始替换文本的字符位置。 *length* : *可选* **Variant** (**Long**)。要替换的字符数。如果省略,使用 *string* 的全部内容。 *string* : 替换 *stringvar* 部分内容的字符串表达式。 替换的字符数始终小于或等于 *stringvar* 中的字符数。 ::: info 使用 [**MidB =**](/official/Reference/Core/MidB-equals) 语句处理字符串中包含的字节数据。在 **MidB =** 语句中,*start* 指定 *stringvar* 中开始替换的字节位置,*length* 指定要替换的字节数。 ::: ### 示例 本示例使用 **Mid =** 语句用另一个字符串的字符替换字符串变量中指定数量的字符。 ```vb Dim MyString MyString = "The dog jumps" ' Initialize string. Mid(MyString, 5, 3) = "fox" ' MyString = "The fox jumps". Mid(MyString, 5) = "cow" ' MyString = "The cow jumps". Mid(MyString, 5) = "cow jumped over" ' MyString = "The cow jumpe". Mid(MyString, 5, 3) = "duck" ' MyString = "The duc jumpe". ``` ### 另请参阅 * [**MidB =** 语句](/official/Reference/Core/MidB-equals) * [**Mid** 函数](/official/Reference/VBA/Strings/Mid) * [**LSet** 语句](/official/Reference/Core/LSet) * [**RSet** 语句](/official/Reference/Core/RSet) --- --- url: /en/official/Reference/Core/MidB-equals.md --- # MidB = statement Replaces a specified number of bytes in a **Variant** (**String**) variable with bytes from another string. The byte-mode counterpart of the [**Mid =**](/en/official/Reference/Core/Mid-equals) statement. Syntax: > **MidB(** *stringvar* **,** *start* \[ **,** *length* ] **) =** *string* *stringvar* : Name of the string variable to modify. *start* : **Variant** (**Long**). Byte position in *stringvar* where the replacement of bytes begins. *length* : *optional* **Variant** (**Long**). Number of bytes to replace. If omitted, all of *string* is used. *string* : String expression whose bytes replace part of *stringvar*. The number of bytes replaced is always less than or equal to the number of bytes in *stringvar*. **MidB =** is the byte-positioned form of [**Mid =**](/en/official/Reference/Core/Mid-equals): in this form, *start* and *length* count bytes of the underlying buffer rather than characters. This matters in double-byte character set languages where one character may occupy two bytes. ### See Also * [**Mid =** statement](/en/official/Reference/Core/Mid-equals) * [**MidB** function](/en/official/Reference/VBA/Strings/Mid) * [**LSet** statement](/en/official/Reference/Core/LSet) * [**RSet** statement](/en/official/Reference/Core/RSet) --- --- url: /zh/official/Reference/Core/MidB-equals.md --- # MidB = 语句 用另一个字符串的字节替换 **Variant** (**String**) 变量中指定数量的字节。[**Mid =**](/official/Reference/Core/Mid-equals) 语句的字节模式对应版本。 语法: > **MidB(** *stringvar* **,** *start* \[ **,** *length* ] **) =** *string* *stringvar* : 要修改的字符串变量的名称。 *start* : **Variant** (**Long**)。*stringvar* 中开始替换字节的字节位置。 *length* : *可选* **Variant** (**Long**)。要替换的字节数。如果省略,使用 *string* 的全部内容。 *string* : 其字节替换 *stringvar* 部分内容的字符串表达式。 替换的字节数始终小于或等于 *stringvar* 中的字节数。 **MidB =** 是 [**Mid =**](/official/Reference/Core/Mid-equals) 的字节定位形式:在此形式中,*start* 和 *length* 计算底层缓冲区的字节而非字符。这在双字节字符集语言中很重要,其中一个字符可能占用两个字节。 ### 另请参阅 * [**Mid =** 语句](/official/Reference/Core/Mid-equals) * [**MidB** 函数](/official/Reference/VBA/Strings/Mid) * [**LSet** 语句](/official/Reference/Core/LSet) * [**RSet** 语句](/official/Reference/Core/RSet) --- --- url: /en/official/Reference/VBA/DateTime/Minute.md --- # Minute Returns a **Variant** (**Integer**) specifying a whole number between 0 and 59, inclusive, representing the minute of the hour. Syntax: **Minute** ( *time* ) *time* : *required* Any **Variant**, numeric expression, string expression, or any combination that can represent a time. If *time* contains **Null**, **Null** is returned. ### Example This example uses the **Minute** function to obtain the minute of the hour from a specified time. ```vb Dim MyTime, MyMinute MyTime = #4:35:17 PM# ' Assign a time. MyMinute = Minute(MyTime) ' MyMinute contains 35. ``` ### See Also * [Hour](/en/official/Reference/VBA/DateTime/Hour), [Second](/en/official/Reference/VBA/DateTime/Second), [DatePart](/en/official/Reference/VBA/DateTime/DatePart) functions --- --- url: /zh/official/Reference/VBA/DateTime/Minute.md --- # Minute 返回一个 **Variant** (**Integer**),指定一个 0 到 59 之间的整数,表示小时中的分钟。 语法:**Minute** ( *time* ) *time* : *必需* 任何可以表示时间的 **Variant**、数值表达式、字符串表达式或其任意组合。如果 *time* 包含 **Null**,则返回 **Null**。 ### 示例 此示例使用 **Minute** 函数从指定时间中获取小时中的分钟。 ```vb Dim MyTime, MyMinute MyTime = #4:35:17 PM# ' Assign a time. MyMinute = Minute(MyTime) ' MyMinute contains 35. ``` ### 另请参阅 * [Hour](/official/Reference/VBA/DateTime/Hour)、[Second](/official/Reference/VBA/DateTime/Second)、[DatePart](/official/Reference/VBA/DateTime/DatePart) 函数 --- --- url: /en/official/Reference/VBA/Financial/MIRR.md --- # MIRR Returns a **Double** specifying the modified internal rate of return for a series of periodic cash flows (payments and receipts). Syntax: **MIRR(** *values()*, *finance\_rate*, *reinvest\_rate* **)** *values()* : *required* Array of **Double** specifying cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt). *finance\_rate* : *required* **Double** specifying interest rate paid as the cost of financing. *reinvest\_rate* : *required* **Double** specifying interest rate received on gains from cash reinvestment. The modified internal rate of return is the internal rate of return when payments and receipts are financed at different rates. The **MIRR** function takes into account both the cost of the investment (*finance\_rate*) and the interest rate received on reinvestment of cash (*reinvest\_rate*). The *finance\_rate* and *reinvest\_rate* arguments are percentages expressed as decimal values. For example, 12 percent is expressed as 0.12. The **MIRR** function uses the order of values within the array to interpret the order of payments and receipts. The payment and receipt values must be in the correct sequence. ### Example This example uses the **MIRR** function to return the modified internal rate of return for a series of cash flows contained in the array `Values()`. `LoanAPR` represents the financing interest, and `InvAPR` represents the interest rate received on reinvestment. ```vb Dim LoanAPR, InvAPR, Fmt, RetRate, Msg Static Values(5) As Double ' Set up array. LoanAPR = .1 ' Loan rate. InvAPR = .12 ' Reinvestment rate. Fmt = "#0.00" ' Define money format. Values(0) = -70000 ' Business start-up costs. ' Positive cash flows reflecting income for four successive years. Values(1) = 22000 : Values(2) = 25000 Values(3) = 28000 : Values(4) = 31000 RetRate = MIRR(Values(), LoanAPR, InvAPR) ' Calculate internal rate. Msg = "The modified internal rate of return for these five cash flows is" Msg = Msg & Format(Abs(RetRate) * 100, Fmt) & "%." MsgBox Msg ' Display internal return rate. ``` ### See Also * [IRR](/en/official/Reference/VBA/Financial/IRR), [NPV](/en/official/Reference/VBA/Financial/NPV), [Rate](/en/official/Reference/VBA/Financial/Rate) functions --- --- url: /zh/official/Reference/VBA/Financial/MIRR.md --- # MIRR 返回一个 **Double**,指定一系列定期现金流(付款和收入)的修正内部收益率。 语法:**MIRR(** *values()*, *finance\_rate*, *reinvest\_rate* **)** *values()* : *必需* **Double** 数组,指定现金流值。数组必须包含至少一个负值(付款)和一个正值(收入)。 *finance\_rate* : *必需* **Double**,指定作为融资成本支付的利率。 *reinvest\_rate* : *必需* **Double**,指定从现金再投资收益中获得的利率。 修正内部收益率是付款和收入以不同利率融资时的内部收益率。**MIRR** 函数考虑了投资成本(*finance\_rate*)和现金再投资收益的利率(*reinvest\_rate*)。 *finance\_rate* 和 *reinvest\_rate* 参数是以小数表示的百分比。例如,12% 表示为 0.12。 **MIRR** 函数使用数组中值的顺序来解释付款和收入的顺序。付款和收入值必须按正确顺序排列。 ### 示例 此示例使用 **MIRR** 函数返回包含在数组 `Values()` 中的一系列现金流的修正内部收益率。`LoanAPR` 代表融资利率,`InvAPR` 代表再投资收益利率。 ```vb Dim LoanAPR, InvAPR, Fmt, RetRate, Msg Static Values(5) As Double ' Set up array. LoanAPR = .1 ' Loan rate. InvAPR = .12 ' Reinvestment rate. Fmt = "#0.00" ' Define money format. Values(0) = -70000 ' Business start-up costs. ' Positive cash flows reflecting income for four successive years. Values(1) = 22000 : Values(2) = 25000 Values(3) = 28000 : Values(4) = 31000 RetRate = MIRR(Values(), LoanAPR, InvAPR) ' Calculate internal rate. Msg = "The modified internal rate of return for these five cash flows is" Msg = Msg & Format(Abs(RetRate) * 100, Fmt) & "%." MsgBox Msg ' Display internal return rate. ``` ### 另请参阅 * [IRR](/official/Reference/VBA/Financial/IRR)、[NPV](/official/Reference/VBA/Financial/NPV)、[Rate](/official/Reference/VBA/Financial/Rate) 函数 --- --- url: /en/official/Reference/VBA/FileSystem/MkDir.md --- # MkDir Creates a new directory or folder. Syntax: **MkDir** *path* *path* : A string expression that identifies the directory or folder to be created. The *path* may include the drive. If no drive is specified, **MkDir** creates the new directory or folder on the current drive. ### See Also * [ChDir](/en/official/Reference/VBA/FileSystem/ChDir), [ChDrive](/en/official/Reference/VBA/FileSystem/ChDrive), [RmDir](/en/official/Reference/VBA/FileSystem/RmDir) statements * [CurDir](/en/official/Reference/VBA/FileSystem/CurDir), [Dir](/en/official/Reference/VBA/FileSystem/Dir) functions ### Example This example uses the **MkDir** statement to create a directory or folder. If the drive is not specified, the new directory or folder is created on the current drive. ```vb MkDir "MYDIR" ' Make new directory or folder. ``` --- --- url: /zh/official/Reference/VBA/FileSystem/MkDir.md --- # MkDir 创建新目录或文件夹。 语法:**MkDir** *path* *path* : 字符串表达式,标识要创建的目录或文件夹。*path*可以包含驱动器。如果未指定驱动器,**MkDir**将在当前驱动器上创建新目录或文件夹。 ### 另请参阅 * [ChDir](/official/Reference/VBA/FileSystem/ChDir)、[ChDrive](/official/Reference/VBA/FileSystem/ChDrive)、[RmDir](/official/Reference/VBA/FileSystem/RmDir)语句 * [CurDir](/official/Reference/VBA/FileSystem/CurDir)、[Dir](/official/Reference/VBA/FileSystem/Dir)函数 ### 示例 本示例使用**MkDir**语句创建目录或文件夹。如果未指定驱动器,则在当前驱动器上创建新目录或文件夹。 ```vb MkDir "MYDIR" ' Make new directory or folder. ``` --- --- url: /zh/official/Reference/Core/MkDir.md --- # MkDir 语句 mkdir 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/MkDir.md --- # MkDir Statement Documentation for the mkdir keyword is not yet available. --- --- url: /en/official/Reference/Core/Mod.md --- # Mod operator Used to divide two numbers and return only the remainder. Syntax: > *result* **=** *number1* **Mod** *number2* *result* : Any numeric variable. *number1*, *number2* : Any numeric expressions. The modulus, or remainder, operator divides *number1* by *number2* (rounding floating-point numbers to integers) and returns only the remainder as *result*. For example, in the following expression, A (*result*) equals 5: ```vb A = 19 Mod 6.7 ``` Usually, the data type of *result* is **Byte**, **Byte** variant, **Integer**, **Integer** variant, **Long**, or **Variant** containing a **Long**, regardless of whether *result* is a whole number. Any fractional portion is truncated. However, if any operand is **Null**, *result* is **Null**. Any operand that is **Empty** is treated as 0. ### Example This example uses the **Mod** operator to divide two numbers and return only the remainder. If either number is a floating-point number, it is first rounded to an integer. ```vb Dim MyResult MyResult = 10 Mod 5 ' Returns 0. MyResult = 10 Mod 3 ' Returns 1. MyResult = 12 Mod 4.3 ' Returns 0. MyResult = 12.6 Mod 5 ' Returns 3. ``` ### See Also * [**\\** operator](/en/official/Reference/Core/IntegerDivide) * [**/** operator](/en/official/Reference/Core/Divide) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Mod.md --- # Mod 运算符 用于将两个数相除并仅返回余数。 语法: > *result* **=** *number1* **Mod** *number2* *result* : 任意数值变量。 *number1*, *number2* : 任意数值表达式。 取模(或余数)运算符将 *number1* 除以 *number2*(将浮点数舍入为整数)并仅返回余数作为 *result*。例如,在以下表达式中,A(*result*)等于5: ```vb A = 19 Mod 6.7 ``` 通常,*result* 的数据类型为 **Byte**、**Byte** 变体、**Integer**、**Integer** 变体、**Long** 或包含 **Long** 的 **Variant**,无论 *result* 是否为整数。任何小数部分被截断。 但如果任一操作数为 **Null**,则 *result* 为 **Null**。任何为 **Empty** 的操作数被视为0。 ### 示例 本示例使用 **Mod** 运算符将两个数相除并仅返回余数。如果任一数为浮点数,先舍入为整数。 ```vb Dim MyResult MyResult = 10 Mod 5 ' Returns 0. MyResult = 10 Mod 3 ' Returns 1. MyResult = 12 Mod 4.3 ' Returns 0. MyResult = 12.6 Mod 5 ' Returns 3. ``` ### 另请参阅 * [**\\** 运算符](/official/Reference/Core/IntegerDivide) * [**/** 运算符](/official/Reference/Core/Divide) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Features/Compiler-IDE/IDE-Features.md --- # Modern IDE Features While the twinBASIC IDE still has a lot of work planned, it already includes a number of features that make life much easier found in other modern IDE, but not the ancient VBx IDEs. ## Theme System Fully theme-able, with Dark (default), Light, and Classic (Light) built in, and an easy inheritance-based system to add your own themes via CSS files. ## Code Navigation and Structure * **Code folding**, with foldable custom-defined regions via `#Region "name" ... #End Region` blocks. * **Sticky-scroll**, which keeps context lines at the top showing major sections of code like module, region, method, `With` blocks, etc. * **Indent guides**, lines drawn along common indent points to help line things up right. * **Code mini-map**, shows a graphics overview of the code structure alongside the scroll bar, helping to guide your scrolling. ## Editing Features * **Fully customizable keyboard shortcuts** covering all commands, with ability to save and switch between different sets. * **Auto-indent on paste**. * **Paste as comment**. * **Inline code hints**, which provide annotations at the end of blocks for what the block is (see picture). * **Color-matching** for parentheses and brackets. ## Advanced Features * **Full Unicode support** in .twin files, so you can use the full Unicode range of the font in your comments and strings. * **Advanced Information popup**, which shows offsets for UDT members, their total size via both `Len()` plus `LenB()`, and their alignment; and v-table entry offsets for interfaces and classes, as well as their inheritance chain. * **A type library viewer** for controls and TLB files that displays the full contents in twinBASIC-style syntax rather than ODL. ## Panels and Windows * **A History panel** containing a list of recently modified methods. * **An Outline panel** with selectable categories. * **Problems panel**, provides a list of all current errors and warnings (you can filter to show only one or the other). ## Form Designer Enhancements On the Form Designer, control with `Visible = False` are faded to visually indicate this. Also, pressing and holding Control shows the tab index of each tab stop. ![image](/assets/014a1d28-30af-4a4d-8b9b-83ab6084f00a.Dq9Q2C3y.png) [Full size](../Images/fafaloneIDEscreenshot1.png) ### New Code-Based Project Explorer A new code structure based Project Explorer: ![image](/assets/9a5c50d5-a9f8-44a7-96f7-ae84548bd7ef.YtjenBmj.png) The classic file-based view is still used by default, you can activate the new view with a toggle button: ![image](/assets/b000d3aa-3689-4d94-88e3-bca44f8b7de6.DdxYXKUA.png) ## View Forms and Packages as JSON Project forms and packages are stored as JSON format data, and you can view this by right-click in Project Explorer and selecting 'View as JSON'. This is particularly interesting for packages as it exposes the entire code in a more parseable format. ![image](/assets/22660f54-ff5d-4b21-93d3-39715f1f35ed.DPbNvO4N.png) ![image](/assets/a6525b1d-ac22-4303-ae27-7984c20eba0c.B8dWFGYA.png) --- --- url: /en/official/Reference/Core/Module.md --- # Module Defines a module --- a non-instantiable container for procedures, constants, types, enums, and module-level variables. A module's members are accessed through the module name (or, for **Public** members in a non-private module, directly). ::: info The explicit **Module** ... **End Module** block is a twinBASIC extension. Classic VBA distinguishes "standard modules" from "class modules" purely by file type (`.bas` vs. `.cls`); the source has no enclosing keyword. In `.twin` files twinBASIC requires (and supports) the explicit block, which permits a class and a module in the same file and allows attributes to apply to the module as a whole. ::: Syntax: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Module** *name*\ >      \[ *modulemember* ]\ >      ...\ > **End Module** *attributes* : *optional* One or more attributes applicable to a module. **Public** : *optional* In an ActiveX project, marks the module as exported into the type library so that consumers in other projects can see its **Public** members. **Private** : *optional* In an ActiveX project, withholds the module from the type library: its members remain usable within the project, but are not exported. Equivalent to placing [**Option Private Module**](/en/official/Reference/Core/Option) at the top of a classic standard module. *name* : The identifier naming the module. *modulemember* : *optional* Any of the following: * constants defined using [**Const**](/en/official/Reference/Core/Const) * module-level variables defined using [**Public**](/en/official/Reference/Core/Public), [**Private**](/en/official/Reference/Core/Private), or [**Dim**](/en/official/Reference/Core/Dim) (modules don't take part in inheritance, so [**Protected**](/en/official/Reference/Core/Protected) is not allowed) * procedures defined using [**Sub**](/en/official/Reference/Core/Sub), [**Function**](/en/official/Reference/Core/Function), or [**Property**](/en/official/Reference/Core/Property) * user-defined types defined using [**Type**](/en/official/Reference/Core/Type) or [**Enum**](/en/official/Reference/Core/Enum) * external procedure declarations using [**Declare**](/en/official/Reference/Core/Declare) Modules cannot be instantiated and have no `New` constructor. Their **Public** members behave as project-wide globals (subject to the **Public**/**Private** module modifier above). ### Example ```vb Public Module StringHelpers Public Function Reverse(ByVal s As String) As String Dim i As Long, r As String For i = Len(s) To 1 Step -1 r = r & Mid$(s, i, 1) Next i Reverse = r End Function Public Function StartsWith(ByVal s As String, ByVal prefix As String) As Boolean StartsWith = (Left$(s, Len(prefix)) = prefix) End Function End Module ``` Callers reach the members either through the module name or directly: ```vb Debug.Print StringHelpers.Reverse("hello") ' "olleh" Debug.Print StartsWith("hello world", "hi") ' False ``` ### See Also * [**Class** statement](/en/official/Reference/Core/Class) * [**Public** statement](/en/official/Reference/Core/Public) * [**Private** statement](/en/official/Reference/Core/Private) * [**Option** statement](/en/official/Reference/Core/Option) * [Class and Module Enhancements](/en/official/Features/Advanced/Classes-and-Modules) --- --- url: /zh/official/Reference/Core/Module.md --- # Module 定义一个模块——一个不可实例化的容器,用于存放过程、常量、类型、枚举和模块级变量。模块的成员通过模块名访问(对于非私有模块中的**Public**成员,也可以直接访问)。 ::: info 显式的**Module** ... **End Module**块是twinBASIC扩展。经典VBA纯粹通过文件类型(`.bas`与`.cls`)区分"标准模块"和"类模块";源代码中没有封闭关键字。在`.twin`文件中,twinBASIC要求(并支持)显式块,这允许在同一文件中包含一个类和一个模块,并允许属性应用于整个模块。 ::: 语法: > \[ *attributes* ]\ > \[ **Public** | **Private** ] **Module** *name*\ >      \[ *modulemember* ]\ >      ...\ > **End Module** *attributes* : *可选* 适用于模块的一个或多个属性。 **Public** : *可选* 在ActiveX项目中,将模块标记为导出到类型库,以便其他项目中的使用者可以看到其**Public**成员。 **Private** : *可选* 在ActiveX项目中,阻止模块导出到类型库:其成员仍可在项目内使用,但不会被导出。等效于在经典标准模块顶部放置[**Option Private Module**](/official/Reference/Core/Option)。 *name* : 命名模块的标识符。 *modulemember* : *可选* 以下任意项: * 使用[**Const**](/official/Reference/Core/Const)定义的常量 * 使用[**Public**](/official/Reference/Core/Public)、[**Private**](/official/Reference/Core/Private)或[**Dim**](/official/Reference/Core/Dim)定义的模块级变量(模块不参与继承,因此不允许使用[**Protected**](/official/Reference/Core/Protected)) * 使用[**Sub**](/official/Reference/Core/Sub)、[**Function**](/official/Reference/Core/Function)或[**Property**](/official/Reference/Core/Property)定义的过程 * 使用[**Type**](/official/Reference/Core/Type)或[**Enum**](/official/Reference/Core/Enum)定义的用户自定义类型 * 使用[**Declare**](/official/Reference/Core/Declare)声明的外部过程 模块不能被实例化,也没有`New`构造函数。其**Public**成员表现为项目级的全局变量(受上述**Public**/**Private**模块修饰符约束)。 ### 示例 ```vb Public Module StringHelpers Public Function Reverse(ByVal s As String) As String Dim i As Long, r As String For i = Len(s) To 1 Step -1 r = r & Mid$(s, i, 1) Next i Reverse = r End Function Public Function StartsWith(ByVal s As String, ByVal prefix As String) As Boolean StartsWith = (Left$(s, Len(prefix)) = prefix) End Function End Module ``` 调用者可以通过模块名或直接访问成员: ```vb Debug.Print StringHelpers.Reverse("hello") ' "olleh" Debug.Print StartsWith("hello world", "hi") ' False ``` ### 另请参阅 * [**Class** 语句](/official/Reference/Core/Class) * [**Public** 语句](/official/Reference/Core/Public) * [**Private** 语句](/official/Reference/Core/Private) * [**Option** 语句](/official/Reference/Core/Option) * [类和模块增强](/official/Features/Advanced/Classes-and-Modules) --- --- url: /en/official/Features/Language/Module-Organization.md --- # Module-Level Code Organization It's now possible to insert module-level code in between methods or properties. Where previously all `Declare` statements, `Enum`, `Type`, etc had to appear prior to the first `Sub/Function/Property`, the following would now be valid: ```vb Private Const foo = "foo" Sub SomeMethod() '... End Sub Private Const bar = "bar" Sub SomeOtherMethod() '... End Sub ``` ## Preset Methods for Code Part Names The following can be used and what they represent will be automatically inserted as a `String`: * `CurrentComponentName`, e.g. "Form1" * `CurrentProcedureName`, e.g. "Foo" when in `Sub Foo()` * `CurrentProjectName` * `CurrentSourceFile` * `CurrentComponentCLSID` ## Removal of Limits twinBASIC imposes no artificial limitations on line continuations, procedure size, number of controls on a form, module size, and more. --- --- url: /en/official/Reference/VBA/DateTime/Month.md --- # Month Returns a **Variant** (**Integer**) specifying a whole number between 1 and 12, inclusive, representing the month of the year. Syntax: **Month** ( *date* ) *date* : *required* Any **Variant**, numeric expression, string expression, or any combination that can represent a date. If *date* contains **Null**, **Null** is returned. ::: info If the [**Calendar**](/en/official/Reference/VBA/DateTime/Calendar) property setting is Gregorian, the returned integer represents the Gregorian month. If the calendar is Hijri, the returned integer represents the Hijri month. For Hijri dates, the argument can be any numeric expression that represents a date and/or time from 1/1/100 (Gregorian Aug 2, 718) through 4/3/9666 (Gregorian Dec 31, 9999). ::: ### Example This example uses the **Month** function to obtain the month from a specified date. ```vb Dim MyDate, MyMonth MyDate = #February 12, 1969# ' Assign a date. MyMonth = Month(MyDate) ' MyMonth contains 2. ``` ### See Also * [Day](/en/official/Reference/VBA/DateTime/Day), [Year](/en/official/Reference/VBA/DateTime/Year), [DatePart](/en/official/Reference/VBA/DateTime/DatePart) functions --- --- url: /zh/official/Reference/VBA/DateTime/Month.md --- # Month 返回一个 **Variant** (**Integer**),指定一个 1 到 12 之间的整数,表示一年中的月份。 语法:**Month** ( *date* ) *date* : *必需* 任何可以表示日期的 **Variant**、数值表达式、字符串表达式或其任意组合。如果 *date* 包含 **Null**,则返回 **Null**。 ::: info 如果 [**Calendar**](/official/Reference/VBA/DateTime/Calendar) 属性设置为公历,则返回的整数表示公历月份。如果日历为回历,则返回的整数表示回历月份。对于回历日期,参数可以是表示 1/1/100(公历 718 年 8 月 2 日)至 4/3/9666(公历 9999 年 12 月 31 日)之间日期和/或时间的任何数值表达式。 ::: ### 示例 此示例使用 **Month** 函数从指定日期中获取月份。 ```vb Dim MyDate, MyMonth MyDate = #February 12, 1969# ' Assign a date. MyMonth = Month(MyDate) ' MyMonth contains 2. ``` ### 另请参阅 * [Day](/official/Reference/VBA/DateTime/Day)、[Year](/official/Reference/VBA/DateTime/Year)、[DatePart](/official/Reference/VBA/DateTime/DatePart) 函数 --- --- url: /en/official/Reference/VBA/Strings/MonthName.md --- # MonthName Returns a string indicating the specified month. Syntax: **MonthName(** *month* \[ **,** *abbreviate* ] **)** *month* : *required* The numeric designation of the month. For example, January is 1, February is 2, and so on. *abbreviate* : *optional* **Boolean** value that indicates if the month name is to be abbreviated. If omitted, the default is **False**, which means that the month name is not abbreviated. ### Example This example uses **MonthName** to return the full and abbreviated name of a month. ```vb Debug.Print MonthName(3) ' "March" Debug.Print MonthName(3, True) ' "Mar" Debug.Print MonthName(12) ' "December" ``` ### See Also * [FormatDateTime](/en/official/Reference/VBA/Strings/FormatDateTime), [WeekdayName](/en/official/Reference/VBA/Strings/WeekdayName) functions --- --- url: /zh/official/Reference/VBA/Strings/MonthName.md --- # MonthName 返回一个表示指定月份的字符串。 语法:**MonthName(** *month* \[ **,** *abbreviate* ] **)** *month* : *必需* 月份的数值。例如,一月为1,二月为2,依此类推。 *abbreviate* : *可选* **Boolean**值,指示是否缩写月份名称。如果省略,默认值为**False**,表示不缩写月份名称。 ### 示例 本示例使用**MonthName**返回月份的全名和缩写。 ```vb Debug.Print MonthName(3) ' "March" Debug.Print MonthName(3, True) ' "Mar" Debug.Print MonthName(12) ' "December" ``` ### 另请参阅 * [FormatDateTime](/official/Reference/VBA/Strings/FormatDateTime)、[WeekdayName](/official/Reference/VBA/Strings/WeekdayName)函数 --- --- url: /en/official/Reference/WinNativeCommonCtls/MonthView.md --- # MonthView class A **MonthView** is a full-month calendar grid: a visible matrix of [**MonthColumns**](#monthcolumns) × [**MonthRows**](#monthrows) month panels, navigable forwards and backwards through the month headers, with optional today indicator, week numbers, and bold-day highlighting through the [**GetDayBold**](#getdaybold) callback event. Unlike [**DTPicker**](/en/official/Reference/WinNativeCommonCtls/DTPicker) --- which shows only its inline value field and pops the calendar on demand --- a **MonthView** is always visible on the form. ```vb Private Sub Form_Load() MonthView1.MonthColumns = 2 MonthView1.MonthRows = 1 MonthView1.MultiSelect = True MonthView1.MaxSelCount = 7 MonthView1.ShowWeekNumbers = True End Sub Private Sub MonthView1_SelChange( _ ByVal StartDate As Date, ByVal EndDate As Date, Cancel As Boolean) Debug.Print "Selection: " & StartDate & " to " & EndDate End Sub Private Sub MonthView1_GetDayBold( _ ByVal StartDate As Date, ByVal Count As Integer, State() As Boolean) Dim i As Integer For i = 1 To Count State(i) = IsHoliday(DateAdd("d", i - 1, StartDate)) Next End Sub ``` The control inherits the focusable rect-dockable members from `BaseControlFocusable` --- size, position, **Anchors**, **Dock**, **Font**, **Appearance**, **MousePointer** / **MouseIcon**, **ToolTipText**, **Drag**, **Refresh**, **SetFocus**, **TabIndex** / **TabStop**, **ZOrder**, **CausesValidation**, **VisualStyles**, **hWnd**, **HelpContextID** / **WhatsThisHelpID**. ## Multi-month layout A **MonthView** can display more than one calendar panel at once. [**MonthColumns**](#monthcolumns) and [**MonthRows**](#monthrows) set the panel grid (default 1 × 1); when [**ResizeToFit**](#resizetofit) is **True** (the default), the control auto-sizes its **Width** and **Height** to fit the requested grid using the current [**Font**](/en/official/Reference/VB/CheckBox/#font) and the [**ShowToday**](#showtoday) / [**ShowWeekNumbers**](#showweeknumbers) options. Setting **ResizeToFit** to **False** allows the application to size the control freely, with the calendar panels arranged to fit whatever space is available. [**GetMonthRange**](#getmonthrange) returns the span of dates currently visible across all panels --- useful inside [**GetDayBold**](#getdaybold) to know which days to populate. ## Single-day and multi-day selection When [**MultiSelect**](#multiselect) is **False** (the default), the user can select one date at a time and [**Value**](#value), [**SelStart**](#selstart), and [**SelEnd**](#selend) all report the same value. When [**MultiSelect**](#multiselect) is **True**, the user can drag-select a contiguous range up to [**MaxSelCount**](#maxselcount) days wide; [**SelStart**](#selstart) and [**SelEnd**](#selend) bracket the range, and [**Value**](#value) returns [**SelStart**](#selstart). Changing [**MultiSelect**](#multiselect) at run time recreates the underlying Win32 window --- the property cannot be flipped through GWL\_STYLE alone. ## Bold days for highlighting The [**GetDayBold**](#getdaybold) event fires after every visible-range change, asking the application which days to render in bold. The application populates the *State* array with **True** / **False** for each day in the visible range; the control then caches the result until the user navigates to a different range. To force an individual day on or off without reissuing the whole event, use [**DayBold**](#dayboldday) ( *date* ) = *boolean*. ## Properties ### Appearance How the control's border is drawn. A [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants) member: **vbAppearFlat** or **vbAppear3d**. Default: **vbAppear3d**. Inherited. ### BackColor The main background color of the calendar panels. **OLE\_COLOR**. Default: **vbWindowBackground**. ### BorderStyle The control's border style. A [**ControlBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants) member: **vbNoBorder** or **vbFixedSingleBorder**. Default: **vbFixedSingleBorder**. ### CalendarCount The number of calendar panels the underlying control is rendering. **Byte**, read-only. Usually equals [**MonthColumns**](#monthcolumns) × [**MonthRows**](#monthrows). ### Day The day-of-month component of [**Value**](#value). **Integer** (1--31). See [**DayCount**](#daycount). ### DayBold(date) Whether a specific date in the visible range is rendered in bold. **Boolean**, read/write. The setter updates the underlying day-state bitmask and re-applies it; reading returns the live cached value. Syntax: *object*.**DayBold**( *date* ) \[ **=** *boolean* ] *date* : A **Date** within the currently visible range. Out-of-range dates raise run-time error 380. ### DayCount The number of days in the current value's month. **Long**, read-only. ### DayOfWeek The day-of-week the current [**Value**](#value) falls on, as a [**VbDayOfWeek**](/en/official/Reference/VBA/Constants/VbDayOfWeek) member. Read-only. ### ForeColor The text color used for normal days. **OLE\_COLOR**. Default: **vbButtonText**. ### MaxDate The upper bound of the navigable date range. **Date**. Default: `9999-12-31`. Assigning a value lower than [**MinDate**](#mindate) raises run-time error 35775. ### MaxSelCount The maximum number of consecutive days the user can select when [**MultiSelect**](#multiselect) is **True**. **Long**. Default: `7`. ### MinDate The lower bound of the navigable date range. **Date**. Default: `1753-01-01`. ### Month The month-of-year component of [**Value**](#value). **Integer** (1--12). ### MonthBackColor The background color used for the day cells. **OLE\_COLOR**. Default: **vbWindowBackground**. Distinct from [**BackColor**](#backcolor), which covers the surrounding area when multiple panels are arranged. ### MonthColumns The number of calendar panels arranged horizontally. **Long**. Default: `1`. Changing this value triggers a resize when [**ResizeToFit**](#resizetofit) is **True**. ### MonthRows The number of calendar panels arranged vertically. **Long**. Default: `1`. ### MultiSelect Whether the user can select a contiguous range of days. **Boolean**. Default: **False**. Changing this property at run time recreates the underlying Win32 window. ### ResizeToFit Whether the control auto-resizes to fit the requested [**MonthColumns**](#monthcolumns) × [**MonthRows**](#monthrows) grid using the current [**Font**](/en/official/Reference/VB/CheckBox/#font). **Boolean**. Default: **True**. ### RightToLeft ::: info **RightToLeft** is tagged `[Unimplemented]` and has no effect on the underlying control's rendering direction. ::: A **Boolean**. ### ScrollRate The number of months the navigation arrows scroll the visible range by. **Long**. Default: `0` --- meaning "use the calendar's natural width" (typically `MonthColumns`). Pass any positive integer to override. ### SelEnd The end of the current selection range. **Date**, read/write. When [**MultiSelect**](#multiselect) is **False**, **SelEnd** equals [**SelStart**](#selstart) and equals [**Value**](#value). ### SelStart The start of the current selection range. **Date**, read/write. Equals [**Value**](#value). ### ShowToday Whether the calendar shows the "Today: …" line at the bottom. **Boolean**. Default: **True**. ### ShowTodayCircle Whether the calendar highlights today's date with a circle. **Boolean**. Default: **True**. ### ShowTrailingDates Whether the calendar shows the leading and trailing days of the previous and next month. **Boolean**. Default: **True**. ### ShowWeekNumbers Whether the calendar shows a week-number column on the left of each panel. **Boolean**. Default: **False**. ### StartOfWeek Which day of the week is rendered as the leftmost column. A [**VbDayOfWeek**](/en/official/Reference/VBA/Constants/VbDayOfWeek) member. Defaults to the system's first-day-of-week setting. ### TitleBackColor The title bar (month name + year header) background color. **OLE\_COLOR**. Default: **vbActiveTitleBar**. ### TitleForeColor The title bar text color. **OLE\_COLOR**. Default: **vbActiveTitleBarText**. ### TrailingForeColor The text color used for trailing days from adjacent months when [**ShowTrailingDates**](#showtrailingdates) is **True**. **OLE\_COLOR**. Default: **vbGrayText**. ### Value The currently selected start date. **Date**. The default member. Reading returns [**SelStart**](#selstart). Assigning fires [**SelChange**](#selchange) (the handler can cancel the change). Assigning a date outside \[[**MinDate**](#mindate), [**MaxDate**](#maxdate)] raises run-time error 35773. ### VisibleDays(sIndex) The date at the *sIndex*'th cell across all visible panels. **Date**, read-only. Syntax: *object*.**VisibleDays**( *sIndex* ) *sIndex* : A 1-based index between 1 and the total cell count returned by [**GetMonthRange**](#getmonthrange). ### Week The week-of-year for the current [**Value**](#value). **Integer** (1--53). ### Year The year component of [**Value**](#value). **Integer**. ## Methods ### GetMonthRange Returns the first and last visible date across all panels. Syntax: *object*.**GetMonthRange** ( *IncludeTrailing*, \[ *StartDate* ] \[ , *EndDate* ] ) **As Long** *IncludeTrailing* : A **Boolean**. When **True**, the range includes the trailing days of the previous month and leading days of the next month that are rendered in the first / last panels (useful for [**GetDayBold**](#getdaybold) population). When **False**, the range covers only the days that belong to the visible month columns. *StartDate* : *output* A **Date** that receives the first visible date. *EndDate* : *output* A **Date** that receives the last visible date. Returns the count of months in the visible range. ## Events ### Click Raised on any mouse click that doesn't hit a date cell. Syntax: *object*\_**Click**( ) ### DateClick Raised when the user clicks a date cell. The clicked date is passed as a parameter. Syntax: *object*\_**DateClick**( **ByVal** *DateClicked* **As Date** ) ### DateDblClick Raised when the user double-clicks a date cell. Syntax: *object*\_**DateDblClick**( **ByVal** *DateDblClicked* **As Date** ) ### DblClick Raised on any double-click that doesn't hit a date cell. Syntax: *object*\_**DblClick**( ) ### DragDrop, DragOver Inherited drag-drop events. ### GetDayBold Raised for every visible range change, asking the application to populate the *State* array with the days that should be rendered in bold. The first array index is `1`; the array runs from *StartDate* through *StartDate* + *Count* − 1. Syntax: *object*\_**GetDayBold**( **ByVal** *StartDate* **As Date**, **ByVal** *Count* **As Integer**, *State*( ) **As Boolean** ) *StartDate* : The first day in the visible range (including trailing days of the previous month). *Count* : The total number of days in the visible range. *State* : An array of **Boolean**, 1-indexed, that the handler sets to **True** for each day that should be bold. ### GotFocus, LostFocus Inherited focus events. ### Initialize Raised after the control's window has been created and properties initialised from persisted state. Fires once per form-load. ### KeyDown, KeyPress, KeyUp Inherited keyboard events. ### MouseDown, MouseMove, MouseUp Inherited mouse events. ### OLECompleteDrag, OLEDragDrop, OLEDragOver, OLEGiveFeedback, OLESetData, OLEStartDrag Inherited OLE drag-and-drop events. ### SelChange Raised when the selection has changed. Set *Cancel* to **True** to roll the selection back to the previous range (the control restores the old [**SelStart**](#selstart) / [**SelEnd**](#selend)). Syntax: *object*\_**SelChange**( **ByVal** *StartDate* **As Date**, **ByVal** *EndDate* **As Date**, *Cancel* **As Boolean** ) ### Validate Inherited validation event. ## See Also * [DTPicker](/en/official/Reference/WinNativeCommonCtls/DTPicker) -- the inline date picker whose dropdown uses the same Win32 calendar control * [ControlTypeConstants](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) -- where **vbMonthView** lives --- --- url: /zh/official/Reference/WinNativeCommonCtls/MonthView.md --- # MonthView 类 **MonthView** 是一个全月日历网格:一个 [**MonthColumns**](#monthcolumns) × [**MonthRows**](#monthrows) 月面板的可见矩阵,可通过月标题向前和向后导航,带可选的今日指示器、周数和通过 [**GetDayBold**](#getdaybold) 回调事件的粗体日期高亮。与 [**DTPicker**](/official/Reference/WinNativeCommonCtls/DTPicker) --- 仅显示其内联值字段并按需弹出日历 --- 不同,**MonthView** 始终在窗体上可见。 ```vb Private Sub Form_Load() MonthView1.MonthColumns = 2 MonthView1.MonthRows = 1 MonthView1.MultiSelect = True MonthView1.MaxSelCount = 7 MonthView1.ShowWeekNumbers = True End Sub Private Sub MonthView1_SelChange( _ ByVal StartDate As Date, ByVal EndDate As Date, Cancel As Boolean) Debug.Print "Selection: " & StartDate & " to " & EndDate End Sub Private Sub MonthView1_GetDayBold( _ ByVal StartDate As Date, ByVal Count As Integer, State() As Boolean) Dim i As Integer For i = 1 To Count State(i) = IsHoliday(DateAdd("d", i - 1, StartDate)) Next End Sub ``` 控件从 `BaseControlFocusable` 继承可聚焦矩形可停靠成员 --- 大小、位置、**Anchors**、**Dock**、**Font**、**Appearance**、**MousePointer** / **MouseIcon**、**ToolTipText**、**Drag**、**Refresh**、**SetFocus**、**TabIndex** / **TabStop**、**ZOrder**、**CausesValidation**、**VisualStyles**、**hWnd**、**HelpContextID** / **WhatsThisHelpID**。 ## 多月布局 **MonthView** 可以同时显示多个日历面板。[**MonthColumns**](#monthcolumns) 和 [**MonthRows**](#monthrows) 设置面板网格(默认 1 × 1);当 [**ResizeToFit**](#resizetofit) 为 **True**(默认)时,控件根据当前 [**Font**](/official/Reference/VB/CheckBox/#font) 和 [**ShowToday**](#showtoday) / [**ShowWeekNumbers**](#showweeknumbers) 选项自动调整 **Width** 和 **Height** 以适应请求的网格。将 **ResizeToFit** 设为 **False** 允许应用程序自由调整控件大小,日历面板排列以适应可用空间。 [**GetMonthRange**](#getmonthrange) 返回所有面板中当前可见的日期范围 --- 在 [**GetDayBold**](#getdaybold) 中很有用,用于了解需要填充哪些天。 ## 单日和多日选择 当 [**MultiSelect**](#multiselect) 为 **False**(默认)时,用户一次只能选择一个日期,[**Value**](#value)、[**SelStart**](#selstart) 和 [**SelEnd**](#selend) 都返回相同值。当 [**MultiSelect**](#multiselect) 为 **True** 时,用户可以拖选最多 [**MaxSelCount**](#maxselcount) 天的连续范围;[**SelStart**](#selstart) 和 [**SelEnd**](#selend) 界定范围,[**Value**](#value) 返回 [**SelStart**](#selstart)。 运行时更改 [**MultiSelect**](#multiselect) 会重新创建底层Win32窗口 --- 该属性无法仅通过 GWL\_STYLE 切换。 ## 粗体日期高亮 [**GetDayBold**](#getdaybold) 事件在每次可见范围更改后触发,询问应用程序哪些天应以粗体渲染。应用程序用 **True** / **False** 填充可见范围内每一天的 *State* 数组;控件随后缓存结果直到用户导航到不同范围。要强制打开或关闭个别日期而无须重新触发整个事件,请使用 [**DayBold**](#dayboldday)(*date*)= *boolean*。 ## 属性 ### Appearance 控件边框的绘制方式。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants) 的成员:**vbAppearFlat** 或 **vbAppear3d**。默认:**vbAppear3d**。继承。 ### BackColor 日历面板的主要背景颜色。**OLE\_COLOR**。默认:**vbWindowBackground**。 ### BorderStyle 控件的边框样式。[**ControlBorderStyleConstants**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants) 的成员:**vbNoBorder** 或 **vbFixedSingleBorder**。默认:**vbFixedSingleBorder**。 ### CalendarCount 底层控件正在渲染的日历面板数。**Byte**,只读。通常等于 [**MonthColumns**](#monthcolumns) × [**MonthRows**](#monthrows)。 ### Day [**Value**](#value) 的月中第几天分量。**Integer**(1--31)。参见 [**DayCount**](#daycount)。 ### DayBold(date) 可见范围内特定日期是否以粗体渲染。**Boolean**,读/写。设置器更新底层日期状态位掩码并重新应用;读取返回实时缓存值。 语法:*object*.**DayBold**(*date*)\[ **=** *boolean* ] *date* : 当前可见范围内的一个 **Date**。超出范围的日期引发运行时错误 380。 ### DayCount 当前值所在月份的天数。**Long**,只读。 ### DayOfWeek 当前 [**Value**](#value) 是星期几,作为 [**VbDayOfWeek**](/official/Reference/VBA/Constants/VbDayOfWeek) 的成员。只读。 ### ForeColor 用于普通日期的文本颜色。**OLE\_COLOR**。默认:**vbButtonText**。 ### MaxDate 可导航日期范围的上限。**Date**。默认:`9999-12-31`。赋值低于 [**MinDate**](#mindate) 时引发运行时错误 35775。 ### MaxSelCount 当 [**MultiSelect**](#multiselect) 为 **True** 时用户可以选择的最大连续天数。**Long**。默认:`7`。 ### MinDate 可导航日期范围的下限。**Date**。默认:`1753-01-01`。 ### Month [**Value**](#value) 的月份分量。**Integer**(1--12)。 ### MonthBackColor 用于日期单元格的背景颜色。**OLE\_COLOR**。默认:**vbWindowBackground**。与 [**BackColor**](#backcolor) 不同,后者覆盖多个面板排列时的周围区域。 ### MonthColumns 水平排列的日历面板数。**Long**。默认:`1`。当 [**ResizeToFit**](#resizetofit) 为 **True** 时,更改此值会触发大小调整。 ### MonthRows 垂直排列的日历面板数。**Long**。默认:`1`。 ### MultiSelect 用户是否可以选择连续多天。**Boolean**。默认:**False**。运行时更改此属性会重新创建底层Win32窗口。 ### ResizeToFit 控件是否根据当前 [**Font**](/official/Reference/VB/CheckBox/#font) 自动调整大小以适应请求的 [**MonthColumns**](#monthcolumns) × [**MonthRows**](#monthrows) 网格。**Boolean**。默认:**True**。 ### RightToLeft ::: info **RightToLeft** 标记为 `[Unimplemented]`,对底层控件的渲染方向无效。 ::: 一个 **Boolean**。 ### ScrollRate 导航箭头滚动可见范围的月数。**Long**。默认:`0` --- 表示"使用日历的自然宽度"(通常为 `MonthColumns`)。传入正整数以覆盖。 ### SelEnd 当前选择范围的结束日期。**Date**,读/写。当 [**MultiSelect**](#multiselect) 为 **False** 时,**SelEnd** 等于 [**SelStart**](#selstart) 并等于 [**Value**](#value)。 ### SelStart 当前选择范围的开始日期。**Date**,读/写。等于 [**Value**](#value)。 ### ShowToday 日历是否在底部显示"Today: …"行。**Boolean**。默认:**True**。 ### ShowTodayCircle 日历是否用圆圈高亮今日日期。**Boolean**。默认:**True**。 ### ShowTrailingDates 日历是否显示上月末和下月初的日期。**Boolean**。默认:**True**。 ### ShowWeekNumbers 日历是否在每个面板的左侧显示周数列。**Boolean**。默认:**False**。 ### StartOfWeek 一周中的哪一天渲染为最左列。[**VbDayOfWeek**](/official/Reference/VBA/Constants/VbDayOfWeek) 的成员。默认为系统的一周起始日设置。 ### TitleBackColor 标题栏(月份名称 + 年份标题)背景颜色。**OLE\_COLOR**。默认:**vbActiveTitleBar**。 ### TitleForeColor 标题栏文本颜色。**OLE\_COLOR**。默认:**vbActiveTitleBarText**。 ### TrailingForeColor 当 [**ShowTrailingDates**](#showtrailingdates) 为 **True** 时用于相邻月份尾随日期的文本颜色。**OLE\_COLOR**。默认:**vbGrayText**。 ### Value 当前选定的开始日期。**Date**。默认成员。 读取返回 [**SelStart**](#selstart)。赋值触发 [**SelChange**](#selchange)(处理程序可取消更改)。赋值超出 \[[**MinDate**](#mindate), [**MaxDate**](#maxdate)] 的日期引发运行时错误 35773。 ### VisibleDays(sIndex) 所有可见面板中第 *sIndex* 个单元格的日期。**Date**,只读。 语法:*object*.**VisibleDays**(*sIndex*) *sIndex* : 一个从1开始的索引,介于1和 [**GetMonthRange**](#getmonthrange) 返回的总单元格数之间。 ### Week 当前 [**Value**](#value) 一年中的第几周。**Integer**(1--53)。 ### Year [**Value**](#value) 的年份分量。**Integer**。 ## 方法 ### GetMonthRange 返回所有面板中的第一个和最后一个可见日期。 语法:*object*.**GetMonthRange**(*IncludeTrailing*, \[*StartDate*] \[, *EndDate*])**As Long** *IncludeTrailing* : 一个 **Boolean**。为 **True** 时,范围包括上月的尾随日期和下月的首导日期,这些日期渲染在第一个/最后一个面板中(用于 [**GetDayBold**](#getdaybold) 填充)。为 **False** 时,范围仅覆盖属于可见月份列的天数。 *StartDate* : *输出* 一个接收第一个可见日期的 **Date**。 *EndDate* : *输出* 一个接收最后一个可见日期的 **Date**。 返回可见范围内的月份数。 ## 事件 ### Click 任何未命中日期单元格的鼠标点击时触发。 语法:*object*\_**Click**( ) ### DateClick 用户点击日期单元格时触发。被点击的日期作为参数传入。 语法:*object*\_**DateClick**(**ByVal** *DateClicked* **As Date**) ### DateDblClick 用户双击日期单元格时触发。 语法:*object*\_**DateDblClick**(**ByVal** *DateDblClicked* **As Date**) ### DblClick 任何未命中日期单元格的双击时触发。 语法:*object*\_**DblClick**( ) ### DragDrop, DragOver 继承的拖放事件。 ### GetDayBold 每次可见范围更改时触发,要求应用程序填充 *State* 数组以指定哪些天应以粗体渲染。第一个数组索引为 `1`;数组从 *StartDate* 到 *StartDate* + *Count* − 1。 语法:*object*\_**GetDayBold**(**ByVal** *StartDate* **As Date**,**ByVal** *Count* **As Integer**,*State*( ) **As Boolean**) *StartDate* : 可见范围内的第一天(包括上月的尾随日期)。 *Count* : 可见范围内的总天数。 *State* : 一个 **Boolean** 数组,从1开始索引,处理程序将应粗体的每一天设为 **True**。 ### GotFocus, LostFocus 继承的焦点事件。 ### Initialize 控件窗口创建并从持久化状态初始化属性后触发。每次窗体加载触发一次。 ### KeyDown, KeyPress, KeyUp 继承的键盘事件。 ### MouseDown, MouseMove, MouseUp 继承的鼠标事件。 ### OLECompleteDrag, OLEDragDrop, OLEDragOver, OLEGiveFeedback, OLESetData, OLEStartDrag 继承的OLE拖放事件。 ### SelChange 选择更改时触发。将 *Cancel* 设为 **True** 将选择回滚到先前范围(控件恢复旧的 [**SelStart**](#selstart) / [**SelEnd**](#selend))。 语法:*object*\_**SelChange**(**ByVal** *StartDate* **As Date**,**ByVal** *EndDate* **As Date**,*Cancel* **As Boolean**) ### Validate 继承的验证事件。 ## 另见 * [DTPicker](/official/Reference/WinNativeCommonCtls/DTPicker) --- 内联日期选择器,其下拉使用相同的Win32日历控件 * [ControlTypeConstants](/official/Reference/VBRUN/Constants/ControlTypeConstants) --- **vbMonthView** 所在位置 --- --- url: /en/packages/vbccr/datetime/monthview.md description: >- MonthView Control - VBCCR Development Manual, complete API reference based on source code --- # MonthView Control Wraps the SysMonthCal32 system month calendar control for date selection and calendar display, supporting advanced features such as multi-date selection and multi-month views. ## Enumerations ### MvwViewConstants | Constant | Value | Description | |----------|-------|-------------| | MvwViewMonth | 0 | Month view | | MvwViewYear | 1 | Year view | | MvwViewDecade | 2 | Decade view | | MvwViewCentury | 3 | Century view | ### MvwHitResultConstants | Constant | Value | Description | |----------|-------|-------------| | MvwHitResultNowhere | 0 | No hit | | MvwHitResultTitleBg | 1 | Title background | | MvwHitResultTitleMonth | 2 | Title month | | MvwHitResultTitleYear | 3 | Title year | | MvwHitResultTitlePrevMonth | 4 | Previous month button | | MvwHitResultTitleNextMonth | 5 | Next month button | | MvwHitResultCalendarBg | 6 | Calendar background | | MvwHitResultCalendarDate | 7 | Calendar date | | MvwHitResultCalendarDateMin | 8 | Calendar minimum date | | MvwHitResultCalendarDateMax | 9 | Calendar maximum date | | MvwHitResultCalendarWeekNumber | 10 | Week number | | MvwHitResultCalendarPrevMonth | 11 | Previous month's date | | MvwHitResultCalendarNextMonth | 12 | Next month's date | | MvwHitResultTodayLink | 13 | "Today" link | ### CCMousePointerConstants See common enumerations. ## Properties ### Value ```vb Property Get Value() As Date Property Let Value(ByVal Value As Date) ``` Currently selected date. ### MinDate ```vb Property Get MinDate() As Date Property Let MinDate(ByVal Value As Date) ``` Minimum selectable date. ### MaxDate ```vb Property Get MaxDate() As Date Property Let MaxDate(ByVal Value As Date) ``` Maximum selectable date. ### Year ```vb Property Get Year() As Integer Property Let Year(ByVal Value As Integer) ``` Current year. ### Month ```vb Property Get Month() As Integer Property Let Month(ByVal Value As Integer) ``` Current month (1-12). ### Week ```vb Property Get Week() As Integer Property Let Week(ByVal Value As Integer) ``` Current week number. ### Day ```vb Property Get Day() As Integer Property Let Day(ByVal Value As Integer) ``` Current day (1-31). ### DayCount ```vb Property Get DayCount() As Long ``` Number of days in the currently visible month. Read-only. ### CalendarCount ```vb Property Get CalendarCount() As Long ``` Number of months currently displayed. Read-only. ### ShowToday ```vb Property Get ShowToday() As Boolean Property Let ShowToday(ByVal Value As Boolean) ``` Whether to display the "today" date. ### ShowTodayCircle ```vb Property Get ShowTodayCircle() As Boolean Property Let ShowTodayCircle(ByVal Value As Boolean) ``` Whether to circle today's date. ### ShowWeekNumbers ```vb Property Get ShowWeekNumbers() As Boolean Property Let ShowWeekNumbers(ByVal Value As Boolean) ``` Whether to display week numbers. ### ShowTrailingDates ```vb Property Get ShowTrailingDates() As Boolean Property Let ShowTrailingDates(ByVal Value As Boolean) ``` Whether to display trailing dates from the previous/next month. ### ScrollRate ```vb Property Get ScrollRate() As Long Property Let ScrollRate(ByVal Value As Long) ``` Scroll rate. ### StartOfWeek ```vb Property Get StartOfWeek() As Integer Property Let StartOfWeek(ByVal Value As Integer) ``` First day of the week (0=Sunday, 1=Monday...6=Saturday). ### MultiSelect ```vb Property Get MultiSelect() As Boolean Property Let MultiSelect(ByVal Value As Boolean) ``` Whether to allow multi-date selection. ### DayState ```vb Property Get DayState() As String Property Let DayState(ByVal Value As String) ``` Day state bitmap string that controls bold display of dates. ### MaxSelCount ```vb Property Get MaxSelCount() As Long Property Let MaxSelCount(ByVal Value As Long) ``` Maximum selectable days in multi-select mode. ### MonthColumns ```vb Property Get MonthColumns() As Long Property Let MonthColumns(ByVal Value As Long) ``` Number of months displayed horizontally. ### MonthRows ```vb Property Get MonthRows() As Long Property Let MonthRows(ByVal Value As Long) ``` Number of months displayed vertically. ### View ```vb Property Get View() As MvwViewConstants Property Let View(ByVal Value As MvwViewConstants) ``` Calendar view mode. ### UseShortestDayNames ```vb Property Get UseShortestDayNames() As Boolean Property Let UseShortestDayNames(ByVal Value As Boolean) ``` Whether to use the shortest day-of-week names. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` Foreground color. ### TitleBackColor ```vb Property Get TitleBackColor() As OLE_COLOR Property Let TitleBackColor(ByVal Value As OLE_COLOR) ``` Title background color. ### TitleForeColor ```vb Property Get TitleForeColor() As OLE_COLOR Property Let TitleForeColor(ByVal Value As OLE_COLOR) ``` Title foreground color. ### TrailingForeColor ```vb Property Get TrailingForeColor() As OLE_COLOR Property Let TrailingForeColor(ByVal Value As OLE_COLOR) ``` Foreground color for trailing dates. ### SelStart ```vb Property Get SelStart() As Date Property Let SelStart(ByVal Value As Date) ``` Start date of the selection range. ### SelEnd ```vb Property Get SelEnd() As Date Property Let SelEnd(ByVal Value As Date) ``` End date of the selection range. ### Today ```vb Property Get Today() As Date ``` Returns today's date. Read-only. ### SystemStartOfWeek ```vb Property Get SystemStartOfWeek() As Integer ``` Returns the system setting for the first day of the week. Read-only. ### DayOfWeek ```vb Property Get DayOfWeek() As Integer ``` Returns the day of the week corresponding to Value. Read-only. ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` Whether to enable visual styles. ### hWnd ```vb Property Get hWnd() As LongPtr ``` Window handle of the month view control. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Window handle of the user control. ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` Font. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` Mouse pointer style. See common enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` Custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Whether to enable mouse enter/leave tracking. ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` Right-to-left display direction. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` Right-to-left mode. See common enumerations. ### Name ```vb Property Get Name() As String ``` Control name. Read-only. ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` Custom data. ### Parent ```vb Property Get Parent() As Object ``` Parent object. Read-only. ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` Container object. ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` Left position. ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` Top position. ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` Width. ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` Height. ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` Whether the control is visible. ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` Tooltip text. ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` Help context ID. ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "What's This" help ID. ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` Drag icon. ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` Drag mode. ## Methods ### SetSelRange ```vb Public Sub SetSelRange(ByVal StartDate As Date, ByVal EndDate As Date) ``` Sets the date selection range. ### ComputeControlSize ```vb Public Sub ComputeControlSize() ``` Recalculates the control size based on current settings. ### GetMonthRange ```vb Public Function GetMonthRange() As String ``` Retrieves the currently displayed month range. ### HitTest ```vb Public Function HitTest(ByVal X As Single, ByVal Y As Single) As MvwHitResultConstants ``` Tests the hit area at the specified coordinates. ### Drag ```vb Public Sub Drag([ByRef Action As Variant]) ``` Starts, ends, or cancels a drag operation. ### SetFocus ```vb Public Sub SetFocus() ``` Moves focus to the control. ### ZOrder ```vb Public Sub ZOrder([ByRef Position As Variant]) ``` Sets the Z-order of the control. ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag-and-drop operation. ### Refresh ```vb Public Sub Refresh() ``` Forces the control to repaint. ## Events ### GetDayBold ```vb Public Event GetDayBold(ByRef DayState As String) ``` Fired when bold state for dates is needed. ### SelChange ```vb Public Event SelChange(ByVal StartDate As Date, ByVal EndDate As Date) ``` Fired when the selection range changes. ### DateClick ```vb Public Event DateClick(ByVal DateClicked As Date) ``` Fired when a date is clicked. ### ViewChange ```vb Public Event ViewChange() ``` Fired when the view mode changes. ### ContextMenu ```vb Public Event ContextMenu(ByRef Handled As Boolean, ByVal X As Single, ByVal Y As Single) ``` Fired when right-clicking or pressing Shift+F10. ### Click ```vb Public Event Click() ``` Fired when the control is clicked. ### DblClick ```vb Public Event DblClick() ``` Fired when the control is double-clicked. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when a mouse button is pressed. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when a mouse button is released. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when the mouse is moved. ### MouseEnter ```vb Public Event MouseEnter() ``` Fired when the mouse enters the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Fired when the mouse leaves the control. ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` Fired when a key is pressed. ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` Fired when a key is released. ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` Fired when a key character is input. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when an OLE drag-and-drop operation is completed. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` Fired when an OLE drag-and-drop operation passes over the control. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` Fired when the OLE drag-and-drop operation needs to change the cursor. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` Fired when an OLE drag-and-drop operation starts. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` Fired when an OLE drag-and-drop operation completes. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` Fired when the OLE drop target requests data. ## Code Examples ```vb ' Basic date selection MonthView1.Value = Date ' Limit selectable date range MonthView1.MinDate = #1/1/2025# MonthView1.MaxDate = #12/31/2025# ' Multi-date selection MonthView1.MultiSelect = True MonthView1.MaxSelCount = 7 Call MonthView1.SetSelRange(#1/1/2025#, #1/7/2025#) ' Multi-month display MonthView1.MonthColumns = 2 MonthView1.MonthRows = 1 ``` --- --- url: /en/official/Reference/VBRUN/Constants/MouseButtonConstants.md --- # MouseButtonConstants Bit flags for the *Button* argument of mouse events such as **MouseDown**, **MouseUp**, and **MouseMove**, identifying which buttons are pressed. Combine with `Or` to test for multiple buttons. | Constant | Value | Description | |----------|-------|-------------| | **vbLeftButton** | 1 | Left mouse button. | | **vbRightButton** | 2 | Right mouse button. | | **vbMiddleButton** | 4 | Middle mouse button. | --- --- url: /zh/official/Reference/VBRUN/Constants/MouseButtonConstants.md --- # MouseButtonConstants **MouseDown**、**MouseUp**和**MouseMove**等鼠标事件的*Button*参数的位标志,标识按下了哪些按钮。使用`Or`组合以测试多个按钮。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbLeftButton** | 1 | 鼠标左键。 | | **vbRightButton** | 2 | 鼠标右键。 | | **vbMiddleButton** | 4 | 鼠标中键。 | --- --- url: /en/official/Reference/VBRUN/Constants/MousePointerConstants.md --- # MousePointerConstants Cursor-shape values for the **MousePointer** property of forms and controls. ## Standard cursors | Constant | Value | Description | |----------|-------|-------------| | **vbDefault** | 0 | The default --- usually an arrow. | | **vbArrow** | 1 | Arrow. | | **vbCrosshair** | 2 | Crosshair. | | **vbIbeam** | 3 | I-beam (text-edit cursor). | | **vbIconPointer** | 4 | Icon (small square inside a square). | | **vbSizePointer** | 5 | Four-headed sizing arrow. | | **vbSizeNESW** | 6 | Diagonal resize arrow (north-east / south-west). | | **vbSizeNS** | 7 | Vertical resize arrow. | | **vbSizeNWSE** | 8 | Diagonal resize arrow (north-west / south-east). | | **vbSizeWE** | 9 | Horizontal resize arrow. | | **vbUpArrow** | 10 | Up arrow. | | **vbHourglass** | 11 | Hourglass (busy). | | **vbNoDrop** | 12 | "No drop" symbol. | | **vbArrowHourglass** | 13 | Arrow with an hourglass (working in background). | | **vbArrowQuestion** | 14 | Arrow with a question mark. | | **vbSizeAll** | 15 | Resize-all (four-headed) arrow. | | **vbCustom** | 99 | The bitmap supplied by the **MouseIcon** property is used. | ## twinBASIC additions | Constant | Value | Description | |----------|-------|-------------| | **vbHand** | 16 | Pointing hand (link cursor). | | **vbPin** | 17 | Pin. | | **vbPerson** | 18 | Person. | | **vbArrowCD** | 19 | Arrow with a CD. | | **vbScrollN** | 20 | Auto-scroll arrow pointing north. | | **vbScrollS** | 21 | Auto-scroll arrow pointing south. | | **vbScrollE** | 22 | Auto-scroll arrow pointing east. | | **vbScrollW** | 23 | Auto-scroll arrow pointing west. | | **vbScrollNS** | 24 | Auto-scroll arrow pointing north--south. | | **vbScrollWE** | 25 | Auto-scroll arrow pointing west--east. | | **vbScrollNW** | 26 | Auto-scroll arrow pointing north-west. | | **vbScrollNE** | 27 | Auto-scroll arrow pointing north-east. | | **vbScrollSW** | 28 | Auto-scroll arrow pointing south-west. | | **vbScrollSE** | 29 | Auto-scroll arrow pointing south-east. | | **vbScrollAll** | 30 | Auto-scroll all-directions cursor. | | **vbPen** | 31 | Pen (digitiser stylus). | --- --- url: /zh/official/Reference/VBRUN/Constants/MousePointerConstants.md --- # MousePointerConstants 窗体和控件的**MousePointer**属性的光标形状值。 ## 标准光标 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbDefault** | 0 | 默认 --- 通常为箭头。 | | **vbArrow** | 1 | 箭头。 | | **vbCrosshair** | 2 | 十字准线。 | | **vbIbeam** | 3 | I形光标(文本编辑光标)。 | | **vbIconPointer** | 4 | 图标(方框内的小方块)。 | | **vbSizePointer** | 5 | 四向调整大小箭头。 | | **vbSizeNESW** | 6 | 对角调整大小箭头(东北/西南)。 | | **vbSizeNS** | 7 | 垂直调整大小箭头。 | | **vbSizeNWSE** | 8 | 对角调整大小箭头(西北/东南)。 | | **vbSizeWE** | 9 | 水平调整大小箭头。 | | **vbUpArrow** | 10 | 上箭头。 | | **vbHourglass** | 11 | 沙漏(忙碌)。 | | **vbNoDrop** | 12 | "禁止放置"符号。 | | **vbArrowHourglass** | 13 | 箭头带沙漏(后台工作中)。 | | **vbArrowQuestion** | 14 | 箭头带问号。 | | **vbSizeAll** | 15 | 四向调整大小箭头。 | | **vbCustom** | 99 | 使用**MouseIcon**属性提供的位图。 | ## twinBASIC新增 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbHand** | 16 | 手形指针(链接光标)。 | | **vbPin** | 17 | 图钉。 | | **vbPerson** | 18 | 人形。 | | **vbArrowCD** | 19 | 箭头带CD。 | | **vbScrollN** | 20 | 自动滚动箭头,朝北。 | | **vbScrollS** | 21 | 自动滚动箭头,朝南。 | | **vbScrollE** | 22 | 自动滚动箭头,朝东。 | | **vbScrollW** | 23 | 自动滚动箭头,朝西。 | | **vbScrollNS** | 24 | 自动滚动箭头,南北方向。 | | **vbScrollWE** | 25 | 自动滚动箭头,东西方向。 | | **vbScrollNW** | 26 | 自动滚动箭头,朝西北。 | | **vbScrollNE** | 27 | 自动滚动箭头,朝东北。 | | **vbScrollSW** | 28 | 自动滚动箭头,朝西南。 | | **vbScrollSE** | 29 | 自动滚动箭头,朝东南。 | | **vbScrollAll** | 30 | 自动滚动全方向光标。 | | **vbPen** | 31 | 画笔(数位板手写笔)。 | --- --- url: /en/official/Reference/VBA/Interaction/MsgBox.md --- # MsgBox Displays a message in a modal dialog with a chosen set of buttons, waits for the user to click a button, and returns a [**VbMsgBoxResult**](/en/official/Reference/VBA/Constants/VbMsgBoxResult) value identifying that button. Syntax: **MsgBox(** *prompt* \[ **,** *buttons* ] \[ **,** *title* ] \[ **,** *helpfile* **,** *context* ] **)** *prompt* : *required* String expression displayed as the message in the dialog box. The maximum length of *prompt* is approximately 1024 characters, depending on the width of the characters used. To break *prompt* across multiple lines, separate the lines with a carriage return (`Chr(13)`), a linefeed (`Chr(10)`), or a CR-LF combination (`vbCrLf`). *buttons* : *optional* A [**VbMsgBoxStyle**](/en/official/Reference/VBA/Constants/VbMsgBoxStyle) value that specifies the number and type of buttons to display, the icon style, the identity of the default button, and the modality of the message box. If omitted, *buttons* defaults to `vbOKOnly`. *title* : *optional* String expression displayed in the title bar of the dialog box. If omitted, the application name is used. *helpfile* : *optional* String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If *helpfile* is supplied, *context* must also be supplied. *context* : *optional* Numeric expression giving the Help context number assigned to the relevant Help topic. If *context* is supplied, *helpfile* must also be supplied. The *buttons* argument is a combination of values from the [**VbMsgBoxStyle**](/en/official/Reference/VBA/Constants/VbMsgBoxStyle) enumeration: one *button group* value (`vbOKOnly`, `vbOKCancel`, `vbAbortRetryIgnore`, `vbYesNoCancel`, `vbYesNo`, `vbRetryCancel`, `vbCancelTryAgainContinue`), optionally combined with one *icon* value (`vbCritical`, `vbQuestion`, `vbExclamation`, `vbInformation`), one *default-button* value (`vbDefaultButton1` through `vbDefaultButton4`), one *modality* value (`vbApplicationModal`, `vbSystemModal`), and any of the option flags (`vbMsgBoxHelpButton`, `vbMsgBoxSetForeground`, `vbMsgBoxRight`, `vbMsgBoxRtlReading`). Combine values with **Or** or addition. The return value is one of the constants from the [**VbMsgBoxResult**](/en/official/Reference/VBA/Constants/VbMsgBoxResult) enumeration, identifying which button the user clicked. If the dialog box displays a **Cancel** button, pressing the ESC key has the same effect as clicking **Cancel**. When both *helpfile* and *context* are supplied, the user can press F1 to view the relevant Help topic; if the dialog also contains a **Help** button, clicking it invokes context-sensitive Help. The dialog stays open and **MsgBox** does not return until one of the non-Help buttons is clicked. ::: info To pass any argument by name (other than the first), use **MsgBox** in an expression context --- for example, assign its result to a variable. To skip a positional argument, include the corresponding comma delimiter. ::: ### Example This example displays a critical-error message in a dialog with **Yes** and **No** buttons; the **No** button is the default. The value returned by **MsgBox** depends on the button the user clicks. ```vb Dim Style As VbMsgBoxStyle Dim Response As VbMsgBoxResult Style = vbYesNo Or vbCritical Or vbDefaultButton2 Response = MsgBox("Do you want to continue?", Style, "MsgBox Demonstration") If Response = vbYes Then ' User chose Yes — perform the action. Else ' User chose No — back out. End If ``` ### See Also * [InputBox](/en/official/Reference/VBA/Interaction/InputBox) function * [VbMsgBoxStyle](/en/official/Reference/VBA/Constants/VbMsgBoxStyle) enumeration * [VbMsgBoxResult](/en/official/Reference/VBA/Constants/VbMsgBoxResult) enumeration --- --- url: /zh/official/Reference/VBA/Interaction/MsgBox.md --- # MsgBox 在模式对话框中显示消息,带有选定的按钮集,等待用户点击按钮,并返回一个[**VbMsgBoxResult**](/official/Reference/VBA/Constants/VbMsgBoxResult)值标识该按钮。 语法:**MsgBox(** *prompt* \[ **,** *buttons* ] \[ **,** *title* ] \[ **,** *helpfile* **,** *context* ] **)** *prompt* : *必需* 字符串表达式,在对话框中显示为消息。*prompt*的最大长度约为1024个字符,取决于所使用字符的宽度。要将*prompt*分为多行,请用回车符(`Chr(13)`)、换行符(`Chr(10)`)或CR-LF组合(`vbCrLf`)分隔各行。 *buttons* : *可选* [**VbMsgBoxStyle**](/official/Reference/VBA/Constants/VbMsgBoxStyle)值,指定要显示的按钮数量和类型、图标样式、默认按钮标识和消息框的模态性。如果省略,*buttons*默认为`vbOKOnly`。 *title* : *可选* 字符串表达式,显示在对话框的标题栏中。如果省略,则使用应用程序名称。 *helpfile* : *可选* 字符串表达式,标识用于为对话框提供上下文相关帮助的帮助文件。如果提供了*helpfile*,则还必须提供*context*。 *context* : *可选* 数值表达式,给出分配给相关帮助主题的帮助上下文编号。如果提供了*context*,则还必须提供*helpfile*。 *buttons*参数是[**VbMsgBoxStyle**](/official/Reference/VBA/Constants/VbMsgBoxStyle)枚举值的组合:一个*按钮组*值(`vbOKOnly`、`vbOKCancel`、`vbAbortRetryIgnore`、`vbYesNoCancel`、`vbYesNo`、`vbRetryCancel`、`vbCancelTryAgainContinue`),可选结合一个*图标*值(`vbCritical`、`vbQuestion`、`vbExclamation`、`vbInformation`),一个*默认按钮*值(`vbDefaultButton1`到`vbDefaultButton4`),一个*模态性*值(`vbApplicationModal`、`vbSystemModal`),以及任何选项标志(`vbMsgBoxHelpButton`、`vbMsgBoxSetForeground`、`vbMsgBoxRight`、`vbMsgBoxRtlReading`)。使用**Or**或加法组合值。 返回值是[**VbMsgBoxResult**](/official/Reference/VBA/Constants/VbMsgBoxResult)枚举中的常量之一,标识用户点击的按钮。 如果对话框显示**Cancel**按钮,按ESC键与点击**Cancel**效果相同。同时提供*helpfile*和*context*时,用户可以按F1查看相关帮助主题;如果对话框还包含**Help**按钮,点击它会调用上下文相关帮助。对话框保持打开状态,**MsgBox**在点击非Help按钮之一之前不会返回。 ::: info 要按名称传递任何参数(第一个除外),请在表达式上下文中使用**MsgBox**——例如,将其结果赋给变量。要跳过位置参数,请包含相应的逗号分隔符。 ::: ### 示例 本示例在带有**Yes**和**No**按钮的对话框中显示严重错误消息;**No**按钮为默认按钮。**MsgBox**返回的值取决于用户点击的按钮。 ```vb Dim Style As VbMsgBoxStyle Dim Response As VbMsgBoxResult Style = vbYesNo Or vbCritical Or vbDefaultButton2 Response = MsgBox("Do you want to continue?", Style, "MsgBox Demonstration") If Response = vbYes Then ' User chose Yes — perform the action. Else ' User chose No — back out. End If ``` ### 另请参阅 * [InputBox](/official/Reference/VBA/Interaction/InputBox)函数 * [VbMsgBoxStyle](/official/Reference/VBA/Constants/VbMsgBoxStyle)枚举 * [VbMsgBoxResult](/official/Reference/VBA/Constants/VbMsgBoxResult)枚举 --- --- url: /en/official/Reference/VB/MultiFrame.md --- # MultiFrame class A **MultiFrame** is a layout container that arranges a set of [**Frame**](/en/official/Reference/VB/Frame/) controls in a single horizontal or vertical strip and resizes them whenever the **MultiFrame** itself is resized. Each contained frame keeps its own border, caption, and child controls; the **MultiFrame** decides only where each frame is placed and how wide (or tall) it is. A frame is associated with a **MultiFrame** by setting the frame's [**Container**](/en/official/Reference/VB/Frame/#container) to point at the **MultiFrame**. The frame's [**MultiFramePosition**](/en/official/Reference/VB/Frame/#multiframeposition) chooses its place in the sequence and [**MultiFrameSize**](/en/official/Reference/VB/Frame/#multiframesize) gives its size as a percentage of the **MultiFrame**'s usable extent. Frames whose **MultiFrameSize** is `0` share whatever extent remains after the fixed-size frames have been laid out. The default event is [**Initialize**](#initialize). There is no default property. ```vb Private Sub Form_Load() mfPanels.Direction = vbDirectionHorizontal Set fraLeft.Container = mfPanels fraLeft.MultiFramePosition = 0 fraLeft.MultiFrameSize = 30 ' fixed 30% of the strip Set fraCenter.Container = mfPanels fraCenter.MultiFramePosition = 1 fraCenter.MultiFrameSize = 0 ' shares the remaining space Set fraRight.Container = mfPanels fraRight.MultiFramePosition = 2 fraRight.MultiFrameSize = 0 ' shares the remaining space End Sub ``` ## Direction and sizing [**Direction**](#direction) chooses between **vbDirectionHorizontal** (the default --- frames laid out left-to-right) and **vbDirectionVertical** (frames stacked top-to-bottom). Changing **Direction** at run time triggers an immediate re-layout. For each contained frame, [**MultiFrameSize**](/en/official/Reference/VB/Frame/#multiframesize) gives its extent as a percentage of the **MultiFrame**'s width (horizontal) or height (vertical). Frames whose **MultiFrameSize** is `0` share the leftover extent equally --- so a typical pattern is to give the edge panels fixed percentages and leave one centre panel at `0` so it absorbs window resizes. Percentages are not clamped; if the fixed-size frames already exceed the **MultiFrame**'s extent the auto-sized frames collapse to zero. ## Position and shuffling Each contained frame is anchored to a sequential position via its [**MultiFramePosition**](/en/official/Reference/VB/Frame/#multiframeposition) property (zero-based). Positions are kept contiguous: assigning a frame a new **MultiFramePosition** at run time makes the **MultiFrame** shuffle the remaining frames up or down so that the old slot closes and the new slot opens at the requested index. Duplicate or out-of-range positions are normalised at the next layout pass --- the **MultiFrame** falls back to the original control order on the parent form, renumbering the frames sequentially from `0`. A frame whose [**Container**](/en/official/Reference/VB/Frame/#container) is the **MultiFrame** but whose **MultiFramePosition** is `-1` is appended at the next free slot the first time the layout is built. ## Adopting frames at run time The mapping from frame to **MultiFrame** is discovered from the parent form's control collection on each layout pass: a frame appears in the strip exactly when its [**Container**](/en/official/Reference/VB/Frame/#container) property points at the **MultiFrame**. The discovered set is then cached. To force the cache to be rebuilt --- for example after re-parenting a frame at run time --- assign any value to [**FramesCount**](#framescount): ```vb Set fraExtra.Container = mfPanels mfPanels.FramesCount = 0 ' assigned value is ignored; the layout cache is rebuilt ``` The **MultiFrame** repositions the frame's existing window in place; it does not change the frame's Win32 parent, so the frame remains a child of the form and continues to raise its events normally. ## Properties ### Anchors The set of edges of the parent that the **MultiFrame**'s corresponding edges follow when the parent resizes. Read-only --- assign individual `.Left`, `.Top`, `.Right`, `.Bottom` flags through the returned **Anchors** object. ### BackColor The background colour of the **MultiFrame**'s drawing surface, as an **OLE\_COLOR**. Defaults to the system window-background colour. Visible only where the contained frames do not fully cover the extent --- e.g. when their **MultiFrameSize**s sum to less than 100%. ### Container The control that hosts this **MultiFrame** --- typically the form. Read with **Get**, change with **Set**. Setting **Container** re-parents the **MultiFrame** to a different container at run time. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control. Always **vbShape**. ### Direction The orientation in which contained frames are laid out. A member of **MultiFrameDirectionConstants**: **vbDirectionHorizontal** (0, default --- frames laid out left-to-right) or **vbDirectionVertical** (1 --- frames stacked top-to-bottom). Changing **Direction** triggers an immediate re-layout of the contained frames. ### Dock Where the **MultiFrame** is docked within its container. A member of [**DockModeConstants**](/en/official/Reference/VBRUN/Constants/DockModeConstants): **vbDockNone** (default), **vbDockLeft**, **vbDockTop**, **vbDockRight**, **vbDockBottom**, or **vbDockFill**. Docked **MultiFrame**s ignore [**Anchors**](#anchors). ### FramesCount The number of [**Frame**](/en/official/Reference/VB/Frame/) controls currently in the **MultiFrame**'s layout. **Long**. Syntax: *object*.**FramesCount** \[ = *value* ] Reading **FramesCount** returns the size of the current layout cache. Assigning *any* value discards the cache so it is rebuilt on the next layout pass --- the assigned number itself is ignored. Use the assignment as a manual refresh after re-parenting a frame at run time. ### Height The **MultiFrame**'s height, in twips by default (or in the container's **ScaleMode** units). **Double**. ### hWnd The Win32 window handle for the **MultiFrame**'s drawing surface, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the **MultiFrame** is part of a control array, the **Long** zero-based index of this instance within the array. Reading **Index** on a non-array instance raises run-time error 343 (*Object not an array*). Read-only at run time. ### Left The horizontal distance from the left edge of the container to the left edge of the **MultiFrame**. **Double**. ### Name The unique design-time name of the **MultiFrame** on its parent form. Read-only at run time. ### Parent A reference to the [**Form**](/en/official/Reference/VB/Form/) that ultimately contains the **MultiFrame**. Read-only. Distinct from [**Container**](#container), which returns the immediate parent. ### TabIndex The position of the **MultiFrame** in the form's TAB-key navigation order. **Long**. ::: info A **MultiFrame** never takes the focus itself --- **TabIndex** is preserved for compatibility but has no observable effect on the user. ::: ### TabStop Whether the **MultiFrame** participates in TAB-key navigation. **Boolean**, default **True**. ::: info A **MultiFrame** never takes the focus itself --- **TabStop** is preserved for compatibility but has no observable effect on the user. ::: ### Tag A free-form **String** the application can use to associate custom data with the **MultiFrame**. Ignored by the framework. ### Top The vertical distance from the top of the container to the top of the **MultiFrame**. **Double**. ### Visible Whether the **MultiFrame** is shown. **Boolean**, default **True**. The contained frames' own visibility is independent of this setting; hiding the **MultiFrame** hides its drawing surface but does not directly hide the frames. ### Width The **MultiFrame**'s width. **Double**. ## Methods ### Move Repositions and optionally resizes the **MultiFrame** in a single call. Contained frames are re-laid out to match the new extent. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### Refresh Forces an immediate repaint of the **MultiFrame**'s drawing surface. Syntax: *object*.**Refresh** ### ZOrder Brings the **MultiFrame** to the front or back of its sibling stack within the container. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Initialize Raised once, after the **MultiFrame**'s underlying window has been created but before the first layout pass has run. Useful for adjusting [**Direction**](#direction) or contained-frame sizes from code at start-up so that the very first layout reflects them. **Default event.** Syntax: *object*\_**Initialize**( ) --- --- url: /zh/official/Reference/VB/MultiFrame.md --- # MultiFrame 类 **MultiFrame**是一个布局容器,将一组[**Frame**](/official/Reference/VB/Frame/)控件排列在单条水平或垂直带中,并在**MultiFrame**自身调整大小时调整它们的尺寸。每个包含的框架保留自己的边框、标题和子控件;**MultiFrame**仅决定每个框架的位置和宽度(或高度)。 通过将框架的[**Container**](/official/Reference/VB/Frame/#container)设置为指向**MultiFrame**来关联框架。框架的[**MultiFramePosition**](/official/Reference/VB/Frame/#multiframeposition)选择其在序列中的位置,[**MultiFrameSize**](/official/Reference/VB/Frame/#multiframesize)给出其尺寸作为**MultiFrame**可用范围的百分比。**MultiFrameSize**为`0`的框架共享固定尺寸框架布局后剩余的范围。 默认事件是[**Initialize**](#initialize)。没有默认属性。 ```vb Private Sub Form_Load() mfPanels.Direction = vbDirectionHorizontal Set fraLeft.Container = mfPanels fraLeft.MultiFramePosition = 0 fraLeft.MultiFrameSize = 30 ' fixed 30% of the strip Set fraCenter.Container = mfPanels fraCenter.MultiFramePosition = 1 fraCenter.MultiFrameSize = 0 ' shares the remaining space Set fraRight.Container = mfPanels fraRight.MultiFramePosition = 2 fraRight.MultiFrameSize = 0 ' shares the remaining space End Sub ``` ## 方向和尺寸 [**Direction**](#direction)选择**vbDirectionHorizontal**(默认——框架从左到右排列)或**vbDirectionVertical**(框架从上到下堆叠)。在运行时更改**Direction**会触发立即重新布局。 对于每个包含的框架,[**MultiFrameSize**](/official/Reference/VB/Frame/#multiframesize)给出其范围作为**MultiFrame**宽度(水平)或高度(垂直)的百分比。**MultiFrameSize**为`0`的框架平均共享剩余范围——因此典型模式是给边缘面板固定百分比,将一个中心面板保持为`0`使其吸收窗口调整大小。百分比不会被钳制;如果固定尺寸框架已超过**MultiFrame**的范围,自动调整尺寸的框架会收缩为零。 ## 位置和重排 每个包含的框架通过其[**MultiFramePosition**](/official/Reference/VB/Frame/#multiframeposition)属性(零基)锚定到顺序位置。位置保持连续:在运行时为框架分配新的**MultiFramePosition**会使**MultiFrame**将其余框架上移或下移,使旧槽位关闭并在请求的索引处打开新槽位。重复或超出范围的位置在下一次布局传递时被规范化——**MultiFrame**回退到父窗体上的原始控件顺序,从`0`开始对框架重新编号。 [**Container**](/official/Reference/VB/Frame/#container)是**MultiFrame**但**MultiFramePosition**为`-1`的框架在首次构建布局时被附加到下一个空闲槽位。 ## 在运行时采用框架 框架到**MultiFrame**的映射在每次布局传递时从父窗体的控件集合中发现:当框架的[**Container**](/official/Reference/VB/Frame/#container)属性指向**MultiFrame**时,框架出现在带中。发现集随后被缓存。要强制重建缓存——例如在运行时重新设置框架的父级后——给[**FramesCount**](#framescount)赋任意值: ```vb Set fraExtra.Container = mfPanels mfPanels.FramesCount = 0 ' assigned value is ignored; the layout cache is rebuilt ``` **MultiFrame**在原地重新定位框架的现有窗口;它不会更改框架的Win32父级,因此框架仍然是窗体的子级并继续正常引发其事件。 ## 属性 ### Anchors 决定控件的哪些边随容器对应边调整的**Anchors**对象集合。只读——通过返回的**Anchors**对象设置各个`.Left`、`.Top`、`.Right`、`.Bottom`标志。 ### BackColor **MultiFrame**绘图表面的背景色,作为**OLE\_COLOR**。默认为系统窗口背景色。仅在包含的框架未完全覆盖范围时可见——例如当其**MultiFrameSize**之和小于100%时。 ### Container 承载此**MultiFrame**的控件——通常是窗体。用**Get**读取,用**Set**更改。设置**Container**在运行时将**MultiFrame**重新设置为其他容器的子级。 ### ControlType 标识此控件的只读[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值。始终为**vbShape**。 ### Direction 包含框架的布局方向。**MultiFrameDirectionConstants**的成员:**vbDirectionHorizontal**(0,默认——框架从左到右排列)或**vbDirectionVertical**(1——框架从上到下堆叠)。更改**Direction**会触发包含框架的立即重新布局。 ### Dock **MultiFrame**在其容器中的停靠位置。[**DockModeConstants**](/official/Reference/VBRUN/Constants/DockModeConstants)的成员:**vbDockNone**(默认)、**vbDockLeft**、**vbDockTop**、**vbDockRight**、**vbDockBottom**或**vbDockFill**。停靠的**MultiFrame**忽略[**Anchors**](#anchors)。 ### FramesCount **MultiFrame**布局中当前[**Frame**](/official/Reference/VB/Frame/)控件的数量。**Long**。 语法:*object*.**FramesCount** \[ = *value* ] 读取**FramesCount**返回当前布局缓存的大小。赋任意值会丢弃缓存使其在下一次布局传递时重建——所赋的数值本身被忽略。将赋值用作运行时重新设置框架父级后的手动刷新。 ### Height **MultiFrame**的高度,默认以缇为单位(或以容器的**ScaleMode**单位)。**Double**。 ### hWnd **MultiFrame**绘图表面的Win32窗口句柄,作为**LongPtr**。只读。适用于传递给API函数。 ### Index 当**MultiFrame**是控件数组的一部分时,此实例在数组中的**Long**零基索引。在非数组实例上读取**Index**会引发运行时错误343(*对象不是数组*)。运行时只读。 ### Left 从容器的左边缘到**MultiFrame**左边缘的水平距离。**Double**。 ### Name **MultiFrame**在其父窗体上的唯一设计时名称。运行时只读。 ### Parent 对最终包含**MultiFrame**的[**Form**](/official/Reference/VB/Form/)的引用。只读。与[**Container**](#container)不同,后者返回直接父级。 ### TabIndex **MultiFrame**在窗体TAB键导航顺序中的位置。**Long**。 ::: info **MultiFrame**自身从不获取焦点——**TabIndex**保留用于兼容但对用户无可见效果。 ::: ### TabStop **MultiFrame**是否参与TAB键导航。**Boolean**,默认**True**。 ::: info **MultiFrame**自身从不获取焦点——**TabStop**保留用于兼容但对用户无可见效果。 ::: ### Tag 应用程序可用于将自定义数据与**MultiFrame**关联的自由格式**String**。框架忽略此属性。 ### Top 从容器顶部到**MultiFrame**顶部的垂直距离。**Double**。 ### Visible **MultiFrame**是否显示。**Boolean**,默认**True**。包含框架自身的可见性与此设置无关;隐藏**MultiFrame**隐藏其绘图表面但不直接隐藏框架。 ### Width **MultiFrame**的宽度。**Double**。 ## 方法 ### Move 在单次调用中重新定位并可选地调整**MultiFrame**的尺寸。包含的框架会重新布局以匹配新的范围。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### Refresh 强制立即重绘**MultiFrame**的绘图表面。 语法:*object*.**Refresh** ### ZOrder 将**MultiFrame**带到容器内同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront**(0,默认)或**vbSendToBack**(1)。 ## 事件 ### Initialize 在**MultiFrame**的底层窗口已创建但第一次布局传递尚未运行后引发一次。适用于在启动时从代码调整[**Direction**](#direction)或包含框架的尺寸,使第一次布局就反映这些设置。**默认事件。** 语法:*object*\_**Initialize**( ) --- --- url: /en/official/Reference/VBRUN/Constants/MultiSelectConstants.md --- # MultiSelectConstants Multi-selection mode values for the **MultiSelect** property of a list-box control. | Constant | Value | Description | |----------|-------|-------------| | **vbMultiSelectNone** | 0 | Only one item can be selected at a time. | | **vbMultiSelectSimple** | 1 | Each click toggles the clicked item's selection. | | **vbMultiSelectExtended** | 2 | The user can select ranges with **Shift** + click and toggle individual items with **Ctrl** + click. | --- --- url: /zh/official/Reference/VBRUN/Constants/MultiSelectConstants.md --- # MultiSelectConstants 列表框控件的**MultiSelect**属性的多选模式值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbMultiSelectNone** | 0 | 一次只能选择一项。 | | **vbMultiSelectSimple** | 1 | 每次点击切换所点击项的选择状态。 | | **vbMultiSelectExtended** | 2 | 用户可用**Shift**+点击选择范围,**Ctrl**+点击切换单项。 | --- --- url: /en/official/Features/Advanced/Multithreading.md --- # Thread Safety / Multithreading Support While there's no native language syntax yet (planned), you can call `CreateThread` directly with no hacks. Previously, VBx and other BASIC languages typically required elaborate workarounds to be able to use `CreateThread` for anything but some specialized, extremely simple things. In twinBASIC, you can call it and all other threading APIs without any special steps, other than of course the careful management of doing threading at a low level like this. ## Example In a new Standard EXE project, add a CommandButton and TextBox to your form: ```vb Private Declare PtrSafe Function GetCurrentThreadId Lib "kernel32" () As Long Private Declare PtrSafe Function CreateThread Lib "kernel32" ( _ ByRef lpThreadAttributes As Any, _ ByVal dwStackSize As Long, _ ByVal lpStartAddress As LongPtr, _ ByRef lpParameter As Any, _ ByVal dwCreationFlags As Long, _ ByRef lpThreadId As Long) As LongPtr Private Declare PtrSafe Function WaitForSingleObject Lib "kernel32" ( _ ByVal hHandle As LongPtr, _ ByVal dwMilliseconds As Long) As Long Private Const INFINITE = -1& Private Sub Command1_Click() Handles Command1.Click Dim lTID As Long Dim lCurTID As Long Dim hThreadNew As LongPtr lCurTID = GetCurrentThreadId() hThreadNew = CreateThread(ByVal 0, 0, AddressOf TestThread, ByVal 0, 0, lTID) Text1.Text = "Thread " & lCurTID & " is waiting on thread " & lTID Dim hr As Long hr = WaitForSingleObject(hThreadNew, 30000&) 'Wait 30s as a default. You can use INFINITE instead if you never want to time out. Text1.Text = "Wait end code " & CStr(hr) End Sub Public Sub TestThread() MsgBox "Hello thread" End Sub ``` Under a single-threaded code, if you called `TestThread` before updating `Text1.Text`, the text wouldn't update until you clicked ok on the message box. But here, the message box in launched in a separate thread, so execution continues and updates the text, after which we manually choose to wait for the message box thread to exit. --- --- url: /en/official/Reference/Core/Name.md --- # Name Renames a disk file, directory, or folder. Syntax: > **Name** *oldpathname* **As** *newpathname* *oldpathname* : String expression that specifies the existing file name and location; may include directory or folder, and drive. *newpathname* : String expression that specifies the new file name and location; may include directory or folder, and drive. The file name specified by *newpathname* can't already exist. The **Name** statement renames a file and moves it to a different directory or folder, if necessary. **Name** can move a file across drives, but it can only rename an existing directory or folder when both *newpathname* and *oldpathname* are located on the same drive. **Name** cannot create a new file, directory, or folder. Using **Name** on an open file produces an error. An open file must be closed before renaming it. **Name** arguments cannot include multiple-character (`*`) and single-character (`?`) wildcards. ### Example This example uses the **Name** statement to rename a file. For purposes of this example, assume that the directories or folders that are specified already exist. ```vb Dim oldName, newName oldName = "OLDFILE": newName = "NEWFILE" ' Define file names. Name oldName As newName ' Rename file. oldName = "C:\MYDIR\OLDFILE": newName = "C:\YOURDIR\NEWFILE" Name oldName As newName ' Move and rename file. ``` ### See Also * [**Kill** statement](/en/official/Reference/VBA/FileSystem/Kill) * [**FileCopy** procedure](/en/official/Reference/VBA/FileSystem/FileCopy) * [**MkDir** statement](/en/official/Reference/VBA/FileSystem/MkDir) * [**RmDir** statement](/en/official/Reference/VBA/FileSystem/RmDir) --- --- url: /zh/official/Reference/Core/Name.md --- # Name 重命名磁盘文件、目录或文件夹。 语法: > **Name** *oldpathname* **As** *newpathname* *oldpathname* : 指定现有文件名和位置的字符串表达式;可以包含目录或文件夹以及驱动器。 *newpathname* : 指定新文件名和位置的字符串表达式;可以包含目录或文件夹以及驱动器。*newpathname*指定的文件名不能已存在。 **Name**语句重命名文件,如有必要可将文件移动到不同的目录或文件夹。**Name**可以跨驱动器移动文件,但只有当*newpathname*和*oldpathname*位于同一驱动器时才能重命名现有目录或文件夹。**Name**不能创建新文件、目录或文件夹。 对已打开的文件使用**Name**会产生错误。重命名前必须先关闭已打开的文件。**Name**参数不能包含多字符(`*`)和单字符(`?`)通配符。 ### 示例 本示例使用**Name**语句重命名文件。在此示例中,假设指定的目录或文件夹已存在。 ```vb Dim oldName, newName oldName = "OLDFILE": newName = "NEWFILE" ' Define file names. Name oldName As newName ' Rename file. oldName = "C:\MYDIR\OLDFILE": newName = "C:\YOURDIR\NEWFILE" Name oldName As newName ' Move and rename file. ``` ### 另请参阅 * [**Kill** 语句](/official/Reference/VBA/FileSystem/Kill) * [**FileCopy** 过程](/official/Reference/VBA/FileSystem/FileCopy) * [**MkDir** 语句](/official/Reference/VBA/FileSystem/MkDir) * [**RmDir** 语句](/official/Reference/VBA/FileSystem/RmDir) --- --- url: /en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection.md --- # NamedPipeClientConnection class One client-side connection to a named pipe. Produced by [**NamedPipeClientManager.Connect**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientManager#connect). Carries the connection-lifecycle events ([**Connected**](#connected), [**Disconnected**](#disconnected)) and the message events ([**MessageReceived**](#messagereceived), [**MessageSent**](#messagesent)), plus the [**AsyncRead**](#asyncread) / [**AsyncWrite**](#asyncwrite) / [**AsyncClose**](#asyncclose) methods that trigger them. The class is tagged `[COMCreatable(False)]` and its constructor takes a package-private interface --- reach instances only through [**NamedPipeClientManager.Connect**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientManager#connect). ::: warning The package `_README.txt` states: *"you MUST call **AsyncClose** on the client side, otherwise the connection is left alive when the object goes out of scope"*. Either call [**AsyncClose**](#asyncclose) explicitly before dropping the last reference, **or** let the object terminate cleanly through its `Class_Terminate` (which calls [**AsyncClose**](#asyncclose) automatically). Holding the reference forever --- in a module-level **Collection**, for example --- without calling [**AsyncClose**](#asyncclose) keeps the pipe handle open and the IOCP thread alive. ::: ```vb Private manager As NamedPipeClientManager Private WithEvents connection As NamedPipeClientConnection Private Sub Form_Load() Set manager = New NamedPipeClientManager Set connection = manager.Connect("MyService") End Sub Private Sub connection_Connected() connection.AsyncWrite StrConv("hello", vbFromUnicode) End Sub Private Sub connection_MessageReceived(ByRef Cookie As Variant, ByRef Data() As Byte) Debug.Print "reply: " & StrConv(Data, vbUnicode) End Sub Private Sub Form_Unload(Cancel As Integer) connection.AsyncClose End Sub ``` See the package [overview](/en/official/Reference/WinNamedPipesLib/) for the IOCP / event-marshalling architecture, the cookie correlation pattern, and the transient lifetime of `Data() As Byte` inside events. ## Properties ### CustomData A per-connection opaque slot the consumer can attach state to --- typically a session object or a pending-replies dictionary tied to this one connection. **Variant**, default **Empty**. The package never reads or writes this field. ### Handle The underlying Win32 file handle returned by `CreateFileW("\\.\pipe\<PipeName>")`. **LongPtr**. Exposed for low-level / debugging use --- most consumers can ignore it. Do not call `CloseHandle` on this value directly; use [**AsyncClose**](#asyncclose) so the IOCP loop and the parent manager's bookkeeping stay consistent. ### PipeName The leaf pipe name this connection was opened against --- the same value that was passed to [**NamedPipeClientManager.Connect**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientManager#connect). **String**. Read-only in practice; the package sets it from the constructor argument and never changes it. ## Events ### Connected Fires once the asynchronous `CreateFileW` started by [**NamedPipeClientManager.Connect**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientManager#connect) has succeeded and the pipe is ready for message exchange. Syntax: *connection*\_**Connected**() ### Disconnected Fires once the pipe has dropped *and* every outstanding asynchronous I/O against the connection has returned. The connection object is no longer usable for I/O after this event. Syntax: *connection*\_**Disconnected**() ### MessageReceived Fires when a complete message has been read from the pipe. Syntax: *connection*\_**MessageReceived**(**ByRef** *Cookie* **As Variant**, **ByRef** *Data*() **As Byte**) *Cookie* : The opaque correlation value originally passed to the [**AsyncRead**](#asyncread) that produced this read --- or **Empty** if the read came from the auto-issued reads triggered by [**NamedPipeClientManager.ContinuouslyReadFromPipe**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientManager#continuouslyreadfrompipe). *Data* : The message payload. See [Working with `Data() As Byte` in events](/en/official/Reference/WinNamedPipesLib/#working-with-data-as-byte-in-events) on the package overview for the transient-buffer lifetime caveat --- copy the bytes out before the handler returns if they are needed later. The [recommended capture mechanism](/en/official/Reference/WinNamedPipesLib/#propertybag-carrier) is to assign *Data* to a fresh [**PropertyBag**](/en/official/Reference/VBRUN/PropertyBag/)'s **Contents**, which deep-copies the bytes and provides typed multi-field access in one step. ### MessageSent Fires when a previously-issued [**AsyncWrite**](#asyncwrite) has completed. Syntax: *connection*\_**MessageSent**(**ByRef** *Cookie* **As Variant**) *Cookie* : The opaque correlation value that was passed to the originating [**AsyncWrite**](#asyncwrite) call. ## Methods ### AsyncClose Cancels every outstanding I/O against this connection and closes the underlying pipe handle. Eventually triggers the [**Disconnected**](#disconnected) event once the cancellation completes. Automatically invoked from `Class_Terminate` when the last reference to the connection drops. Syntax: *connection*.**AsyncClose** ::: warning See the class intro: the README requires that either this method runs (explicitly, or through `Class_Terminate`) before the connection is considered finished. ::: ### AsyncRead Manually issues an asynchronous read against this connection. Syntax: *connection*.**AsyncRead** \[ *Cookie* \[, *OverlappedStruct* ] ] *Cookie* : *optional* A **Variant** correlation value, passed back as the *Cookie* parameter of the matching [**MessageReceived**](#messagereceived) event. Default **Empty**. *OverlappedStruct* : *optional* A **LongPtr** to a pre-allocated `OVERLAPPED_CUSTOM` structure. **Internal use only** --- the IOCP machinery passes this when re-issuing a read after `ERROR_MORE_DATA`. Consumer code should always omit this parameter. Only needed when the parent manager's [**ContinuouslyReadFromPipe**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientManager#continuouslyreadfrompipe) is **False**; otherwise the IOCP loop keeps a read pending automatically and explicit calls are redundant. ### AsyncWrite Sends a message to the server. Syntax: *connection*.**AsyncWrite** *Data*() \[, *Cookie* ] *Data* : *required* A **Byte()** array containing the bytes to send. An uninitialised or zero-length array is a no-op. For typed multi-field payloads the recommended encoding is [**PropertyBag**](/en/official/Reference/VBRUN/PropertyBag/) --- see [Recommended payload encoding: `PropertyBag`](/en/official/Reference/WinNamedPipesLib/#propertybag-carrier) on the package overview. *Cookie* : *optional* A **Variant** correlation value, passed back as the *Cookie* parameter of the matching [**MessageSent**](#messagesent) event. Default **Empty**. Returns immediately; the actual transmission runs through the IOCP loop. The completion fires [**MessageSent**](#messagesent) on this connection. ## See Also * [WinNamedPipesLib package](/en/official/Reference/WinNamedPipesLib/) -- overview, IOCP / event-marshalling architecture, cookie pattern, `Data()` lifetime caveat, the **AsyncClose** rule * [Recommended payload encoding: `PropertyBag`](/en/official/Reference/WinNamedPipesLib/#propertybag-carrier) -- the deep-copy capture pattern for transient *Data* in events * [NamedPipeClientManager class](/en/official/Reference/WinNamedPipesLib/NamedPipeClientManager) -- the manager that produced this connection * [NamedPipeServerConnection class](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection) -- the server-side counterpart --- --- url: /zh/official/Reference/WinNamedPipesLib/NamedPipeClientConnection.md --- # NamedPipeClientConnection 类 一个到命名管道的客户端连接。由 [**NamedPipeClientManager.Connect**](/official/Reference/WinNamedPipesLib/NamedPipeClientManager#connect) 产生。承载连接生命周期事件([**Connected**](#connected)、[**Disconnected**](#disconnected))和消息事件([**MessageReceived**](#messagereceived)、[**MessageSent**](#messagesent)),以及触发它们的 [**AsyncRead**](#asyncread) / [**AsyncWrite**](#asyncwrite) / [**AsyncClose**](#asyncclose) 方法。 该类标记为 `[COMCreatable(False)]`,其构造函数接受包私有接口——只能通过 [**NamedPipeClientManager.Connect**](/official/Reference/WinNamedPipesLib/NamedPipeClientManager#connect) 获取实例。 ::: warning 包的 `_README.txt` 声明:*"你必须在客户端调用 **AsyncClose**,否则当对象超出作用域时连接仍然存活"*。在丢弃最后一个引用之前显式调用 [**AsyncClose**](#asyncclose),**或者**让对象通过其 `Class_Terminate`(自动调用 [**AsyncClose**](#asyncclose))干净地终止。永远持有引用——例如在模块级 **Collection** 中——而不调用 [**AsyncClose**](#asyncclose) 会使管道句柄保持打开且IOCP线程保持活动。 ::: ```vb Private manager As NamedPipeClientManager Private WithEvents connection As NamedPipeClientConnection Private Sub Form_Load() Set manager = New NamedPipeClientManager Set connection = manager.Connect("MyService") End Sub Private Sub connection_Connected() connection.AsyncWrite StrConv("hello", vbFromUnicode) End Sub Private Sub connection_MessageReceived(ByRef Cookie As Variant, ByRef Data() As Byte) Debug.Print "reply: " & StrConv(Data, vbUnicode) End Sub Private Sub Form_Unload(Cancel As Integer) connection.AsyncClose End Sub ``` 参见包[概述](/official/Reference/WinNamedPipesLib/)了解IOCP/事件封送架构、cookie关联模式和事件中 `Data() As Byte` 的瞬时生命周期。 ## 属性 ### CustomData 消费者可附加状态的每连接不透明槽——通常是与该连接关联的会话对象或待回复字典。**Variant**,默认 **Empty**。包从不读取或写入此字段。 ### Handle 由 `CreateFileW("\\.\pipe\<PipeName>")` 返回的底层Win32文件句柄。**LongPtr**。为低级/调试用途暴露——大多数消费者可以忽略。不要直接对此值调用 `CloseHandle`;使用 [**AsyncClose**](#asyncclose) 以保持IOCP循环和父管理器簿记的一致性。 ### PipeName 此连接所打开的叶管道名称——与传递给 [**NamedPipeClientManager.Connect**](/official/Reference/WinNamedPipesLib/NamedPipeClientManager#connect) 的值相同。**String**。实际上只读;包从构造函数参数设置它且从不更改。 ## 事件 ### Connected 当由 [**NamedPipeClientManager.Connect**](/official/Reference/WinNamedPipesLib/NamedPipeClientManager#connect) 启动的异步 `CreateFileW` 成功且管道准备好进行消息交换时触发一次。 语法:*connection*\_**Connected**() ### Disconnected 当管道已断开*且*对连接的每个未完成异步I/O已返回后触发一次。此事件后连接对象不再可用于I/O。 语法:*connection*\_**Disconnected**() ### MessageReceived 当从管道读取完整消息时触发。 语法:*connection*\_**MessageReceived**(**ByRef** *Cookie* **As Variant**, **ByRef** *Data*() **As Byte**) *Cookie* : 最初传递给产生此读取的 [**AsyncRead**](#asyncread) 的不透明关联值——如果读取来自 [**NamedPipeClientManager.ContinuouslyReadFromPipe**](/official/Reference/WinNamedPipesLib/NamedPipeClientManager#continuouslyreadfrompipe) 触发的自动发起读取则为 **Empty**。 *Data* : 消息载荷。参见包概述上的[在事件中使用 `Data() As Byte`](/official/Reference/WinNamedPipesLib/#working-with-data-as-byte-in-events)了解瞬时缓冲区生命周期注意事项——如果稍后需要字节,请在处理程序返回之前将其复制出来。[推荐的捕获机制](/official/Reference/WinNamedPipesLib/#propertybag-carrier)是将 *Data* 赋值给新的 [**PropertyBag**](/official/Reference/VBRUN/PropertyBag/) 的 **Contents**,这会深拷贝字节并一步提供类型化的多字段访问。 ### MessageSent 当之前发出的 [**AsyncWrite**](#asyncwrite) 已完成时触发。 语法:*connection*\_**MessageSent**(**ByRef** *Cookie* **As Variant**) *Cookie* : 传递给发起 [**AsyncWrite**](#asyncwrite) 调用的不透明关联值。 ## 方法 ### AsyncClose 取消对此连接的每个未完成I/O并关闭底层管道句柄。取消完成后最终触发 [**Disconnected**](#disconnected) 事件。当连接的最后一个引用丢弃时自动从 `Class_Terminate` 调用。 语法:*connection*.**AsyncClose** ::: warning 参见类简介:README要求此方法运行(显式地或通过 `Class_Terminate`)才能认为连接完成。 ::: ### AsyncRead 手动对此连接发出异步读取。 语法:*connection*.**AsyncRead** \[ *Cookie* \[, *OverlappedStruct* ] ] *Cookie* : *可选* **Variant** 关联值,作为匹配的 [**MessageReceived**](#messagereceived) 事件的 *Cookie* 参数传回。默认 **Empty**。 *OverlappedStruct* : *可选* 指向预分配的 `OVERLAPPED_CUSTOM` 结构的 **LongPtr**。**仅供内部使用**——IOCP机制在 `ERROR_MORE_DATA` 后重新发出读取时传递此参数。消费者代码应始终省略此参数。 仅当父管理器的 [**ContinuouslyReadFromPipe**](/official/Reference/WinNamedPipesLib/NamedPipeClientManager#continuouslyreadfrompipe) 为 **False** 时需要;否则IOCP循环自动保持待处理读取,显式调用是冗余的。 ### AsyncWrite 向服务器发送消息。 语法:*connection*.**AsyncWrite** *Data*() \[, *Cookie* ] *Data* : *必需* 包含要发送字节的 **Byte()** 数组。未初始化或零长度数组为无操作。对于类型化的多字段载荷,推荐编码为 [**PropertyBag**](/official/Reference/VBRUN/PropertyBag/)——参见包概述上的[推荐的载荷编码:`PropertyBag`](/official/Reference/WinNamedPipesLib/#propertybag-carrier)。 *Cookie* : *可选* **Variant** 关联值,作为匹配的 [**MessageSent**](#messagesent) 事件的 *Cookie* 参数传回。默认 **Empty**。 立即返回;实际传输通过IOCP循环运行。完成时触发此连接上的 [**MessageSent**](#messagesent)。 ## 另见 * [WinNamedPipesLib 包](/official/Reference/WinNamedPipesLib/) -- 概述、IOCP/事件封送架构、cookie模式、`Data()` 生命周期注意事项、**AsyncClose** 规则 * [推荐的载荷编码:`PropertyBag`](/official/Reference/WinNamedPipesLib/#propertybag-carrier) -- 事件中瞬时 *Data* 的深拷贝捕获模式 * [NamedPipeClientManager 类](/official/Reference/WinNamedPipesLib/NamedPipeClientManager) -- 产生此连接的管理器 * [NamedPipeServerConnection 类](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection) -- 服务器端对应项 --- --- url: /en/official/Reference/WinNamedPipesLib/NamedPipeClientManager.md --- # NamedPipeClientManager class The client-side coordinator. Owns a Windows I/O Completion Port and a pool of worker threads shared by every [**NamedPipeClientConnection**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) it produces, and returns them through [**Connect**](#connect). One [**NamedPipeClientManager**](/en/official/Reference/WinNamedPipesLib/) typically lives for the lifetime of the consuming process and manages many connections --- to one or several servers --- through that shared IOCP infrastructure. Instantiate with **New**. Configure the public fields (all four have reasonable defaults), call [**Connect**](#connect) for each pipe the application wants to dial, and respond to the [**NamedPipeClientConnection**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) events. The first [**Connect**](#connect) lazily creates the completion port and starts the worker threads; subsequent calls reuse them. ```vb Private manager As NamedPipeClientManager Private WithEvents connection As NamedPipeClientConnection Private Sub Form_Load() Set manager = New NamedPipeClientManager Set connection = manager.Connect("MyService") End Sub Private Sub connection_Connected() Dim payload() As Byte = StrConv("hello", vbFromUnicode) connection.AsyncWrite payload End Sub Private Sub Form_Unload(Cancel As Integer) connection.AsyncClose ' required — see README manager.Stop ' or just let the manager go out of scope End Sub ``` See the package [overview](/en/official/Reference/WinNamedPipesLib/) for the IOCP / event-marshalling architecture, the cookie correlation pattern, the transient lifetime of `Data() As Byte` inside events, and the mandatory `AsyncClose` rule for client connections. ## Properties The four configuration fields are read once on the first [**Connect**](#connect) call and propagated to every [**NamedPipeClientConnection**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) created through this manager. Subsequent changes affect connections opened thereafter but **not** connections that already exist --- set the fields before the first [**Connect**](#connect). ### ContinuouslyReadFromPipe When **True** (the default), each [**NamedPipeClientConnection**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) keeps a read pending against its pipe at all times --- every [**MessageReceived**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection#messagereceived) is followed by an automatic `AsyncRead` issued from inside the IOCP thread. Set to **False** to handle reads one-at-a-time; each [**MessageReceived**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection#messagereceived) handler must then call [**NamedPipeClientConnection.AsyncRead**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection#asyncread) to receive the next message. **Boolean**, default **True**. ### FreeThreadingEvents Controls where the [**NamedPipeClientConnection**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) events are raised. When **False** (the default), the IOCP worker threads marshal each event to the main UI thread through the manager's hidden message-only window, and the consuming process must be pumping a Win32 message loop. When **True**, events fire directly on whichever IOCP worker thread received the completion --- no message-loop dependency, but the consumer's event handlers must be thread-safe. **Boolean**, default **False**. ### MessageBufferSize The size, in bytes, of the per-completion `ReadFile` buffer initially allocated for each client connection. **Long**, default **131072** (128 KiB). Does not cap the maximum message size --- on `ERROR_MORE_DATA` the IOCP loop allocates a larger overflow buffer and re-issues the read --- but the initial size affects throughput for sustained large-message traffic. ### NumThreadsIOCP The number of IOCP worker threads created when [**Connect**](#connect) is first called. **Long**, default **1**. One thread is enough for most scenarios; raise this to allow concurrent event handlers under [**FreeThreadingEvents**](#freethreadingevents) = **True**, or to keep up with heavy traffic on multi-core hardware. ## Methods ### Connect Opens an asynchronous connection to a named pipe on the local machine. Syntax: *manager*.**Connect**( *PipeName* ) **As NamedPipeClientConnection** *PipeName* : *required* The leaf name of the pipe to dial --- the package prepends `\\.\pipe\` itself. Raises run-time error 5 *"cannot start without specifying a pipe name"* if empty. Lazy on first call: creates the completion port and starts [**NumThreadsIOCP**](#numthreadsiocp) worker threads. Returns immediately with a [**NamedPipeClientConnection**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) in the not-yet-connected state. The actual `CreateFileW` runs asynchronously on an IOCP worker and fires [**Connected**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection#connected) on the returned object once the pipe is open. Raises run-time error 5 *"unable to create an IOCP port"* if `CreateIoCompletionPort` fails on the first call. ### FindNamedPipes Enumerates the named pipes currently published on the local machine. Syntax: *manager*.**FindNamedPipes** ( \[ *Pattern* ] ) **As Collection** *Pattern* : *optional* A wildcard pattern matched against the leaf pipe name (no `\\.\pipe\` prefix; the package adds it). `*` matches any sequence, `?` matches any single character. Default `"*"` --- return every pipe. Returns a **Collection** of **String** values, each a leaf pipe name suitable to pass to [**Connect**](#connect). Useful as a discovery step when the consumer doesn't know the exact server name in advance: ```vb Dim names As Collection = manager.FindNamedPipes("MyService_*") Dim name As Variant For Each name In names Debug.Print "found: " & name Next ``` The package does not publish an event when pipes appear or disappear, so dynamic UIs that list available servers typically refresh the list from a low-frequency [**Timer**](/en/official/Reference/VB/Timer/) --- see [Discovering pipes](/en/official/Reference/WinNamedPipesLib/#discovering-pipes) on the package overview for the polling-loop pattern that preserves the user's current selection across refreshes. ### Stop Cancels every outstanding I/O on every connection produced by this manager, posts the IOCP shutdown sentinel to each worker, waits for the threads to exit, closes every pipe handle, and frees the completion port. Idempotent: calling [**Stop**](#stop) on a manager that has not connected anything --- or has already been stopped --- is a no-op. Automatically invoked from `Class_Terminate`, so a manager going out of scope closes resources implicitly. Syntax: *manager*.**Stop** [**NamedPipeClientConnection**](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) objects produced by this manager remain valid as references after [**Stop**](#stop), but their underlying pipe handles are closed and they cannot perform I/O. ### New Constructs a manager in the not-yet-connected state. Creates the hidden `STATIC`-class message window used to marshal IOCP-thread completions back to the UI thread. Syntax: **New NamedPipeClientManager** ## See Also * [WinNamedPipesLib package](/en/official/Reference/WinNamedPipesLib/) -- overview, IOCP / event-marshalling architecture, cookie pattern, `Data()` lifetime caveat, **AsyncClose** rule * [Discovering pipes](/en/official/Reference/WinNamedPipesLib/#discovering-pipes) -- the **Timer**-driven polling loop that powers dynamic pipe-listing UIs * [NamedPipeClientConnection class](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) -- the per-connection object returned by [**Connect**](#connect) * [NamedPipeServer class](/en/official/Reference/WinNamedPipesLib/NamedPipeServer) -- the server-side counterpart --- --- url: /zh/official/Reference/WinNamedPipesLib/NamedPipeClientManager.md --- # NamedPipeClientManager 类 客户端协调器。拥有一个Windows I/O完成端口和一个由其产生的每个 [**NamedPipeClientConnection**](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) 共享的工作线程池,并通过 [**Connect**](#connect) 返回它们。一个 [**NamedPipeClientManager**](/official/Reference/WinNamedPipesLib/) 通常在消费进程的整个生命周期内存在,通过共享的IOCP基础设施管理许多连接——到一个或多个服务器。使用 **New** 实例化。 配置公共字段(四个都有合理默认值),为应用程序想要拨号的每个管道调用 [**Connect**](#connect),并响应 [**NamedPipeClientConnection**](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) 事件。第一次 [**Connect**](#connect) 延迟创建完成端口并启动工作线程;后续调用重用它们。 ```vb Private manager As NamedPipeClientManager Private WithEvents connection As NamedPipeClientConnection Private Sub Form_Load() Set manager = New NamedPipeClientManager Set connection = manager.Connect("MyService") End Sub Private Sub connection_Connected() Dim payload() As Byte = StrConv("hello", vbFromUnicode) connection.AsyncWrite payload End Sub Private Sub Form_Unload(Cancel As Integer) connection.AsyncClose ' 必需——参见 README manager.Stop ' 或直接让管理器超出作用域 End Sub ``` 参见包[概述](/official/Reference/WinNamedPipesLib/)了解IOCP/事件封送架构、cookie关联模式、事件中 `Data() As Byte` 的瞬时生命周期,以及客户端连接的强制性 `AsyncClose` 规则。 ## 属性 四个配置字段在第一次 [**Connect**](#connect) 调用时读取一次并传播到通过此管理器创建的每个 [**NamedPipeClientConnection**](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection)。后续更改影响之后打开的连接但**不影响**已存在的连接——在第一次 [**Connect**](#connect) 之前设置这些字段。 ### ContinuouslyReadFromPipe 当 **True**(默认)时,每个 [**NamedPipeClientConnection**](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) 始终对其管道保持一个待处理读取——每个 [**MessageReceived**](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection#messagereceived) 之后,IOCP线程内部会发出一个自动的 `AsyncRead`。设置为 **False** 以逐个处理读取;每个 [**MessageReceived**](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection#messagereceived) 处理程序必须随后调用 [**NamedPipeClientConnection.AsyncRead**](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection#asyncread) 来接收下一条消息。**Boolean**,默认 **True**。 ### FreeThreadingEvents 控制 [**NamedPipeClientConnection**](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) 事件在何处引发。当 **False**(默认)时,IOCP工作线程通过管理器的隐藏仅消息窗口将每个事件封送到主UI线程,消费进程必须正在泵送Win32消息循环。当 **True** 时,事件直接在接收到完成的IOCP工作线程上触发——无消息循环依赖,但消费者的事件处理程序必须是线程安全的。**Boolean**,默认 **False**。 ### MessageBufferSize 为每个客户端连接初始分配的每完成 `ReadFile` 缓冲区大小(字节)。**Long**,默认 **131072**(128 KiB)。不限制最大消息大小——在 `ERROR_MORE_DATA` 时IOCP循环分配更大的溢出缓冲区并重新发出读取——但初始大小影响持续大消息流量的吞吐量。 ### NumThreadsIOCP 首次调用 [**Connect**](#connect) 时创建的IOCP工作线程数。**Long**,默认 **1**。一个线程对于大多数场景足够;提高此值以允许多个 [**FreeThreadingEvents**](#freethreadingevents) = **True** 下的并发事件处理程序,或者在多核硬件上跟上大流量。 ## 方法 ### Connect 打开到本地计算机上命名管道的异步连接。 语法:*manager*.**Connect**( *PipeName* ) **As NamedPipeClientConnection** *PipeName* : *必需* 要拨号的管道叶名称——包自行添加 `\\.\pipe\` 前缀。如果为空则引发运行时错误5 *"cannot start without specifying a pipe name"*。 首次调用时延迟创建:创建完成端口并启动 [**NumThreadsIOCP**](#numthreadsiocp) 个工作线程。立即返回处于尚未连接状态的 [**NamedPipeClientConnection**](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection)。实际 `CreateFileW` 在IOCP工作线程上异步运行,管道打开后触发返回对象上的 [**Connected**](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection#connected)。 首次调用时如果 `CreateIoCompletionPort` 失败则引发运行时错误5 *"unable to create an IOCP port"*。 ### FindNamedPipes 枚举本地计算机上当前发布的命名管道。 语法:*manager*.**FindNamedPipes** ( \[ *Pattern* ] ) **As Collection** *Pattern* : *可选* 与管道叶名称匹配的通配符模式(不带 `\\.\pipe\` 前缀;包会添加)。`*` 匹配任意序列,`?` 匹配任意单个字符。默认 `"*"`——返回每个管道。 返回 **String** 值的 **Collection**,每个都是适合传递给 [**Connect**](#connect) 的叶管道名称。用作消费者事先不知道确切服务器名称时的发现步骤: ```vb Dim names As Collection = manager.FindNamedPipes("MyService_*") Dim name As Variant For Each name In names Debug.Print "found: " & name Next ``` 包不发布管道出现或消失的事件,因此列出可用服务器的动态UI通常从低频率的 [**Timer**](/official/Reference/VB/Timer/) 刷新列表——参见包概述上的[发现管道](/official/Reference/WinNamedPipesLib/#discovering-pipes)了解在刷新间保留用户当前选择的轮询循环模式。 ### Stop 取消此管理器产生的每个连接上每个未完成的I/O,向每个工作线程发送IOCP关闭哨兵,等待线程退出,关闭每个管道句柄,并释放完成端口。幂等:在未连接任何内容或已停止的管理器上调用 [**Stop**](#stop) 为无操作。自动从 `Class_Terminate` 调用,因此超出作用域的管理器隐式关闭资源。 语法:*manager*.**Stop** [**NamedPipeClientConnection**](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) 对象在 [**Stop**](#stop) 后作为引用仍然有效,但其底层管道句柄已关闭,无法执行I/O。 ### New 在尚未连接的状态下构造管理器。创建用于将IOCP线程完成封送回UI线程的隐藏 `STATIC` 类消息窗口。 语法:**New NamedPipeClientManager** ## 另见 * [WinNamedPipesLib 包](/official/Reference/WinNamedPipesLib/) -- 概述、IOCP/事件封送架构、cookie模式、`Data()` 生命周期注意事项、**AsyncClose** 规则 * [发现管道](/official/Reference/WinNamedPipesLib/#discovering-pipes) -- 驱动动态管道列表UI的 **Timer** 轮询循环 * [NamedPipeClientConnection 类](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) -- 由 [**Connect**](#connect) 返回的每连接对象 * [NamedPipeServer 类](/official/Reference/WinNamedPipesLib/NamedPipeServer) -- 服务器端对应项 --- --- url: /en/official/Reference/WinNamedPipesLib/NamedPipeServer.md --- # NamedPipeServer class Hosts one named pipe and accepts an unbounded number of concurrent client connections, each represented by a [**NamedPipeServerConnection**](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection). The class owns a Windows I/O Completion Port and a configurable pool of worker threads that handle every connection's reads, writes, and connect notifications. Instantiate with **New**. Configure the public fields ([**PipeName**](#pipename) is required, the others have reasonable defaults), call [**Start**](#start), and respond to the lifecycle events as clients arrive and exchange messages. The package opens the underlying pipe as **PIPE\_TYPE\_MESSAGE** / **PIPE\_READMODE\_MESSAGE** --- messages preserve their boundaries between sender and receiver. ```vb Private WithEvents server As NamedPipeServer Private Sub Form_Load() Set server = New NamedPipeServer server.PipeName = "MyService" server.Start End Sub Private Sub server_ClientConnected(Connection As NamedPipeServerConnection) Debug.Print "client " & Connection.Handle & " arrived" End Sub Private Sub server_ClientMessageReceived( _ Connection As NamedPipeServerConnection, _ ByRef Cookie As Variant, _ ByRef Data() As Byte) Connection.AsyncWrite Data ' echo it back End Sub ``` See the package [overview](/en/official/Reference/WinNamedPipesLib/) for the IOCP / event-marshalling architecture, the cookie correlation pattern, and the transient lifetime of `Data() As Byte` inside events. ## Properties ### ContinuouslyReadFromPipe When **True** (the default), the server keeps a read pending against every connected client at all times --- every [**ClientMessageReceived**](#clientmessagereceived) is followed by an automatic `AsyncRead` issued from inside the IOCP thread. Set to **False** to handle reads one-at-a-time; each [**ClientMessageReceived**](#clientmessagereceived) handler must then call [**NamedPipeServerConnection.AsyncRead**](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#asyncread) to receive the next message. **Boolean**, default **True**. ### FreeThreadingEvents Controls where the lifecycle and message events are raised. When **False** (the default), the IOCP worker threads marshal each event to the main UI thread through a hidden message-only window, and the consuming process must be pumping a Win32 message loop. When **True**, events fire directly on whichever IOCP worker thread received the completion --- no message-loop dependency, but the consumer's event handlers must be thread-safe. **Boolean**, default **False**. Set this before calling [**Start**](#start); it is read once when the worker threads are created and propagated to every [**NamedPipeServerConnection**](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection). ### MessageBufferSize The size, in bytes, of the per-completion `ReadFile` buffer initially allocated for each connection. **Long**, default **131072** (128 KiB). Does not cap the maximum message size --- on `ERROR_MORE_DATA` the IOCP loop allocates a larger overflow buffer and re-issues the read --- but the initial size affects how often that overflow path runs, and so affects throughput for sustained large-message traffic. ### NumThreadsIOCP The number of IOCP worker threads created by [**Start**](#start). **Long**, default **1**. One thread is enough for most scenarios because every blocking call inside the worker is an overlapped Win32 operation that releases the thread immediately. Raise this to allow multiple [**ClientMessageReceived**](#clientmessagereceived) handlers to run concurrently under [**FreeThreadingEvents**](#freethreadingevents) = **True**, or to keep up with heavy traffic on multi-core hardware. Set this before calling [**Start**](#start). ### PipeName The name the pipe is published under. **String**, no default. The Win32 pipe namespace path is `\\.\pipe\<PipeName>` --- the package prepends `\\.\pipe\` itself; pass just the leaf name. ::: warning [**PipeName**](#pipename) must be set to a non-empty value before [**Start**](#start), or [**Start**](#start) raises run-time error 5 (*"cannot start without specifying a pipe name"*). ::: ## Events ### ClientConnected Fires after a client's `ConnectNamedPipe` has completed and the connection is ready for message exchange. Syntax: *server*\_**ClientConnected**(*Connection* **As NamedPipeServerConnection**) *Connection* : The newly-connected client's server-side connection object. Hold the reference to keep per-client state across messages --- the same instance is passed to every event for this client. **Cookie** / `Tag`-style storage is available through [**NamedPipeServerConnection.CustomData**](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#customdata). ### ClientDisconnected Fires once the client has dropped *and* every outstanding asynchronous I/O against the connection has returned. The connection object is no longer usable for I/O after this event. Syntax: *server*\_**ClientDisconnected**(*Connection* **As NamedPipeServerConnection**) *Connection* : The connection that has just shut down. Its [**IsConnected**](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#isconnected) is **False**. ### ClientMessageReceived Fires when a complete message has been read from the pipe. Syntax: *server*\_**ClientMessageReceived**(*Connection* **As NamedPipeServerConnection**, **ByRef** *Cookie* **As Variant**, **ByRef** *Data*() **As Byte**) *Connection* : The connection the message came from. *Cookie* : The opaque correlation value originally passed to the [**NamedPipeServerConnection.AsyncRead**](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#asyncread) that produced this read --- or **Empty** if the read came from the auto-issued reads triggered by [**ContinuouslyReadFromPipe**](#continuouslyreadfrompipe). *Data* : The message payload. See [Working with `Data() As Byte` in events](/en/official/Reference/WinNamedPipesLib/#working-with-data-as-byte-in-events) on the package overview for the transient-buffer lifetime caveat --- copy the bytes out before the handler returns if they are needed later. The [recommended capture mechanism](/en/official/Reference/WinNamedPipesLib/#propertybag-carrier) is to assign *Data* to a fresh [**PropertyBag**](/en/official/Reference/VBRUN/PropertyBag/)'s **Contents**, which deep-copies the bytes and provides typed multi-field access in one step. ### ClientMessageSent Fires when a previously-issued [**NamedPipeServerConnection.AsyncWrite**](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#asyncwrite) has completed (or when an [**AsyncBroadcast**](#asyncbroadcast) message reaches each individual client). Syntax: *server*\_**ClientMessageSent**(*Connection* **As NamedPipeServerConnection**, **ByRef** *Cookie* **As Variant**) *Connection* : The connection the write went out on. *Cookie* : The opaque correlation value that was passed to the originating [**AsyncWrite**](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#asyncwrite) call. ### ServerReady Fires once, after [**Start**](#start), when every IOCP worker thread has joined the completion-port loop and the first connection listener is published. Use this as the "the server is now accepting connections" signal. Syntax: *server*\_**ServerReady**() ## Methods ### AsyncBroadcast Issues an [**AsyncWrite**](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#asyncwrite) against every currently-connected client. Syntax: *server*.**AsyncBroadcast** *Data*() \[, *Cookie* ] *Data* : *required* The message bytes to send. twinBASIC will coerce a **String** literal to **Byte()** implicitly, so `server.AsyncBroadcast "shutting down"` works without a separate `StrConv` step --- useful for protocol-less server-pushed notifications. *Cookie* : *optional* A **Variant** correlation value, attached to *each* per-client [**ClientMessageSent**](#clientmessagesent) event. Default **Empty**. The set of recipients is snapshotted under a lock at the start of the call. Clients connecting after the snapshot do not receive this broadcast; clients disconnecting after the snapshot but before their per-client write completes simply fail that individual write silently. ### ManualMessageLoopEnter Runs a Win32 message loop on the calling thread until [**ManualMessageLoopLeave**](#manualmessageloopleave) is called from another thread (or any handler raises a `WM_USER_QUITTING` posting). Syntax: *server*.**ManualMessageLoopEnter** Intended for console / service hosts that do not have a Forms-style message pump of their own but want the default ([**FreeThreadingEvents**](#freethreadingevents) = **False**) marshalled-event semantics. UI hosts already pump messages naturally and do not need this method. The canonical caller is a Windows service that owns this server: the service-thread entry-point opens the server, transitions the service to `Running`, calls **ManualMessageLoopEnter** to block while events flow, and a control-code handler running on the dispatcher thread calls [**ManualMessageLoopLeave**](#manualmessageloopleave) when the SCM signals stop. See [Hosting inside a Windows service](/en/official/Reference/WinNamedPipesLib/#service-host-idiom) on the package overview for the complete pattern, including the two-thread coordination and the *Pause* / *Continue* extension. ### ManualMessageLoopLeave Posts a `WM_USER_QUITTING` message to the hidden marshalling window, causing the [**ManualMessageLoopEnter**](#manualmessageloopenter) loop on the other thread to exit. Safe to call from any thread. Syntax: *server*.**ManualMessageLoopLeave** The intended caller is a thread *other* than the one inside [**ManualMessageLoopEnter**](#manualmessageloopenter) --- typically the Windows service's dispatcher thread waking the service-entry-point thread out of its blocked loop. See [Hosting inside a Windows service](/en/official/Reference/WinNamedPipesLib/#service-host-idiom). ### Start Creates the I/O Completion Port, starts [**NumThreadsIOCP**](#numthreadsiocp) worker threads, and publishes the first connection listener under `\\.\pipe\<PipeName>`. Fires [**ServerReady**](#serverready) when every worker has joined. Syntax: *server*.**Start** Raises run-time error 5 *"cannot start without specifying a pipe name"* if [**PipeName**](#pipename) is empty, or *"unable to create an IOCP port"* if `CreateIoCompletionPort` fails. Idempotent: calling [**Start**](#start) while the server is already running is a no-op. ### Stop Cancels every outstanding I/O on every connection, posts the IOCP shutdown sentinel to each worker, waits for the threads to exit, closes every pipe handle, and frees the completion port. Idempotent: calling [**Stop**](#stop) on a server that has not been started --- or has already been stopped --- is a no-op. Automatically invoked from `Class_Terminate`, so a server going out of scope closes resources implicitly. Syntax: *server*.**Stop** ### New Constructs a server in the not-yet-started state. Creates the hidden `STATIC`-class message window used to marshal IOCP-thread completions back to the UI thread. Syntax: **New NamedPipeServer** ## See Also * [WinNamedPipesLib package](/en/official/Reference/WinNamedPipesLib/) -- overview, IOCP / event-marshalling architecture, cookie pattern, `Data()` lifetime caveat, known limitations * [Hosting inside a Windows service](/en/official/Reference/WinNamedPipesLib/#service-host-idiom) -- the **ManualMessageLoopEnter** / **ManualMessageLoopLeave** service-entry-point pattern * [Recommended payload encoding: `PropertyBag`](/en/official/Reference/WinNamedPipesLib/#propertybag-carrier) -- the deep-copy capture pattern for transient *Data* in events * [NamedPipeServerConnection class](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection) -- the per-client connection passed to every event * [NamedPipeClientManager class](/en/official/Reference/WinNamedPipesLib/NamedPipeClientManager) -- the client-side counterpart --- --- url: /zh/official/Reference/WinNamedPipesLib/NamedPipeServer.md --- # NamedPipeServer 类 承载一个命名管道并接受无限数量的并发客户端连接,每个连接由 [**NamedPipeServerConnection**](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection) 表示。该类拥有一个Windows I/O完成端口和一个可配置的工作线程池,处理每个连接的读取、写入和连接通知。使用 **New** 实例化。 配置公共字段([**PipeName**](#pipename) 必填,其他有合理默认值),调用 [**Start**](#start),并响应客户端到达和交换消息的生命周期事件。包以 **PIPE\_TYPE\_MESSAGE** / **PIPE\_READMODE\_MESSAGE** 方式打开底层管道——消息在发送方和接收方之间保持边界。 ```vb Private WithEvents server As NamedPipeServer Private Sub Form_Load() Set server = New NamedPipeServer server.PipeName = "MyService" server.Start End Sub Private Sub server_ClientConnected(Connection As NamedPipeServerConnection) Debug.Print "client " & Connection.Handle & " arrived" End Sub Private Sub server_ClientMessageReceived( _ Connection As NamedPipeServerConnection, _ ByRef Cookie As Variant, _ ByRef Data() As Byte) Connection.AsyncWrite Data ' 原样回显 End Sub ``` 参见包[概述](/official/Reference/WinNamedPipesLib/)了解IOCP/事件封送架构、cookie关联模式和事件中 `Data() As Byte` 的瞬时生命周期。 ## 属性 ### ContinuouslyReadFromPipe 当 **True**(默认)时,服务器始终对每个已连接客户端保持一个待处理读取——每个 [**ClientMessageReceived**](#clientmessagereceived) 之后,IOCP线程内部会发出一个自动的 `AsyncRead`。设置为 **False** 以逐个处理读取;每个 [**ClientMessageReceived**](#clientmessagereceived) 处理程序必须随后调用 [**NamedPipeServerConnection.AsyncRead**](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#asyncread) 来接收下一条消息。**Boolean**,默认 **True**。 ### FreeThreadingEvents 控制生命周期和消息事件在何处引发。当 **False**(默认)时,IOCP工作线程通过隐藏的仅消息窗口将每个事件封送到主UI线程,消费进程必须正在泵送Win32消息循环。当 **True** 时,事件直接在接收到完成的IOCP工作线程上触发——无消息循环依赖,但消费者的事件处理程序必须是线程安全的。**Boolean**,默认 **False**。 在调用 [**Start**](#start) 之前设置此项;它在创建工作线程时读取一次并传播到每个 [**NamedPipeServerConnection**](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection)。 ### MessageBufferSize 为每个连接初始分配的每完成 `ReadFile` 缓冲区大小(字节)。**Long**,默认 **131072**(128 KiB)。不限制最大消息大小——在 `ERROR_MORE_DATA` 时IOCP循环分配更大的溢出缓冲区并重新发出读取——但初始大小影响该溢出路径的运行频率,从而影响持续大消息流量的吞吐量。 ### NumThreadsIOCP 由 [**Start**](#start) 创建的IOCP工作线程数。**Long**,默认 **1**。一个线程对于大多数场景足够,因为工作器内的每个阻塞调用都是重叠的Win32操作,会立即释放线程。提高此值以允许多个 [**ClientMessageReceived**](#clientmessagereceived) 处理程序在 [**FreeThreadingEvents**](#freethreadingevents) = **True** 下并发运行,或者在多核硬件上跟上大流量。在调用 [**Start**](#start) 之前设置此项。 ### PipeName 管道发布的名称。**String**,无默认值。Win32管道命名空间路径为 `\\.\pipe\<PipeName>`——包自行添加 `\\.\pipe\` 前缀;只需传递叶名称。 ::: warning [**PipeName**](#pipename) 必须在 [**Start**](#start) 之前设置为非空值,否则 [**Start**](#start) 引发运行时错误5(*"cannot start without specifying a pipe name"*)。 ::: ## 事件 ### ClientConnected 在客户端的 `ConnectNamedPipe` 完成且连接准备好进行消息交换之后触发。 语法:*server*\_**ClientConnected**(*Connection* **As NamedPipeServerConnection**) *Connection* : 新连接客户端的服务器端连接对象。持有引用以在消息之间保持每客户端状态——同一实例传递给该客户端的每个事件。可通过 [**NamedPipeServerConnection.CustomData**](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#customdata) 使用 **Cookie** / `Tag` 样式存储。 ### ClientDisconnected 在客户端已断开*且*对连接的每个未完成异步I/O已返回后触发一次。此事件后连接对象不再可用于I/O。 语法:*server*\_**ClientDisconnected**(*Connection* **As NamedPipeServerConnection**) *Connection* : 刚刚关闭的连接。其 [**IsConnected**](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#isconnected) 为 **False**。 ### ClientMessageReceived 当从管道读取完整消息时触发。 语法:*server*\_**ClientMessageReceived**(*Connection* **As NamedPipeServerConnection**, **ByRef** *Cookie* **As Variant**, **ByRef** *Data*() **As Byte**) *Connection* : 消息来源的连接。 *Cookie* : 最初传递给产生此读取的 [**NamedPipeServerConnection.AsyncRead**](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#asyncread) 的不透明关联值——如果读取来自 [**ContinuouslyReadFromPipe**](#continuouslyreadfrompipe) 触发的自动发起读取则为 **Empty**。 *Data* : 消息载荷。参见包概述上的[在事件中使用 `Data() As Byte`](/official/Reference/WinNamedPipesLib/#working-with-data-as-byte-in-events)了解瞬时缓冲区生命周期注意事项——如果稍后需要字节,请在处理程序返回之前将其复制出来。[推荐的捕获机制](/official/Reference/WinNamedPipesLib/#propertybag-carrier)是将 *Data* 赋值给新的 [**PropertyBag**](/official/Reference/VBRUN/PropertyBag/) 的 **Contents**,这会深拷贝字节并一步提供类型化的多字段访问。 ### ClientMessageSent 当之前发出的 [**NamedPipeServerConnection.AsyncWrite**](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#asyncwrite) 已完成(或当 [**AsyncBroadcast**](#asyncbroadcast) 消息到达每个客户端)时触发。 语法:*server*\_**ClientMessageSent**(*Connection* **As NamedPipeServerConnection**, **ByRef** *Cookie* **As Variant**) *Connection* : 写出时使用的连接。 *Cookie* : 传递给发起 [**AsyncWrite**](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#asyncwrite) 调用的不透明关联值。 ### ServerReady 在 [**Start**](#start) 之后触发一次,当每个IOCP工作线程已加入完成端口循环且第一个连接监听器已发布时。用作"服务器现在正在接受连接"的信号。 语法:*server*\_**ServerReady**() ## 方法 ### AsyncBroadcast 向每个当前已连接的客户端发出 [**AsyncWrite**](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection#asyncwrite)。 语法:*server*.**AsyncBroadcast** *Data*() \[, *Cookie* ] *Data* : *必需* 要发送的消息字节。twinBASIC 会将 **String** 字面量隐式强制转换为 **Byte()**,因此 `server.AsyncBroadcast "shutting down"` 无需单独的 `StrConv` 步骤即可工作——用于无协议的服务器推送通知很方便。 *Cookie* : *可选* 附加到*每个*每客户端 [**ClientMessageSent**](#clientmessagesent) 事件的 **Variant** 关联值。默认 **Empty**。 接收者集合在调用开始时在锁下快照。快照后连接的客户端不接收此广播;快照后但在每客户端写入完成之前断开连接的客户端只会静默失败该个别写入。 ### ManualMessageLoopEnter 在调用线程上运行Win32消息循环,直到从另一个线程调用 [**ManualMessageLoopLeave**](#manualmessageloopleave)(或任何处理程序引发 `WM_USER_QUITTING` 发布)。 语法:*server*.**ManualMessageLoopEnter** 用于没有自己Forms风格消息泵但想要默认([**FreeThreadingEvents**](#freethreadingevents) = **False**)封送事件语义的控制台/服务宿主。UI宿主自然地泵送消息,不需要此方法。 典型调用者是拥有此服务器的Windows服务:服务线程入口点打开服务器,将服务转换为 `Running`,调用 **ManualMessageLoopEnter** 在事件流动时阻塞,当SCM发出停止信号时,运行在调度器线程上的控制代码处理程序调用 [**ManualMessageLoopLeave**](#manualmessageloopleave)。参见包概述上的[在Windows服务中托管](/official/Reference/WinNamedPipesLib/#service-host-idiom)了解完整模式,包括双线程协调和 *Pause* / *Continue* 扩展。 ### ManualMessageLoopLeave 向隐藏的封送窗口发送 `WM_USER_QUITTING` 消息,使另一个线程上的 [**ManualMessageLoopEnter**](#manualmessageloopenter) 循环退出。可从任何线程安全调用。 语法:*server*.**ManualMessageLoopLeave** 预期调用者是在 [**ManualMessageLoopEnter**](#manualmessageloopenter) *之外*的线程——通常是Windows服务的调度器线程唤醒服务入口点线程离开其阻塞循环。参见[在Windows服务中托管](/official/Reference/WinNamedPipesLib/#service-host-idiom)。 ### Start 创建I/O完成端口,启动 [**NumThreadsIOCP**](#numthreadsiocp) 个工作线程,并在 `\\.\pipe\<PipeName>` 下发布第一个连接监听器。当每个工作线程已加入时触发 [**ServerReady**](#serverready)。 语法:*server*.**Start** 如果 [**PipeName**](#pipename) 为空则引发运行时错误5 *"cannot start without specifying a pipe name"*,或如果 `CreateIoCompletionPort` 失败则引发 *"unable to create an IOCP port"*。 幂等:在服务器已运行时调用 [**Start**](#start) 为无操作。 ### Stop 取消每个连接上每个未完成的I/O,向每个工作线程发送IOCP关闭哨兵,等待线程退出,关闭每个管道句柄,并释放完成端口。幂等:在未启动或已停止的服务器上调用 [**Stop**](#stop) 为无操作。自动从 `Class_Terminate` 调用,因此超出作用域的服务器隐式关闭资源。 语法:*server*.**Stop** ### New 在尚未启动的状态下构造服务器。创建用于将IOCP线程完成封送回UI线程的隐藏 `STATIC` 类消息窗口。 语法:**New NamedPipeServer** ## 另见 * [WinNamedPipesLib 包](/official/Reference/WinNamedPipesLib/) -- 概述、IOCP/事件封送架构、cookie模式、`Data()` 生命周期注意事项、已知限制 * [在Windows服务中托管](/official/Reference/WinNamedPipesLib/#service-host-idiom) -- **ManualMessageLoopEnter** / **ManualMessageLoopLeave** 服务入口点模式 * [推荐的载荷编码:`PropertyBag`](/official/Reference/WinNamedPipesLib/#propertybag-carrier) -- 事件中瞬时 *Data* 的深拷贝捕获模式 * [NamedPipeServerConnection 类](/official/Reference/WinNamedPipesLib/NamedPipeServerConnection) -- 传递给每个事件的每客户端连接 * [NamedPipeClientManager 类](/official/Reference/WinNamedPipesLib/NamedPipeClientManager) -- 客户端对应项 --- --- url: /en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection.md --- # NamedPipeServerConnection class One server-side per-client connection. A [**NamedPipeServer**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer) creates one of these for every client that connects, and passes it as the *Connection* parameter of every server event. Use it to send messages to that specific client, to manually issue reads when [**NamedPipeServer.ContinuouslyReadFromPipe**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer#continuouslyreadfrompipe) is **False**, and to close the connection from the server side. The class is tagged `[COMCreatable(False)]` and its constructor takes a package-private interface --- reach instances only through [**NamedPipeServer**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer) events. Connection-lifecycle and message events come through the parent [**NamedPipeServer**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer); this class holds the per-connection data and methods only. ```vb Private Sub server_ClientConnected(Connection As NamedPipeServerConnection) ' attach per-client state through the CustomData slot Connection.CustomData = New ClientSession End Sub Private Sub server_ClientMessageReceived( _ Connection As NamedPipeServerConnection, _ ByRef Cookie As Variant, _ ByRef Data() As Byte) Dim session As ClientSession = Connection.CustomData session.HandleMessage Data End Sub ``` See the package [overview](/en/official/Reference/WinNamedPipesLib/) for the IOCP / event-marshalling architecture, the cookie correlation pattern, and the transient lifetime of `Data() As Byte` inside events. ## Properties ### CustomData A per-connection opaque slot the consumer can attach state to --- typically a session object scoped to that one client. **Variant**, default **Empty**. The package never reads or writes this field; it is provided for convenience so that consumers do not have to maintain a parallel `Dictionary` keyed by [**Handle**](#handle). ### Handle The underlying Win32 named-pipe handle. **LongPtr**. Exposed for low-level / debugging use --- most consumers can ignore it. Do not call `CloseHandle` on this value directly; use [**AsyncClose**](#asyncclose) so the IOCP loop and the parent server's bookkeeping stay consistent. ### IsConnected **True** between the client connecting and the connection dropping. **Boolean**. Set internally; consumer code typically reads this rather than writes it. Becomes **False** as soon as the underlying pipe drops, even before the [**ClientDisconnected**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer#clientdisconnected) event fires (the event waits until every outstanding I/O has returned). ### IsOpening **True** during the brief window between the package creating the connection object and `ConnectNamedPipe` completing. **Boolean**. Used internally by [**NamedPipeServer.Stop**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer#stop) to avoid a race condition during shutdown; consumer code does not normally need to read it. ## Methods ### AsyncClose Cancels every outstanding I/O against this connection and closes the underlying pipe handle. Eventually triggers a [**ClientDisconnected**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer#clientdisconnected) event on the parent server once the cancellation completes. Automatically invoked from `Class_Terminate` when the last reference to the connection drops. Syntax: *connection*.**AsyncClose** ### AsyncRead Manually issues an asynchronous read against this connection. Syntax: *connection*.**AsyncRead** \[ *Cookie* \[, *OverlappedStruct* ] ] *Cookie* : *optional* A **Variant** correlation value, passed back as the *Cookie* parameter of the matching [**ClientMessageReceived**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer#clientmessagereceived) event. Default **Empty**. *OverlappedStruct* : *optional* A **LongPtr** to a pre-allocated `OVERLAPPED_CUSTOM` structure. **Internal use only** --- the IOCP machinery passes this when re-issuing a read after `ERROR_MORE_DATA`. Consumer code should always omit this parameter. Only needed when the parent server's [**ContinuouslyReadFromPipe**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer#continuouslyreadfrompipe) is **False**; otherwise the IOCP loop keeps a read pending automatically and explicit calls are redundant. ### AsyncWrite Sends a message back to this specific client. Syntax: *connection*.**AsyncWrite** *Data*() \[, *Cookie* ] *Data* : *required* A **Byte()** array containing the bytes to send. An uninitialised or zero-length array is a no-op. For typed multi-field payloads the recommended encoding is [**PropertyBag**](/en/official/Reference/VBRUN/PropertyBag/) --- see [Recommended payload encoding: `PropertyBag`](/en/official/Reference/WinNamedPipesLib/#propertybag-carrier) on the package overview. *Cookie* : *optional* A **Variant** correlation value, passed back as the *Cookie* parameter of the matching [**ClientMessageSent**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer#clientmessagesent) event. Default **Empty**. Returns immediately; the actual transmission runs through the IOCP loop. The completion fires [**ClientMessageSent**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer#clientmessagesent) on the parent server. ```vb ' Reply to a request using the PropertyBag convention: Dim reply As New PropertyBag reply.WriteProperty "ResponseCommandID", "WHAT_TIME_IS_IT" reply.WriteProperty "ResponseData", Time() Connection.AsyncWrite reply.Contents ``` To send the same message to every connected client at once, use [**NamedPipeServer.AsyncBroadcast**](/en/official/Reference/WinNamedPipesLib/NamedPipeServer#asyncbroadcast). ## See Also * [WinNamedPipesLib package](/en/official/Reference/WinNamedPipesLib/) -- overview, IOCP / event-marshalling architecture, cookie pattern, `Data()` lifetime caveat * [Recommended payload encoding: `PropertyBag`](/en/official/Reference/WinNamedPipesLib/#propertybag-carrier) -- the deep-copy capture / typed-payload convention for messages * [NamedPipeServer class](/en/official/Reference/WinNamedPipesLib/NamedPipeServer) -- the parent server that owns this connection * [NamedPipeClientConnection class](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) -- the client-side counterpart --- --- url: /zh/official/Reference/WinNamedPipesLib/NamedPipeServerConnection.md --- # NamedPipeServerConnection 类 一个服务器端的每客户端连接。[**NamedPipeServer**](/official/Reference/WinNamedPipesLib/NamedPipeServer) 为每个连接的客户端创建一个这样的对象,并将其作为每个服务器事件的 *Connection* 参数传递。使用它向特定客户端发送消息,在 [**NamedPipeServer.ContinuouslyReadFromPipe**](/official/Reference/WinNamedPipesLib/NamedPipeServer#continuouslyreadfrompipe) 为 **False** 时手动发出读取,以及从服务器端关闭连接。 该类标记为 `[COMCreatable(False)]`,其构造函数接受包私有接口——只能通过 [**NamedPipeServer**](/official/Reference/WinNamedPipesLib/NamedPipeServer) 事件获取实例。连接生命周期和消息事件通过父 [**NamedPipeServer**](/official/Reference/WinNamedPipesLib/NamedPipeServer) 传递;此类仅持有每连接的数据和方法。 ```vb Private Sub server_ClientConnected(Connection As NamedPipeServerConnection) ' 通过 CustomData 槽附加每客户端状态 Connection.CustomData = New ClientSession End Sub Private Sub server_ClientMessageReceived( _ Connection As NamedPipeServerConnection, _ ByRef Cookie As Variant, _ ByRef Data() As Byte) Dim session As ClientSession = Connection.CustomData session.HandleMessage Data End Sub ``` 参见包[概述](/official/Reference/WinNamedPipesLib/)了解IOCP/事件封送架构、cookie关联模式和事件中 `Data() As Byte` 的瞬时生命周期。 ## 属性 ### CustomData 消费者可附加状态的每连接不透明槽——通常是与该客户端关联的会话对象。**Variant**,默认 **Empty**。包从不读取或写入此字段;提供它是为了方便,使得消费者不必维护以 [**Handle**](#handle) 为键的并行 `Dictionary`。 ### Handle 底层Win32命名管道句柄。**LongPtr**。为低级/调试用途暴露——大多数消费者可以忽略。不要直接对此值调用 `CloseHandle`;使用 [**AsyncClose**](#asyncclose) 以保持IOCP循环和父服务器簿记的一致性。 ### IsConnected 在客户端连接和连接断开之间为 **True**。**Boolean**。内部设置;消费者代码通常读取而非写入。在底层管道断开时立即变为 **False**,甚至在 [**ClientDisconnected**](/official/Reference/WinNamedPipesLib/NamedPipeServer#clientdisconnected) 事件触发之前(事件等待每个未完成I/O已返回)。 ### IsOpening 在包创建连接对象到 `ConnectNamedPipe` 完成之间的短暂窗口内为 **True**。**Boolean**。由 [**NamedPipeServer.Stop**](/official/Reference/WinNamedPipesLib/NamedPipeServer#stop) 内部使用以避免关闭期间的竞态条件;消费者代码通常不需要读取它。 ## 方法 ### AsyncClose 取消对此连接的每个未完成I/O并关闭底层管道句柄。取消完成后最终触发父服务器上的 [**ClientDisconnected**](/official/Reference/WinNamedPipesLib/NamedPipeServer#clientdisconnected) 事件。当连接的最后一个引用丢弃时自动从 `Class_Terminate` 调用。 语法:*connection*.**AsyncClose** ### AsyncRead 手动对此连接发出异步读取。 语法:*connection*.**AsyncRead** \[ *Cookie* \[, *OverlappedStruct* ] ] *Cookie* : *可选* **Variant** 关联值,作为匹配的 [**ClientMessageReceived**](/official/Reference/WinNamedPipesLib/NamedPipeServer#clientmessagereceived) 事件的 *Cookie* 参数传回。默认 **Empty**。 *OverlappedStruct* : *可选* 指向预分配的 `OVERLAPPED_CUSTOM` 结构的 **LongPtr**。**仅供内部使用**——IOCP机制在 `ERROR_MORE_DATA` 后重新发出读取时传递此参数。消费者代码应始终省略此参数。 仅当父服务器的 [**ContinuouslyReadFromPipe**](/official/Reference/WinNamedPipesLib/NamedPipeServer#continuouslyreadfrompipe) 为 **False** 时需要;否则IOCP循环自动保持待处理读取,显式调用是冗余的。 ### AsyncWrite 向特定客户端发送回消息。 语法:*connection*.**AsyncWrite** *Data*() \[, *Cookie* ] *Data* : *必需* 包含要发送字节的 **Byte()** 数组。未初始化或零长度数组为无操作。对于类型化的多字段载荷,推荐编码为 [**PropertyBag**](/official/Reference/VBRUN/PropertyBag/)——参见包概述上的[推荐的载荷编码:`PropertyBag`](/official/Reference/WinNamedPipesLib/#propertybag-carrier)。 *Cookie* : *可选* **Variant** 关联值,作为匹配的 [**ClientMessageSent**](/official/Reference/WinNamedPipesLib/NamedPipeServer#clientmessagesent) 事件的 *Cookie* 参数传回。默认 **Empty**。 立即返回;实际传输通过IOCP循环运行。完成时触发父服务器上的 [**ClientMessageSent**](/official/Reference/WinNamedPipesLib/NamedPipeServer#clientmessagesent)。 ```vb ' 使用 PropertyBag 惯例回复请求: Dim reply As New PropertyBag reply.WriteProperty "ResponseCommandID", "WHAT_TIME_IS_IT" reply.WriteProperty "ResponseData", Time() Connection.AsyncWrite reply.Contents ``` 要一次向每个已连接客户端发送相同消息,使用 [**NamedPipeServer.AsyncBroadcast**](/official/Reference/WinNamedPipesLib/NamedPipeServer#asyncbroadcast)。 ## 另见 * [WinNamedPipesLib 包](/official/Reference/WinNamedPipesLib/) -- 概述、IOCP/事件封送架构、cookie模式、`Data()` 生命周期注意事项 * [推荐的载荷编码:`PropertyBag`](/official/Reference/WinNamedPipesLib/#propertybag-carrier) -- 消息的深拷贝捕获/类型化载荷惯例 * [NamedPipeServer 类](/official/Reference/WinNamedPipesLib/NamedPipeServer) -- 拥有此连接的父服务器 * [NamedPipeClientConnection 类](/official/Reference/WinNamedPipesLib/NamedPipeClientConnection) -- 客户端对应项 --- --- url: /en/official/Reference/VBRUN/Constants/NegotiatePositionConstants.md --- # NegotiatePositionConstants Position values for the **NegotiatePosition** property of menu items, controlling where a menu appears when an OLE in-place active object negotiates the host's menu bar. | Constant | Value | Description | |----------|-------|-------------| | **vbNegotiatePositionNone** | 0 | The menu is hidden during in-place activation. | | **vbNegotiatePositionLeft** | 1 | The menu is placed in the left group of the negotiated menu bar. | | **vbNegotiatePositionMiddle** | 2 | The menu is placed in the middle group. | | **vbNegotiatePositionRight** | 3 | The menu is placed in the right group. | --- --- url: /zh/official/Reference/VBRUN/Constants/NegotiatePositionConstants.md --- # NegotiatePositionConstants 菜单项**NegotiatePosition**属性的位置值,控制OLE就地活动对象协商宿主菜单栏时菜单出现在何处。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbNegotiatePositionNone** | 0 | 就地激活期间菜单被隐藏。 | | **vbNegotiatePositionLeft** | 1 | 菜单放置在协商菜单栏的左侧组。 | | **vbNegotiatePositionMiddle** | 2 | 菜单放置在中间组。 | | **vbNegotiatePositionRight** | 3 | 菜单放置在右侧组。 | --- --- url: /en/official/Reference/Core/New.md --- # New Creates a new instance of a class. The **New** keyword is used in two contexts: * In a declaration ([**Dim**](/en/official/Reference/Core/Dim), [**Private**](/en/official/Reference/Core/Private), [**Public**](/en/official/Reference/Core/Public), or [**Static**](/en/official/Reference/Core/Static)) to enable *implicit* object creation: a new instance is created on the first reference to the variable. * In a [**Set**](/en/official/Reference/Core/Set) statement, to create a new instance of a class and assign the reference to a variable or property. Syntax: * > \[ **Dim** | **Private** | **Public** | **Static** ] *varname* **As** **New** *type* * > **Set** *objectvar* **=** **New** *type* *varname*, *objectvar* : Name of the variable or property receiving the new object reference. *type* : A class name or other creatable object type. **New** can't be used to create new instances of any intrinsic data type (such as **Long** or **String**), and can't be used to create dependent objects. When **New** is used in a declaration, no instance is created at the point of declaration. Instead, an instance is created automatically the first time the variable is referenced after declaration. Each time the variable is set to **Nothing** and then referenced again, a new instance is created. When **New** is used with **Set**, an instance is created immediately, and the reference is assigned to *objectvar*. If *objectvar* previously held a reference to another object, that reference is released when the new one is assigned. ::: info **New** cannot be used together with **WithEvents** in a declaration. To connect an event-aware object reference, declare the variable with **WithEvents** and assign it later with **Set**. ::: ### Example Implicit creation via **New** in a declaration. The instance of `Worksheet` is created on first use, not at the **Dim** line. ```vb Dim X As New Worksheet ' No instance exists yet. X.Activate ' First reference - instance is created here. ``` Explicit creation via **Set ... = New**. The instance is created at the **Set** line. This is the more common form, since the moment of construction is visible at the call site. ```vb Dim Forms(1 To 4) As Form1 Dim i As Long For i = 1 To 4 Set Forms(i) = New Form1 Next i ``` ### See Also * [**Set** statement](/en/official/Reference/Core/Set) * [**Dim** statement](/en/official/Reference/Core/Dim) * [**Class** statement](/en/official/Reference/Core/Class) --- --- url: /zh/official/Reference/Core/New.md --- # New 创建类的新实例。 **New**关键字用于两种上下文: * 在声明语句([**Dim**](/official/Reference/Core/Dim)、[**Private**](/official/Reference/Core/Private)、[**Public**](/official/Reference/Core/Public)或[**Static**](/official/Reference/Core/Static))中启用*隐式*对象创建:首次引用变量时创建新实例。 * 在[**Set**](/official/Reference/Core/Set)语句中,创建类的新实例并将引用赋给变量或属性。 语法: * > \[ **Dim** | **Private** | **Public** | **Static** ] *varname* **As** **New** *type* * > **Set** *objectvar* **=** **New** *type* *varname*, *objectvar* : 接收新对象引用的变量或属性名称。 *type* : 类名或其他可创建的对象类型。**New**不能用于创建任何内部数据类型(如**Long**或**String**)的新实例,也不能用于创建依赖对象。 在声明中使用**New**时,不会在声明处创建实例。而是在声明后首次引用变量时自动创建实例。每次将变量设置为**Nothing**后再次引用,都会创建新实例。 在**Set**中使用**New**时,会立即创建实例,并将引用赋给*objectvar*。如果*objectvar*先前持有对另一个对象的引用,则在赋新引用时释放旧引用。 ::: info **New**不能与**WithEvents**在声明中一起使用。要连接可感知事件的对象引用,请先用**WithEvents**声明变量,然后再用**Set**赋值。 ::: ### 示例 通过声明中的**New**隐式创建。`Worksheet`的实例在首次使用时创建,而非在**Dim**行创建。 ```vb Dim X As New Worksheet ' No instance exists yet. X.Activate ' First reference - instance is created here. ``` 通过**Set ... = New**显式创建。实例在**Set**行创建。这是更常用的形式,因为构造的时刻在调用处可见。 ```vb Dim Forms(1 To 4) As Form1 Dim i As Long For i = 1 To 4 Set Forms(i) = New Form1 Next i ``` ### 另请参阅 * [**Set** 语句](/official/Reference/Core/Set) * [**Dim** 语句](/official/Reference/Core/Dim) * [**Class** 语句](/official/Reference/Core/Class) --- --- url: /en/official/Features/GUI-Components/New.md --- # New Controls twinBASIC introduces several new controls to enhance your applications. ## QR Code Control ![image](/assets/54ed49d8-b434-45e3-9e63-a1fe75cdf814.CsGo_QgA.png) Easily display custom QR codes with a native control. ## Multiframe Control ![image](/assets/4ad9c774-b31d-47d3-9963-6d99ac4f37bb.fM2RmIbS.png) This control allows you to create a number of frames within it with their size specified as a percentage, such that as the control is resized the frames within expand proportionally. For details and a video demonstration, Mike Wolfe's twinBASIC Weekly Update [covered it when released](https://nolongerset.com/twinbasic-update-april-29-2025/#experimental-multi-frame-control). Combined with anchors and docking, this allows designing highly functional and complex layouts visually, without writing any code to handling resizing. ## CheckMark Control ![image](/assets/5fc60b7b-4f54-445c-8504-451019b7ec55.kSlH4oTD.png) Primarily intended for reports but available in Forms and UserControls as well, the CheckMark control provides a scalable check component where this is fixed to a single size in a normal CheckBox control. --- --- url: /en/official/Features/Standard-Library/New-Functions.md --- # New Built-in Functions In addition to the new datatype-related and component name functions already described, the standard builtin `VBA` library now includes many new capabilities. ## New Functions * `IsArrayInitialized(variable)` - Determines if an array is initialized. Note: A `Variant` declared as empty array with `Array()` will return `True`. * `RGBA(r, g, b, a)` - Like the `RBG()` function, only including the alpha channel. * `RBG_R(rgba)`, `RGB_B(rgba)`, `RBG_G(rgba)`, and `RGBA_A(rgba)` - Get the values for individual channels. * `TranslateColor(ColorValue, Optional Palette)` - Translates an OLE color value to an RGB color. * `ProcessorArchitecture()` - Returns either `vbArchWin32` or `vbArchWin64`, depending on application bitness. * `CallByDispId(Object, DispId, CallType, Arguments)` - Similar to `CallByName()`, but uses the dispatch id instead of method name. * `RaiseEventByName(Object, Name, Args)` - Invokes an event on class, using arguments specified as a single `Variant` containing an array. * `RaiseEventByName2(Object, Name, Arg1, Arg2, ...)` - Invokes an event on class, using arguments specified as a ParamArray. * `PictureToByteArray(StdPicture)` - Converts a picture to a byte array; Global.LoadPicture supports loading from byte arrays. * `CreateGUID()` - Returns a string with a freshly generated GUID. * `AllocMem(size)` and `FreeMem` - allocate and free memory from the process heap. * `Int3Breakpoint` - Inserts a true breakpoint helpful for attached external debuggers. * `GetDeclaredTypeProgId(Of T)` / `GetDeclaredTypeClsid(Of T)` generics for getting strings of ProgID/CLSID. * `GetDeclaredMinEnumValue(Of T)` / `GetDeclaredMaxEnumValue(Of T)` generics. * Some `Interlocked*` functions ## Runtime Functions from msvbvm60.dll tB has built in support for some of the most commonly used runtime functions, for compatibility. These all support both 32 and 64bit. Unless otherwise noted, all of these function in two ways: First, built in native versions that are always present (unless you remove the basic compiler packages), with the most common arrangements of arguments. These don't require a `Declare` statement. If you *do* provide a `Declare` version, tB will allow whatever arrangements of arguments you specify (e.g. `As Any` instead of `As LongPtr`), mapped to an alias if provided. ### Memory Functions * `GetMem1`, `GetMem2`, `GetMem4`, `GetMem8`, `PutMem1`, `PutMem2`, `PutMem4`, `PutMem8` * New additions `GetMemPtr` and `PutMemPtr` pegged to the current pointer size ### Object Manipulation * `vbaObjSet`, `vbaObjSetAddref`, `vbaCastObj`, and `vbaObjAddref` for manipulating object assignments through pointers. ### Array Operations * `vbaCopyBytes` and `vbaCopyBytesZero` * `vbaAryMove` and `vbaRefVarAry` (currently only with a `Declare` statement). * tB also has an instrinsic `VarPtr` but will still redirect calls via a declare statement, e.g. aliases used for arrays (though tB's `VarPtr` supports arrays natively). ## New App Object Properties * `App.IsInIDE` - `True` when running from the IDE. * `App.IsElevated` - Returns whether the program is currently running with administrator rights. * `App.LastBuildPath` - Returns the full path of the last build. Does not persist between compiler/IDE restarts. * `App.Build` - For the additional version number field. * `App.ModulePath` - Returns the full path of the currently executing module. For example, if placed in a DLL and called from an EXE, the path of the DLL would be returned. Also, the twinBASIC debugger DLL is given when running from the IDE, when the method is in the app itself. ## COM Error Handling ### Direct Access to COM Errors You can retrieve the last `HRESULT` to a COM interface call via `Err.LastHResult`; these are usually hidden and mapped to internal errors-- everything in a COM interface normally called a `Sub` is actually an `HRESULT`-returning function. ### Setting Return HRESULT More importantly, you can now **set** the `HRESULT` in interface implementations with `Err.ReturnHResult`. This was a critical missing feature for which sometimes Err.Raise would work, but mostly programmers resorted to complicated vtable-swapping code to redirect to a standard module function. For instance you can now return `S_FALSE` where expected with `Err.ReturnHResult = S_FALSE`. ## Destructuring Assignment This feature allows you to assign the contents of an array to multiple variables in a single line: ```vb Dim a As Long, b As Long, c As Long Dim d(2) As Long d(0) = 1 d(1) = 2 d(2) = 3 Array(a, b, c) = d Debug.Print a, b, c ``` This would print `1 2 3`. You could also assign multiple variables at once like this and get the same result: ```vb Dim a As Long, b As Long, c As Long Array(a, b, c) = Array(1, 2, 3) Debug.Print a, b, c ``` You can now also do assignments like this: ```vb Dim a As Long = 9 Dim b As Long = 7 Dim c() As Long = Array(a, b) Debug.Print c(1), UBound(c) ``` Which prints `7 1`. --- --- url: /en/official/Reference/WinNativeCommonCtls/TreeView/Node.md --- # Node class A **Node** is a single entry in a [**TreeView**](/en/official/Reference/WinNativeCommonCtls/TreeView/)'s [**Nodes**](/en/official/Reference/WinNativeCommonCtls/TreeView/Nodes) collection. Returned from [**Nodes.Add**](/en/official/Reference/WinNativeCommonCtls/TreeView/Nodes#add) and from [**Nodes.Item**](/en/official/Reference/WinNativeCommonCtls/TreeView/Nodes#item). Each node has its own text, icons, sort settings, check state, and sibling / parent / child relationships. The class is tagged `[COMCreatable(False)]` --- user code accesses **Node** instances through the parent [**TreeView**](/en/official/Reference/WinNativeCommonCtls/TreeView/)'s [**Nodes**](/en/official/Reference/WinNativeCommonCtls/TreeView/Nodes) collection or through navigation properties on other nodes. ```vb Dim root As Node = TreeView1.Nodes.Add(, , "root", "My Computer") Dim drive As Node = TreeView1.Nodes.Add(root, tvwChild, "c", "C: drive") drive.Bold = True drive.Image = "disk" Debug.Print drive.FullPath ' "My Computer\C: drive" Debug.Print drive.Parent.Text ' "My Computer" Debug.Print drive.Root.Text ' "My Computer" ``` ## Properties ### BackColor The background color used to render this node. **OLE\_COLOR**. Default: **vbWindowBackground**. ### Bold Whether the node text is rendered in a bold font. **Boolean**. Default: **False**. ### Checked Whether the node's checkbox is checked. **Boolean**. Only meaningful when [**TreeView.CheckBoxes**](/en/official/Reference/WinNativeCommonCtls/TreeView/#checkboxes) is **True**. ### Child The first child node of this node, or **Nothing** if it has no children. **Node**, read-only. ### Children The number of immediate child nodes of this node. **Long**, read-only. ### Expanded Whether the node is currently expanded (showing its children). **Boolean**, read/write. Assigning fires [**TreeView.BeforeExpand**](/en/official/Reference/WinNativeCommonCtls/TreeView/#beforeexpand) / [**TreeView.BeforeCollapse**](/en/official/Reference/WinNativeCommonCtls/TreeView/#beforecollapse) (cancellable) followed by [**TreeView.Expand**](/en/official/Reference/WinNativeCommonCtls/TreeView/#expand) / [**TreeView.Collapse**](/en/official/Reference/WinNativeCommonCtls/TreeView/#collapse). ### FirstSibling The first sibling of this node (the leftmost peer under the same parent). **Node**, read-only. If the node is itself the first sibling, returns the node. ### ForeColor The text color used to render this node. **OLE\_COLOR**. Default: **vbWindowText**. ### FullPath The hierarchical path from the root to this node, with [**TreeView.PathSeparator**](/en/official/Reference/WinNativeCommonCtls/TreeView/#pathseparator) inserted between node texts. **String**, read-only. Example: a node "C: drive" whose parent is "My Computer" returns `"My Computer\C: drive"`. ### Image The icon rendered when the node is not selected. **Variant** --- either a 1-based **Long** index into [**TreeView.ImageList**](/en/official/Reference/WinNativeCommonCtls/TreeView/#imagelist), or a **String** key. Assignment validates against the bound image list. ### Index The 1-based position of this node in the parent collection. **Long**, read-only. ### Key The string key the node was added under. **String**, read/write. ### LastSibling The last sibling of this node (the rightmost peer under the same parent). **Node**, read-only. ### Next The next sibling of this node, or **Nothing** if this is the last sibling. **Node**, read-only. ### Parent The parent **Node**, or **Nothing** if this node is at the root level. **Node**, read/write. Note: assigning **Parent** does not move the node --- it merely changes the recorded parent reference. ### Previous The previous sibling of this node, or **Nothing** if this is the first sibling. **Node**, read-only. ### Root The root node of the subtree this node belongs to. **Node**, read-only. ### Selected Whether this node is the [**TreeView.SelectedItem**](/en/official/Reference/WinNativeCommonCtls/TreeView/#selecteditem) of the treeview. **Boolean**, read/write. ### SelectedImage The icon rendered when the node is selected. **Variant** --- either an index or a key into [**TreeView.ImageList**](/en/official/Reference/WinNativeCommonCtls/TreeView/#imagelist). When unset, defaults to the same as [**Image**](#image). ### Sorted Whether this node's children are sorted. **Boolean**. Default: **False**. Independent of [**TreeView.Sorted**](/en/official/Reference/WinNativeCommonCtls/TreeView/#sorted), which controls root-level sorting. ### SortOrder The sort direction for this node's children. A member of [**TreeSortOrderConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortOrderConstants). Default: **tvwAscending**. ### SortType The string comparison used for sorting this node's children. A member of [**TreeSortTypeConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortTypeConstants): **tvwBinary** or **tvwText**. Default: **tvwText**. ### Tag Arbitrary data the application can attach to the node. **Variant**. ### Text The node's label text. **String**, read/write. ### Visible Whether the node is currently visible --- i.e. not hidden because an ancestor is collapsed and not scrolled out of view. **Boolean**, read-only. ## Methods ### EnsureVisible Scrolls and expands ancestor nodes as necessary to make this node visible in the treeview. Syntax: *object*.**EnsureVisible** ## See Also * [TreeView](/en/official/Reference/WinNativeCommonCtls/TreeView/) -- the parent control * [Nodes](/en/official/Reference/WinNativeCommonCtls/TreeView/Nodes) -- the collection holding **Node** instances * [TreeSortOrderConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortOrderConstants), [TreeSortTypeConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortTypeConstants) -- the **SortOrder** / **SortType** enums --- --- url: /zh/official/Reference/WinNativeCommonCtls/TreeView/Node.md --- # Node 类 **Node** 是 [**TreeView**](/official/Reference/WinNativeCommonCtls/TreeView/) 的 [**Nodes**](/official/Reference/WinNativeCommonCtls/TreeView/Nodes) 集合中的单个条目。从 [**Nodes.Add**](/official/Reference/WinNativeCommonCtls/TreeView/Nodes#add) 和 [**Nodes.Item**](/official/Reference/WinNativeCommonCtls/TreeView/Nodes#item) 返回。每个节点拥有自己的文本、图标、排序设置、选中状态和同级/父级/子级关系。 该类标记为 `[COMCreatable(False)]` --- 用户代码通过父级 [**TreeView**](/official/Reference/WinNativeCommonCtls/TreeView/) 的 [**Nodes**](/official/Reference/WinNativeCommonCtls/TreeView/Nodes) 集合或其他节点上的导航属性访问 **Node** 实例。 ```vb Dim root As Node = TreeView1.Nodes.Add(, , "root", "My Computer") Dim drive As Node = TreeView1.Nodes.Add(root, tvwChild, "c", "C: drive") drive.Bold = True drive.Image = "disk" Debug.Print drive.FullPath ' "My Computer\C: drive" Debug.Print drive.Parent.Text ' "My Computer" Debug.Print drive.Root.Text ' "My Computer" ``` ## 属性 ### BackColor 用于渲染此节点的背景颜色。**OLE\_COLOR**。默认:**vbWindowBackground**。 ### Bold 节点文本是否以粗体渲染。**Boolean**。默认:**False**。 ### Checked 节点的复选框是否选中。**Boolean**。仅在 [**TreeView.CheckBoxes**](/official/Reference/WinNativeCommonCtls/TreeView/#checkboxes) 为 **True** 时有意义。 ### Child 此节点的第一个子节点,如果没有子节点则为 **Nothing**。**Node**,只读。 ### Children 此节点的直接子节点数。**Long**,只读。 ### Expanded 节点当前是否展开(显示其子节点)。**Boolean**,读/写。赋值触发 [**TreeView.BeforeExpand**](/official/Reference/WinNativeCommonCtls/TreeView/#beforeexpand) / [**TreeView.BeforeCollapse**](/official/Reference/WinNativeCommonCtls/TreeView/#beforecollapse)(可取消),随后触发 [**TreeView.Expand**](/official/Reference/WinNativeCommonCtls/TreeView/#expand) / [**TreeView.Collapse**](/official/Reference/WinNativeCommonCtls/TreeView/#collapse)。 ### FirstSibling 此节点的第一个同级节点(同一父级下最左侧的对等节点)。**Node**,只读。如果节点本身就是第一个同级,则返回该节点。 ### ForeColor 用于渲染此节点的文本颜色。**OLE\_COLOR**。默认:**vbWindowText**。 ### FullPath 从根到此节点的层次路径,节点文本之间插入 [**TreeView.PathSeparator**](/official/Reference/WinNativeCommonCtls/TreeView/#pathseparator)。**String**,只读。 示例:父节点为"My Computer"的"C: drive"节点返回 `"My Computer\C: drive"`。 ### Image 节点未选中时渲染的图标。**Variant** --- 可以是基于1的 **Long** 索引指向 [**TreeView.ImageList**](/official/Reference/WinNativeCommonCtls/TreeView/#imagelist),或 **String** 键。赋值会对照绑定图像列表进行验证。 ### Index 此节点在父集合中基于1的位置。**Long**,只读。 ### Key 节点添加时的字符串键。**String**,读/写。 ### LastSibling 此节点的最后一个同级节点(同一父级下最右侧的对等节点)。**Node**,只读。 ### Next 此节点的下一个同级节点,如果这是最后一个同级则为 **Nothing**。**Node**,只读。 ### Parent 父级 **Node**,如果此节点位于根级则为 **Nothing**。**Node**,读/写。注意:赋值 **Parent** 不会移动节点 --- 它仅更改记录的父级引用。 ### Previous 此节点的前一个同级节点,如果这是第一个同级则为 **Nothing**。**Node**,只读。 ### Root 此节点所属子树的根节点。**Node**,只读。 ### Selected 此节点是否为树视图的 [**TreeView.SelectedItem**](/official/Reference/WinNativeCommonCtls/TreeView/#selecteditem)。**Boolean**,读/写。 ### SelectedImage 节点选中时渲染的图标。**Variant** --- 可以是一个索引或 [**TreeView.ImageList**](/official/Reference/WinNativeCommonCtls/TreeView/#imagelist) 的键。未设置时默认与 [**Image**](#image) 相同。 ### Sorted 此节点的子节点是否排序。**Boolean**。默认:**False**。独立于控制根级排序的 [**TreeView.Sorted**](/official/Reference/WinNativeCommonCtls/TreeView/#sorted)。 ### SortOrder 此节点子节点的排序方向。[**TreeSortOrderConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortOrderConstants) 的成员。默认:**tvwAscending**。 ### SortType 此节点子节点排序使用的字符串比较。[**TreeSortTypeConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortTypeConstants) 的成员:**tvwBinary** 或 **tvwText**。默认:**tvwText**。 ### Tag 应用程序可附加到节点的任意数据。**Variant**。 ### Text 节点的标签文本。**String**,读/写。 ### Visible 节点当前是否可见 --- 即未因祖先折叠而隐藏且未滚出视图。**Boolean**,只读。 ## 方法 ### EnsureVisible 滚动并展开祖先节点以使此节点在树视图中可见。 语法:*object*.**EnsureVisible** ## 另见 * [TreeView](/official/Reference/WinNativeCommonCtls/TreeView/) --- 父控件 * [Nodes](/official/Reference/WinNativeCommonCtls/TreeView/Nodes) --- 持有 **Node** 实例的集合 * [TreeSortOrderConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortOrderConstants)、[TreeSortTypeConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeSortTypeConstants) --- **SortOrder** / **SortType** 枚举 --- --- url: /en/official/Reference/WinNativeCommonCtls/TreeView/Nodes.md --- # Nodes class The **Nodes** collection is the entry point for managing the [**Node**](/en/official/Reference/WinNativeCommonCtls/TreeView/Node) tree of a [**TreeView**](/en/official/Reference/WinNativeCommonCtls/TreeView/). Accessed as `<treeView>.Nodes`; supports adding, removing, indexed access, and `For Each` iteration. The class is tagged `[COMCreatable(False)]` --- user code accesses **Nodes** through the parent [**TreeView**](/en/official/Reference/WinNativeCommonCtls/TreeView/) control's [**Nodes**](/en/official/Reference/WinNativeCommonCtls/TreeView/#nodes) property. ```vb With TreeView1.Nodes Dim root As Node Set root = .Add(, , "root", "My Computer") .Add root, tvwChild, "c", "C: drive" .Add root, tvwChild, "d", "D: drive" End With Dim node As Node For Each node In TreeView1.Nodes Debug.Print node.Index, node.Key, node.FullPath Next ``` The `For Each` iteration visits **only the nodes in the order they were added** --- not in tree order. For a depth-first or breadth-first traversal that follows the visual hierarchy, traverse the parent-child links manually starting from a root [**Node**](/en/official/Reference/WinNativeCommonCtls/TreeView/Node) and using [**Node.Child**](/en/official/Reference/WinNativeCommonCtls/TreeView/Node#child) / [**Node.Next**](/en/official/Reference/WinNativeCommonCtls/TreeView/Node#next). ## Properties ### Count The total number of nodes in the treeview (root nodes plus all descendants). **Long**, read-only. ### Item Returns the [**Node**](/en/official/Reference/WinNativeCommonCtls/TreeView/Node) at the given index or with the given key. The default member, so `TreeView1.Nodes("root")` works without writing `.Item("root")`. Syntax: *object*.**Item** ( *Index* ) **As Node** *Index* : A **Variant** --- either a 1-based **Long** position or a **String** key. ## Methods ### Add Adds a node to the treeview, optionally positioned relative to another node. Syntax: *object*.**Add** ( \[ *Relative* ] \[, *Relationship* ] \[, *Key* ] \[, *Text* ] \[, *Image* ] \[, *SelectedImage* ] ) **As Node** *Relative* : *optional* A **Variant** identifying the existing node the new node will be positioned against --- either a [**Node**](/en/official/Reference/WinNativeCommonCtls/TreeView/Node) reference, a 1-based **Long** index, or a **String** key. When omitted, the new node is inserted at the root level using *Relationship* = **tvwNext** semantics. *Relationship* : *optional* A member of [**TreeRelationshipConstants**](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeRelationshipConstants) describing where the new node is placed relative to *Relative*. Default: **tvwNext**. *Key* : *optional* A **String** name under which the node can be looked up. Keys must be unique within the **Nodes** collection (otherwise run-time error 35602). *Text* : *optional* A **String** giving the node's label. *Image* : *optional* A **Variant** identifying the unselected-state icon --- either a 1-based **Long** index into [**TreeView.ImageList**](/en/official/Reference/WinNativeCommonCtls/TreeView/#imagelist), or a **String** key. *SelectedImage* : *optional* A **Variant** identifying the selected-state icon. When unset, defaults to the same as *Image*. Returns the newly-created [**Node**](/en/official/Reference/WinNativeCommonCtls/TreeView/Node). ### Clear Removes every node from the treeview, including all descendants. Syntax: *object*.**Clear** ### Remove Removes a node from the treeview, along with all its descendants. The remaining nodes' [**Index**](/en/official/Reference/WinNativeCommonCtls/TreeView/Node#index) values are recomputed. Syntax: *object*.**Remove** ( *Index* ) *Index* : A **Variant** --- either a 1-based **Long** position or a **String** key. ### \_NewEnum Returns the enumerator used by `For Each node In treeView.Nodes`. Iterates nodes in **Index** order (the order they were added), not in tree-traversal order. Syntax: *object*.**\_NewEnum** **As stdole.IUnknown** ## See Also * [TreeView](/en/official/Reference/WinNativeCommonCtls/TreeView/) -- the parent control * [Node](/en/official/Reference/WinNativeCommonCtls/TreeView/Node) -- one node in the collection * [TreeRelationshipConstants](/en/official/Reference/WinNativeCommonCtls/Enumerations/TreeRelationshipConstants) -- the *Relationship* values for [**Add**](#add) --- --- url: /zh/official/Reference/WinNativeCommonCtls/TreeView/Nodes.md --- # Nodes 类 **Nodes** 集合是管理 [**TreeView**](/official/Reference/WinNativeCommonCtls/TreeView/) 的 [**Node**](/official/Reference/WinNativeCommonCtls/TreeView/Node) 树的入口。通过 `<treeView>.Nodes` 访问;支持添加、删除、索引访问和 `For Each` 迭代。 该类标记为 `[COMCreatable(False)]` --- 用户代码通过父级 [**TreeView**](/official/Reference/WinNativeCommonCtls/TreeView/) 控件的 [**Nodes**](/official/Reference/WinNativeCommonCtls/TreeView/#nodes) 属性访问 **Nodes**。 ```vb With TreeView1.Nodes Dim root As Node Set root = .Add(, , "root", "My Computer") .Add root, tvwChild, "c", "C: drive" .Add root, tvwChild, "d", "D: drive" End With Dim node As Node For Each node In TreeView1.Nodes Debug.Print node.Index, node.Key, node.FullPath Next ``` `For Each` 迭代**仅按添加顺序访问节点** --- 而非树序。对于遵循视觉层次的深度优先或广度优先遍历,请从根 [**Node**](/official/Reference/WinNativeCommonCtls/TreeView/Node) 开始手动遍历父子链接,使用 [**Node.Child**](/official/Reference/WinNativeCommonCtls/TreeView/Node#child) / [**Node.Next**](/official/Reference/WinNativeCommonCtls/TreeView/Node#next)。 ## 属性 ### Count 树视图中的节点总数(根节点加所有后代)。**Long**,只读。 ### Item 返回给定索引或键的 [**Node**](/official/Reference/WinNativeCommonCtls/TreeView/Node)。默认成员,因此 `TreeView1.Nodes("root")` 无须写 `.Item("root")`。 语法:*object*.**Item**(*Index*)**As Node** *Index* : 一个 **Variant** --- 可以是基于1的 **Long** 位置或 **String** 键。 ## 方法 ### Add 向树视图添加一个节点,可选相对于另一个节点定位。 语法:*object*.**Add**(\[*Relative*] \[, *Relationship*] \[, *Key*] \[, *Text*] \[, *Image*] \[, *SelectedImage*])**As Node** *Relative* : *可选* 标识新节点定位所依据的现有节点的 **Variant** --- 可以是 [**Node**](/official/Reference/WinNativeCommonCtls/TreeView/Node) 引用、基于1的 **Long** 索引或 **String** 键。省略时,新节点按 *Relationship* = **tvwNext** 语义在根级插入。 *Relationship* : *可选* [**TreeRelationshipConstants**](/official/Reference/WinNativeCommonCtls/Enumerations/TreeRelationshipConstants) 的成员,描述新节点相对于 *Relative* 的位置。默认:**tvwNext**。 *Key* : *可选* 一个 **String** 名称,可通过其查找节点。键在 **Nodes** 集合中必须唯一(否则运行时错误 35602)。 *Text* : *可选* 一个给出节点标签的 **String**。 *Image* : *可选* 标识未选中状态图标的 **Variant** --- 可以是基于1的 **Long** 索引指向 [**TreeView.ImageList**](/official/Reference/WinNativeCommonCtls/TreeView/#imagelist) 或 **String** 键。 *SelectedImage* : *可选* 标识选中状态图标的 **Variant**。未设置时默认与 *Image* 相同。 返回新创建的 [**Node**](/official/Reference/WinNativeCommonCtls/TreeView/Node)。 ### Clear 从树视图中移除所有节点,包括所有后代。 语法:*object*.**Clear** ### Remove 从树视图中移除一个节点及其所有后代。剩余节点的 [**Index**](/official/Reference/WinNativeCommonCtls/TreeView/Node#index) 值会重新计算。 语法:*object*.**Remove**(*Index*) *Index* : 一个 **Variant** --- 可以是基于1的 **Long** 位置或 **String** 键。 ### \_NewEnum 返回 `For Each node In treeView.Nodes` 使用的枚举器。按 **Index** 顺序(添加顺序)迭代节点,而非树遍历顺序。 语法:*object*.**\_NewEnum** **As stdole.IUnknown** ## 另见 * [TreeView](/official/Reference/WinNativeCommonCtls/TreeView/) --- 父控件 * [Node](/official/Reference/WinNativeCommonCtls/TreeView/Node) --- 集合中的一个节点 * [TreeRelationshipConstants](/official/Reference/WinNativeCommonCtls/Enumerations/TreeRelationshipConstants) --- [**Add**](#add) 的 *Relationship* 值 --- --- url: /en/official/Reference/Core/Not.md --- # Not operator Used to perform bitwise negation on an expression. Syntax: > *result* **=** **Not** *expression* *result* : Any numeric variable. *expression* : Any expression. The following table illustrates how *result* is determined: | If *expression* is | Then *result* is | |:-----|:-----| | **True** | **False** | | **False** | **True** | | **Null** | **Null** | The **Not** operator inverts the bit values of its operand and sets the corresponding bit in *result* according to the following table: | If bit in *expression* is | Then bit in *result* is | |:-----:|:-----:| | 0 | 1 | | 1 | 0 | ### Example This example uses the **Not** operator to perform logical negation on an expression. ```vb Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = Not (A > B) ' Returns False. MyCheck = Not (B > A) ' Returns True. MyCheck = Not (C > D) ' Returns Null. MyCheck = Not A ' Returns -11 (bitwise comparison). ``` ### See Also * [**And** operator](/en/official/Reference/Core/And) * [**Or** operator](/en/official/Reference/Core/Or) * [**Xor** operator](/en/official/Reference/Core/Xor) * [**Eqv** operator](/en/official/Reference/Core/Eqv) * [**Imp** operator](/en/official/Reference/Core/Imp) * [**IsNot** operator](/en/official/Reference/Core/IsNot) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Not.md --- # Not 运算符 用于对表达式执行按位取反。 语法: > *result* **=** **Not** *expression* *result* : 任意数值变量。 *expression* : 任意表达式。 下表说明*result*的确定方式: | 如果 *expression* 为 | 则 *result* 为 | |:-----|:-----| | **True** | **False** | | **False** | **True** | | **Null** | **Null** | **Not**运算符反转其操作数的位值,并根据下表设置*result*中的相应位: | 如果 *expression* 中的位为 | 则 *result* 中的位为 | |:-----:|:-----:| | 0 | 1 | | 1 | 0 | ### 示例 本示例使用**Not**运算符对表达式执行逻辑取反。 ```vb Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = Not (A > B) ' Returns False. MyCheck = Not (B > A) ' Returns True. MyCheck = Not (C > D) ' Returns Null. MyCheck = Not A ' Returns -11 (bitwise comparison). ``` ### 另请参阅 * [**And** 运算符](/official/Reference/Core/And) * [**Or** 运算符](/official/Reference/Core/Or) * [**Xor** 运算符](/official/Reference/Core/Xor) * [**Eqv** 运算符](/official/Reference/Core/Eqv) * [**Imp** 运算符](/official/Reference/Core/Imp) * [**IsNot** 运算符](/official/Reference/Core/IsNot) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Tutorials/CustomControls/Notes-about-the-form-designer.md --- # Notes About the Form Designer For the painting of controls in the form designer, CustomControl instances are instantiated and then release immediately after painting has finished. The design-mode flag is exposed on the framework's [`SerializeInfo.RuntimeUISrzIsDesignMode`](/en/official/Reference/CustomControls/Framework/SerializeInfo#runtimeuisrzisdesignmode) --- controls that want to render a placeholder only inside the designer (the way [`WaynesTimer`](/en/official/Reference/CustomControls/WaynesTimer) draws its 🕑 glyph) check this flag during [`Initialize`](/en/official/Reference/CustomControls/Framework/ICustomControl#initialize). ## See also * [CustomControls package reference](/en/official/Reference/CustomControls/) -- overview of the framework and the built-in `Waynes…` controls --- --- url: /en/official/Reference/VBA/DateTime/Now.md --- # Now Returns a **Variant** (**Date**) specifying the current date and time according to the system date and time. Syntax: **Now** \[ **()** ] ### Example This example uses the **Now** function to return the current system date and time. ```vb Dim Today Today = Now ' Assign current system date and time. Debug.Print Today ' Prints e.g. 5/7/2026 2:30:15 PM Debug.Print Year(Today) ' e.g. 2026 Debug.Print Month(Today) ' e.g. 5 Debug.Print Hour(Today) ' e.g. 14 ``` ### See Also * [Date](/en/official/Reference/VBA/DateTime/Date), [Time](/en/official/Reference/VBA/DateTime/Time) properties --- --- url: /zh/official/Reference/VBA/DateTime/Now.md --- # Now 返回一个 **Variant** (**Date**),根据系统日期和时间指定当前日期和时间。 语法:**Now** \[ **()** ] ### 示例 此示例使用 **Now** 函数返回当前系统日期和时间。 ```vb Dim Today Today = Now ' Assign current system date and time. Debug.Print Today ' Prints e.g. 5/7/2026 2:30:15 PM Debug.Print Year(Today) ' e.g. 2026 Debug.Print Month(Today) ' e.g. 5 Debug.Print Hour(Today) ' e.g. 14 ``` ### 另请参阅 * [Date](/official/Reference/VBA/DateTime/Date)、[Time](/official/Reference/VBA/DateTime/Time) 属性 --- --- url: /zh/official/Reference/Core/Now.md --- # Now 函数 Now 关键字的文档尚不可用。 --- --- url: /en/official/Reference/Core/Now.md --- # Now Function Documentation for the now keyword is not yet available. --- --- url: /en/official/Reference/VBA/Financial/NPer.md --- # NPer Returns a **Double** specifying the number of periods for an annuity based on periodic, fixed payments and a fixed interest rate. Syntax: **NPer(** *rate*, *pmt*, *pv* \[ **,** *fv* \[ **,** *type* ] ] **)** *rate* : *required* **Double** specifying interest rate per period. For example, for a car loan at an annual percentage rate (APR) of 10 percent with monthly payments, the rate per period is 0.1/12, or 0.0083. *pmt* : *required* **Double** specifying payment to be made each period. Payments usually contain principal and interest that doesn't change over the life of the annuity. *pv* : *required* **Double** specifying present value, or value today, of a series of future payments or receipts. For example, when borrowing money to buy a car, the loan amount is the present value to the lender of the monthly car payments to be made. *fv* : *optional* **Variant** specifying future value or cash balance remaining after the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, to save $50,000 over 18 years for a child's education, $50,000 is the future value. If omitted, 0 is assumed. *type* : *optional* **Variant** specifying when payments are due. 0 means payments are due at the end of the period; 1 means payments are due at the beginning. If omitted, 0 is assumed. An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan). For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers. ### Example This example uses the **NPer** function to return the number of periods during which payments must be made to pay off a loan whose value is contained in `PVal`. Also provided are the interest percentage rate per period (`APR / 12`), the payment (`Payment`), the future value of the loan (`FVal`), and a number that indicates whether the payment is due at the beginning or end of the payment period (`PayType`). ```vb Dim FVal, PVal, APR, Payment, PayType, TotPmts Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. FVal = 0 ' Usually 0 for a loan. PVal = InputBox("How much do you want to borrow?") APR = InputBox("What is the annual percentage rate of your loan?") If APR > 1 Then APR = APR / 100 ' Ensure proper form. Payment = InputBox("How much do you want to pay each month?") PayType = MsgBox("Do you make payments at the end of month?", vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD TotPmts = NPer(APR / 12, -Payment, PVal, FVal, PayType) If Int(TotPmts) <> TotPmts Then TotPmts = Int(TotPmts) + 1 MsgBox "It will take you " & TotPmts & " months to pay off your loan." ``` ### See Also * [FV](/en/official/Reference/VBA/Financial/FV), [PV](/en/official/Reference/VBA/Financial/PV), [Pmt](/en/official/Reference/VBA/Financial/Pmt), [Rate](/en/official/Reference/VBA/Financial/Rate) functions --- --- url: /zh/official/Reference/VBA/Financial/NPer.md --- # NPer 返回一个**Double**值,指定基于定期固定付款和固定利率的年金期数。 语法:**NPer(** *rate*, *pmt*, *pv* \[ **,** *fv* \[ **,** *type* ] ] **)** *rate* : *必需* **Double**,指定每期利率。例如,对于年利率(APR)为10%且按月还款的汽车贷款,每期利率为0.1/12,即0.0083。 *pmt* : *必需* **Double**,指定每期应付金额。付款通常包含在年金期限内不变的本金和利息。 *pv* : *必需* **Double**,指定一系列未来付款或收入的现值。例如,贷款买车时,贷款金额就是贷款人未来每月车贷还款的现值。 *fv* : *可选* **Variant**,指定最终付款后的未来值或现金余额。例如,贷款的未来值为$0,因为这是最终付款后的价值。但如果要在18年内为孩子的教育储蓄$50,000,则$50,000就是未来值。如果省略,则默认为0。 *type* : *可选* **Variant**,指定付款到期时间。0表示期末付款;1表示期初付款。如果省略,则默认为0。 年金是在一段时间内进行的一系列固定现金支付。年金可以是贷款(如住房抵押贷款)或投资(如月度储蓄计划)。 对于所有参数,支出的现金(如储蓄存款)用负数表示;收入的现金(如股息支票)用正数表示。 ### 示例 本示例使用**NPer**函数返回偿还值为`PVal`的贷款所需的付款期数。同时提供了每期利率百分比(`APR / 12`)、付款金额(`Payment`)、贷款未来值(`FVal`)以及指示付款是在期初还是期末到期的数字(`PayType`)。 ```vb Dim FVal, PVal, APR, Payment, PayType, TotPmts Const ENDPERIOD = 0, BEGINPERIOD = 1 ' When payments are made. FVal = 0 ' Usually 0 for a loan. PVal = InputBox("How much do you want to borrow?") APR = InputBox("What is the annual percentage rate of your loan?") If APR > 1 Then APR = APR / 100 ' Ensure proper form. Payment = InputBox("How much do you want to pay each month?") PayType = MsgBox("Do you make payments at the end of month?", vbYesNo) If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD TotPmts = NPer(APR / 12, -Payment, PVal, FVal, PayType) If Int(TotPmts) <> TotPmts Then TotPmts = Int(TotPmts) + 1 MsgBox "It will take you " & TotPmts & " months to pay off your loan." ``` ### 另请参阅 * [FV](/official/Reference/VBA/Financial/FV)、[PV](/official/Reference/VBA/Financial/PV)、[Pmt](/official/Reference/VBA/Financial/Pmt)、[Rate](/official/Reference/VBA/Financial/Rate)函数 --- --- url: /en/official/Reference/VBA/Financial/NPV.md --- # NPV Returns a **Double** specifying the net present value of an investment based on a series of periodic cash flows (payments and receipts) and a discount rate. Syntax: **NPV(** *rate*, *values()* **)** *rate* : *required* **Double** specifying discount rate over the length of the period, expressed as a decimal. *values()* : *required* Array of **Double** specifying cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt). The net present value of an investment is the current value of a future series of payments and receipts. The **NPV** function uses the order of values within the array to interpret the order of payments and receipts. The payment and receipt values must be in the correct sequence. The **NPV** investment begins one period before the date of the first cash flow value and ends with the last cash flow value in the array. The net present value calculation is based on future cash flows. If the first cash flow occurs at the beginning of the first period, the first value must be added to the value returned by **NPV** and must not be included in the cash flow values of *values()*. The **NPV** function is similar to the [**PV**](/en/official/Reference/VBA/Financial/PV) function (present value) except that the **PV** function allows cash flows to begin either at the end or the beginning of a period. Unlike the variable **NPV** cash flow values, **PV** cash flows must be fixed throughout the investment. ### Example This example uses the **NPV** function to return the net present value for a series of cash flows contained in the array `Values()`. `RetRate` represents the fixed internal rate of return. ```vb Dim Fmt, Guess, RetRate, NetPVal, Msg Static Values(5) As Double ' Set up array. Fmt = "###,##0.00" ' Define money format. Guess = .1 ' Guess starts at 10 percent. RetRate = .0625 ' Set fixed internal rate. Values(0) = -70000 ' Business start-up costs. ' Positive cash flows reflecting income for four successive years. Values(1) = 22000 : Values(2) = 25000 Values(3) = 28000 : Values(4) = 31000 NetPVal = NPV(RetRate, Values()) ' Calculate net present value. Msg = "The net present value of these cash flows is " Msg = Msg & Format(NetPVal, Fmt) & "." MsgBox Msg ' Display net present value. ``` ### See Also * [IRR](/en/official/Reference/VBA/Financial/IRR), [MIRR](/en/official/Reference/VBA/Financial/MIRR), [PV](/en/official/Reference/VBA/Financial/PV) functions --- --- url: /zh/official/Reference/VBA/Financial/NPV.md --- # NPV 返回一个**Double**值,指定基于一系列定期现金流(付款和收入)和贴现率的投资净现值。 语法:**NPV(** *rate*, *values()* **)** *rate* : *必需* **Double**,指定整个期间内的贴现率,以小数表示。 *values()* : *必需* **Double**数组,指定现金流值。该数组必须至少包含一个负值(付款)和一个正值(收入)。 投资的净现值是未来一系列付款和收入的当前价值。 **NPV**函数使用数组中值的顺序来解释付款和收入的顺序。付款和收入值必须按正确的顺序排列。 **NPV**投资从第一个现金流值日期的前一期开始,到数组中最后一个现金流值结束。 净现值计算基于未来现金流。如果第一个现金流发生在第一期的期初,则第一个值必须加到**NPV**返回的值中,并且不能包含在\*values()\*的现金流值中。 **NPV**函数类似于[**PV**](/official/Reference/VBA/Financial/PV)函数(现值),但**PV**函数允许现金流从期末或期初开始。与可变的**NPV**现金流值不同,**PV**现金流在整个投资期间必须是固定的。 ### 示例 本示例使用**NPV**函数返回包含在数组`Values()`中的一系列现金流的净现值。`RetRate`表示固定的内部收益率。 ```vb Dim Fmt, Guess, RetRate, NetPVal, Msg Static Values(5) As Double ' Set up array. Fmt = "###,##0.00" ' Define money format. Guess = .1 ' Guess starts at 10 percent. RetRate = .0625 ' Set fixed internal rate. Values(0) = -70000 ' Business start-up costs. ' Positive cash flows reflecting income for four successive years. Values(1) = 22000 : Values(2) = 25000 Values(3) = 28000 : Values(4) = 31000 NetPVal = NPV(RetRate, Values()) ' Calculate net present value. Msg = "The net present value of these cash flows is " Msg = Msg & Format(NetPVal, Fmt) & "." MsgBox Msg ' Display net present value. ``` ### 另请参阅 * [IRR](/official/Reference/VBA/Financial/IRR)、[MIRR](/official/Reference/VBA/Financial/MIRR)、[PV](/official/Reference/VBA/Financial/PV)函数 --- --- url: /en/official/Reference/VBA/ErrObject/Number.md --- # Number Returns or sets a **Long** value specifying an error. **Number** is the default member of the **Err** object, so a bare reference to **Err** is equivalent to **Err.Number**. Read/write. Syntax: * **Err**.**Number** * **Err**.**Number** **=** *errorNumber* *errorNumber* : A **Long** error code to assign to the **Err** object. When read, **Number** returns the current error code, or **0** if no error is active. When returning a user-defined error from an object, set **Err.Number** by adding the chosen error code to the [**vbObjectError**](/en/official/Reference/VBA/Constants/#vbObjectError) constant. For example, the following code returns 1051 as an error code: ```vb Err.Raise Number:=vbObjectError + 1051, Source:="SomeClass" ``` ### Example The first example illustrates a typical use of the **Number** property in an error-handling routine. ```vb Sub Demo() On Error GoTo Handler Dim x As Double, y As Double x = 1 / y ' Create division-by-zero error. Exit Sub Handler: MsgBox Err.Number MsgBox Err.Description ' Check for division-by-zero error. If Err.Number = 11 Then y = y + 1 End If Resume End Sub ``` The second example examines the **Number** property of the **Err** object to determine whether an error returned by an Automation object was defined by the object, or whether it was mapped to a built-in error. The constant **vbObjectError** is a very large negative number that an object adds to its own error code to indicate that the error is server-defined; subtracting it from **Err.Number** strips it back out. If the error is object-defined, the base number is left in `myError`, which is displayed in a message box along with the original source of the error. If **Err.Number** represents a built-in error, the built-in error number is displayed instead. ```vb Dim myError As Long, msg As String ' Strip off the constant added by the object to indicate one of its own errors. myError = Err.Number - vbObjectError ' If you subtract vbObjectError and the number is still in the range 0-65535, ' it is an object-defined error code. If myError > 0 And myError < 65535 Then msg = "The object you accessed assigned this number to the error: " _ & myError & ". The originator of the error was: " _ & Err.Source & ". Press F1 to see the originator's Help topic." Else msg = "This error (# " & Err.Number & ") is a built-in error number." _ & " Press the Help button or F1 for the Help topic for this error." End If MsgBox msg, , "Object Error", Err.HelpFile, Err.HelpContext ``` ### See Also * [Description](/en/official/Reference/VBA/ErrObject/Description) property * [Source](/en/official/Reference/VBA/ErrObject/Source) property * [Raise](/en/official/Reference/VBA/ErrObject/Raise) method * [Clear](/en/official/Reference/VBA/ErrObject/Clear) method --- --- url: /zh/official/Reference/VBA/ErrObject/Number.md --- # Number 返回或设置一个 **Long** 值,指定一个错误。**Number** 是 **Err** 对象的默认成员,因此单独引用 **Err** 等效于 **Err.Number**。可读/写。 语法: * **Err**.**Number** * **Err**.**Number** **=** *errorNumber* *errorNumber* : 要赋给 **Err** 对象的 **Long** 错误代码。读取时,**Number** 返回当前错误代码,如果没有活动错误则返回 **0**。 从对象返回用户定义的错误时,通过将选定的错误代码与 [**vbObjectError**](/official/Reference/VBA/Constants/#vbObjectError) 常量相加来设置 **Err.Number**。例如,以下代码返回 1051 作为错误代码: ```vb Err.Raise Number:=vbObjectError + 1051, Source:="SomeClass" ``` ### 示例 第一个示例说明 **Number** 属性在错误处理例程中的典型用法。 ```vb Sub Demo() On Error GoTo Handler Dim x As Double, y As Double x = 1 / y ' Create division-by-zero error. Exit Sub Handler: MsgBox Err.Number MsgBox Err.Description ' Check for division-by-zero error. If Err.Number = 11 Then y = y + 1 End If Resume End Sub ``` 第二个示例检查 **Err** 对象的 **Number** 属性,以确定自动化对象返回的错误是由该对象定义的,还是映射到了内置错误。 常量 **vbObjectError** 是一个非常大的负数,对象将其加到自己的错误代码上以指示该错误是服务器定义的;从 **Err.Number** 中减去它即可剥离该偏移。如果错误是对象定义的,基础数字会留在 `myError` 中,并连同错误的原始来源一起显示在消息框中。如果 **Err.Number** 表示内置错误,则显示内置错误号。 ```vb Dim myError As Long, msg As String ' Strip off the constant added by the object to indicate one of its own errors. myError = Err.Number - vbObjectError ' If you subtract vbObjectError and the number is still in the range 0-65535, ' it is an object-defined error code. If myError > 0 And myError < 65535 Then msg = "The object you accessed assigned this number to the error: " _ & myError & ". The originator of the error was: " _ & Err.Source & ". Press F1 to see the originator's Help topic." Else msg = "This error (# " & Err.Number & ") is a built-in error number." _ & " Press the Help button or F1 for the Help topic for this error." End If MsgBox msg, , "Object Error", Err.HelpFile, Err.HelpContext ``` ### 另请参阅 * [Description](/official/Reference/VBA/ErrObject/Description) 属性 * [Source](/official/Reference/VBA/ErrObject/Source) 属性 * [Raise](/official/Reference/VBA/ErrObject/Raise) 方法 * [Clear](/official/Reference/VBA/ErrObject/Clear) 方法 --- --- url: /en/official/Reference/VBA/Conversion/Nz.md --- # Nz Replaces a **Null** value with the specified replacement value. Syntax: **Nz(** *value* \[ **,** *valueIfNull* ] **)** *value* : *required* A **Variant** to check for **Null**. *valueIfNull* : *optional* A **Variant** to return if *value* is **Null**. If omitted, **Nz** returns **Empty**. The return type is **Variant**. **Nz** is useful for handling expressions that may evaluate to **Null** --- most commonly, fields read from a database recordset where a column permits **Null**. Unlike a direct comparison with **Null** (which itself yields **Null**), **Nz** returns a usable substitute value. If *value* is anything other than **Null**, **Nz** returns *value* unchanged. ::: info The function originated in Microsoft Access. twinBASIC provides it as a built-in so the same idiom can be used outside of an Access host. ::: ### Example This example uses **Nz** to substitute the string `"Unknown"` for a recordset field that may be **Null**. ```vb Dim customerName As Variant customerName = recordset.Fields("Name").Value MsgBox "Customer Name: " & Nz(customerName, "Unknown") ``` ### See Also * [IsNull](/en/official/Reference/VBA/Information/IsNull) function * [IIf](/en/official/Reference/VBA/Interaction/IIf) function --- --- url: /zh/official/Reference/VBA/Conversion/Nz.md --- # Nz 用指定的替换值替代 **Null** 值。 语法:**Nz(** *value* \[ **,** *valueIfNull* ] **)** *value* : *必需* 要检查是否为 **Null** 的 **Variant**。 *valueIfNull* : *可选* 如果 *value* 为 **Null** 则返回的 **Variant**。如果省略,**Nz** 返回 **Empty**。 返回类型为 **Variant**。 **Nz** 在处理可能计算为 **Null** 的表达式时非常有用——最常见的是从允许 **Null** 列的数据库记录集中读取字段。与直接与 **Null** 比较(其本身产生 **Null**)不同,**Nz** 返回一个可用的替代值。 如果 *value* 不是 **Null**,**Nz** 原样返回 *value*。 ::: info 该函数起源于 Microsoft Access。twinBASIC 将其作为内置函数提供,以便在 Access 宿主之外也能使用相同的惯用法。 ::: ### 示例 此示例使用 **Nz** 将字符串 `"Unknown"` 替代可能为 **Null** 的记录集字段。 ```vb Dim customerName As Variant customerName = recordset.Fields("Name").Value MsgBox "Customer Name: " & Nz(customerName, "Unknown") ``` ### 另请参阅 * [IsNull](/official/Reference/VBA/Information/IsNull) 函数 * [IIf](/official/Reference/VBA/Interaction/IIf) 函数 --- --- url: /en/official/Reference/VBA/Information/ObjPtr.md --- # ObjPtr Returns the COM-identity address of an object as a **LongPtr**. Syntax: **ObjPtr(** *Object* **)** *Object* : *required* The object reference whose pointer is to be obtained. The argument is taken as **IUnknown**. The returned value is the address of the object's **IUnknown** vtable --- the same value the COM runtime uses to test object identity. Two **Object** variables refer to the same instance if and only if their **ObjPtr** values are equal. The pointer is valid only as long as the underlying object stays alive; nothing about taking **ObjPtr** holds a reference. Pass the result to API functions that need a raw object address, or store it for an identity check, but do not assume it remains meaningful after the last reference is released. ### Example ```vb Dim a As Collection Dim b As Collection Set a = New Collection Set b = a Debug.Print ObjPtr(a) = ObjPtr(b) ' True — same instance. Set b = New Collection Debug.Print ObjPtr(a) = ObjPtr(b) ' False — different instances. ``` ### See Also * [StrPtr](/en/official/Reference/VBA/Information/StrPtr) function * [VarPtr](/en/official/Reference/VBA/Information/VarPtr) function --- --- url: /zh/official/Reference/VBA/Information/ObjPtr.md --- # ObjPtr 返回对象的COM标识地址,作为**LongPtr**。 语法:**ObjPtr(** *Object* **)** *Object* : *必需* 要获取指针的对象引用。参数作为**IUnknown**传入。 返回值是对象**IUnknown**虚表的地址——COM运行时用于测试对象标识的相同值。两个**Object**变量引用同一实例当且仅当它们的**ObjPtr**值相等。 该指针仅在底层对象保持活动期间有效;获取**ObjPtr**不会持有引用。将结果传给需要原始对象地址的API函数,或存储用于标识检查,但不要假设在最后一个引用释放后它仍有意义。 ### 示例 ```vb Dim a As Collection Dim b As Collection Set a = New Collection Set b = a Debug.Print ObjPtr(a) = ObjPtr(b) ' True — same instance. Set b = New Collection Debug.Print ObjPtr(a) = ObjPtr(b) ' False — different instances. ``` ### 另请参阅 * [StrPtr](/official/Reference/VBA/Information/StrPtr)函数 * [VarPtr](/official/Reference/VBA/Information/VarPtr)函数 --- --- url: /en/official/Reference/VBA/Conversion/Oct.md --- # Oct, Oct$ Returns a string representing the octal value of a number. Syntax: * **Oct$(** *number* **)** * **Oct(** *number* **)** *number* : *required* Any valid numeric or string expression. If *number* is not a whole number, it is rounded to the nearest whole number before being evaluated. The `$`-suffixed form returns a **String**; the unsuffixed form returns a **Variant** (**String**). | If *number* is | Oct returns | |----------------|---------------------------------| | **Null** | **Null** (unsuffixed form only) | | **Empty** | Zero (`"0"`) | | Any other number | Up to 11 octal characters | Octal numbers can be represented directly by preceding numbers in the proper range with `&O`. For example, `&O10` is the octal notation for decimal 8. ### Example This example uses the **Oct** function to return the octal value of a number. ```vb Dim MyOct MyOct = Oct(4) ' Returns "4". MyOct = Oct(8) ' Returns "10". MyOct = Oct(459) ' Returns "713". ``` ### See Also * [Hex](/en/official/Reference/VBA/Conversion/Hex), [Str](/en/official/Reference/VBA/Conversion/Str) functions --- --- url: /zh/official/Reference/VBA/Conversion/Oct.md --- # Oct, Oct$ 返回表示数字八进制值的字符串。 语法: * **Oct$(** *number* **)** * **Oct(** *number* **)** *number* : *必需* 任何有效的数值或字符串表达式。如果 *number* 不是整数,则在求值前四舍五入到最接近的整数。 `$` 后缀形式返回 **String**;无后缀形式返回 **Variant** (**String**)。 | 如果 *number* 为 | Oct 返回 | |------------------|----------| | **Null** | **Null**(仅限无后缀形式) | | **Empty** | 零(`"0"`) | | 任何其他数字 | 最多 11 个八进制字符 | 八进制数可以通过在适当范围内的数字前加 `&O` 来直接表示。例如,`&O10` 是十进制 8 的八进制表示法。 ### 示例 此示例使用 **Oct** 函数返回数字的八进制值。 ```vb Dim MyOct MyOct = Oct(4) ' Returns "4". MyOct = Oct(8) ' Returns "10". MyOct = Oct(459) ' Returns "713". ``` ### 另请参阅 * [Hex](/official/Reference/VBA/Conversion/Hex)、[Str](/official/Reference/VBA/Conversion/Str) 函数 --- --- url: /en/official/Reference/VBRUN/Constants/OldLinkModeConstants.md --- # OldLinkModeConstants Legacy DDE link-mode values retained for compatibility with very early versions of Visual Basic. New code should use [**LinkModeConstants**](/en/official/Reference/VBRUN/Constants/LinkModeConstants). | Constant | Value | Description | |----------|-------|-------------| | **vbHot** | 1 | The control updates whenever the source data changes ("hot" link). | | **vbServer** | 1 | The form acts as a DDE source. | | **vbCold** | 2 | The control updates only when explicitly requested ("cold" link). | --- --- url: /zh/official/Reference/VBRUN/Constants/OldLinkModeConstants.md --- # OldLinkModeConstants 为与早期Visual Basic版本兼容而保留的旧式DDE链接模式值。新代码应使用[**LinkModeConstants**](/official/Reference/VBRUN/Constants/LinkModeConstants)。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbHot** | 1 | 源数据更改时控件自动更新("热"链接)。 | | **vbServer** | 1 | 窗体作为DDE源。 | | **vbCold** | 2 | 仅在显式请求时控件更新("冷"链接)。 | --- --- url: /en/official/Reference/VB/OLE.md --- # OLE class An **OLE** *container* control hosts a linked or embedded OLE Automation object --- typically a Word document, an Excel spreadsheet, or any other registered OLE server --- directly on a form, and lets the user activate and edit the contained object in place via its registered verbs. ::: info The OLE container control is a **VB6 compatibility stub** in twinBASIC. Almost every OLE-specific property, method, and event is currently unimplemented (each is flagged below). The inherited base-control members --- positioning, sizing, anchoring, focus, drag, mouse cursor --- do work normally, so a project ported from VB6 still parses and lays out the control on its form, but cannot create, embed, link, paste, save, or activate an actual OLE object through it. ::: There is no default property. The default-designer event is [**Click**](#click). ```vb ' The OLE-specific calls below are not currently functional ' in twinBASIC; the example is given for reference only. Private Sub Form_Load() OLE1.CreateEmbed vbNullString, "Excel.Sheet" ' [Unimplemented] End Sub Private Sub OLE1_Click() OLE1.DoVerb vbOLEPrimary ' [Unimplemented] End Sub ``` ## Linked vs embedded objects An OLE container holds either a *linked* object --- a reference to a document on disk that opens in its registered server when activated --- or an *embedded* object whose data is stored inside the host form's data stream. [**CreateLink**](#createlink) creates a linked object from an existing file; [**CreateEmbed**](#createembed) creates a fresh embedded object of a given class. [**OLEType**](#oletype) reports which form the current contents take, and [**OLETypeAllowed**](#oletypeallowed) restricts which forms the container will accept at design or run time. [**SourceDoc**](#sourcedoc) and [**SourceItem**](#sourceitem) identify the linked file (and, for partial links, the item within it). [**Class**](#class) holds the ProgID of the embedded server (e.g. `"Word.Document"`, `"Excel.Sheet"`). ## Verbs Each OLE server registers a set of *verbs* --- labelled actions like *Open*, *Edit*, or *Play*. [**FetchVerbs**](#fetchverbs) populates the per-instance verb list, exposed as the indexed [**ObjectVerbs**](#objectverbs), [**ObjectVerbFlags**](#objectverbflags), and [**ObjectVerbsCount**](#objectverbscount) properties. [**DoVerb**](#doverb) executes a verb by index --- passing **vbOLEPrimary** runs the server's primary verb, which is the action invoked by a double-click. [**AutoVerbMenu**](#autoverbmenu) controls whether right-clicking the control automatically pops up the verb menu. ## Activation and display [**AutoActivate**](#autoactivate) chooses when the embedded object is activated for in-place editing --- manually, on focus, or on a double-click. [**DisplayType**](#displaytype) selects between rendering the object's content directly and rendering a registered icon. [**SizeMode**](#sizemode) chooses how the object's bitmap is fitted into the container (clipped, stretched, auto-sized, or zoomed). ## Updates and storage A linked object's last-cached presentation can be re-fetched from its server with [**Update**](#update); [**UpdateOptions**](#updateoptions) decides whether updates happen automatically or only on demand. The container can be persisted out of an open file with [**SaveToFile**](#savetofile) (or [**SaveToOle1File**](#savetoole1file) for the legacy OLE1 stream format) and re-loaded with [**ReadFromFile**](#readfromfile), in each case using a Basic file number opened with **Open**. [**InsertObjDlg**](#insertobjdlg) and [**PasteSpecialDlg**](#pastespecialdlg) raise the standard Windows OLE dialogs for picking an object class or a clipboard format. ## Data binding Setting [**DataSource**](#datasource) and [**DataField**](#datafield) connects the container's contents to a binary field on a [**Data**](/en/official/Reference/VB/Data/) control's recordset, so the embedded object is loaded from and saved back into the row. [**DataChanged**](#datachanged) reports whether the contained object differs from the bound row's stored value. ## Properties ### Action ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A run-time-only **Integer** that, when assigned, performs one of the predefined OLE actions such as *create*, *delete*, *paste*, or *update*. Modern code uses the equivalent named methods ([**CreateEmbed**](#createembed), [**Delete**](#delete), [**Paste**](#paste), [**Update**](#update), …) instead. ### Anchors The set of edges of the parent that the OLE control's corresponding edges follow when the parent resizes. Read-only --- assign individual `.Left`, `.Top`, `.Right`, `.Bottom` flags through the returned **Anchors** object. ### Appearance ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Determines how the container's border is drawn. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). ### AppIsRunning ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A run-time-only **Boolean**: **True** while the OLE server hosting the embedded object is running. Assigning **True** starts the server; assigning **False** shuts it down. ### AutoActivate ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Selects when the embedded object is activated for in-place editing. A member of [**OLEContainerActivateConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerActivateConstants): **vbOLE\_ActivateManual**, **vbOLE\_ActivateGetFocus**, **vbOLE\_ActivateDoubleclick** (default), or **vbOLE\_ActivateAuto**. ### AutoVerbMenu ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: When **True** (default), right-clicking the container automatically pops up a menu of the contained object's registered verbs. **Boolean**. ### BackColor ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: The background colour, as an **OLE\_COLOR**. Defaults to the system window-background colour. ### BackStyle ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Selects between an opaque and transparent background ([**BackFillStyleConstants**](/en/official/Reference/VBRUN/Constants/BackFillStyleConstants)): **vbBFTransparent** or **vbBFOpaque** (default). ### BorderStyle ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Whether the container is drawn with a border. A member of [**ControlBorderStyleConstants**](/en/official/Reference/VBRUN/Constants/ControlBorderStyleConstants): **vbNoBorder** or **vbFixedSingleBorder** (default). ### CausesValidation Determines whether the previously focused control's [**Validate**](#validate) event runs before this control receives the focus. **Boolean**, default **True**. ### Class ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: The ProgID of the OLE server class for the contained object --- for example `"Word.Document"` or `"Excel.Sheet"`. **String**. Used together with [**SourceDoc**](#sourcedoc) and [**SourceItem**](#sourceitem) when populating the container at design time, or as the default class for [**InsertObjDlg**](#insertobjdlg). ### Container The control that hosts this OLE control --- typically the form. Read with **Get**, change with **Set**. Setting **Container** re-parents the control to a different container at run time. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as an OLE container. Always **vbOLEControl**. ### Data ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A run-time-only **Long** handle to the data block returned for the format named in [**Format**](#format). Used together with the [**ObjectAcceptFormats**](#objectacceptformats) / [**ObjectGetFormats**](#objectgetformats) machinery to round-trip raw OLE data. ### DataChanged ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A run-time-only **Boolean**: **True** if the bound recordset field has changed since the container last loaded it. Cleared after a successful save. ### DataField ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: The name of the binary field, in the recordset of the bound [**DataSource**](#datasource), whose contents are stored and retrieved by the OLE container. **String**. ### DataSource ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A reference to a [**Data**](/en/official/Reference/VB/Data/) control (or other **DataSource** provider) whose recordset supplies the value for [**DataField**](#datafield). Set with **Set**. ### DataText ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A run-time-only **String** alias for transferring text-format data into and out of the contained object's clipboard equivalent. ### DisplayType ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Whether the container shows the object's content or its registered icon. A member of [**OLEContainerDisplayTypeConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants): **vbOLE\_DisplayContent** (default) or **vbOLE\_DisplayIcon**. ### Dock Where the OLE control is docked within its container. A member of [**DockModeConstants**](/en/official/Reference/VBRUN/Constants/DockModeConstants): **vbDockNone** (default), **vbDockLeft**, **vbDockTop**, **vbDockRight**, **vbDockBottom**, or **vbDockFill**. Docked controls ignore [**Anchors**](#anchors). ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the control accepts user input. **Boolean**, default **True**. ### FileNumber ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A run-time-only **Integer** giving the Basic file number passed to the most recent [**ReadFromFile**](#readfromfile), [**SaveToFile**](#savetofile), or [**SaveToOle1File**](#savetoole1file) call. ### Format ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: The clipboard format identifier currently associated with the [**Data**](#data) handle. **String**. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). **Single**. ### HelpContextID ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. Available only when the host build defines `FEATURE_HELP`. ::: A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the control has focus. ### HostName ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: The friendly name the OLE server should display for the host application --- e.g. shown in Word's title bar while editing the embedded document in place. **String**. ### hWnd The Win32 window handle for the underlying control, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Reading **Index** on a non-array instance raises run-time error 343 (*Object not an array*). Read-only at run time. ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Single**. ### LpOleObject ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A run-time-only **LongPtr** giving the raw `IOleObject` interface pointer of the contained object, for passing to native code. ### MiscFlags ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A bit-mask of miscellaneous container behaviours (see [**OLEContainerConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerConstants) --- **vbOLEMiscFlagMemStorage**, **vbOLEMiscFlagDisableInPlace**). **Long**. ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### object ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A run-time-only **Object** reference to the OLE Automation interface of the contained object --- the late-bound entry point for scripting it. **Read-only**. ### ObjectAcceptFormats ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: An indexed **String** property listing the clipboard formats that the contained object can accept on a paste. Use [**ObjectAcceptFormatsCount**](#objectacceptformatscount) to bound the index. ### ObjectAcceptFormatsCount ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: The number of entries in [**ObjectAcceptFormats**](#objectacceptformats). **Integer**. ### ObjectGetFormats ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: An indexed **String** property listing the clipboard formats that the contained object can produce on a copy. Use [**ObjectGetFormatsCount**](#objectgetformatscount) to bound the index. ### ObjectGetFormatsCount ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: The number of entries in [**ObjectGetFormats**](#objectgetformats). **Integer**. ### ObjectVerbFlags ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: An indexed **Long** property giving the menu-flag bit-mask for each entry in [**ObjectVerbs**](#objectverbs). The flag values match the Win32 `MF_*` menu constants and indicate whether the verb item is greyed, checked, etc. ### ObjectVerbs ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: An indexed **String** property listing the names of the verbs registered for the contained object --- populated by [**FetchVerbs**](#fetchverbs). Pass an index to [**DoVerb**](#doverb) to invoke a verb. ### ObjectVerbsCount ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: The number of entries in [**ObjectVerbs**](#objectverbs). **Long**. ### OLEDropAllowed ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: When **True**, the container accepts OLE objects dragged onto it from outside the application. **Boolean**, default **False**. ### OLEType ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A run-time-only **Integer** reporting whether the contained object is currently linked, embedded, or empty (see [**OLEContainerConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerConstants) --- **vbOLELinked**, **vbOLEEmbedded**, **vbOLEEither**, **vbOLENone**). ### OLETypeAllowed ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Restricts which kinds of contained object the container will accept. A member of [**OLEContainerTypesAllowedConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants): **vbOLE\_Linked**, **vbOLE\_Embedded**, or **vbOLE\_Either** (default). ### Parent A reference to the [**Form**](/en/official/Reference/VB/Form/) (or **UserControl**) that contains this control. Read-only. ### PasteOK ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A run-time-only, read-only **Boolean**: **True** if the current clipboard contents are in a format the contained object would accept via [**Paste**](#paste). ### Picture ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A run-time-only, read-only **IPictureDisp** giving the contained object's current presentation as a picture, suitable for printing or copying onto a [**PictureBox**](/en/official/Reference/VB/PictureBox/). ### SizeMode ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: How the contained object's bitmap is fitted into the container. A member of [**OLEContainerSizeModeConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants): **vbOLE\_SizeClip** (default), **vbOLE\_SizeStretch**, **vbOLE\_SizeAutoSize**, or **vbOLE\_SizeZoom**. ### SourceDoc ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: The full path of the source file used by [**CreateLink**](#createlink) (and the default value for [**InsertObjDlg**](#insertobjdlg)). **String**. ### SourceItem ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: The named item within [**SourceDoc**](#sourcedoc) that the link refers to --- for example, an Excel range name. **String**. ### TabIndex The position of the control in the form's TAB-key navigation order. **Long**. ### TabStop Whether the user can reach the control by pressing the **TAB** key. **Boolean**, default **True**. A disabled control is skipped regardless of this setting. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### Top The vertical distance from the top of the container to the top of the control. **Single**. ### UpdateOptions ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: How a linked object's cached presentation is refreshed. A member of [**OLEContainerUpdateOptionsConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants): **vbOLE\_UpdateAutomatic** (default), **vbOLE\_UpdateFrozen**, or **vbOLE\_UpdateManual**. ### Verb ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: A **Long** verb index used by the legacy [**Action**](#action) property when performing the *do verb* action. New code should call [**DoVerb**](#doverb) directly. ### Visible Whether the control is shown. **Boolean**, default **True**. ### WhatsThisHelpID ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. Available only when the host build defines `FEATURE_HELP`. ::: A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### Width The control's width. **Single**. ## Methods ### Close ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Closes the contained object, ending the running server session if one is open. The container's data is preserved; only the live editing connection is dropped. Syntax: *object*.**Close** ### Copy ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Copies the contained object to the system clipboard. Syntax: *object*.**Copy** ### CreateEmbed ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Creates a new embedded object of the given class, optionally pre-filled from a template file. Syntax: *object*.**CreateEmbed** *SourceDoc* \[, *Class* ] *SourceDoc* : *required* A **String**. Path of a file to use as a template for the new object, or `vbNullString` to create a blank object. *Class* : *optional* A **Variant** **String** ProgID identifying the OLE server class to instantiate (e.g. `"Word.Document"`). Required when *SourceDoc* is empty. ### CreateLink ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Creates a linked object that references an existing file on disk. Syntax: *object*.**CreateLink** *SourceDoc* \[, *SourceItem* ] *SourceDoc* : *required* A **String** giving the full path of the source file. *SourceItem* : *optional* A **Variant** **String** identifying a named item within the source file (e.g. an Excel range name) to link to a fragment rather than the whole document. ### Delete ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Removes the contained object from the container. Releases all resources associated with it. Syntax: *object*.**Delete** ### DoVerb ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Invokes a registered verb on the contained object. The standard verb constants are defined in [**OLEContainerConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerConstants) --- **vbOLEPrimary** (0), **vbOLEShow** (-1), **vbOLEOpen** (-2), **vbOLEHide** (-3), **vbOLEUIActivate** (-4), **vbOLEInPlaceActivate** (-5), **vbOLEDiscardUndoState** (-6); positive indices refer to the per-server entries in [**ObjectVerbs**](#objectverbs). Syntax: *object*.**DoVerb** \[ *Verb* ] *Verb* : *optional* A **Variant** **Long**. Defaults to **vbOLEPrimary** if omitted. ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Typically called from a [**MouseDown**](#mousedown) handler when [**DragMode**](#dragmode) is **vbManual**. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### FetchVerbs ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Re-reads the verb list from the contained object's server and refreshes [**ObjectVerbs**](#objectverbs), [**ObjectVerbFlags**](#objectverbflags), and [**ObjectVerbsCount**](#objectverbscount). Syntax: *object*.**FetchVerbs** ### InsertObjDlg ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Displays the standard Windows *Insert Object* dialog so the user can choose between a new embedded object, an existing file (linked or embedded), or an icon. Syntax: *object*.**InsertObjDlg** ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### Paste ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Pastes the current clipboard contents into the container, if [**PasteOK**](#pasteok) reports the format is acceptable. Syntax: *object*.**Paste** ### PasteSpecialDlg ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Displays the standard Windows *Paste Special* dialog so the user can choose how the current clipboard contents are pasted (link, embed, or as a specific format). Syntax: *object*.**PasteSpecialDlg** ### ReadFromFile ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Reads the container's contents from a Basic-style binary file previously written with [**SaveToFile**](#savetofile). Syntax: *object*.**ReadFromFile** *FileNumber* *FileNumber* : *required* An **Integer**. The file number returned by the **Open** statement, on a stream opened **For Binary**. ### SaveToFile ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Writes the container's contents --- including the linked or embedded object's data and any presentation cache --- to a Basic-style binary file in the current OLE2 stream format. Syntax: *object*.**SaveToFile** *FileNumber* *FileNumber* : *required* An **Integer** opened **For Binary**. ### SaveToOle1File ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Writes the container's contents in the legacy OLE1 stream format. Provided for round-tripping data files produced by very old applications; new code should use [**SaveToFile**](#savetofile). Syntax: *object*.**SaveToOle1File** *FileNumber* *FileNumber* : *required* An **Integer** opened **For Binary**. ### SetFocus Moves the input focus to the control. The control must be both [**Visible**](#visible) and [**Enabled**](#enabled), or run-time error 5 (*Invalid procedure call or argument*) is raised. Syntax: *object*.**SetFocus** ### ShowWhatsThis ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. Available only when the host build defines `FEATURE_HELP`. ::: Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### Update ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: For a linked object, retrieves the latest data from the source file and refreshes the cached presentation. For an embedded object whose server is running, asks the server to commit any pending changes back into the container. Syntax: *object*.**Update** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Click ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the user clicks the container with any mouse button. **Default-designer event.** Syntax: *object*\_**Click**( ) ### DblClick ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the user double-clicks the container. With the default [**AutoActivate**](#autoactivate) setting **vbOLE\_ActivateDoubleclick**, this is the same gesture that activates the contained object for in-place editing. Syntax: *object*\_**DblClick**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the control receives the input focus. Syntax: *object*\_**GotFocus**( ) ### Initialize ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised once, after the control's underlying window has been created. Syntax: *object*\_**Initialize**( ) ### KeyDown ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the user presses any key while the control has focus. Syntax: *object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the user types a character that produces an ANSI keystroke. Syntax: *object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the user releases a key while the control has focus. Syntax: *object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the control loses the input focus. Syntax: *object*\_**LostFocus**( ) ### MouseDown ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the user presses any mouse button over the control. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the cursor moves over the control. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the user releases a mouse button over the control. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### ObjectMove ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the contained object asks the container to relocate or resize itself --- typically in response to in-place editing changes. Syntax: *object*\_**ObjectMove**( *Left* **As Single**, *Top* **As Single**, *Width* **As Single**, *Height* **As Single** ) ### Resize ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised when the contained object reports a new natural size --- for example, after an embedded image is replaced with one of different dimensions. Syntax: *object*\_**Resize**( *HeightNew* **As Single**, *WidthNew* **As Single** ) ### Updated ::: info Reserved for VB6 compatibility; not currently implemented in twinBASIC. ::: Raised after the contained object has been modified, so the host can flag itself as dirty. *Code* is one of the status values in [**OLEContainerConstants**](/en/official/Reference/VBRUN/Constants/OLEContainerConstants): **vbOLEChanged**, **vbOLESaved**, **vbOLEClosed**, or **vbOLERenamed**. Syntax: *object*\_**Updated**( *Code* **As Integer** ) ### Validate Raised when the focus is moving to another control whose [**CausesValidation**](#causesvalidation) is **True**. Setting *Cancel* to **True** keeps the focus on this control. Syntax: *object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /zh/official/Reference/VB/OLE.md --- # OLE 类 **OLE** *容器*控件在窗体上承载链接或嵌入的OLE Automation对象——通常是Word文档、Excel电子表格或任何其他已注册的OLE服务器——并允许用户通过其注册的动词就地激活和编辑包含的对象。 ::: info OLE容器控件在twinBASIC中是**VB6兼容性存根**。几乎所有OLE特有的属性、方法和事件当前均未实现(每个都在下方标注)。继承的基控件成员——定位、大小调整、锚定、焦点、拖动、鼠标光标——可以正常工作,因此从VB6移植的项目仍然可以解析控件并将其布局在窗体上,但无法通过它创建、嵌入、链接、粘贴、保存或激活实际的OLE对象。 ::: 没有默认属性。默认设计器事件为[**Click**](#click)。 ```vb ' 以下OLE特有调用在twinBASIC中当前不可用 ' 此示例仅供参考。 Private Sub Form_Load() OLE1.CreateEmbed vbNullString, "Excel.Sheet" ' [未实现] End Sub Private Sub OLE1_Click() OLE1.DoVerb vbOLEPrimary ' [未实现] End Sub ``` ## 链接与嵌入对象 OLE容器持有*链接*对象——对磁盘上文档的引用,在激活时以注册的服务器打开——或*嵌入*对象,其数据存储在主机窗体的数据流中。[**CreateLink**](#createlink)从现有文件创建链接对象;[**CreateEmbed**](#createembed)创建给定类的新嵌入对象。[**OLEType**](#oletype)报告当前内容采用哪种形式,[**OLETypeAllowed**](#oletypeallowed)限制容器在设计或运行时接受哪种形式。 [**SourceDoc**](#sourcedoc)和[**SourceItem**](#sourceitem)标识链接文件(以及对于部分链接,其中的项目)。[**Class**](#class)保存嵌入服务器的ProgID(例如`"Word.Document"`、`"Excel.Sheet"`)。 ## 动词 每个OLE服务器注册一组*动词*——标记的操作,如*打开*、*编辑*或*播放*。[**FetchVerbs**](#fetchverbs)填充每个实例的动词列表,作为索引属性[**ObjectVerbs**](#objectverbs)、[**ObjectVerbFlags**](#objectverbflags)和[**ObjectVerbsCount**](#objectverbscount)暴露。[**DoVerb**](#doverb)按索引执行动词——传递**vbOLEPrimary**运行服务器的主动词,即双击调用的操作。[**AutoVerbMenu**](#autoverbmenu)控制右击控件是否自动弹出动词菜单。 ## 激活和显示 [**AutoActivate**](#autoactivate)选择嵌入对象何时被激活进行就地编辑——手动、焦点时或双击时。[**DisplayType**](#displaytype)在直接渲染对象内容和渲染注册图标之间选择。[**SizeMode**](#sizemode)选择对象的位图如何适配容器(裁剪、拉伸、自动调整大小或缩放)。 ## 更新和存储 链接对象的最后缓存表示可以通过[**Update**](#update)从其服务器重新获取;[**UpdateOptions**](#updateoptions)决定更新是自动还是按需进行。容器可以通过[**SaveToFile**](#savetofile)(或[**SaveToOle1File**](#savetoole1file)用于旧版OLE1流格式)从打开的文件中持久化,并使用[**ReadFromFile**](#readfromfile)重新加载,每种情况都使用以**Open**打开的Basic文件号。[**InsertObjDlg**](#insertobjdlg)和[**PasteSpecialDlg**](#pastespecialdlg)引发用于选择对象类或剪贴板格式的标准Windows OLE对话框。 ## 数据绑定 设置[**DataSource**](#datasource)和[**DataField**](#datafield)将容器的内容连接到[**Data**](/official/Reference/VB/Data/)控件记录集的二进制字段,使嵌入对象从行中加载并保存回行。[**DataChanged**](#datachanged)报告包含的对象是否与绑定行的存储值不同。 ## 属性 ### Action ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 运行时专用的**Integer**,赋值时执行预定义的OLE操作之一,如*创建*、*删除*、*粘贴*或*更新*。现代代码使用等效的命名方法([**CreateEmbed**](#createembed)、[**Delete**](#delete)、[**Paste**](#paste)、[**Update**](#update)等)代替。 ### Anchors 父级的边缘集合,OLE控件的对应边缘在父级调整大小时跟随。只读——通过返回的**Anchors**对象分配单独的`.Left`、`.Top`、`.Right`、`.Bottom`标志。 ### Appearance ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 决定容器的边框如何绘制。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。 ### AppIsRunning ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 运行时专用的**Boolean**:当承载嵌入对象的OLE服务器正在运行时为**True**。赋值**True**启动服务器;赋值**False**关闭它。 ### AutoActivate ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 选择嵌入对象何时被激活进行就地编辑。[**OLEContainerActivateConstants**](/official/Reference/VBRUN/Constants/OLEContainerActivateConstants)的成员:**vbOLE\_ActivateManual**、**vbOLE\_ActivateGetFocus**、**vbOLE\_ActivateDoubleclick**(默认)或**vbOLE\_ActivateAuto**。 ### AutoVerbMenu ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当**True**(默认)时,右击容器自动弹出包含对象注册动词的菜单。**Boolean**。 ### BackColor ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 背景颜色,作为**OLE\_COLOR**。默认为系统窗口背景颜色。 ### BackStyle ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 在 opaque 和透明背景之间选择([**BackFillStyleConstants**](/official/Reference/VBRUN/Constants/BackFillStyleConstants)):**vbBFTransparent**或**vbBFOpaque**(默认)。 ### BorderStyle ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 容器是否绘有边框。[**ControlBorderStyleConstants**](/official/Reference/VBRUN/Constants/ControlBorderStyleConstants)的成员:**vbNoBorder**或**vbFixedSingleBorder**(默认)。 ### CausesValidation 决定之前焦点控件的[**Validate**](#validate)事件是否在此控件获得焦点之前运行。**Boolean**,默认**True**。 ### Class ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 包含对象的OLE服务器类的ProgID——例如`"Word.Document"`或`"Excel.Sheet"`。**String**。在设计时填充容器时与[**SourceDoc**](#sourcedoc)和[**SourceItem**](#sourceitem)一起使用,或作为[**InsertObjDlg**](#insertobjdlg)的默认类。 ### Container 承载此OLE控件的控件——通常是窗体。使用**Get**读取,使用**Set**更改。设置**Container**在运行时将控件重新父级化到不同的容器。 ### ControlType 标识此控件为OLE容器的只读[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值。始终为**vbOLEControl**。 ### Data ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 运行时专用的**Long**句柄,指向[**Format**](#format)中命名的格式返回的数据块。与[**ObjectAcceptFormats**](#objectacceptformats) / [**ObjectGetFormats**](#objectgetformats)机制一起使用,以往返原始OLE数据。 ### DataChanged ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 运行时专用的**Boolean**:如果绑定的记录集字段自容器上次加载以来已更改则为**True**。成功保存后被清除。 ### DataField ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 在绑定的[**DataSource**](#datasource)的记录集中,由OLE容器存储和检索其内容的二进制字段的名称。**String**。 ### DataSource ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 引用[**Data**](/official/Reference/VB/Data/)控件(或其他**DataSource**提供者),其记录集为[**DataField**](#datafield)提供值。使用**Set**设置。 ### DataText ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 运行时专用的**String**别名,用于将文本格式数据传入和传出包含对象的剪贴板等效物。 ### DisplayType ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 容器显示对象内容还是其注册图标。[**OLEContainerDisplayTypeConstants**](/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants)的成员:**vbOLE\_DisplayContent**(默认)或**vbOLE\_DisplayIcon**。 ### Dock OLE控件在其容器中停靠的位置。[**DockModeConstants**](/official/Reference/VBRUN/Constants/DockModeConstants)的成员:**vbDockNone**(默认)、**vbDockLeft**、**vbDockTop**、**vbDockRight**、**vbDockBottom**或**vbDockFill**。停靠的控件忽略[**Anchors**](#anchors)。 ### DragIcon 在控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时拖动自身。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual** (0, 默认——从代码调用[**Drag**](#drag))或**vbAutomatic** (1)。 ### Enabled 决定控件是否接受用户输入。**Boolean**,默认**True**。 ### FileNumber ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 运行时专用的**Integer**,给出最近一次[**ReadFromFile**](#readfromfile)、[**SaveToFile**](#savetofile)或[**SaveToOle1File**](#savetoole1file)调用传递的Basic文件号。 ### Format ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当前与[**Data**](#data)句柄关联的剪贴板格式标识符。**String**。 ### Height 控件的高度,默认以缇为单位(或以容器的**ScaleMode**单位)。**Single**。 ### HelpContextID ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。仅当主机构建定义了`FEATURE_HELP`时可用。 ::: 标识应用程序帮助文件中主题的**Long**,当用户在控件具有焦点时按**F1**时检索。 ### HostName ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: OLE服务器应为宿主应用程序显示的友好名称——例如,在就地编辑嵌入文档时显示在Word的标题栏中。**String**。 ### hWnd 底层控件的Win32窗口句柄,作为**LongPtr**。只读。适用于传递给API函数。 ### Index 当控件是控件数组的一部分时,此实例在数组中从零开始的**Long**索引。在非数组实例上读取**Index**会引发运行时错误343(*Object not an array*)。运行时只读。 ### Left 从容器的左边缘到控件左边缘的水平距离。**Single**。 ### LpOleObject ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 运行时专用的**LongPtr**,给出包含对象的原始`IOleObject`接口指针,用于传递给原生代码。 ### MiscFlags ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 杂项容器行为的位掩码(参见[**OLEContainerConstants**](/official/Reference/VBRUN/Constants/OLEContainerConstants)——**vbOLEMiscFlagMemStorage**、**vbOLEMiscFlagDisableInPlace**)。**Long**。 ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针位于控件上时用作鼠标光标的**StdPicture**。 ### MousePointer 当指针位于控件上时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### object ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 运行时专用的包含对象OLE Automation接口的**Object**引用——用于后期绑定脚本编写的入口点。**只读**。 ### ObjectAcceptFormats ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 索引**String**属性,列出包含对象在粘贴时可以接受的剪贴板格式。使用[**ObjectAcceptFormatsCount**](#objectacceptformatscount)限定索引范围。 ### ObjectAcceptFormatsCount ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: [**ObjectAcceptFormats**](#objectacceptformats)中的条目数。**Integer**。 ### ObjectGetFormats ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 索引**String**属性,列出包含对象在复制时可以生成的剪贴板格式。使用[**ObjectGetFormatsCount**](#objectgetformatscount)限定索引范围。 ### ObjectGetFormatsCount ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: [**ObjectGetFormats**](#objectgetformats)中的条目数。**Integer**。 ### ObjectVerbFlags ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 索引**Long**属性,给出[**ObjectVerbs**](#objectverbs)中每个条目的菜单标志位掩码。标志值与Win32 `MF_*`菜单常量匹配,指示动词项是否灰显、选中等等。 ### ObjectVerbs ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 索引**String**属性,列为包含对象注册的动词名称——由[**FetchVerbs**](#fetchverbs)填充。将索引传递给[**DoVerb**](#doverb)以调用动词。 ### ObjectVerbsCount ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: [**ObjectVerbs**](#objectverbs)中的条目数。**Long**。 ### OLEDropAllowed ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当**True**时,容器接受从应用程序外部拖放到其上的OLE对象。**Boolean**,默认**False**。 ### OLEType ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 运行时专用的**Integer**,报告包含对象当前是链接的、嵌入的还是空的(参见[**OLEContainerConstants**](/official/Reference/VBRUN/Constants/OLEContainerConstants)——**vbOLELinked**、**vbOLEEmbedded**、**vbOLEEither**、**vbOLENone**)。 ### OLETypeAllowed ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 限制容器将接受哪种类型的包含对象。[**OLEContainerTypesAllowedConstants**](/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants)的成员:**vbOLE\_Linked**、**vbOLE\_Embedded**或**vbOLE\_Either**(默认)。 ### Parent 引用包含此控件的[**Form**](/official/Reference/VB/Form/)(或**UserControl**)。只读。 ### PasteOK ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 运行时专用只读**Boolean**:当当前剪贴板内容的格式可被包含对象通过[**Paste**](#paste)接受时为**True**。 ### Picture ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 运行时专用只读**IPictureDisp**,给出包含对象当前的表示作为图片,适合打印或复制到[**PictureBox**](/official/Reference/VB/PictureBox/)上。 ### SizeMode ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 包含对象的位图如何适配容器。[**OLEContainerSizeModeConstants**](/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants)的成员:**vbOLE\_SizeClip**(默认)、**vbOLE\_SizeStretch**、**vbOLE\_SizeAutoSize**或**vbOLE\_SizeZoom**。 ### SourceDoc ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: [**CreateLink**](#createlink)使用的源文件的完整路径(以及[**InsertObjDlg**](#insertobjdlg)的默认值)。**String**。 ### SourceItem ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: [**SourceDoc**](#sourcedoc)中链接引用的命名项目——例如Excel范围名称。**String**。 ### TabIndex 控件在窗体TAB键导航顺序中的位置。**Long**。 ### TabStop 用户是否可以通过按**TAB**键到达控件。**Boolean**,默认**True**。禁用的控件无论此设置如何都会被跳过。 ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### Top 从容器顶部到控件顶部的垂直距离。**Single**。 ### UpdateOptions ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 链接对象的缓存表示如何刷新。[**OLEContainerUpdateOptionsConstants**](/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants)的成员:**vbOLE\_UpdateAutomatic**(默认)、**vbOLE\_UpdateFrozen**或**vbOLE\_UpdateManual**。 ### Verb ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 旧版[**Action**](#action)属性执行*执行动词*操作时使用的**Long**动词索引。新代码应直接调用[**DoVerb**](#doverb)。 ### Visible 控件是否显示。**Boolean**,默认**True**。 ### WhatsThisHelpID ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。仅当主机构建定义了`FEATURE_HELP`时可用。 ::: 标识应用程序帮助文件中"What's This?"帮助弹出主题的**Long**。参见[**ShowWhatsThis**](#showwhatsthis)。 ### Width 控件的宽度。**Single**。 ## 方法 ### Close ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 关闭包含的对象,结束正在运行的服务器会话(如果有)。容器的数据被保留;仅断开实时编辑连接。 语法:*object*.**Close** ### Copy ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 将包含的对象复制到系统剪贴板。 语法:*object*.**Copy** ### CreateEmbed ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 创建给定类的新嵌入对象,可选地从模板文件预填充。 语法:*object*.**CreateEmbed** *SourceDoc* \[, *Class* ] *SourceDoc* : *必需* **String**。用作新对象模板的文件路径,或`vbNullString`创建空白对象。 *Class* : *可选* **Variant** **String** ProgID,标识要实例化的OLE服务器类(例如`"Word.Document"`)。当*SourceDoc*为空时必需。 ### CreateLink ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 创建引用磁盘上现有文件的链接对象。 语法:*object*.**CreateLink** *SourceDoc* \[, *SourceItem* ] *SourceDoc* : *必需* 给出源文件完整路径的**String**。 *SourceItem* : *可选* **Variant** **String**,标识源文件中要链接到片段而非整个文档的命名项目(例如Excel范围名称)。 ### Delete ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 从容器中移除包含的对象。释放与其关联的所有资源。 语法:*object*.**Delete** ### DoVerb ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 对包含的对象调用已注册的动词。标准动词常量在[**OLEContainerConstants**](/official/Reference/VBRUN/Constants/OLEContainerConstants)中定义——**vbOLEPrimary** (0)、**vbOLEShow** (-1)、**vbOLEOpen** (-2)、**vbOLEHide** (-3)、**vbOLEUIActivate** (-4)、**vbOLEInPlaceActivate** (-5)、**vbOLEDiscardUndoState** (-6);正索引引用[**ObjectVerbs**](#objectverbs)中按服务器的条目。 语法:*object*.**DoVerb** \[ *Verb* ] *Verb* : *可选* **Variant** **Long**。省略时默认为**vbOLEPrimary**。 ### Drag 开始、完成或取消手动拖放操作。通常在[**DragMode**](#dragmode)为**vbManual**时从[**MouseDown**](#mousedown)处理程序调用。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel** (0)、**vbBeginDrag** (1, 默认)或**vbEndDrag** (2)。 ### FetchVerbs ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 从包含对象的服务器重新读取动词列表并刷新[**ObjectVerbs**](#objectverbs)、[**ObjectVerbFlags**](#objectverbflags)和[**ObjectVerbsCount**](#objectverbscount)。 语法:*object*.**FetchVerbs** ### InsertObjDlg ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 显示标准Windows*插入对象*对话框,以便用户可以选择新嵌入对象、现有文件(链接或嵌入)或图标。 语法:*object*.**InsertObjDlg** ### Move 通过一次调用重新定位并可选地调整控件大小。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**。 *Top*, *Width*, *Height* : *可选* 相应属性的新值。省略的值保持不变。 ### Paste ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 将当前剪贴板内容粘贴到容器中,前提是[**PasteOK**](#pasteok)报告格式可接受。 语法:*object*.**Paste** ### PasteSpecialDlg ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 显示标准Windows*选择性粘贴*对话框,以便用户可以选择当前剪贴板内容的粘贴方式(链接、嵌入或作为特定格式)。 语法:*object*.**PasteSpecialDlg** ### ReadFromFile ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 从先前用[**SaveToFile**](#savetofile)写入的Basic样式二进制文件中读取容器内容。 语法:*object*.**ReadFromFile** *FileNumber* *FileNumber* : *必需* **Integer**。**Open**语句返回的文件号,在以**For Binary**打开的流上。 ### SaveToFile ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 将容器内容——包括链接或嵌入对象的数据和任何表示缓存——以当前OLE2流格式写入Basic样式二进制文件。 语法:*object*.**SaveToFile** *FileNumber* *FileNumber* : *必需* 以**For Binary**打开的**Integer**。 ### SaveToOle1File ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 以旧版OLE1流格式写入容器内容。为往返非常旧的应用程序生成的数据文件而提供;新代码应使用[**SaveToFile**](#savetofile)。 语法:*object*.**SaveToOle1File** *FileNumber* *FileNumber* : *必需* 以**For Binary**打开的**Integer**。 ### SetFocus 将输入焦点移到控件。控件必须同时[**Visible**](#visible)和[**Enabled**](#enabled),否则会引发运行时错误5(*Invalid procedure call or argument*)。 语法:*object*.**SetFocus** ### Show WhatsThis ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。仅当主机构建定义了`FEATURE_HELP`时可用。 ::: 将以[**WhatsThisHelpID**](#whatsthishelpid)标识的主题显示为"What's This?"弹出窗口。 语法:*object*.**ShowWhatsThis** ### Update ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 对于链接对象,从源文件检索最新数据并刷新缓存的表示。对于服务器正在运行的嵌入对象,请求服务器将任何待处理的更改提交回容器。 语法:*object*.**Update** ### ZOrder 将控件带到其同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront** (0, 默认)或**vbSendToBack** (1)。 ## 事件 ### Click ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当用户用任意鼠标按钮点击容器时引发。**默认设计器事件。** 语法:*object*\_**Click**( ) ### DblClick ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当用户双击容器时引发。使用默认的[**AutoActivate**](#autoactivate)设置**vbOLE\_ActivateDoubleclick**时,这与激活包含对象进行就地编辑的手势相同。 语法:*object*\_**DblClick**( ) ### DragDrop 当手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 当手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当控件获得输入焦点时引发。 语法:*object*\_**GotFocus**( ) ### Initialize ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 在控件的底层窗口创建之后引发一次。 语法:*object*\_**Initialize**( ) ### KeyDown ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当控件具有焦点时用户按下任意键引发。 语法:*object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当用户输入产生ANSI按键的字符时引发。 语法:*object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当控件具有焦点时用户释放键引发。 语法:*object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当控件失去输入焦点时引发。 语法:*object*\_**LostFocus**( ) ### MouseDown ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当用户在控件上按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当光标在控件上移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当用户在控件上释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### ObjectMove ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当包含对象请求容器重新定位或调整自身大小时引发——通常是响应就地编辑更改。 语法:*object*\_**ObjectMove**( *Left* **As Single**, *Top* **As Single**, *Width* **As Single**, *Height* **As Single** ) ### Resize ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 当包含对象报告新的自然大小时引发——例如,嵌入图像被替换为不同尺寸的图像后。 语法:*object*\_**Resize**( *HeightNew* **As Single**, *WidthNew* **As Single** ) ### Updated ::: info 保留用于VB6兼容性;twinBASIC中当前未实现。 ::: 在包含对象被修改后引发,以便主机可以将自身标记为脏。*Code*是[**OLEContainerConstants**](/official/Reference/VBRUN/Constants/OLEContainerConstants)中的状态值之一:**vbOLEChanged**、**vbOLESaved**、**vbOLEClosed**或**vbOLERenamed**。 语法:*object*\_**Updated**( *Code* **As Integer** ) ### Validate 当焦点移向另一个[**CausesValidation**](#causesvalidation)为**True**的控件时引发。将*Cancel*设置为**True**使焦点保持在此控件上。 语法:*object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /en/official/Reference/VBRUN/Constants/OLEContainerActivateConstants.md --- # OLEContainerActivateConstants Activation-trigger values for the **AutoActivate** property of an **OLE** container control. | Constant | Value | Description | |----------|-------|-------------| | **vbOLE\_ActivateManual** | 0 | The embedded object is activated only when the **DoVerb** method is called. | | **vbOLE\_ActivateGetFocus** | 1 | The object activates when the **OLE** container receives focus. | | **vbOLE\_ActivateDoubleclick** | 2 | The object activates when the user double-clicks it. | | **vbOLE\_ActivateAuto** | 3 | The object activates automatically based on its registered defaults. | --- --- url: /zh/official/Reference/VBRUN/Constants/OLEContainerActivateConstants.md --- # OLEContainerActivateConstants **OLE**容器控件**AutoActivate**属性的激活触发值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLE\_ActivateManual** | 0 | 嵌入对象仅在调用**DoVerb**方法时激活。 | | **vbOLE\_ActivateGetFocus** | 1 | **OLE**容器获得焦点时激活对象。 | | **vbOLE\_ActivateDoubleclick** | 2 | 用户双击时激活对象。 | | **vbOLE\_ActivateAuto** | 3 | 根据注册的默认设置自动激活对象。 | --- --- url: /en/official/Reference/VBRUN/Constants/OLEContainerConstants.md --- # OLEContainerConstants A combined enumeration containing every option value used by the **OLE** container control. Each logical group of values has a more specific enumeration of its own --- see the See Also section --- but **OLEContainerConstants** retains all of the original VB6 names so existing code continues to compile. ## OLE type | Constant | Value | Description | |----------|-------|-------------| | **vbOLELinked** | 0 | The object is linked to its source. | | **vbOLEEmbedded** | 1 | The object is embedded inside the container. | | **vbOLEEither** | 2 | Either linked or embedded. | | **vbOLENone** | 3 | No object. | ## Update options | Constant | Value | Description | |----------|-------|-------------| | **vbOLEAutomatic** | 0 | The container updates the linked object whenever the source changes. | | **vbOLEFrozen** | 1 | Updates are paused. | | **vbOLEManual** | 2 | Updates happen only when **Update** is called. | ## Activation triggers | Constant | Value | Description | |----------|-------|-------------| | **vbOLEActivateManual** | 0 | Manual activation via **DoVerb**. | | **vbOLEActivateGetFocus** | 1 | Activate on focus. | | **vbOLEActivateDoubleclick** | 2 | Activate on double-click. | | **vbOLEActivateAuto** | 3 | Activate automatically based on the object's defaults. | ## Sizing | Constant | Value | Description | |----------|-------|-------------| | **vbOLESizeClip** | 0 | The object is clipped at the container's edges. | | **vbOLESizeStretch** | 1 | The object is stretched to fill the container. | | **vbOLESizeAutoSize** | 2 | The container resizes itself to fit the object. | | **vbOLESizeZoom** | 3 | The object is scaled to fit, preserving its aspect ratio. | ## Display style | Constant | Value | Description | |----------|-------|-------------| | **vbOLEDisplayContent** | 0 | The object's contents are displayed. | | **vbOLEDisplayIcon** | 1 | The object is displayed as an icon. | ## Status | Constant | Value | Description | |----------|-------|-------------| | **vbOLEChanged** | 0 | The object has been changed since the last update. | | **vbOLESaved** | 1 | The object has been saved. | | **vbOLEClosed** | 2 | The object has been closed. | | **vbOLERenamed** | 3 | The object has been renamed. | ## Verbs | Constant | Value | Description | |----------|-------|-------------| | **vbOLEPrimary** | 0 | Invoke the object's primary verb. | | **vbOLEShow** | -1 | Show the object. | | **vbOLEOpen** | -2 | Open the object in a separate window. | | **vbOLEHide** | -3 | Hide the object. | | **vbOLEUIActivate** | -4 | Activate the object's user interface. | | **vbOLEInPlaceActivate** | -5 | Activate the object in place. | | **vbOLEDiscardUndoState** | -6 | Discard any undo state the object holds. | ## Menu flags | Constant | Value | Description | |----------|-------|-------------| | **vbOLEFlagGrayed** | 1 | The verb appears grayed in the menu. | | **vbOLEFlagDisabled** | 2 | The verb is disabled. | | **vbOLEFlagChecked** | 8 | The verb appears with a check mark. | | **vbOLEFlagSeparator** | 2048 | The item is rendered as a menu separator. | ## Miscellaneous | Constant | Value | Description | |----------|-------|-------------| | **vbOLEMiscFlagMemStorage** | 1 | The object's storage is held in memory rather than on disk. | | **vbOLEMiscFlagDisableInPlace** | 2 | In-place activation is disabled for this object. | ### See Also * [OLEContainerActivateConstants](/en/official/Reference/VBRUN/Constants/OLEContainerActivateConstants) * [OLEContainerDisplayTypeConstants](/en/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants) * [OLEContainerSizeModeConstants](/en/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants) * [OLEContainerTypesAllowedConstants](/en/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants) * [OLEContainerUpdateOptionsConstants](/en/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants) --- --- url: /zh/official/Reference/VBRUN/Constants/OLEContainerConstants.md --- # OLEContainerConstants 包含**OLE**容器控件使用的所有选项值的组合枚举。每组逻辑值都有更具体的枚举 --- 参见另见部分 --- 但**OLEContainerConstants**保留了所有原始VB6名称,以便现有代码继续编译。 ## OLE类型 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLELinked** | 0 | 对象链接到其源。 | | **vbOLEEmbedded** | 1 | 对象嵌入在容器中。 | | **vbOLEEither** | 2 | 链接或嵌入。 | | **vbOLENone** | 3 | 无对象。 | ## 更新选项 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLEAutomatic** | 0 | 源更改时容器自动更新链接对象。 | | **vbOLEFrozen** | 1 | 更新已暂停。 | | **vbOLEManual** | 2 | 仅在调用**Update**时更新。 | ## 激活触发 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLEActivateManual** | 0 | 通过**DoVerb**手动激活。 | | **vbOLEActivateGetFocus** | 1 | 获得焦点时激活。 | | **vbOLEActivateDoubleclick** | 2 | 双击时激活。 | | **vbOLEActivateAuto** | 3 | 根据对象默认设置自动激活。 | ## 大小调整 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLESizeClip** | 0 | 对象在容器边缘处被裁剪。 | | **vbOLESizeStretch** | 1 | 对象拉伸以填充容器。 | | **vbOLESizeAutoSize** | 2 | 容器自动调整大小以适应对象。 | | **vbOLESizeZoom** | 3 | 对象按比例缩放以适应容器,保持宽高比。 | ## 显示样式 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLEDisplayContent** | 0 | 显示对象内容。 | | **vbOLEDisplayIcon** | 1 | 对象以图标显示。 | ## 状态 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLEChanged** | 0 | 对象自上次更新以来已更改。 | | **vbOLESaved** | 1 | 对象已保存。 | | **vbOLEClosed** | 2 | 对象已关闭。 | | **vbOLERenamed** | 3 | 对象已重命名。 | ## 动词 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLEPrimary** | 0 | 调用对象的主动词。 | | **vbOLEShow** | -1 | 显示对象。 | | **vbOLEOpen** | -2 | 在单独窗口中打开对象。 | | **vbOLEHide** | -3 | 隐藏对象。 | | **vbOLEUIActivate** | -4 | 激活对象的用户界面。 | | **vbOLEInPlaceActivate** | -5 | 就地激活对象。 | | **vbOLEDiscardUndoState** | -6 | 丢弃对象持有的任何撤销状态。 | ## 菜单标志 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLEFlagGrayed** | 1 | 动词在菜单中灰显。 | | **vbOLEFlagDisabled** | 2 | 动词被禁用。 | | **vbOLEFlagChecked** | 8 | 动词显示有复选标记。 | | **vbOLEFlagSeparator** | 2048 | 项目呈现为菜单分隔符。 | ## 杂项 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLEMiscFlagMemStorage** | 1 | 对象的存储保留在内存中而非磁盘上。 | | **vbOLEMiscFlagDisableInPlace** | 2 | 此对象禁用就地激活。 | ### 另见 * [OLEContainerActivateConstants](/official/Reference/VBRUN/Constants/OLEContainerActivateConstants) * [OLEContainerDisplayTypeConstants](/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants) * [OLEContainerSizeModeConstants](/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants) * [OLEContainerTypesAllowedConstants](/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants) * [OLEContainerUpdateOptionsConstants](/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants) --- --- url: /en/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants.md --- # OLEContainerDisplayTypeConstants Display-style values for the **DisplayType** property of an **OLE** container control. | Constant | Value | Description | |----------|-------|-------------| | **vbOLE\_DisplayContent** | 0 | The object's contents are displayed. | | **vbOLE\_DisplayIcon** | 1 | The object is displayed as an icon. | --- --- url: /zh/official/Reference/VBRUN/Constants/OLEContainerDisplayTypeConstants.md --- # OLEContainerDisplayTypeConstants **OLE**容器控件**DisplayType**属性的显示样式值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLE\_DisplayContent** | 0 | 显示对象内容。 | | **vbOLE\_DisplayIcon** | 1 | 对象以图标显示。 | --- --- url: /en/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants.md --- # OLEContainerSizeModeConstants Sizing-rule values for the **SizeMode** property of an **OLE** container control. | Constant | Value | Description | |----------|-------|-------------| | **vbOLE\_SizeClip** | 0 | The object is clipped at the container's edges. | | **vbOLE\_SizeStretch** | 1 | The object is stretched to fill the container, ignoring aspect ratio. | | **vbOLE\_SizeAutoSize** | 2 | The container resizes itself to fit the object. | | **vbOLE\_SizeZoom** | 3 | The object is scaled to fit the container while preserving its aspect ratio. | --- --- url: /zh/official/Reference/VBRUN/Constants/OLEContainerSizeModeConstants.md --- # OLEContainerSizeModeConstants **OLE**容器控件**SizeMode**属性的大小调整规则值。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLE\_SizeClip** | 0 | 对象在容器边缘处被裁剪。 | | **vbOLE\_SizeStretch** | 1 | 对象拉伸以填充容器,忽略宽高比。 | | **vbOLE\_SizeAutoSize** | 2 | 容器自动调整大小以适应对象。 | | **vbOLE\_SizeZoom** | 3 | 对象按比例缩放以适应容器,保持宽高比。 | --- --- url: /en/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants.md --- # OLEContainerTypesAllowedConstants Object-type filter values for the **OLETypeAllowed** property of an **OLE** container control, restricting which kinds of object the container will accept. | Constant | Value | Description | |----------|-------|-------------| | **vbOLE\_Linked** | 0 | Only linked objects are allowed. | | **vbOLE\_Embedded** | 1 | Only embedded objects are allowed. | | **vbOLE\_Either** | 2 | Either linked or embedded objects are allowed. | --- --- url: /zh/official/Reference/VBRUN/Constants/OLEContainerTypesAllowedConstants.md --- # OLEContainerTypesAllowedConstants **OLE**容器控件**OLETypeAllowed**属性的对象类型过滤值,限制容器接受哪些类型的对象。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLE\_Linked** | 0 | 仅允许链接对象。 | | **vbOLE\_Embedded** | 1 | 仅允许嵌入对象。 | | **vbOLE\_Either** | 2 | 允许链接或嵌入对象。 | --- --- url: /en/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants.md --- # OLEContainerUpdateOptionsConstants Update-mode values for the **UpdateOptions** property of an **OLE** container control, controlling how a linked object is kept in sync with its source. | Constant | Value | Description | |----------|-------|-------------| | **vbOLE\_UpdateAutomatic** | 0 | The object is updated whenever the source data changes. | | **vbOLE\_UpdateFrozen** | 1 | Updates are paused. | | **vbOLE\_UpdateManual** | 2 | The object is updated only when **Update** is called. | --- --- url: /zh/official/Reference/VBRUN/Constants/OLEContainerUpdateOptionsConstants.md --- # OLEContainerUpdateOptionsConstants **OLE**容器控件**UpdateOptions**属性的更新模式值,控制链接对象如何与其源保持同步。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLE\_UpdateAutomatic** | 0 | 源数据更改时自动更新对象。 | | **vbOLE\_UpdateFrozen** | 1 | 更新已暂停。 | | **vbOLE\_UpdateManual** | 2 | 仅在调用**Update**时更新对象。 | --- --- url: /en/official/Reference/VBRUN/Constants/OLEDragConstants.md --- # OLEDragConstants Mode values for the **OLEDragMode** property of a control, controlling whether OLE drag operations start automatically or only on demand. | Constant | Value | Description | |----------|-------|-------------| | **vbOLEDragManual** | 0 | OLE dragging starts only when the control's **OLEDrag** method is called from code. | | **vbOLEDragAutomatic** | 1 | OLE dragging starts automatically when the user begins to drag the control. | ::: info Available only when the **FEATURE\_OLEDRAGDROP** feature is enabled. ::: --- --- url: /zh/official/Reference/VBRUN/Constants/OLEDragConstants.md --- # OLEDragConstants 控件**OLEDragMode**属性的模式值,控制OLE拖动操作自动开始还是仅按需开始。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLEDragManual** | 0 | 仅在代码调用控件的**OLEDrag**方法时开始OLE拖动。 | | **vbOLEDragAutomatic** | 1 | 用户开始拖动控件时自动开始OLE拖动。 | ::: info 仅在启用**FEATURE\_OLEDRAGDROP**功能时可用。 ::: --- --- url: /en/official/Reference/VBRUN/Constants/OLEDropConstants.md --- # OLEDropConstants Mode values for the **OLEDropMode** property of a control, controlling whether and how the control accepts OLE drop operations. | Constant | Value | Description | |----------|-------|-------------| | **vbOLEDropNone** | 0 | The control does not accept OLE drops. | | **vbOLEDropManual** | 1 | The control raises **OLEDragOver** and **OLEDragDrop** events; the developer's code decides what to do. | | **vbOLEDropAutomatic** | 2 | The control handles drops automatically based on the dropped data's format. | ::: info Available only when the **FEATURE\_OLEDRAGDROP** feature is enabled. ::: --- --- url: /zh/official/Reference/VBRUN/Constants/OLEDropConstants.md --- # OLEDropConstants 控件**OLEDropMode**属性的模式值,控制控件是否以及如何接受OLE放置操作。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbOLEDropNone** | 0 | 控件不接受OLE放置。 | | **vbOLEDropManual** | 1 | 控件引发**OLEDragOver**和**OLEDragDrop**事件;由开发者的代码决定如何处理。 | | **vbOLEDropAutomatic** | 2 | 控件根据放置数据的格式自动处理放置。 | ::: info 仅在启用**FEATURE\_OLEDRAGDROP**功能时可用。 ::: --- --- url: /en/official/Reference/VBRUN/Constants/OLEDropEffectConstants.md --- # OLEDropEffectConstants Bit flags for the *Effect* argument of OLE drag-and-drop events, controlling what the source and target want the drop to do. | Constant | Value | Description | |----------|-------|-------------| | **vbDropEffectNone** | 0 | The drop is not allowed. | | **vbDropEffectCopy** | 1 | The data should be copied to the target. | | **vbDropEffectMove** | 2 | The data should be moved to the target --- the source removes it after a successful drop. | | **vbDropEffectLink** | 4 | A link to the data should be created at the target. *(twinBASIC addition.)* | | **vbDropEffectScroll** | -2147483648 | The target is scrolling because the cursor is near its edge. | ::: info Available only when the **FEATURE\_OLEDRAGDROP** feature is enabled. ::: --- --- url: /zh/official/Reference/VBRUN/Constants/OLEDropEffectConstants.md --- # OLEDropEffectConstants OLE拖放事件*Effect*参数的位标志,控制源和目标希望放置执行的操作。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbDropEffectNone** | 0 | 不允许放置。 | | **vbDropEffectCopy** | 1 | 数据应复制到目标。 | | **vbDropEffectMove** | 2 | 数据应移动到目标 --- 放置成功后源端将其删除。 | | **vbDropEffectLink** | 4 | 应在目标创建数据的链接。*(twinBASIC新增)* | | **vbDropEffectScroll** | -2147483648 | 目标正在滚动,因为光标靠近其边缘。 | ::: info 仅在启用**FEATURE\_OLEDRAGDROP**功能时可用。 ::: --- --- url: /en/official/Reference/Core/On-Error.md --- # On Error Enables an error-handling routine and specifies the location of the routine within a procedure; can also be used to disable an error-handling routine. Syntax: * > **On Error GoTo** *line* * > **On Error Resume Next** * > **On Error GoTo 0** **On Error GoTo** *line* : Enables the error-handling routine that starts at *line*. The *line* argument is any line label or line number. If a run-time error occurs, control branches to *line*, making the error handler active. The specified *line* must be in the same procedure as the **On Error** statement; otherwise, a compile-time error occurs. **On Error Resume Next** : Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred and execution continues. This form is preferred over **On Error GoTo** when accessing objects. **On Error GoTo 0** : Disables any enabled error handler in the current procedure. Without an **On Error** statement, any run-time error that occurs is fatal; that is, an error message is displayed and execution stops. An "enabled" error handler is one that is turned on by an **On Error** statement; an "active" error handler is an enabled handler that is in the process of handling an error. If an error occurs while an error handler is active (between the occurrence of the error and a [**Resume**](/en/official/Reference/Core/Resume), [**Exit Sub**](/en/official/Reference/Core/Exit), **Exit Function**, or **Exit Property** statement), the current procedure's error handler can't handle the error. Control returns to the calling procedure. If the calling procedure has an enabled error handler, it is activated to handle the error. If the calling procedure's error handler is also active, control passes back through previous calling procedures until an enabled, but inactive, error handler is found. If no inactive, enabled error handler is found, the error is fatal at the point at which it actually occurred. Each time the error handler passes control back to a calling procedure, that procedure becomes the current procedure. After an error is handled by an error handler in any procedure, execution resumes in the current procedure at the point designated by the **Resume** statement. ::: info An error-handling routine is not a [**Sub**](/en/official/Reference/Core/Sub) procedure or [**Function**](/en/official/Reference/Core/Function) procedure. It's a section of code marked by a line label or line number. ::: Error-handling routines rely on the value in the **Number** property of the **Err** object to determine the cause of the error. The error-handling routine should test or save relevant property values in the **Err** object before any other error can occur or before a procedure that might cause an error is called. The property values in the **Err** object reflect only the most recent error. The error message associated with **Err.Number** is contained in **Err.Description**. **On Error Resume Next** causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most recent call out of the procedure containing the **On Error Resume Next** statement. This statement allows execution to continue despite a run-time error. The error-handling routine can be placed where the error would occur, rather than transferring control to another location within the procedure. An **On Error Resume Next** statement becomes inactive when another procedure is called, so an **On Error Resume Next** statement must be executed in each called routine that requires inline error handling. ::: info The **On Error Resume Next** construct may be preferable to **On Error GoTo** when handling errors generated during access to other objects. Checking **Err** after each interaction with an object removes ambiguity about which object was accessed by the code. It is then clear which object placed the error code in **Err.Number**, as well as which object originally generated the error (the object specified in **Err.Source**). ::: **On Error GoTo 0** disables error handling in the current procedure. It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0. Without an **On Error GoTo 0** statement, an error handler is automatically disabled when a procedure is exited. To prevent error-handling code from running when no error has occurred, place an [**Exit Sub**](/en/official/Reference/Core/Exit), **Exit Function**, or **Exit Property** statement immediately before the error-handling routine, as in the following fragment: ```vb Sub InitializeMatrix(Var1, Var2, Var3, Var4) On Error GoTo ErrorHandler . . . Exit Sub ErrorHandler: . . . Resume Next End Sub ``` Here, the error-handling code follows the **Exit Sub** statement and precedes the [**End Sub**](/en/official/Reference/Core/End) statement to separate it from the procedure flow. Error-handling code can be placed anywhere in a procedure. When creating an object that accesses other objects, try to handle errors passed back from them unhandled. When such errors cannot be handled, map the error code in **Err.Number** to a project-specific error, and then pass it back to the caller of the object. Specify the error by adding the project error code to the **vbObjectError** constant. For example, if the error code is 1052, assign it as follows: ```vb Err.Number = vbObjectError + 1052 ``` ::: info System errors during calls to Windows dynamic-link libraries (DLLs) don't raise exceptions and cannot be trapped with twinBASIC error trapping. When calling DLL functions, check each return value for success or failure (according to the API specifications), and in the event of a failure, check the value in the **Err** object's **LastDLLError** property. ::: ### Example This example first uses the **On Error GoTo** statement to specify the location of an error-handling routine within a procedure. In the example, an attempt to delete an open file generates error number 55. The error is handled in the error-handling routine, and control is then returned to the statement that caused the error. The **On Error GoTo 0** statement turns off error trapping. The **On Error Resume Next** statement is then used to defer error trapping so that the context for the error generated by the next statement can be known for certain. Note that **Err.Clear** is used to clear the **Err** object's properties after the error is handled. ```vb Sub OnErrorStatementDemo() On Error GoTo ErrorHandler ' Enable error-handling routine. Open "TESTFILE" For Output As #1 ' Open file for output. Kill "TESTFILE" ' Attempt to delete open file. On Error GoTo 0 ' Turn off error trapping. On Error Resume Next ' Defer error trapping. ObjectRef = GetObject("MyWord.Basic") ' Try to start nonexistent object. ' Check for likely Automation errors. If Err.Number = 440 Or Err.Number = 432 Then ' Tell user what happened. Then clear the Err object. Msg = "There was an error attempting to open the Automation object!" MsgBox Msg, , "Deferred Error Test" Err.Clear ' Clear Err object fields. End If Exit Sub ' Exit to avoid handler. ErrorHandler: ' Error-handling routine. Select Case Err.Number ' Evaluate error number. Case 55 ' "File already open" error. Close #1 ' Close open file. Case Else ' Handle other situations here... End Select Resume ' Resume execution at same line that caused the error. End Sub ``` ### See Also * [**Resume** statement](/en/official/Reference/Core/Resume) * [**Error** statement](/en/official/Reference/Core/Error) * [**Exit** statement](/en/official/Reference/Core/Exit) * [**GoTo** statement](/en/official/Reference/Core/GoTo) --- --- url: /zh/official/Reference/Core/On-Error.md --- # On Error 启用错误处理例程并指定该例程在过程中的位置;也可用于禁用错误处理例程。 语法: * > **On Error GoTo** *line* * > **On Error Resume Next** * > **On Error GoTo 0** **On Error GoTo** *line* : 启用从*line*开始的错误处理例程。*line*参数可以是任何行标签或行号。如果发生运行时错误,控制分支转到*line*,使错误处理程序成为活动的。指定的*line*必须与**On Error**语句在同一过程中;否则会产生编译时错误。 **On Error Resume Next** : 指定当运行时错误发生时,控制转到出错语句之后紧接着的语句并继续执行。在访问对象时,此形式优于**On Error GoTo**。 **On Error GoTo 0** : 禁用当前过程中已启用的错误处理程序。 如果没有**On Error**语句,任何发生的运行时错误都是致命的;即显示错误消息并停止执行。 "已启用"的错误处理程序是已由**On Error**语句打开的处理程序;"活动的"错误处理程序是正在处理错误的已启用处理程序。如果错误处理程序处于活动状态时发生错误(在错误发生和[**Resume**](/official/Reference/Core/Resume)、[**Exit Sub**](/official/Reference/Core/Exit)、**Exit Function**或**Exit Property**语句之间),当前过程的错误处理程序无法处理该错误。控制返回到调用过程。 如果调用过程有已启用的错误处理程序,则激活它来处理错误。如果调用过程的错误处理程序也处于活动状态,则控制向上回溯先前调用过程,直到找到已启用但非活动的错误处理程序。如果找不到非活动的已启用错误处理程序,则错误在实际发生点成为致命错误。 每次错误处理程序将控制返回给调用过程时,该过程就成为当前过程。在错误被任何过程中的错误处理程序处理后,执行在当前过程中由**Resume**语句指定的位置继续。 ::: info 错误处理例程不是[**Sub**](/official/Reference/Core/Sub)过程或[**Function**](/official/Reference/Core/Function)过程。它是由行标签或行号标记的代码段。 ::: 错误处理例程依赖**Err**对象的**Number**属性值来确定错误原因。在发生任何其他错误或调用可能产生错误的过程之前,错误处理例程应测试或保存**Err**对象中的相关属性值。**Err**对象中的属性值仅反映最近一次错误。与**Err.Number**关联的错误消息包含在**Err.Description**中。 **On Error Resume Next**使执行继续到导致运行时错误的语句之后紧接着的语句,或继续到从包含**On Error Resume Next**语句的过程最近一次调用之后的语句。此语句允许在运行时错误发生时继续执行。错误处理例程可以放在错误可能发生的位置,而不是将控制转移到过程内的其他位置。**On Error Resume Next**语句在调用其他过程时变为非活动状态,因此必须在需要内联错误处理的每个被调用例程中执行**On Error Resume Next**语句。 ::: info 在处理访问其他对象时产生的错误时,**On Error Resume Next**结构可能比**On Error GoTo**更可取。在与对象每次交互后检查**Err**可以消除代码访问了哪个对象的歧义。这样就可以清楚地知道哪个对象将错误代码放入了**Err.Number**,以及哪个对象最初产生了错误(**Err.Source**中指定的对象)。 ::: **On Error GoTo 0**禁用当前过程中的错误处理。即使过程包含编号为0的行,它也不会将第0行指定为错误处理代码的起始位置。如果没有**On Error GoTo 0**语句,错误处理程序在过程退出时自动禁用。 为防止在没有错误发生时错误处理代码运行,请在错误处理例程之前紧接放置[**Exit Sub**](/official/Reference/Core/Exit)、**Exit Function**或**Exit Property**语句,如下面的代码片段所示: ```vb Sub InitializeMatrix(Var1, Var2, Var3, Var4) On Error GoTo ErrorHandler . . . Exit Sub ErrorHandler: . . . Resume Next End Sub ``` 此处,错误处理代码位于**Exit Sub**语句之后、[**End Sub**](/official/Reference/Core/End)语句之前,以将其与过程流程分开。错误处理代码可以放在过程中的任何位置。 创建访问其他对象的对象时,应尽量处理从这些对象传回的未处理错误。当无法处理此类错误时,将**Err.Number**中的错误代码映射为项目特定的错误,然后将其传回给对象的调用者。通过将项目错误代码加到**vbObjectError**常量上来指定错误。例如,如果错误代码为1052,则按如下方式赋值: ```vb Err.Number = vbObjectError + 1052 ``` ::: info 调用Windows动态链接库(DLL)时的系统错误不会引发异常,也无法用twinBASIC的错误捕获机制捕获。调用DLL函数时,应根据API规范检查每个返回值的成功或失败,如果失败,则检查**Err**对象的**LastDLLError**属性值。 ::: ### 示例 本示例首先使用**On Error GoTo**语句指定过程中错误处理例程的位置。在示例中,尝试删除已打开的文件会产生错误号55。该错误在错误处理例程中处理,然后控制返回到导致错误的语句。**On Error GoTo 0**语句关闭错误捕获。 然后使用**On Error Resume Next**语句延迟错误捕获,以便可以确定下一条语句所产生的错误的上下文。注意,在处理错误后使用**Err.Clear**清除**Err**对象的属性。 ```vb Sub OnErrorStatementDemo() On Error GoTo ErrorHandler ' Enable error-handling routine. Open "TESTFILE" For Output As #1 ' Open file for output. Kill "TESTFILE" ' Attempt to delete open file. On Error GoTo 0 ' Turn off error trapping. On Error Resume Next ' Defer error trapping. ObjectRef = GetObject("MyWord.Basic") ' Try to start nonexistent object. ' Check for likely Automation errors. If Err.Number = 440 Or Err.Number = 432 Then ' Tell user what happened. Then clear the Err object. Msg = "There was an error attempting to open the Automation object!" MsgBox Msg, , "Deferred Error Test" Err.Clear ' Clear Err object fields. End If Exit Sub ' Exit to avoid handler. ErrorHandler: ' Error-handling routine. Select Case Err.Number ' Evaluate error number. Case 55 ' "File already open" error. Close #1 ' Close open file. Case Else ' Handle other situations here... End Select Resume ' Resume execution at same line that caused the error. End Sub ``` ### 另请参阅 * [**Resume** 语句](/official/Reference/Core/Resume) * [**Error** 语句](/official/Reference/Core/Error) * [**Exit** 语句](/official/Reference/Core/Exit) * [**GoTo** 语句](/official/Reference/Core/GoTo) --- --- url: /en/official/Reference/Core/On-GoSub.md --- # On...GoSub Branches to one of several specified subroutine lines, depending on the value of an expression. The **On...GoSub** statement is documented together with **On...GoTo** on the [**On...GoTo, On...GoSub**](/en/official/Reference/Core/On-GoTo) page. Syntax: > **On** *expression* **GoSub** *destinationlist* When *expression* evaluates to *n*, control transfers to the *n*-th label in *destinationlist*, just as if a [**GoSub**](/en/official/Reference/Core/GoSub-Return) had been executed against that label. A subsequent [**Return**](/en/official/Reference/Core/Return) within the called subroutine resumes execution at the statement following the **On...GoSub**. See [**On...GoTo, On...GoSub**](/en/official/Reference/Core/On-GoTo) for the full description of out-of-range values, the 0-255 constraint on *expression*, and worked examples. ### See Also * [**On...GoTo** statement](/en/official/Reference/Core/On-GoTo) * [**GoSub...Return** statement](/en/official/Reference/Core/GoSub-Return) * [**Select Case** statement](/en/official/Reference/Core/Select-Case) --- --- url: /zh/official/Reference/Core/On-GoSub.md --- # On...GoSub 根据表达式的值,分支到几个指定子例行程序行之一。 **On...GoSub**语句与**On...GoTo**一起记录在[**On...GoTo, On...GoSub**](/official/Reference/Core/On-GoTo)页面上。 语法: > **On** *expression* **GoSub** *destinationlist* 当*expression*的计算结果为*n*时,控制转移到*destinationlist*中的第*n*个标签,就像对该标签执行了[**GoSub**](/official/Reference/Core/GoSub-Return)一样。被调用子例程中后续的[**Return**](/official/Reference/Core/Return)在**On...GoSub**之后的语句处恢复执行。有关超范围值的处理、*expression*的0-255约束以及详细示例,请参见[**On...GoTo, On...GoSub**](/official/Reference/Core/On-GoTo)。 ### 另请参阅 * [**On...GoTo** 语句](/official/Reference/Core/On-GoTo) * [**GoSub...Return** 语句](/official/Reference/Core/GoSub-Return) * [**Select Case** 语句](/official/Reference/Core/Select-Case) --- --- url: /en/official/Reference/Core/On-GoTo.md --- # On...GoTo, On...GoSub Branch to one of several specified lines, depending on the value of an expression. Syntax: * > **On** *expression* **GoTo** *destinationlist* * > **On** *expression* **GoSub** *destinationlist* *expression* : Any numeric expression that evaluates to a whole number between 0 and 255, inclusive. If *expression* is any number other than a whole number, it is rounded before it is evaluated. *destinationlist* : List of line numbers or line labels separated by commas. The value of *expression* determines which line is branched to in *destinationlist*. If the value of *expression* is less than 1 or greater than the number of items in the list, one of the following results occurs: | If *expression* is | Then | |:-----|:-----| | Equal to 0 | Control drops to the statement following **On...GoSub** or **On...GoTo**. | | Greater than the number of items in the list | Control drops to the statement following **On...GoSub** or **On...GoTo**. | | Negative | An error occurs. | | Greater than 255 | An error occurs. | Line numbers and line labels can be mixed in the same list. Any number of line labels and line numbers can be used with **On...GoSub** and **On...GoTo**. However, when more labels or numbers are present than fit on a single line, the line-continuation character must be used to continue the logical line onto the next physical line. ::: tip [**Select Case**](/en/official/Reference/Core/Select-Case) provides a more structured and flexible way to perform multiple branching. ::: ### Example This example uses the **On...GoSub** and **On...GoTo** statements to branch to subroutines and line labels, respectively. ```vb Sub OnGosubGotoDemo() Dim Number, MyString Number = 2 ' Initialize variable. ' Branch to Sub2. On Number GoSub Sub1, Sub2 ' Execution resumes here after On...GoSub. On Number GoTo Line1, Line2 ' Branch to Line2. ' Execution does not resume here after On...GoTo. Exit Sub Sub1: MyString = "In Sub1" : Return Sub2: MyString = "In Sub2" : Return Line1: MyString = "In Line1" Line2: MyString = "In Line2" End Sub ``` ### See Also * [**GoTo** statement](/en/official/Reference/Core/GoTo) * [**GoSub...Return** statement](/en/official/Reference/Core/GoSub-Return) * [**Select Case** statement](/en/official/Reference/Core/Select-Case) --- --- url: /zh/official/Reference/Core/On-GoTo.md --- # On...GoTo, On...GoSub 根据表达式的值,分支到几个指定行之一。 语法: * > **On** *expression* **GoTo** *destinationlist* * > **On** *expression* **GoSub** *destinationlist* *expression* : 计算结果为0到255之间(含)的整数的任意数值表达式。如果*expression*不是整数,则在计算前进行四舍五入。 *destinationlist* : 以逗号分隔的行号或行标签列表。 *expression*的值决定分支到*destinationlist*中的哪一行。如果*expression*的值小于1或大于列表中的项数,则产生以下结果之一: | 如果 *expression* 为 | 则 | |:-----|:-----| | 等于0 | 控制落到**On...GoSub**或**On...GoTo**之后的语句。 | | 大于列表中的项数 | 控制落到**On...GoSub**或**On...GoTo**之后的语句。 | | 为负数 | 产生错误。 | | 大于255 | 产生错误。 | 行号和行标签可以在同一列表中混合使用。**On...GoSub**和**On...GoTo**可以使用任意数量的行标签和行号。但是,当标签或编号多于一行所能容纳时,必须使用行继续符将逻辑行延续到下一个物理行。 ::: tip [**Select Case**](/official/Reference/Core/Select-Case)提供了一种更结构化、更灵活的方式来执行多路分支。 ::: ### 示例 本示例使用**On...GoSub**和**On...GoTo**语句分别分支到子例行程序和行标签。 ```vb Sub OnGosubGotoDemo() Dim Number, MyString Number = 2 ' Initialize variable. ' Branch to Sub2. On Number GoSub Sub1, Sub2 ' Execution resumes here after On...GoSub. On Number GoTo Line1, Line2 ' Branch to Line2. ' Execution does not resume here after On...GoTo. Exit Sub Sub1: MyString = "In Sub1" : Return Sub2: MyString = "In Sub2" : Return Line1: MyString = "In Line1" Line2: MyString = "In Line2" End Sub ``` ### 另请参阅 * [**GoTo** 语句](/official/Reference/Core/GoTo) * [**GoSub...Return** 语句](/official/Reference/Core/GoSub-Return) * [**Select Case** 语句](/official/Reference/Core/Select-Case) --- --- url: /en/official/Reference/Core/Open.md --- # Open Enables input/output (I/O) to a file. Syntax: > **Open** *pathname* **For** *mode* \[ **Access** *access* ] \[ *lock* ] \[ **Encoding** *encoding* ] **As** \[ **#** ] *filenumber* \[ **Len** **=** *reclength* ] *pathname* : String expression that specifies a file name; may include directory or folder, and drive. *mode* : Keyword specifying the file mode: **Append**, **Binary**, **Input**, **Output**, or **Random**. If unspecified, the file is opened for **Random** access. *access* : *optional* Keyword specifying the operations permitted on the open file: **Read**, **Write**, or **Read Write**. *lock* : *optional* Keyword specifying the operations restricted on the open file by other processes: **Shared**, **Lock Read**, **Lock Write**, or **Lock Read Write**. *encoding* : *optional* An encoding identifier --- for example **utf\_8**, **utf\_16**, **windows\_1252\_western**, or **default\_system\_ansi**. See [Text Encodings](#text-encodings) below for the full list. The **Encoding** clause applies to text-mode I/O (**Input**, **Output**, **Append**); it has no effect on **Binary** or **Random** mode files. *filenumber* : A valid file number in the range 1 to 511, inclusive. Use the [**FreeFile**](/en/official/Reference/VBA/FileSystem/FreeFile) function to obtain the next available file number. *reclength* : *optional* Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered. A file must be opened before any I/O operation can be performed on it. **Open** allocates a buffer for I/O to the file and determines the mode of access to use with the buffer. If the file specified by *pathname* doesn't exist, it is created when a file is opened for **Append**, **Binary**, **Output**, or **Random** modes. If the file is already opened by another process, and the specified type of access is not allowed, the **Open** operation fails and an error occurs. The **Len** clause is ignored if *mode* is **Binary**. ::: warning In **Binary**, **Input**, and **Random** modes, a file can be opened with a different file number without first closing the file. In **Append** and **Output** modes, a file must be closed before opening it with a different file number. ::: ::: info The **Encoding** clause is a twinBASIC extension. Classic VBA has no equivalent and reads or writes text using the system ANSI code page only. ::: ### Example This example illustrates various uses of the **Open** statement to enable input and output to a file. The following code opens the file in sequential-input mode. ```vb Open "TESTFILE" For Input As #1 ' Close before reopening in another mode. Close #1 ``` This example opens the file in **Binary** mode for writing operations only. ```vb Open "TESTFILE" For Binary Access Write As #1 ' Close before reopening in another mode. Close #1 ``` The following example opens the file in **Random** mode. The file contains records of the user-defined type. ```vb Type Record ' Define user-defined type. ID As Integer Name As String * 20 End Type Dim MyRecord As Record ' Declare variable. Open "TESTFILE" For Random As #1 Len = Len(MyRecord) ' Close before reopening in another mode. Close #1 ``` This code example opens the file for sequential output; any process can read or write to the file. ```vb Open "TESTFILE" For Output Shared As #1 ' Close before reopening in another mode. Close #1 ``` This code example opens the file in **Binary** mode for reading; other processes can't read the file. ```vb Open "TESTFILE" For Binary Access Read Lock Read As #1 ``` This example reads a UTF-8 text file, naming the [**utf\_8**](#utf_8) encoding identifier. ```vb Open "C:\MyFile.txt" For Input Encoding utf_8 As #1 ' Subsequent Line Input #, Input #, etc. interpret bytes as UTF-8. Close #1 ``` ### Text Encodings These identifier strings are accepted as the **Encoding** argument. The constants listed below name the well-known encodings; other system-supported encodings with similar identifier strings are also accepted at runtime. All members are marked **\[Hidden, Restricted]** --- they are omitted from general IntelliSense, but the IDE shows them automatically after the **Encoding** keyword. #### Default and Unicode | Constant | Value | Description | | ----------------------- | -------------- | ---------------------------------- | | **default\_system\_ansi** | `"default"` | The system default ANSI code page. | | **utf\_7** | `"utf-7"` | UTF-7. | | **utf\_7\_bom** | `"utf-7 bom"` | UTF-7 with byte-order mark. | | **utf\_8** | `"utf-8"` | UTF-8. | | **utf\_8\_bom** | `"utf-8 bom"` | UTF-8 with byte-order mark. | | **utf\_16** | `"utf-16"` | UTF-16 (little-endian). | | **utf\_16\_bom** | `"utf-16 bom"` | UTF-16 with byte-order mark. | | **us\_ascii** | `"us-ascii"` | 7-bit US-ASCII. | #### KOI8 (Cyrillic) | Constant | Value | Description | | ---------- | ---------- | ------------------ | | **koi8\_r** | `"koi8_r"` | KOI8-R, Russian. | | **koi8\_u** | `"koi8_u"` | KOI8-U, Ukrainian. | #### Big5 | Constant | Value | Description | | -------- | -------- | -------------------------- | | **big5** | `"big5"` | Big5, Traditional Chinese. | #### ISO 8859 | Constant | Value | Description | | ------------------------------ | --------------- | --------------------------------------------- | | **iso\_8859\_1\_latin1** | `"iso-8859-1"` | Latin-1, Western European. | | **iso\_8859\_2\_latin2** | `"iso-8859-2"` | Latin-2, Central European. | | **iso\_8859\_3\_latin3** | `"iso-8859-3"` | Latin-3, South European (Esperanto, Maltese). | | **iso\_8859\_4\_latin4** | `"iso-8859-4"` | Latin-4, North European. | | **iso\_8859\_5\_cyrillic** | `"iso-8859-5"` | Cyrillic. | | **iso\_8859\_6\_arabic** | `"iso-8859-6"` | Arabic. | | **iso\_8859\_7\_greek** | `"iso-8859-7"` | Greek. | | **iso\_8859\_8\_hebrew** | `"iso-8859-8"` | Hebrew. | | **iso\_8859\_9\_latin5\_turkish** | `"iso-8859-9"` | Latin-5, Turkish. | | **iso\_8859\_10\_latin6\_nordic** | `"iso-8859-10"` | Latin-6, Nordic. | | **iso\_8859\_11\_thai** | `"iso-8859-11"` | Thai. | | **iso\_8859\_13\_latin8\_baltic** | `"iso-8859-13"` | Latin-7, Baltic Rim. | | **iso\_8859\_14\_latin8\_celtic** | `"iso-8859-14"` | Latin-8, Celtic. | | **iso\_8859\_15\_latin9\_euro** | `"iso-8859-15"` | Latin-9, Western European with euro sign. | | **iso\_8859\_16\_latin10\_balkan** | `"iso-8859-16"` | Latin-10, South-Eastern European. | #### Windows code pages | Constant | Value | Description | | ------------------------------- | ---------------- | ----------------- | | **windows\_1250\_central\_europe** | `"windows-1250"` | Central European. | | **windows\_1251\_cyrillic** | `"windows-1251"` | Cyrillic. | | **windows\_1252\_western** | `"windows-1252"` | Western European. | | **windows\_1253\_greek** | `"windows-1253"` | Greek. | | **windows\_1254\_turkish** | `"windows-1254"` | Turkish. | | **windows\_1255\_hebrew** | `"windows-1255"` | Hebrew. | | **windows\_1256\_arabic** | `"windows-1256"` | Arabic. | | **windows\_1257\_baltic** | `"windows-1257"` | Baltic. | | **windows\_1258\_vietnamese** | `"windows-1258"` | Vietnamese. | #### IBM/OEM code pages | Constant | Value | Description | | -------------------------------------- | ------- | --------------------------------------------- | | **ibm\_850\_western\_europe** | `"850"` | OEM Multilingual Latin-1, Western European. | | **ibm\_852\_central\_and\_eastern\_europe** | `"852"` | OEM Latin-2, Central and Eastern European. | | **ibm\_855\_cyrillic** | `"855"` | OEM Cyrillic (primarily pre-Unicode Russian). | | **ibm\_856\_hebrew** | `"856"` | Hebrew. | | **ibm\_857\_turkish** | `"857"` | OEM Turkish (Latin-5). | | **ibm\_858\_western\_europe** | `"858"` | OEM Multilingual Latin-1 with euro sign. | | **ibm\_860\_portuguese** | `"860"` | Portuguese. | | **ibm\_861\_icelandic** | `"861"` | Icelandic. | | **ibm\_862\_hebrew** | `"862"` | Hebrew. | | **ibm\_863\_canadian** | `"863"` | French Canadian. | | **ibm\_865\_danish** | `"865"` | Nordic (Danish, Norwegian). | | **ibm\_866\_cyrillic** | `"866"` | Russian. | | **ibm\_869\_greek** | `"869"` | Modern Greek. | | **ibm\_932\_japanese** | `"932"` | Japanese (Shift-JIS, Microsoft variant). | | **ibm\_949\_korean** | `"949"` | Korean (Unified Hangul Code). | ### See Also * [**Close** statement](/en/official/Reference/Core/Close) * [**Get** statement](/en/official/Reference/Core/Get) * [**Put** statement](/en/official/Reference/Core/Put) * [**Input #** statement](/en/official/Reference/Core/Input) * [**Line Input #** statement](/en/official/Reference/Core/Line-Input) * [**Print #** statement](/en/official/Reference/Core/Print) * [**Write #** statement](/en/official/Reference/Core/Write) * [**Lock** / **Unlock** statements](/en/official/Reference/Core/Lock) * [**FreeFile** function](/en/official/Reference/VBA/FileSystem/FreeFile) --- --- url: /zh/official/Reference/Core/Open.md --- # Open 启用对文件的输入/输出(I/O)。 语法: > **Open** *pathname* **For** *mode* \[ **Access** *access* ] \[ *lock* ] \[ **Encoding** *encoding* ] **As** \[ **#** ] *filenumber* \[ **Len** **=** *reclength* ] *pathname* : 指定文件名的字符串表达式;可以包含目录或文件夹以及驱动器。 *mode* : 指定文件模式的关键字:**Append**、**Binary**、**Input**、**Output**或**Random**。如果未指定,文件以**Random**访问模式打开。 *access* : *可选* 指定对打开文件允许的操作的关键字:**Read**、**Write**或**Read Write**。 *lock* : *可选* 指定其他进程对打开文件受限操作的关键字:**Shared**、**Lock Read**、**Lock Write**或**Lock Read Write**。 *encoding* : *可选* 编码标识符——例如**utf\_8**、**utf\_16**、**windows\_1252\_western**或**default\_system\_ansi**。完整列表见下面的[文本编码](#text-encodings)。**Encoding**子句适用于文本模式I/O(**Input**、**Output**、**Append**);对**Binary**或**Random**模式文件无效。 *filenumber* : 范围1到511(含)的有效文件号。使用[**FreeFile**](/official/Reference/VBA/FileSystem/FreeFile)函数获取下一个可用文件号。 *reclength* : *可选* 小于或等于32,767(字节)的数字。对于以随机访问方式打开的文件,此值为记录长度。对于顺序文件,此值为缓冲的字符数。 在执行任何I/O操作之前,必须先打开文件。**Open**为文件I/O分配缓冲区并确定用于缓冲区的访问模式。 如果*pathname*指定的文件不存在,当以**Append**、**Binary**、**Output**或**Random**模式打开文件时会创建该文件。 如果文件已被其他进程打开,且不允许指定的访问类型,则**Open**操作失败并产生错误。 如果*mode*为**Binary**,则忽略**Len**子句。 ::: warning 在**Binary**、**Input**和**Random**模式下,可以在不先关闭文件的情况下用不同的文件号打开文件。在**Append**和**Output**模式下,必须先关闭文件才能用不同的文件号打开。 ::: ::: info **Encoding**子句是twinBASIC扩展。经典VBA没有等效功能,只能使用系统ANSI代码页读写文本。 ::: ### 示例 本示例演示了**Open**语句启用文件输入和输出的各种用法。 以下代码以顺序输入模式打开文件。 ```vb Open "TESTFILE" For Input As #1 ' Close before reopening in another mode. Close #1 ``` 本示例以**Binary**模式打开文件,仅用于写操作。 ```vb Open "TESTFILE" For Binary Access Write As #1 ' Close before reopening in another mode. Close #1 ``` 以下示例以**Random**模式打开文件。该文件包含用户自定义类型的记录。 ```vb Type Record ' Define user-defined type. ID As Integer Name As String * 20 End Type Dim MyRecord As Record ' Declare variable. Open "TESTFILE" For Random As #1 Len = Len(MyRecord) ' Close before reopening in another mode. Close #1 ``` 此代码示例以顺序输出方式打开文件;任何进程都可以读写该文件。 ```vb Open "TESTFILE" For Output Shared As #1 ' Close before reopening in another mode. Close #1 ``` 此代码示例以**Binary**模式打开文件用于读取;其他进程无法读取该文件。 ```vb Open "TESTFILE" For Binary Access Read Lock Read As #1 ``` 此示例读取UTF-8文本文件,指定[**utf\_8**](#utf_8)编码标识符。 ```vb Open "C:\MyFile.txt" For Input Encoding utf_8 As #1 ' Subsequent Line Input #, Input #, etc. interpret bytes as UTF-8. Close #1 ``` ### 文本编码 以下标识符字符串被接受为**Encoding**参数。下面列出的常量命名了已知编码;运行时也接受具有类似标识符字符串的其他系统支持的编码。所有成员均标记为\*\*\[Hidden, Restricted]**——它们在常规IntelliSense中省略,但IDE在**Encoding\*\*关键字后自动显示。 #### 默认和Unicode | 常量 | 值 | 说明 | | ----------------------- | -------------- | ------------------------ | | **default\_system\_ansi** | `"default"` | 系统默认ANSI代码页。 | | **utf\_7** | `"utf-7"` | UTF-7。 | | **utf\_7\_bom** | `"utf-7 bom"` | 带字节顺序标记的UTF-7。 | | **utf\_8** | `"utf-8"` | UTF-8。 | | **utf\_8\_bom** | `"utf-8 bom"` | 带字节顺序标记的UTF-8。 | | **utf\_16** | `"utf-16"` | UTF-16(小端序)。 | | **utf\_16\_bom** | `"utf-16 bom"` | 带字节顺序标记的UTF-16。 | | **us\_ascii** | `"us-ascii"` | 7位US-ASCII。 | #### KOI8(西里尔文) | 常量 | 值 | 说明 | | ---------- | ---------- | ------------------ | | **koi8\_r** | `"koi8_r"` | KOI8-R,俄语。 | | **koi8\_u** | `"koi8_u"` | KOI8-U,乌克兰语。 | #### Big5 | 常量 | 值 | 说明 | | -------- | -------- | ---------------- | | **big5** | `"big5"` | Big5,繁体中文。 | #### ISO 8859 | 常量 | 值 | 说明 | | ------------------------------ | --------------- | ----------------------------------- | | **iso\_8859\_1\_latin1** | `"iso-8859-1"` | Latin-1,西欧。 | | **iso\_8859\_2\_latin2** | `"iso-8859-2"` | Latin-2,中欧。 | | **iso\_8859\_3\_latin3** | `"iso-8859-3"` | Latin-3,南欧(世界语、马耳他语)。 | | **iso\_8859\_4\_latin4** | `"iso-8859-4"` | Latin-4,北欧。 | | **iso\_8859\_5\_cyrillic** | `"iso-8859-5"` | 西里尔文。 | | **iso\_8859\_6\_arabic** | `"iso-8859-6"` | 阿拉伯语。 | | **iso\_8859\_7\_greek** | `"iso-8859-7"` | 希腊语。 | | **iso\_8859\_8\_hebrew** | `"iso-8859-8"` | 希伯来语。 | | **iso\_8859\_9\_latin5\_turkish** | `"iso-8859-9"` | Latin-5,土耳其语。 | | **iso\_8859\_10\_latin6\_nordic** | `"iso-8859-10"` | Latin-6,北欧。 | | **iso\_8859\_11\_thai** | `"iso-8859-11"` | 泰语。 | | **iso\_8859\_13\_latin8\_baltic** | `"iso-8859-13"` | Latin-7,波罗的海地区。 | | **iso\_8859\_14\_latin8\_celtic** | `"iso-8859-14"` | Latin-8,凯尔特语。 | | **iso\_8859\_15\_latin9\_euro** | `"iso-8859-15"` | Latin-9,带欧元符号的西欧。 | | **iso\_8859\_16\_latin10\_balkan** | `"iso-8859-16"` | Latin-10,东南欧。 | #### Windows代码页 | 常量 | 值 | 说明 | | ------------------------------- | ---------------- | -------------- | | **windows\_1250\_central\_europe** | `"windows-1250"` | 中欧。 | | **windows\_1251\_cyrillic** | `"windows-1251"` | 西里尔文。 | | **windows\_1252\_western** | `"windows-1252"` | 西欧。 | | **windows\_1253\_greek** | `"windows-1253"` | 希腊语。 | | **windows\_1254\_turkish** | `"windows-1254"` | 土耳其语。 | | **windows\_1255\_hebrew** | `"windows-1255"` | 希伯来语。 | | **windows\_1256\_arabic** | `"windows-1256"` | 阿拉伯语。 | | **windows\_1257\_baltic** | `"windows-1257"` | 波罗的海地区。 | | **windows\_1258\_vietnamese** | `"windows-1258"` | 越南语。 | #### IBM/OEM代码页 | 常量 | 值 | 说明 | | -------------------------------------- | ------- | ------------------------------------ | | **ibm\_850\_western\_europe** | `"850"` | OEM多语言Latin-1,西欧。 | | **ibm\_852\_central\_and\_eastern\_europe** | `"852"` | OEM Latin-2,中东欧。 | | **ibm\_855\_cyrillic** | `"855"` | OEM西里尔文(主要为Unicode前俄语)。 | | **ibm\_856\_hebrew** | `"856"` | 希伯来语。 | | **ibm\_857\_turkish** | `"857"` | OEM土耳其语(Latin-5)。 | | **ibm\_858\_western\_europe** | `"858"` | 带欧元符号的OEM多语言Latin-1。 | | **ibm\_860\_portuguese** | `"860"` | 葡萄牙语。 | | **ibm\_861\_icelandic** | `"861"` | 冰岛语。 | | **ibm\_862\_hebrew** | `"862"` | 希伯来语。 | | **ibm\_863\_canadian** | `"863"` | 法语加拿大。 | | **ibm\_865\_danish** | `"865"` | 北欧(丹麦语、挪威语)。 | | **ibm\_866\_cyrillic** | `"866"` | 俄语。 | | **ibm\_869\_greek** | `"869"` | 现代希腊语。 | | **ibm\_932\_japanese** | `"932"` | 日语(Shift-JIS,Microsoft变体)。 | | **ibm\_949\_korean** | `"949"` | 韩语(统一Hangul码)。 | ### 另请参阅 * [**Close** 语句](/official/Reference/Core/Close) * [**Get** 语句](/official/Reference/Core/Get) * [**Put** 语句](/official/Reference/Core/Put) * [**Input #** 语句](/official/Reference/Core/Input) * [**Line Input #** 语句](/official/Reference/Core/Line-Input) * [**Print #** 语句](/official/Reference/Core/Print) * [**Write #** 语句](/official/Reference/Core/Write) * [**Lock** / **Unlock** 语句](/official/Reference/Core/Lock) * [**FreeFile** 函数](/official/Reference/VBA/FileSystem/FreeFile) --- --- url: /en/official/IDE/Open-Editors.md --- # Open Editors When a project isn't open this will be empty. ![Open Editors](Images/OpenEditors.png "Open Editors") When a project is open it will list the files that are currently open in your [Editor](/en/official/IDE/Editor) ![Open Editors](/assets/OpenEditors_1.BcjDvHpf.png "Open Editors") Clicking a file in the list brings it into focus in the editor. --- --- url: /en/official/Features/Language/Operators.md --- # New Operators twinBASIC introduces several new operators to enhance language capabilities. Reference pages for each individual operator live under [Reference → Operators](/en/official/Reference/Operators). ## Bitshift Operators [`<<`](/en/official/Reference/Core/LeftShift) and [`>>`](/en/official/Reference/Core/RightShift) perform left-shift and right-shift operations on a numeric variable. Note that shifts beyond available size result in 0, not wrapping. ## Short-Circuit Conditional Operators ### OrElse and AndAlso With the regular [`Or`](/en/official/Reference/Core/Or) and [`And`](/en/official/Reference/Core/And) statements, both sides are evaluated, even when not necessary. With a short-circuit operator, if the condition is resolved by the first side, the other side is not evaluated. So if you have `If Condition1 `[`OrElse`](/en/official/Reference/Core/OrElse)` Condition2 Then`, if `Condition1` is `True`, then `Condition2` will not be evaluated, and any code called by it will not run. The companion conjunction operator is [`AndAlso`](/en/official/Reference/Core/AndAlso). ### If() Operator Short-circuit [`If()`](/en/official/Reference/Core/If) operator with syntax identical to the traditional [`IIf`](/en/official/Reference/Core/IIf). This has the additional benefit of not converting variables into a `Variant` if they're the same type; i.e. `If(condition, Long, Long)` the `Long` variables will never become a `Variant`. ## Assignment Operators `+= -= /= \= *= ^= &= <<= >>=` These are the equivalent of `var = var (operand) (var2)`. So `i += 1` is the equivalent of `i = i + 1`. See [Reference → Operators → Compound Assignment](/en/official/Reference/Operators#compound-assignment) for the per-operator details. ## IsNot Operator The logical opposite of the [`Is`](/en/official/Reference/Core/Is) operator for testing object equivalence. For example, instead of `If (object Is Nothing) = False` you could now write `If object `[`IsNot`](/en/official/Reference/Core/IsNot)` Nothing Then`. ## Examples ```vb Dim n As Long = &HFF Dim shifted As Long = n << 4 ' result: &HFF0 n += 1 ' compound assignment: n = &H100 n <<= 2 ' left-shift assignment: n = &H400 Dim obj As Object = Nothing If obj IsNot Nothing Then Debug.Print obj Dim x As Long = -5 Debug.Print If(x >= 0, x, -x) ' short-circuit If(): prints 5 ``` --- --- url: /en/official/Reference/Operators.md --- # Operators Operators built into the twinBASIC language. They are understood by the compiler and are not declared or defined in the runtime library. ## Arithmetic * [+](/en/official/Reference/Core/Plus) -- addition; with **String** operands, concatenation * [-](/en/official/Reference/Core/Minus) -- subtraction; as a unary operator, negation * [\*](/en/official/Reference/Core/Multiply) -- multiplication * [/](/en/official/Reference/Core/Divide) -- floating-point division * [\\](/en/official/Reference/Core/IntegerDivide) -- integer division (truncating) * [Mod](/en/official/Reference/Core/Mod) -- divides two numbers and returns only the remainder * [ ^](/en/official/Reference/Core/Exponent) -- exponentiation ## Concatenation * [&](/en/official/Reference/Core/Concat) -- forces string concatenation, regardless of operand types ## Comparison * [Comparison operators](/en/official/Reference/Core/Comparison-Operators) (`=`, `<>`, `<`, `<=`, `>`, `>=`) -- numeric or string comparison * [Like](/en/official/Reference/Core/Like) -- wildcard / pattern-matching comparison * [Is](/en/official/Reference/Core/Is) -- compares two object references for identity * [IsNot](/en/official/Reference/Core/IsNot) -- (twinBASIC) the logical inverse of **Is** ## Bitwise Both operands are always evaluated. Booleans are treated as integers: True = -1, False = 0. * [And](/en/official/Reference/Core/And) -- bitwise conjunction * [Or](/en/official/Reference/Core/Or) -- bitwise disjunction * [Not](/en/official/Reference/Core/Not) -- bitwise negation * [Xor](/en/official/Reference/Core/Xor) -- bitwise exclusive-or * [Eqv](/en/official/Reference/Core/Eqv) -- bitwise equivalence * [Imp](/en/official/Reference/Core/Imp) -- bitwise implication ## Logical Short-Circuit The right operand is evaluated only when the left operand does not already determine the result. * [AndAlso](/en/official/Reference/Core/AndAlso) -- (twinBASIC) short-circuit conjunction; evaluates the right operand only if the left is **True** * [OrElse](/en/official/Reference/Core/OrElse) -- (twinBASIC) short-circuit disjunction; evaluates the right operand only if the left is **False** ## Bitshift *(twinBASIC)* Shifts are *logical* --- vacated bits are filled with zero, and shifts past the operand's width yield `0` rather than wrapping. * [<<](/en/official/Reference/Core/LeftShift) -- (twinBASIC) shifts a numeric value left by a given number of bits * [>>](/en/official/Reference/Core/RightShift) -- (twinBASIC) shifts a numeric value right by a given number of bits ## Object Identity * [Is](/en/official/Reference/Core/Is) -- compares two object references for identity * [IsNot](/en/official/Reference/Core/IsNot) -- (twinBASIC) the logical inverse of **Is** ## Compound Assignment *(twinBASIC)* For most arithmetic, concatenation, and bitshift operators, twinBASIC provides a compound form `op=` that combines the operation with assignment. `x op= y` is equivalent to `x = x op y`, but evaluates the left-hand side only once and is a statement rather than an expression. | Operator | Compound form | Equivalent to | | :----------------------------- | :------------ | :------------ | | [+](/en/official/Reference/Core/Plus) | **+=** | `x = x + y` | | [-](/en/official/Reference/Core/Minus) | **-=** | `x = x - y` | | [\*](/en/official/Reference/Core/Multiply) | **\*=** | `x = x * y` | | [/](/en/official/Reference/Core/Divide) | **/=** | `x = x / y` | | [\\](/en/official/Reference/Core/IntegerDivide) | **\\=** | `x = x \ y` | | [ ^](/en/official/Reference/Core/Exponent) | **^=** | `x = x ^ y` | | [&](/en/official/Reference/Core/Concat) | **&=** | `x = x & y` | | [<<](/en/official/Reference/Core/LeftShift) | **<<=** | `x = x << y` | | [>>](/en/official/Reference/Core/RightShift) | **>>=** | `x = x >> y` | There is no compound form for [**Mod**](/en/official/Reference/Core/Mod), or for any of the logical / comparison operators. ## Function Pointers * [AddressOf](/en/official/Reference/Core/AddressOf) -- produces a typed function-pointer to a procedure ## Operator Precedence When several operations occur in an expression, each part is evaluated in a fixed order. Arithmetic operators are evaluated first, comparison operators next, and logical operators last. Parentheses override the default order. Within each category, the order from highest to lowest precedence is: | Arithmetic | Comparison | Logical | |:-----------------------------------------------------|:--------------------------------------|:-----------| | Exponentiation (`^`) | Equality (`=`) | **Not** | | Unary negation (`-`) | Inequality (`<>`) | **And**, **AndAlso** | | Multiplication and division (`*`, `/`) | Less than (`<`) | **Or**, **OrElse** | | Integer division (`\`) | Greater than (`>`) | **Xor** | | Modulus (`Mod`) | Less than or equal to (`<=`) | **Eqv** | | Addition and subtraction (`+`, `-`) | Greater than or equal to (`>=`) | **Imp** | | String concatenation (`&`) | **Like**, **Is**, **IsNot** | | | Bitshift (`<<`, `>>`) | | | Comparison operators all have equal precedence and evaluate left-to-right. Multiplication and division also evaluate left-to-right when they appear together, as do addition and subtraction. The `&` operator is not strictly arithmetic, but in precedence it follows all arithmetic operators and precedes all comparison operators. The compound-assignment operators (`+=`, `-=`, `*=`, `/=`, `^=`, `&=`, `<<=`, `>>=`) appear only at statement level --- they are not part of any expression, so they do not participate in precedence. --- --- url: /en/official/Reference/Core/Option.md --- # Option Configures a compiler option. ## Option Base Syntax: **Option Base** { **0** | **1** } Used at the [module level](/en/official/Reference/Glossary#module-level) to declare the default lower bound for array subscripts. Because the default base is **0**, the **Option Base** statement is never required. If used, the statement must appear in a [module](/en/official/Reference/Glossary#module) or [class](/en/official/Reference/Glossary#class) before any procedures, functions, or properties. **Option Base** can appear only once in a module and must precede array [declarations](/en/official/Reference/Glossary#declaration) that include dimensions. ::: info The **To** clause in the [**Dim**](/en/official/Reference/Core/Dim), [**Private**](/en/official/Reference/Core/Private), [**Public**](/en/official/Reference/Core/Public), [**ReDim**](/en/official/Reference/Core/ReDim), and [**Static**](/en/official/Reference/Core/Static) statements provides a more flexible way to control the range of an array's subscripts. However, when the lower bound is not explicitly set with a **To** clause, **Option Base** can change the default lower bound to 1. The base of an array created with the [**ParamArray**](/en/official/Reference/Core/ParamArray) keyword is zero; **Option Base** does not affect [**ParamArray**](/en/official/Reference/Core/ParamArray) (or the [**Array**](/en/official/Reference/Core/Array) function). ::: The **Option Base** statement only affects the lower bound of arrays in the module where the statement is located. ### See Also * [**Dim**](/en/official/Reference/Core/Dim) and [**ReDim**](/en/official/Reference/Core/ReDim) statements * [**LBound**](/en/official/Reference/Core/LBound) and [**UBound**](/en/official/Reference/Core/UBound) functions ### Example of use at module level This example uses the **Option Base** statement to override the default base array subscript value of 0. The [**LBound**](/en/official/Reference/Core/LBound) function returns the smallest available subscript for the indicated dimension of an array. The **Option Base** statement is used at the module level only. ```vb Module MyModule Option Base 1 ' Set the default array subscripts to 1. Sub Example() Dim Lower Dim MyArray(20), TwoDArray(3, 4) ' Declare array variables. Dim ZeroArray(0 To 5) ' Override the default base subscript. ' Use LBound function to test lower bounds of arrays. Console.WriteLine LBound(MyArray) ' Prints 1. Console.WriteLine LBound(TwoDArray, 2) ' Returns 1. Console.WriteLinee LBound(ZeroArray) ' Returns 0. End Sub End Module ``` ### Example of use at class level ```vb Class Example1 Option Base 1 Sub New() Dim A1(5) Console.WriteLine LBound(A1) ' Prints 1 End Sub End Class Class Example0 Option Base 0 Sub New() Dim A0(5) Console.WriteLine LBound(A0) ' Prints 0 End Sub End Class ``` ## Option Explicit Syntax: **Option Explicit** Used at the [module level](/en/official/Reference/Glossary#module-level) to force explicit declaration of all [variables](/en/official/Reference/Glossary#variable) in that [module](/en/official/Reference/Glossary#module). If used, the **Option Explicit** statement must appear in a module before any [procedures](/en/official/Reference/Glossary#procedure). This option makes it mandatory to require variable declarations. There is no complementary option to make the declarations optional. When **Option Explicit** appears in a module, all variables must be explicitly declared by using the [**Dim**](/en/official/Reference/Core/Dim), [**Private**](/en/official/Reference/Core/Private), [**Public**](/en/official/Reference/Core/Public), [**ReDim**](/en/official/Reference/Core/ReDim), or [**Static**](/en/official/Reference/Core/Static) statements. Attempting to use an undeclared variable name raises an error at [compile time](/en/official/Reference/Glossary#compile-time). Without the **Option Explicit** statement, and when the [**Option Explicit On**](/en/official/IDE/Project-Settings#option-explicit-on) project setting is changed to its non-default value of *No*, all undeclared variables are of **Variant** type unless the default type is otherwise specified with a [**Def***type*](/en/official/Reference/Core/Deftype) statement. ::: info The **Option Explicit On** project setting is *Yes* by default in new projects. ::: **Option Explicit** prevents incorrect typing of an existing variable's name, and removes confusion where the [scope](/en/official/Reference/Glossary#scope) of a variable is not clear. ### See Also * [**Const**](/en/official/Reference/Core/Const), [**Dim**](/en/official/Reference/Core/Dim), and [**Static**](/en/official/Reference/Core/Static) statements ### Example of use at module level ```vb Module MyModule Option Explicit ' Force explicit variable declaration. Dim MyVar ' Declare variable. Sub Example() MyInt = 10 ' Undeclared variable generates error. MyVar = 10 ' Declared variable does not generate error. End Sub End Module ``` ## Option Compare Syntax: **Option Compare** { **Binary** | **Text** | **Database** } If used, the **Option Compare** statement must appear in a [module](/en/official/Reference/Glossary#module) before any [procedures](/en/official/Reference/Glossary#procedure). The **Option Compare** statement specifies the [string comparison](/en/official/Reference/Glossary#string-comparison) method (**Binary**, **Text**, or **Database**) for a module. If a module doesn't include an **Option Compare** statement, the default text comparison method is **Binary**. * **Option Compare Binary** results in string comparisons based on a [sort order](/en/official/Reference/Glossary#sort-order) derived from the internal binary representations of the characters. In Microsoft Windows, sort order is determined by the code page. A typical binary sort order is shown in the following example: ```vb A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø ``` * **Option Compare Text** results in string comparisons based on a case-insensitive text sort order determined by the system's [locale](/en/official/Reference/Glossary#locale). When the same characters are sorted by using **Option Compare Text**, the following text sort order is produced: ```vb (A=a) < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø) ``` * **Option Compare Database** has no effect in twinBASIC. When used within Microsoft Access, it results in string comparisons based on the sort order determined by the locale ID of the database where the string comparisons occur. ### See Also * [**InStr$**](/en/official/Reference/VBA/Strings/InStr), [**InStr**](/en/official/Reference/VBA/Strings/InStr), [**InStrB**](/en/official/Reference/VBA/Strings/InStr), and [**InStrRev**](/en/official/Reference/VBA/Strings/InStrRev) functions. ### Example This example uses the **Option Compare** statement to set the default string comparison method. The **Option Compare** statement is used at the module level only. ```vb Module ModBin ' Set the string comparison method to Binary. Option Compare Binary ' That is, "AAA" is less than "aaa". End Module Module ModText ' Set the string comparison method to Text. Option Compare Text ' That is, "AAA" is equal to "aaa". End Module ``` ## Option Private Syntax: **Option Private Module** When used in applications that reference multiple [packages](/en/official/Reference/Glossary#package), **Option Private Module** prevents a [module's](/en/official/Reference/Glossary#module) or [class's](/en/official/Reference/Glossary#class) contents from being referenced outside its package. If used, the **Option Private** statement must appear at [module level](/en/official/Reference/Glossary#module-level) or [class level](/en/official/Reference/Glossary#class-level), before any [procedures](/en/official/Reference/Glossary#procedure). When a module contains **Option Private Module**, the public parts, for example, [variables](/en/official/Reference/Glossary#variable), [objects](/en/official/Reference/Glossary#object), and [user-defined types](/en/official/Reference/Glossary#user-defined-type) declared at the module level, are still available within the [project](/en/official/Reference/Glossary#project) containing the module, but they are not available to other applications or projects. ::: info **Option Private** is a more verbose way of making modules or classes private to the package. An equivalent effect in a less verbose fashion is obtained with [**Private**](/en/official/Reference/Core/Private) statement as follows: ```vb Private Module MyModule ' ... End Module Private Class MyClass ' ... End Class ``` ::: ### Example This example demonstrates the **Option Private** statement, which is used at module level to indicate that the entire module is private. With **Option Private Module**, module-level parts not declared **Private** are available to other modules in the project, but not to other projects or applications. ```vb Module MyModule Option Private Module ' Indicates that the module is private. End Module ``` --- --- url: /zh/official/Reference/Core/Option.md --- # Option 配置编译器选项。 ## Option Base 语法:**Option Base** { **0** | **1** } 在[模块级](/official/Reference/Glossary#module-level)用于声明数组下标的默认下界。 由于默认基数为**0**,**Option Base**语句永远不是必需的。 如果使用,该语句必须出现在[模块](/official/Reference/Glossary#module)或[类](/official/Reference/Glossary#class)中的任何过程、函数或属性之前。**Option Base**在模块中只能出现一次,且必须在包含维度的数组[声明](/official/Reference/Glossary#declaration)之前。 ::: info [**Dim**](/official/Reference/Core/Dim)、[**Private**](/official/Reference/Core/Private)、[**Public**](/official/Reference/Core/Public)、[**ReDim**](/official/Reference/Core/ReDim)和[**Static**](/official/Reference/Core/Static)语句中的**To**子句提供了更灵活的方式来控制数组下标的范围。但是,当未用**To**子句显式设置下界时,**Option Base**可以将默认下界更改为1。使用[**ParamArray**](/official/Reference/Core/ParamArray)关键字创建的数组的基数为零;**Option Base**不影响[**ParamArray**](/official/Reference/Core/ParamArray)(或[**Array**](/official/Reference/Core/Array)函数)。 ::: **Option Base**语句仅影响该语句所在模块中数组的下界。 ### 另请参阅 * [**Dim**](/official/Reference/Core/Dim)和[**ReDim**](/official/Reference/Core/ReDim)语句 * [**LBound**](/official/Reference/Core/LBound)和[**UBound**](/official/Reference/Core/UBound)函数 ### 模块级使用示例 本示例使用**Option Base**语句将默认的数组下标基数值0覆盖为1。[**LBound**](/official/Reference/Core/LBound)函数返回数组指定维度的最小可用下标。**Option Base**语句仅在模块级使用。 ```vb Module MyModule Option Base 1 ' Set the default array subscripts to 1. Sub Example() Dim Lower Dim MyArray(20), TwoDArray(3, 4) ' Declare array variables. Dim ZeroArray(0 To 5) ' Override the default base subscript. ' Use LBound function to test lower bounds of arrays. Console.WriteLine LBound(MyArray) ' Prints 1. Console.WriteLine LBound(TwoDArray, 2) ' Returns 1. Console.WriteLinee LBound(ZeroArray) ' Returns 0. End Sub End Module ``` ### 类级使用示例 ```vb Class Example1 Option Base 1 Sub New() Dim A1(5) Console.WriteLine LBound(A1) ' Prints 1 End Sub End Class Class Example0 Option Base 0 Sub New() Dim A0(5) Console.WriteLine LBound(A0) ' Prints 0 End Sub End Class ``` ## Option Explicit 语法:**Option Explicit** 在[模块级](/official/Reference/Glossary#module-level)用于强制显式声明该[模块](/official/Reference/Glossary#module)中的所有[变量](/official/Reference/Glossary#variable)。 如果使用,**Option Explicit**语句必须出现在模块中的任何[过程](/official/Reference/Glossary#procedure)之前。 此选项使变量声明成为强制性的。没有对应的选项可以使声明变为可选。 当**Option Explicit**出现在模块中时,所有变量必须使用[**Dim**](/official/Reference/Core/Dim)、[**Private**](/official/Reference/Core/Private)、[**Public**](/official/Reference/Core/Public)、[**ReDim**](/official/Reference/Core/ReDim)或[**Static**](/official/Reference/Core/Static)语句显式声明。尝试使用未声明的变量名会在[编译时](/official/Reference/Glossary#compile-time)引发错误。 如果没有**Option Explicit**语句,且[**Option Explicit On**](/official/IDE/Project-Settings#option-explicit-on)项目设置更改为非默认值*No*,则所有未声明的变量均为**Variant**类型,除非使用[**Def***type*](/official/Reference/Core/Deftype)语句另行指定默认类型。 ::: info **Option Explicit On**项目设置在新项目中默认为*Yes*。 ::: **Option Explicit**可防止错误键入现有变量的名称,并消除变量[作用域](/official/Reference/Glossary#scope)不清晰时的混淆。 ### 另请参阅 * [**Const**](/official/Reference/Core/Const)、[**Dim**](/official/Reference/Core/Dim)和[**Static**](/official/Reference/Core/Static)语句 ### 模块级使用示例 ```vb Module MyModule Option Explicit ' Force explicit variable declaration. Dim MyVar ' Declare variable. Sub Example() MyInt = 10 ' Undeclared variable generates error. MyVar = 10 ' Declared variable does not generate error. End Sub End Module ``` ## Option Compare 语法:**Option Compare** { **Binary** | **Text** | **Database** } 如果使用,**Option Compare**语句必须出现在[模块](/official/Reference/Glossary#module)中的任何[过程](/official/Reference/Glossary#procedure)之前。 **Option Compare**语句为模块指定[字符串比较](/official/Reference/Glossary#string-comparison)方法(**Binary**、**Text**或**Database**)。如果模块不包含**Option Compare**语句,默认的文本比较方法为**Binary**。 * **Option Compare Binary**会根据字符的内部二进制表示派生的[排序顺序](/official/Reference/Glossary#sort-order)进行字符串比较。在Microsoft Windows中,排序顺序由代码页决定。典型的二进制排序顺序如下例所示: ```vb A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø ``` * **Option Compare Text**会根据系统的[区域设置](/official/Reference/Glossary#locale)确定的不区分大小写的文本排序顺序进行字符串比较。当使用**Option Compare Text**对相同字符排序时,产生的文本排序顺序如下: ```vb (A=a) < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø) ``` * **Option Compare Database**在twinBASIC中无效。在Microsoft Access中使用时,它会根据发生字符串比较的数据库的区域设置ID确定的排序顺序进行字符串比较。 ### 另请参阅 * [**InStr$**](/official/Reference/VBA/Strings/InStr)、[**InStr**](/official/Reference/VBA/Strings/InStr)、[**InStrB**](/official/Reference/VBA/Strings/InStr)和[**InStrRev**](/official/Reference/VBA/Strings/InStrRev)函数。 ### 示例 本示例使用**Option Compare**语句设置默认的字符串比较方法。**Option Compare**语句仅在模块级使用。 ```vb Module ModBin ' Set the string comparison method to Binary. Option Compare Binary ' That is, "AAA" is less than "aaa". End Module Module ModText ' Set the string comparison method to Text. Option Compare Text ' That is, "AAA" is equal to "aaa". End Module ``` ## Option Private 语法:**Option Private Module** 在引用多个[包](/official/Reference/Glossary#package)的应用程序中使用时,**Option Private Module**可防止[模块](/official/Reference/Glossary#module)或[类](/official/Reference/Glossary#class)的内容在其包外被引用。 如果使用,**Option Private**语句必须出现在[模块级](/official/Reference/Glossary#module-level)或[类级](/official/Reference/Glossary#class-level),在任何[过程](/official/Reference/Glossary#procedure)之前。 当模块包含**Option Private Module**时,公共部分(例如在模块级声明的[变量](/official/Reference/Glossary#variable)、[对象](/official/Reference/Glossary#object)和[用户自定义类型](/official/Reference/Glossary#user-defined-type))仍可在包含该模块的[项目](/official/Reference/Glossary#project)内使用,但其他应用程序或项目无法使用。 ::: info **Option Private**是使模块或类对包私有的更冗长的方式。使用[**Private**](/official/Reference/Core/Private)语句可以用更简洁的方式获得等效效果: ```vb Private Module MyModule ' ... End Module Private Class MyClass ' ... End Class ``` ::: ### 示例 本示例演示**Option Private**语句,该语句用在模块级表示整个模块是私有的。使用**Option Private Module**时,模块级中未声明为**Private**的部分对项目中的其他模块可用,但对其他项目或应用程序不可用。 ```vb Module MyModule Option Private Module ' Indicates that the module is private. End Module ``` --- --- url: /en/official/Reference/VB/OptionButton.md --- # OptionButton class An **OptionButton** is a Win32 native control that displays a small round selector, optionally followed by a text caption, used to give the user a single choice within a group of related options. Option buttons that share a [**Container**](#container) form a *mutually exclusive group*: selecting one automatically clears every other option button in the same container. The control is normally placed on a [**Form**](/en/official/Reference/VB/Form/), [**Frame**](/en/official/Reference/VB/Frame/), or **UserControl** at design time. The default property is [**Value**](#value) and the default event is [**Click**](#click). ```vb Private Sub Form_Load() optHTML.Caption = "&HTML" optMarkdown.Caption = "&Markdown" optPlain.Caption = "&Plain text" optHTML.Value = True ' default selection End Sub Private Sub optHTML_Click() Debug.Print "Output format: HTML" End Sub ``` ## Mutual exclusion Setting [**Value**](#value) to **True** on one option button clears every other option button whose [**Container**](#container) is the same control --- typically the parent form or a [**Frame**](/en/official/Reference/VB/Frame/). Option buttons in sibling frames are not affected, so a single form can host any number of independent groups: drop the buttons that belong to one group onto a frame, and the buttons that belong to a different group onto another frame (or directly onto the form). ```vb ' Two independent groups on one form: ' fraSize: optSmall, optMedium, optLarge (children of fraSize) ' fraColour: optRed, optGreen, optBlue (children of fraColour) ``` Setting [**Value**](#value) to **False** never deselects another button --- there is no automatic *fallback* to a different option, so applications normally guarantee that exactly one button in each group is selected by setting one of them to **True** at start-up. Assigning **False** to the currently selected button leaves the group with no selection until the user (or code) selects another one. ## Click semantics [**Click**](#click) is raised only when [**Value**](#value) transitions from **False** to **True** --- whether the user clicked the button, pressed its access key, or assigned **True** in code. Re-clicking an already selected option button does nothing, and assigning **False** to a selected button does *not* raise [**Click**](#click). The event also does not fire while the form is loading; it starts firing once the control's [**Initialize**](#initialize) event has run. ## Caption and mnemonics The text shown next to (or, with [**Alignment**](#alignment) `tbRightJustify`, before) the selector comes from [**Caption**](#caption). An ampersand in the caption marks the next character as a keyboard mnemonic: pressing **Alt+** that character moves the focus to the option button and selects it. Use `&&` to display a literal ampersand. ```vb optTerms.Caption = "I &agree to the terms" optTerms.Caption = "Use && in folder names" ' renders as: Use & in folder names ``` ## Graphical style When [**Style**](#style) is **vbButtonGraphical**, the option button is owner-drawn and displays the bitmaps assigned to [**Picture**](#picture), [**DownPicture**](#downpicture), and [**DisabledPicture**](#disabledpicture) instead of the standard round selector. [**PictureAlignment**](#picturealignment), [**Padding**](#padding), and [**PictureDpiScaling**](#picturedpiscaling) control how the picture is positioned relative to the caption. ## Properties ### Alignment Specifies the side of the selector on which the [**Caption**](#caption) text appears. Syntax: *object*.**Alignment** \[ = *value* ] *value* : A member of [**AlignmentConstantsNoCenter**](/en/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter): **tbLeftJustify** (0, default --- caption to the right of the selector) or **tbRightJustify** (1 --- caption to the left of the selector). ### Anchors The set of edges of the parent that the option button's corresponding edges follow when the parent resizes. Read-only --- assign individual `.Left`, `.Top`, `.Right`, `.Bottom` flags through the returned **Anchors** object. ### Appearance Determines how the control's border is drawn by the OS. A member of [**AppearanceConstants**](/en/official/Reference/VBRUN/Constants/AppearanceConstants): **vbAppearFlat** or **vbAppear3d** (default). ### BackColor The background colour, as an **OLE\_COLOR**. Defaults to the system 3-D face colour. ### Caption The text displayed next to the option button. An ampersand marks the next character as a mnemonic; `&&` produces a literal ampersand. The string is read directly from the underlying window --- assigning to **Caption** is reflected immediately. Syntax: *object*.**Caption** \[ = *string* ] ### CausesValidation Determines whether the previously focused control's [**Validate**](#validate) event runs before this control receives the focus. **Boolean**, default **True**. ### Container The control that hosts this option button --- typically a [**Frame**](/en/official/Reference/VB/Frame/) or the parent form. Read with **Get**, change with **Set**. Setting **Container** at run time re-parents the option button into a different group; it is automatically excluded from the old group's mutual-exclusion set and included in the new one. ### ControlType A read-only [**ControlTypeConstants**](/en/official/Reference/VBRUN/Constants/ControlTypeConstants) value identifying this control as an option button. Always **vbOptionButton**. ### DisabledPicture A **StdPicture** drawn instead of [**Picture**](#picture) when the control is disabled and [**Style**](#style) is **vbButtonGraphical**. ### Dock Where the option button is docked within its container. A member of [**DockModeConstants**](/en/official/Reference/VBRUN/Constants/DockModeConstants): **vbDockNone** (default), **vbDockLeft**, **vbDockTop**, **vbDockRight**, **vbDockBottom**, or **vbDockFill**. Docked controls ignore [**Anchors**](#anchors). ### DownPicture A **StdPicture** drawn instead of [**Picture**](#picture) while the control is in the depressed/selected state, when [**Style**](#style) is **vbButtonGraphical**. ### DragIcon A **StdPicture** used as the mouse cursor while the control is being drag-and-dropped (see [**Drag**](#drag) and [**DragMode**](#dragmode)). ### DragMode Whether the control should drag itself when the user holds the mouse over it. A member of [**DragModeConstants**](/en/official/Reference/VBRUN/Constants/DragModeConstants): **vbManual** (0, default --- call [**Drag**](#drag) from code) or **vbAutomatic** (1). ### Enabled Determines whether the control accepts user input. A disabled option button shows its current value but is dimmed and ignores keyboard and mouse interaction. **Boolean**, default **True**. ### Font The **StdFont** used to render [**Caption**](#caption). The convenience properties **FontName**, **FontSize**, **FontBold**, **FontItalic**, **FontStrikethru**, and **FontUnderline** read or write the corresponding members of this object. ### ForeColor The text colour for the caption, as an **OLE\_COLOR**. Defaults to the system button-text colour. ### Height The control's height, in twips by default (or in the container's **ScaleMode** units). **Single**. ### HelpContextID A **Long** identifying a topic in the application's help file, retrieved when the user presses **F1** while the control has focus. ### hWnd The Win32 window handle for the underlying button, as a **LongPtr**. Read-only. Useful for passing to API functions. ### Index When the control is part of a control array, the **Long** zero-based index of this instance within the array. Reading **Index** on a non-array instance raises run-time error 343 (*Object not an array*). Read-only at run time. ### Left The horizontal distance from the left edge of the container to the left edge of the control. **Single**. ### MaskColor ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### MouseIcon A **StdPicture** used as the mouse cursor when [**MousePointer**](#mousepointer) is **vbCustom** and the pointer is over the control. ### MousePointer The mouse cursor shown when the pointer is over the control. A member of [**MousePointerConstants**](/en/official/Reference/VBRUN/Constants/MousePointerConstants). ### Name The unique design-time name of the control on its parent form. Read-only at run time. ### OLEDropMode How the control responds to OLE drops. A restricted member of [**OLEDropConstants**](/en/official/Reference/VBRUN/Constants/OLEDropConstants): **vbOLEDropNone** or **vbOLEDropManual**. Automatic-drop mode is not supported on an OptionButton. ### Opacity The control's opacity as a percentage (0--100, default 100). Values outside the range are clamped on **Initialize**. Requires Windows 8 or later for child controls. ### Padding The number of pixels of empty space inserted between the picture and the caption (when [**PictureAlignment**](#picturealignment) is **vbAlignLeft** or **vbAlignRight**) or between the caption and the corresponding edge (when **vbAlignTop** or **vbAlignBottom**). **Long**, default 2. Only meaningful when [**Style**](#style) is **vbButtonGraphical**. ### Parent A reference to the [**Form**](/en/official/Reference/VB/Form/) (or **UserControl**) that ultimately contains this control. Read-only. Distinct from [**Container**](#container), which returns the immediate parent --- for an option button placed inside a [**Frame**](/en/official/Reference/VB/Frame/), **Container** returns the frame and **Parent** returns the form. ### Picture A **StdPicture** drawn on the control when [**Style**](#style) is **vbButtonGraphical**. Assigning **Nothing** restores an empty picture rather than removing the bitmap surface. ### PictureAlignment How [**Picture**](#picture) is positioned relative to the caption when [**Style**](#style) is **vbButtonGraphical**. A member of [**AlignConstants**](/en/official/Reference/VBRUN/Constants/AlignConstants): **vbAlignNone**, **vbAlignTop** (default), **vbAlignBottom**, **vbAlignLeft**, **vbAlignRight**. ### PictureDpiScaling When **True**, scales [**Picture**](#picture), [**DownPicture**](#downpicture), and [**DisabledPicture**](#disabledpicture) by the current DPI factor before drawing. **Boolean**, default **False**. ### RightToLeft ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. Use [**Alignment**](#alignment) to flip the caption to the left of the selector. ::: ### Style Selects between the standard Win32 option-button appearance and an owner-drawn graphical button. A member of [**ButtonConstants**](/en/official/Reference/VBRUN/Constants/ButtonConstants): **vbButtonStandard** (0, default) or **vbButtonGraphical** (1). Changing **Style** at run time recreates the underlying window. ### TabIndex The position of the control in the form's TAB-key navigation order. **Long**. ### TabStop Whether the user can reach the control by pressing the **TAB** key. **Boolean**, default **True**. The TAB-key navigation also follows the option-button group convention: once the focus enters a group, the arrow keys move it (and the selection) between the group's members rather than between unrelated controls. A disabled control is skipped regardless of this setting. ### Tag A free-form **String** the application can use to associate custom data with the control. Ignored by the framework. ### ToolTipText A multi-line **String** displayed as a tooltip when the user hovers over the control. ### Top The vertical distance from the top of the container to the top of the control. **Single**. ### TransparencyKey An **OLE\_COLOR** that, when set, becomes fully transparent in the rendered control. Default `-1` disables the effect. Requires Windows 8 or later for child controls. ### UseMaskColor ::: info Reserved for compatibility with VB6; not currently implemented in twinBASIC. ::: ### Value The current state of the option button. **Default property.** Syntax: *object*.**Value** \[ = *value* ] *value* : A **Boolean**: **True** if the option button is selected, **False** if cleared. Assigning **True** clears every other option button in the same [**Container**](#container) and raises [**Click**](#click). Assigning **False** clears just this button without affecting any other and does not raise [**Click**](#click). Assigning the value the button already holds does nothing. ### Visible Whether the control is shown. **Boolean**, default **True**. ### VisualStyles Whether the OS theme engine should be used when drawing the control. **Boolean**. ### WhatsThisHelpID A **Long** identifying a "What's This?" help-pop-up topic in the application's help file. See [**ShowWhatsThis**](#showwhatsthis). ### Width The control's width. **Single**. ## Methods ### Drag Begins, completes, or cancels a manual drag-and-drop operation. Typically called from a [**MouseDown**](#mousedown) handler when [**DragMode**](#dragmode) is **vbManual**. Syntax: *object*.**Drag** \[ *Action* ] *Action* : *optional* A member of [**DragConstants**](/en/official/Reference/VBRUN/Constants/DragConstants): **vbCancel** (0), **vbBeginDrag** (1, default), or **vbEndDrag** (2). ### Move Repositions and optionally resizes the control in a single call. Syntax: *object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *required* A **Single** giving the new horizontal position. *Top*, *Width*, *Height* : *optional* New values for the corresponding properties. Omitted values are left unchanged. ### OLEDrag Initiates an OLE drag operation from the control, raising the [**OLEStartDrag**](#olestartdrag) event so the application can populate the **DataObject**. Syntax: *object*.**OLEDrag** ### Refresh Forces an immediate repaint of the control. Syntax: *object*.**Refresh** ### SetFocus Moves the input focus to the control. The control must be both [**Visible**](#visible) and [**Enabled**](#enabled), or run-time error 5 (*Invalid procedure call or argument*) is raised. Syntax: *object*.**SetFocus** ### ShowWhatsThis Displays the topic identified by [**WhatsThisHelpID**](#whatsthishelpid) as a "What's This?" pop-up. Syntax: *object*.**ShowWhatsThis** ### ZOrder Brings the control to the front or back of its sibling stack. Syntax: *object*.**ZOrder** \[ *Position* ] *Position* : *optional* A member of [**ZOrderConstants**](/en/official/Reference/VBRUN/Constants/ZOrderConstants): **vbBringToFront** (0, default) or **vbSendToBack** (1). ## Events ### Click Raised when [**Value**](#value) transitions from **False** to **True** --- whether the user clicked the selector, pressed the access key, or assigned **True** in code. Not raised on the form's first display, on a click that doesn't change the value, or when **Value** is set to **False**. **Default event.** Syntax: *object*\_**Click**( ) ### DblClick Raised when the user double-clicks the option button. The first click of the pair also raises [**Click**](#click) if it changes [**Value**](#value); the second is delivered here. Syntax: *object*\_**DblClick**( ) ### DragDrop Raised on the destination control when a manual drag operation ends over it. Syntax: *object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver Raised on the control under the cursor while a manual drag operation is in progress. Syntax: *object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus Raised when the control receives the input focus. Syntax: *object*\_**GotFocus**( ) ### Initialize Raised once, after the control's underlying window has been created and its design-time [**Value**](#value) has been applied. [**Click**](#click) does not fire until **Initialize** has run, so the design-time selection does not raise a spurious event. Syntax: *object*\_**Initialize**( ) ### KeyDown Raised when the user presses any key while the control has focus. Syntax: *object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress Raised when the user types a character that produces an ANSI keystroke. Syntax: *object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp Raised when the user releases a key while the control has focus. Syntax: *object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus Raised when the control loses the input focus. Syntax: *object*\_**LostFocus**( ) ### MouseDown Raised when the user presses any mouse button over the control. Syntax: *object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove Raised when the cursor moves over the control. Syntax: *object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp Raised when the user releases a mouse button over the control. Syntax: *object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag Raised on the source control when the OLE drag operation finishes, indicating which effect (copy, move, none) the destination accepted. Syntax: *object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop Raised on the destination control when the user drops data on it. Syntax: *object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver Raised on the destination control while an OLE drag passes over it. Syntax: *object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback Raised on the source control during a drag so the application can adjust the cursor or other visual feedback. Syntax: *object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData Raised on the source control when the destination requests data in a format that was registered but not yet supplied. Syntax: *object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag Raised on the source control at the start of an OLE drag, so the application can populate the **DataObject** and choose the allowed effects. Syntax: *object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Validate Raised when the focus is moving to another control whose [**CausesValidation**](#causesvalidation) is **True**. Setting *Cancel* to **True** keeps the focus on this control. Syntax: *object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /zh/official/Reference/VB/OptionButton.md --- # OptionButton 类 **OptionButton**是一个Win32原生控件,显示一个小的圆形选择器,后面可选文本标题,用于在一组相关选项中让用户进行单项选择。共享相同[**Container**](#container)的选项按钮形成*互斥组*:选中一个会自动清除同一容器中的其他选项按钮。 该控件通常在设计时放置在[**Form**](/official/Reference/VB/Form/)、[**Frame**](/official/Reference/VB/Frame/)或**UserControl**上。默认属性是[**Value**](#value),默认事件是[**Click**](#click)。 ```vb Private Sub Form_Load() optHTML.Caption = "&HTML" optMarkdown.Caption = "&Markdown" optPlain.Caption = "&Plain text" optHTML.Value = True ' default selection End Sub Private Sub optHTML_Click() Debug.Print "Output format: HTML" End Sub ``` ## 互斥行为 将一个选项按钮的[**Value**](#value)设置为**True**会清除[**Container**](#container)相同的所有其他选项按钮——通常是父窗体或[**Frame**](/official/Reference/VB/Frame/)。同级Frame中的选项按钮不受影响,因此单个窗体可以承载任意数量的独立组:将属于一个组的按钮放在一个Frame上,属于不同组的按钮放在另一个Frame上(或直接放在窗体上)。 ```vb ' 两个独立组在同一窗体上: ' fraSize: optSmall, optMedium, optLarge (fraSize的子控件) ' fraColour: optRed, optGreen, optBlue (fraColour的子控件) ``` 将[**Value**](#value)设置为**False**从不会取消选择其他按钮——没有自动*回退*到其他选项,因此应用程序通常通过在启动时将其中一个设置为**True**来保证每组中恰好有一个按钮被选中。将**False**赋值给当前选中的按钮会使该组无选中状态,直到用户(或代码)选择另一个。 ## Click语义 [**Click**](#click)仅在[**Value**](#value)从**False**转换为**True**时引发——无论用户点击了按钮、按了访问键还是在代码中赋值**True**。重新点击已选中的选项按钮不会产生效果,将**False**赋值给已选中的按钮*不会*引发[**Click**](#click)。该事件在窗体加载期间也不会引发;它在控件的[**Initialize**](#initialize)事件运行后开始引发。 ## 标题和助记符 选择器旁边(或当[**Alignment**](#alignment)为`tbRightJustify`时在选择器之前)显示的文本来自[**Caption**](#caption)。标题中的&符号将下一个字符标记为键盘助记符:按\*\*Alt+\*\*该字符可将焦点移到选项按钮并选中它。使用`&&`显示字面&符号。 ```vb optTerms.Caption = "I &agree to the terms" optTerms.Caption = "Use && in folder names" ' 显示为: Use & in folder names ``` ## 图形样式 当[**Style**](#style)为**vbButtonGraphical**时,选项按钮为所有者绘制模式,显示分配给[**Picture**](#picture)、[**DownPicture**](#downpicture)和[**DisabledPicture**](#disabledpicture)的位图,而非标准的圆形选择器。[**PictureAlignment**](#picturealignment)、[**Padding**](#padding)和[**PictureDpiScaling**](#picturedpiscaling)控制图片相对于标题的定位方式。 ## 属性 ### Alignment 指定[**Caption**](#caption)文本出现在选择器的哪一侧。 语法:*object*.**Alignment** \[ = *value* ] *value* : [**AlignmentConstantsNoCenter**](/official/Reference/VBRUN/Constants/AlignmentConstantsNoCenter)的成员:**tbLeftJustify** (0,默认——标题在选择器右侧)或**tbRightJustify** (1——标题在选择器左侧)。 ### Anchors 选项按钮的对应边缘跟随父控件调整大小时所依据的父控件边缘集合。只读——通过返回的**Anchors**对象分配单独的`.Left`、`.Top`、`.Right`、`.Bottom`标志。 ### Appearance 确定操作系统如何绘制控件的边框。[**AppearanceConstants**](/official/Reference/VBRUN/Constants/AppearanceConstants)的成员:**vbAppearFlat**或**vbAppear3d**(默认)。 ### BackColor 背景颜色,类型为**OLE\_COLOR**。默认为系统3D面色。 ### Caption 选项按钮旁边显示的文本。&符号标记下一个字符为助记符;`&&`产生字面&符号。字符串直接从底层窗口读取——赋值给**Caption**会立即反映。 语法:*object*.**Caption** \[ = *string* ] ### CausesValidation 确定先前获得焦点的控件的[**Validate**](#validate)事件是否在此控件获得焦点之前运行。**Boolean**,默认**True**。 ### Container 承载此选项按钮的控件——通常是[**Frame**](/official/Reference/VB/Frame/)或父窗体。使用**Get**读取,使用**Set**更改。在运行时设置**Container**会将选项按钮重新父级化到不同的组;它自动从旧组的互斥集合中排除并包含在新组中。 ### ControlType 只读的[**ControlTypeConstants**](/official/Reference/VBRUN/Constants/ControlTypeConstants)值,将此控件标识为选项按钮。始终为**vbOptionButton**。 ### DisabledPicture 当控件禁用且[**Style**](#style)为**vbButtonGraphical**时替代[**Picture**](#picture)绘制的**StdPicture**。 ### Dock 选项按钮在其容器中的停靠位置。[**DockModeConstants**](/official/Reference/VBRUN/Constants/DockModeConstants)的成员:**vbDockNone**(默认)、**vbDockLeft**、**vbDockTop**、**vbDockRight**、**vbDockBottom**或**vbDockFill**。停靠控件忽略[**Anchors**](#anchors)。 ### DownPicture 当[**Style**](#style)为**vbButtonGraphical**时,控件处于按下/选中状态时替代[**Picture**](#picture)绘制的**StdPicture**。 ### DragIcon 控件被拖放时用作鼠标光标的**StdPicture**(参见[**Drag**](#drag)和[**DragMode**](#dragmode))。 ### DragMode 控件是否应在用户按住鼠标时自动拖动。[**DragModeConstants**](/official/Reference/VBRUN/Constants/DragModeConstants)的成员:**vbManual** (0,默认——从代码调用[**Drag**](#drag))或**vbAutomatic** (1)。 ### Enabled 确定控件是否接受用户输入。禁用的选项按钮显示其当前值但变暗并忽略键盘和鼠标交互。**Boolean**,默认**True**。 ### Font 用于渲染[**Caption**](#caption)的**StdFont**。便捷属性**FontName**、**FontSize**、**FontBold**、**FontItalic**、**FontStrikethru**和**FontUnderline**读写此对象的相应成员。 ### ForeColor 标题的文本颜色,类型为**OLE\_COLOR**。默认为系统按钮文本色。 ### Height 控件的高度,默认以缇为单位(或使用容器的**ScaleMode**单位)。**Single**。 ### HelpContextID 标识应用程序帮助文件中主题的**Long**值,当用户在控件具有焦点时按**F1**时检索。 ### hWnd 底层按钮的Win32窗口句柄,类型为**LongPtr**。只读。可用于传递给API函数。 ### Index 当控件是控件数组的一部分时,此实例在数组中的从零开始的**Long**索引。在非数组实例上读取**Index**会引发运行时错误343(*Object not an array*)。运行时只读。 ### Left 从容器的左边缘到控件左边缘的水平距离。**Single**。 ### MaskColor ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: ### MouseIcon 当[**MousePointer**](#mousepointer)为**vbCustom**且指针位于控件上时用作鼠标光标的**StdPicture**。 ### MousePointer 指针位于控件上时显示的鼠标光标。[**MousePointerConstants**](/official/Reference/VBRUN/Constants/MousePointerConstants)的成员。 ### Name 控件在其父窗体上的唯一设计时名称。运行时只读。 ### OLEDropMode 控件如何响应OLE放置。[**OLEDropConstants**](/official/Reference/VBRUN/Constants/OLEDropConstants)的受限成员:**vbOLEDropNone**或**vbOLEDropManual**。OptionButton不支持自动放置模式。 ### Opacity 控件的不透明度百分比(0--100,默认100)。超出范围的值在**Initialize**时被钳制。子控件需要Windows 8或更高版本。 ### Padding 图片和标题之间(当[**PictureAlignment**](#picturealignment)为**vbAlignLeft**或**vbAlignRight**时)或标题与对应边缘之间(当**vbAlignTop**或**vbAlignBottom**时)插入的空白像素数。**Long**,默认2。仅在[**Style**](#style)为**vbButtonGraphical**时有意义。 ### Parent 对最终包含此控件的[**Form**](/official/Reference/VB/Form/)(或**UserControl**)的引用。只读。与[**Container**](#container)不同,后者返回直接父级——对于放置在[**Frame**](/official/Reference/VB/Frame/)内的选项按钮,**Container**返回Frame而**Parent**返回窗体。 ### Picture 当[**Style**](#style)为**vbButtonGraphical**时在控件上绘制的**StdPicture**。赋值**Nothing**恢复空图片而非移除位图表面。 ### PictureAlignment 当[**Style**](#style)为**vbButtonGraphical**时[**Picture**](#picture)相对于标题的定位方式。[**AlignConstants**](/official/Reference/VBRUN/Constants/AlignConstants)的成员:**vbAlignNone**、**vbAlignTop**(默认)、**vbAlignBottom**、**vbAlignLeft**、**vbAlignRight**。 ### PictureDpiScaling 当为**True**时,在绘制前按当前DPI因子缩放[**Picture**](#picture)、[**DownPicture**](#downpicture)和[**DisabledPicture**](#disabledpicture)。**Boolean**,默认**False**。 ### RightToLeft ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。使用[**Alignment**](#alignment)将标题翻转到选择器左侧。 ::: ### Style 在标准Win32选项按钮外观和所有者绘制图形按钮之间选择。[**ButtonConstants**](/official/Reference/VBRUN/Constants/ButtonConstants)的成员:**vbButtonStandard** (0,默认)或**vbButtonGraphical** (1)。在运行时更改**Style**会重新创建底层窗口。 ### TabIndex 控件在窗体TAB键导航顺序中的位置。**Long**。 ### TabStop 用户是否可以通过按**TAB**键到达控件。**Boolean**,默认**True**。TAB键导航也遵循选项按钮组约定:一旦焦点进入一个组,箭头键在组内成员之间移动焦点(和选择),而非在不相关的控件之间移动。禁用的控件无论此设置如何都会被跳过。 ### Tag 应用程序可用于将自定义数据与控件关联的自由格式**String**。框架忽略此属性。 ### ToolTipText 当用户将鼠标悬停在控件上时作为工具提示显示的多行**String**。 ### Top 从容器顶部到控件顶部的垂直距离。**Single**。 ### TransparencyKey 一个**OLE\_COLOR**值,设置后在渲染的控件中变为完全透明。默认`-1`禁用此效果。子控件需要Windows 8或更高版本。 ### UseMaskColor ::: info 保留用于与VB6兼容;目前在twinBASIC中未实现。 ::: ### Value 选项按钮的当前状态。**默认属性。** 语法:*object*.**Value** \[ = *value* ] *value* : **Boolean**:**True**表示选项按钮被选中,**False**表示被清除。 赋值**True**会清除同一[**Container**](#container)中的所有其他选项按钮并引发[**Click**](#click)。赋值**False**仅清除此按钮不影响其他按钮,且不引发[**Click**](#click)。赋值按钮已持有的值不会产生效果。 ### Visible 控件是否显示。**Boolean**,默认**True**。 ### VisualStyles 绘制控件时是否使用操作系统主题引擎。**Boolean**。 ### WhatsThisHelpID 标识应用程序帮助文件中"这是什么?"弹出帮助主题的**Long**值。参见[**ShowWhatsThis**](#showwhatsthis)。 ### Width 控件的宽度。**Single**。 ## 方法 ### Drag 开始、完成或取消手动拖放操作。通常在[**DragMode**](#dragmode)为**vbManual**时从[**MouseDown**](#mousedown)处理程序中调用。 语法:*object*.**Drag** \[ *Action* ] *Action* : *可选* [**DragConstants**](/official/Reference/VBRUN/Constants/DragConstants)的成员:**vbCancel** (0)、**vbBeginDrag** (1,默认)或**vbEndDrag** (2)。 ### Move 在单次调用中重新定位并可选地调整控件大小。 语法:*object*.**Move** *Left* \[, *Top* \[, *Width* \[, *Height* ] ] ] *Left* : *必需* 给出新水平位置的**Single**值。 *Top*、*Width*、*Height* : *可选* 对应属性的新值。省略的值保持不变。 ### OLEDrag 从控件发起OLE拖动操作,引发[**OLEStartDrag**](#olestartdrag)事件以便应用程序填充**DataObject**。 语法:*object*.**OLEDrag** ### Refresh 强制控件立即重绘。 语法:*object*.**Refresh** ### SetFocus 将输入焦点移至控件。控件必须同时[**Visible**](#visible)和[**Enabled**](#enabled),否则引发运行时错误5(*Invalid procedure call or argument*)。 语法:*object*.**SetFocus** ### ShowWhatsThis 以"这是什么?"弹出的方式显示由[**WhatsThisHelpID**](#whatsthishelpid)标识的主题。 语法:*object*.**ShowWhatsThis** ### ZOrder 将控件置于其同级堆栈的前面或后面。 语法:*object*.**ZOrder** \[ *Position* ] *Position* : *可选* [**ZOrderConstants**](/official/Reference/VBRUN/Constants/ZOrderConstants)的成员:**vbBringToFront** (0,默认)或**vbSendToBack** (1)。 ## 事件 ### Click 当[**Value**](#value)从**False**转换为**True**时引发——无论用户点击了选择器、按了访问键还是在代码中赋值**True**。在窗体首次显示时不引发、在不更改值的点击时不引发、或在**Value**设置为**False**时不引发。**默认事件。** 语法:*object*\_**Click**( ) ### DblClick 用户双击选项按钮时引发。配对的第一次点击如果更改了[**Value**](#value)也会引发[**Click**](#click);第二次点击在此处传递。 语法:*object*\_**DblClick**( ) ### DragDrop 手动拖动操作在目标控件上结束时在目标控件上引发。 语法:*object*\_**DragDrop**( *Source* **As Control**, *X* **As Single**, *Y* **As Single** ) ### DragOver 手动拖动操作进行中时在光标下方的控件上引发。 语法:*object*\_**DragOver**( *Source* **As Control**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### GotFocus 控件获得输入焦点时引发。 语法:*object*\_**GotFocus**( ) ### Initialize 在控件的底层窗口创建且其设计时[**Value**](#value)已应用后引发一次。[**Click**](#click)在**Initialize**运行前不会引发,因此设计时选择不会引发虚假事件。 语法:*object*\_**Initialize**( ) ### KeyDown 用户在控件具有焦点时按下任意键引发。 语法:*object*\_**KeyDown**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### KeyPress 用户键入产生ANSI击键的字符时引发。 语法:*object*\_**KeyPress**( *KeyAscii* **As Integer** ) ### KeyUp 用户在控件具有焦点时释放键引发。 语法:*object*\_**KeyUp**( *KeyCode* **As Integer**, *Shift* **As Integer** ) ### LostFocus 控件失去输入焦点时引发。 语法:*object*\_**LostFocus**( ) ### MouseDown 用户在控件上按下任意鼠标按钮时引发。 语法:*object*\_**MouseDown**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseMove 光标在控件上移动时引发。 语法:*object*\_**MouseMove**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### MouseUp 用户在控件上释放鼠标按钮时引发。 语法:*object*\_**MouseUp**( *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLECompleteDrag OLE拖动操作完成时在源控件上引发,指示目标接受了哪种效果(复制、移动、无)。 语法:*object*\_**OLECompleteDrag**( *Effect* **As Long** ) ### OLEDragDrop 用户将数据放置到目标控件上时在目标控件上引发。 语法:*object*\_**OLEDragDrop**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single** ) ### OLEDragOver OLE拖动经过目标控件时在目标控件上引发。 语法:*object*\_**OLEDragOver**( *Data* **As DataObject**, *Effect* **As Long**, *Button* **As Integer**, *Shift* **As Integer**, *X* **As Single**, *Y* **As Single**, *State* **As Integer** ) ### OLEGiveFeedback 拖动期间在源控件上引发,以便应用程序调整光标或其他视觉反馈。 语法:*object*\_**OLEGiveFeedback**( *Effect* **As Long**, *DefaultCursors* **As Boolean** ) ### OLESetData 当目标请求已注册但尚未提供的数据格式时在源控件上引发。 语法:*object*\_**OLESetData**( *Data* **As DataObject**, *DataFormat* **As Integer** ) ### OLEStartDrag OLE拖动开始时在源控件上引发,以便应用程序填充**DataObject**并选择允许的效果。 语法:*object*\_**OLEStartDrag**( *Data* **As DataObject**, *AllowedEffects* **As Long** ) ### Validate 焦点移动到另一个[**CausesValidation**](#causesvalidation)为**True**的控件时引发。将*Cancel*设置为**True**可使焦点保留在此控件上。 语法:*object*\_**Validate**( *Cancel* **As Boolean** ) --- --- url: /en/packages/vbccr/buttons/optionbuttonw.md description: >- OptionButtonW Control - VBCCR Development Manual, complete API reference based on source code --- # OptionButtonW Control Wraps the Windows system Button control, running in radio button style, with support for graphical style, owner-draw, image list, and visual styles. ## Enumerations ### OptImageListAlignmentConstants | Constant | Value | Description | |----------|-------|-------------| | OptImageListAlignmentLeft | 0 | Left alignment | | OptImageListAlignmentRight | 1 | Right alignment | | OptImageListAlignmentTop | 2 | Top alignment | | OptImageListAlignmentBottom | 3 | Bottom alignment | | OptImageListAlignmentCenter | 4 | Center alignment | ### OptDrawModeConstants | Constant | Value | Description | |----------|-------|-------------| | OptDrawModeNormal | 0 | Standard mode, drawn by the system | | OptDrawModeOwnerDraw | 1 | Owner-draw mode, drawing handled by code | ### CCAppearanceConstants See Common Enumerations. ### CCLeftRightAlignmentConstants See Common Enumerations. ### CCVerticalAlignmentConstants See Common Enumerations. ### CCMousePointerConstants See Common Enumerations. ### CCRightToLeftModeConstants See Common Enumerations. ### OLEDropModeConstants See Common Enumerations. ## Properties ### Value ```vb Property Get Value() As OLE_OPTEXCLUSIVE Property Let Value(ByVal NewValue As OLE_OPTEXCLUSIVE) ``` Selected state of the option button. True means selected. ### Caption ```vb Property Get Caption() As String Property Let Caption(ByVal Value As String) ``` Text caption displayed on the control. ### Alignment ```vb Property Get Alignment() As CCLeftRightAlignmentConstants Property Let Alignment(ByVal Value As CCLeftRightAlignmentConstants) ``` Alignment of the option button caption (left or right). See Common Enumerations. ### TextAlignment ```vb Property Get TextAlignment() As VBRUN.AlignmentConstants Property Let TextAlignment(ByVal Value As VBRUN.AlignmentConstants) ``` Alignment of the caption text (left, center, or right). ### PushLike ```vb Property Get PushLike() As Boolean Property Let PushLike(ByVal Value As Boolean) ``` Whether to make the control look and behave like a push button. ### Picture ```vb Property Get Picture() As IPictureDisp Property Let Picture(ByVal Value As IPictureDisp) Property Set Picture(ByVal Value As IPictureDisp) ``` Picture displayed on the control. ### WordWrap ```vb Property Get WordWrap() As Boolean Property Let WordWrap(ByVal Value As Boolean) ``` Whether to allow the caption text to wrap to prevent overflow. ### Transparent ```vb Property Get Transparent() As Boolean Property Let Transparent(ByVal Value As Boolean) ``` Whether to simulate a transparent background using a copy of the underlying background. This property is ignored at design time. ### VerticalAlignment ```vb Property Get VerticalAlignment() As CCVerticalAlignmentConstants Property Let VerticalAlignment(ByVal Value As CCVerticalAlignmentConstants) ``` Vertical alignment. See Common Enumerations. ### Style ```vb Property Get Style() As VBRUN.ButtonConstants Property Let Style(ByVal Value As VBRUN.ButtonConstants) ``` Control appearance style, standard or graphical. When DrawMode is not Normal, Style must be Standard. ### DisabledPicture ```vb Property Get DisabledPicture() As IPictureDisp Property Let DisabledPicture(ByVal Value As IPictureDisp) Property Set DisabledPicture(ByVal Value As IPictureDisp) ``` Picture displayed when the button is disabled. Only applicable when Style is graphical. ### DownPicture ```vb Property Get DownPicture() As IPictureDisp Property Let DownPicture(ByVal Value As IPictureDisp) Property Set DownPicture(ByVal Value As IPictureDisp) ``` Picture displayed when the button is pressed. Only applicable when Style is graphical. ### UseMaskColor ```vb Property Get UseMaskColor() As Boolean Property Let UseMaskColor(ByVal Value As Boolean) ``` Whether to use the MaskColor property as a transparent color. Only applicable when Style is graphical. ### MaskColor ```vb Property Get MaskColor() As OLE_COLOR Property Let MaskColor(ByVal Value As OLE_COLOR) ``` Color used as the transparent (mask) color in pictures. Only applicable when Style is graphical. ### DrawMode ```vb Property Get DrawMode() As OptDrawModeConstants Property Let DrawMode(ByVal Value As OptDrawModeConstants) ``` Draw mode, standard or owner-draw. ### ImageList ```vb Property Get ImageList() As Variant Property Let ImageList(ByVal Value As Variant) Property Set ImageList(ByVal Value As Variant) ``` Associated image list control. The image list should contain a single image (for all states) or separate images for each state. Requires comctl32.dll 6.0 or later. ### ImageListAlignment ```vb Property Get ImageListAlignment() As OptImageListAlignmentConstants Property Let ImageListAlignment(ByVal Value As OptImageListAlignmentConstants) ``` Alignment of images from the image list. Requires comctl32.dll 6.0 or later. ### ImageListMargin ```vb Property Get ImageListMargin() As Single Property Let ImageListMargin(ByVal Value As Single) ``` Margin for images from the image list. Requires comctl32.dll 6.0 or later. ### Pushed ```vb Property Get Pushed() As Boolean Property Let Pushed(ByVal Value As Boolean) ``` Whether the option button is in a pressed state. ### Hot ```vb Property Get Hot() As Boolean Property Let Hot(ByVal Value As Boolean) ``` Whether the option button is in a hot state (mouse hover). Read-only; writing raises error 383. Requires comctl32.dll 6.0 or later. ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` Whether to enable visual styles. Requires comctl32.dll 6.0 or later. ### Appearance ```vb Property Get Appearance() As CCAppearanceConstants Property Let Appearance(ByVal Value As CCAppearanceConstants) ``` Control appearance, flat or 3D effect. See Common Enumerations. ### BackColor ```vb Property Get BackColor() As OLE_COLOR Property Let BackColor(ByVal Value As OLE_COLOR) ``` Background color. ### ForeColor ```vb Property Get ForeColor() As OLE_COLOR Property Let ForeColor(ByVal Value As OLE_COLOR) ``` Foreground color. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### OLEDropMode ```vb Property Get OLEDropMode() As OLEDropModeConstants Property Let OLEDropMode(ByVal Value As OLEDropModeConstants) ``` OLE drag-drop target mode. See Common Enumerations. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` Mouse pointer style. See Common Enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` Custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Whether to enable mouse enter/leave tracking. ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` Right-to-left display direction. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` Right-to-left mode. See Common Enumerations. ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` Font. ### hWnd ```vb Property Get hWnd() As LongPtr ``` Window handle of the option button control. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Window handle of the UserControl. ### Name ```vb Property Get Name() As String ``` Control name. Read-only. ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` Custom data. ### Parent ```vb Property Get Parent() As Object ``` Parent object. Read-only. ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` Container object. ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` Left position. ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` Top position. ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` Width. ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` Height. ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` Whether the control is visible. ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` Tooltip text. ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` Help context ID. ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "What's This" help ID. ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` Drag icon. ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` Drag mode. ## Methods ### Drag ```vb Public Sub Drag([ByRef Action As Variant]) ``` Starts, ends, or cancels a drag operation. ### SetFocus ```vb Public Sub SetFocus() ``` Moves focus to the control. ### ZOrder ```vb Public Sub ZOrder([ByRef Position As Variant]) ``` Sets the Z-order of the control. ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag-drop operation. ### Refresh ```vb Public Sub Refresh() ``` Forces the control to repaint. ## Events ### Click ```vb Public Event Click() ``` Fired when a mouse button is pressed and released on the control. ### DblClick ```vb Public Event DblClick() ``` Fired when the mouse is double-clicked on the control. ### HotChanged ```vb Public Event HotChanged() ``` Fired when the hot state of the option button changes. Requires comctl32.dll 6.0 or later. ### OwnerDraw ```vb Public Event OwnerDraw(ByVal Action As Long, ByVal State As Long, ByVal hDC As Long, ByVal Left As Long, ByVal Top As Long, ByVal Right As Long, ByVal Bottom As Long) ``` Fired when a visual aspect of the owner-draw button needs to be drawn. ### PreviewKeyDown ```vb Public Event PreviewKeyDown(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Fired before the KeyDown event. ### PreviewKeyUp ```vb Public Event PreviewKeyUp(ByVal KeyCode As Integer, ByRef IsInputKey As Boolean) ``` Fired before the KeyUp event. ### KeyDown ```vb Public Event KeyDown(KeyCode As Integer, Shift As Integer) ``` Fired when a key is pressed. ### KeyUp ```vb Public Event KeyUp(KeyCode As Integer, Shift As Integer) ``` Fired when a key is released. ### KeyPress ```vb Public Event KeyPress(KeyChar As Integer) ``` Fired when a key character is input. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when a mouse button is pressed. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when the mouse is moved. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when a mouse button is released. ### MouseEnter ```vb Public Event MouseEnter() ``` Fired when the mouse enters the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Fired when the mouse leaves the control. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` Fired after an OLE drag-drop operation is completed or cancelled. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Fired when data is dropped on the control via an OLE drag-drop operation. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` Fired when the mouse moves over the control during an OLE drag-drop operation. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` Fired when the mouse cursor needs to be changed during an OLE drag-drop operation. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` Fired when the drop target requests data not provided during OLEDragStart. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` Fired when an OLE drag-drop operation starts. ## Code Examples ```vb ' Basic option button OptionButtonW1.Caption = "Option A" OptionButtonW1.Value = True ' Graphical style OptionButtonW1.Style = vbButtonGraphical Set OptionButtonW1.Picture = LoadPicture("C:\icon.bmp") Set OptionButtonW1.DownPicture = LoadPicture("C:\icon_down.bmp") ' Push-like option button OptionButtonW1.PushLike = True ' Using image list Set OptionButtonW1.ImageList = ImageList1 OptionButtonW1.ImageListAlignment = OptImageListAlignmentLeft OptionButtonW1.ImageListMargin = 4 ' Owner draw OptionButtonW1.DrawMode = OptDrawModeOwnerDraw ``` --- --- url: /en/official/Reference/Core/Or.md --- # Or operator Used to perform a bitwise disjunction on two expressions. Syntax: > *result* **=** *expression1* **Or** *expression2* *result* : Any numeric variable. *expression1*, *expression2* : Any expressions. If either or both expressions evaluate to **True**, *result* is **True**. The following table illustrates how *result* is determined: | If *expression1* is | And *expression2* is | Then *result* is | |:-----|:-----|:-----| | **True** | **True** | **True** | | **True** | **False** | **True** | | **True** | **Null** | **True** | | **False** | **True** | **True** | | **False** | **False** | **False** | | **False** | **Null** | **Null** | | **Null** | **True** | **True** | | **Null** | **False** | **Null** | | **Null** | **Null** | **Null** | The **Or** operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in *result* according to the following table: | If bit in *expression1* is | And bit in *expression2* is | Then *result* is | |:-----:|:-----:|:-----:| | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 1 | ::: info **Or** evaluates *both* operands every time, even when *expression1* alone determines the result. Use [**OrElse**](/en/official/Reference/Core/OrElse) for short-circuit evaluation --- for example, when *expression2* is expensive, has side effects, or only matters when *expression1* is **False**. ::: ### Example This example uses the **Or** operator to perform logical disjunction on two expressions. ```vb Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B Or B > C ' Returns True. MyCheck = B > A Or B > C ' Returns True. MyCheck = A > B Or B > D ' Returns True. MyCheck = B > D Or B > A ' Returns Null. MyCheck = A Or B ' Returns 10 (bitwise comparison). ``` ### See Also * [**OrElse** operator](/en/official/Reference/Core/OrElse) * [**And** operator](/en/official/Reference/Core/And) * [**Not** operator](/en/official/Reference/Core/Not) * [**Xor** operator](/en/official/Reference/Core/Xor) * [**Eqv** operator](/en/official/Reference/Core/Eqv) * [**Imp** operator](/en/official/Reference/Core/Imp) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/Or.md --- # Or 运算符 用于对两个表达式执行按位析取。 语法: > *result* **=** *expression1* **Or** *expression2* *result* : 任意数值变量。 *expression1*, *expression2* : 任意表达式。 如果一个或两个表达式的计算结果为**True**,则*result*为**True**。下表说明*result*的确定方式: | 如果 *expression1* 为 | 且 *expression2* 为 | 则 *result* 为 | |:-----|:-----|:-----| | **True** | **True** | **True** | | **True** | **False** | **True** | | **True** | **Null** | **True** | | **False** | **True** | **True** | | **False** | **False** | **False** | | **False** | **Null** | **Null** | | **Null** | **True** | **True** | | **Null** | **False** | **Null** | | **Null** | **Null** | **Null** | **Or**运算符对两个数值表达式中相同位置的位执行按位比较,并根据下表设置*result*中的相应位: | 如果 *expression1* 中的位为 | 且 *expression2* 中的位为 | 则 *result* 为 | |:-----:|:-----:|:-----:| | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 1 | ::: info **Or**每次都会计算*两个*操作数,即使仅*expression1*就能确定结果。使用[**OrElse**](/official/Reference/Core/OrElse)进行短路求值——例如,当*expression2*计算开销大、有副作用,或仅当*expression1*为**False**时才有意义。 ::: ### 示例 本示例使用**Or**运算符对两个表达式执行逻辑析取。 ```vb Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B Or B > C ' Returns True. MyCheck = B > A Or B > C ' Returns True. MyCheck = A > B Or B > D ' Returns True. MyCheck = B > D Or B > A ' Returns Null. MyCheck = A Or B ' Returns 10 (bitwise comparison). ``` ### 另请参阅 * [**OrElse** 运算符](/official/Reference/Core/OrElse) * [**And** 运算符](/official/Reference/Core/And) * [**Not** 运算符](/official/Reference/Core/Not) * [**Xor** 运算符](/official/Reference/Core/Xor) * [**Eqv** 运算符](/official/Reference/Core/Eqv) * [**Imp** 运算符](/official/Reference/Core/Imp) * [运算符](/official/Reference/Operators) --- --- url: /en/official/Reference/Core/OrElse.md --- # OrElse operator Performs a short-circuit logical disjunction of two **Boolean** expressions. If the left operand evaluates to **True**, the right operand is not evaluated. ::: info **OrElse** is a twinBASIC extension. The classic [**Or**](/en/official/Reference/Core/Or) operator always evaluates both operands and returns a bitwise result; **OrElse** evaluates the right operand only when needed and always returns a **Boolean**. ::: Syntax: > *result* **=** *expression1* **OrElse** *expression2* *result* : A **Boolean** variable. *expression1*, *expression2* : Any expressions that evaluate to **Boolean** (or are coercible to **Boolean**). If *expression1* is **True**, *result* is **True** and *expression2* is not evaluated. Otherwise *expression2* is evaluated and its **Boolean** value becomes *result*. This is the standard "short-circuit OR". It is useful when *expression2* is more expensive to evaluate, or when *expression2* would fail or have unwanted side effects in the case where *expression1* is already **True**. ### Example Skipping an expensive lookup when a cheaper test already proves the condition: ```vb If IsCached(key) OrElse FetchFromDisk(key) Then ' FetchFromDisk is only called when IsCached returned False. Process key End If ``` Compare with the equivalent code using **Or**, which would always call `FetchFromDisk` even when the cached lookup already succeeded: ```vb ' Inefficient - FetchFromDisk runs even when IsCached returned True. If IsCached(key) Or FetchFromDisk(key) Then Process key End If ``` ### See Also * [**AndAlso** operator](/en/official/Reference/Core/AndAlso) * [**Or** operator](/en/official/Reference/Core/Or) * [Operators](/en/official/Reference/Operators) --- --- url: /zh/official/Reference/Core/OrElse.md --- # OrElse 运算符 对两个**Boolean**表达式执行短路逻辑析取。如果左操作数的计算结果为**True**,则不计算右操作数。 ::: info **OrElse**是twinBASIC扩展。经典的[**Or**](/official/Reference/Core/Or)运算符总是计算两个操作数并返回按位结果;**OrElse**仅在需要时计算右操作数,且始终返回**Boolean**。 ::: 语法: > *result* **=** *expression1* **OrElse** *expression2* *result* : **Boolean**变量。 *expression1*, *expression2* : 计算结果为**Boolean**(或可强制转换为**Boolean**)的任意表达式。 如果*expression1*为**True**,则*result*为**True**且不计算*expression2*。否则计算*expression2*,其**Boolean**值成为*result*。 这是标准的"短路OR"。当*expression2*计算开销大,或当*expression1*已经为**True**时*expression2*会失败或产生不需要的副作用时,此运算符非常有用。 ### 示例 当较简单的测试已经证明条件时,跳过开销大的查找: ```vb If IsCached(key) OrElse FetchFromDisk(key) Then ' FetchFromDisk is only called when IsCached returned False. Process key End If ``` 与使用**Or**的等效代码比较,后者即使缓存查找已成功也会始终调用`FetchFromDisk`: ```vb ' Inefficient - FetchFromDisk runs even when IsCached returned True. If IsCached(key) Or FetchFromDisk(key) Then Process key End If ``` ### 另请参阅 * [**AndAlso** 运算符](/official/Reference/Core/AndAlso) * [**Or** 运算符](/official/Reference/Core/Or) * [运算符](/official/Reference/Operators) --- --- url: >- /en/official/Reference/WinNativeCommonCtls/Enumerations/OrientationConstants.md --- # OrientationConstants The horizontal / vertical enumeration shared by [**Slider.Orientation**](/en/official/Reference/WinNativeCommonCtls/Slider#orientation) and [**UpDown.Orientation**](/en/official/Reference/WinNativeCommonCtls/UpDown#orientation). | Member | Value | Description | |---------------------------------|-------|-----------------------| | **ccOrientationHorizontal** | 0 | Horizontal orientation. | | **ccOrientationVertical** | 1 | Vertical orientation. | ## See Also * [Slider](/en/official/Reference/WinNativeCommonCtls/Slider) -- consumer * [UpDown](/en/official/Reference/WinNativeCommonCtls/UpDown) -- consumer --- --- url: >- /zh/official/Reference/WinNativeCommonCtls/Enumerations/OrientationConstants.md --- # OrientationConstants 由 [**Slider.Orientation**](/official/Reference/WinNativeCommonCtls/Slider#orientation) 和 [**UpDown.Orientation**](/official/Reference/WinNativeCommonCtls/UpDown#orientation) 共享的水平/垂直枚举。 | 成员 | 值 | 描述 | |---------------------------------|-------|-----------------------| | **ccOrientationHorizontal** | 0 | 水平方向。 | | **ccOrientationVertical** | 1 | 垂直方向。 | ## 另见 * [Slider](/official/Reference/WinNativeCommonCtls/Slider) —— 使用者 * [UpDown](/official/Reference/WinNativeCommonCtls/UpDown) —— 使用者 --- --- url: /en/official/IDE/Outline.md --- # Outline The Outline pane shows a structural overview of the declarations in the active source file---modules, classes, procedures, and properties. When a project isn't open this will be empty. ![Outline](Images/Outline.png "Outline") Once you open a project it will list the `Modules`/`Classes` etc. ![Outline](Images/Outline_1.png "Outline") You can click on an item to navigate to that point in the code file. --- --- url: /en/official/Features/Language/Overloading.md --- # Overloading twinBASIC supports overloading in two ways: ## Overloading by Type of Argument The following Subs are valid together in a module/class/etc: ```vb Sub foo(bar As Integer) '... End Sub Sub foo(bar As Long) '... End Sub Sub foo(bar As Double) '... End Sub ``` The compiler will automatically pick which one is called by the data type. ## Overloading by Number of Arguments In addition to the above, you could also add the following: ```vb Sub Foo(bar1 As Integer) '... End Sub Sub Foo(bar1 As Integer, bar2 As Integer) '... End Sub ``` The compiler will automatically pick which one is called by the number and/or types of arguments. --- --- url: /en/official/Features/Packages.md --- # Package Management In twinBASIC, a *package* is a collection of components that you can reference from another twinBASIC project. The components can be modules, classes or interfaces. twinBASIC comes complete with a package manager service called TWINSERV\[^1], allowing you to share and distribute TWINPACK packages to other twinBASIC developers. A twinBASIC package is distributed as a TWINPACK file that contains everything needed by the components in that package. A project that references a TWINPACK package, imports the whole package into the file system of the root project, resulting in no external dependencies. With TWINPACK packages you group common components together into their own namespace whilst allowing for convenient code reuse without any of the problems often associated with using external DLL libraries. Please be aware that TWINPACK files currently contain the full source code of your packaged components. It is planned that we will in future allow for creating binary (compiled) TWINPACK files for developers that hold an Ultimate edition licence of twinBASIC. ## Topics * [Creating a TWINPACK Package](/en/official/Features/Packages/Creating-a-TWINPACK-package) -- packaging twinBASIC components into a distributable TWINPACK file. * [Importing a Package from TWINSERV](/en/official/Features/Packages/Importing-a-package-from-TWINSERV) -- browsing and installing packages from the TWINSERV online repository. * [Importing a Package from a TWINPACK File](/en/official/Features/Packages/Importing-a-package-from-a-TWINPACK-file) -- installing a package from a local TWINPACK file. * [Linked Packages](/en/official/Features/Packages/Linked-Packages) -- storing a package in a shared location rather than embedding it in each project file. * [Updating a Package](/en/official/Features/Packages/Updating-a-package) -- removing an outdated package and installing a newer version from TWINSERV. \[^1]: A service of TWINBASIC LTD offered to the user community. --- --- url: /en/official/IDE/Package-Publishing.md --- # Package Publishing The Package Publishing pane manages the metadata for the current project when it is published as a twinBASIC package, including the package name, version, and description. When a project isn't open this will be empty. ![Package Publishing](/assets/PackagePublishing.cttvMIko.png "Package Publishing") Once you open a project you will be able to edit the properties. ![Package Publishing](/assets/PackagePublishing_1.BNXsYHtO.png "Package Publishing") Click the "EDIT" and this will open the [Project Settings](/en/official/IDE/Project-Settings) --- --- url: /en/official/Features/Compiler-IDE/Package-Server.md --- # Package Server Code can be grouped as a package, and published to an online server. You can have Private packages, visible only to you, or Public packages, visible to everyone. ![image](/assets/5951dab6-738e-4b63-83c4-3331ec6d36b9.CgLJrXeN.png) For more information, see the following pages: * [What is a package](/en/official/Features/Packages/) * [Creating a TWINPACK package](/en/official/Features/Packages/Creating-a-TWINPACK-package) * [Importing a package from a TWINPACK file](/en/official/Features/Packages/Importing-a-package-from-a-TWINPACK-file) * [Importing a package from TWINSERV](/en/official/Features/Packages/Importing-a-package-from-TWINSERV) * [Updating a package](/en/official/Features/Packages/Updating-a-package) --- --- url: /en/official/Reference/Packages.md --- # Packages A *package* groups related code --- modules, classes, controls, and enumerations --- under a single namespace, and is referenced from a project as a single dependency. See [Features → Packages](/en/official/Features/Packages/) for how packages are built and distributed in general; the pages below document the *built-in* packages that ship with twinBASIC itself. ## Default Packages These packages are included in every project by default. * [VB Package](/en/official/Reference/VB/) -- standard controls (**CheckBox**, **CommandButton**, **TextBox**, …), forms, and the application-level singletons (**App**, **Screen**, **Clipboard**, **Printer**, …) * [VBA Package](/en/official/Reference/VBA/) -- the standard runtime library -- **MsgBox**, **CStr**, **Mid**, **Format**, … grouped into modules, plus the **Collection** and **Err** intrinsics and twinBASIC's runtime expression engine * [VBRUN Package](/en/official/Reference/VBRUN/) -- runtime-only types -- ambient properties, asynchronous-read state, structured error context, the **PropertyBag**, the clipboard / drag-and-drop container, and the enumerations used by classic VB6 forms and controls ## Built-In Packages These packages are built into twinBASIC and are always available, even offline. To use them, add them to Project → References (Ctrl-T) → Available Packages. * [Assert Package](/en/official/Reference/Assert/) -- assertion functions for unit tests -- three modules (**Exact**, **Strict**, **Permissive**) sharing the same fifteen-member API with different comparison strictness * [CustomControls Package](/en/official/Reference/CustomControls/) -- owner-drawn `Waynes…` custom controls (button, form, frame, grid, label, slider, textbox, timer), the shared `Styles/` helpers that paint them, and the DESIGNER framework (interfaces, callback objects, **Canvas**, **SerializeInfo**) for authoring new custom controls * [CEF Package](/en/official/Reference/CEF/) -- the **CefBrowser** control wrapping the Chromium Embedded Framework: cross-platform-ready browser embedding with a choice of three Chromium runtimes (v49 / v109 / v145); currently in BETA * [WebView2 Package](/en/official/Reference/WebView2/) -- the **WebView2** control wrapping the Microsoft Edge runtime, plus its surrounding wrapper objects (request / response / headers / environment options) and the `wv2…` enumerations * [WinEventLogLib Package](/en/official/Reference/WinEventLogLib/) -- writes Windows Event Log entries from twinBASIC; the generic **EventLog**(*Of EventIds, Categories*) class handles registration, registry setup, and the per-event `ReportEventW` call, with message-table resources for *EventIds* and *Categories* synthesised into the EXE at compile time * [WinNamedPipesLib Package](/en/official/Reference/WinNamedPipesLib/) -- Windows named pipes as twinBASIC objects with an asynchronous IOCP-driven I/O model; **NamedPipeServer** + **NamedPipeServerConnection** on the host side, **NamedPipeClientManager** + **NamedPipeClientConnection** on the client side, with message-boundary semantics and a cookie-based correlation pattern across `AsyncRead` / `AsyncWrite` and their matching events * [WinServicesLib Package](/en/official/Reference/WinServicesLib/) -- runs a twinBASIC EXE as one or more Windows services; the **Services** singleton coordinates configuration, install / uninstall, and the SCM dispatcher loop, while user-implemented [**ITbService**](/en/official/Reference/WinServicesLib/ITbService) classes are instantiated through [**ServiceCreator**](/en/official/Reference/WinServicesLib/ServiceCreator)`(Of T)` * [tbIDE Package](/en/official/Reference/tbIDE/) -- the **addin SDK** for the twinBASIC IDE: every addin is a Standard DLL that exports `tbCreateCompilerAddin`, returns an object implementing the [**AddIn**](/en/official/Reference/tbIDE/AddIn) contract, and from there reaches the IDE's toolbar, tool-window DOM, virtual file system, debug console, current project (and its `Evaluate` debug-console hook), keyboard shortcuts, and themes -- all through the [**Host**](/en/official/Reference/tbIDE/Host) object the IDE passes in * [WinNativeCommonCtls Package](/en/official/Reference/WinNativeCommonCtls/) -- VB6-compatible replacement for **Microsoft Common Controls 6.0** (`MSCOMCTL.OCX`) built on top of the Win32 ComCtl32 controls: eight controls ([**DTPicker**](/en/official/Reference/WinNativeCommonCtls/DTPicker), [**ImageList**](/en/official/Reference/WinNativeCommonCtls/ImageList/), [**ListView**](/en/official/Reference/WinNativeCommonCtls/ListView/), [**MonthView**](/en/official/Reference/WinNativeCommonCtls/MonthView), [**ProgressBar**](/en/official/Reference/WinNativeCommonCtls/ProgressBar), [**Slider**](/en/official/Reference/WinNativeCommonCtls/Slider), [**TreeView**](/en/official/Reference/WinNativeCommonCtls/TreeView/), [**UpDown**](/en/official/Reference/WinNativeCommonCtls/UpDown)) with the original member names preserved, plus the collection sub-objects ([**ListItems**](/en/official/Reference/WinNativeCommonCtls/ListView/ListItems), [**ColumnHeaders**](/en/official/Reference/WinNativeCommonCtls/ListView/ColumnHeaders), [**Nodes**](/en/official/Reference/WinNativeCommonCtls/TreeView/Nodes), [**ListImages**](/en/official/Reference/WinNativeCommonCtls/ImageList/ListImages)) and the user-facing enumerations --- --- url: /en/official/Reference/CustomControls/Styles/Padding.md --- # Padding class Per-side padding, in pixels, applied around the text inside a [**TextRendering**](/en/official/Reference/CustomControls/Styles/TextRendering). Accessed as [**TextRendering.Padding**](/en/official/Reference/CustomControls/Styles/TextRendering#padding). The padded region is what the text [**Alignment**](/en/official/Reference/CustomControls/Styles/TextRendering#alignment) is applied to --- adding 5 pixels of left padding moves left-aligned text 5 pixels to the right, and shrinks the available area by 5 pixels at the left edge. ```vb With txtNotes.NormalState.TextRendering.Padding .Left = 5 .Right = 5 End With ``` ## Properties ### Bottom Padding inserted at the bottom edge, in pixels. [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount). Default: 0. ### Left Padding inserted at the left edge, in pixels. [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount). Default: 0. ### Right Padding inserted at the right edge, in pixels. [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount). Default: 0. ### Top Padding inserted at the top edge, in pixels. [**PixelCount**](/en/official/Reference/CustomControls/Enumerations/PixelCount). Default: 0. ## Events ### OnChanged Raised whenever any of the four padding values is assigned. The containing [**TextRendering**](/en/official/Reference/CustomControls/Styles/TextRendering) re-raises its own **OnChanged** in response, which in turn triggers a repaint on the hosting control. --- --- url: /zh/official/Reference/CustomControls/Styles/Padding.md --- # Padding 类 逐侧内边距(像素),应用于 [**TextRendering**](/official/Reference/CustomControls/Styles/TextRendering) 内文本周围。通过 [**TextRendering.Padding**](/official/Reference/CustomControls/Styles/TextRendering#padding) 访问。带内边距的区域是文本 [**Alignment**](/official/Reference/CustomControls/Styles/TextRendering#alignment) 应用的对象——添加 5 像素左侧内边距将左对齐文本向右移动 5 像素,并在左边缘缩小可用区域 5 像素。 ```vb With txtNotes.NormalState.TextRendering.Padding .Left = 5 .Right = 5 End With ``` ## 属性 ### Bottom 底边插入的内边距(像素)。[**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount)。默认:0。 ### Left 左边插入的内边距(像素)。[**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount)。默认:0。 ### Right 右边插入的内边距(像素)。[**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount)。默认:0。 ### Top 顶边插入的内边距(像素)。[**PixelCount**](/official/Reference/CustomControls/Enumerations/PixelCount)。默认:0。 ## 事件 ### OnChanged 四个内边距值中任一个被赋值时触发。包含的 [**TextRendering**](/official/Reference/CustomControls/Styles/TextRendering) 随之重新触发自身的 **OnChanged**,进而触发承载控件的重绘。 --- --- url: /zh/official/Documentation/Fixes-PagedJS.md --- # Paged.js 补丁 `book/lib/paged.browser.js` 是 paged.js v0.4.3(MIT)的内置修补副本。上游 paged.js 为交互式浏览器设计:它让出事件循环以在长时间渲染期间保持页面响应,全程使用异步函数,并注册观察和调整大小回调。这些在无头、非交互式 Chromium 进程中都无用,唯一的目标是尽快生成 PDF。本页记录了每个补丁及其原理。 ## 同步执行链 **问题。** 上游 paged.js 由 `async function` 链构建。核心让出机制是 `waitForTick()`,在核心 `*layout` 生成器内每 100 个布局对象调用一次。在 1651 页的书籍上,这增加了数千次强制事件循环轮转。除 `waitForTick()` 外,异步机制本身 --- 每个函数编译为 tslib `__awaiter` + `__generator` 状态机 --- 即使在从不实际让出的路径上也为每次调用分配一个 Promise。 在无头 Chromium 中,事件循环不与任何面向用户的交互共享;让出只会增加延迟而无任何好处。`preview()` 返回 Promise 也使每页钩子架构复杂化:意外异步的处理程序可能让其可等待的工作被静默丢弃。 **修复。** 十四个方法被重写为同步等效方法,整个文件中标记为 `[PATCH: sync-chain]`。 | 方法 | 变更 | |---|---| | `*layout()` | 同步生成器;`renderer.next()` 同步返回。 | | `render()` | 普通同步;不再有每页异步状态机。 | | `renderTo()` | 移除 `async`;`renderTo` 同步返回。 | | `layout()` | 移除 `async`;同步调用 `renderTo` 和 `handleBreaks`。 | | `handleBreaks()` | 不再等待钩子触发;`Hook.trigger()` 在全同步路径上返回 `undefined`。 | | `flow()` | 移除所有五个 `await` 站点;`beforeParsed`/`afterParsed`/`afterRendered` 钩子同步调用并由 `_assertSync` 保护。 | | `renderOnIdle()` / `renderAsync()` | 完全移除;两者都在不必要的异步机制中包裹 `renderer.next()`。 | | `clonePage()` | 移除 `async`;仅通过 `Footnotes` 处理程序可达,当文档没有脚注时该处理程序自禁用。 | | `loadFonts()` | 重写为同步断言。`render-book.mjs` 中的 `waitUntil: "load"` 保证在 paged.js 运行前每个 `FontFace` 已加载。 | | `parse()` | 移除 `async`;此管线中为其触发的钩子注册的处理程序没有异步的。 | | `request()` | 替换为同步 XHR(`XMLHttpRequest` 且 `async=false`),直接返回 `responseText`。 | | `add()` | 移除 `async`;所有输入都是行内 `{url: text}` 对象,无需获取。 | | `convertViaSheet()` | 移除 `async`;`request()` 现在直接返回文本。 | 在每个接收 `Hook.trigger()` 同步哨兵值的调用站点添加了保护函数 `_assertSync(triggerResult, hookName)`。如果处理程序返回 thenable,`_assertSync` 立即抛出包含钩子名称的异常,而非静默丢弃异步工作。 ::: info `render-book.mjs` 中的 `await page.evaluate(...)` 是 puppeteer 对 CDP 往返的要求,而非 `preview()` 在 Chromium 内部是异步的标志。`await` 仅在 Chromium 的同步执行完成且 CDP 响应返回到 Node 后才解析。 ::: ## 钩子分发快速路径 **问题。** `Hook.trigger()` 总是返回 `Promise.all(promises)`,将每个同步处理程序结果包裹在 `new Promise(resolve => resolve(...))` 中。调用者总是等待结果,即使没有异步处理程序也支付微任务边界。`Hook.triggerSync()`(用于每页钩子的同步变体)总是分配结果数组并对其调用 `.forEach`,即使 `this.hooks` 为空。此管线中 `onOverflow` 和 `onBreakToken` 钩子注册了零个处理程序;`triggerSync` 每次渲染被调用约 3300 次纯属分发开销。 **修复。** `[PATCH: hook-fast-path]` 当所有处理程序完成且未返回 thenable 时,`trigger()` 返回 `undefined`(同步哨兵)而非已解析的 Promise。调用者被重写为: ```js let p = hook.trigger(...); if (p) await p; ``` `[PATCH: hook-fast-path-sync]` 当 `this.hooks` 为空时,`triggerSync()` 立即返回 `undefined`,跳过数组分配和 `.forEach`。 在每个现在接收同步哨兵值的调用站点,`_assertSync(result, hookName)` 在结果为 thenable 时抛出,将静默正确性风险转化为可诊断的错误。 ## DOM 元素查找 ### indexOfRefs 字典 **问题。** `findElement(ref, root)` 通过其 `data-ref` 属性查找元素。当 `indexOfRefs` 快速路径字典未填充时,它回退到 `root.querySelector("[data-ref='X']")`,扫描整个 `root` 子树。在 1651 页的书籍上,仅 `createBreakToken` 内的 848 + 42 次此类扫描就占用了超过一秒的渲染时间。 **修复。** `[PATCH: findRef fast-path]` 在 `addRefs()` 遍历期间,每个具有 `data-ref` 属性的元素被记录到 `root.indexOfRefs` 中。后续的 `findElement` 调用命中字典并完全跳过 `querySelector` 扫描。 ### 片段合并 **问题。** 当 `append()` 重建祖先并通过 `dest.appendChild(fragment)` 插入时,重建节点的 `data-ref` 映射未被带入 `dest.indexOfRefs`。后续的 `findElement(rebuiltAncestor, dest)` 调用未命中字典并回退到 `querySelector`。 **修复。** `[PATCH: findRef fast-path]` 在 `dest.appendChild(fragment)` 之后,`fragment.indexOfRefs` 在单次遍历中合并到 `dest.indexOfRefs`。 ### 源 indexOfRefs 表示 **问题。** 源内容的 `indexOfRefs` 是普通 JavaScript 对象(`{}`)。当键计数很大时,V8 将此类对象表示为哈希映射:每条目约 40-50 字节。键是转换为顺序整数的十进制字符串 UUID 计数器。 **修复。** `[PATCH: source-indexOfRefs-array]` 源 `indexOfRefs` 现在是普通 `Array`。V8 将其存储为 `PACKED_ELEMENTS`(密集数组模式):每槽约 8 字节。`[PATCH: source-indexOfRefs-presize]` 数组在遍历前从 `HTMLCollection.length` 预设大小,消除遍历期间的几何增长后备存储重新分配。 ## 父节点查找缓存 **问题。** `append()` 的内层循环通过调用 `findElement(srcParent, dest)` 为每个源节点解析目标父节点(`destParent`)。源树中的连续兄弟共享相同的 `srcParent`;每个兄弟独立调用 `findElement`。 **修复。** `[PATCH: parent-lookup-cache]` `Layout` 实例上的单条备忘存储最后的 `(srcParent, dest) → destParent` 解析。连续兄弟命中缓存并跳过字典查找。备忘在每次 `renderTo` 调用开始时失效,因为 `removeOverflow` 可能在两次调用之间分离了缓存的 `destParent`。 ## data-ref 属性缓存 **问题。** `element.dataset.ref` 内部调用 `getAttribute` 并在每次访问时分配新的 JS 字符串。`addRefs` 遍历和 `append()` 各读取同一属性值两次:一次用于存在检查,一次用于 `indexOfRefs` 写入。 **修复。** `[PATCH: addRefs-uuid-local]` / `[PATCH: append-ref-local]` 通过 `getAttribute` 将属性读取一次到局部变量并在两个操作中复用。这在 `addRefs` 遍历中每个元素和每次 append 调用中各保存一次字符串分配 --- 书籍上约 50,000 次调用,按 A/B 采样对测量约 1.5 MB 堆减少。 ## 渲染队列调度器 **问题。** 内部渲染队列使用 `requestAnimationFrame` 作为其每任务节拍。在无头 puppeteer 渲染中,`rAF` 即使没有可视输出和交互也仍等待下一个合成器帧。在 1651 页的书籍上,每页队列迭代累积了约 700 ms 的 V8 空闲时间来自 `rAF` 延迟回调。 **修复。** `[PATCH: queue-tick]` 每任务回调使用 `queueMicrotask` 而非 `requestAnimationFrame` 调度。它在微任务检查点触发而非等待合成器帧。 ## 页面布局正确性 ### maxChars 冻结 **问题。** 上游以 `!settings.maxChars` 为门控条件来决定是否更新每页 `maxChars` 估计值。在第一次带非空页面的遍历中,`settings.maxChars` 被设置,门控阻止了任何后续更新。对于开头页面较短的书籍(标题页、部分分隔),估计永久偏小,导致后续满文本页面上的不必要溢出检查。 **修复。** `[PATCH: maxChars-propagate]` 移除 `!settings.maxChars` 门控。估计值每页重新计算。 ### maxChars 估计算法 **问题。** 更新后的 `maxChars` 估计是最近四页文本内容长度的滚动平均值。滚动平均值被短页面(章节末尾、全页图片)拉低,导致估计对后续的正常页面偏低预测,触发过多的溢出检查。 **修复。** `[PATCH: maxChars-running-max]` 滚动平均值替换为运行最大值。估计跟踪到目前为止看到的最大页面而非最近均值。 ### 循环检测 **问题。** 断开 token 的循环检测在 Array 上使用 `tokens.lastIndexOf(breakToken)`,每页最多扫描 N 个条目。在 1651 页渲染中这是 O(n²)。 **修复。** `[PATCH: tokens-set]` Array 替换为 `Set`,将每次查找成本从 O(n) 降低到 O(1)。 ## 边距组渲染 **问题。** `finalizePage` 钩子通过在布局时读取 `getComputedStyle()` 计算每页边距组的 `grid-template-columns` 和 `grid-template-rows` 值。这触发布局刷新且每页运行一次。 **修复。** `[PATCH: emit static grid-template rules]` grid-template 决策树提升到 `AtPage.emitMarginGridTemplates()`,在 CSS 解析阶段从 `afterTreeWalk` 调用一次。它从解析的 `@page` AST 读取每个边距格的有效 `hasContent` / `max-width` / `max-height` --- 在 CSS 遍历期间作为字符串捕获 --- 并将静态 `grid-template-columns` / `grid-template-rows` 规则发出到样式表中。浏览器通过层叠将它们应用于每个匹配的页面类。每页的 `finalizePage` 仅保留布局后真正需要 DOM 检查的情况。 ## 内容准备 ### innerHTML 往返 **问题。** `[PATCH: wrap-content-move]` 上游通过 `innerHTML` 将 `<body>` 内容序列化为字符串并重新解析到 `<template>` 来将其移入 paged.js 的布局容器。对于大型书籍,此序列化代价高昂且销毁活跃 DOM 节点,需要完全重新解析。 **修复。** 子节点通过 `appendChild` 直接移入活文档拥有的普通 `DocumentFragment`。片段存储在标记 `<template>` 元素的 `_pagedjsContent` 扩展属性上,使重入调用返回已移入的片段而非尝试移动已分离的节点。 ### 空白过滤器 **问题。** `[PATCH: whitespace-filter-opt-in]` 空白过滤器 --- 将元素间空白文本节点包裹在 `<span class="w">` 中以防止 paged.js 在分页处丢弃 --- 默认在所有文档上运行。 **修复。** 过滤器默认禁用。`book.html` 的元素间空白在文件被 paged.js 读取之前由 tbdocs 构建管线剥离,因此过滤器找不到要包裹的内容。 ## 处理程序自禁用 **问题。** `Footnotes` 和类似处理程序在启动时无条件注册每页钩子(`renderNode`、`afterPageLayout`、`beforePageLayout`、`afterOverflowRemoved`),即使文档不包含脚注。这些钩子在每个页面上触发却无事可做。 **修复。** `[PATCH: handler-self-disable]` 处理程序跟踪其注册的每个 `(hook, bound)` 对。`[PATCH: footnotes-self-disable]` `Footnotes` 处理程序在 `afterParsed` 中检查解析文档中是否存在任何 `float: footnote` CSS 规则或 `data-note="footnote"` 元素。如果两者都不存在,它在布局开始前从所有每页钩子中移除自身。 相关的 `[PATCH: extract-vs-delete]` 在 `Footnotes` 每页处理程序中保护 `removed` 访问:当 `removeOverflow` 走了 `deleteContents` 快速路径(渲染区域无脚注)时,`removed` 为 `null`。该保护防止在该路径上对 `null` 的未检查属性访问。 ## ResizeObserver **问题。** `[PATCH: disable-resize-observer]` 上游在布局包装器上注册 `ResizeObserver` 以检测后期加载资源(字体、图片)引起的布局后回流。在无头管线中,`waitUntil: "load"` 保证在 paged.js 运行前所有资源都已存在并加载;观察者从不触发。 **修复。** 此分支中 `addResizeObserver()` 为空操作。 ## 另见 * [pdf-lib 补丁](/official/Documentation/Fixes-PDFLib) -- 处理阶段应用的 pdf-lib 垫片。 * [PDF 生成](/official/Documentation/PDF-Generation) -- paged.js 包如何融入三阶段渲染管线。 > AI生成 --- --- url: /en/official/Documentation/Fixes-PagedJS.md --- # Paged.js Patches `book/lib/paged.browser.js` is a vendored, patched copy of paged.js v0.4.3 (MIT). Upstream paged.js is designed for interactive browsers: it yields to the event loop to keep pages responsive during long renders, uses async functions throughout, and registers observation and resize callbacks. None of that is useful in a headless, non-interactive Chromium process where the only goal is to produce a PDF as fast as possible. This page documents every patch and its rationale. ## Synchronous execution chain **Problem.** Upstream paged.js is built from a chain of `async function`s. The central yield mechanism is `waitForTick()`, called every 100 laid-out objects inside the core `*layout` generator. On a 1651-page book this adds thousands of forced event-loop turns. Beyond `waitForTick()`, the async machinery itself --- each function compiles to a tslib `__awaiter` + `__generator` state machine --- allocates a Promise per call even on paths that never actually yield. In headless Chromium the event loop is not shared with any user-facing interaction; yielding to it adds latency with no benefit. `preview()` returning a Promise also complicated the per-page hook architecture: an accidentally-async handler could have its awaitable work silently dropped. **Fix.** Fourteen methods were rewritten as synchronous equivalents, marked `[PATCH: sync-chain]` throughout the file. | Method | Change | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `*layout()` | Sync generator; `renderer.next()` returns synchronously. | | `render()` | Plain sync; no more per-page async state machine. | | `renderTo()` | `async` removed; `renderTo` returns synchronously. | | `layout()` | `async` removed; calls `renderTo` and `handleBreaks` synchronously. | | `handleBreaks()` | No longer awaits hook triggers; `Hook.trigger()` returns `undefined` on the all-sync path. | | `flow()` | All five `await` sites removed; `beforeParsed`/`afterParsed`/`afterRendered` hooks are called synchronously and guarded by `_assertSync`. | | `renderOnIdle()` / `renderAsync()` | Removed entirely; both wrapped `renderer.next()` in unnecessary async machinery. | | `clonePage()` | `async` removed; only reachable via the `Footnotes` handler, which self-disables when the document has no footnotes. | | `loadFonts()` | Rewritten as a synchronous assertion. `waitUntil: "load"` in `render-book.mjs` guarantees every `FontFace` is loaded before paged.js runs. | | `parse()` | `async` removed; no registered handler in this pipeline is async for the hooks it fires. | | `request()` | Replaced with synchronous XHR (`XMLHttpRequest` with `async=false`), returning `responseText` directly. | | `add()` | `async` removed; all inputs are inline `{url: text}` objects requiring no fetch. | | `convertViaSheet()` | `async` removed; `request()` now returns text directly. | A guard function `_assertSync(triggerResult, hookName)` is added at each call site that receives the sync sentinel from `Hook.trigger()`. If a handler returns a thenable, `_assertSync` throws immediately with the hook name rather than silently discarding the async work. ::: info `await page.evaluate(...)` in `render-book.mjs` is a puppeteer requirement for the CDP round-trip, not a sign that `preview()` is async inside Chromium. The `await` resolves only after Chromium's synchronous execution completes and the CDP response returns to Node. ::: ## Hook dispatch fast-paths **Problem.** `Hook.trigger()` always returned `Promise.all(promises)`, wrapping every sync handler result in `new Promise(resolve => resolve(...))`. Callers always awaited the result, paying a microtask boundary even when no handler was async. `Hook.triggerSync()` (the synchronous variant used for per-page hooks) always allocated a results array and called `.forEach` over it, even when `this.hooks` was empty. The `onOverflow` and `onBreakToken` hooks have zero registered handlers in this pipeline; `triggerSync` was called ~3300 times per render for pure dispatch overhead. **Fix.** `[PATCH: hook-fast-path]` `trigger()` returns `undefined` (the sync sentinel) when all handlers complete without returning a thenable, rather than a resolved Promise. Callers are rewritten as: ```js let p = hook.trigger(...); if (p) await p; ``` `[PATCH: hook-fast-path-sync]` `triggerSync()` returns `undefined` immediately when `this.hooks` is empty, skipping both the array allocation and the `.forEach`. At each call site that now receives the sync sentinel, `_assertSync(result, hookName)` throws if the result is thenable, converting a silent correctness risk into a diagnosable error. ## DOM element lookup ### indexOfRefs dictionary **Problem.** `findElement(ref, root)` looked up elements by their `data-ref` attribute. When the `indexOfRefs` fast-path dictionary was not populated, it fell through to `root.querySelector("[data-ref='X']")`, which scanned the entire `root` subtree. On a 1651-page book, 848 + 42 such scans inside `createBreakToken` alone accounted for over one second of render time. **Fix.** `[PATCH: findRef fast-path]` During the `addRefs()` walk, every element with a `data-ref` attribute is recorded in `root.indexOfRefs`. Subsequent `findElement` calls hit the dictionary and skip the `querySelector` scan entirely. ### Fragment merge **Problem.** When `append()` rebuilt an ancestor and inserted it via `dest.appendChild(fragment)`, the rebuilt nodes' `data-ref` mappings were not carried into `dest.indexOfRefs`. Subsequent `findElement(rebuiltAncestor, dest)` calls missed the dictionary and fell back to `querySelector`. **Fix.** `[PATCH: findRef fast-path]` After `dest.appendChild(fragment)`, `fragment.indexOfRefs` is merged into `dest.indexOfRefs` in a single pass. ### Source indexOfRefs representation **Problem.** The source content's `indexOfRefs` was a plain JavaScript object (`{}`). V8 represents such objects as a hash map when the key count is large: ~40--50 bytes per entry. The keys are decimal-string UUID counters that translate to sequential integers. **Fix.** `[PATCH: source-indexOfRefs-array]` The source `indexOfRefs` is now a plain `Array`. V8 stores it as `PACKED_ELEMENTS` (dense array mode): ~8 bytes per slot. `[PATCH: source-indexOfRefs-presize]` The array is pre-sized from `HTMLCollection.length` before the walk, eliminating geometric-growth backing-store reallocations during the traversal. ## Parent node lookup cache **Problem.** The inner loop of `append()` resolved the destination parent (`destParent`) for each source node by calling `findElement(srcParent, dest)`. Consecutive siblings in the source tree share the same `srcParent`; each sibling called `findElement` independently. **Fix.** `[PATCH: parent-lookup-cache]` A one-entry memo on the `Layout` instance stores the last `(srcParent, dest) → destParent` resolution. Consecutive siblings hit the cache and skip the dictionary lookup. The memo is invalidated at the start of each `renderTo` call because `removeOverflow` may have detached the cached `destParent` between calls. ## data-ref attribute caching **Problem.** `element.dataset.ref` calls `getAttribute` internally and allocates a fresh JS string on every access. The `addRefs` walk and `append()` each read the same attribute value twice: once for the existence check and once for the `indexOfRefs` write. **Fix.** `[PATCH: addRefs-uuid-local]` / `[PATCH: append-ref-local]` Read the attribute once via `getAttribute` into a local variable and reuse it for both operations. This saves one string allocation per element in the `addRefs` walk and per append call --- roughly 50 000 calls on the book, measured at ~1.5 MB heap reduction per A/B sampling pair. ## Render queue scheduler **Problem.** The internal render queue used `requestAnimationFrame` as its per-task tick. In headless puppeteer renders, `rAF` still waits for the next compositor frame even with no visual output and no interaction. On a 1651-page book, the per-page queue iterations accumulated ~700 ms of V8 idle time from `rAF` deferred callbacks. **Fix.** `[PATCH: queue-tick]` The per-task callback is scheduled with `queueMicrotask` instead of `requestAnimationFrame`. It fires in the microtask checkpoint rather than waiting for a compositor frame. ## Page layout correctness ### maxChars freeze **Problem.** Upstream gated the per-page `maxChars` estimate update on `!settings.maxChars`. On the first pass with a non-empty page, `settings.maxChars` was set and the gate prevented any further updates. On a book whose opening pages are short (title page, part dividers), the estimate was permanently too small, causing unnecessary overflow checks on subsequent full-text pages. **Fix.** `[PATCH: maxChars-propagate]` The `!settings.maxChars` gate is removed. The estimate is recalculated every page. ### maxChars estimation algorithm **Problem.** The updated `maxChars` estimate was a rolling average over the last four page text-content lengths. A rolling average is pulled down by short pages (chapter ends, full-page images), causing the estimate to underpredict for the normal pages that follow, triggering excess overflow checks. **Fix.** `[PATCH: maxChars-running-max]` The rolling average is replaced by a running maximum. The estimate tracks the largest page seen so far rather than the recent mean. ### Loop detection **Problem.** Break-token loop detection used `tokens.lastIndexOf(breakToken)` on an Array, which scanned up to N entries per page. Across a 1651-page render this was O(n²). **Fix.** `[PATCH: tokens-set]` The Array is replaced with a `Set`, reducing the per-lookup cost from O(n) to O(1). ## Margin group rendering **Problem.** The `finalizePage` hook computed `grid-template-columns` and `grid-template-rows` values for each page's margin groups by reading `getComputedStyle()` at layout time. This triggered layout flushes and ran once per page. **Fix.** `[PATCH: emit static grid-template rules]` The grid-template decision tree is hoisted to `AtPage.emitMarginGridTemplates()`, called once from `afterTreeWalk` during the CSS parse phase. It reads the effective `hasContent` / `max-width` / `max-height` per margin cell from the parsed `@page` AST --- captured as strings during the CSS walk --- and emits static `grid-template-columns` / `grid-template-rows` rules into the stylesheet. The browser applies them via cascade for every matching page class. Per-page `finalizePage` retains only the cases that genuinely require a DOM inspection after layout. ## Content preparation ### innerHTML round-trip **Problem.** `[PATCH: wrap-content-move]` Upstream moved the `<body>` content into paged.js's layout container by serialising the entire body to a string via `innerHTML` and reparsing it into a `<template>`. For a large book this serialisation is expensive and destroys the live DOM nodes, requiring a full reparse. **Fix.** Children are moved directly into a plain `DocumentFragment` owned by the live document via `appendChild`. The fragment is stashed on a marker `<template>` element's `_pagedjsContent` expando so re-entrant calls return the already-moved fragment rather than attempting to move already-detached nodes. ### Whitespace filter **Problem.** `[PATCH: whitespace-filter-opt-in]` The whitespace filter --- which wraps inter-element whitespace text nodes in `<span class="w">` to prevent paged.js from discarding them at page breaks --- ran on all documents by default. **Fix.** The filter is disabled by default. `book.html` has its inter-element whitespace stripped by the tbdocs build pipeline before the file is read by paged.js, so the filter would find nothing to wrap. ## Handler self-disable **Problem.** `Footnotes` and similar handlers register per-page hooks (`renderNode`, `afterPageLayout`, `beforePageLayout`, `afterOverflowRemoved`) unconditionally at startup, even when the document contains no footnotes. These hooks fire on every page with nothing to do. **Fix.** `[PATCH: handler-self-disable]` Handlers track each `(hook, bound)` pair they register. `[PATCH: footnotes-self-disable]` The `Footnotes` handler checks in `afterParsed` whether any `float: footnote` CSS rules or `data-note="footnote"` elements exist in the parsed document. If neither is present, it splices itself out of all per-page hooks before layout begins. The related `[PATCH: extract-vs-delete]` guards `removed` access in the `Footnotes` per-page handler: when `removeOverflow` took the `deleteContents` fast path (no footnotes in the rendered area), `removed` is `null`. The guard prevents an unchecked property access on `null` in that path. ## ResizeObserver **Problem.** `[PATCH: disable-resize-observer]` Upstream registered a `ResizeObserver` on the layout wrapper to detect post-layout reflow from late-loading resources (fonts, images). In the headless pipeline, `waitUntil: "load"` guarantees all resources are present and loaded before paged.js runs; the observer never fires. **Fix.** `addResizeObserver()` is a no-op in this fork. ## See Also * [pdf-lib Patches](/en/official/Documentation/Fixes-PDFLib) -- the pdf-lib shims applied during the process phase. * [PDF Generation](/en/official/Documentation/PDF-Generation) -- how the paged.js bundle fits into the three-phase render pipeline. --- --- url: /en/packages/vbccr/bars/pager.md description: >- Pager Control - VBCCR Developer Reference, complete API documentation based on source code --- # Pager Control Wraps the SysPager system pager control, used to create scrollable control areas by scrolling an associated buddy control via left/right or up/down buttons. ## Enumerations ### PgrOrientationConstants | Constant | Value | Description | |----------|-------|-------------| | PgrOrientationHorizontal | 0 | Horizontal orientation | | PgrOrientationVertical | 1 | Vertical orientation | ### PgrDirectionConstants | Constant | Value | Description | |----------|-------|-------------| | PgrDirectionLeft | 0 | Scroll left | | PgrDirectionRight | 1 | Scroll right | | PgrDirectionUp | 2 | Scroll up | | PgrDirectionDown | 3 | Scroll down | ### PgrButtonConstants | Constant | Value | Description | |----------|-------|-------------| | PgrButtonLeftTop | 0 | Left/top button | | PgrButtonRightBottom | 1 | Right/bottom button | ### PgrButtonStateConstants | Constant | Value | Description | |----------|-------|-------------| | PgrButtonStateNormal | 0 | Normal | | PgrButtonStateInvisible | 1 | Hidden | | PgrButtonStateGrayed | 2 | Grayed (disabled) | | PgrButtonStateInactive | 4 | Inactive | | PgrButtonStateHot | 8 | Hot | ### CCMousePointerConstants See common enumerations. ## Properties ### BuddyControl ```vb Property Get BuddyControl() As Variant Property Let BuddyControl(ByVal Value As Variant) ``` Associated buddy control. Can accept a control object, a control name, or an hWnd. ### Orientation ```vb Property Get Orientation() As PgrOrientationConstants Property Let Orientation(ByVal Value As PgrOrientationConstants) ``` Pager control orientation. ### BorderWidth ```vb Property Get BorderWidth() As Long Property Let BorderWidth(ByVal Value As Long) ``` Border width (pixels). ### AutoScroll ```vb Property Get AutoScroll() As Boolean Property Let AutoScroll(ByVal Value As Boolean) ``` Whether automatic scrolling is enabled. ### ButtonSize ```vb Property Get ButtonSize() As Long Property Let ButtonSize(ByVal Value As Long) ``` Button size (pixels). ### OLEDragDropScroll ```vb Property Get OLEDragDropScroll() As Boolean Property Let OLEDragDropScroll(ByVal Value As Boolean) ``` Whether automatic scrolling is enabled during OLE drag-and-drop. ### Value ```vb Property Get Value() As Single Property Let Value(ByVal Value As Single) ``` Current scroll position. ### VisualStyles ```vb Property Get VisualStyles() As Boolean Property Let VisualStyles(ByVal Value As Boolean) ``` Whether visual styles are enabled. ### hWnd ```vb Property Get hWnd() As LongPtr ``` Window handle of the pager control. ### hWndUserControl ```vb Property Get hWndUserControl() As LongPtr ``` Window handle of the user control. ### Font ```vb Property Get Font() As StdFont Property Let Font(ByVal NewFont As StdFont) Property Set Font(ByVal NewFont As StdFont) ``` Font. ### Enabled ```vb Property Get Enabled() As Boolean Property Let Enabled(ByVal Value As Boolean) ``` Whether the control is enabled. ### MousePointer ```vb Property Get MousePointer() As CCMousePointerConstants Property Let MousePointer(ByVal Value As CCMousePointerConstants) ``` Mouse pointer style. See common enumerations. ### MouseIcon ```vb Property Get MouseIcon() As IPictureDisp Property Let MouseIcon(ByVal Value As IPictureDisp) Property Set MouseIcon(ByVal Value As IPictureDisp) ``` Custom mouse icon. ### MouseTrack ```vb Property Get MouseTrack() As Boolean Property Let MouseTrack(ByVal Value As Boolean) ``` Whether mouse enter/leave tracking is enabled. ### RightToLeft ```vb Property Get RightToLeft() As Boolean Property Let RightToLeft(ByVal Value As Boolean) ``` Right-to-left display direction. ### RightToLeftMode ```vb Property Get RightToLeftMode() As CCRightToLeftModeConstants Property Let RightToLeftMode(ByVal Value As CCRightToLeftModeConstants) ``` Right-to-left mode. See common enumerations. ### Name ```vb Property Get Name() As String ``` Control name. Read-only. ### Tag ```vb Property Get Tag() As String Property Let Tag(ByVal Value As String) ``` Custom data. ### Parent ```vb Property Get Parent() As Object ``` Parent object. Read-only. ### Container ```vb Property Get Container() As Object Property Set Container(ByVal Value As Object) ``` Container object. ### Left ```vb Property Get Left() As Single Property Let Left(ByVal Value As Single) ``` Left edge distance. ### Top ```vb Property Get Top() As Single Property Let Top(ByVal Value As Single) ``` Top edge distance. ### Width ```vb Property Get Width() As Single Property Let Width(ByVal Value As Single) ``` Width. ### Height ```vb Property Get Height() As Single Property Let Height(ByVal Value As Single) ``` Height. ### Visible ```vb Property Get Visible() As Boolean Property Let Visible(ByVal Value As Boolean) ``` Whether visible. ### ToolTipText ```vb Property Get ToolTipText() As String Property Let ToolTipText(ByVal Value As String) ``` ToolTip text. ### HelpContextID ```vb Property Get HelpContextID() As Long Property Let HelpContextID(ByVal Value As Long) ``` Help context ID. ### WhatsThisHelpID ```vb Property Get WhatsThisHelpID() As Long Property Let WhatsThisHelpID(ByVal Value As Long) ``` "What's This" help ID. ### DragIcon ```vb Property Get DragIcon() As IPictureDisp Property Let DragIcon(ByVal Value As IPictureDisp) Property Set DragIcon(ByVal Value As IPictureDisp) ``` Drag icon. ### DragMode ```vb Property Get DragMode() As Integer Property Let DragMode(ByVal Value As Integer) ``` Drag mode. ## Methods ### ReCalcSize ```vb Public Sub ReCalcSize() ``` Recalculates the size of the pager control and the buddy control. ### GetButtonState ```vb Public Function GetButtonState(ByVal Button As PgrButtonConstants) As PgrButtonStateConstants ``` Returns the state of the specified button. ### Drag ```vb Public Sub Drag([ByRef Action As Variant]) ``` Starts, ends, or cancels a drag-and-drop operation. ### SetFocus ```vb Public Sub SetFocus() ``` Sets focus to the control. ### ZOrder ```vb Public Sub ZOrder([ByRef Position As Variant]) ``` Sets the control's Z-order. ### OLEDrag ```vb Public Sub OLEDrag() ``` Initiates an OLE drag-and-drop operation. ### Refresh ```vb Public Sub Refresh() ``` Forces a redraw of the control. ## Events ### Scroll ```vb Public Event Scroll() ``` Raised when the scroll position changes. ### CalcSize ```vb Public Event CalcSize() ``` Raised before the buddy control size needs to be recalculated. ### HotChanged ```vb Public Event HotChanged() ``` Raised when a button's hot state changes. ### Click ```vb Public Event Click() ``` Raised when the control is clicked. ### DblClick ```vb Public Event DblClick() ``` Raised when the control is double-clicked. ### MouseDown ```vb Public Event MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Raised when a mouse button is pressed. ### MouseUp ```vb Public Event MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Raised when a mouse button is released. ### MouseMove ```vb Public Event MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Raised when the mouse is moved. ### MouseEnter ```vb Public Event MouseEnter() ``` Raised when the mouse enters the control. ### MouseLeave ```vb Public Event MouseLeave() ``` Raised when the mouse leaves the control. ### OLEDragDrop ```vb Public Event OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single) ``` Raised when an OLE drag-and-drop operation completes. ### OLEDragOver ```vb Public Event OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single, State As Integer) ``` Raised when an OLE drag-and-drop operation passes over the control. ### OLEGiveFeedback ```vb Public Event OLEGiveFeedback(Effect As Long, DefaultCursors As Boolean) ``` Raised when an OLE drag-and-drop operation needs to change the cursor. ### OLEStartDrag ```vb Public Event OLEStartDrag(Data As DataObject, AllowedEffects As Long) ``` Raised when an OLE drag-and-drop operation starts. ### OLECompleteDrag ```vb Public Event OLECompleteDrag(Effect As Long) ``` Raised when an OLE drag-and-drop operation completes. ### OLESetData ```vb Public Event OLESetData(Data As DataObject, DataFormat As Integer) ``` Raised when an OLE drop target requests data. ## Code Examples ```vb ' Set up a horizontal pager control with a picture box as the buddy Pager1.Orientation = PgrOrientationHorizontal Set Pager1.BuddyControl = Picture1 Pager1.ButtonSize = 16 Call Pager1.ReCalcSize ``` --- --- url: /en/official/Tutorials/CustomControls/Painting-drawing-to-your-control.md --- # Painting / Drawing to Your Control ### The ICustomControl.Paint method This is by far the most important method of a CustomControl. It tells the form engine exactly how you want it to render your control. See the [`ICustomControl.Paint`](/en/official/Reference/CustomControls/Framework/ICustomControl#paint) reference for the host-side contract. ::: tip It is highly advisable to look at and experiment with the sample project provided with twinBASIC before trying to implement your own CustomControl. ::: ```vb Private Sub OnPaint(ByVal Canvas As CustomControls.Canvas) _ Implements ICustomControl.Paint ``` You are passed a [`Canvas`](/en/official/Reference/CustomControls/Framework/Canvas) object that offers the following methods: ```vb Canvas.Width As Long ' Property-Get Canvas.Height As Long ' Property-Get] Canvas.Dpi As Long ' Property-Get] Canvas.DpiScaleFactor As Double ' Property-Get Canvas.AddElement(Descriptor As ElementDescriptor) ``` ::: info The current framework spells these members [`RuntimeUICCGetWidth`](/en/official/Reference/CustomControls/Framework/Canvas#runtimeuiccgetwidth), [`RuntimeUICCGetHeight`](/en/official/Reference/CustomControls/Framework/Canvas#runtimeuiccgetheight), [`RuntimeUICCGetDpi`](/en/official/Reference/CustomControls/Framework/Canvas#runtimeuiccgetdpi), [`RuntimeUICCGetDpiScaleFactor`](/en/official/Reference/CustomControls/Framework/Canvas#runtimeuiccgetdpiscalefactor), and [`RuntimeUICCCanvasAddElement`](/en/official/Reference/CustomControls/Framework/Canvas#runtimeuicccanvasaddelement). The shorter names shown above are how the API was originally drafted; the underlying behaviour is the same. ::: `Canvas.Width` and `Canvas.Height` are the absolute pixel sizes that your control is drawing to. Unlike your controls Width/Height properties that are not DPI-scaled, the `Canvas.Width` and `Canvas.Height` values **are** DPI-scaled. The `Canvas.Dpi` property represents the DPI setting in Windows. If no DPI scaling is in effect, this value is 96. For example, if you have scaling set at 150% on your monitor, then the `Canvas.Dpi` property will be 144. The `Canvas.DpiScaleFactor` property gives a floating point value representing the DPI scaling percentage. A value of 1 indicates no scaling. For example, if you have scaling set at 150% on your monitor, then the `Canvas.DpiScaleFactor` property will be 1.5. The `Canvas.AddElement` method is used for adding elements to your control. An *element* is considered to be something that the form-engine will render for you. For example, you might have a grid control that displays 100 cells at a time. Each of those cells would be an *element*. Elements can overlap each over (allowing for opacity/transparency). The form engine draws them in the order that you call AddElement, meaning that the last element added will have the highest z-order. *** ### AddElement(ElementDescriptor) The AddElement method takes a single argument; an ElementDescriptor. ElementDescriptor is a UDT that defines exactly how the element will be drawn and how it reacts to events like mouse clicks. ```vb Public Type ElementDescriptor OnClick As LongPtr ' event function callback pointer OnDblClick As LongPtr ' event function callback pointer OnMouseDown As LongPtr ' event function callback pointer OnMouseUp As LongPtr ' event function callback pointer OnMouseEnter As LongPtr ' event function callback pointer OnMouseLeave As LongPtr ' event function callback pointer OnMouseMove As LongPtr ' event function callback pointer OnScrollH As LongPtr ' event function callback pointer OnScrollV As LongPtr ' event function callback pointer Left As Long ' pixel offset (control relative, DPI scaled) Top As Long ' pixel offset (control relative, DPI scaled) Width As Long ' pixel width (DPI scaled) Height As Long ' pixel width (DPI scaled) Cursor As MousePointerConstants ' cursor/pointer icon TrackingIdX As LongLong ' for tracking this element, passed to events TrackingIdY As LongLong ' for tracking this element, passed to events Text As String ' the text to render TextRenderingOptions As TextRendering ' options to customize text rendering (object) BackgroundFill As Fill ' options to customize back fill rendering (object) Corners As Corners ' options to customize corner rendering (object) Borders As Borders ' options to customize border rendering (object) End Type ``` *** ### Tips * Each time your OnPaint method is called, you start with a blank canvas. * Left/Top/Width/Height can legitimately be outside of the canvas area. For example, negative Left/Top, or a Width/Height past the Canvas.Width/Canvas.Height has no ill-effects. The form engine will clip everything appropriately for you, allowing for much simpler designing of your control. * You should put thought into making the Paint routine efficient. Try not to instantiate COM objects, and when drawing multiple similar elements, try to re-use ElementDescriptors by setting up common properties outside of loops (see WaynesGrid for examples of this) * TrackingIdX and TrackingIdY are important when you have multiple elements within a control. The two values, when combined, should uniquely represent the element, and must be maintained if your Paint routine is called again. This is needed for supporting events. For example, in a grid control, each cell would have a TrackingIdX / TrackingIdY value associated with it, given the X/Y co-ordinates of the cell. * Currently, only mouse events are provided, but focus events are coming soon, as well as keyboard events. * You can use class-based event handlers by simply using the `AddressOf MyEvent` which is now possible to use even on class members. You can see this used frequently in the samples, such as WaynesGrid. All mouse events have the following format: ```vb Class MyCustomControl '... Private Sub MyClickEvent(ByRef EventInfo As MouseEvent) MsgBox "You clicked me!" End Sub Private Sub OnPaint(ByVal Canvas As CustomControls.Canvas) _ Implements ICustomControl.Paint Dim MyDescriptor As ElementDescriptor MyDescriptor.OnClick = AddressOf MyClickEvent End Sub ``` EventInfo (MouseEvent) provides mouse information such as the relative X/Y position of the mouse, plus the TrackingX/Y values discussed earlier. * When you call Canvas.AddElement, your element goes into a render pipeline. It is **not** immediately painted to the screen. The render pipeline is compared to the previous render pipeline that was provided by you in the last OnPaint call, and the tB form engine will only redraw areas of the control that have changed. This allows for efficient painting of controls whilst not needing to be concerned about the finer details of how to do partial repainting. *** ## See also * [`ICustomControl`](/en/official/Reference/CustomControls/Framework/ICustomControl) -- the interface every custom control implements * [`Canvas`](/en/official/Reference/CustomControls/Framework/Canvas) -- the drawing surface passed to **Paint** * Style helpers used by the `BackgroundFill` / `Borders` / `Corners` / `TextRenderingOptions` fields of an `ElementDescriptor`: [`Fill`](/en/official/Reference/CustomControls/Styles/Fill), [`Borders`](/en/official/Reference/CustomControls/Styles/Borders), [`Corners`](/en/official/Reference/CustomControls/Styles/Corners), [`TextRendering`](/en/official/Reference/CustomControls/Styles/TextRendering) * [CustomControls package reference](/en/official/Reference/CustomControls/) -- overview of the framework and the built-in `Waynes…` controls (a number of which --- `WaynesGrid`, `WaynesButton`, … --- are exactly the worked examples mentioned above) --- --- url: /en/official/Reference/VBRUN/AmbientProperties/Palette.md --- # Palette Returns the colour palette the container would like its embedded controls to draw with, as an **stdole.IPictureDisp**. Read-only. Syntax: *object*.**Palette** *object* : *required* An object expression that evaluates to an **AmbientProperties** object. The returned object is a picture whose attached palette identifies the colours the host expects to be available. A control rendering on a palette-managed display should use these colours to avoid unwanted palette flashing when its window receives the focus. On modern true-colour displays the palette is rarely meaningful, and most controls can ignore it. ### Example This example responds to an ambient **Palette** change by triggering a repaint. ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "Palette" UserControl.Refresh ' repaint using the updated palette End Select End Sub ``` ### See Also * [BackColor](/en/official/Reference/VBRUN/AmbientProperties/BackColor) property * [ForeColor](/en/official/Reference/VBRUN/AmbientProperties/ForeColor) property --- --- url: /zh/official/Reference/VBRUN/AmbientProperties/Palette.md --- # Palette 返回容器希望其嵌入控件使用的调色板,类型为**stdole.IPictureDisp**。只读。 语法:*object*.**Palette** *object* : *必需* 求值为**AmbientProperties**对象的对象表达式。 返回的对象是附带了调色板的图片,该调色板标识宿主期望可用的颜色。在调色板管理的显示器上渲染的控件应使用这些颜色,以避免窗口获得焦点时出现不希望的调色板闪烁。在现代真彩色显示器上,调色板很少有意义,大多数控件可以忽略它。 ### 示例 此示例响应环境**Palette**更改,触发重绘。 ```vb Private Sub UserControl_AmbientChanged(PropertyName As String) Select Case PropertyName Case "Palette" UserControl.Refresh ' 使用更新的调色板重绘 End Select End Sub ``` ### 另见 * [BackColor](/official/Reference/VBRUN/AmbientProperties/BackColor) 属性 * [ForeColor](/official/Reference/VBRUN/AmbientProperties/ForeColor) 属性 --- --- url: /en/official/Reference/VBRUN/Constants/PaletteModeConstants.md --- # PaletteModeConstants Palette-source values for the **PaletteMode** property of forms and **UserControls**, choosing where the colour palette used to render child controls comes from. | Constant | Value | Description | |----------|-------|-------------| | **vbPaletteModeHalftone** | 0 | Use the standard halftone palette. | | **vbPaletteModeUseZOrder** | 1 | Use the palette of the topmost control that has one. | | **vbPaletteModeCustom** | 2 | Use the bitmap supplied by the **Palette** property. | | **vbPaletteModeContainer** | 3 | Use the container's palette. | | **vbPaletteModeNone** | 4 | No palette is set. | | **vbPaletteModeObject** | 5 | Use the palette supplied by an in-place active OLE object. | --- --- url: /zh/official/Reference/VBRUN/Constants/PaletteModeConstants.md --- # PaletteModeConstants 窗体和**UserControl**的**PaletteMode**属性的调色板来源值,选择用于呈现子控件的颜色调色板来源。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbPaletteModeHalftone** | 0 | 使用标准半色调调色板。 | | **vbPaletteModeUseZOrder** | 1 | 使用最上层具有调色板的控件的调色板。 | | **vbPaletteModeCustom** | 2 | 使用**Palette**属性提供的位图。 | | **vbPaletteModeContainer** | 3 | 使用容器的调色板。 | | **vbPaletteModeNone** | 4 | 未设置调色板。 | | **vbPaletteModeObject** | 5 | 使用就地活动OLE对象提供的调色板。 | --- --- url: /en/official/Reference/Core/ParamArray.md --- # ParamArray Used in the argument list of a [**Sub**](/en/official/Reference/Core/Sub), [**Function**](/en/official/Reference/Core/Function), or [**Property**](/en/official/Reference/Core/Property) procedure to indicate that the final parameter is an open-ended list of arguments. The **ParamArray** keyword permits the procedure to accept an arbitrary number of arguments at the call site. Syntax: > \[ **Public** | **Private** | **Friend** ] \[ **Static** ] **Sub** | **Function** | **Property Get** | **Property Let** | **Property Set** *name* **(** \[ *arglist*, ] **ParamArray** *varname*\[ **()** ] \[ **As** *type* ] **)** *varname* : Name of the variable representing the **ParamArray**; follows standard variable naming conventions. *type* : *optional* Must be **Variant** (explicitly or by default). Each argument supplied at the call site can be of a different data type, so **ParamArray** must always be an array of **Variant** elements. **ParamArray** must be the last parameter in the argument list of a **Sub**, **Function**, or **Property Get** procedure. In a **Property Let** or **Property Set** procedure it must precede the *value*/*reference* parameter and so cannot be the only parameter. **ParamArray** cannot be combined with **Optional**, **ByVal**, or **ByRef** on the same parameter --- arguments supplied to a **ParamArray** are always passed by reference as elements of a **Variant** array. When the procedure is called, each argument supplied in the call becomes a corresponding element of the **Variant** array. If no arguments are supplied for the **ParamArray** position, the array is empty. ::: info A procedure that defines a **ParamArray** parameter cannot be called using named-argument syntax. All arguments to such a procedure must be positional. To omit individual elements within the **ParamArray** position at a call site, leave the position blank between commas. ::: ### Example This example defines a function that sums an arbitrary number of numeric arguments by using **ParamArray**. ```vb Function CalcSum(ParamArray Args() As Variant) As Double Dim Total As Double, i As Long For i = LBound(Args) To UBound(Args) Total = Total + CDbl(Args(i)) Next i CalcSum = Total End Function ' Calls of varying arity: Debug.Print CalcSum() ' 0 Debug.Print CalcSum(1) ' 1 Debug.Print CalcSum(1, 2, 3, 4) ' 10 Debug.Print CalcSum(1.5, 2.5, 3#) ' 7 ``` A **ParamArray** can follow ordinary positional parameters; only those that come after a fixed leading list participate in the variadic tail. ```vb Function Concat(ByVal Separator As String, ParamArray Parts() As Variant) As String Dim i As Long, s As String For i = LBound(Parts) To UBound(Parts) If i > LBound(Parts) Then s = s & Separator s = s & CStr(Parts(i)) Next i Concat = s End Function Debug.Print Concat(", ", "one", "two", "three") ' "one, two, three" ``` ### See Also * [**Sub** statement](/en/official/Reference/Core/Sub) * [**Function** statement](/en/official/Reference/Core/Function) * [**Property** statement](/en/official/Reference/Core/Property) * [**Call** statement](/en/official/Reference/Core/Call) --- --- url: /zh/official/Reference/Core/ParamArray.md --- # ParamArray 在[**Sub**](/official/Reference/Core/Sub)、[**Function**](/official/Reference/Core/Function)或[**Property**](/official/Reference/Core/Property)过程的参数列表中使用,指示最后一个参数是开放式参数列表。**ParamArray**关键字允许过程在调用点接受任意数量的参数。 语法: > \[ **Public** | **Private** | **Friend** ] \[ **Static** ] **Sub** | **Function** | **Property Get** | **Property Let** | **Property Set** *name* **(** \[ *arglist*, ] **ParamArray** *varname*\[ **()** ] \[ **As** *type* ] **)** *varname* : 表示**ParamArray**的变量名称;遵循标准变量命名约定。 *type* : *可选* 必须为**Variant**(显式指定或默认)。在调用点提供的每个参数可以是不同的数据类型,因此**ParamArray**必须始终是**Variant**元素的数组。 **ParamArray**必须是**Sub**、**Function**或**Property Get**过程参数列表中的最后一个参数。在**Property Let**或**Property Set**过程中,它必须在*value*/*reference*参数之前,因此不能是唯一的参数。 **ParamArray**不能与同一参数上的**Optional**、**ByVal**或**ByRef**组合——提供给**ParamArray**的参数始终以引用方式作为**Variant**数组的元素传递。 当调用过程时,调用中提供的每个参数成为**Variant**数组的对应元素。如果没有为**ParamArray**位置提供参数,则数组为空。 ::: info 定义了**ParamArray**参数的过程不能使用命名参数语法调用。此类过程的所有参数必须是位置参数。要在调用点省略**ParamArray**位置中的个别元素,请在逗号之间留空。 ::: ### 示例 本示例定义了一个使用**ParamArray**对任意数量数值参数求和的函数。 ```vb Function CalcSum(ParamArray Args() As Variant) As Double Dim Total As Double, i As Long For i = LBound(Args) To UBound(Args) Total = Total + CDbl(Args(i)) Next i CalcSum = Total End Function ' Calls of varying arity: Debug.Print CalcSum() ' 0 Debug.Print CalcSum(1) ' 1 Debug.Print CalcSum(1, 2, 3, 4) ' 10 Debug.Print CalcSum(1.5, 2.5, 3#) ' 7 ``` **ParamArray**可以跟在普通的位置参数之后;只有固定前导列表之后的参数参与可变参数尾部。 ```vb Function Concat(ByVal Separator As String, ParamArray Parts() As Variant) As String Dim i As Long, s As String For i = LBound(Parts) To UBound(Parts) If i > LBound(Parts) Then s = s & Separator s = s & CStr(Parts(i)) Next i Concat = s End Function Debug.Print Concat(", ", "one", "two", "three") ' "one, two, three" ``` ### 另请参阅 * [**Sub** 语句](/official/Reference/Core/Sub) * [**Function** 语句](/official/Reference/Core/Function) * [**Property** 语句](/official/Reference/Core/Property) * [**Call** 语句](/official/Reference/Core/Call) --- --- url: /en/official/Reference/VBRUN/ParentControls.md --- # ParentControls class The **ParentControls** object is the collection of other controls that live in the same container as a **UserControl** --- its siblings on the host form, frame, or page. It is reachable inside a **UserControl** through **UserControl.ParentControls** and lets the control discover and interact with the other controls around it without being given explicit references. By default each item is returned wrapped in its host **Extender** --- the container's per-control adapter that adds layout properties (**Top**, **Left**, **Tag**, **Visible**, **Name**, and so on) on top of the control's own interface. Set [**ParentControlsType**](#parentcontrolstype) to **vbNoExtender** to receive the bare controls instead. The collection itself is read-only: items cannot be added or removed through it. ```vb ' Inside a UserControl: print the name and type of every sibling control. Dim ctl As Object For Each ctl In UserControl.ParentControls Debug.Print ctl.Name, TypeName(ctl) Next ctl ``` ## Members ### Count Returns the number of controls in the collection. Syntax: *object*.**Count** *object* : *required* An object expression that evaluates to a **ParentControls** object. The value is a **Long**. Valid indexes for [**Item**](#item) run from `1` to **Count**. ### Item Returns a single control from the collection by its one-based position. Syntax: *object*.**Item(** *index* **)** *object* : *required* An object expression that evaluates to a **ParentControls** object. *index* : *required* A **Long** giving the one-based position of the control to return. Must be between `1` and [**Count**](#count); otherwise an error occurs. **Item** is the default member of **ParentControls**, so the following lines are equivalent: ```vb Set ctl = UserControl.ParentControls.Item(1) Set ctl = UserControl.ParentControls(1) ``` The result is typed as **Object** because the container may hold any kind of control. Whether the returned reference exposes the host-supplied **Extender** properties is governed by [**ParentControlsType**](#parentcontrolstype). ### ParentControlsType Returns or sets whether each item is returned wrapped in its host **Extender** or as the bare control. Syntax: *object*.**ParentControlsType** \[ **=** *value* ] *object* : *required* An object expression that evaluates to a **ParentControls** object. *value* : A **ParentControlsType** value: `vbExtender` (`1`) : Items are returned wrapped in the host's **Extender**, exposing the container-supplied layout properties (**Top**, **Left**, **Visible**, **Name**, **Tag**, and so on) in addition to the control's own interface. This is the default. `vbNoExtender` (`0`) : Items are returned as the bare control, without the **Extender** wrapper. Use this when the **Extender**'s extra properties are not needed, or when the control's own interface defines members that would otherwise be shadowed. Changing **ParentControlsType** affects subsequent reads from [**Item**](#item) and **For Each** iteration; references already obtained are not retroactively re-wrapped. ### For Each iteration A **ParentControls** object can be iterated with the [**For Each...Next**](/en/official/Reference/Core/For-Each-Next) statement, which yields each sibling control in turn, in the order the host returns them. The hidden `_NewEnum` member supplies the enumerator and is not called directly from user code. ```vb Dim ctl As Object For Each ctl In UserControl.ParentControls Debug.Print ctl.Name Next ctl ``` --- --- url: /zh/official/Reference/VBRUN/ParentControls.md --- *** title: ParentControls parent: VBRUN Package nav\_order: 17 permalink: /tB/Packages/VBRUN/ParentControls/ --------------------------------------------- # ParentControls 类 **ParentControls**对象是与**UserControl**位于同一容器中的其他控件集合——其在宿主窗体、框架或页面上的同级控件。可在**UserControl**内部通过**UserControl.ParentControls**访问,使控件能够发现和交互周围的其他控件,而无需获得显式引用。 默认情况下,每个项在返回时包装在其宿主**Extender**中——容器逐控件的适配器,在控件自身接口之上添加布局属性(**Top**、**Left**、**Tag**、**Visible**、**Name**等)。将[**ParentControlsType**](#parentcontrolstype)设置为**vbNoExtender**可改为接收裸控件。集合本身为只读:不能通过它添加或移除项。 `vb ' 在UserControl内部:打印每个同级控件的名称和类型。 Dim ctl As Object For Each ctl In UserControl.ParentControls Debug.Print ctl.Name, TypeName(ctl) Next ctl ` ## 成员 ### Count 返回集合中的控件数量。 语法:*object*.**Count** *object* : *必需* 求值为**ParentControls**对象的对象表达式。 值为**Long**。[**Item**](#item)的有效索引范围从1到**Count**。 ### Item 按从一开始的位置从集合中返回单个控件。 语法:*object*.**Item(** *index* **)** *object* : *必需* 求值为**ParentControls**对象的对象表达式。 *index* : *必需* 给出要返回控件从一开始位置的**Long**。必须在1和[**Count**](#count)之间;否则将发生错误。 **Item**是**ParentControls**的默认成员,因此以下两行等效: `vb Set ctl = UserControl.ParentControls.Item(1) Set ctl = UserControl.ParentControls(1) ` 结果类型为**Object**,因为容器可能包含任何类型的控件。返回的引用是否公开宿主提供的**Extender**属性由[**ParentControlsType**](#parentcontrolstype)决定。 ### ParentControlsType 返回或设置每个项是包装在宿主**Extender**中返回还是作为裸控件返回。 语法:*object*.**ParentControlsType** \[ **=** *value* ] *object* : *必需* 求值为**ParentControls**对象的对象表达式。 *value* : **ParentControlsType**值: bExtender(1) : 项在宿主的**Extender**中包装返回,公开容器提供的布局属性(**Top**、**Left**、**Visible**、**Name**、**Tag**等)以及控件的自身接口。这是默认值。 bNoExtender(�) : 项作为裸控件返回,不带**Extender**包装。当不需要**Extender**的额外属性,或控件的自身接口定义了会被遮蔽的成员时使用。 更改**ParentControlsType**影响后续从[**Item**](#item)和**For Each**迭代的读取;已获取的引用不会被追溯重新包装。 ### For Each 迭代 **ParentControls**对象可以使用[**For Each...Next**](/official/Reference/Core/For-Each-Next)语句进行迭代,按宿主返回的顺序依次产生每个同级控件。隐藏的\_NewEnum成员提供枚举器,不从用户代码直接调用。 `vb Dim ctl As Object For Each ctl In UserControl.ParentControls Debug.Print ctl.Name Next ctl ` --- --- url: /en/official/Reference/VBRUN/Constants/ParentControlsType.md --- # ParentControlsType Wrapping mode for the [**ParentControls**](/en/official/Reference/VBRUN/ParentControls/) collection, controlling whether each item is returned wrapped in its host **Extender** or as the bare control. | Constant | Value | Description | |----------|-------|-------------| | **vbNoExtender** | 0 | Items are returned as the bare control, without the host's **Extender** wrapper. | | **vbExtender** | 1 | Items are returned wrapped in the host's **Extender**, exposing the container-supplied layout properties. This is the default. | ### See Also * [ParentControls](/en/official/Reference/VBRUN/ParentControls/) module --- --- url: /zh/official/Reference/VBRUN/Constants/ParentControlsType.md --- # ParentControlsType [**ParentControls**](/official/Reference/VBRUN/ParentControls/)集合的包装模式,控制每个项目是在其宿主**Extender**中包装返回还是作为裸控件返回。 | 常量 | 值 | 说明 | |----------|-------|-------------| | **vbNoExtender** | 0 | 项目作为裸控件返回,不带宿主的**Extender**包装。 | | **vbExtender** | 1 | 项目在宿主的**Extender**中包装返回,暴露容器提供的布局属性。这是默认值。 | ### 另见 * [ParentControls](/official/Reference/VBRUN/ParentControls/) 模块 --- --- url: /en/official/Reference/VBA/Interaction/Partition.md --- # Partition Returns a **Variant** (**String**) labelling which of a series of equal-width numeric ranges a value falls into. Syntax: **Partition(** *number* **,** *start* **,** *stop* **,** *interval* **)** *number* : *required* The value to evaluate against the ranges. *start* : *required* The number that begins the overall range. May not be less than 0. *stop* : *required* The number that ends the overall range. May not be less than or equal to *start*. *interval* : *required* The width of each individual range. May not be less than 1. The return value identifies the particular range in which *number* falls, formatted as `"<lowervalue>: <uppervalue>"`. **Partition** is most useful in queries --- for example, an SQL `SELECT` that groups orders by freight-cost band. The following table shows how the ranges are determined for three sample sets of *start*, *stop*, and *interval*. The *Before First* column is what **Partition** returns for a *number* below *start*; the *After Last* column is what it returns for a *number* above *stop*. | *start* | *stop* | *interval* | Before First | First Range | Last Range | After Last | |--------:|-------:|-----------:|:-------------|:------------|:-----------|:-----------| | 0 | 99 | 5 | `" :-1"` | `" 0: 4"` | `" 95: 99"`| `" 100: "` | | 20 | 199 | 10 | `" : 19"` | `" 20: 29"`| `" 190:199"`| `" 200: "` | | 100 | 1010 | 20 | `" : 99"` | `" 100: 119"`| `"1000:1010"`| `"1011: "` | In the third row, *start* and *stop* don't divide evenly by *interval*: the last range extends to *stop* (covering 11 numbers) even though *interval* is 20. If necessary, **Partition** pads each end of the range with leading spaces so that there are the same number of characters to the left and right of the colon as there are characters in *stop*, plus one. This keeps the labels in the right order under a plain text sort. If *interval* is 1, the range collapses to *number:number*, regardless of *start* and *stop*. Any argument may be a decimal value, but is rounded to the nearest even integer before processing. If any argument is **Null**, **Partition** returns **Null**. ### Example This example uses **Partition** in an SQL `SELECT` to count the orders whose freight cost falls into each of several ranges. With *start* = 0, *stop* = 500, *interval* = 50, the first range is `" 0: 49"`, and so on up to 500. ```sql SELECT DISTINCTROW Partition([Freight], 0, 500, 50) AS Range, Count(Orders.Freight) AS [Count] FROM Orders GROUP BY Partition([Freight], 0, 500, 50); ``` --- --- url: /zh/official/Reference/VBA/Interaction/Partition.md --- # Partition 返回一个**Variant**(**String**),标记某个值落入一系列等宽数值范围中的哪一个。 语法:**Partition(** *number* **,** *start* **,** *stop* **,** *interval* **)** *number* : *必需* 要针对范围评估的值。 *start* : *必需* 开始整体范围的数字。不得小于0。 *stop* : *必需* 结束整体范围的数字。不得小于或等于*start*。 *interval* : *必需* 每个单独范围的宽度。不得小于1。 返回值标识*number*落入的特定范围,格式为`"<lowervalue>: <uppervalue>"`。**Partition**在查询中最有用——例如按运费成本区间分组订单的SQL `SELECT`。 下表显示了三组*start*、*stop*和*interval*的示例范围确定方式。*Before First*列是**Partition**对*number*低于*start*时返回的内容;*After Last*列是对*number*高于*stop*时返回的内容。 | *start* | *stop* | *interval* | Before First | First Range | Last Range | After Last | |--------:|-------:|-----------:|:-------------|:------------|:-----------|:-----------| | 0 | 99 | 5 | `" :-1"` | `" 0: 4"` | `" 95: 99"`| `" 100: "` | | 20 | 199 | 10 | `" : 19"` | `" 20: 29"`| `" 190:199"`| `" 200: "` | | 100 | 1010 | 20 | `" : 99"` | `" 100: 119"`| `"1000:1010"`| `"1011: "` | 在第三行中,*start*和*stop*不能被*interval*整除:最后一个范围扩展到*stop*(覆盖11个数字),即使*interval*为20。 如有必要,**Partition**在范围的每一端填充前导空格,使冒号左右两侧的字符数与*stop*中的字符数加一相同。这使标签在纯文本排序下保持正确顺序。 如果*interval*为1,范围折叠为*number:number*,无论*start*和*stop*如何。 任何参数都可以是十进制值,但在处理前四舍五入到最接近的偶数整数。如果任何参数为**Null**,**Partition**返回**Null**。 ### 示例 本示例在SQL `SELECT`中使用**Partition**统计运费落入每个范围的订单数量。*start* = 0,*stop* = 500,*interval* = 50,第一个范围为`" 0: 49"`,依此类推到500。 ```sql SELECT DISTINCTROW Partition([Freight], 0, 500, 50) AS Range, Count(Orders.Freight) AS [Count] FROM Orders GROUP BY Partition([Freight], 0, 500, 50); ``` --- --- url: /zh/official/Documentation/PDF-Generation.md --- # PDF 生成 两阶段PDF管线的内部机制:`tbdocs`阶段8组装稀疏的`_site-pdf/`源树,然后`book/render-book.mjs`通过无头Chromium + paged.js + pdf-lib将其渲染为`_pdf/twinBASIC Book.pdf`。在修改渲染器、打印样式表或paged.js包时阅读此页。 ## 数据流 ![PDF render pipeline](/assets/images/mmd/pdf-render-pipeline.svg) 两个阶段是解耦的:`tbdocs`构建`_site-pdf/`作为其正常运行的一部分;`render-book.mjs`仅在`book.bat`显式调用时运行。这使得`puppeteer`和`pdf-lib`(两者都很大)不进入站点生成器的依赖树。 ## 运行渲染器 ``` node book/render-book.mjs <input.html> -o <output.pdf> [--outline-tags h1,h2,h3,h4] [-t <timeout-ms>] [--additional-script <path>]... ``` | 标志 | 默认值 | 描述 | |---|---|---| | `<input.html>` | 必需 | 已组装HTML文件的路径(通常为`_site-pdf/book.html`)。 | | `-o` / `--output` | 必需 | 目标PDF路径。 | | `--outline-tags` | `h1,h2,h3,h4` | 逗号分隔的标题标签,用于包含在PDF书签树中。 | | `-t` / `--timeout` | `0`(禁用) | 每次操作的puppeteer超时时间(毫秒)。 | | `--additional-script` | — | 在paged.js包之后注入额外的页面内脚本。可重复使用。 | `book.bat`运行标准的生产调用: ```batch node ..\book\render-book.mjs _site-pdf\book.html -o "_pdf\twinBASIC Book.pdf" ^ --outline-tags h1,h2,h3,h4 ^ --additional-script ..\perf\detach-pages.js ``` 始终先运行`build.bat`以填充`_site-pdf/`。 ## render-book.mjs `book/render-book.mjs`驱动三个阶段。其辅助模块位于`book/lib/`。 ### 阶段1:渲染 打开无头Chromium实例,在`file://`下加载`book.html`,并调用`PagedPolyfill.preview()`运行CSS Paged Media排版引擎。返回时,DOM中包含每个`.pagedjs_page`元素,对应一个输出PDF页面。 **Chromium启动标志:** | 标志 | 原因 | |---|---| | `--allow-file-access-from-files` | paged.js通过XHR从`file://` URL获取`print.css`。没有此标志Chrome会拒绝请求。 | | `--disable-gpu` + `--disable-software-rasterizer` | 将GPU进程从约100MB缩减到约16MB,并让Skia跳过GPU初始化路径,从而为生成阶段节省约5秒。 | 在`page.goto()`之后、加载任何脚本之前,驱动程序注入: ```js window.PagedConfig = { auto: false }; ``` 这阻止paged.js在包加载时自动运行。然后通过`page.addScriptTag()`按顺序注入脚本: 1. `lib/paged.browser.js` --- paged.js CSS Paged Media polyfill。 2. `lib/progress-handler.js` --- 注册一个处理器,在每页排版完成后将`[render-progress] page=N elapsed=Xs`记录到浏览器控制台。 3. 任何`--additional-script`路径(生产环境添加`perf/detach-pages.js`)。 接下来通过`page.evaluate()`调用`PagedPolyfill.preview()`。在vendor包中,该调用是完全同步的;`page.evaluate()`上的`await`仅仅是puppeteer将结果带回Node所需的CDP往返。 `perf/detach-pages.js`实现了激进分离优化:在每个页面排版完成后立即从DOM中物理移除该页面,然后在`afterRendered`时按顺序恢复所有页面。这使得`getBoundingClientRect`(paged.js对每页调用)保持在约0.7毫秒/页的平缓速度,而不是在1638页的书中以约8毫秒/页的速度增长。CSS计数器在分离页面间会断裂,因此`print.css`使用`var(--page-num)`(paged.js为每页写入的自定义属性)而不是`counter(page)`来生成页码。 ### 阶段2:生成 提取文档元数据并构建大纲树,然后调用`page.pdf()`从Chromium内部写入器生成原始PDF。 **元数据提取**通过`page.evaluate()`返回: ```js { title: string, // <title> text content lang: string, // <html lang="..."> value [name]: string, // one entry per <meta name="..."> tag } ``` **大纲提取**通过`parseOutline(page, outlineTags)`(参见[`outline.mjs`](#outlinemjs))返回嵌套的`OutlineNode[]`树。 **PDF生成**通过`page.pdf()`: ```js page.pdf({ printBackground: true, displayHeaderFooter: false, preferCSSPageSize: true, // use the A4 size from print.css @page rules margin: { top: 0, right: 0, bottom: 0, left: 0 }, }) ``` `preferCSSPageSize: true`使Chromium使用`print.css`中声明的尺寸,而非硬编码的默认值。该调用在返回之前在内部缓冲整个文档——没有中间进度信号。在约50秒的调用运行期间,一个500毫秒的心跳在TTY上向stdout写入已用时间计数器。 ### 阶段3:处理 用书签树和文档元数据增强Chromium的原始PDF,然后保存最终输出。 `page.pdf()`的原始缓冲区是有效但最小的PDF:没有`/Outlines`条目,并带有Chromium的默认元数据。处理阶段按顺序运行四个操作: 1. **`measureRawPdf(rawPdf)`** --- 遍历原始字节而不分配任何对象。返回`dictSlots`和`arraySlots`计数,用于在加载前预调整两个shim后备数组的大小(参见[`measure-pass.mjs`](#measure-passmjs))。 2. **`PDFDocument.load(rawPdf)`** --- 将原始PDF解析为pdf-lib的内存模型。fast-\* shim(参见[pdf-lib补丁](/official/Documentation/Fixes-PDFLib))已从import块激活;此调用使用其优化的数据结构。 3. **`setMetadata(pdfDoc, meta)`**和**`setOutline(pdfDoc, outline)`** --- 将`/Info`字典和`/Outlines`树写入文档(参见[`postprocesser.mjs`](#postprocessermjs)和[`outline.mjs`](#outlinemjs))。 4. **`parallelSave(pdfDoc, { objectsPerStream: 500 })`** --- 将修改后的文档序列化为字节,在libuv线程池上并行运行deflate(参见[`parallel-deflate.mjs`](#parallel-deflatemjs))。 ## lib/ 引用 ### outline.mjs 两个导出:`parseOutline`在浏览器中通过puppeteer运行;`setOutline`在Node中对pdf-lib文档运行。 **`parseOutline(page, tags)`** --- 查询`document.querySelectorAll(tags.join(','))`,按文档顺序遍历结果,并构建嵌套树。每个节点: ```js // OutlineNode { title: string, // heading innerText, HTML-stripped destination: string, // percent-encoded heading id (# → #25) children: OutlineNode[], closed?: true, // present when the heading or its ancestor // article carries data-pdf-bookmark-closed } ``` 该函数还在`<body>`之前为每个标题注入一个包含`<a href="#id">`链接的隐藏`<div>`。没有这些链接,Chromium的PDF写入器不会注册命名目标,因此大纲中的`/Dest`条目将无处解析。 `closed`节点在PDF `/Outlines`树中产生负的`/Count`,PDF阅读器使用它来显示折叠的书签。 **`setOutline(pdfDoc, outline, enableWarnings?)`** --- 通过`pdfDoc.context.nextRef()`为每个大纲节点分配PDF引用,每个节点写入一个链接的`PDFDict`,并将`pdfDoc.catalog.Outlines`设置为根引用。每个节点的`Dest`是一个PDF名称,Chromium的`/Dests`目录将其映射到页码和坐标。 ### postprocesser.mjs **`setMetadata(pdfDoc, meta)`** --- 从阶段2收集的元数据对象写入标准`/Info`字典条目。始终将`ModDate`设置为当前时间。在从Chromium继承的`Creator`字符串后追加`" + Paged.js"`,并保留Chromium的`"Skia/PDF mXX"` `Producer`字符串。 **`setTrimBoxes(pdfDoc, pages)`** --- 从`PagedPolyfill`暴露的框数据设置每页的`/TrimBox`条目。在生产管线中未被调用(页面没有出血区域),但对于带裁切标记的印刷就绪输出可用。 ### measure-pass.mjs **`measure(bytes)`** --- 对原始PDF缓冲区的无分配字节遍历器。解析PDF语法(间接对象、字典、数组、流、嵌入的ObjStm)而不实例化任何PDFObject。返回: ```js { indirectObjects: number, dicts: number, dictSlots: number, // total key + value slots across all dicts arrays: number, arraySlots: number, // total element slots across all arrays refs: number, names: number, numbers: number, strings: number, hexStrings: number, streams: number, objStms: number, objStmInner: number, maxDictSlots: number, maxArraySlots: number, maxRecursion: number, totalStreamBytes: number, totalInflatedBytes: number, } ``` `dictSlots`和`arraySlots`驱动fast-dict-onebuf和fast-array-onebuf shim上的`setExpectedDictSlots()`和`setExpectedArraySlots()`。在`PDFDocument.load()`之前调用这些函数可以让每个shim预分配其后备数组到测量大小,从而消除解析期间V8的增长调整大小。 内部的`Measurer`类在深度索引的`Int32Array` / `Uint8Array`栈上保持每字典状态(`/Length`、`/Type`、`/N`、`/First`),而非每对象的堆记录。栈深度为64;在书上观察到的最大深度为4。 ### parallel-deflate.mjs **`parallelSave(pdfDoc, opts?)`** --- `pdfDoc.save({ useObjectStreams: true })`的替代品。运行与`PDFDocument.save()`相同的预序列化步骤(`flush`、`updateFieldAppearances`),然后调用自定义的`ParallelStreamWriter`,将保存分为三个阶段: 1. **分类** --- 与pdf-lib的`PDFStreamWriter.computeBufferSize`逻辑相同。将间接对象分为`uncompressedObjects`(PDF流、加密引用、生成号≠0)和`compressedChunks`(其余所有内容,按`objectsPerStream`分块)。 2. **并行deflate** --- 实例化所有`PDFObjectStream`对象,然后触发`Promise.all(streams.map(s => deflateAsync(s.getUnencodedContents())))`。每个deflate在libuv线程池上运行。结果直接写入每个流的`contentsCache.value`,因此阶段3只发现缓存命中。 3. **大小计算与输出** --- 与上游相同。每次`computeIndirectObjectSize`调用都是阶段2的缓存命中。xref流(依赖于阶段3中固定的字节偏移量)在其内容最终确定后立即通过`deflateSync`同步deflate。 默认选项及其生产值: ```js { objectsPerStream: 50, // production: 500 encodeStreams: true, parallel: true, addDefaultPage: true, updateFieldAppearances: true, } ``` `objectsPerStream: 500`(生产值)产生的PDF比pdf-lib默认值50小约5%,因为更大的deflate窗口能捕获分组对象间更多的重复字符串。 返回`{ bytes: Uint8Array, streamCount: number }`。 ### progress-handler.js 一个最小的浏览器内脚本,注册一个`Paged.Handler`子类,带有一个钩子: ```js class ProgressHandler extends Paged.Handler { afterPageLayout(_pageElement, _page, _breakToken) { this.count++; const elapsed = ((performance.now() - start) / 1000).toFixed(1); console.log(`[render-progress] page=${this.count} elapsed=${elapsed}`); } } Paged.registerHandlers(ProgressHandler); ``` `render-book.mjs`通过`page.on('console', ...)`拦截这些控制台消息,并在TTY上向stdout写入`\r`覆盖的进度行,在stdout被管道传输时每100页写一行。 ## paged.browser.js `book/lib/paged.browser.js`是[Paged.js](https://pagedjs.org/) v0.4.3(MIT)的vendor包副本,带有少量补丁。Paged.js是CSS Paged Media polyfill:它从链接的样式表中读取`@page`规则,将文档分割为离散的DOM页面,解析CSS计数器,并将`string-set`声明中的运行页眉和页脚复制到每页的边距框中。然后Chromium将结果DOM渲染为PDF。 ### 全局API 两个全局变量控制polyfill: **`window.PagedConfig`** --- 加载时读取的配置对象。 | 键 | 类型 | 描述 | |---|---|---| | `auto` | `boolean` | 当为`false`时,paged.js在包加载时不会自动运行。驱动程序在注入包之前设置此项。 | **`window.PagedPolyfill`** --- 主polyfill对象,在包加载后可用。 | 成员 | 描述 | |---|---| | `PagedPolyfill.preview()` | 运行完整排版管线。在vendor包中这是完全同步的。 | ### 处理程序系统 Paged.js提供了用于观察和拦截排版过程的插件API。处理程序是扩展`Paged.Handler`并通过`Paged.registerHandlers()`在`preview()`调用之前注册的类。 ```js class MyHandler extends Paged.Handler { constructor(chunker, polisher, caller) { super(chunker, polisher, caller); } afterPageLayout(pageElement, page, breakToken) { // fires after each page is fully laid out } } Paged.registerHandlers(MyHandler); ``` 关键生命周期钩子(均可选覆盖): | 钩子 | 签名 | 触发时机 | |---|---|---| | `beforeParsed` | `(content)` | 在源文档被处理之前。 | | `afterParsed` | `(parsed)` | 在源文档处理完成后、排版开始之前。 | | `beforePageLayout` | `(page)` | 在新页面排版之前。 | | `afterPageLayout` | `(pageElement, page, breakToken)` | 在每页完全排版后。`pageElement`是`.pagedjs_page` DOM节点;`breakToken`携带下一页开始的位置。 | | `finalizePage` | `(pageElement, page, breakToken)` | 在页面最终确定后。调用时间略晚于`afterPageLayout`;`detach-pages.js`使用它从DOM中移除前一页。 | | `afterRendered` | `(pages)` | 在所有页面渲染完成后、`page.pdf()`运行之前。`detach-pages.js`使用它按文档顺序恢复页面。 | ### DOM输出 `preview()`完成后,文档包含: * 一个添加到`<body>`的`.pagedjs_pages`容器,包裹所有页面。 * 每个输出PDF页面对应一个`.pagedjs_page`。每个页面包含`.pagedjs_area > .pagedjs_content`,其中是切片后的章节内容。 * 从`@page`边距规则(`@top-right`、`@bottom-right`等)渲染的边距框,承载`string-set`跟踪的运行页眉和页脚页码。 `render-book.mjs`在`preview()`之后读取页面计数: ```js document.querySelectorAll('.pagedjs_pages > .pagedjs_page').length ``` ### 同步渲染 在上游paged.js中,排版过程每100个对象就让出一次浏览器事件循环。vendor包移除了这些让出门控,使`preview()`成为单一的同步调用。由于渲染器运行在无头Chromium内部,浏览器响应性无关紧要,因此这是安全的。 驱动程序中的`await page.evaluate(...)`包装是puppeteer对CDP往返的要求——并不表示`preview()`是异步的。CDP响应仅在Chromium内部的同步执行完全完成后才到达。 ### CSS互操作 Paged.js通过XHR获取链接的样式表以提取`@page`规则。在`file://`下,Chrome会阻止此操作,除非在启动时向Chromium传递`--allow-file-access-from-files`。 paged.js处理的`docs/assets/css/print.css`中的关键`@page`规则: | 规则 | 效果 | |---|---| | `@page { size: A4; margin: 22mm; }` | 基础页面尺寸和边距。 | | `@page { @bottom-right { content: string(part-title) " - " var(--page-num); } }` | 页脚:部分名称和页码。 | | `@page { @top-right { content: string(chapter-title); } }` | 运行页眉:当前章节标题。 | `string(chapter-title)`由每个`<article class="page">`开头的隐藏`.header-string` `<span>`填充,其中`print.css`设置`string-set: chapter-title content(text)`。`var(--page-num)`是paged.js在排版期间写入每个`.pagedjs_page`元素的CSS自定义属性;`counter(page)`才是自然选择,但当`detach-pages.js`从DOM中移除已最终确定的页面时会断裂,因此改用自定义属性。 ## 另见 * [Book配置](/official/Documentation/Book-Configuration) --- 控制`book.html`内容的`_book.yml`清单。 * [管线阶段](/official/Documentation/Pipeline-Stages) --- 阶段8的`pdf.mjs`和`book.mjs`接口约定。 * [tbdocs构建器](/official/Documentation/Builder) --- tbdocs管线中阶段8的设计理念。 * [pdf-lib补丁](/official/Documentation/Fixes-PDFLib) --- 每个`fast-*.mjs` shim的详细描述:上游问题、修复和机制。 * [Paged.js补丁](/official/Documentation/Fixes-PagedJS) --- 对`paged.browser.js`每个补丁的详细描述。 > AI生成 --- --- url: /en/official/Documentation/PDF-Generation.md --- # PDF Generation Internals of the two-stage PDF pipeline: `tbdocs` Phase 8 assembles a sparse `_site-pdf/` source tree, then `book/render-book.mjs` renders it into `_pdf/twinBASIC Book.pdf` via headless Chromium + paged.js + pdf-lib. Read this when modifying the renderer, the print stylesheet, or the paged.js bundle. ## Data flow ![PDF render pipeline](/assets/images/mmd/pdf-render-pipeline.svg) The two stages are decoupled: `tbdocs` builds `_site-pdf/` as part of its normal run; `render-book.mjs` runs only when `book.bat` calls it explicitly. This keeps `puppeteer` and `pdf-lib` --- both large --- out of the site generator's dependency tree. ## Running the renderer ``` node book/render-book.mjs <input.html> -o <output.pdf> [--outline-tags h1,h2,h3,h4] [-t <timeout-ms>] [--additional-script <path>]... ``` | Flag | Default | Description | | --------------------- | -------------- | --------------------------------------------------------------------- | | `<input.html>` | required | Path to the assembled HTML file (usually `_site-pdf/book.html`). | | `-o` / `--output` | required | Destination PDF path. | | `--outline-tags` | `h1,h2,h3,h4` | Comma-separated heading tags to include in the PDF bookmark tree. | | `-t` / `--timeout` | `0` (disabled) | Per-operation puppeteer timeout in milliseconds. | | `--additional-script` | — | Inject an extra in-page script after the paged.js bundle. Repeatable. | `book.bat` runs the standard production invocation: ```batch node ..\book\render-book.mjs _site-pdf\book.html -o "_pdf\twinBASIC Book.pdf" ^ --outline-tags h1,h2,h3,h4 ^ --additional-script ..\perf\detach-pages.js ``` Always run `build.bat` first to populate `_site-pdf/`. ## render-book.mjs `book/render-book.mjs` drives the three phases. Its helpers live in `book/lib/`. ### Phase 1: Render Opens a headless Chromium instance, loads `book.html` under `file://`, and calls `PagedPolyfill.preview()` to run the CSS Paged Media layout engine. When it returns, the DOM contains one `.pagedjs_page` element per output PDF page. **Chromium launch flags:** | Flag | Why | | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `--allow-file-access-from-files` | paged.js fetches `print.css` via XHR from a `file://` URL. Without this flag Chrome rejects the request. | | `--disable-gpu` + `--disable-software-rasterizer` | Shrinks the GPU process from ~100 MB to ~16 MB and cuts ~5 s off the generate phase by letting Skia skip a GPU init path. | After `page.goto()` and before loading any scripts, the driver injects: ```js window.PagedConfig = { auto: false }; ``` This prevents paged.js from running automatically when the bundle loads. Then it injects scripts in order via `page.addScriptTag()`: 1. `lib/paged.browser.js` --- the paged.js CSS Paged Media polyfill. 2. `lib/progress-handler.js` --- registers a handler that logs `[render-progress] page=N elapsed=Xs` to the browser console after each page is laid out. 3. Any `--additional-script` paths (production adds `perf/detach-pages.js`). `PagedPolyfill.preview()` is called next via `page.evaluate()`. In the vendored bundle the call is fully synchronous; the `await` on `page.evaluate()` is just the CDP round-trip puppeteer needs to bring the result back to Node. `perf/detach-pages.js` implements the aggressive-detach optimisation: it physically removes each finalised page from the DOM immediately after layout, then restores all pages in order at `afterRendered`. This keeps `getBoundingClientRect` (which paged.js calls per page) at ~0.7 ms/page flat instead of growing at ~8 ms/page on a 1638-page book. CSS counters break across detached pages, so `print.css` uses `var(--page-num)` (a custom property paged.js writes per page) rather than `counter(page)` for running page numbers. ### Phase 2: Generate Extracts document metadata and builds the outline tree, then calls `page.pdf()` to generate the raw PDF from Chromium's internal writer. **Meta extraction** via `page.evaluate()` returns: ```js { title: string, // <title> text content lang: string, // <html lang="..."> value [name]: string, // one entry per <meta name="..."> tag } ``` **Outline extraction** via `parseOutline(page, outlineTags)` (see [`outline.mjs`](#outlinemjs)) returns a nested `OutlineNode[]` tree. **PDF generation** via `page.pdf()`: ```js page.pdf({ printBackground: true, displayHeaderFooter: false, preferCSSPageSize: true, // use the A4 size from print.css @page rules margin: { top: 0, right: 0, bottom: 0, left: 0 }, }); ``` `preferCSSPageSize: true` makes Chromium use the dimensions declared in `print.css` rather than a hardcoded default. The call buffers the entire document internally before returning --- there is no intermediate progress signal. A 500 ms heartbeat writes an elapsed counter to stdout on TTYs while the ~50 s call runs. ### Phase 3: Process Augments the raw PDF from Chromium with a bookmark tree and document metadata, then saves the final output. The raw buffer from `page.pdf()` is a valid but minimal PDF: it has no `/Outlines` entry and carries Chromium's default metadata. The process phase runs four operations in sequence: 1. **`measureRawPdf(rawPdf)`** --- traverses the raw bytes without allocating any objects. Returns `dictSlots` and `arraySlots` counts used to pre-size two shim backing arrays before the load (see [`measure-pass.mjs`](#measure-passmjs)). 2. **`PDFDocument.load(rawPdf)`** --- parses the raw PDF into pdf-lib's in-memory model. The fast-\* shims (see [pdf-lib Patches](/en/official/Documentation/Fixes-PDFLib)) are already active from the import block; this call uses their optimised data structures. 3. **`setMetadata(pdfDoc, meta)`** and **`setOutline(pdfDoc, outline)`** --- write the `/Info` dict and the `/Outlines` tree into the document (see [`postprocesser.mjs`](#postprocessermjs) and [`outline.mjs`](#outlinemjs)). 4. **`parallelSave(pdfDoc, { objectsPerStream: 500 })`** --- serialises the modified document to bytes, running deflate concurrently on libuv's thread pool (see [`parallel-deflate.mjs`](#parallel-deflatemjs)). ## lib/ reference ### outline.mjs Two exports: `parseOutline` runs inside the browser via puppeteer; `setOutline` runs in Node against a pdf-lib document. **`parseOutline(page, tags)`** --- queries `document.querySelectorAll(tags.join(','))`, traverses the results in document order, and builds a nested tree. Each node: ```js // OutlineNode { title: string, // heading innerText, HTML-stripped destination: string, // percent-encoded heading id (# → #25) children: OutlineNode[], closed?: true, // present when the heading or its ancestor // article carries data-pdf-bookmark-closed } ``` The function also injects a hidden `<div>` of `<a href="#id">` links before `<body>` for every heading. Without these, Chromium's PDF writer does not register named destinations, so the `/Dest` entries in the outline would resolve nowhere. `closed` nodes produce a negative `/Count` in the PDF `/Outlines` tree, which PDF readers use to display the bookmark collapsed. **`setOutline(pdfDoc, outline, enableWarnings?)`** --- allocates a PDF reference for each outline node via `pdfDoc.context.nextRef()`, writes a linked `PDFDict` per node, and sets `pdfDoc.catalog.Outlines` to the root reference. Each node's `Dest` is a PDF name that Chromium's `/Dests` catalog maps to a page number and coordinates. ### postprocesser.mjs **`setMetadata(pdfDoc, meta)`** --- writes standard `/Info` dict entries from the meta object collected in Phase 2. Always sets `ModDate` to the current time. Appends `" + Paged.js"` to the `Creator` string inherited from Chromium and retains Chromium's `"Skia/PDF mXX"` `Producer` string. **`setTrimBoxes(pdfDoc, pages)`** --- sets per-page `/TrimBox` entries from the box data `PagedPolyfill` exposes. Not called in the production pipeline (pages have no bleed), but available for print-ready output with crop marks. ### measure-pass.mjs **`measure(bytes)`** --- a no-allocate byte walker over a raw PDF buffer. Parses the PDF grammar (indirect objects, dicts, arrays, streams, embedded ObjStms) without instantiating any PDFObject. Returns: ```js { indirectObjects: number, dicts: number, dictSlots: number, // total key + value slots across all dicts arrays: number, arraySlots: number, // total element slots across all arrays refs: number, names: number, numbers: number, strings: number, hexStrings: number, streams: number, objStms: number, objStmInner: number, maxDictSlots: number, maxArraySlots: number, maxRecursion: number, totalStreamBytes: number, totalInflatedBytes: number, } ``` `dictSlots` and `arraySlots` drive `setExpectedDictSlots()` and `setExpectedArraySlots()` on the fast-dict-onebuf and fast-array-onebuf shims. Calling these before `PDFDocument.load()` lets each shim pre-allocate its backing array to the measured size, eliminating V8 growth resizes during parse. The internal `Measurer` class keeps per-dict state (`/Length`, `/Type`, `/N`, `/First`) on depth-indexed `Int32Array` / `Uint8Array` stacks rather than per-object heap records. Stack depth is 64; maximum observed on the book is 4. ### parallel-deflate.mjs **`parallelSave(pdfDoc, opts?)`** --- replacement for `pdfDoc.save({ useObjectStreams: true })`. Runs the same pre-serialize steps as `PDFDocument.save()` (`flush`, `updateFieldAppearances`), then invokes a custom `ParallelStreamWriter` that splits the save into three phases: 1. **Classify** --- same logic as pdf-lib's `PDFStreamWriter.computeBufferSize`. Partitions indirect objects into `uncompressedObjects` (PDF streams, encrypted refs, gen-number ≠ 0) and `compressedChunks` (everything else, grouped into chunks of `objectsPerStream`). 2. **Parallel deflate** --- instantiates all `PDFObjectStream` objects, then fires `Promise.all(streams.map(s => deflateAsync(s.getUnencodedContents())))`. Each deflate runs on libuv's thread pool. Results are written directly into each stream's `contentsCache.value` so Phase 3 finds only cache hits. 3. **Size and emit** --- same as upstream. Every `computeIndirectObjectSize` call is a Phase 2 cache hit. The xref stream (which depends on byte offsets pinned in Phase 3) is deflated synchronously via `deflateSync` immediately after its content is finalised. Default options and their production values: ```js { objectsPerStream: 50, // production: 500 encodeStreams: true, parallel: true, addDefaultPage: true, updateFieldAppearances: true, } ``` `objectsPerStream: 500` (the production value) produces ~5% smaller PDFs than the pdf-lib default of 50 because a larger deflate window captures more repeated strings across grouped objects. Returns `{ bytes: Uint8Array, streamCount: number }`. ### progress-handler.js A minimal in-browser script that registers a `Paged.Handler` subclass with one hook: ```js class ProgressHandler extends Paged.Handler { afterPageLayout(_pageElement, _page, _breakToken) { this.count++; const elapsed = ((performance.now() - start) / 1000).toFixed(1); console.log(`[render-progress] page=${this.count} elapsed=${elapsed}`); } } Paged.registerHandlers(ProgressHandler); ``` `render-book.mjs` intercepts these console messages via `page.on('console', ...)` and writes a `\r`-overwriting progress line to stdout on TTYs, or one line per 100 pages when stdout is piped. ## paged.browser.js `book/lib/paged.browser.js` is a vendored, lightly patched copy of [Paged.js](https://pagedjs.org/) v0.4.3 (MIT). Paged.js is a CSS Paged Media polyfill: it reads `@page` rules from the linked stylesheet, breaks the document into discrete DOM pages, resolves CSS counters, and copies running headers and footers from `string-set` declarations into each page's margin boxes. Chromium then renders the resulting DOM into a PDF. ### Global API Two globals control the polyfill: **`window.PagedConfig`** --- configuration object read at load time. | Key | Type | Description | | ------ | --------- | -------------------------------------------------------------------------------------------------------------------------- | | `auto` | `boolean` | When `false`, paged.js does not run automatically when the bundle loads. The driver sets this before injecting the bundle. | **`window.PagedPolyfill`** --- the main polyfill object, available after the bundle loads. | Member | Description | | ------------------------- | -------------------------------------------------------------------------------- | | `PagedPolyfill.preview()` | Runs the full layout pipeline. In the vendored bundle this is fully synchronous. | ### Handler system Paged.js provides a plugin API for observing and intercepting the layout process. A handler is a class that extends `Paged.Handler` and is registered via `Paged.registerHandlers()` before `preview()` is called. ```js class MyHandler extends Paged.Handler { constructor(chunker, polisher, caller) { super(chunker, polisher, caller); } afterPageLayout(pageElement, page, breakToken) { // fires after each page is fully laid out } } Paged.registerHandlers(MyHandler); ``` Key lifecycle hooks (all optional overrides): | Hook | Signature | When it fires | | ------------------ | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `beforeParsed` | `(content)` | Before the source document is processed. | | `afterParsed` | `(parsed)` | After the source document has been processed, before layout begins. | | `beforePageLayout` | `(page)` | Before a new page is laid out. | | `afterPageLayout` | `(pageElement, page, breakToken)` | After each page is fully laid out. `pageElement` is the `.pagedjs_page` DOM node; `breakToken` carries the position where the next page starts. | | `finalizePage` | `(pageElement, page, breakToken)` | After a page is finalised. Called slightly later than `afterPageLayout`; used by `detach-pages.js` to remove the previous page from the DOM. | | `afterRendered` | `(pages)` | After all pages have been rendered, before `page.pdf()` runs. Used by `detach-pages.js` to restore pages in document order. | ### DOM output After `preview()` completes, the document contains: * A `.pagedjs_pages` container added to `<body>`, wrapping all pages. * One `.pagedjs_page` per output PDF page. Each page contains `.pagedjs_area > .pagedjs_content` with the sliced chapter content. * Margin boxes rendered from `@page` margin rules (`@top-right`, `@bottom-right`, etc.) carrying `string-set`-tracked running headers and footer page numbers. `render-book.mjs` reads the page count after `preview()`: ```js document.querySelectorAll(".pagedjs_pages > .pagedjs_page").length; ``` ### Synchronous rendering In upstream paged.js, the layout process yields to the browser event loop every 100 objects. The vendored bundle removes these yield gates, making `preview()` a single synchronous call. Since the renderer runs inside headless Chromium where browser responsiveness is irrelevant, this is safe. The `await page.evaluate(...)` wrapper in the driver is a puppeteer requirement for the CDP round-trip --- not a sign that `preview()` is async. The CDP response arrives only after the synchronous execution inside Chromium is fully complete. ### CSS interop Paged.js fetches the linked stylesheet via XHR to extract `@page` rules. Under `file://`, Chrome blocks this unless `--allow-file-access-from-files` is passed to Chromium at launch. The key `@page` rules in `docs/assets/css/print.css` that paged.js acts on: | Rule | Effect | | -------------------------------------------------------------------------------- | -------------------------------------- | | `@page { size: A4; margin: 22mm; }` | Base page size and margins. | | `@page { @bottom-right { content: string(part-title) " - " var(--page-num); } }` | Footer: part name and page number. | | `@page { @top-right { content: string(chapter-title); } }` | Running header: current chapter title. | `string(chapter-title)` is populated by the hidden `.header-string` `<span>` at the start of each `<article class="page">`, where `print.css` sets `string-set: chapter-title content(text)`. `var(--page-num)` is a CSS custom property that paged.js writes to each `.pagedjs_page` element during layout; `counter(page)` would be the natural choice but breaks when `detach-pages.js` removes finalised pages from the DOM, so the custom property is used instead. ## See Also * [Book Configuration](/en/official/Documentation/Book-Configuration) -- the `_book.yml` manifest that controls what goes into `book.html`. * [Pipeline Stages](/en/official/Documentation/Pipeline-Stages) -- the `pdf.mjs` and `book.mjs` interface contracts for Phase 8. * [tbdocs Builder](/en/official/Documentation/Builder) -- design rationale for Phase 8 in the tbdocs pipeline. * [pdf-lib Patches](/en/official/Documentation/Fixes-PDFLib) -- detailed description of each `fast-*.mjs` shim: upstream problem, fix, and mechanism. * [Paged.js Patches](/en/official/Documentation/Fixes-PagedJS) -- detailed description of every patch to `paged.browser.js`. --- --- url: /zh/official/Documentation/Fixes-PDFLib.md --- # pdf-lib 补丁 `book/lib/fast-*.mjs` 和 `book/lib/parallel-deflate.mjs` 下的文件是修补 pdf-lib 运行时导出的副作用 ES 模块。所有模块都在 `render-book.mjs` 顶部导入,在任何 pdf-lib 操作运行之前;它们相互兼容且幂等(每个模块通过修补原型或模块上的标志保护其安装)。它们共同将处理阶段 --- 解析 Chromium 的原始 PDF 输出、添加书签和元数据、序列化结果 --- 从约 40 秒减少到约 1.6 秒(1651 页书籍)。 所有这些补丁的根本原因相同:pdf-lib 设计用于浏览器和 Node 中的通用场景,并针对通用性而非单一大文档的吞吐量进行优化。 ## fast-refs-class.mjs **问题。** `PDFRef.of(objectNumber, generationNumber)` 是 PDF 中每个间接引用的工厂。原始工厂通过 `Object.create(PDFRef.prototype)` 后跟单独的属性写入来构建实例。V8 将以这种方式构建的对象视为通过中间隐藏类映射进行转换,每个写入产生一个过渡,产生的实例大约是通过 `new` 构建的实例大小的两倍。在书籍上测量:上游路径每个实例约 60 字节。有约 226,000 个唯一间接引用,即约 13.5 MB 的额外堆。此外,没有池:每次调用 `PDFRef.of(N, 0)` 即使对于之前见过的对象编号也会分配新实例。 **修复。** 两个构造函数:`_FastRef`(gen=0)和 `_FastRefGen`(gen≠0),两者的 `prototype` 都别名为 `PDFRef.prototype`。V8 从第一个实例为每个分配稳定的隐藏类。`_FastRef` 仅携带 `objectNumber`;`generationNumber` 作为原型数据属性默认值 `0` 提供,因此 gen=0 实例只需一个内联槽(每个实例约 16 字节,从约 60 字节降低)。gen=0 实例缓存在以 `objectNumber` 索引的密集 `pool0` Array 中;gen≠0 实例使用以 `"N M"` 字符串为键的 `Map`(极其罕见:仅 Chromium 发出的 PDF 中对象 0 处的空闲条目)。热原型方法 `toString`、`sizeInBytes` 和 `copyBytesInto` 被重写,将 `objectNumber` 和 `generationNumber` 作为普通数据属性读取,而非通过每个实例上存储的原始 `tag` 字符串。 ## fast-inflate.mjs **问题。** `PDFCrossRefStreamParser` 使用 `pako.inflate()` 解压 PDF 的交叉引用流,这是纯 JavaScript 的 zlib 实现。Node 提供了由原生 zlib C 库支持的 `zlib.inflateSync`,速度显著更快。交叉引用流在每个 `PDFDocument.load` 调用中精确解压一次,因此绝对墙钟时间的节省很小,但这是 `parallel-deflate.mjs` 接管 deflate 侧后最后一个对 pako 的调用,消除它使运行时 pako 调用计数归零。 **修复。** 修改运行时 `pako` 导出对象:用在不传选项时(pdf-lib 唯一的调用模式)委托给 `zlib.inflateSync` 的包装器替换 `pako.inflate`,对于传递选项的调用回退到原始 `pako.inflate`。PDF 的 `/FlateDecode` 编码(RFC 1950 zlib 帧)被两种实现接受,因此交换是字节兼容的。 **机制。** pdf-lib 在调用点惰性调用 `require("pako")` 而非在导入时捕获导出,因此修改模块导出对象上的运行时 `pako.inflate` 属性对调用点可见。 ## fast-parse-number.mjs **问题。** `BaseParser.parseRawNumber` 和 `BaseParser.parseRawInt` 通过一次一个字符追加到 JavaScript 字符串来构建数值(`value += charFromCode(byte)`),然后调用 `Number(value)` 将字符串转换回数字。PDF 中的每个数字 token --- 对象编号、生成编号、字节长度、坐标、字体大小、数组索引 --- 都流经这些路径之一。每次调用分配一个立即被丢弃的临时字符串。在书籍上这触发了数十万次。 **修复。** 直接整数累加器:`n = n * 10 + (byte - 0x30)`,每个字节消耗一次。`parseRawNumber` 另外用单独的累加器和 `scale` 除数处理小数部分。当整数部分超过 15 位(为病理输入保留 `Number.MAX_SAFE_INTEGER` 语义)或输入完全没有数字时,两种实现都回退到原始版本。 **机制。** `BaseParser` 未从 pdf-lib 的公共索引重新导出;它通过 `createRequire` 经 CJS 内部路径 `pdf-lib/cjs/core/parser/BaseParser.js` 导入。修改 `BaseParser.prototype` 影响所有子类:`PDFParser`、`PDFObjectParser`、`PDFObjectStreamParser` 和 `PDFXRefStreamParser`。 ## fast-decode-name.mjs **问题。** `PDFName.of(name)` 无条件地对每次调用调用 `decodeName(name)` --- 一个 `.replace(/#([\dABCDEF]{2})/g, ...)` 正则扫描 --- 以解码 `#XX` 十六进制转义序列。在书籍上,`PDFName.of` 被调用 2,759,635 次;恰好两个输入包含 `#`。正则扫描了 276 万个字符串只找到两个匹配,占处理阶段自耗时间约 168 ms(7%)。 **修复。** 一个以原始输入字符串为键的并行 `Map<string, PDFName>`。当输入不包含 `#`(通过 `indexOf` 检查)时,解码形式等于原始形式,因此映射键与 pdf-lib 内部池键匹配。缓存命中返回去重后的 `PDFName` 实例,无需正则工作。缓存未命中委托给原始 `PDFName.of`(运行一次正则,从 pdf-lib 自己的池返回规范实例);结果然后存储在快速缓存中。包含 `#` 的输入完全绕过缓存,保留原始解码语义。 ## fast-number-to-string.mjs **问题。** `numberToString(num)` --- 由 `PDFNumber` 等用于将数字序列化为 PDF 语法 --- 总是调用 `num.toString()` 两次:一次获取 `numStr`,第二次在指数表示法检查内部(`num.toString().split('e-')` 等)。指数表示法的情况仅在 `|num| < 1e-6` 或 `|num| >= 1e21` 时出现,这在真实 PDF 中都不会出现。每次调用都支付第二次 `toString()`、`split` 和 `parseInt` 的成本来确认指数检查无关。 **修复。** 计算一次 `numStr = String(num)` 并检查 `numStr.indexOf('e') === -1`。常见情况下立即返回 `numStr`。仅在 `'e'` 存在时走原始逻辑。 **机制。** pdf-lib 针对 tslib 1.x 编译,其 `__exportStar` 在模块求值时按值复制导出值而非按引用。当 `PDFNumber.js` 的 `index_1.numberToString(value)` 执行时,`index_1` 持有对原始函数的捕获引用。仅修补源模块对调用点不可见。垫片修补三个位置:`pdf-lib/cjs/utils/numbers.js`(源)、`pdf-lib/cjs/utils/index.js`(`PDFNumber` 读取的桶文件)和 `pdf-lib/cjs/index.js`(顶层公共索引)。 ## fast-size-in-bytes.mjs **问题。** `utils.sizeInBytes(n)` 通过调用 `Math.ceil(n.toString(2).length / 8)` 计算 PDF 交叉引用流字段中编码整数所需的字节数 --- 转换为二进制字符串、测量其长度、然后除法。它在每个 xref 条目上被调用三次(来自 `PDFCrossRefStream.computeMaxEntryByteWidths`),每本书约 50,000 个条目,每次调用分配一个临时二进制字符串。 **修复。** 无分配的短路阶梯: ```js if (n < 0x100) return 1; if (n < 0x10000) return 2; if (n < 0x1000000) return 3; if (n < 0x100000000) return 4; return 4 + Math.ceil((32 - Math.clz32(Math.floor(n / 0x100000000))) / 8); ``` 四字节情况覆盖所有 4 GB 以下的 PDF;回退处理更大的值而无需分配字符串。 **机制。** 与 `fast-number-to-string` 相同的 tslib 桶文件复制问题;在三个位置修补。 ## fast-dict-onebuf.mjs **问题。** 每个 `PDFDict` 实例在 `Map` 中保存其键值对。空 Map 承担约 200 字节的每实例开销,每个条目约 50 字节。在书籍上,`PDFDocument.load` 期间创建了约 260,000 个 `PDFDict` 实例。随着文档在解析期间增长,Map 反复将其内部哈希表存储空间翻倍并将每个之前的竞技场丢弃给 GC。 **修复。** 一个在文档生命周期内所有 `PDFDict` 实例共享的单个只追加 Array(`main`)。每个 `PDFDict` 携带一个编码整数(`d`),将 `start` 索引(23 位)和条目对 `length` 计数(16 位)打包到单个 JavaScript 数字中。`main[start..start+length]` 存放交替的键和值引用。添加新条目的修改在字典位于数组高水位标记时原地扩展其范围,否则首先将范围复制到尾部(写时复制)。`PDFCatalog`、`PDFPageTree` 和 `PDFPageLeaf` 共享相同的后备数组;`PDFPageLeaf` 的 `normalized` 和 `autoNormalizeCTM` 布尔值编码在 `d` 的两个备用位(第 23 和 24 位)中。`PDFObjectParser.parseDict` 使用每个解析器的临时数组作为递归帧栈,将每个完成的帧作为单个连续追加提交到 `main`。 `measure-pass.mjs` 的预遍计数原始 PDF 字节流中的总 `dictSlots`。在 `PDFDocument.load` 之前调用 `setExpectedDictSlots(n)` 通过 `main.length = n` 原地将 `main` 调整到精确所需的大小,消除解析期间的 V8 增长重新分配。使用原地调整大小而非替换模块级绑定;替换会使读取 `main` 的每个闭包中的 V8 内联缓存槽失效,导致解析时去优化峰值。 ## fast-parse-object.mjs **问题。** `PDFObjectParser.parseObject` 在读取当前 token 的第一个字节以按其类型分发之前,运行三个推测性 `matchKeyword` 调用 --- 检查 `true`、`false` 和 `null`。失败时的 `matchKeyword` 仍然消耗 `bytes.offset()` 读取、两次 `bytes.next()` 调用(前进和回退)以及一次比较。`true`/`false`/`null` 值在真实 PDF 中极其罕见;在书籍上,这三个调用在 `parseObject` 的几乎每次调用中都失败,而 `parseObject` 在每个 dict 值、数组元素和间接对象体上被调用一次。 **修复。** 先读取第一个字节,然后按字节值分发。数字、符号字符和句点进入 `parseNumberOrRef`;`<<` 进入 `parseDictOrStream`;`/` 进入 `parseName`;`[` 进入 `parseArray`;`(` 进入 `parseString`;单独的 `<` 进入 `parseHexString`。`true`/`false`/`null` 的 `matchKeyword` 调用仅在第一个字节分别为 `t`、`f` 或 `n` 时运行。未识别 token 的 `PDFObjectParsingError` 被保留。 ## fast-parse-name.mjs **问题。** `parseName` 从名称体的原始字节构建 JavaScript 字符串,通过 cons 链累加器一次一个字符,然后调用 `PDFName.of(string)` 获取规范实例。每次调用分配一个临时字符串(平均约 8 个字符),尽管 99.7% 的调用指向已在池中的名称(书籍上 4787 个唯一名称对 168 万次总调用)。 **修复。** `parseName` 前的字节哈希缓存。名称体字节被扫描以计算 Java 风格哈希(`hash = hash * 31 + byte`),同时推进字节游标 --- 此路径上不分配字符串。哈希在 `Map` 中查找;命中时,存储的 `Uint8Array` 键与当前缓冲区切片逐字节比较以确认相等(处理哈希冲突)。确认命中时,缓存的 `PDFName` 实例随即返回,零字符串分配。 未命中时,名称字符串通过一次 `String.fromCharCode.apply(null, slice)` 调用构建(而非逐字节 cons 链),并传递给 `PDFName.of`(此栈上是 `fast-decode-name` 的字符串键缓存)。结果 `PDFName` 实例然后作为新条目存储在字节哈希缓存中。 两个缓存收敛于每个逻辑名称的同一 `PDFName` 实例。来自非解析器代码的直接 `PDFName.of(string)` 调用(如 `setOutline`、`setMetadata`)绕过字节哈希缓存,直接通过 `fast-decode-name` --- 正确,因为那些调用点没有可哈希的字节范围。 ## fast-sync-load.mjs **问题。** pdf-lib 的解析器和写入方法从 TypeScript `async function` 编译为 tslib 的 `__awaiter` + `__generator` 状态机。在浏览器上,这些通过 `objectsPerTick` / `waitForTick()` 定期让出以保持页面响应。在 Node 中使用 `objectsPerTick: Infinity`(`parseSpeed: Fastest` 配置),让出门控从不触发 --- 整个生成器在一个 tick 中运行 --- 但每个间接对象(书籍上约 50,000 个)仍为单个 `case 0` 直通支付状态机分发开销。 **修复。** 八个方法被替换为普通同步等效方法。 加载侧: * `PDFParser.parseDocument`、`parseDocumentSection`、`parseIndirectObjects`、`parseIndirectObject` * `PDFObjectStreamParser.parseIntoContext` * `PDFDocument.load`(静态工厂) 保存侧: * `PDFWriter.serializeToBuffer`(保持 `async`,因为 `ParallelStreamWriter.computeBufferSize` 通过 `Promise.all` 在 libuv 上是真正异步的) * `PDFWriter.computeBufferSize` 和 `PDFStreamWriter.computeBufferSize` `PDFDocument.load` 返回普通 `PDFDocument` 值而非 Promise。现有调用点的 `await PDFDocument.load(...)` 仍然有效,因为对非 thenable 的 `await` 立即解析为该值。 `parseIndirectObjects` 中的额外优化:上游实现在每个间接对象之后调用 `skipJibberish()` 以从格式错误 PDF 中对象间的垃圾中恢复。`skipJibberish` 在下一个字节已经是数字(常见情况)时仍推测性尝试关键字匹配。同步重写短路此逻辑:当下一个字节是数字时,外部 `while` 循环直接继续;仅当字节不是数字时才调用 `skipJibberish`。 ## fast-indirect-objects.mjs **问题。** `PDFContext.indirectObjects` 是一个 `Map<PDFRef, PDFObject>`。在 `PDFDocument.load` 期间,每个间接对象的赋值调用 `indirectObjects.set(ref, object)`。Map 经过约 14 次翻倍步骤增长以容纳书籍的约 9,000 个间接对象,将每个中间后备竞技场丢弃给 GC。性能分析将约 14.5 MB 堆流量归因于这些 `Map.set` 调用。 **修复。** 每个 `PDFContext` 上的辅助密集数组 `_objArr`,以 `objectNumber` 索引 gen=0 引用(Chromium 发出的 PDF 上压倒性的常见情况)。gen≠0 引用使用原始 `indirectObjects` Map 作为回退。方法 `assign`、`lookup`、`lookupMaybe`、`delete`、`getObjectRef` 和 `enumerateIndirectObjects` 都先查询 `_objArr`。额外好处:`enumerateIndirectObjects` 不再需要对结果排序:密集数组迭代已经按 `objectNumber` 升序。 ## fast-pdfnumber-pool.mjs **问题。** `PDFNumber.of(value)` 在每次调用时分配新的 `PDFNumber` 实例。`PDFNumber` 构造函数还调用 `numberToString(value)` 计算 `stringValue` 字段,分配第二个对象。PDF 中密集包含重复的数值 --- 页面索引、`/MediaBox` 尺寸(612、792、595、842)、字体大小、位宽。在书籍上,约 15 MB 堆归因于对一小组唯一值的 `PDFNumber.of` 调用。 **修复。** 密集数组 `intPool` 以 `value` 索引 `[0, 16384)` 范围内的非负整数(远超书籍上所有观察到的整数值)。`Map` 回退覆盖浮点数、负数和超范围整数。`PDFNumber` 实例不可变(`numberValue` 和 `stringValue` 在构造函数中设置且永不改变),因此共享缓存实例是安全的。书籍上 `PDFNumber.of` 归因的堆从约 15 MB 降至约 0.8 MB。 ## fast-array-onebuf.mjs **问题。** 每个 `PDFArray` 实例在其构造函数中分配每实例的 `this.array = []`。在书籍上,这些每实例分配贡献了约 19 MB 堆。每个 `this.array` 是按需增长的短命数组,导致 V8 对小数组执行重复的后备存储重新分配。 **修复。** 与 `fast-dict-onebuf` 相同的单缓冲策略,应用于 `PDFArray`。一个所有 `PDFArray` 实例共享的单个只追加 Array(`arrayMain`)。每个 `PDFArray` 携带一个编码整数(`d`),打包 `start`(24 位)和 `length`(16 位)。`arrayMain[start..start+length]` 存放数组元素作为普通 JavaScript 引用 --- 无编码,读取时无解码步骤。`PDFObjectParser.parseArray` 使用每个解析器的 `_arrayTemp` 栈,将每个完成的帧作为一个连续追加提交到 `arrayMain`。修改遵循与 `fast-dict-onebuf` 相同的写时复制逻辑。 来自 `measure-pass.mjs` 的 `setExpectedArraySlots(n)` 在解析前原地调整 `arrayMain` 大小,原因与 `setExpectedDictSlots` 相同:原地调整大小保留 V8 内联缓存槽。 ## parallel-deflate.mjs **问题。** `PDFDocument.save({ useObjectStreams: true })` 同步驱动 `PDFStreamWriter.computeBufferSize`。该方法创建每个 `PDFObjectStream`,然后立即对其调用 `computeIndirectObjectSize`。`PDFObjectStream` 上的 `sizeInBytes()` 通过对流未编码内容运行 zlib deflate 惰性填充其内容缓存 --- 在 Node.js 主线程上同步执行。在书籍上(约 450 个对象流,每个分组 50 个对象),这些顺序 deflate 调用占保存阶段墙钟时间约 30%。 **修复。** `ParallelStreamWriter` 是 `PDFStreamWriter` 的子类,将缓冲区大小计算阶段分为三个阶段: 1. **分类** --- 与上游相同的分区逻辑:对象被分为未压缩(PDF 流、加密引用、gen≠0)和压缩块。 2. **并行 deflate** --- 所有 `PDFObjectStream` 实例预先创建,然后调用 `await Promise.all(streams.map(s => deflateAsync(s.getUnencodedContents())))`。每个 deflate 在 libuv 的线程池(默认 4 个线程)上运行。结果直接写入每个流的 `contentsCache.value`,以便后续大小阶段只找到缓存命中。 3. **大小与发出** --- 与上游相同;每个 `computeIndirectObjectSize` 调用都是缓存命中。 交叉引用流的内容取决于阶段 3 中固定的字节偏移,因此它通过 `deflateSync` 在这些偏移固定后立即同步 deflate。这是一个流;主线程开销可忽略。 `parallelSave(pdfDoc, opts)` 是公共入口点,替代 `pdfDoc.save({ useObjectStreams: true })`。生产配置使用 `{ objectsPerStream: 500 }` --- pdf-lib 默认值 50 的十倍。更大的对象流为 deflate 压缩器提供更宽的窗口以处理相似的重复字符串(PDF 名称、对象类型、坐标模式),产生的输出比默认分组小约 5%。 `UV_THREADPOOL_SIZE`(默认 4)限制 deflate 并发。在有超过四个 CPU 核心的机器上,在任何 libuv 工作触发之前设置 `process.env.UV_THREADPOOL_SIZE = '8'` 可以减少阶段 2 墙钟时间。 ## 另见 * [Paged.js 补丁](/official/Documentation/Fixes-PagedJS) -- 对内置 paged.js 包的补丁。 * [PDF 生成](/official/Documentation/PDF-Generation) -- 这些垫片如何融入三阶段渲染管线和整体数据流。 > AI生成 --- --- url: /en/official/Documentation/Fixes-PDFLib.md --- # pdf-lib Patches The files under `book/lib/fast-*.mjs` and `book/lib/parallel-deflate.mjs` are side-effecting ES modules that patch pdf-lib's live exports. All are imported at the top of `render-book.mjs` before any pdf-lib operation runs; they are mutually compatible and idempotent (each guards its installation with a flag on the patched prototype or module). Together they reduce the process phase --- parsing Chromium's raw PDF output, adding bookmarks and metadata, and serialising the result --- from ~40 seconds to ~1.6 seconds on the 1651-page book. The root cause of the need for all these patches is the same: pdf-lib is designed for general-purpose use in both browsers and Node, and optimises for generality rather than throughput on a single large document. ## fast-refs-class.mjs **Problem.** `PDFRef.of(objectNumber, generationNumber)` is the factory for every indirect reference in the PDF. The original factory built instances via `Object.create(PDFRef.prototype)` followed by individual property writes. V8 treats objects built that way as transitioning through intermediate hidden-class maps for each write, producing instances roughly twice as large as those built with `new`. Measured on the book: ~60 bytes per instance via the upstream path. With ~226 000 unique indirect references, that is ~13.5 MB of excess heap. Additionally, there was no pool: each call to `PDFRef.of(N, 0)` allocated a new instance even for previously seen object numbers. **Fix.** Two constructor functions, `_FastRef` (gen=0) and `_FastRefGen` (gen≠0), both with their `prototype` aliased to `PDFRef.prototype`. V8 assigns each a stable hidden class from the first instance. `_FastRef` carries only `objectNumber`; `generationNumber` is provided as a prototype data-property default of `0`, so gen=0 instances need only one inline slot (~16 bytes per instance, down from ~60). Gen=0 instances are cached in a dense `pool0` Array indexed by `objectNumber`; gen≠0 instances use a `Map` keyed by `"N M"` string (vanishingly rare: only the free entry at object 0 in Chromium-emitted PDFs). The hot prototype methods `toString`, `sizeInBytes`, and `copyBytesInto` are rewritten to read `objectNumber` and `generationNumber` as plain data-property reads rather than going through the original `tag` string stored on each instance. ## fast-inflate.mjs **Problem.** `PDFCrossRefStreamParser` decompressed the PDF's cross-reference stream with `pako.inflate()`, which is a pure-JavaScript zlib implementation. Node provides `zlib.inflateSync` backed by the native zlib C library, which is substantially faster. The cross-reference stream is compressed exactly once per `PDFDocument.load` call, so the saving is small in absolute wall-clock terms, but this was the last remaining call to pako after `parallel-deflate.mjs` took over the deflate side, and eliminating it brings the runtime pako call count to zero. **Fix.** Mutates the live `pako` exports object: replaces `pako.inflate` with a wrapper that delegates to `zlib.inflateSync` when called with no options (the only call pattern pdf-lib uses), and falls back to the original `pako.inflate` for any call that passes options. PDF's `/FlateDecode` encoding (RFC 1950 zlib framing) is accepted by both implementations, so the swap is byte-compatible. **Mechanism.** pdf-lib calls `require("pako")` lazily at the call site rather than capturing the export at import time, so mutating the live `pako.inflate` property on the module's exports object is visible to the call site. ## fast-parse-number.mjs **Problem.** `BaseParser.parseRawNumber` and `BaseParser.parseRawInt` built numeric values by appending one character at a time to a JavaScript string (`value += charFromCode(byte)`), then called `Number(value)` to convert the string back to a number. Every numeric token in a PDF --- object numbers, generation numbers, byte lengths, coordinates, font sizes, array indices --- flows through one of these paths. Each call allocated a temporary string that was immediately discarded. On the book this fired hundreds of thousands of times. **Fix.** Direct integer accumulators: `n = n * 10 + (byte - 0x30)`, consuming each byte once. `parseRawNumber` additionally handles the decimal part with a separate accumulator and a `scale` divisor. Both implementations fall back to the original when the integer part would exceed 15 digits (preserving `Number.MAX_SAFE_INTEGER` semantics for pathological inputs) or when the input has no digits at all. **Mechanism.** `BaseParser` is not re-exported from pdf-lib's public index; it is imported via `createRequire` through the CJS internal path `pdf-lib/cjs/core/parser/BaseParser.js`. Mutating `BaseParser.prototype` affects all subclasses: `PDFParser`, `PDFObjectParser`, `PDFObjectStreamParser`, and `PDFXRefStreamParser`. ## fast-decode-name.mjs **Problem.** `PDFName.of(name)` called `decodeName(name)` --- a `.replace(/#([\dABCDEF]{2})/g, ...)` regex scan --- unconditionally on every call to decode `#XX` hex-escape sequences. On the book, `PDFName.of` was called 2 759 635 times; exactly two inputs contained a `#`. The regex scanned 2.76 million strings to find two matches, accounting for ~168 ms (7%) of process phase self-time. **Fix.** A parallel `Map<string, PDFName>` keyed by the raw input string. When the input contains no `#` (checked via `indexOf`), the decoded form equals the raw form, so the map key matches pdf-lib's internal pool key. Cache hits return the deduplicated `PDFName` instance with zero regex work. Cache misses delegate to the original `PDFName.of` (which runs the regex once, returning the canonical instance from pdf-lib's own pool); the result is then stored in the fast cache. Inputs containing `#` bypass the cache entirely, preserving the original decode semantics. ## fast-number-to-string.mjs **Problem.** `numberToString(num)` --- used by `PDFNumber` and others to serialise numbers to PDF syntax --- always called `num.toString()` twice: once to obtain `numStr` and a second time inside the exponential-notation check (`num.toString().split('e-')` etc.). The exponential-notation case only occurs for `|num| < 1e-6` or `|num| >= 1e21`, neither of which appears in real PDFs. Every call paid the cost of the second `toString()`, the `split`, and a `parseInt` to confirm the exponent check was irrelevant. **Fix.** Compute `numStr = String(num)` once and check `numStr.indexOf('e') === -1`. Return `numStr` immediately on the common case. Fall through to the original only when `'e'` is present. **Mechanism.** pdf-lib is compiled against tslib 1.x, whose `__exportStar` copies export values by value rather than by reference at module evaluation time. By the time `PDFNumber.js`'s `index_1.numberToString(value)` executes, `index_1` holds a captured reference to the original function. Patching only the source module is invisible to the call site. The shim patches three locations: `pdf-lib/cjs/utils/numbers.js` (the source), `pdf-lib/cjs/utils/index.js` (the barrel `PDFNumber` reads from), and `pdf-lib/cjs/index.js` (the top-level public index). ## fast-size-in-bytes.mjs **Problem.** `utils.sizeInBytes(n)` computed how many bytes are required to encode an integer in a PDF cross-reference stream field by calling `Math.ceil(n.toString(2).length / 8)` --- converting to a binary string, measuring its length, and dividing. It was called three times per xref entry (from `PDFCrossRefStream.computeMaxEntryByteWidths`) on ~50 000 entries per book, allocating a temporary binary string on every call. **Fix.** A non-allocating short-circuit ladder: ```js if (n < 0x100) return 1; if (n < 0x10000) return 2; if (n < 0x1000000) return 3; if (n < 0x100000000) return 4; return 4 + Math.ceil((32 - Math.clz32(Math.floor(n / 0x100000000))) / 8); ``` The four-byte case covers all PDFs under 4 GB; the fallback handles larger values without allocating a string. **Mechanism.** Same tslib barrel-copy issue as `fast-number-to-string`; patched in three locations. ## fast-dict-onebuf.mjs **Problem.** Each `PDFDict` instance held its key-value pairs in a `Map`. Maps carry ~200 bytes of per-instance overhead when empty and ~50 bytes per entry. On the book, ~260 000 `PDFDict` instances are created during `PDFDocument.load`. As the document grows during parse, the Maps repeatedly doubled their internal hash-table storage and discarded each previous arena to GC. **Fix.** A single append-only Array (`main`) shared across all `PDFDict` instances for the document's lifetime. Each `PDFDict` carries one encoded integer (`d`) that packs a `start` index (23 bits) and entry-pair `length` count (16 bits) into a single JavaScript number. `main[start..start+length]` holds alternating key and value references. Mutations that add a new entry either extend the dict's range in-place when it is at the array's high-water mark, or copy the range to the tail first (copy-on-write). `PDFCatalog`, `PDFPageTree`, and `PDFPageLeaf` share the same backing array; `PDFPageLeaf`'s `normalized` and `autoNormalizeCTM` booleans are encoded in two spare bits of `d` (bits 23 and 24). `PDFObjectParser.parseDict` uses a per-parser temp array as a recursion-frame stack, committing each completed frame to `main` as a single contiguous append. The `measure-pass.mjs` pre-pass counts total `dictSlots` in the raw PDF byte stream. Calling `setExpectedDictSlots(n)` before `PDFDocument.load` resizes `main` in-place to the exact required size via `main.length = n`, eliminating V8 growth reallocations during parse. An in-place resize is used rather than replacing the module-level binding; replacing it would invalidate V8's inline-cache slots in every closure that reads `main`, causing a parse-time deoptimisation spike. ## fast-parse-object.mjs **Problem.** `PDFObjectParser.parseObject` ran three speculative `matchKeyword` calls --- checking for `true`, `false`, and `null` --- before reading the first byte of the current token to dispatch on its type. `matchKeyword` on failure still consumed the `bytes.offset()` read, two `bytes.next()` calls (advance and rewind), and a comparison. `true`/`false`/`null` values are extremely rare in real PDFs; on the book these three calls failed on essentially every invocation of `parseObject`, which was called once per dict value, array element, and indirect-object body. **Fix.** Read the first byte first, then dispatch by byte value. Digits, sign characters, and period go to `parseNumberOrRef`; `<<` goes to `parseDictOrStream`; `/` goes to `parseName`; `[` goes to `parseArray`; `(` goes to `parseString`; a lone `<` goes to `parseHexString`. The `matchKeyword` calls for `true`/`false`/`null` run only when the first byte is `t`, `f`, or `n` respectively. The `PDFObjectParsingError` for unrecognised tokens is preserved. ## fast-parse-name.mjs **Problem.** `parseName` built a JavaScript string from the raw bytes of the name body, one character at a time via a cons-chain accumulator, then called `PDFName.of(string)` to retrieve the canonical instance. Each call allocated a temporary string (~8 characters on average), even though 99.7% of calls were to names already in the pool (4787 unique names vs 1.68 million total calls on the book). **Fix.** A byte-hash cache in front of `parseName`. The name body bytes are scanned to compute a Java-style hash (`hash = hash * 31 + byte`) while simultaneously advancing the byte cursor --- no string is allocated on this path. The hash is looked up in a `Map`; on a hit the stored `Uint8Array` key is compared byte-by-byte against the current buffer slice to confirm equality (handling hash collisions). On a confirmed hit the cached `PDFName` instance is returned with zero string allocation. On a miss, the name string is built in one `String.fromCharCode.apply(null, slice)` call (not a per-byte cons-chain) and passed to `PDFName.of` (which on this stack is the `fast-decode-name` string-keyed cache). The resulting `PDFName` instance is then stored in the byte-hash cache as a new entry. Both caches converge on the same `PDFName` instance per logical name. Direct `PDFName.of(string)` calls from non-parser code (e.g., `setOutline`, `setMetadata`) bypass the byte-hash cache and go through `fast-decode-name` directly --- correct, since those call sites don't have a byte range to hash. ## fast-sync-load.mjs **Problem.** pdf-lib's parser and writer methods are compiled from TypeScript `async function`s to tslib's `__awaiter` + `__generator` state machines. On browsers, these yield periodically via `objectsPerTick` / `waitForTick()` to keep the page responsive. In Node with `objectsPerTick: Infinity` (the `parseSpeed: Fastest` configuration), the yield gate never fires --- the entire generator runs in one tick --- yet every indirect object (~50 000 on the book) still paid the state-machine dispatch overhead for a single `case 0` fall-through. **Fix.** Eight methods are replaced with plain synchronous equivalents. Load side: * `PDFParser.parseDocument`, `parseDocumentSection`, `parseIndirectObjects`, `parseIndirectObject` * `PDFObjectStreamParser.parseIntoContext` * `PDFDocument.load` (static factory) Save side: * `PDFWriter.serializeToBuffer` (kept `async` because `ParallelStreamWriter.computeBufferSize` is genuinely async via `Promise.all` over libuv) * `PDFWriter.computeBufferSize` and `PDFStreamWriter.computeBufferSize` `PDFDocument.load` returns a plain `PDFDocument` value rather than a Promise. `await PDFDocument.load(...)` at existing call sites still works, because `await` on a non-thenable resolves immediately to the value. An additional optimisation in `parseIndirectObjects`: the upstream implementation called `skipJibberish()` after every indirect object to recover from garbage between objects in malformed PDFs. `skipJibberish` speculatively attempted keyword matches even when the next byte was already a digit (the common case). The sync rewrite short-circuits this: when the next byte is a digit, the outer `while` loop continues directly; `skipJibberish` is called only when the byte is not a digit. ## fast-indirect-objects.mjs **Problem.** `PDFContext.indirectObjects` was a `Map<PDFRef, PDFObject>`. During `PDFDocument.load`, every indirect object's assignment called `indirectObjects.set(ref, object)`. The Map grew through ~14 doubling steps to accommodate the book's ~9 000 indirect objects, discarding each intermediate backing arena to GC. Profiling attributed ~14.5 MB of heap traffic to these `Map.set` calls. **Fix.** An auxiliary dense Array `_objArr` on each `PDFContext`, indexed by `objectNumber` for gen=0 references (the overwhelmingly common case on Chromium-emitted PDFs). Gen≠0 references use the original `indirectObjects` Map as a fallback. The methods `assign`, `lookup`, `lookupMaybe`, `delete`, `getObjectRef`, and `enumerateIndirectObjects` all consult `_objArr` first. As a side benefit, `enumerateIndirectObjects` no longer needs to sort the result: dense-array iteration is already in ascending `objectNumber` order. ## fast-pdfnumber-pool.mjs **Problem.** `PDFNumber.of(value)` allocated a new `PDFNumber` instance on every call. The `PDFNumber` constructor also called `numberToString(value)` to compute a `stringValue` field, allocating a second object. PDFs are dense with repeated numeric values --- page indices, `/MediaBox` dimensions (612, 792, 595, 842), font sizes, bit widths. On the book, ~15 MB of heap was attributed to `PDFNumber.of` calls against a small set of unique values. **Fix.** A dense Array `intPool` indexed by `value` for non-negative integers in `[0, 16384)` (covers all observed integer values on the book by a wide margin). A `Map` fallback covers floats, negatives, and out-of-range integers. `PDFNumber` instances are immutable (`numberValue` and `stringValue` are set in the constructor and never changed), so sharing cached instances is safe. Heap attributed to `PDFNumber.of` drops from ~15 MB to ~0.8 MB on the book. ## fast-array-onebuf.mjs **Problem.** Each `PDFArray` instance allocated a per-instance `this.array = []` in its constructor. On the book, these per-instance allocations contributed ~19 MB of heap. Each `this.array` was a short-lived Array grown on demand, causing V8 to perform repeated backing-store reallocations for small arrays. **Fix.** The same one-buffer strategy as `fast-dict-onebuf`, applied to `PDFArray`. A single append-only Array (`arrayMain`) shared across all `PDFArray` instances. Each `PDFArray` carries one encoded integer (`d`) packing `start` (24 bits) and `length` (16 bits). `arrayMain[start..start+length]` holds array elements as plain JavaScript references --- no encoding, no decode step on reads. `PDFObjectParser.parseArray` uses a per-parser `_arrayTemp` stack, committing each completed frame to `arrayMain` in one contiguous append. Mutations follow the same copy-on-write logic as `fast-dict-onebuf`. `setExpectedArraySlots(n)` from `measure-pass.mjs` resizes `arrayMain` in-place before parse for the same reason as `setExpectedDictSlots`: in-place resize preserves V8's inline-cache slots. ## parallel-deflate.mjs **Problem.** `PDFDocument.save({ useObjectStreams: true })` drove `PDFStreamWriter.computeBufferSize` synchronously. This method created each `PDFObjectStream`, then immediately called `computeIndirectObjectSize` on it. `sizeInBytes()` on a `PDFObjectStream` lazy-populates its content cache by running zlib deflate on the stream's unencoded content --- synchronously on the Node.js main thread. On the book (~450 object streams, each grouping 50 objects), these sequential deflate calls accounted for ~30% of save phase wall time. **Fix.** `ParallelStreamWriter`, a `PDFStreamWriter` subclass, splits the buffer-sizing pass into three phases: 1. **Classify** --- same partition logic as upstream: objects are divided into uncompressed (PDF streams, encrypted refs, gen≠0) and compressed chunks. 2. **Parallel deflate** --- all `PDFObjectStream` instances are created up-front, then `await Promise.all(streams.map(s => deflateAsync(s.getUnencodedContents())))` is called. Each deflate runs on libuv's thread pool (4 threads by default). Results are written directly into each stream's `contentsCache.value` so that the subsequent size pass finds only cache hits. 3. **Size and emit** --- same as upstream; every `computeIndirectObjectSize` call is a cache hit. The cross-reference stream's contents depend on byte offsets fixed in phase 3, so it is deflated synchronously via `deflateSync` immediately after those offsets are pinned. This is one stream; the main thread overhead is negligible. `parallelSave(pdfDoc, opts)` is the public entry point, replacing `pdfDoc.save({ useObjectStreams: true })`. The production configuration uses `{ objectsPerStream: 500 }` --- ten times the pdf-lib default of 50. Larger object streams give the deflate compressor a wider window over similar repeated strings (PDF names, object types, coordinate patterns), producing ~5% smaller output than the default grouping. `UV_THREADPOOL_SIZE` (default 4) bounds the deflate concurrency. Setting it higher via `process.env.UV_THREADPOOL_SIZE = '8'` before any libuv work fires can reduce phase 2 wall time on machines with more than four CPU cores. ## See Also * [Paged.js Patches](/en/official/Documentation/Fixes-PagedJS) -- patches to the vendored paged.js bundle. * [PDF Generation](/en/official/Documentation/PDF-Generation) -- how these shims fit into the three-phase render pipeline and the overall data flow. --- --- url: /en/official/Documentation/Permanent-Links.md --- # Permanent Links The stable, or machine-accessible, part of the documentation tree is rooted on the `/tB/` prefix. URLs with this prefix --- and the internal links that target them, e.g. [`docs.twinbasic.com/tB/Modules/Math/Round`](/en/official/Reference/VBA/Math/Round) --- are guaranteed not to move. This is the contract the IDE help system, `[Documentation(...)]` attribute references, and external links rely on; anything documented below should be treated as essential. ## /tB/Core/`<Statement>` * [AppActivate](/en/official/Reference/Core/AppActivate) * [Beep](/en/official/Reference/Core/Beep) * [Call](/en/official/Reference/Core/Call), [ChDir](/en/official/Reference/Core/ChDir), [ChDrive](/en/official/Reference/Core/ChDrive), [Class](/en/official/Reference/Core/Class), [Close](/en/official/Reference/Core/Close), [CoClass](/en/official/Reference/Core/CoClass), [Const](/en/official/Reference/Core/Const), [Continue](/en/official/Reference/Core/Continue) * [Date](/en/official/Reference/Core/Date), [Declare](/en/official/Reference/Core/Declare), [Deftype](/en/official/Reference/Core/Deftype), [DeleteSetting](/en/official/Reference/Core/DeleteSetting), [Dim](/en/official/Reference/Core/Dim), [Do-Loop](/en/official/Reference/Core/Do-Loop) * [End](/en/official/Reference/Core/End), [Enum](/en/official/Reference/Core/Enum), [Erase](/en/official/Reference/Core/Erase), [Error](/en/official/Reference/Core/Error), [Event](/en/official/Reference/Core/Event), [Exit](/en/official/Reference/Core/Exit) * [FileCopy](/en/official/Reference/Core/FileCopy), [For-Next](/en/official/Reference/Core/For-Next), [For-Each-Next](/en/official/Reference/Core/For-Each-Next), [Function](/en/official/Reference/Core/Function) * [Get](/en/official/Reference/Core/Get), [GetSetting](/en/official/Reference/Core/GetSetting), [GoSub-Return](/en/official/Reference/Core/GoSub-Return), [GoTo](/en/official/Reference/Core/GoTo) * [If-Then-Else](/en/official/Reference/Core/If-Then-Else), [Implements](/en/official/Reference/Core/Implements), [Input](/en/official/Reference/Core/Input), [Interface](/en/official/Reference/Core/Interface), [Is](/en/official/Reference/Core/Is) * [Kill](/en/official/Reference/Core/Kill) * [LBound](/en/official/Reference/Core/LBound), [Let](/en/official/Reference/Core/Let), [Line-Input](/en/official/Reference/Core/Line-Input), [Load](/en/official/Reference/Core/Load), [Lock](/en/official/Reference/Core/Lock), [LSet](/en/official/Reference/Core/LSet) * [Mid-equals](/en/official/Reference/Core/Mid-equals) for `Mid(...) = ...` , [MidB-equals](/en/official/Reference/Core/MidB-equals) for `MidB(...) = ...`, [MkDir](/en/official/Reference/Core/MkDir), [Module](/en/official/Reference/Core/Module) * [Name](/en/official/Reference/Core/Name), [New](/en/official/Reference/Core/New) * [Option](/en/official/Reference/Core/Option), [On-Error](/en/official/Reference/Core/On-Error), [On-GoSub](/en/official/Reference/Core/On-GoSub), [On-GoTo](/en/official/Reference/Core/On-GoTo), [Open](/en/official/Reference/Core/Open) * [ParamArray](/en/official/Reference/Core/ParamArray), [Print](/en/official/Reference/Core/Print), [Private](/en/official/Reference/Core/Private), [Property](/en/official/Reference/Core/Property), [Protected](/en/official/Reference/Core/Protected), [Public](/en/official/Reference/Core/Public), [Put](/en/official/Reference/Core/Put) * [RaiseEvent](/en/official/Reference/Core/RaiseEvent), [ReDim](/en/official/Reference/Core/ReDim), [Reset](/en/official/Reference/Core/Reset), [Resume](/en/official/Reference/Core/Resume), [RmDir](/en/official/Reference/Core/RmDir), [RSet](/en/official/Reference/Core/RSet) * [SavePicture](/en/official/Reference/Core/SavePicture), [SaveSetting](/en/official/Reference/Core/SaveSetting), [Seek](/en/official/Reference/Core/Seek), [Select-Case](/en/official/Reference/Core/Select-Case), [SendKeys](/en/official/Reference/Core/SendKeys), [Set](/en/official/Reference/Core/Set), [SetAttr](/en/official/Reference/Core/SetAttr), [Static](/en/official/Reference/Core/Static), [Sub](/en/official/Reference/Core/Sub), [Stop](/en/official/Reference/Core/Stop) * [Time](/en/official/Reference/Core/Time), [Type](/en/official/Reference/Core/Type) * [Unload](/en/official/Reference/Core/Unload), [Unlock](/en/official/Reference/Core/Unlock) * [While-Wend](/en/official/Reference/Core/While-Wend), [Width](/en/official/Reference/Core/Width), [With](/en/official/Reference/Core/With), [Write](/en/official/Reference/Core/Write) ## /tB/Modules/`<ModuleName>`/`<Symbol>` Within each VBA module, each procedure, property, or statement has its own stand-alone page, e.g. [**LenB**: /tB/Modules/Strings/Len](/en/official/Reference/VBA/Strings/Len). The `$`-suffixed and `B`/`W` variants are documented on the same page as the base symbol (so `LenB`, `Len$`, etc. all share the [`Len`](/en/official/Reference/VBA/Strings/Len) page). * [Collection](/en/official/Reference/VBA/Collection/) * [Compilation](/en/official/Reference/VBA/Compilation/) * [Constants](/en/official/Reference/VBA/Constants/) * [Conversion](/en/official/Reference/VBA/Conversion/) * [DateTime](/en/official/Reference/VBA/DateTime/) * [ErrObject](/en/official/Reference/VBA/ErrObject/) * [TbExpressionService](/en/official/Reference/VBA/TbExpressionService/) * [FileSystem](/en/official/Reference/VBA/FileSystem/) * [Financial](/en/official/Reference/VBA/Financial/) * [Information](/en/official/Reference/VBA/Information/) * [Interaction](/en/official/Reference/VBA/Interaction/) * [Math](/en/official/Reference/VBA/Math/) * [Strings](/en/official/Reference/VBA/Strings/) * Internal [\_HiddenModule](/en/official/Reference/VBA/HiddenModule/) ## /tB/Packages/`<Package>`/... Each package lives under `/tB/Packages/<Package>/`. The sub-structure depends on the package: modules, classes, enumerations, and sub-objects each have their own page. ### VBRUN -- /tB/Packages/VBRUN/`<Module>`/ * [AmbientProperties](/en/official/Reference/VBRUN/AmbientProperties/) * [AsyncProperty](/en/official/Reference/VBRUN/AsyncProperty/) * [Constants](/en/official/Reference/VBRUN/Constants/) * [ContainedControls](/en/official/Reference/VBRUN/ContainedControls/) * [DataMembers](/en/official/Reference/VBRUN/DataMembers/) * [DataObject](/en/official/Reference/VBRUN/DataObject/) * [ErrorCallstack](/en/official/Reference/VBRUN/ErrorCallstack/) * [ErrorContext](/en/official/Reference/VBRUN/ErrorContext/) * [ErrorStackFrame](/en/official/Reference/VBRUN/ErrorStackFrame/) * [Hyperlink](/en/official/Reference/VBRUN/Hyperlink/) * [ParentControls](/en/official/Reference/VBRUN/ParentControls/) * [PropertyBag](/en/official/Reference/VBRUN/PropertyBag/) ### VB -- /tB/Packages/VB/`<Class>`/ * [App](/en/official/Reference/VB/App/), [CheckBox](/en/official/Reference/VB/CheckBox/), [CheckMark](/en/official/Reference/VB/CheckMark/), [Clipboard](/en/official/Reference/VB/Clipboard/), [ComboBox](/en/official/Reference/VB/ComboBox/), [CommandButton](/en/official/Reference/VB/CommandButton/) * [Data](/en/official/Reference/VB/Data/), [DirListBox](/en/official/Reference/VB/DirListBox/), [DriveListBox](/en/official/Reference/VB/DriveListBox/) * [FileListBox](/en/official/Reference/VB/FileListBox/), [Form](/en/official/Reference/VB/Form/), [Frame](/en/official/Reference/VB/Frame/), [Global](/en/official/Reference/VB/Global/) * [HScrollBar](/en/official/Reference/VB/HScrollBar/), [Image](/en/official/Reference/VB/Image/) * [Label](/en/official/Reference/VB/Label/), [Line](/en/official/Reference/VB/Line/), [ListBox](/en/official/Reference/VB/ListBox/) * [MDIForm](/en/official/Reference/VB/MDIForm/), [Menu](/en/official/Reference/VB/Menu/), [MultiFrame](/en/official/Reference/VB/MultiFrame/) * [OLE](/en/official/Reference/VB/OLE/), [OptionButton](/en/official/Reference/VB/OptionButton/) * [PictureBox](/en/official/Reference/VB/PictureBox/), [Printer](/en/official/Reference/VB/Printer/), [Printers](/en/official/Reference/VB/Printers/), [PropertyPage](/en/official/Reference/VB/PropertyPage/) * [QRCode](/en/official/Reference/VB/QRCode/), [Report](/en/official/Reference/VB/Report/) * [Screen](/en/official/Reference/VB/Screen/), [Shape](/en/official/Reference/VB/Shape/) * [TextBox](/en/official/Reference/VB/TextBox/), [Timer](/en/official/Reference/VB/Timer/) * [UserControl](/en/official/Reference/VB/UserControl/), [VScrollBar](/en/official/Reference/VB/VScrollBar/) ### WebView2 -- /tB/Packages/WebView2/... * [WebView2](/en/official/Reference/WebView2/WebView2/) (control class, with [EnvironmentOptions](/en/official/Reference/WebView2/WebView2/EnvironmentOptions) sub-page) * [WebView2Header](/en/official/Reference/WebView2/WebView2Header), [WebView2HeadersCollection](/en/official/Reference/WebView2/WebView2HeadersCollection), [WebView2Request](/en/official/Reference/WebView2/WebView2Request), [WebView2RequestHeaders](/en/official/Reference/WebView2/WebView2RequestHeaders), [WebView2Response](/en/official/Reference/WebView2/WebView2Response), [WebView2ResponseHeaders](/en/official/Reference/WebView2/WebView2ResponseHeaders) * Enumerations: [wv2DefaultDownloadCornerAlign](/en/official/Reference/WebView2/Enumerations/wv2DefaultDownloadCornerAlign), [wv2ErrorStatus](/en/official/Reference/WebView2/Enumerations/wv2ErrorStatus), [wv2HostResourceAccessKind](/en/official/Reference/WebView2/Enumerations/wv2HostResourceAccessKind), [wv2KeyEventKind](/en/official/Reference/WebView2/Enumerations/wv2KeyEventKind), [wv2PermissionKind](/en/official/Reference/WebView2/Enumerations/wv2PermissionKind), [wv2PermissionState](/en/official/Reference/WebView2/Enumerations/wv2PermissionState), [wv2PrintOrientation](/en/official/Reference/WebView2/Enumerations/wv2PrintOrientation), [wv2ProcessFailedKind](/en/official/Reference/WebView2/Enumerations/wv2ProcessFailedKind), [wv2ScriptDialogKind](/en/official/Reference/WebView2/Enumerations/wv2ScriptDialogKind), [wv2WebResourceContext](/en/official/Reference/WebView2/Enumerations/wv2WebResourceContext) * Types: [COREWEBVIEW2\_PHYSICAL\_KEY\_STATUS](/en/official/Reference/WebView2/Types/COREWEBVIEW2_PHYSICAL_KEY_STATUS) ### Assert -- /tB/Packages/Assert/`<Module>` * [Exact](/en/official/Reference/Assert/Exact), [Strict](/en/official/Reference/Assert/Strict), [Permissive](/en/official/Reference/Assert/Permissive) ### CustomControls -- /tB/Packages/CustomControls/... * Controls: [WaynesButton](/en/official/Reference/CustomControls/WaynesButton/) (with [WaynesButtonState](/en/official/Reference/CustomControls/WaynesButton/WaynesButtonState)), [WaynesForm](/en/official/Reference/CustomControls/WaynesForm/) (with [WindowsFormOptions](/en/official/Reference/CustomControls/WaynesForm/WindowsFormOptions)), [WaynesFrame](/en/official/Reference/CustomControls/WaynesFrame), [WaynesGrid](/en/official/Reference/CustomControls/WaynesGrid/) (with [CellRenderingOptions](/en/official/Reference/CustomControls/WaynesGrid/CellRenderingOptions), [Column](/en/official/Reference/CustomControls/WaynesGrid/Column)), [WaynesLabel](/en/official/Reference/CustomControls/WaynesLabel), [WaynesSlider](/en/official/Reference/CustomControls/WaynesSlider/) (with [WaynesSliderState](/en/official/Reference/CustomControls/WaynesSlider/WaynesSliderState)), [WaynesTextBox](/en/official/Reference/CustomControls/WaynesTextBox/) (with [WaynesTextBoxState](/en/official/Reference/CustomControls/WaynesTextBox/WaynesTextBoxState)), [WaynesTimer](/en/official/Reference/CustomControls/WaynesTimer) * Styles: [Anchors](/en/official/Reference/CustomControls/Styles/Anchors), [Borders](/en/official/Reference/CustomControls/Styles/Borders), [Corners](/en/official/Reference/CustomControls/Styles/Corners), [Fill](/en/official/Reference/CustomControls/Styles/Fill), [Line](/en/official/Reference/CustomControls/Styles/Line), [Padding](/en/official/Reference/CustomControls/Styles/Padding), [TextRendering](/en/official/Reference/CustomControls/Styles/TextRendering) * Framework: [Canvas](/en/official/Reference/CustomControls/Framework/Canvas), [CustomControlContext](/en/official/Reference/CustomControls/Framework/CustomControlContext), [CustomControlsCollection](/en/official/Reference/CustomControls/Framework/CustomControlsCollection), [CustomControlTimer](/en/official/Reference/CustomControls/Framework/CustomControlTimer), [CustomFormContext](/en/official/Reference/CustomControls/Framework/CustomFormContext), [ICustomControl](/en/official/Reference/CustomControls/Framework/ICustomControl), [ICustomForm](/en/official/Reference/CustomControls/Framework/ICustomForm), [SerializeInfo](/en/official/Reference/CustomControls/Framework/SerializeInfo) * Enumerations: [BorderStyle](/en/official/Reference/CustomControls/Enumerations/BorderStyle), [ColorRGBA](/en/official/Reference/CustomControls/Enumerations/ColorRGBA), [CornerShape](/en/official/Reference/CustomControls/Enumerations/CornerShape), [Customtate](/en/official/Reference/CustomControls/Enumerations/Customtate), [DockMode](/en/official/Reference/CustomControls/Enumerations/DockMode), [FillPattern](/en/official/Reference/CustomControls/Enumerations/FillPattern), [FontWeight](/en/official/Reference/CustomControls/Enumerations/FontWeight), [PixelCount](/en/official/Reference/CustomControls/Enumerations/PixelCount), [PointSize](/en/official/Reference/CustomControls/Enumerations/PointSize), [StartupPosition](/en/official/Reference/CustomControls/Enumerations/StartupPosition), [TextAlignment](/en/official/Reference/CustomControls/Enumerations/TextAlignment), [TextOverflowMode](/en/official/Reference/CustomControls/Enumerations/TextOverflowMode), [WindowState](/en/official/Reference/CustomControls/Enumerations/WindowState) ### CEF -- /tB/Packages/CEF/... * [CefBrowser](/en/official/Reference/CEF/CefBrowser/) (control class, with [EnvironmentOptions](/en/official/Reference/CEF/CefBrowser/EnvironmentOptions) sub-page) * Enumerations: [CefLogSeverity](/en/official/Reference/CEF/Enumerations/CefLogSeverity), [cefPrintOrientation](/en/official/Reference/CEF/Enumerations/cefPrintOrientation) ### WinEventLogLib -- /tB/Packages/WinEventLogLib/`<Class>` * [EventLog](/en/official/Reference/WinEventLogLib/EventLog), [EventLogHelperPublic](/en/official/Reference/WinEventLogLib/EventLogHelperPublic) ### WinNamedPipesLib -- /tB/Packages/WinNamedPipesLib/`<Class>` * [NamedPipeClientConnection](/en/official/Reference/WinNamedPipesLib/NamedPipeClientConnection), [NamedPipeClientManager](/en/official/Reference/WinNamedPipesLib/NamedPipeClientManager), [NamedPipeServer](/en/official/Reference/WinNamedPipesLib/NamedPipeServer), [NamedPipeServerConnection](/en/official/Reference/WinNamedPipesLib/NamedPipeServerConnection) ### WinServicesLib -- /tB/Packages/WinServicesLib/... * [ITbService](/en/official/Reference/WinServicesLib/ITbService), [ServiceCreator](/en/official/Reference/WinServicesLib/ServiceCreator), [ServiceManager](/en/official/Reference/WinServicesLib/ServiceManager), [Services](/en/official/Reference/WinServicesLib/Services), [ServiceState](/en/official/Reference/WinServicesLib/ServiceState) * Enumerations: [ServiceControlCodeConstants](/en/official/Reference/WinServicesLib/Enumerations/ServiceControlCodeConstants), [ServiceStartConstants](/en/official/Reference/WinServicesLib/Enumerations/ServiceStartConstants), [ServiceStatusConstants](/en/official/Reference/WinServicesLib/Enumerations/ServiceStatusConstants), [ServiceTypeConstants](/en/official/Reference/WinServicesLib/Enumerations/ServiceTypeConstants) ### tbIDE -- /tB/Packages/tbIDE/`<Class>` * [AddIn](/en/official/Reference/tbIDE/AddIn), [AddinTimer](/en/official/Reference/tbIDE/AddinTimer), [Button](/en/official/Reference/tbIDE/Button), [CodeEditor](/en/official/Reference/tbIDE/CodeEditor), [DebugConsole](/en/official/Reference/tbIDE/DebugConsole), [Editor](/en/official/Reference/tbIDE/Editor), [Editors](/en/official/Reference/tbIDE/Editors) * [File](/en/official/Reference/tbIDE/File), [FileSystem](/en/official/Reference/tbIDE/FileSystem), [FileSystemItem](/en/official/Reference/tbIDE/FileSystemItem), [Folder](/en/official/Reference/tbIDE/Folder) * [Host](/en/official/Reference/tbIDE/Host), [HtmlElement](/en/official/Reference/tbIDE/HtmlElement), [HtmlElementProperties](/en/official/Reference/tbIDE/HtmlElementProperties), [HtmlElementProperty](/en/official/Reference/tbIDE/HtmlElementProperty), [HtmlElements](/en/official/Reference/tbIDE/HtmlElements), [HtmlEventProperties](/en/official/Reference/tbIDE/HtmlEventProperties), [HtmlEventProperty](/en/official/Reference/tbIDE/HtmlEventProperty) * [KeyboardShortcuts](/en/official/Reference/tbIDE/KeyboardShortcuts), [Project](/en/official/Reference/tbIDE/Project), [Themes](/en/official/Reference/tbIDE/Themes), [Toolbar](/en/official/Reference/tbIDE/Toolbar), [Toolbars](/en/official/Reference/tbIDE/Toolbars), [ToolWindow](/en/official/Reference/tbIDE/ToolWindow), [ToolWindows](/en/official/Reference/tbIDE/ToolWindows) ### WinNativeCommonCtls -- /tB/Packages/WinNativeCommonCtls/... * Controls: [DTPicker](/en/official/Reference/WinNativeCommonCtls/DTPicker), [ImageList](/en/official/Reference/WinNativeCommonCtls/ImageList/), [ListView](/en/official/Reference/WinNativeCommonCtls/ListView/), [MonthView](/en/official/Reference/WinNativeCommonCtls/MonthView), [ProgressBar](/en/official/Reference/WinNativeCommonCtls/ProgressBar), [Slider](/en/official/Reference/WinNativeCommonCtls/Slider), [TreeView](/en/official/Reference/WinNativeCommonCtls/TreeView/), [UpDown](/en/official/Referenc