arabic text printing using raw printing in c# - vb.net

I need to print arabic text using raw printing am using below code. But its printing ????? instated of text
Public Function SendStringToPrinter(szPrinterName As String, szString As String) As Boolean
If PrinterOpen Then
Dim pBytes As IntPtr
Dim dwCount As Int32
Dim dwWritten As Int32 = 0
dwCount = szString.Length
pBytes = Marshal.StringToCoTaskMemAnsi(szString)
SendStringToPrinter = WritePrinter(hPrinter, pBytes, dwCount, dwWritten)
Marshal.FreeCoTaskMem(pBytes)
Else
SendStringToPrinter = False
End If
End Function

Related

How to avoid text to flicker using Windows.media.ocr and timer control

I'm scanning some text in the screen using Windows.Media.Ocr under a timer control, firing the tick event every 200 ms.
I'm then displaying the output in a richtextbox that is unfortunately flickering..
I made a gif to show the issue ( the ocr is on purpose scanning just the values with M)
is there any way to stop this behavior? Thanks
The code I'm using inside of the timer is:
Dim softwareBmp As Windows.Graphics.Imaging.SoftwareBitmap
Using bmp As Bitmap = New Bitmap(PictureBox1.Width, PictureBox1.Height)
Using g As Graphics = Graphics.FromImage(bmp)
Dim pt As Point = Me.PointToScreen(New Point(PictureBox1.Left, PictureBox1.Top))
g.CopyFromScreen(pt.X, pt.Y, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy)
Using memStream = New Windows.Storage.Streams.InMemoryRandomAccessStream()
bmp.Save(memStream.AsStream(), System.Drawing.Imaging.ImageFormat.Bmp)
Dim decoder As Windows.Graphics.Imaging.BitmapDecoder = Await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(memStream)
softwareBmp = Await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, BitmapAlphaMode.Ignore)
End Using
End Using
End Using
Dim ocrEng = OcrEngine.TryCreateFromLanguage(New Windows.Globalization.Language("en-US"))
Dim languages As IReadOnlyList(Of Windows.Globalization.Language) = ocrEng.AvailableRecognizerLanguages
For Each language In languages
Console.WriteLine(language.LanguageTag)
Next
Dim r = ocrEng.RecognizerLanguage
Dim n = ocrEng.MaxImageDimension
Dim ocrResult = Await ocrEng.RecognizeAsync(softwareBmp)
RichTextBox1.Clear()
Dim wordList As List(Of cText) = New List(Of cText)()
Dim lines As IReadOnlyList(Of OcrLine) = ocrResult.Lines
For Each line In lines
For Each word In line.Words
Dim nY As Double = CLng(word.BoundingRect.Bottom / 10) * 10
wordList.Add(New cText() With {.Text = word.Text, .LocY = nY, .LocX = word.BoundingRect.Left})
Next
Next
wordList.Sort(New WordComparer())
Dim oldLocY As Double = 0
For Each item As cText In wordList
If (item.LocY > oldLocY And oldLocY <> 0) Then
RichTextBox1.Text += Environment.NewLine
End If
RichTextBox1.Text += (item.Text + " ")
oldLocY = item.LocY
Next
I solved using WM_SETREDRAW
<DllImport("User32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)>
Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As IntPtr) As Integer
End Function
Public Const WM_SETREDRAW As Integer = &HB
Before adding lines (before RichTextBox1.Clear())
If (RichTextBox1.IsHandleCreated) Then
SendMessage(RichTextBox1.Handle, WM_SETREDRAW, 0, IntPtr.Zero)
End If
After lines have been added :
If (RichTextBox1.IsHandleCreated) Then
SendMessage(RichTextBox1.Handle, WM_SETREDRAW, 1, IntPtr.Zero)
RichTextBox1.Invalidate()
End If

Decode base64 returns foreign characters

