A call to PInvoke function 'RawPrinterHelper::OpenPrinter' has unbalanced the stack - wpf

Why do I get this error at runtime:
Additional information: A call to PInvoke function 'BoxBox!BoxBox.RawPrinterHelper::OpenPrinter' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
This is the part of my class that shows the error:
<DllImport("winspool.Drv", EntryPoint:="OpenPrinterW",
SetLastError:=True, CharSet:=CharSet.Unicode,
ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)>
Public Shared Function OpenPrinter(ByVal src As String, ByRef hPrinter As IntPtr, ByVal pd As Long) As Boolean
End Function
I see that there is a problem with .NET framework above 2.0 but i really need to use .NET 4.5.2

This has worked for me in the past with VB.NET 4.5
Private Structure PRINTER_DEFAULTS
Public pDatatype As IntPtr
Public pDevMode As IntPtr
Public DesiredAccess As Integer
End Structure
<DllImport("winspool.drv", EntryPoint:="OpenPrinter", CharSet:=CharSet.Auto, SetLastError:=True)>
Private Shared Function OpenPrinter(ByVal pPrinterName As String, <Out> ByRef phPrinter As IntPtr, ByRef pDefault As PRINTER_DEFAULTS) As Integer
End Function
<DllImport("winspool.drv", EntryPoint:="ClosePrinter", CharSet:=CharSet.Auto, SetLastError:=True)>
Private Shared Function ClosePrinter(ByVal hPrinter As IntPtr) As Integer
End Function
Private Const ERROR_ACCESS_DENIED As Integer = &H5
Private Const PRINTER_ACCESS_ADMINISTER As Integer = &H4 'Printing-specific access rights for printers to perform administrative tasks
Private Const PRINTER_ACCESS_USE As Integer = &H8 'Printing-specific access rights for printers to perform basic printing operations
Private Const PRINTER_ACCESS_MANAGE_LIMITED As Integer = &H40 'Printing-specific access rights for printers to perform printer data management operations
Private Const PRINTER_ALL_ACCESS As Integer = &HF000C 'Access rights for printers to perform all administrative tasks and basic printing operations except synchronization. Combines WO (Write Owner), WD (Write DACL), RC (Read Control), and DE (Delete) of ACCESS_MASK with printing-specific PRINTER_ACCESS_ADMINISTER and printing-specific PRINTER_ACCESS_USE.
Private Const PRINTER_READ As Integer = &H20008 'Access rights for printers combining RC (Read Control) of ACCESS_MASK with printing-specific PRINTER_ACCESS_USE.

Related

How to fix RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters 1, True not updating every time

I have had a look at this StackOverflow article and the same thing applies to me. Why is it that RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters 1, True does not work everytime? Is there some other way to make it work rather than repeating that until it works or is there some way to code it so that it works? .cmd , .bat and .ps1 is fine) Or is the best/only way to run it alot of times so that it works
Right now my solution is to just run that multiple time until it works. Is there any other way to refresh the desktop wallpaper without running RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters 1, True alot of times?
From Help
https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-systemparametersinfow
Although this is from the 2001 documentation and has been removed from current.
Setting pvParam to "" removes the wallpaper. Setting pvParam to VBNULL
reverts to the default wallpaper.
REM ChangeWallpaper.bat
REM Compiles ChangeWallpaper.vb to ChangeWallpaper.exe
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\ChangeWallpaper.vb" /out:"%~dp0\ChangeWallpaper.exe" /target:winexe
pause
;ChangeWallpaper.vb
Imports System.Runtime.InteropServices
Public Module ChangeWallpaper
Public Declare Unicode Function SystemParametersInfoW Lib "user32" (ByVal uAction As Integer, ByVal uParam As Integer, ByVal lpvParam As String, ByVal fuWinIni As Integer) As Integer
Public Const SPI_SETDESKWALLPAPER = 20
Public Const SPIF_SENDWININICHANGE = &H2
Public Const SPIF_UPDATEINIFILE = &H1
Public Sub Main()
Dim Ret as Integer
Dim FName As String
Fname = "C:\Windows\Web\Wallpaper\Theme1\img1.jpg"
'This below line which is commented out takes a filename on the command line
'FName = Replace(Command(), """", "")
Ret = SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, FName, SPIF_SENDWININICHANGE + SPIF_UPDATEINIFILE)
If Ret = 0 Then Msgbox(err.lastdllerror)
End Sub
End Module
The code is from here https://winsourcecode.blogspot.com/2019/06/changewallpaper.html
Update
This is the problem with using it
Declare Function UpdatePerUserSystemParameters Lib "User32.dll" (ByVal i As Long, ByVal b As Boolean) As long
As you can see from the article Rundll32 is passing a hwnd (probably 0 to say Desktop is the parent) for j and RunDll32's HInst as a Boolean for b, and as this will be non zero it will be treated as true.

