调试模式在VB 6中?

Nah*_*hum 23 vb6 conditional-compilation

如何在VB 6中执行类似于以下C代码的操作?

#ifdef _DEBUG_
    // do things
#else
    // do other things
#end if
Run Code Online (Sandbox Code Playgroud)

Cod*_*ray 35

它与您习惯的其他语言几乎相同.语法如下所示:

#If DEBUG = 1 Then
    ' Do something
#Else
    ' Do something else
#End If
Run Code Online (Sandbox Code Playgroud)

如果您只记得语法与VB 6中的其他流控制语句完全相同,那么很容易记住,除了编译时条件以井号(#)开头.

诀窍实际上是定义DEBUG(或任何)常量,因为我很确定默认情况下没有定义.有两种标准方法:

  1. 使用#Const关键字在每个源文件的顶部定义常量.以这种方式建立的定义在整个源模块中都有效.它看起来像:

     #Const DEBUG = 1
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在项目的属性中设置常量.这将定义一个在整个项目中有效的常量(可能是您想要的"调试"模式指示器).

    为此,请在"项目属性"对话框的"生成"选项卡上的"条件编译常量"文本框中输入以下内容:

     DEBUG = 1
    
    Run Code Online (Sandbox Code Playgroud)

    您可以在此对话框中定义多个常量,方法是使用冒号(:)分隔每个常量:

     DEBUG = 1 : VERSION2 = 1
    
    Run Code Online (Sandbox Code Playgroud)

请记住,这是任何常数限定被假定为0.


Mar*_*rkJ 10

Cody告诉你有关条件编译的事.我想补充一点,如果你想在IDE上调试时需要不同的行为(例如关闭你自己的错误处理,以便IDE捕获错误),你不需要条件编译.您可以像这样在运行时检测IDE.

On Error Resume Next 
Debug.Print 1/0 
If Err=0 then 
  'Compiled Binary 
Else 
  'in the IDE 
End if
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为在编译的EXE中省略了Debug.Print.

  • 编辑记得关闭On Error Resume Next!
  • 编辑你可以用支票像一个函数这个(感谢CraigJ)


G M*_*ros 7

要获得与MarkJ相同的效果,但有错误处理,您可以使用以下代码.

Public Function GetRunningInIDE() As Boolean

   Dim x As Long
   Debug.Assert Not TestIDE(x)
   GetRunningInIDE = x = 1

End Function

Private Function TestIDE(x As Long) As Boolean

    x = 1

End Function
Run Code Online (Sandbox Code Playgroud)

当您在IDE中运行时,将会有一个额外的调用函数的开销(这是非常小的).编译时,这将评估为简单的数字比较.


Fil*_*yus 5

这是我的简短而稳定的代码。我认为它比条件常量更好,因为您不需要每次复杂时都更改它。

Public Function InIDE() As Boolean
  On Error Resume Next
  Debug.Print 0 / 0
  InIDE = Err.Number <> 0
End Function
Run Code Online (Sandbox Code Playgroud)