Two methods, one to encode base64 and the other to UndEncode base64 - using the sample string "password" the encoded result is: OY5QsDipwgvvhHZk32fzG7vd7m4jvhPr9gyP6smEARE=
When using the above result to UnEncode, the following is the result: 猀猀眀漀爀搀�
passwordFormat = 2
Why is this returning Chinese characters instead of US?
Public Function EncodePassword(ByVal pass As String, ByVal passwordFormat As Integer, ByVal salt As String) As String
If passwordFormat = 0 Then Return pass
Dim bIn As Byte() = Encoding.Unicode.GetBytes(pass)
Dim bSalt As Byte() = Convert.FromBase64String(salt)
Dim bAll As Byte() = New Byte(bSalt.Length + bIn.Length - 1) {}
Dim bRet As Byte() = Nothing
Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length)
Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length)
If passwordFormat = 1 Then
Dim s As HashAlgorithm = HashAlgorithm.Create(_HashAlgorithmType)
If s Is Nothing Then
Throw New ProviderException("Could not create a hash algorithm")
End If
bRet = s.ComputeHash(bAll)
Else
bRet = EncryptPassword(bAll)
End If
Return Convert.ToBase64String(bRet)
End Function
Public Function UnEncodePassword(ByVal pass As String, ByVal passwordFormat As Integer) As String
Select Case passwordFormat
Case 0
Return pass
Case 1
Throw New ProviderException("Provider can not decode hashed password")
Case Else
Dim bIn As Byte() = Convert.FromBase64String(pass)
Dim bRet As Byte() = DecryptPassword(bIn)
If bRet Is Nothing Then Return Nothing
'Return Encoding.Unicode.GetString(bRet)
Return Encoding.Unicode.GetString(bRet, SALT_SIZE_IN_BYTES, bRet.Length - SALT_SIZE_IN_BYTES)
End Select
End Function

How to find a displayversion for a specific installed program in vb.net

I'm trying get a displayversion for a specific program in uninstall registry path. I can get it from a direct path or get the whole uninstall listed, but I cannot get it to find a specific program based on displayname and returns displayversion. Thank you if you can help or provide instruction.
Public Function GetDisplayLink() As String
On Error Resume Next
Dim strRegPath As String = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{772811A3-D34B-4594-AF3E-A7C655013E62}\"
Dim regVersion64 As Microsoft.Win32.RegistryKey = Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, strWorkstation, Microsoft.Win32.RegistryView.Registry64).OpenSubKey(strRegPath)
Dim strDisplayLink As String = regVersion64.GetValue("DisplayVersion")
GetDisplayLink = "DisplayLink Driver|" & strDisplayLink & "<BR>"
regVersion64 = Nothing
End Function
I cannot get it to find a specific program based on displayname and
returns displayversion.
There are several ways (WMI, Shell, Msi, ...)
WMI is the simplest one but slow
A sample with Msi, test with "Microsoft Silverlight" on Windows 10 =>
Dim sProductName As String = "Microsoft Silverlight"
Dim nResult As UInteger = 0
Dim sProductCode As StringBuilder = New StringBuilder(256)
Dim nIndex As Integer = 0
Do While (True)
nResult = MsiEnumProducts(nIndex, sProductCode)
If (nResult <> 0) Then
Exit Do
End If
Dim nSize As Integer = 256
Dim sbProductName As StringBuilder = New StringBuilder(nSize)
nResult = MsiGetProductInfo(sProductCode.ToString(), "InstalledProductName", sbProductName, nSize)
If (sbProductName.ToString() = sProductName) Then
nSize = 256
Dim sbVersionString As StringBuilder = New StringBuilder(nSize)
nResult = MsiGetProductInfo(sProductCode.ToString(), "VersionString", sbVersionString, nSize)
Console.WriteLine("Product: {0}", sProductName)
Console.WriteLine(vbTab + "Code: {0}", sProductCode.ToString())
Console.WriteLine(vbTab + "Version: {0}", sbVersionString.ToString())
Exit Do
End If
nIndex += 1
Loop
With declarations :
<DllImport("Msi.dll", SetLastError:=True, CharSet:=CharSet.Unicode)>
Public Shared Function MsiEnumProducts(iProductIndex As Integer, lpProductBuf As StringBuilder) As UInteger
End Function
<DllImport("Msi.dll", SetLastError:=True, CharSet:=CharSet.Unicode)>
Public Shared Function MsiGetProductInfo(szProduct As String, szAttribute As String, lpValueBuf As StringBuilder, ByRef pcchValueBuf As Integer) As UInteger
End Function

Failed to write multilined result to text file vb.net

