I suppose you know how to import Win32 API functions into C#.
Like this :

BOOL ExitWindowsEx(UINT uFlags, DWORD dwReason);  // Original Win32 function
[DllImport("User32.dll")] public static extern bool ExitWindowsEx(uint uFlags, uint dwReason);  // How to import into C#

I want to import SetSuspendState() function, but don't know what DLL file it requires.
Here the explanation of SetSuspendState() in MSDN :

[IMG][/IMG] [IMG][/IMG] Platform SDK: Power Management SetSuspendState


The SetSuspendState function suspends the system by shutting power down. Depending on the Hibernate parameter, the system either enters a suspend (sleep) state or hibernation (S4).
BOOLEAN SetSuspendState(
BOOL Hibernate ,
BOOL ForceCritical ,
BOOL DisableWakeEvent ); Parameters

Hibernate [in] If this parameter is TRUE, the system hibernates. If the parameter is FALSE, the system is suspended. ForceCritical [in] If this parameter is TRUE, the system suspends operation immediately; if it is FALSE, the system broadcasts a event to each application to request permission to suspend operation. DisableWakeEvent [in] If this parameter is TRUE, the system disables all wake events. If the parameter is FALSE, any system wake events remain enabled. Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks

An application may use SetSuspendState to transition the system from the working state to the standby (sleep), or optionally, hibernate (S4) state. This function is similar to the SetSystemPowerState function.
Requirements

Client: Included in Windows XP, Windows 2000 Professional, Windows Me, and Windows 98.
Server: Included in Windows Server 2003 and Windows 2000 Server.
Header: Declared in Powrprof.h.
Library: Use Powrprof.lib.

See Also

, , ,
[IMG][/IMG]
Platform SDK Release: February 2003 [EMAIL="sdkfdbk@microsoft.com?subject=TITLE:%20SetSuspendState;%20RELEASE:%20February%202003;%20URL:%20base/setsuspendstate.xml"][IMG][/IMG][/EMAIL] [EMAIL="sdkfdbk@microsoft.com?subject=TITLE:%20SetSuspendState;%20RELEASE:%20February%202003;%20URL:%20base/setsuspendstate.xml"]What did you think of this topic?[/EMAIL]
[IMG][/IMG]

Requirements

Client: Included in Windows XP, Windows 2000 Professional, Windows Me, and Windows 98.
Server: Included in Windows Server 2003 and Windows 2000 Server.
Header: Declared in Powrprof.h.
Library: Use Powrprof.lib.


See Also

, , ,

It instructs to import Powrprof.h, but doesn't give a DLL name.
So, is there any suggestions?

Dani AI

Generated

A short, practical summary and a few things to check beyond the replies from and .

The Windows API reference is authoritative: it shows the header, import library and the runtime DLL that actually exports each function, and a P/Invoke call must use the runtime DLL listed in the docs. When a DllImport points at the wrong binary you typically get a runtime error (EntryPointNotFoundException / DllNotFoundException) — that is what the thread diagnosis corrected. See the official SetSuspendState reference and the Platform Invoke guidance for how to match managed signatures to native exports. (learn.microsoft.com)

Common P/Invoke pitfalls to avoid

  • Boolean sizes: the native SetSuspendState signature uses Windows BOOLEAN (1 byte). The CLR default marshals C# bool as a Win32 BOOL-sized value, so be explicit when you need 1-byte C booleans (use UnmanagedType.U1) or explicitly marshal the return value. That prevents return-value/stack-mismatch surprises.
  • Error reporting: include SetLastError in your DllImport/LibraryImport and read the error with Marshal.GetLastWin32Error() / Marshal.GetLastPInvokeError() to get actionable diagnostics. See the type-marshalling and P/Invoke docs for details. (learn.microsoft.com)

Runtime requirements and quick checks

  • Privilege: SetSuspendState can require the SE_SHUTDOWN_NAME privilege. If the call silently fails, enable the privilege (AdjustTokenPrivileges) or check GetLastError for ERROR_PRIVILEGE_NOT_HELD. (learn.microsoft.com)
  • Hardware/OS support: hibernation/sleep must be supported and enabled on the machine. Run powercfg /a to list available states and powercfg /hibernate on to enable hibernation where supported. (learn.microsoft.com)

About math.h / cos(): headers are compile-time declarations; the runtime implementations live in the C runtime (MSVCRT/UCRT) which differs by compiler/OS. In managed code prefer the .NET equivalent (System.Math.Cos) instead of P/Invoking CRT functions. The CRT route is fragile and unnecessary for typical .NET apps. (learn.microsoft.com)

If a call still fails, check (1) the exact exception text, (2) the DLL name you passed to DllImport, (3) the parameter/return marshaling, and (4) GetLastWin32Error/GetLastPInvokeError output — those four items will almost always point to the root cause.

Recommended Answers

All 4 Replies

