前几日安装了VS2008,在C#中直接用Win32的API会提示未定义。后来查了资料知道在C#中要用WIN32 API要用DllImportAttribute引用。我想使用WIN32 API:GetLocalTime()来获取系统时间。但是出错。
源码如下:
using System;
using System.Runtime.InteropServices;
using System.Timers;namespace ApiTest
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
///
[DllImportAttribute("Kernel32.dll")]
public static extern void GetLocalTime(SystemTime st);
[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);
[STAThread]
static void Main()
{
string myString;
myString=System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
MessageBox(0,myString,"title",0);
Console.Write("Enter your message: ");
myString = Console.ReadLine();
}
}
}
出现了如下错误:
错误 1 找不到类型或命名空间名称“SystemTime”(是否缺少 using 指令或程序集引用?)
把public static extern void GetLocalTime(SystemTime st);中的SystemTime改为SYSTEMTIME也说找不到类型或命名空间名称。
本人是一个地地道道的菜鸟。谁指教一下是什么地方出错了。
源码如下:
using System;
using System.Runtime.InteropServices;
using System.Timers;namespace ApiTest
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
///
[DllImportAttribute("Kernel32.dll")]
public static extern void GetLocalTime(SystemTime st);
[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);
[STAThread]
static void Main()
{
string myString;
myString=System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
MessageBox(0,myString,"title",0);
Console.Write("Enter your message: ");
myString = Console.ReadLine();
}
}
}
出现了如下错误:
错误 1 找不到类型或命名空间名称“SystemTime”(是否缺少 using 指令或程序集引用?)
把public static extern void GetLocalTime(SystemTime st);中的SystemTime改为SYSTEMTIME也说找不到类型或命名空间名称。
本人是一个地地道道的菜鸟。谁指教一下是什么地方出错了。
public struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}
然后,增加外部函数的说明
public class PublicFunction
{
[DllImport("Kernel32.dll")]
public static extern void GetLocalTime(ref SYSTEMTIME st);
}
由于,这个函数会把取出来的时间放到SYSTEMTIME结构体中,所以需要加入ref表示引用传递
然后你就可以调用了
SYSTEMTIME st = new SYSTEMTIME();
PublicFunction.GetLocalTime(ref st);