using System.Runtime.InteropServices;
WinAPI参考手册下载:API32.7Z
1.读写INI文件(参考:C#_读写ini文件)
[DllImport("kernel32")] private static extern long WritePrivateProfileString(string section,string key,string val,string filePath); [DllImport("kernel32")] private static extern long GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath);
2.设置/获取系统时间(参考:C#_获取Internet时间)
[DllImport("Kernel32.dll")] public static extern bool SetLocalTime(ref SystemTime Time); [DllImport("Kernel32.dll")] public static extern void GetLocalTime(ref SystemTime Time);
3.设置系统日期格式
[DllImport("kernel32.dll ")] public static extern int GetSystemDefaultLCID(); [DllImport("kernel32.dll ")] public static extern int SetLocaleInfo(int Locale, int LCType, string lpLCData); public const int LOCALE_SSHORTDATE = 0x1F;//见Win32.txt int x = GetSystemDefaultLCID();
SetLocaleInfo(x, LOCALE_SSHORTDATE, "yyyy-MM-dd");//更改为短日期格式
4. 获取鼠标坐标(参考:C#_动态获取鼠标坐标)
Point p; [DllImport("user32.dll")] public static extern bool GetCursorPos(out Point pt); private void timer1_Tick(object sender, EventArgs e) { GetCursorPos(out p); label1.Text = p.X.ToString();//X坐标 label2.Text = p.Y.ToString();//Y坐标 }
5.获取鼠标坐标点的颜色(参考:C#_动态获取鼠标位置的颜色)
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hwnd); [DllImport("user32.dll")] static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc); [DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos); public Color GetPixelColor(int x, int y) { IntPtr hdc = GetDC(IntPtr.Zero); uint pixel = GetPixel(hdc, x, y); ReleaseDC(IntPtr.Zero, hdc); Color color = Color.FromArgb((int)(pixel & 0x000000FF), (int)(pixel & 0x0000FF00) >> 8, (int)(pixel & 0x00FF0000) >> 16); return color; }
6. 全局快捷键设置(参考:C#_注册系统全局快捷键)
[DllImport("user32.dll")] static extern bool RegisterHotKey(IntPtr hWnd, int id, int modifiers, Keys vk); [DllImport("user32.dll")] static extern bool UnregisterHotKey(IntPtr hWnd, int id);
7.窗体动画效果(参考:C#_让WinForm窗体拥有动画效果(淡入淡出等…))
/// <summary> /// 窗体动画函数 /// </summary> /// <param name="hwnd">指定产生动画的窗口的句柄</param> /// <param name="dwTime">指定动画持续的时间</param> /// <param name="dwFlags">指定动画类型,可以是一个或多个标志的组合。</param> /// <returns></returns> [DllImport("user32")] private static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
8.获取鼠标坐标处的窗口句柄(参考:C#_获取鼠标所在处的窗口句柄 )
/// <summary> /// 返回包含了指定点的窗口的句柄。忽略屏蔽、隐藏以及透明窗口 /// </summary> /// <param name="Point">指定的鼠标坐标</param> /// <returns>鼠标坐标处的窗口句柄,如果没有,返回</returns> [DllImport("user32.dll")] internal static extern IntPtr WindowFromPoint(Point Point);
9.WinForm窗体调用控制台窗口
/// <summary> /// 启动控制台 /// </summary> /// <returns></returns> [DllImport("kernel32.dll")] public static extern bool AllocConsole(); /// <summary> /// 释放控制台 /// </summary> /// <returns></returns> [DllImport("kernel32.dll")] public static extern bool FreeConsole();