how to include a header file in VB - vb.net

I can write program VB 6.0, but I don't know how to include a file in VB 6.0.
In c it was
include "aa.h"
But I really don't know how to include this "aa.h" in my VB program.

Comments indicate that you are trying to share a variable between all modules. Just declare a Public variable in a .bas module:
Public foo As String
And, by the way, VB6 is totally different from C.

You don't. The purpose of header files in C is to declare (function) prototypes for libraries that you use.
If your C function is available as a COM component (OCX), then you can use the OCX as an external component.
In classic Visual Basic (up to 6.0) you can declare dependencies to external libraries if those libraries reside inside DLLs. For this you must use the declare feature of Visual Basic. This is basically the Visual Basic variant of the prototype used in the .h file. You must manually convert the C prototypes you want to use from the .h file to VB syntax: e.g. the C prototype BOOL foo(LPCSTR lpString, HWND hWnd) becomes Declare Function foo Lib "a.dll" (ByVal lpString As String, ByVal hwnd As Long) As Long
If your C functionality is a static libary (.lib), then you cannot use this libary directly. Instead, you must create a DLL or OCX out of it (using C), and use one of the above VB features for external dependencies.

Goto
Menu -> Projects -> Components
and choose from the list of Components available
or for adding references
Menu -> Projects -> References
and choose from the list of References available
and call/declare it like
Dim comp as YourComponent

The only available solution close to C include headers is to add a module with all your declares and shared variables.
For example:
Public variable1, variable2 as string...
Declare Function X alias Y...

Related

VB GetAsyncKeyState' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature.

I'm working on a small program but when running my program in visual studio I get the following error:
GetAsyncKeyState' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature.
But when I build it to an .exe it runs just fine. But that makes it a bit hard to debug the program.
This is the code snipper that throws the error:
If InGame And Not GetAsyncKeyState(Keys.Tab) Then
If Settings.SkinChangera Then SkinChanger.Skinchanger()
End If
and this is GetAsyncKeyState()
Public Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
I advice you to never ever look for, or use, Declare Lib statements you got from the internet. Most of them out there are for VB6 and are therefore almost always not fully compatible with VB.NET.
Instead, stick to the solutions that use the DllImport attribute. The site pinvoke.net is a great place to look for P/Invoke declarations. If you can't find a VB.NET version of a P/Invoke declaration, take the C# version and run it through a converter such as Telerik.
Having that said, you are receiving the error because the parameter and the return value are not of the correct data types. The GetAsyncKeyState() function's parameter should be Integer and its return value should be Short.
Use the DllImport version of the function instead, with the correct data types, and it should work:
<DllImport("user32.dll")> _
Public Shared Function GetAsyncKeyState(ByVal vKey As System.Windows.Forms.Keys) As Short
End Function
Note: The System.Windows.Forms.Keys enumeration is of type Integer.

How to load a dll into VS c++, which acts like a wrapper to another CAPL code?

I am trying to reference functions in a 3rd party dll file through CAPL Script. Since, I cannot directly call them, I am trying to create a wrapper which exports the functions in the dll.
int MA_Init(char *TbName, int Option); is the function in the dll file.
The wrapper code for this is
int CAPLEXPORT far CAPLPASCAL CMA_Init(char *TbName, int Option)
{
return MA_Init(*TbName, Option);
}
I am trying to use
HINSTANCE DllHandel = loadlibrary("C:\\Turbo.dll"); to load the library and
typedef int(*TESTFnptr)(char, int);
TESTFnptr fn= (TESTFnptr)getprocaddress(DllHandle, "MA_Init"); to resolve the function address.
However the compiler says the function "MA_Init()" is not defined. I am not sure if I am using the correct procedure to load the dll into my visual C++ project. Has anyone tried doing this or knows how it's done? Thank you very much.
The standard procedure would be to include the corresponding .lib file to VS project. Go to "Project - Properties - Configuration Properties - Linker - Additional Dependencies" and add turbo.lib on a new line. Then you'll need to include the corresponding turbo.h header file which contains the definition for MA_Init function.
In this case, you'll be able to call MA_Init directly, as you do now. The compiler will happily find the definition of MA_Init in the header file, and the linker will find the reference to MA_Init in the .lib file.
If you don't have turbo.h file, you can create one yourself provided you know the prototypes of all functions you want to use. Just put definitions like
int MA_Init(char *TbName, int Option);
there and include it.
If you don't have turbo.lib file, you'll have to proceed with LoadLibrary and GetProcAddress. Obviously, you cannot call MA_Init by name in this case, since it is undefined. You'll have to call the pointer returned by GetProcAddress instead:
TESTFnptr fn = (TESTFnptr)GetProcAddress(DllHandle, "MA_Init");
int CAPLEXPORT far CAPLPASCAL CMA_Init(char *TbName, int Option)
{
return fn(TbName, Option);
}
PS. Notice I removed the start in front of TbName?
PPS. Don't forget to include your wrapper function, CMA_Init, to CAPL_DLL_INFO_LIST, otherwise it will not be accessible in CANoe/CANalyzer.

