I use VB .Net to call the Kernel32.dll WriteFile API:
Public Declare Function WriteFile Lib "kernel32" _
( _
ByVal hFile As IntPtr, _
ByVal lpBuffer As Byte(), _
ByVal nNumberOfBytesToWrite As Int32, _
ByRef lpNumberOfBytesWritten As Int32, _
ByVal lpOverlapped As IntPtr _
) _
As Boolean
Can anybody tell me how to create an Overlapped structure (lpOverlapped) for this function, and how to correctly pass it (the API expects a pointer?) Please show a working code snippet, if possible...
All info I found either didn't show usable examples or were too complicated to understand for me, or just weren't for VB .Net ...
Probably resolved... I guess it's done like this:
Dim structPtr As IntPtr
'Create an empty pointer
structPtr = Marshal.AllocHGlobal(Marshal.SizeOf(my_struct))
'Copy the structure and data to the pointer in memory
Marshal.StructureToPtr(my_struct, structPtr, True)
You don't need to pass a pointer to an overlapped structure and if you are finding the examples too complicated don't use it. WinAPI can be complicated in general and it is often easier to accomplish what you need directly in .Net and avoid WinAPI altogehter.
To answer your question the structure would be defined as:
Public Structure OVERLAPPED
Public Internal As Long
Public InternalHigh As Long
Public offset As Long
Public OffsetHigh As Long
Public hEvent As Long
End Structure
However, System.Threading has two classes Overlapped and NativeOverlapped meant to make life easier. Overlapped is a .Net class which you can pack into a NativeOverlapped. The structure allows you to set a call back to be fired:
In C# you would define it like this:
Overlapped overlapped = new Overlapped();
NativeOverlapped* nativeOverlapped = overlapped.Pack(
DeviceWriteControlIOCompletionCallback,
null);
Note I said in C#, that's because Net. doesn't support the return type in VB because it is unsafe code:
Visual Basic does not support APIs that consume or return unsafe types.
So if you are really looking to do Overlapped IO, it might be a lot easier for you code your overlapped methods in a C# class library, which you can then reference in and call in your VB application.
From All API:
ยท lpOverlapped Points to an OVERLAPPED structure. This structure is
required if hFile was opened with FILE_FLAG_OVERLAPPED. If hFile was
opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must not
be NULL. It must point to a valid OVERLAPPED structure. If hFile was
opened with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the
function can incorrectly report that the write operation is complete.
If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not
NULL, the write operation starts at the offset specified in the
OVERLAPPED structure and WriteFile may return before the write
operation has been completed. In this case, WriteFile returns FALSE
and the GetLastError function returns ERROR_IO_PENDING. This allows
the calling process to continue processing while the write operation
is being completed. The event specified in the OVERLAPPED structure is
set to the signaled state upon completion of the write operation. If
hFile was not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is
NULL, the write operation starts at the current file position and
WriteFile does not return until the operation has been completed. If
hFile was not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not
NULL, the write operation starts at the offset specified in the
OVERLAPPED structure and WriteFile does not return until the write
operation has been completed.
Related
I am attempting to use the FindWindow API using Visual Studio 2017 (.NET Framework 4.6.1) and VB.NET to retrieve the window handle for a currently running instance of Microsoft Word. I am finding that, although it has worked in the past (and is working in another area of the code) in one particular instance, although the FindWindow call is returning a value, I am not able to assign it to a variable. I have verified this in debug mode (screenshots available). I am trying to figure why the API call is not working in this particular instance.
Screenshots link: https://imgur.com/a/NuwpUyz
I have executed this call in some areas of the .NET code I am working with, so I know that it does work. I've changed the type in the definition of the "assignee" variable (from Object, to Integer, to IntPtr, etc., etc.) and rerun the application, with the same results (the "assignee" variable ends up with a value of zero, but the FindWindow call itself returns a integer value which appears to be the correct window handle.
The FindWindow API definition:
<DllImport("user32.dll")>
Public Shared Function FindWindow(ByVal strclassName As String, ByVal strWindowName As String) As Integer
End Function
The FindWindow API call:
.
.
.
Public hndMDIWord As Integer
.
.
.
.
If Word_Previously_Running Then
Try
_mdiWordApp = GetObject(, "Word.Application")
Catch ex As Exception
_mdiWordApp = New Word.Application
End Try
Else
_mdiWordApp = New Word.Application
End If
hndMDIWord = FindWindow("Opusapp", "")
If hndMDIWord <> 0 Then
SetParent(hndMDIWord, Me.Handle.ToInt32())
End If
I am expecting FindWindow to return an integer representing the window handle of the currently running instance of Word and than have that result assigned to the hndMDIWord variable. FindWindow does return the expected result, but the assignment statement for the hndMDIWord variable does not execute properly; hndMDIWord ends up with a value of zero. There is no error and no exception is thrown.
Any suggestions and/or insights will, of course, be greatly appreciated.
Regards,
Chris Fleetwood
I think the problem is: IntPtr is not compatible with Integer.
You need to declare return type as IntPtr:
<DllImport("user32.dll")>
Public Shared Function FindWindow(ByVal strclassName As String, ByVal strWindowName As String) As IntPtr
End Function
Because:
FindWindow has HWND return type
From MSDN handles are marshaled as IntPtr
Also there is a pinvoke.net website with examples of .net interop with wast majority of WinAPI functions.
Also hndMDIWord need to be declared as IntPtr and used accordingly, and other WinAPI functions need to be declared to use IntPtr for handlers too:
Public hndMDIWord As IntPtr
. . . .
If hndMDIWord <> IntPtr.Zero Then
I'm on a quest to figure out how to identify different icon overlays through Excel VBA.
There is a cloud syncing software and I am trying to identify whenever the syncing of my excel file has finished or still in progress. I was able to achieve a basic level of reliability by following the modification date of some meta(?) files but there is not enough consistency to fully rely on this method.
The result of my searches is a big punch in the face, since there is not much info about it in VBA. Basically all I have found that everyone uses advanced languages like C++ to handle these things.
The closest source I've got in VBA does something similar with the System Tray and uses the shell32.dll calling the appropiate windows api (link). But I have no idea how to make it to the Shell Icon Overlay Identifier.
What do you guys think, is there a possible way to make it through VBA or I have to learn C++?
Awesome! It is possible! The SHGetFileInfo method works!
It gives me values according to the current overlays. Here is the code for any other crazy people who wanna mess around with it:
Const SHGFI_ICON = &H100
Const SHGFI_OVERLAYINDEX = &H40
Const MAX_PATH = 260
Const SYNCED = 100664316 'own specific value
Const UNDSYNC = 117442532 'own specific value
Private Type SHFILEINFO
hIcon As Long 'icon
iIcon As Long 'icon index
dwAttributes As Long 'SFGAO_ flags
szDisplayName As String * MAX_PATH 'display name (or path)
szTypeName As String * 80 'type name
End Type
Private Declare Function SHGetFileInfo Lib "shell32.dll" Alias "SHGetFileInfoA" _
(ByVal pszPath As String, _
ByVal dwFileAttributes As Long, _
psfi As SHFILEINFO, _
ByVal cbFileInfo As Long, _
ByVal uFlags As Long) As Long
Private Sub GetThatInfo()
Dim FI As SHFILEINFO
SHGetFileInfo "E:\Test.xlsm", 0, FI, Len(FI), SHGFI_ICON Or SHGFI_OVERLAYINDEX
Select Case FI.iIcon
Case SYNCED
Debug.Print "Synchronized"
Case UNDSYNC
Debug.Print "Synchronization in progress"
Case Else
Debug.Print "Some shady stuff is going on!"
End Select
End Sub
Thanks for the tip again!
i am new to data macro in ms access 2013 and need some help with it.
so lets assume that i have a simple database with only one table of Users.
when i change the "Age" Field in the table, i want to run an external exe file (the reason why dosent matter).
so i learn the subject during the last few days and end up with this:
1. i build a module in ms access called RunMiniFix (MiniFix is the name of the exe file i want to run). the module uses ShellExecute function and the whole module looks like that:
Option Compare Database
Const SW_SHOW = 1
Const SW_SHOWMAXIMIZED = 3
Public Declare Function ShellExecute Lib "Shell32.dll" Alias "ShellExecuteA"
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
Optional ByVal nShowCmd As Long) As Long
Public Function RunMiniFix()
Dim RetVal As Long
On Error Resume Next
RetVal = ShellExecute(0, "open", "C:\Program Files\MiniFix\MiniFix.exe", "<arguments>", _
"<run in folder>", SW_SHOWMAXIMIZED)
End Function
Now, when activating the module, everything works just fine and the exe file is running.
in ms access, i build a data macro based on an 'If Then' statement, asking
if [Users]![Age] > x and then calls the build-in RunCode event from the action catalog which calls the RunMiniFix function.
Now, when saving the data macro, the ms access pops up a message box saying Microsoft access dosen't have the ability to find the name "Users" i mentioned in the phrase and recommend me to look for the right control in the form. "the form"? yes, the form!
this database is not form based. i have no gui designed what so ever. i have no buttons or click event to handle.
what i am asking is how can i trigger the RunMiniFix module when the Age field is modify. please, this is very important!
thanks a head,
oron.
Please use SetLocalVar from the action list in data macro and set the expression to name of your function. Sample:
name: "test"
Expression: RunMiniFix()
I have an access application with one main form. When you open the application, an AutoExec macro hides the application via the Windows API apiShowWindow. Then, the AutoExec opens up the main form which is set to Popup. This all works beautifully; my database guts are hidden and the form opens up and just floats along.
However, when the access database gets hidden, you loose the taskbar icon. I have a custom icon set in the Options\Current Database\Application Icon setting. If I don't hide the database, this icon displays just fine in the task bar.
I found an API workaround that will show an icon in the taskbar for just the form. It goes a little something like this:
Public Declare Function GetWindowLong Lib "user32" _
Alias "GetWindowLongA" _
(ByVal hWnd As Long, _
ByVal nIndex As Long) As Long
Public Declare Function SetWindowLong Lib "user32" _
Alias "SetWindowLongA" _
(ByVal hWnd As Long, _
ByVal nIndex As Long, _
ByVal dwNewLong As Long) As Long
Public Declare Function SetWindowPos Lib "user32" _
(ByVal hWnd As Long, _
ByVal hWndInsertAfter As Long, _
ByVal X As Long, _
ByVal Y As Long, _
ByVal cx As Long, _
ByVal cy As Long, _
ByVal wFlags As Long) As Long
Public Sub AppTasklist(frmHwnd)
Dim WStyle As Long
Dim Result As Long
WStyle = GetWindowLong(frmHwnd, GWL_EXSTYLE)
WStyle = WStyle Or WS_EX_APPWINDOW
Result = SetWindowPos(frmHwnd, HWND_TOP, 0, 0, 0, 0, _
SWP_NOMOVE Or _
SWP_NOSIZE Or _
SWP_NOACTIVATE Or _
SWP_HIDEWINDOW)
Result = SetWindowLong(frmHwnd, GWL_EXSTYLE, WStyle)
Debug.Print Result
Result = SetWindowPos(frmHwnd, HWND_TOP, 0, 0, 0, 0, _
SWP_NOMOVE Or _
SWP_NOSIZE Or _
SWP_NOACTIVATE Or _
SWP_SHOWWINDOW)
End Sub
This approach does work; I get an icon in the taskbar dedicated to just the form. However, the icon in the taskbar is the standard Access icon.
In response to this problem, I added another API call using the SendMessageA:
Public Declare Function SendMessage32 Lib "user32" Alias _
"SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, _ ByVal wParam
As Long, ByVal lParam As Long) As Long
Executed thus:
Private Const WM_SETICON = &H80
Private Const ICON_SMALL = 0&
Private Const ICON_BIG = 1&
Dim icoPth As String: icoPth = CurrentProject.Path & "\MyAppIcon.ico"
Dim NewIco As Long: NewIco = ExtractIcon32(0, icoPth, 0)
Dim frmHwnd As Long: frmHwnd = Me.hwnd 'the form's handle
SendMessage32 frmHwnd, WM_SETICON, ICON_SMALL, NewIco
SendMessage32 frmHwnd, WM_SETICON, ICON_BIG, NewIco
SendMessage32 hWndAccessApp, WM_SETICON, ICON_SMALL, NewIco
SendMessage32 hWndAccessApp, WM_SETICON, ICON_BIG, NewIco
Keep in mind that I have tried the above four lines of 'SendMessages' in various orders inside of and outside of, top of and bottom of the AppTasklist Sub to no avail.
It does appear to work at the application level, but it never seems to work at the form level.
For those of you familiar with this particular predicament, let me list some of the other options outside of VBA that I have tried.
1.) Taskbar\Properties\Taskbar buttons. I've changed this menu option to 'Never Combine' and 'Combine When Taskbar Is Full'. So, basically, this does work; I now get my icon for just the folder and the little label. BUT(!), it only works if the users have these settings checked on their end. In my experience, almost no one uses any of the options except 'Always combine, hide labels'.
2.) Changing the Registry settings. You can change the following registry key to change the default icon an application uses: "HKEY_CLASSES_ROOT\Access.Application.14\DefaultIcon(Default)." However, most users (myself included) don't have access to the HKEY_CLASSES_ROOT part of the registry. Furthermore, I would have to write some code to find the proper key and then change it (which I could do) but, it's unclear if this change would be immediate--not to mention I'd have to change it back when exiting the application.
3.) Right-clicking the pinned application, then right clicking the application in the menu does give you a properties menu with a button called 'Change Icon...' in the 'Shortcut' tab. However, for a program like Access, this button is greyed out.
I am using Windows 7 and Access 2010.
Is it possible to force the Taskbar Icon in the above scenario to something other than the standard Access Icon?
I feel like there's ether a little something I'm missing, or an API function that could be used, or a better SendMessage constant, or that, maybe, it just can't be done.
Any help would be greatly appreciated.
Also, as a disclaimer (I guess): obviously the above code was pulled from other posts from this forum and others. Most of it was unattributed from whence I got it. I've made some minor tweeks to make it work in Access as opposed to that other piece of Microsoft Software that keeps getting in my search results so I will not name it here.
Thanks!
Okay. So I'm going to answer my own question. Apparently all I really needed was a break from the action and to type out my problem. A short time after I posted the question, I got back on the horse and tried some more search terms. I eventually came across a post which really didn't seem fruitfull at the outset because it wasn't clear to me if the poster and myself were dealing with the same scenario.
I found my answer here:
http://www.access-programmers.co.uk/forums/showthread.php?t=231422
First off, your application must open via a shortcut. Fortunately for me, I've been using a Desktop shortcut from the begining.
When I started building the application, I knew from the outset that I would be using a VBScript to do the installation of the application (as well as updating when a newer version get's released). In that script, I create a Desktop shortcut to the application which I store in the user's Documents directory. I also store the application icon in that directory which I attach to the application shortcut.
If you've never created a shortcut via vba/script, you'll essentially do something like this (written in vbScript):
Dim WinShell
Dim ShtCut
Set WinShell = CreateObject("WScript.Shell")
Set ShtCut = WinShell.CreateShortcut(strDesktopPath & "\MyCoolApp.lnk")
With ShtCut
.TargetPath = (See below)
.Arguments = (See below)
.IconLocation = ...
.Desciption = "This is the coolest app, yo!"
.WorkingDirectory = strAppPath
.WindowStyle = 1
.Save
End With
Now, the target of the shortcut started out being something like this:
"C:\Users\UserName\Public\Documents\MyCoolApp\MyCoolApp.accdb"
Obviously your users may have a different enterprise structure for the Documents location...
What the above reference post suggests doing is turning that shortcut into a psuedo command line script.
To do this:
First, your actual target is going to be the path to the user's version of access (Runtime or full), like such:
"C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE"
IMPORTANT! You will have to wrap this target in double-quotes, i.e.:
.TargetPath = Chr(34) & strAccessPath & Chr(34)
Next (and you won't find this in the above post, I had to figure it out), you'll need to set the Argument to the directory of the application, like such:
"C:\Users\UserName\Public\Documents\MyCoolApp\MyCoolApp.accdb"
IMPORTANT! Again, you'll have to wrap the arguments in double-quotes, i.e.:
.Arguments = Chr(34) & strAppPath & Chr(34)
Also important, I hope your app IS cool.
Once you have this shortcut set up, essentially you're making it so your application will have it's own workgroup on the taskbar. I.e., if Access is open in general, your application will have it's own group on the taskbar. This group will have your cool, custom icon associated with it. And as a huge unexpected bonus, you'll be able to pin your shortcut to the taskbar outside of Access. SWEEEEEET!
Good luck!
I've got a project in Access 2010 that runs without issues. That is, until I add a breakpoint and I try to debug code. As soon as it reaches the first breakpoint, the VBA project opens up and about 1 second later Access crashes and restarts.
I can add a Debug.Print and all works fine. I just can't step through code.
Repair and compact did not work, nor to create a new project and import everything.
Looking at the event viewer I get:
Faulting application name: MSACCESS.EXE, version: 14.0.4750.1000, time stamp: 0x4b8bae0f
Faulting module name: ntdll.dll, version: 6.2.9200.16579, time stamp: 0x51637f77
Exception code: 0xc0150010
Fault offset: 0x00000000001041c0
Faulting process id: 0x2ef4
Faulting application start time: 0x01cf180a44c35b8a
Faulting application path: C:\Program Files\Microsoft Office 2010\Office14\MSACCESS.EXE
I can't unregister and reregister the DLL (entry point not found).
I've tried everything on http://pcsupport.about.com/od/fixtheproblem/a/ntdlldll.htm short of reisntalling Windows and still nothing.
Running Access in Safe mode does help, but does not fix it permanently.
Any other ideas?
UPDATE: I now have a new laptop and upgraded to Access 365. And it still happens. But only on one specific project. Other projects work fine.
Seems this is not the first time this type of error happens https://learn.microsoft.com/en-us/answers/questions/269052/vba-access-stop-command.html
The above link is very detailed (in terms of text + screenshots) and may be similar to what you experience.
Anyhow... please try to open your access software using the run as administrator option (right click access icon and pick this option). There is a chance that vba is trying to use elevated permissions and without it - it results in a spectacular crash
I got this error and discovered it was because of not declaring a variable as the correct type when using the GetUserName function, declared from the advapi32.dll library. I had to change "Dim buffer As String" to "Dim buffer As String * 256" before I could call "GetUserName(buffer, Size)". This is the code:
#If VBA7 Then
Private Declare PtrSafe Function GetUserName Lib "advapi32.dll" _
Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#Else
Private Declare Function GetUserName Lib "advapi32.dll" _
Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If
Function getNetworkName() As String
Dim ret As Long, Size As Long
Dim buffer As String * 256
Size = 256
ret = GetUserName(buffer, Size)
If ret <> 0 Then
getNetworkName = Mid(buffer, 1, InStr(1, buffer, vbNullChar) - 1)
Else
getNetworkName = "API ERROR"
End If
End Function
I don't know if your issues would be the exact same thing, but maybe it's due to a data type issue like this.