tags:

views:

457

answers:

4

i tried the code below to convert it to c#. But i am getting many errors when i use it. Like error related to || and && symbols using in c# version.

can any one help me to convert to perfect c# code ?? Thanks.

Option Explicit On 
Option Strict On

Imports Microsoft.Win32
Imports System.Runtime.InteropServices

Public Class Kiosk
    Implements IDisposable

#Region "IDisposable"

    '' Implementing IDisposable since it might be possible for
    '' someone to forget to cause the unhook to occur.  I didn''t really
    '' see any problems with this in testing, but since the SDK says
    '' you should do it, then here''s a way to make sure it will happen.

    Public Overloads Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            '' Free other state (managed objects).
        End If
        If m_hookHandle <> 0 Then
            UnhookWindowsHookEx(m_hookHandle)
            m_hookHandle = 0
        End If
        If m_taskManagerValue > -1 Then
            EnableTaskManager()
        End If
    End Sub

    Protected Overrides Sub Finalize()
        Dispose(False)
    End Sub

#End Region

    Shared Sub main()

    End Sub
    Private Delegate Function LowLevelHookDelegate(ByVal code As Integer, ByVal wParam As Integer, ByRef lParam As KeyboardLowLevelHookStruct) As Integer

    Private Const Hc_Action As Integer = 0
    Private Const WindowsHookKeyboardLowLevel As Integer = 13
    Private Const LowLevelKeyboardHfAltDown As Integer = &H20

    Private Enum WindowsMessage
        KeyDown = &H100
        KeyUp = &H101
        SystemKeyDown = &H104
        SystemKeyUp = &H105
    End Enum

    Private Enum Vk
        Tab = &H9
        Escape = &H1B
        Shift = &H10
        Control = &H11
        Menu = &H12         '' ALT key.
        Alt = &H12
        Pause = &H13
        LeftWindows = &H5B  '' Left Windows key (Microsoft® Natural® keyboard).
        RightWindows = &H5C '' Right Windows key (Natural keyboard).
        Applications = &H5D '' Applications key (Natural keyboard).
    End Enum

    Private Structure KeyboardLowLevelHookStruct
        Public VirtualKeyCode As Integer
        Public ScanCode As Integer
        Public Flags As Integer
        Public Time As Integer
        Public ExtraInfo As UInt32
    End Structure

    Private Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal hook As Integer, ByVal address As LowLevelHookDelegate, ByVal [mod] As Integer, ByVal threadId As Integer) As Integer
    Private Declare Function CallNextHookEx Lib "user32" (ByVal handle As Integer, ByVal code As Integer, ByVal wParam As Integer, ByVal lParam As KeyboardLowLevelHookStruct) As Integer
    Private Declare Function UnhookWindowsHookEx Lib "user32" (ByVal handle As Integer) As Integer
    Private Declare Function GetAsyncKeyState Lib "user32" (ByVal virtualKey As Integer) As Integer

    Private m_hookHandle As Integer

    Private Function LowLevelHook(ByVal code As Integer, ByVal wParam As Integer, ByRef lParam As KeyboardLowLevelHookStruct) As Integer

        If code = Hc_Action Then

            If (wParam = WindowsMessage.KeyDown) OrElse _
               (wParam = WindowsMessage.SystemKeyDown) OrElse _
               (wParam = WindowsMessage.KeyUp) OrElse _
               (wParam = WindowsMessage.SystemKeyUp) Then

                ''Dim alt As Boolean = (GetAsyncKeyState(Vk.Alt) And &H8000) = &H8000
                ''Dim shift As Boolean = (GetAsyncKeyState(Vk.Shift) And &H8000) = &H8000
                Dim control As Boolean = (GetAsyncKeyState(Vk.Control) And &H8000) = &H8000

                Dim suppress As Boolean

                '' CTRL+ESC
                If control AndAlso lParam.VirtualKeyCode = Vk.Escape Then
                    suppress = True
                End If

                '' ALT+TAB
                If (lParam.Flags And LowLevelKeyboardHfAltDown) = LowLevelKeyboardHfAltDown AndAlso lParam.VirtualKeyCode = Vk.Tab Then
                    suppress = True
                End If

                '' ALT+ESC
                If (lParam.Flags And LowLevelKeyboardHfAltDown) = LowLevelKeyboardHfAltDown AndAlso lParam.VirtualKeyCode = Vk.Escape Then
                    suppress = True
                End If

                '' Left Windows button.
                If lParam.VirtualKeyCode = Vk.LeftWindows Then
                    suppress = True
                    MessageBox.Show("Pressed Left windows key")
                End If

                '' Right Windows button.
                If lParam.VirtualKeyCode = Vk.RightWindows Then
                    suppress = True
                    MessageBox.Show("Pressed Right windows key")
                End If

                '' Applications button.
                If lParam.VirtualKeyCode = Vk.Applications Then
                    suppress = True
                End If

                If suppress Then
                    Return 1
                End If

            End If

            Return CallNextHookEx(m_hookHandle, code, wParam, lParam)

        End If

    End Function

    Public Sub Disable()
        If m_hookHandle = 0 Then
            m_hookHandle = SetWindowsHookEx(WindowsHookKeyboardLowLevel, AddressOf LowLevelHook, Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly.GetModules()(0)).ToInt32, 0)
        End If
    End Sub

    Public Sub Enable()
        If m_hookHandle <> 0 Then
            UnhookWindowsHookEx(m_hookHandle)
            m_hookHandle = 0
        End If
    End Sub