Using C++ DLL in VB6 app

I am following the guide on: https://msdn.microsoft.com/en-us/library/ms235636.aspx
I have created a DLL as it was stated above and now i want to include it in my VB6 app
I have declared a function in the code:
Private Declare Function Add Lib "C:\WINDOWS\system32\Win32Project1.dll" (ByVal a As Double, ByVal b As Double)
In the form load I have declared some variables and called a function
Dim a As Double
Dim b As Integer
a = 7.4
b = 99
Call Add(a, b)
Each time I run program I get an error that file not found.
File is present in C:\WINDOWS\system32\ and I did try to register dll using:
regsvr32 Win32Project1.dll
But I keep getting error:
LoadLibrary("Win32Project1.dll") failed - The specified module could not be found.
How can this be resolved?
Update:
I have looked further into the issue, please refer to step 2 of "Martin Schlott" answer, and it happens that VC++ encodes DLL functions and because of that i would have a funny name of ever function within DLL.
Using dumpbin.exe, which can be found in the $\Visual Studio\VC\bin, i was able to read the function names that are stored in the DLL. This is what I would get originally:
1 0 00001050 ?Add#MyMathFuncs#MathFuncs##SANNN#Z = ?Add#MyMathFuncs
#MathFuncs##SANNN#Z (public: static double __cdecl MathFuncs::MyMathFuncs::Add(d
ouble,double))
"?Add#MyMathFuncs#MathFuncs##SANNN#Z" - is what I would have to call as a function in VB6 for things to work... and it wouldn't... so I had to decode the name which is done by creating a definition file (.def) within C++ DLL app
In the new Source.def file I have defined that I want to have "Add" function:
LIBRARY
EXPORTS
Add
After rebuilding solution in the "Release" mode dumpbin gave me a much better result. However, __cdecl is automatically added to every function in VC++, unless specified otherways, and it happens that __cdecl doesn't allow function to be used in the VB6. If you run VB6 app right now you would receive a new error "Bad DLL calling convention".
For this to be resolved I had to amend "MyMathFuncs.h" file where I have defined functions to export and change
"static MATHFUNCSDLL_API double Add(double a, double b);"
to
"static MATHFUNCSDLL_API double __stdcall Add(double a, double b);"
After that dumpbin.exe returned much nicer values:
1 3 00001050 Add
This however haven't resolved my problem fully, I would still get "Bad DLL calling convention" and it was due to how I have referenced library in the VB6
Private Declare Function Add Lib "Win32Project1.dll" (ByVal a As Double, ByVal b As Double)
The function "Add" returns a double and in the abovee declaration I declare that values should be pushed and no return given. So I have followed the function format that I have in C++ and added a return with a correct data type that matches the data type in C++ file:
Private Declare Function Add Lib "Win32Project1.dll" (ByVal a As Double, ByVal b As Double) As Double
Now when I run:
Dim a As Double
Dim b As Integer
a = 7.4
b = 99
MsgBox (Add(a, b))
I have a message box stating that result is 106.4!
There are several points wrong in that what you are doing. Funny thing is,nevertheless it should work.
If you specify a DLL directly, you do not need to register it with regsvr32.
Read:
https://msdn.microsoft.com/en-us/library/aa716201(v=vs.60).aspx
resvr32 expect special exported functions to COM Conform register the DLL in the registry. A COM able DLL can be used via for e.g. with CoCreateInstance not with your declare.
If you didn't know this, regsvr is failing.
Also do not copy DLL belonging to your Project into the system32 folder. It do not belong there and it is bad behavior nowadays. For disk memory reasons it was maybe necessary centuries ago, but not today.
Copy the DLL in the same folder where the VB program is. Correct the path to
Private Declare Function Add Lib "Win32Project1.dll" (ByVal a As Double, ByVal b As Double)
and as someone already suggest, use dependency walker. If a dll starting with "MS" is missing. Read my following answer:
https://stackoverflow.com/a/18600033/1922748
to install the proper redist.
UPDATE
You wrote you are missing the "MSVCR120D.DLL". This happens if you compiled the DLL in debug mode, not release mode. You cannot install the MSVCR120D.DLL without the Visual Studio. You need to compile your DLL in release mode and install the redist.
2. Second Update
Regarding to your last comment, the entry point is missing.
You have to export the function! Add
__declspec(dllexport)
before the function you want to export. Look here
https://msdn.microsoft.com/de-de/library/3y1sfaz2.aspx
Your declaration in C++ should look like:
__declspec(dllexport) double Add(double val);
You can forget about dllimport, you do not need that in your case.

