Csharp/C Sharp/Windows/Windows API
Содержание
- 1 BitBlt
- 2 DLL: GetVersionEx
- 3 Get OS Version from kernel32.dll
- 4 Get the Total Free Space on a Drive by using kernel32.dll
- 5 import CreateDirectory and FormatMessage
- 6 imports the GetModuleHandleW function specifically
- 7 imports the printf function
- 8 imports three functions to display the vertical and horizontal size of the screen.
- 9 Keyboard timer: GetTickCount
- 10 marshals string for unmanaged memory as ANSI.
- 11 MessageBox from user32.dll
BitBlt
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
public class Form1 : Form {
const int SRCCOPY = 0xcc0020;
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern int BitBlt(
IntPtr hdcDest, // handle to destination DC (device context)
int nXDest, // x-coord of destination upper-left corner
int nYDest, // y-coord of destination upper-left corner
int nWidth, // width of destination rectangle
int nHeight, // height of destination rectangle
IntPtr hdcSrc, // handle to source DC
int nXSrc, // x-coordinate of source upper-left corner
int nYSrc, // y-coordinate of source upper-left corner
System.Int32 dwRop // raster operation code
);
public Form1() {
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e) {
Graphics g = e.Graphics;
g.FillRectangle(Brushes.White, ClientRectangle);
g.DrawRectangle(Pens.Black, 10, 10, 40, 40);
IntPtr dc = g.GetHdc();
BitBlt(dc, 70, 0, 60, 60, dc, 0, 0, SRCCOPY);
g.ReleaseHdc(dc);
}
private void InitializeComponent() {
this.SuspendLayout();
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 268);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
this.ResumeLayout(false);
}
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
DLL: GetVersionEx
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
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);
}
}
Get OS Version from kernel32.dll
using System;
using System.Runtime.InteropServices;
public class Starter {
public static void Main() {
API.OSVERSIONINFO info = new API.OSVERSIONINFO();
info.dwOSVersionInfoSize = Marshal.SizeOf(info);
bool resp = API.GetVersionEx(ref info);
if (resp == false) {
Console.WriteLine("GetVersion failed");
}
Console.WriteLine("{0}.{1}.{2}",
info.dwMajorVersion,
info.dwMinorVersion,
info.dwBuildNumber);
}
}
public class API {
[DllImport("kernel32.dll")]
public static extern
bool GetVersionEx(ref OSVERSIONINFO lpVersionInfo);
[StructLayout(LayoutKind.Sequential)]
public struct OSVERSIONINFO {
public System.Int32 dwOSVersionInfoSize;
public System.Int32 dwMajorVersion;
public System.Int32 dwMinorVersion;
public System.Int32 dwBuildNumber;
public System.Int32 dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public String szCSDVersion;
}
}
Get the Total Free Space on a Drive by using kernel32.dll
using System;
using System.Runtime.InteropServices;
public class GetFreeSpace {
[DllImport("kernel32.dll", EntryPoint="GetDiskFreeSpaceExA" )]
private static extern long GetDiskFreeSpaceEx(string lpDirectoryName, out long lpFreeBytesAvailableToCaller, out long lpTotalNumberOfBytes, out long lpTotalNumberOfFreeBytes);
private static void Main() {
long result, total, free, available;
result = GetDiskFreeSpaceEx("c:", out available, out total, out free);
if (result != 0) {
Console.WriteLine("Total Bytes: {0:N}", total);
Console.WriteLine("Free Bytes: {0:N}", free);
Console.WriteLine("Available Bytes: {0:N}", available);
}
}
}
import CreateDirectory and FormatMessage
using System;
using System.Text;
using System.Runtime.InteropServices;
public class Starter {
public static void Main() {
bool resp = API.CreateDirectory(@"c*:\file.txt", IntPtr.Zero);
if (resp == false) {
StringBuilder message;
int errorcode = Marshal.GetLastWin32Error();
API.FormatMessage(API.FORMAT_MESSAGE_ALLOCATE_BUFFER | API.FORMAT_MESSAGE_FROM_SYSTEM | API.FORMAT_MESSAGE_IGNORE_INSERTS,IntPtr.Zero, errorcode,0, out message, 0, IntPtr.Zero);
Console.WriteLine(message);
}
}
}
public class API {
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CreateDirectory(string lpPathName, IntPtr lpSecurityAttributes);
[DllImport("kernel32.dll", SetLastError = false)]
public static extern System.Int32 FormatMessage(
System.Int32 dwFlags,
IntPtr lpSource,
System.Int32 dwMessageId,
System.Int32 dwLanguageId,
out StringBuilder lpBuffer,
System.Int32 nSize,
IntPtr va_list);
public const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 256;
public const int FORMAT_MESSAGE_IGNORE_INSERTS = 512;
public const int FORMAT_MESSAGE_FROM_STRING = 1024;
public const int FORMAT_MESSAGE_FROM_HMODULE = 2048;
public const int FORMAT_MESSAGE_FROM_SYSTEM = 4096;
public const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192;
public const int FORMAT_MESSAGE_MAX_WIDTH_MASK = 255;
}
imports the GetModuleHandleW function specifically
using System;
using System.Runtime.InteropServices;
public class Starter {
public static void Main() {
int hProcess = API.GetModuleHandleW(null);
}
}
public class API {
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern int GetModuleHandleW(string filename);
}
imports the printf function
using System;
using System.Runtime.InteropServices;
public class Starter {
public static void Main() {
int val1 = 5, val2 = 10;
API.printf("%d+%d=%d", val1, val2, val1 + val2);
}
}
public class API {
[DllImport("msvcrt.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern int printf(string formatspecifier, int lhs, int rhs, int total);
}
imports three functions to display the vertical and horizontal size of the screen.
using System;
using System.Runtime.InteropServices;
public class Starter {
public static void Main() {
IntPtr hDC = API.GetDC(IntPtr.Zero);
int v = API.GetDeviceCaps(hDC, API.HORZRES);
Console.WriteLine("Vertical size of window {0}mm.", v);
int h = API.GetDeviceCaps(hDC, API.HORZRES);
Console.WriteLine("Horizontal size of window {0}mm.", h);
int resp = API.ReleaseDC(IntPtr.Zero, hDC);
if (resp != 1) {
Console.WriteLine("Error releasing hdc");
}
}
}
public static class API {
[DllImport("user32.dll")]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern int GetDeviceCaps(IntPtr hDC, int nIndex);
public const int HORZSIZE = 4; // horizontal size in pixels
public const int VERTSIZE = 6; // vertical size in pixels
public const int HORZRES = 8; // horizontal size in millimeters
public const int VERTRES = 10; // vertical size in millimeters
}
Keyboard timer: GetTickCount
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
public class KeyTimer : System.Windows.Forms.Form {
private System.ruponentModel.Container components = null;
private uint start = 0;
private uint stop = 0;
[DllImport("kernel32.dll")]
public static extern uint GetTickCount();
public KeyTimer() {
}
[STAThread]
static void Main() {
Application.Run(new KeyTimer());
}
protected override void OnKeyDown(KeyEventArgs args) {
start = GetTickCount();
}
protected override void OnKeyUp(KeyEventArgs args) {
stop = GetTickCount();
uint elapsed = (stop - start);
MessageBox.Show(Convert.ToString(args.KeyData) + ", time elapsed: " + Convert.ToString(elapsed) + " msecs");
}
}
marshals string for unmanaged memory as ANSI.
using System;
using System.Runtime.InteropServices;
public class Starter {
public static void Main() {
int hProcess = API.GetModuleHandle(null);
}
}
public class API {
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
public static extern int GetModuleHandle(string filename);
}
MessageBox from user32.dll
using System;
using System.Runtime.InteropServices;
public class Starter {
public static void Main() {
string caption = "Visual C# 2005";
string text = "Hello, world!";
API.ShowMessage(0, text, caption, 0);
}
}
public class API {
[DllImport("user32.dll", EntryPoint = "MessageBox")]
public static extern int ShowMessage(int hWnd,
string text, string caption, uint type);
}