www.pudn.com > crestroncontrol.rar > Main.cpp, change:2006-10-10,size:11875b


//--------------------------------------------------------------------------- 
 
#include <vcl.h> 
#pragma hdrstop 
 
#include "Main.h" 
//--------------------------------------------------------------------------- 
#pragma package(smart_init) 
#pragma link "trayicon" 
#pragma resource "*.dfm" 
TFormMain *FormMain; 
//--------------------------------------------------------------------------- 
__fastcall TFormMain::TFormMain(TComponent* Owner): TForm(Owner) 
{ 
/*    ProcessMessage = new TProcessMessage(); 
    ProcessMessage->proccessCCBaseMessage = &execProcessMessage; 
    ClientSocket->OnRead = ProcessMessage->ServerSocketMsgClientRead;*/ 
} 
//--------------------------------------------------------------------------- 
void __fastcall TFormMain::ClientSocketConnect(TObject *Sender, 
      TCustomWinSocket *Socket) 
{ 
    lblState->Caption = "already connect!"; 
} 
//--------------------------------------------------------------------------- 
void __fastcall TFormMain::FormCreate(TObject *Sender) 
{ 
    try 
    { 
        TIniFile *iniFile = new TIniFile(ExtractFileDir(Application->ExeName) + "\\config.ini"); 
        ClientSocket->Host = iniFile->ReadString("Server", "IP", "172.19.5.35"); 
        ClientSocket->Port = iniFile->ReadInteger("Server", "Port", 10200); 
        ClientSocket->Open(); 
 
        TimerConn->Interval = iniFile->ReadInteger("TimerInterval", "interval", 60); 
        delete iniFile; 
    } 
    catch(...) 
    { 
        Application->MessageBox("创建配置文件出错,系统即将退出!", "错误", MB_OK); 
        Application->Terminate(); 
    } 
    Application->ShowMainForm = false; 
} 
//--------------------------------------------------------------------------- 
int execProcessMessage(TCCBaseMessage *ccBaseMessage) 
{ 
    TCCBaseMessage_512 *Msg; 
    Msg = (TCCBaseMessage_512 *)ccBaseMessage; 
 
    AnsiString LocalIP = IntToStr(Msg->Data[0]) + "." + IntToStr(Msg->Data[1]) 
        + "." + IntToStr(Msg->Data[2]) +"." + IntToStr(Msg->Data[3]); 
    if(LocalIP == FormMain->ReadIP()) 
    { 
        //处理socket收到的消息,进行分解并和界面打交道 
        switch(Msg->Class) 
        { 
            case COMPUTER_CLOSE: 
                FormMain->CloseComputer(StrToInt(FormMain->MessageBuffer(Msg)), false); 
                break; 
            case COMPUTER_RESTART: 
                FormMain->CloseComputer(StrToInt(FormMain->MessageBuffer(Msg)), true); 
                break; 
            case PROGRAM_RUN: 
                WinExec(FormMain->MessageBuffer(Msg).c_str(), SW_SHOW); 
                break; 
            case COMPUTER_MAC: 
                FormMain->SendCommand(FormMain->GetLocalMac(), COMPUTER_MAC); 
                break; 
            default: 
                return 0; 
        } 
    } 
    return 0; 
} 
//------------------------------------------------------------------------------ 
AnsiString __fastcall TFormMain::MessageBuffer(TCCBaseMessage_512 *Msg) 
{ 
    AnsiString exeName(Msg->Buffer); 
    //exeName.sprintf(Msg->Buffer, sizeof(Msg->Buffer)); 
    //exeName = exeName.SubString(1, exeName.AnsiPos(" ") - 1); 
    return exeName; 
} 
//------------------------------------------------------------------------------------ 
AnsiString __fastcall TFormMain::ReadIP() 
{ 
    WORD wVersionRequested; 
    WSADATA wsaData; 
    char name[255]; //本机名 
    AnsiString ip;//本机IP 
    PHOSTENT hostinfo; 
    wVersionRequested = MAKEWORD(2, 0); 
 
    if(WSAStartup(wVersionRequested, &wsaData) == 0) 
    { 
        if(gethostname(name, sizeof(name)) == 0) 
        { 
            if((hostinfo = gethostbyname(name)) != NULL) 
            { 
                ip = inet_ntoa(*(struct in_addr *)*hostinfo->h_addr_list); 
            } 
        } 
        WSACleanup(); 
    } 
    return ip; 
} 
//--------------------------------------------------------------------------------------- 
int __fastcall TFormMain::ReadTime() 
{ 
//    int iTime = 0;//关机时间 
//    AnsiString ip = ReadIP(); 
//    TIniFile *iniFile = new TIniFile(ExtractFileDir(Application->ExeName) + "\\config.ini"); 
//    iTime = iniFile->ReadInteger("CloseTime", ip, 0); 
//    delete iniFile; 
 
    return 0; 
} 
//------------------------------------------------------------------------------------- 
void __fastcall TFormMain::CloseComputer(int closetime, bool Flag) 
{ 
    TOKEN_PRIVILEGES tkp; 
	HANDLE hToken; 
 
    FormMain->SendCommand("disconnect", CLIENT_DISCONNECT); 
    Application->ProcessMessages(); 
    ClientSocket->Close(); 
    TimerConn->Enabled = false; 
 
    if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) 
	{ 
  //	    MessageBox("OpenProcessToken failed!"); 
	} 
 
    LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid); //获得本地机唯一的标识 
	tkp.PrivilegeCount = 1;   
	tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;  
    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0); //调整获得的权限 
 
	if (GetLastError() != ERROR_SUCCESS)  
	{ 
      //      MessageBox("AdjustTokenPrivileges enable failed!"); 
	} 
    //AnsiString strName = "centercontrol";//\\192.168.10.21"; 
    //int iTime = ReadTime(); 
    BOOL fResult =InitiateSystemShutdown( 
             NULL,                 // 要关的计算机用户名,可在局域网网中关掉对方的机器,NULL表示关本机 
             "关机倒计时中...",                   // 显示的消息 
             closetime,                                // 关机所需的时间 
             TRUE,                                 //true :强制关,不保存,false:出题是框让保存 
             Flag);                             //设为TRUE为重起,设为FALSE为关机 
    //int i = GetLastError(); 
    if(!fResult) 
    { 
        TimerConn->Enabled = true; 
    //   MessageBox("InitiateSystemShutdown failed."); 
	}  
 
    //FormMain->SendCommand("disconnect", CLIENT_DISCONNECT); 
 
    tkp.Privileges[0].Attributes = 0; 
    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0); 
 
    if (GetLastError() != ERROR_SUCCESS) 
	{ 
     //   MessageBox("AdjustTokenPrivileges disable failed."); 
	} 
 
   	ExitWindowsEx(EWX_POWEROFF|EWX_FORCE, 0);     //开始关机 
    //int i = GetLastError(); 
} 
//----------------------------------------------------------------------------------- 
void __fastcall TFormMain::Button1Click(TObject *Sender) 
{ 
    //CloseComputer(true); 
} 
//--------------------------------------------------------------------------- 
void __fastcall TFormMain::ClientSocketError(TObject *Sender, 
      TCustomWinSocket *Socket, TErrorEvent ErrorEvent, int &ErrorCode) 
{ 
    ErrorCode = 0; 
} 
//--------------------------------------------------------------------------- 
void __fastcall TFormMain::TimerConnTimer(TObject *Sender) 
{ 
    if(ClientSocket->Active == false) 
    { 
        ClientSocket->Open(); 
    } 
    else 
    { 
        ClientSocket->Socket->SendText("DisConnect"); 
    } 
} 
//--------------------------------------------------------------------------- 
 