End Class
+3  A: 

First, the provided code will not compile because of it calling a method EnableTaskManager() that does not exists in the example code. But just to go around that problem, I changed it to call the Enable-function that DOES exist in the example.

The provided code did also use a variable that was not declared anywhere in the code: m_taskManagerValue, to get around that I declaraed that as an int=0 in my example.

Also, the function LowLevelHook did not return a value on one codepath so I just added so it returned 0 in that case (I dont know what it suppose to return there)

And finally, C# didn't like the sub Finally with the dispose so I just deleted it. ;)

Well. After that fixed I converted the code to C# here http://www.developerfusion.com/tools/convert/vb-to-csharp/

I fixed the errors where it complained about comparing a int with a non-int by ctype the value to int.

And then I compiled the vb-version and looked in it with reflection to get the SetWindowHookEx-row to work.

And voila, this will compile:

using System;
using System.Configuration;
using System.Xml;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Reflection;
using Microsoft.VisualBasic;

public class Kiosk1 : IDisposable
{

    #region "IDisposable"

    // Implementing IDisposable since it might be possible for
    // someone to forget to cause the unhook to occur. I didn't really
    // see any problems with this in testing, but since the SDK says
    // you should do it, then here's a way to make sure it will happen.

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    int m_taskManagerValue=0;

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
        }
        // Free other state (managed objects).
        if (m_hookHandle != 0)
        {
            UnhookWindowsHookEx(m_hookHandle);
            m_hookHandle = 0;
        }
        if (m_taskManagerValue > -1)
        {
            Enable();
        }
    }



    #endregion

    public static void main()
    {

    }
    private delegate int LowLevelHookDelegate(int code, int wParam, ref KeyboardLowLevelHookStruct lParam);

    private const int Hc_Action = 0;
    private const int WindowsHookKeyboardLowLevel = 13;
    private const int LowLevelKeyboardHfAltDown = 0x20;

    private enum WindowsMessage
    {
        KeyDown = 0x100,
        KeyUp = 0x101,
        SystemKeyDown = 0x104,
        SystemKeyUp = 0x105
    }

    private enum Vk
    {
        Tab = 0x9,
        Escape = 0x1b,
        Shift = 0x10,
        Control = 0x11,
        Menu = 0x12,
        // ALT key.
        Alt = 0x12,
        Pause = 0x13,
        LeftWindows = 0x5b,
        // Left Windows key (Microsoft® Natural® keyboard).
        RightWindows = 0x5c,
        // Right Windows key (Natural keyboard).
        Applications = 0x5d
        // Applications key (Natural keyboard).
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct KeyboardLowLevelHookStruct
    {
        public int VirtualKeyCode;
        public int ScanCode;
        public int Flags;
        public int Time;
        public UInt32 ExtraInfo;
    }
    [DllImport("user32", EntryPoint = "SetWindowsHookExA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    private static extern int SetWindowsHookEx(int hook, LowLevelHookDelegate address, int mod, int threadId);
    [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    private static extern int CallNextHookEx(int handle, int code, int wParam, KeyboardLowLevelHookStruct lParam);
    [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    private static extern int UnhookWindowsHookEx(int handle);
    [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    private static extern int GetAsyncKeyState(int virtualKey);


    private int m_hookHandle;

    private int LowLevelHook(int code, int wParam, ref KeyboardLowLevelHookStruct lParam)
    {

        if (code == Hc_Action)
        {

            if ((wParam == (int)WindowsMessage.KeyDown) || (wParam == (int)WindowsMessage.SystemKeyDown) || (wParam == (int)WindowsMessage.KeyUp) || (wParam == (int)WindowsMessage.SystemKeyUp))
            {

                //Dim alt As Boolean = (GetAsyncKeyState(Vk.Alt) And &H8000) = &H8000
                //Dim shift As Boolean = (GetAsyncKeyState(Vk.Shift) And &H8000) = &H8000
                bool control = (GetAsyncKeyState((int)Vk.Control) & 0x8000) == 0x8000;

                bool suppress = false;

                // CTRL+ESC
                if (control && lParam.VirtualKeyCode == (int)Vk.Escape)
                {
                    suppress = true;
                }

                // ALT+TAB
                if ((lParam.Flags & LowLevelKeyboardHfAltDown) == LowLevelKeyboardHfAltDown && lParam.VirtualKeyCode == (int)Vk.Tab)
                {
                    suppress = true;
                }

                // ALT+ESC
                if ((lParam.Flags & LowLevelKeyboardHfAltDown) == LowLevelKeyboardHfAltDown && lParam.VirtualKeyCode == (int)Vk.Escape)
                {
                    suppress = true;
                }

                // Left Windows button.
                if (lParam.VirtualKeyCode == (int)Vk.LeftWindows)
                {
                    suppress = true;
                    MessageBox.Show("Pressed Left windows key");
                }

                // Right Windows button.
                if (lParam.VirtualKeyCode == (int)Vk.RightWindows)
                {
                    suppress = true;
                    MessageBox.Show("Pressed Right windows key");
                }

                // Applications button.
                if (lParam.VirtualKeyCode == (int)Vk.Applications)
                {
                    suppress = true;
                }

                if (suppress)
                {
                    return 1;

                }
            }


            return CallNextHookEx(m_hookHandle, code, wParam, lParam);

        }
        return 0;
    }

    public void Disable()
    {
        if (m_hookHandle == 0)
        {

            m_hookHandle = SetWindowsHookEx(WindowsHookKeyboardLowLevel, new LowLevelHookDelegate(this.LowLevelHook), Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]).ToInt32(), 0);
        }
    }

    public void Enable()
    {
        if (m_hookHandle != 0)
        {
            UnhookWindowsHookEx(m_hookHandle);
            m_hookHandle = 0;
        }
    }

}
Stefan
I tried converting the code in all the sites provided.All the converted codes are throwing same errors.There are totally 22 errors.If the code is pasted in a class file and builded. You can see the problem.Please help.
Anuya
Fixed what I could and updated my answer.
Stefan
Updated one more time, now with a version that compiles.
Stefan
+1  A: 

Try this link (Convert VB.NET to C# online)

More good converters

http://converter.telerik.com/

http://www.carlosag.net/Tools/CodeTranslator/

Bye.

RRUZ
I tried converting the code in all the sites provided. All the converted codes are throwing same errors. There are totally 22 errors. If the code is pasted in a class file and builded. You can see the problem. Please help. –
Anuya
A: 

Another way is to compile the dll and then read it in with reflector. You can choose the language reflector is dissasembling the il to.

Stormenet
Sorry for downvoting, but this will produce unmaintainable code. The single and only reason to do this is when you want to merge an VB Lib and an C# lib/codebase in one DLL for final release.
Dykam
reflector's exported code often needs lots of cleaning up, especially if it's being used for translations--it's useful in a pinch but definately not a silver bullet
STW
Reflector solved the problem for me, I could'nt fix the SetWindowsHookEx-row, had no Idea to what to do. Compiled the VB-code, checked just that row in Reflector and got the solution. So it can be good to fix those things where you are stuck.
Stefan
@Dykam: That's okay :) Just offered a fallback solution when you bump into some "auto-converter" weirdness, not the holy grail :p
Stormenet
+2  A: 

Telerik has a great free online converter

The following was produced by their converter:

using Microsoft.Win32;
using System.Runtime.InteropServices;

public class Kiosk : IDisposable
{
#region "IDisposable"

    //' Implementing IDisposable since it might be possible for
    //' someone to forget to cause the unhook to occur.  I didn''t really
    //' see any problems with this in testing, but since the SDK says
    //' you should do it, then here''s a way to make sure it will happen.

    public void IDisposable.Dispose()
    {
     Dispose(true);
     GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
     if (disposing) {
      //' Free other state (managed objects).
     }
     if (m_hookHandle != 0) {
      UnhookWindowsHookEx(m_hookHandle);
      m_hookHandle = 0;
     }
     if (m_taskManagerValue > -1) {
      EnableTaskManager();
     }
    }

    protected override void Finalize()
    {
     Dispose(false);
    }
#endregion

    static void main()
    {

    }
    private delegate int LowLevelHookDelegate(int code, int wParam, ref KeyboardLowLevelHookStruct lParam);

    private const int Hc_Action = 0;
    private const int WindowsHookKeyboardLowLevel = 13;
    private const int LowLevelKeyboardHfAltDown = 0x20;

    private enum WindowsMessage
    {
     KeyDown = 0x100,
     KeyUp = 0x101,
     SystemKeyDown = 0x104,
     SystemKeyUp = 0x105
    }

    private enum Vk
    {
     Tab = 0x9,
     Escape = 0x1b,
     Shift = 0x10,
     Control = 0x11,
     Menu = 0x12,
     //' ALT key.
     Alt = 0x12,
     Pause = 0x13,
     LeftWindows = 0x5b,
     //' Left Windows key (Microsoft® Natural® keyboard).
     RightWindows = 0x5c,
     //' Right Windows key (Natural keyboard).
     Applications = 0x5d
     //' Applications key (Natural keyboard).
    }

    private struct KeyboardLowLevelHookStruct
    {
     public int VirtualKeyCode;
     public int ScanCode;
     public int Flags;
     public int Time;
     public UInt32 ExtraInfo;
    }


 // ERROR: Not supported in C#: DeclareDeclaration
 // ERROR: Not supported in C#: DeclareDeclaration
 // ERROR: Not supported in C#: DeclareDeclaration
 // ERROR: Not supported in C#: DeclareDeclaration
    private int m_hookHandle;

    private int LowLevelHook(int code, int wParam, ref KeyboardLowLevelHookStruct lParam)
    {

     if (code == Hc_Action) {

      if ((wParam == WindowsMessage.KeyDown) || (wParam == WindowsMessage.SystemKeyDown) || (wParam == WindowsMessage.KeyUp) || (wParam == WindowsMessage.SystemKeyUp)) {

       //'Dim alt As Boolean = (GetAsyncKeyState(Vk.Alt) And &H8000) = &H8000
       //'Dim shift As Boolean = (GetAsyncKeyState(Vk.Shift) And &H8000) = &H8000
       bool control = (GetAsyncKeyState(Vk.Control) & 0x8000) == 0x8000;

       bool suppress;

       //' CTRL+ESC
       if (control && lParam.VirtualKeyCode == Vk.Escape) {
        suppress = true;
       }

       //' ALT+TAB
       if ((lParam.Flags & LowLevelKeyboardHfAltDown) == LowLevelKeyboardHfAltDown && lParam.VirtualKeyCode == Vk.Tab) {
        suppress = true;
       }

       //' ALT+ESC
       if ((lParam.Flags & LowLevelKeyboardHfAltDown) == LowLevelKeyboardHfAltDown && lParam.VirtualKeyCode == Vk.Escape) {
        suppress = true;
       }

       //' Left Windows button.
       if (lParam.VirtualKeyCode == Vk.LeftWindows) {
        suppress = true;
        MessageBox.Show("Pressed Left windows key");
       }

       //' Right Windows button.
       if (lParam.VirtualKeyCode == Vk.RightWindows) {
        suppress = true;
        MessageBox.Show("Pressed Right windows key");
       }

       //' Applications button.
       if (lParam.VirtualKeyCode == Vk.Applications) {
        suppress = true;
       }

       if (suppress) {
        return 1;
       }

      }

      return CallNextHookEx(m_hookHandle, code, wParam, lParam);

     }

    }

    public void Disable()
    {
     if (m_hookHandle == 0) {
      m_hookHandle = SetWindowsHookEx(WindowsHookKeyboardLowLevel, LowLevelHook, Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly.GetModules()(0)).ToInt32, 0);
     }
    }

    public void Enable()
    {
     if (m_hookHandle != 0) {
      UnhookWindowsHookEx(m_hookHandle);
      m_hookHandle = 0;
     }
    }

}
Alison