Csharp/CSharp Tutorial/Windows/Native Windows Function — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 15:31, 26 мая 2010
Содержание
- 1 Calling a Function with a Structure Parameter
- 2 Calling Native DLL Functions
- 3 Enumerate Display Monitors
- 4 Get Computer name (char * parameter)
- 5 Get computer name (StringBuilder parameter)
- 6 Get current Active Window
- 7 Get free disk space
- 8 Get Monitor Information
- 9 GetVersionEx by using kernel32.dll
- 10 Get Workstation information
- 11 Lock work station
- 12 Reading INI file: Get Private Profile String
- 13 The windows version information
- 14 Use native windows function to read file
- 15 Writing INI file: Write Private Profile String
Calling a Function with a Structure Parameter
// Code from
// A Programmer"s Introduction to C# 2.0, Third Edition
// copyright 2000 Eric Gunnerson
using System;
using System.Runtime.InteropServices;
struct Point
{
public int x;
public int y;
public override string ToString()
{
return(String.Format("({0}, {1})", x, y));
}
}
struct Rect
{
public int left;
public int top;
public int right;
public int bottom;
public override string ToString()
{
return(String.Format("({0}, {1})\n ({2}, {3})", left, top, right, bottom));
}
}
struct WindowPlacement
{
public uint length;
public uint flags;
public uint showCmd;
public Point minPosition;
public Point maxPosition;
public Rect normalPosition;
public override string ToString()
{
return(String.Format("min, max, normal:\n{0}\n{1}\n{2}",
minPosition, maxPosition, normalPosition));
}
}
class MainClass
{
[DllImport("user32")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32")]
static extern bool GetWindowPlacement(IntPtr handle, ref WindowPlacement wp);
public static void Main()
{
IntPtr window = GetForegroundWindow();
WindowPlacement wp = new WindowPlacement();
wp.length = (uint) Marshal.SizeOf(wp);
bool result = GetWindowPlacement(window, ref wp);
if (result)
{
Console.WriteLine(wp);
}
}
}
min, max, normal: (-32000, -32000) (-60, -8) (-1, -1) (1273, 728)
Calling Native DLL Functions
using System;
using System.Runtime.InteropServices;
class Test
{
[DllImport("user32.dll")]
public static extern int MessageBox(IntPtr h, string m, string c, int type);
public static void Main()
{
int retval = MessageBox(IntPtr.Zero, "Hello", "Caption", 0);
}
}
Enumerate Display Monitors
/*
NET Development for Java Programmers
# By Paul Gibbons
# ISBN: 1-59059-038-4
# 432 pp.
# Published: Jul 2002
*/
using System;
using System.Runtime.InteropServices;
[ StructLayout( LayoutKind.Sequential ) ]
struct Rect
{
public int left;
public int top;
public int right;
public int bottom;
}
[ StructLayout( LayoutKind.Sequential ) ]
struct MonitorInfo
{
public uint size;
public Rect monitor;
public Rect work;
public uint flags;
}
class MainClass
{
delegate bool MonitorEnumDelegate( IntPtr hMonitor,IntPtr hdcMonitor,ref Rect lprcMonitor, IntPtr dwData );
[ DllImport( "user32.dll" ) ]
static extern bool EnumDisplayMonitors( IntPtr hdc, IntPtr lprcClip, MonitorEnumDelegate lpfnEnum, IntPtr dwData );
[ DllImport( "user32.dll" ) ]
static extern bool GetMonitorInfo( IntPtr hmon, ref MonitorInfo mi );
static bool MonitorEnum( IntPtr hMonitor, IntPtr hdcMonitor, ref Rect lprcMonitor, IntPtr dwData )
{
MonitorInfo mi = new MonitorInfo();
mi.size = (uint)Marshal.SizeOf( mi );
bool success = GetMonitorInfo( hMonitor, ref mi );
return true;
}
[STAThread]
static void Main(string[] args)
{
MonitorEnumDelegate med = new MonitorEnumDelegate( MonitorEnum );
EnumDisplayMonitors( IntPtr.Zero, IntPtr.Zero, med, IntPtr.Zero );
}
}
Get Computer name (char * parameter)
using System;
using System.Runtime.InteropServices;
class MainClass
{
[ DllImport( "kernel32.dll" ) ]
static extern unsafe bool GetComputerNameW( char* name, ref ulong size );
[STAThread]
static unsafe void Main(string[] args)
{
ulong size = 256;
char* name = stackalloc char[ (int)size ];
bool success = GetComputerNameW( name, ref size );
for ( uint i = 0; i < size; i++, name++ )
{
System.Console.Write( *name );
}
}
}
nfex
Get computer name (StringBuilder parameter)
using System;
using System.Runtime.InteropServices;
using System.Text;
class MainClass{
[ DllImport( "kernel32.dll" ) ]
static extern bool GetComputerName( StringBuilder name, ref ulong size );
[STAThread]
static void Main(string[] args)
{
ulong size = 256;
StringBuilder name = new StringBuilder( (int)size );
bool success = GetComputerName( name, ref size );
Console.WriteLine( name.ToString() );
}
}
nfex
Get current Active Window
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
public class MainClass
// Declare external functions.
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
public static void Main() {
int chars = 256;
StringBuilder buff = new StringBuilder(chars);
// Obtain the handle of the active window.
IntPtr handle = GetForegroundWindow();
// Update the controls.
if (GetWindowText(handle, buff, chars) > 0)
{
Console.WriteLine(buff.ToString());
Console.WriteLine(handle.ToString());
}
}
}
Get free disk space
using System;
using System.IO;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
public class MainClass
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
out ulong lpFreeBytesAvailable,
out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes);
public static void Main()
{
ulong freeBytesAvail;
ulong totalNumOfBytes;
ulong totalNumOfFreeBytes;
if (!GetDiskFreeSpaceEx("C:\\", out freeBytesAvail, out totalNumOfBytes, out totalNumOfFreeBytes))
{
Console.Error.WriteLine("Error occurred: {0}",
Marshal.GetExceptionForHR(Marshal.GetLastWin32Error()).Message);
}
else
{
Console.WriteLine("Free disk space:");
Console.WriteLine(" Available bytes : {0}", freeBytesAvail);
Console.WriteLine(" Total # of bytes: {0}", totalNumOfBytes);
Console.WriteLine(" Total free bytes: {0}", totalNumOfFreeBytes);
}
}
}
Free disk space: Available bytes : 33091416064 Total # of bytes: 60003381248 Total free bytes: 33091416064
Get Monitor Information
/*
Revised from
NET Development for Java Programmers
*/
using System;
using System.Runtime.InteropServices;
[ StructLayout( LayoutKind.Explicit ) ]
struct Point
{
[ FieldOffset( 0 ) ]
public int x;
[ FieldOffset( 4 ) ]
public int y;
}
[ StructLayout( LayoutKind.Sequential ) ]
struct Rect
{
public int left;
public int top;
public int right;
public int bottom;
}
[ StructLayout( LayoutKind.Sequential ) ]
struct MonitorInfo
{
public uint size;
public Rect monitor;
public Rect work;
public uint flags;
}
class MainClass
{
[ DllImport( "user32.dll" ) ]
static extern IntPtr MonitorFromPoint( Point p, uint flags );
[ DllImport( "user32.dll" ) ]
static extern bool GetMonitorInfo( IntPtr hmon, ref MonitorInfo mi );
[STAThread]
static void Main(string[] args)
{
Point p = new Point();
p.x = 1;
p.y = 1;
IntPtr hmon = MonitorFromPoint( p, 1 );
MonitorInfo mi = new MonitorInfo();
mi.size = (uint)Marshal.SizeOf( mi );
bool success = GetMonitorInfo( hmon, ref mi );
Console.WriteLine(mi.size);
Console.WriteLine(mi.monitor);
}
}
40 Rect
GetVersionEx by using kernel32.dll
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public class OSVersionInfo
{
public int dwOSVersionInfoSize;
public int dwMajorVersion;
public int dwMinorVersion;
public int dwBuildNumber;
public int dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public String szCSDVersion;
}
class MainClass
{
[DllImport("kernel32.dll")]
public static extern bool GetVersionEx([In, Out] OSVersionInfo osvi);
static void Main(string[] args)
{
OSVersionInfo osvi = new OSVersionInfo();
osvi.dwOSVersionInfoSize = Marshal.SizeOf(osvi);
GetVersionEx(osvi);
Console.WriteLine("Class size: " + osvi.dwOSVersionInfoSize);
Console.WriteLine("Major Version: " + osvi.dwMajorVersion);
Console.WriteLine("Minor Version: " + osvi.dwMinorVersion);
Console.WriteLine("Build Number: " + osvi.dwBuildNumber);
Console.WriteLine("Platform Id: " + osvi.dwPlatformId);
Console.WriteLine("CSD Version: " + osvi.szCSDVersion);
Console.WriteLine("Platform: " + Environment.OSVersion.Platform);
Console.WriteLine("Version: " + Environment.OSVersion.Version);
}
}
Class size: 148 Major Version: 5 Minor Version: 1 Build Number: 2600 Platform Id: 2 CSD Version: Service Pack 2 Platform: Win32NT Version: 5.1.2600.131072
Get Workstation information
/*
NET Development for Java Programmers
# By Paul Gibbons
# ISBN: 1-59059-038-4
# 432 pp.
# Published: Jul 2002
*/
using System;
using System.Runtime.InteropServices;
using System.Text;
class NWGetInfo
{
[ StructLayout( LayoutKind.Sequential ) ]
struct WkstaInfo102
{
public uint platform_id;
public IntPtr computername;
public IntPtr langroup;
public uint ver_major;
public uint ver_minor;
public IntPtr lanroot;
public uint logged_on_users;
}
[ DllImport( "Netapi32.dll" ) ]
static extern unsafe int NetWkstaGetInfo( IntPtr servername, int level, byte** bufptr );
[ DllImport( "Netapi32.dll" ) ]
static extern unsafe int NetApiBufferFree( byte* bufptr );
[STAThread]
static unsafe void Main(string[] args)
{
byte* bp = null;
int rc = NetWkstaGetInfo( IntPtr.Zero, 102, &bp );
WkstaInfo102* wip = (WkstaInfo102*)bp;
Console.WriteLine( "System {0} has {1} users logged on", Marshal.PtrToStringAuto( wip->computername ), wip->logged_on_users );
rc = NetApiBufferFree( bp );
}
}
System nfex has 3 users logged on
Lock work station
using System;
using System.Collections;
using System.Data;
using System.Runtime.InteropServices;
public class MainClass {
[ DllImport( "user32.dll" ) ]
private static extern bool LockWorkStation();
[STAThread]
static void Main()
{
LockWorkStation();
}
}
Reading INI file: Get Private Profile String
using System;
using System.Runtime.InteropServices;
using System.Text;
class MainClass
{
// Declare the unmanaged functions.
[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString")]
private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
static void Main(string[] args)
{
string section = "SampleSection"
string key = "Key1";
string filename = "\\initest.ini";
int chars = 256;
StringBuilder buffer = new StringBuilder(chars);
string sDefault = "";
if (GetPrivateProfileString(section, key, sDefault, buffer, chars, filename) != 0)
{
Console.WriteLine("Value of Key1 in [SampleSection] is: " + buffer.ToString());
}
else
{
Console.WriteLine("Value of Key1 in [SampleSection] is: " + null);
}
}
}
The windows version information
// Code from
// A Programmer"s Introduction to C# 2.0, Third Edition
// copyright 2000 Eric Gunnerson
using System;
using System.Runtime.InteropServices;
unsafe struct OSVERSIONINFO
{
public uint dwOSVersionInfoSize;
public uint dwMajorVersion;
public uint dwMinorVersion;
public uint dwBuildNumber;
public uint dwPlatformId;
public fixed char szCSDVersion[128];
}
class Program{
[DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
static extern bool GetVersionEx(ref OSVERSIONINFO lpVersionInfo);
unsafe static void Main(string[] args)
{
OSVERSIONINFO versionInfo = new OSVERSIONINFO();
versionInfo.dwOSVersionInfoSize = (uint)sizeof(OSVERSIONINFO);
bool res = GetVersionEx(ref versionInfo);
Console.WriteLine(Marshal.PtrToStringUni(new IntPtr(versionInfo.szCSDVersion)));
}
}
S
Use native windows function to read file
// Code from
// A Programmer"s Introduction to C# 2.0, Third Edition
// copyright 2000 Eric Gunnerson
using System;
using System.Runtime.InteropServices;
using System.Text;
class FileRead
{
const uint GENERIC_READ = 0x80000000;
const uint OPEN_EXISTING = 3;
IntPtr handle;
public FileRead(string filename)
{
// opens the existing file
handle = CreateFile( filename,
GENERIC_READ,
0,
0,
OPEN_EXISTING,
0,
0);
}
[DllImport("kernel32", SetLastError=true)]
static extern IntPtr CreateFile(
string filename,
uint desiredAccess,
uint shareMode,
uint attributes, // really SecurityAttributes pointer
uint creationDisposition,
uint flagsAndAttributes,
uint templateFile);
[DllImport("kernel32", SetLastError=true)]
static extern unsafe bool ReadFile(
IntPtr hFile,
void* lpBuffer,
int nBytesToRead,
int* nBytesRead,
int overlapped);
public unsafe int Read(byte[] buffer, int count)
{
int n = 0;
fixed (byte* p = buffer)
{
ReadFile(handle, p, count, &n, 0);
}
return n;
}
}
class Test
{
public static void Main(string[] args)
{
FileRead fr = new FileRead("test.cs");
byte[] buffer = new byte[128];
ASCIIEncoding e = new ASCIIEncoding();
// loop through, read until done
Console.WriteLine("Contents");
while (fr.Read(buffer, 128) != 0)
{
Console.Write("{0}", e.GetString(buffer));
}
}
}
Contents
Writing INI file: Write Private Profile String
using System;
using System.Runtime.InteropServices;
using System.Text;
class MainClass
{
[DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString")]
private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);
static void Main(string[] args)
{
// Write a new value.
WritePrivateProfileString("MySection", "MyKey", "New Value", "\\initest.ini");
}
}