void __fastcall TFormMain::ClientSocketDisconnect(TObject *Sender, 
      TCustomWinSocket *Socket) 
{ 
    lblState->Caption = "not connect!"; 
} 
//--------------------------------------------------------------------------- 
 
 
void __fastcall TFormMain::Button2Click(TObject *Sender) 
{ 
    LANA_ENUM AdapterList; 
    NCB Ncb; 
    //调用memset函数将Ncb结构清零 
    memset(&Ncb, 0 ,sizeof(NCB)); 
    Ncb.ncb_command  = NCBENUM; 
    Ncb.ncb_buffer = (unsigned char *)&AdapterList; 
    Ncb.ncb_length = sizeof(AdapterList); 
    Netbios(&Ncb); 
 
    //获取所有的网卡 
    AnsiString mac_addr; 
    for(int i = 0; i < AdapterList.length; i++) 
    { 
        if(!GetAdapterInfo(AdapterList.lana[i], mac_addr)) 
        { 
            Application->MessageBoxA("读取硬件标志错误", "错误信息", MB_OK); 
            break; 
        } 
        ShowMessage(mac_addr); 
    } 
} 
//--------------------------------------------------------------------------- 
bool TFormMain::GetAdapterInfo(int adapter_num, AnsiString &mac_addr) 
{ 
    //重置Ncb结构内容 
    NCB Ncb; 
    memset(&Ncb, 0, sizeof(NCB)); 
    Ncb.ncb_command = NCBRESET; 
    Ncb.ncb_lana_num = adapter_num; 
    if(Netbios(&Ncb) != NRC_GOODRET) 
    { 
        mac_addr = "bad(NCBRESET):)"; 
        mac_addr += AnsiString(Ncb.ncb_retcode); 
        return false; 
    } 
 
    //准备获取网卡状态 
    ZeroMemory(&Ncb, sizeof(Ncb)); 
    Ncb.ncb_command = NCBASTAT; 
    Ncb.ncb_lana_num = adapter_num; 
    strcpy((char *)Ncb.ncb_callname, "*"); 
    struct ASTAT 
    { 
        ADAPTER_STATUS adapt; 
        NAME_BUFFER NameBuff[30]; 
    }Adapter; 
    ZeroMemory(&Adapter, sizeof(Adapter)); 
    Ncb.ncb_buffer = (unsigned char *)&Adapter; 
    Ncb.ncb_length = sizeof(Adapter); 
 
    //获取网卡信息,如果运行正常,则返回冒号分割的串 
    if(Netbios(&Ncb) == 0) 
    { 
        char acMAC[18]; 
        sprintf(acMAC, "%02X-%02X-%02X-%02X-%02X-%02X", 
                    int(Adapter.adapt.adapter_address[0]), 
                    int(Adapter.adapt.adapter_address[1]), 
                    int(Adapter.adapt.adapter_address[2]), 
                    int(Adapter.adapt.adapter_address[3]), 
                    int(Adapter.adapt.adapter_address[4]), 
                    int(Adapter.adapt.adapter_address[5])); 
        mac_addr = acMAC; 
        return true; 
    } 
    else 
    { 
        mac_addr = "bad(NCBASTAT):"; 
        mac_addr += AnsiString(Ncb.ncb_retcode); 
        return false; 
    } 
} 
//--------------------------------------------------------------------------- 
AnsiString __fastcall TFormMain::GetLocalMac() 
{ 
    LANA_ENUM AdapterList; 
    NCB Ncb; 
    //调用memset函数将Ncb结构清零 
    memset(&Ncb, 0 ,sizeof(NCB)); 
    Ncb.ncb_command  = NCBENUM; 
    Ncb.ncb_buffer = (unsigned char *)&AdapterList; 
    Ncb.ncb_length = sizeof(AdapterList); 
    Netbios(&Ncb); 
 
    //获取所有的网卡 
    AnsiString mac_addr; 
    for(int i = 0; i < AdapterList.length; i++) 
    { 
        if(!GetAdapterInfo(AdapterList.lana[i], mac_addr)) 
        { 
            Application->MessageBoxA("读取硬件标志错误", "错误信息", MB_OK); 
            break; 
        } 
    } 
    return mac_addr; 
} 
//--------------------------------------------------------------------------- 
void TFormMain::SendCommand(AnsiString ClientMac , int Class) 
{ 
    TCCBaseMessage_512 Msg; 
    Msg.Head = CC_HEAD; 
    Msg.Length = sizeof(TCCBaseMessage_512); 
    Msg.Class = Class; 
 
    memset(Msg.Buffer, 0x00, 500); 
    memcpy(Msg.Buffer, ClientMac.c_str(), ClientMac.Length()); 
 
    //把IP分割分别放在Data里 
    AnsiString ip = this->ReadIP(); 
    int i = 0; 
    int pos = ip.AnsiPos("."); 
    while(pos > 0) 
    { 
        Msg.Data[i] = 0; 
        Msg.Data[i] = ip.SubString(1, pos - 1).ToInt(); 
        ip = ip.SubString(pos + 1, ip.Length() - pos + 1); 
        pos = ip.AnsiPos("."); 
        i++; 
    } 
    Msg.Data[3] = 0; 
    Msg.Data[3] = ip.ToInt(); 
 
    FormMain->ClientSocket->Socket->SendBuf(&Msg, sizeof(TCCBaseMessage_512)); 
} 
//--------------------------------------------------------------------------- 
 
void __fastcall TFormMain::FormCloseQuery(TObject *Sender, bool &CanClose) 
{ 
    FormMain->SendCommand("disconnect", CLIENT_DISCONNECT); 
    Application->ProcessMessages(); 
    ClientSocket->Close(); 
} 
//--------------------------------------------------------------------------- 
 
 
void __fastcall TFormMain::ClientSocketRead(TObject *Sender, 
      TCustomWinSocket *Socket) 
{// 
    AnsiString strCmd = ClientSocket->Socket->ReceiveText(); 
    int iStart = strCmd.Pos("<"); 
    int iEnd = strCmd.Pos(">"); 
    int pos = strCmd.Pos("CloseAll"); 
    if((iStart < pos) && (pos < iEnd)) 
    { 
        CloseComputer(5, false); 
    } 
} 
//---------------------------------------------------------------------------