How to load DLL file from Jscript file?

So I'm writing a standalone JScript file to be executed by Windows Script Host (this file is not going to be used as a web application).
My goal is to load a dll file. Just like using LoadLibrary function in a C++ application.
I tried researching the subject but I didn't come up with anything useful. I'm so lost I don't have any piece of code to share. I understand using ActiveXObject may come to my rescue. if so, any idea how to use it?
Update:
If we all agree that loading is impossible, I'll settle for validity check. Meaning, don't try to load but check if it is loaded and functional.
You can export a specific function for this purpose.
Then, from your JScript, execute rundll32.exe and check that the function ran as expected.
You might also give Gilles Laurent's DynaWrap
ocx a chance.
This kind of dll needs to be registered on the target system like regsvr32 /s DynaWrap.dll.
It is restricted to 32-bit DLLs, and this might be inconvenient for you to use, but it works on a 64bit Windows. You can't access function exported by ordinal number and you can't directly handle 64bit or greater values/pointers.
Here's a sample to call MessageBoxA from JScript:
var oDynaWrap = new ActiveXObject( "DynamicWrapper" )
// to call MessageBoxA(), first register the API function
oDynaWrap.Register( "USER32.DLL", "MessageBoxA", "I=HsSu", "f=s", "R=l" )
// now call the function
oDynaWrap.MessageBoxA( null, "MessageBoxA()", "A messagebox from JScript...", 3 )
And here from VBScript:
Option Explicit
Dim oDynaWrap
Set oDynaWrap = CreateObject( "DynamicWrapper" )
' to call MessageBoxA(), first register the API function
UserWrap.Register "USER32.DLL", "MessageBoxA", "I=HsSu", "f=s", "R=l"
' now call the function
UserWrap.MessageBoxA Null, "MessageBoxA()", "A messagebox from VBScript...", 3
To use a function you need to "register" the exported function of your DLL.
To do this you need to call the register method with a first parameter containing a string object to the complete path of the DLL, a second parameter for the exported name of the function to use, and following three paremeters describing the functions declartion in a somehow obscure syntax.
i= describes the number and data type of the functions parameters.
f= describes the type of call: _stdcall or _cdecl. Default to _stdcall.
r= describes the return values data type.
The supported data types are:
Code Variant Description
a VT_DISPATCH IDispatch*
b VT_BOOL BOOL
c VT_I4 unsigned char
d VT_R8 8 byte real
f VT_R4 4 byte real
h VT_I4 HANDLE
k VT_UNKNOWN IUnknown*
l VT_I4 LONG
p VT_PTR pointer
r VT_LPSTR string by reference
s VT_LPSTR string
t VT_I2 SHORT
u VT_UINT UINT
w VT_LPWSTR wide string
Thus the Register method call used in the examples describes MessageBoxA like this:
_stdcall LONG MessageBoxA( HANDLE, LPSTR, LPSTR, UINT );
For a explanation of MessageBoxA look at the docs on MSDN.
Please read the DynaWrap docs for more sophisticated examples... But you might need Google translate, 'cos they are written in french ;-)
To be able to use a dll as ActiveXObject, it needs to be registered as COM object. There are some restrictions on this but if you have a code for this dll, it is certainly doable.
When you register your dll as COM object, it is assigned a name. You use this name to create an object. This example from MSDN uses excel since it is already registered if you installed office.
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
// Make Excel visible through the Application object.
ExcelSheet.Application.Visible = true;
// Place some text in the first cell of the sheet.
ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1";
// Save the sheet.
ExcelSheet.SaveAs("C:\\TEST.XLS");
// Close Excel with the Quit method on the Application object.
ExcelSheet.Application.Quit();
Apart from restriction of registering dll, using dll is no different from using it as c++ or c# dll. Note that, C# (or other .NET dlls) should be ComVisible to be used from javascript this way.
EDIT: The only other way of using C/C++ dll from javascript is swig interfaces. I have not used it, therefore I can only point you in that direction.
SWIG is a software development tool that connects programs written in
C and C++ with a variety of high-level programming languages. SWIG is
used with different types of target languages including common
scripting languages such as Javascript, Perl, PHP, Python, Tcl and
Ruby.