I have this function which return all TCP connections for all proccess
Declare Auto Function GetExtendedTcpTable Lib "iphlpapi.dll" (ByVal pTCPTable As IntPtr, ByRef OutLen As Integer, ByVal Sort As Boolean, ByVal IpVersion As Integer, ByVal dwClass As Integer, ByVal Reserved As Integer) As Integer
Const TCP_TABLE_OWNER_PID_ALL As Integer = 5
<StructLayout(LayoutKind.Sequential)> _
Public Structure MIB_TCPTABLE_OWNER_PID
Public NumberOfEntries As Integer 'number of rows
Public Table As IntPtr 'array of tables
End Structure
<StructLayout(LayoutKind.Sequential)> _
Public Structure MIB_TCPROW_OWNER_PID
Public state As Integer 'state of the connection
Public localAddress As UInteger
Public LocalPort As Integer
Public RemoteAddress As UInteger
Public remotePort As Integer
Public PID As Integer 'Process ID
End Structure
Structure TcpConnection
Public State As TcpState
Public localAddress As String
Public LocalPort As Integer
Public RemoteAddress As String
Public remotePort As Integer
Public Proc As String
End Structure
Function GetAllTCPConnections() As MIB_TCPROW_OWNER_PID()
GetAllTCPConnections = Nothing
Dim cb As Integer
GetExtendedTcpTable(Nothing, cb, False, 2, TCP_TABLE_OWNER_PID_ALL, 0)
Dim tcptable As IntPtr = Marshal.AllocHGlobal(cb)
If GetExtendedTcpTable(tcptable, cb, False, 2, TCP_TABLE_OWNER_PID_ALL, 0) = 0 Then
Dim tab As MIB_TCPTABLE_OWNER_PID = Marshal.PtrToStructure(tcptable, GetType(MIB_TCPTABLE_OWNER_PID))
Dim Mibs(tab.NumberOfEntries - 1) As MIB_TCPROW_OWNER_PID
Dim row As IntPtr
For i As Integer = 0 To tab.NumberOfEntries - 1
row = New IntPtr(tcptable.ToInt32 + Marshal.SizeOf(tab.NumberOfEntries) + Marshal.SizeOf(GetType(MIB_TCPROW_OWNER_PID)) * i)
Mibs(i) = Marshal.PtrToStructure(row, GetType(MIB_TCPROW_OWNER_PID))
Next
GetAllTCPConnections = Mibs
End If
Marshal.FreeHGlobal(tcptable)
End Function
Function MIB_ROW_To_TCP(ByVal row As MIB_TCPROW_OWNER_PID) As TcpConnection
Dim tcp As New TcpConnection
tcp.State = DirectCast(row.state, TcpState) 'a State enum is better than an int
Dim ipad As New IPAddress(row.localAddress)
tcp.localAddress = ipad.ToString
tcp.LocalPort = row.LocalPort / 256 + (row.LocalPort Mod 256) * 256
ipad = New IPAddress(row.RemoteAddress)
tcp.RemoteAddress = ipad.ToString
tcp.remotePort = row.remotePort / 256 + (row.remotePort Mod 256) * 256
Dim p As Process = Process.GetProcessById(row.PID)
tcp.Proc = p.ProcessName
p.Dispose()
Return tcp
End Function
I wan't to store only the out going connections of certain processes in a text file so I used
Sub main()
For Each Row In GetAllTCPConnections()
Dim Tcp As TcpConnection = MIB_ROW_To_TCP(Row)
Dim RemoteAddress As String = Tcp.RemoteAddress.ToString
Dim process As String = Tcp.Proc
If (process = "chrome" Or process = "Viber" Or process = "ddns") And (RemoteAddress <> "127.0.0.1") And (RemoteAddress <> "0.0.0.0") Then
Dim myFile As String = "C:\TCP.txt"
Using sw As StreamWriter = New StreamWriter(myFile)
Dim line As String = Tcp.RemoteAddress & "|" & Tcp.localAddress & "|" & Tcp.LocalPort & "|" & Tcp.Proc
sw.WriteLine(line)
MsgBox(line)
End Using
End If
Next
End Sub
msgbox works fine showing every process and out going connections that established by it but when I open
TCP.txt
file I only find one line.
So how to write the entire results (Each process with its out going connections) to the text file?
You need to set the append to text file.
You need to change:
Using sw As StreamWriter = New StreamWriter(myFile)
To
Using sw As StreamWriter = New StreamWriter(myFile, True)
By setting the true you set the append to file to true

How would I write this VB.Net loop functionally?

I have a VB.Net function that translates a NameValueColletion to an IDictionary. How would I write this functionally (with Select, etc. instead of a loop)?
<Extension()>
Public Function ToDictionary(ByVal source As NameValueCollection)
As IDictionary(Of String, String)
Dim ret = New Dictionary(Of String, String)
Dim keys = source.Keys
For Each key In keys
Dim sKey = TryCast(key, String)
Dim sVal = TryCast(source(key), String)
If sKey Is Nothing OrElse sVal Is Nothing Then Continue For
ret(sKey) = sVal
Next
Return ret
End Function
Return source.Cast(Of String)().
ToDictionary(Function(key) key, Function(key) source(key))