日期:2014-05-17  浏览次数:20841 次

C# 调用C++ builder写的DLL文件
我的DLL代码如下(用的是C++ builder 2010):
 extern  "C"  __declspec(dllexport) void __stdcall  Suspend(bool Flas3,AnsiString time) ;
void __stdcall  Suspend(bool Flas3,AnsiString time)    // LPCTSTR
{
  TOKEN_PRIVILEGES tp;
HANDLE hToken;
LUID luid;
LPTSTR MachineName=NULL;
HANDLE hTimer = NULL;
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES,&hToken )) ////////从这里////////////////////////////
{
 //Application->MessageBox("ERROR type 1", NULL, MB_OKCANCEL);
 ShowMessage("ERROR type 1");
         //PERR("OpenProcessToken", GetLastError());
//return RTN_ERROR;
}
if(!LookupPrivilegeValue(MachineName, SE_SHUTDOWN_NAME, &luid))
{
        //PERR("LookupPrivilegeValue", GetLastError() );
//Application->MessageBox("ERROR type 2", NULL, MB_OKCANCEL);
ShowMessage("ERROR type 2");
//return RTN_ERROR;
}

        tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
        AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),
        NULL, NULL ); ////////////////到这里,是取得权限/////////////////////
// ExitWindowsEx(EWX_POWEROFF | EWX_FORCE, 0);
//Hans,

time = "-"+time + "0000000"  ;
ShowMessage(time);

LARGE_INTEGER liDueTime;
liDueTime.QuadPart=StrToInt64(time);
// Create a waitable timer.
hTimer = CreateWaitableTimer(NULL, TRUE, "WaitableTimer");
if (!hTimer)
{
//printf("CreateWaitableTimer failed (%d)\n", GetLastError());
//Application->MessageBoxA("CreateWaitableTimer failed!",NULL,MB_OKCANCEL);
ShowMessage("CreateWaitableTimer failed!");
//return 1;
}
//printf("Waiting for 10 seconds...\n");
// Set a timer to wait for 10 seconds.
if (!SetWaitableTimer(
hTimer, &liDueTime, 0, NULL, NULL, 1))
{
//Application->MessageBoxA("SetWaitableTimer failed!",NULL,MB_OKCANCEL);
ShowMessage("SetWaitableTimer failed!");
//printf("SetWaitableTimer failed (%d)\n", GetLastError());
//return 2;
}
//Hans.
if(Flas3) SetSystemPowerState(TRUE,TRUE);
else SetSystemPowerState(FALSE,TRUE);

}

我在我的C#程序是这样调用的
[DllImport("WakeUpDll.dll",CharSet = CharSet.Auto)]
        public static extern void Suspend(bool Flag3, string time);

        private void button1_Click(object sender, EventArgs e)
        {
            string ad;
        &nb