Run exe as impersonated account from vb.net

I am trying to run an exe from another account which has admin rights, I have this so far but its giving me an unknown error (0xfffffffe):
Private Shared Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As Int32) As Boolean
End Function
Public Sub RunAsAdmin()
Dim tokenHandle As New IntPtr(0)
If LogonUser(_ImpersinateUser, _ImpersinateDomain, _ImpersinatePassword, 2, 0, tokenHandle) Then
Dim newId As New WindowsIdentity(tokenHandle)
Using impersonatedUser As WindowsImpersonationContext = newId.Impersonate()
Dim p As New Process
p.StartInfo.FileName = "C:\\Temp\\MCPR.exe"
p.StartInfo.WindowStyle = ProcessWindowStyle.Normal
p.Start()
ShowWindow(p.MainWindowHandle, SW_RESTORE)
End Using
End If
End Sub

Is my WPF element visible on the screen or hidden by another window of any application

How do I know if an element in my WPF application, is hidden by another window of any application
Here are my example how I get information about open windows on the screen. For example: Is my application on top.
(the basic code I am learned in http://www.codeproject.com/Articles/19529/Is-My-Application-on-Top)
Declare Function GetTopWindow Lib "user32" Alias "GetTopWindow" (ByVal hwnd As Integer) As Integer
Declare Function GetNextWindow Lib "user32" Alias "GetWindow" (ByVal hwnd As Integer, ByVal wFlag As Integer) As Integer
Declare Function IsWindowVisible Lib "user32" Alias "IsWindowVisible" (ByVal hwnd As Integer) As Boolean
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Integer, ByVal lpString As String, ByVal cch As Integer) As Integer
Declare Function GetWindowRect Lib "user32" Alias "GetWindowRect" (ByVal hwnd As IntPtr, ByRef pwi As Rect) As Boolean
Function IsOnTop(ByVal hwnd As Integer) As Boolean
Dim i As Integer = GetTopWindow(0)
Dim x As Integer = 1
Dim s As String
Do
i = GetNextWindow(i, 2) ' Find next window in Z-order
If i = hwnd Then
Exit Do
Else
If i = 0 Then ' Never find any window match the input handle
Return False
End If
End If
If IsWindowVisible(i) = True Then
s = Space(256)
If GetWindowText(i, s, 255) <> 0 Then
' Very important to prevent confusing of BalloonTips and ContextMenuStrips
x += 1
End If
End If
Loop
' x is Z-order number
If x = 1 Then
Return True
Else
Return False
End If
End Function
Public Function GetWindowText(ByVal hWnd As IntPtr) As String
Dim s = Space(256)
GetWindowText(hWnd, s, 255)
Return s.ToString()
End Function
Function GetRectWindow(hwnd As Integer) As Rect
Dim rc As Rect
GetWindowRect(hwnd, rc)
Return rc
End Function
I need to know the width & height of other windows. Without this data, I still can not know about an element if it is hidden to the user. For example, in my application, I have a window that contains two DataGrid's, one of which may be hidden by other application.
The problem is, Although the GetRectWindow method returns this data, but, for example, it gives in Width property = 4.09332988076806E-311 and it should be 350. To my knowledge, it uses Twips unit. I converted it to pixel unit, but the result I got is an infinite number -0.
Here is a way :
Compute bounds of your visual relative to root visual (Visual.TransformToAncestor)
Compute bounds of your visual relative to screen (native GetWindowRect & GetClientRect)
Enumerate all top level windows (native EnumWindows)
Check for each windows if it's visible and if it overlaps the bounds of your visual (native GetWindowRect)