This is the relevant code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Shutdown
{
    public partial class frmMain : Form
    {
        //BOOL ExitWindowsEx(UINT uFlags, DWORD dwReason);
        [DllImport("User32.dll")] public static extern bool ExitWindowsEx(uint uFlags, uint dwReason);
        //BOOLEAN SetSuspendState(BOOL Hibernate, BOOL ForceCritical, BOOL DisableWakeEvent);
        [DllImport("User32.dll")] public static extern bool SetSuspendState(bool Hibernate, bool ForceCritical, bool DisableWakeEvent);

        public void TimeOut(object sender, EventArgs e)
        {
            tmrTimer.Enabled = false;
            btStart.Enabled = true;
            btStop.Enabled = false;
            uint EWX_LOGOFF                 = 0;
            uint EWX_SHUTDOWN               = 1;
            uint EWX_REBOOT                 = 2;
            uint EWX_FORCE                  = 4;
            uint EWX_POWEROFF               = 8;
            uint EWX_FORCEIFHUNG            = 16;
            uint SHTDN_REASON_FLAG_PLANNED  = 0x80000000;
            if      (rbShutdown.Checked == true)
            {
                if (cbForce.Checked == true)
                    ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, SHTDN_REASON_FLAG_PLANNED);
                else
                    ExitWindowsEx(EWX_SHUTDOWN, SHTDN_REASON_FLAG_PLANNED);
            }
            else if (rbRestart.Checked == true)
            {
                if (cbForce.Checked == true)
                    ExitWindowsEx(EWX_REBOOT | EWX_FORCE, SHTDN_REASON_FLAG_PLANNED);
                else
                    ExitWindowsEx(EWX_REBOOT, SHTDN_REASON_FLAG_PLANNED);
            }
            else if (rbLogOff.Checked == true)
            {
                if (cbForce.Checked == true)
                    ExitWindowsEx(EWX_LOGOFF | EWX_FORCE, SHTDN_REASON_FLAG_PLANNED);
                else
                    ExitWindowsEx(EWX_LOGOFF, SHTDN_REASON_FLAG_PLANNED);
            }
            else if (rbStandBy.Checked == true)
            {
                if (cbForce.Checked == true)
                    SetSuspendState(false, true, false);
                else
                    SetSuspendState(false, false, false);
            }
            else if (rbHibernate.Checked == true)
            {
                if (cbForce.Checked == true)
                    SetSuspendState(true, true, false);
                else
                    SetSuspendState(true, false, false);
            }
        }

        public frmMain()
        {
            InitializeComponent();
        }

        private void btStart_Click(object sender, EventArgs e)
        {
            btStart.Enabled = false;
            btStop.Enabled = true;
            tmrTimer.Enabled = true;
        }

        private void btStop_Click(object sender, EventArgs e)
        {
            btStart.Enabled = true;
            btStop.Enabled = false;
            tmrTimer.Enabled = false;
        }

        private void btAbout_Click(object sender, EventArgs e)
        {
            frmAbout winAbout = new frmAbout();
            winAbout.Show();
        }

        private void tmrTimer_Tick(object sender, EventArgs e)
        {
            int nDay = int.Parse(tbDay.Text);
            int nHour = int.Parse(tbHour.Text);
            int nMinute = int.Parse(tbMinute.Text);
            int nSecond = int.Parse(tbSecond.Text);
            if ((nDay == 0) && (nHour == 0) && (nMinute == 0) && (nSecond == 0))
                TimeOut(sender, e);
            else
            {
                if (--nSecond < 0) { nSecond = 59; nMinute--; }
                if (nMinute < 0) { nMinute = 59; nHour--; }
                if (nHour < 0) { nHour = 23; nDay--; }
                tbDay.Text = nDay.ToString(); if (tbDay.Text.Length == 1) tbDay.Text = "0" + tbDay.Text;
                tbHour.Text = nHour.ToString(); if (tbHour.Text.Length == 1) tbHour.Text = "0" + tbHour.Text;
                tbMinute.Text = nMinute.ToString(); if (tbMinute.Text.Length == 1) tbMinute.Text = "0" + tbMinute.Text;
                tbSecond.Text = nSecond.ToString(); if (tbSecond.Text.Length == 1) tbSecond.Text = "0" + tbSecond.Text;
            }
        }
    }
}

And the given runtime error is :
[IMG][/IMG]

SetSuspendState() should be in PowrProf.dll, not User32.dll.

[DllImport("PowrProf.dll")]
public static extern bool SetSuspendState(bool Hibernate, bool ForceCritical, bool DisableWakeEvent);
commented: Thank you +1

SetSuspendState() should be in PowrProf.dll, not User32.dll.

[DllImport("PowrProf.dll")]
public static extern bool SetSuspendState(bool Hibernate, bool ForceCritical, bool DisableWakeEvent);

Thank you Ravalon, it works now.

But it made me curious. Was that a coincidence that we used powerprof.dll instead of powerprof.h? I mean, if an API function requires xyzw.h should I always add xyzw.dll?
For example, say, I want to import cos() function in C# which is declared in math.h in C++. Should I import math.dll?

Was that a coincidence that we used powerprof.dll instead of powerprof.h? I mean, if an API function requires xyzw.h should I always add xyzw.dll?

Not always. The documentation should tell you what dll to load for dynamic linking and what *.lib file to use for static linking. The header file is for C and C++ only so that you can use libraries without having to type all of the declarations manually. That's not fun, take my word for it. :)

For example, say, I want to import cos() function in C# which is declared in math.h in C++. Should I import math.dll?

For most of the standard C++ functions you should import msvcrt.dll. But I don't think you need to do that when the .NET base class library has most of that stuff and more. :)

Linking can be confusing, I know. :sad:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.