Trying to call a C DLL from VB. Can't get one of the parameters working

Trying to set up a USB power strip.
Here's the documentation:
Initializes the Power USB API.
Name: InitPowerUSB
Parameters: model:returns the model number(1:basic, 2:digIO, 3:watchdog, 4:Smart), firmware: returns firmware version in ?.? format in a character string (major revision and minor revision)
Return: >0 if successful. Returns number of PowerUSB devices connected
C++ Example:
if (!m_pwrUSBInit)
{
int model; char firmware[8];
if ((ret=InitPowerUSB(&model, firmware)) > 0)
{
m_pwrUSBInit = 1;
m_numDevices = ret;
}
}
I have been trying to get this working with my VB6 code for around an hour now with no luck. The program either crashes, displays an error like Bad Calling Dll Convention, type mismatch, et cetera.
Here's what I have:
Public Declare Function InitPowerUSB Lib "PwrUSBDll.dll" (ByRef model As Integer, ByVal firmware As String) As Integer
Dim model As Integer
model = 0
Dim firmware As String
firmware = ""
If (InitPowerUSB(model, firmware)) > 0) Then
EndIf
I have tried changing firmware to byte arrays, byref, string, integer, long, etc. It just doesn't seem to want to run.
Does anyone know of a solution to this problem? Thanks
I can't answer the rest of your function signature woes since I don't have any documentation for your PwrUSBDll.dll.
However "Bad DLL calling convention" errors generally mean you have a CDecl entrypoint and VB6 can only call those with some help.
There are a couple of fixes.
The obvious one is to modifiy the source and recompile that DLL using StdCall instead.
Another is to create a type library for that DLL, which helps inform VB6 about the issue and resolves it.
Then you have the option of using VB6's undocumented CDecl decorator:
Public Declare Function InitPowerUSB CDecl Lib "PwrUSBDll.dll" ( _
ByRef model As Integer, _
ByVal firmware As String) As Integer
However the downside is that this will not work when run within the IDE, nor will it work when compiled to p-code. The p-code interpreter doesn't process this keyword.
So you could just bypass it in IDE runs and supply dummy results for testing, or you can create a small wrapper DLL in VB6 that you separately compile to native code.
Caveats:
For this to solve your problem we'd have to assume you are passing correct data types in that argument list. A C++ int is a VB6 Long. You are probably better off passing a VB6 Byte array ByRef for that char[8] unless this is a Unicode DLL entrypoint. The function return value is also most likely Long.