dal2 linq error in custom module when calling repository GetById

I have a simple custom module I am building but I have run into a problem when using the DAL2 GetById.
Here is the POCO declaration of the table i am using:
<TableName("KrisisStore_Products")> _
<PrimaryKey("ProductId", AutoIncrement:=True)> _
<Cacheable("Products", CacheItemPriority.Default, 20)> _
<Scope("PortalId")>
Public Class Product
Public Property ProductId As Int64
Public Property PortalId As Integer
Public Property ModuleId As Integer
''other columns here
End Class
I am attempting to delete a record from the database using the following (i removed other methods for clarity):
In the module view:
Dim pc As New ProductController
pc.DeleteItem(e.CommandArgument, PortalId)
Here is my product controller:
Imports System.Collections.Generic
Imports DotNetNuke.Data
Namespace Components
Public Class ProductController
Public Sub DeleteItem(ByVal itemId As Integer, ByVal PortalId As Integer)
Dim _item As Product = GetItem(itemId, PortalId)
DeleteItem(_item)
End Sub
Public Sub DeleteItem(ByVal p As Product)
Using ctx As IDataContext = DataContext.Instance()
Dim rep As IRepository(Of Product) = ctx.GetRepository(Of Product)()
rep.Delete(p)
End Using
End Sub
Public Function GetItem(ByVal itemId As Integer, ByVal PortalId As Integer) As Product
Dim p As Product
Using ctx As IDataContext = DataContext.Instance()
Dim rep As IRepository(Of Product) = ctx.GetRepository(Of Product)()
p = rep.GetById(Of Int32, Int32)(itemId, PortalId)
End Using
Return p
End Function
End Class
End Namespace
PROBLEM:
When the code gets to the following line in the GetITem function
p = rep.GetById(Of Int32, Int32)(itemId, PortalId)
The following error is generated:
Value cannot be null. Parameter name: source
Here is a little more detail from the stack trace:
InnerException: Value cannot be null. Parameter name: source
FileName:
FileLineNumber: 0
FileColumnNumber: 0
Method: System.Linq.Enumerable.SingleOrDefault
StackTrace:
Message: DotNetNuke.Services.Exceptions.ModuleLoadException: Value cannot be null. Parameter name: source ---> System.ArgumentNullException: Value cannot be null. Parameter name: source at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate) at DotNetNuke.Data.RepositoryBase`1.GetById[TProperty,TScopeType](TProperty id, TScopeType scopeValue) at Krisis.Modules.KrisisStore.Components.ProductController.GetItem(Int32 itemId, Int32 PortalId) in C:\websites\dnndev.me\DesktopModules\KrisisStore\Components\ProductController.vb:line 51
QUESTION
Can someone help me figure out why this linq error is being generated, the values being passed to the function are valid and the other repository function like GetItems work properly when supplied with a portalID as their scope.
In your model class, you defined the ProductId As Int64, but in your controller methods it is passed as an Integer or Int32. You would think this wouldn't matter, but I have experience other issues where PetaPoco requires very specific implementation in order to work properly. Perhaps this is an issue?
At first glance, it looks like the query is bringing back multiple records. Could there be more than one product row with that ID?

Add bitmap to resource

I am trying to add compressed bitmap as resource of another executable, but got stuck to an error. The error is:
Value of type 'System.Drawing.Bitmap' cannot be converted to '1-dimensional array of System.Drawing.Bitmap'
Here's my pseudo code:
Module1:
Imports System.Runtime.InteropServices
Module ResourceWriter
Private Function ToPtr(ByVal data As Object) As IntPtr
Dim h As GCHandle = GCHandle.Alloc(data, GCHandleType.Pinned)
Dim ptr As IntPtr
Try
ptr = h.AddrOfPinnedObject()
Finally
h.Free()
End Try
Return ptr
End Function
<DllImport("kernel32.dll", SetLastError:=True)> _
Private Function UpdateResource(ByVal hUpdate As IntPtr, ByVal lpType As String, ByVal lpName As String, ByVal wLanguage As UShort, ByVal lpData As IntPtr, ByVal cbData As UInteger) As Boolean
End Function
<DllImport("kernel32.dll", SetLastError:=True)> _
Private Function BeginUpdateResource(ByVal pFileName As String, <MarshalAs(UnmanagedType.Bool)> ByVal bDeleteExistingResources As Boolean) As IntPtr
End Function
<DllImport("kernel32.dll", SetLastError:=True)> _
Private Function EndUpdateResource(ByVal hUpdate As IntPtr, ByVal fDiscard As Boolean) As Boolean
End Function
Public Function WriteResource(ByVal filename As String, ByVal bmp As Bitmap()) As Boolean
Try
Dim handle As IntPtr = BeginUpdateResource(filename, False)
Dim file1 As Bitmap() = bmp
Dim fileptr As IntPtr = ToPtr(file1)
Dim res As Boolean = UpdateResource(handle, "BitMaps", "0", 0, fileptr, Convert.ToUInt32(file1.Length))
EndUpdateResource(handle, False)
Catch ex As Exception
Return False
End Try
Return True
End Function
End Module
In form, under button:
'...here's code to compress the image, commented out for now
Dim bmp1 As Bitmap = Compressed
WriteResource("C:\Users\Admin\Desktop\Testfile.exe", bmp1)
But it doesn't work. What changes I should make to the module, or to the code under button? I see I should convert System.Drawing.Bitmap to 1-dimensional array before putting the image into the resources, but how?
Any help is much appreciated :)
Edit:
I have now tried all answers I found from google & MSDN, and I cannot figure it out. So if anyone could just show how to do it, I would really appreciate it..
Here's one of the methods I tried.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'...
Dim bmp1 As Bitmap = Compressed
Dim Converted = ConvertToByteArray(bmp1)
WriteResource("C:\Users\Admin\Desktop\Testfile.exe", Converted)
End Sub
Public Shared Function ConvertToByteArray(ByVal value As Bitmap) As Byte()
Dim bitmapBytes As Byte()
Using stream As New System.IO.MemoryStream
value.Save(stream, value.RawFormat)
bitmapBytes = stream.ToArray
End Using
Return bitmapBytes
End Function
And yes, I changed the Bitmap() to Byte() at Module1; but it returned "Value cannot be NULL" in runtime.
I also tried to save it as IO.MemoryStream and then convert to bytes but didn't success.
So if anyone could show me how to do this, that would be really great.
You declared the parameter as a Bitmap array by putting () after the type name here:
Public Function WriteResource(ByVal filename As String, ByVal bmp As Bitmap()) As Boolean
If you don't want it to be an array, remove the ():
Public Function WriteResource(ByVal filename As String, ByVal bmp As Bitmap) As Boolean
The first problem you have is well covered in Ryan's answer (Dim file1 As Bitmap() = bmp is wrong too); the second is that you are covering up a different problem.
If you refer to UpdateResource on MSDN you'll see that cbdata is the number of bytes to write, that is the byte count of the bitmap. Your code is passing the size of the array. Further, lpData is supposed to be a long pointer to the data and also "Note that this is the raw binary data to be stored". You cannot just pass a bitmap as you are trying to do.
The bitmap class's save method will let you save to a memorystream from which the bytes AND BYTE COUNT can be gotten and fed to UpdateResource.

Resources