You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Windows Mobile应用调用kernel32.dll报错:找不到PInvoke DLL 'kernel32'

问题:调用P/Invoke设置Windows系统时间时提示找不到kernel32.dll

我想要实现的功能是将自定义的时间数据设置为Windows系统时间,以下是我的代码:

[System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]
private static extern bool GetSystemTime(out SYSTEMTIME systemTime);
[System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]
private static extern bool SetSystemTime(ref SYSTEMTIME systemTime);
public struct SYSTEMTIME
{
    public short Year;
    public short Month;
    public short DayOfWeek;
    public short Day;
    public short Hour;
    public short Minute;
    public short Second;
    public short Milliseconds;
}

private void Form1_Load(object sender, EventArgs e)
{
    DateTime serverTime = DateTime.Now;

    SYSTEMTIME zaman = new SYSTEMTIME();
    zaman.Day = 25;
    zaman.Month = 9;
    zaman.Year = 2010;
    zaman.Hour = 14;
    zaman.Minute = 45;
    SetSystemTime(ref zaman);

    label1.Text = zaman.Day.ToString();
    label2.Text = zaman.Month.ToString();
    label3.Text = zaman.Year.ToString();
}

运行时出现错误:Can't find PInvoke DLL 'kernel32',请问该如何解决这个问题?


解决方法
  • 确认运行环境为Windows平台
    kernel32.dll是Windows专属的系统核心库,非Windows系统(如Linux、macOS)不存在这个文件。如果你的项目基于跨平台框架(.NET Core/.NET 5+),需要指定Windows为目标平台:

    • 右键项目→属性→应用程序,将目标框架改为Windows专用版本(如net6.0-windows);
    • 或直接编辑项目文件,添加如下配置:
      <TargetFramework>net6.0-windows</TargetFramework>
      <RuntimeIdentifier>win-x64</RuntimeIdentifier> <!-- 根据系统架构选择win-x86/win-arm64等 -->
      
  • 修正DllImport的库名称
    原代码中DllImport仅写了kernel32,尝试补充完整扩展名kernel32.dll,确保系统能正确识别:

    [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool GetSystemTime(out SYSTEMTIME systemTime);
    [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetSystemTime(ref SYSTEMTIME systemTime);
    
  • 补充:设置系统时间需要管理员权限
    即使解决了DLL问题,调用SetSystemTime仍可能失败,因为修改系统时间需要管理员权限。可以右键程序选择「以管理员身份运行」,或在项目中添加权限清单,让程序默认请求管理员权限。


内容的提问来源于stack exchange,提问作者BurakBK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 16:01:48