Solved

<DllImport> examples needed !!

Posted on 2007-11-17
3
2,793 Views
Last Modified: 2013-12-17
Hi,

I have the following info from web:

VB.NET
======

<DllImport("User32.dll")> _
Public Shared Function MessageBox(ByVal [Hwnd] As Integer, ByVal [text] As String, _
                                                            ByVal [Caption] As String, ByVal [Type] As Integer) As Integer
EndFunction

C#.NET
======

[DllImport("User32.dll")]
public static extern int MessageBox(int [Hwnd], string [text], string [Caption], int [Type]);

Why we are using "extern" in C#.NET ? Can you please provide me entire code in both VB.NET and C#.NET for this example including calling of this Win32 API?

Thanks
0
Comment
Question by:kishore_peddi
3 Comments
 
LVL 29

Assisted Solution

by:Gautham Janardhan
Gautham Janardhan earned 110 total points
ID: 20303669
           #region---GetKeyboardState---
            [DllImport("user32.dll", CharSet = CharSet .Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
            static extern bool GetKeyboardState(byte[] lpKeyState);            

public static bool CapsOn()
            {
                  byte[] Bytes = new byte[256];
                  GetKeyboardState(Bytes);
                  return Convert.ToBoolean( ( Bytes[(int )
                        System.Windows.Forms.Keys.Capital]));
            }
0
 
LVL 4

Assisted Solution

by:JunnickYso
JunnickYso earned 190 total points
ID: 20303688
In this example retrieving Winamp Song Title:
the complete C# .net CODE:

[System.Runtime.InteropServices.DllImport("user32.dll",
  CharSet=System.Runtime.InteropServices.CharSet.Auto)]
public static extern IntPtr FindWindow(string lpClassName,
  string lpWindowName);
 
[System.Runtime.InteropServices.DllImport("user32.dll",
  CharSet=System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetWindowText(IntPtr hwnd,
  string lpString, int cch);
 
const string lpClassName = "Winamp v1.x";
const string strTtlEnd = " - Winamp";
 
static string GetSongTitle()
{
      IntPtr hwnd = FindWindow(lpClassName, null);
      if (hwnd.Equals(IntPtr.Zero)) return "Not running";
 
      string lpText = new string((char) 0, 100);
      int intLength = GetWindowText(hwnd, lpText, lpText.Length);
           
      if ((intLength <= 0) || (intLength > lpText.Length))
        return "unknown";
 
      string strTitle = lpText.Substring(0, intLength);
      int intName = strTitle.IndexOf(strTtlEnd);
      int intLeft = strTitle.IndexOf("[");
      int intRight = strTitle.IndexOf("]");
 
      if ((intName >= 0) && (intLeft >= 0) && (intName < intLeft) &&
          (intRight >= 0) && (intLeft + 1 < intRight))
            return strTitle.Substring(intLeft + 1, intRight - intLeft - 1);
 
      if ((strTitle.EndsWith(strTtlEnd)) && 
            (strTitle.Length > strTtlEnd.Length))
            strTitle = strTitle.Substring(0,
                strTitle.Length - strTtlEnd.Length);
 
      int intDot = strTitle.IndexOf(".");
      if ((intDot > 0) && IsNumeric(strTitle.Substring(0, intDot)))
            strTitle = strTitle.Remove(0, intDot + 1);
 
      return strTitle.Trim();
}
 
static bool IsNumeric(string Value)
{
      try
      {
            double.Parse(Value);
            return true;
      }
      catch
      {
            return false;
      }
}


the Complete VB.net CODE:

Private Declare Auto Function FindWindow Lib "user32" ( _
  ByVal lpClassName As String, _
  ByVal lpWindowName As String) As IntPtr
Private Declare Auto Function GetWindowText Lib "user32" ( _
   ByVal hwnd As IntPtr, _
   ByVal lpString As String, _
   ByVal cch As Integer) As Integer
 
Private Const lpClassName = "Winamp v1.x"
Private Const strTtlEnd = " - Winamp"
 
Private Function GetWinampSong() As String
    Dim hwnd As IntPtr = FindWindow(lpClassName, vbNullString)
 
    Dim lpText As String
 
    If hwnd.Equals(IntPtr.Zero) Then Return "Not running"
 
    lpText = New String(Chr(0), 100)
    Dim intLength As Integer = GetWindowText(hwnd, lpText, _
      lpText.Length)
 
    If (intLength <= 0) OrElse (intLength > lpText.Length) _
             Then Return "Unknown"
 
    Dim strTitle As String = lpText.Substring(0, intLength)
    Dim intName As Integer = strTitle.IndexOf(strTtlEnd)
    Dim intLeft As Integer = strTitle.IndexOf("[")
    Dim intRight As Integer = strTitle.IndexOf("]")
 
    If (intName >= 0) AndAlso (intLeft >= 0) AndAlso _
            (intName < intLeft) AndAlso _
       (intRight >= 0) AndAlso (intLeft + 1 < intRight) Then _
        Return strTitle.Substring(intLeft + 1, intRight - intLeft - 1)
 
    If (strTitle.EndsWith(strTtlEnd)) AndAlso _
        (strTitle.Length > strTtlEnd.Length) Then _
        strTitle = strTitle.Substring(0, _
          strTitle.Length - strTtlEnd.Length)
 
    Dim intDot As Integer = strTitle.IndexOf(".")
    If (intDot > 0) AndAlso (IsNumeric( _
           strTitle.Substring(0, intDot))) Then _
        strTitle = strTitle.Remove(0, intDot + 1)
 
    Return strTitle.Trim
End Function

good luck happy coding ..................
0
 
LVL 11

Accepted Solution

by:
Babycorn-Starfish earned 200 total points
ID: 20305133
Hi,

check this link out also, it has LOTS of pInvoke examples:

http://pinvoke.net/
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
As a trusted technology advisor to your customers you are likely getting the daily question of, ‘should I put this in the cloud?’ As customer demands for cloud services increases, companies will see a shift from traditional buying patterns to new…
CodeTwo Sync for iCloud (http://www.codetwo.com/sync-for-icloud?sts=6554) automatically synchronizes your Outlook 2016, 2013, 2010 or 2007 folders with iCloud folders available via iCloud Control Panel. This lets you automatically sync them with…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now