4 Ocak 2015 Pazar

SetFileTime


#include <windows.h>
#include <tchar.h>
#include <stdio.h>



BOOL SetFileToCurrentTime(HANDLE hFile)
{
    FILETIME ftFileTime;
    SYSTEMTIME st;
    BOOL bIsChanged;

    GetSystemTime(&st);              // Åžimdiki Sistem Zamanını Al
    SystemTimeToFileTime(&st, &ftFileTime);  // Åžimdiki sistem zamanını "File Time" formatına çevir.
    bIsChanged = SetFileTime(hFile, //DeÄŸiÅŸtirilecek dosyaya ait handle
&ftFileTime,   //lpCreationTime
         &ftFileTime,   //lpLastAccessTime
&ftFileTime    //lpLastWriteTime
        );  

    return bIsChanged;
}

BOOL GetLastWriteTime(HANDLE hFile, int FileProcess)    //opsiyonel, -->dosyaya ait zamanları gösterme.
{
    FILETIME ftCreate, ftAccess, ftWrite;
    SYSTEMTIME stUTC, stLocal;

    // Dosyaya ait olusturmaison eriÅŸim ve son deÄŸiÅŸtirme zamanlarını geri döndür
    if (!GetFileTime(hFile, &ftCreate/*olusturma*/, &ftAccess/*son erisim*/, &ftWrite/*son degistirme*/))
        return FALSE;

switch (FileProcess)
{

case 1:
    //dosyanın olusturma tarihini bugunun tarihi olarak goster...
    FileTimeToSystemTime(&ftCreate, &stUTC);
    SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
printf("olusturulma saati--> %d : %d : %d : %d \n",stLocal.wHour,stLocal.wMinute,stLocal.wSecond, stLocal.wMilliseconds);
printf("olusturulma tarihi--> %d.%d.%d\n",stLocal.wDay,stLocal.wMonth,stLocal.wYear);
break;
case 2:
/////////////////////////////////////////////////////////
//dosyanın son erisim tarihini bugunun tarihi olarak goster...
    FileTimeToSystemTime(&ftAccess, &stUTC);
    SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
printf("son erisim saati--> %d : %d : %d : %d \n",stLocal.wHour,stLocal.wMinute,stLocal.wSecond, stLocal.wMilliseconds);
printf("son erisim tarihi--> %d.%d.%d\n",stLocal.wDay,stLocal.wMonth,stLocal.wYear);
break;
case 3:
/////////////////////////////////////////////////////////
//dosyanın son değiştirme tarihini bugunun tarihi olarak goster...
    FileTimeToSystemTime(&ftWrite, &stUTC);
    SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
printf("son degistirme saati--> %d : %d : %d : %d \n",stLocal.wHour,stLocal.wMinute,stLocal.wSecond, stLocal.wMilliseconds);
printf("son degistirme tarihi--> %d.%d.%d\n",stLocal.wDay,stLocal.wMonth,stLocal.wYear);
/////////////////////////////////////////////////////////
break;

default:
printf("Yanlis bir secim yaptiniz");
break;
}
return true;
}

int main()
{
    HANDLE hFile;

#if defined _UNICODE
hFile = CreateFile(L"D:\indir.jpg", GENERIC_WRITE, 0, 0,
                           OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL,0);
#elif defined _MBCS
hFile = CreateFile("D:\indir.jpg", GENERIC_WRITE, 0, 0,
                           OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL,0);
#endif

    if(hFile == INVALID_HANDLE_VALUE)
    {
printf("Dosya olusturma basarisiz... Mesaj : %d\n", GetLastError());
        return 0;
    }
else
{
printf("\nDosyaya basari ile erisim saglandi...");
}


int iTimeChoice;
printf("\n****DOSYAYA AIT ZAMANLARI GOSTER****\n Olusturma Tarihi -->1 \n Son Erisim Tarihi -->2 \n Degistirme Tarihi -->3");
scanf("%d",&iTimeChoice);
GetLastWriteTime( hFile,iTimeChoice);

if(SetFileToCurrentTime(hFile))
{
printf("\n\nDosya zamanlari basari ile degistirildi\n");
}
else
{
wprintf(L"\n\nDosya zamanlari degistirilemedi\n");
}

#if defined _MBCS
TCHAR A[]=_T("EWtFbb\0koko");
printf("karakter --->>%s \n\n\n",A);
LPTSTR a;
#endif



CloseHandle(hFile);


}

FarProc

/****************************************************************************
 * Program Name : Gokmen Setup Bootstrapper
 * Program Ver. : v1.2.0.0
 * Module Name  : Setup.exe
 * Last Edition : 08.04.2013
 * Optimization : No code analysis issues were detected.
 ****************************************************************************/
#include <windows.h>
#include <strsafe.h>

typedef void( WINAPI *SYSINF )( LPSYSTEM_INFO );
#define BUFFERSIZE 260

int main()
{

   
    //ek bilbi : bilgisayar adını Load library ile almak
HMODULE szMod = LoadLibraryA("kernel32.dll");     // dll için adres
    FARPROC szAdd = GetProcAddress(szMod, "GetComputerNameA");  // fnk adresi al



    char szTmp[MAX_COMPUTERNAME_LENGTH + 1];
    DWORD dwSize = sizeof(szTmp);
    ((BOOL(WINAPI*)(LPSTR, LPDWORD))szAdd)(szTmp, &dwSize); //szadd GetComputerName şekline getir. (aldıgı parametreler dönüş tipi v.s. )
    MessageBoxA(0, szTmp, 0, 0); //
 //   return ERROR_SUCCESS;







SYSTEM_INFO sysInfo; //system bilgilerini tut
WIN32_FIND_DATA ffd;     //dosya bilgileri.. unicode derlenirse arkada WIN32_FIND_DATAW olarak tanımlanır.
HANDLE hFind;   //dosya için handle
HINSTANCE hInstance;  //bir modüle yapılan handle... örnek bir exe yüklenınce onu tanımak içindir
SYSINF sysINF=NULL;
TCHAR myPath[MAX_PATH];
TCHAR EXE[MAX_PATH] = L"setup.exe";
TCHAR MSI[MAX_PATH] = L"setup.msi";
TCHAR *cpuArch, *subDir, *MsgError;

#ifdef _DEBUG
wprintf( L"Checking System Architecture... : " );
#endif

hInstance = LoadLibrary( L"kernel32.dll" ); //yüklenen dll ye artık hInstance kullanarak eriş...
FARPROC fp;
if ( hInstance != NULL )                  // loading DLL failed
fp=GetProcAddress( hInstance , //module adı (handle (hinstance))
                                   "GetNativeSystemInfo" // buraya fnk ya da değişken ismi gelebilir...
 );

((void( WINAPI *)( LPSYSTEM_INFO ))fp)(&sysInfo);


//eğer GetProcAdress basarılı olursa, geriye çıkarılan fnk ya da değişkenın adresini döndürür
if ( NULL != sysINF )
sysINF( &sysInfo );                        // found, use this DLL function
else
GetSystemInfo( &sysInfo );

switch ( sysInfo.wProcessorArchitecture ) {
case PROCESSOR_ARCHITECTURE_INTEL:
{ cpuArch = L"32-Bit"; subDir = L"x86"; };

break;
case PROCESSOR_ARCHITECTURE_AMD64:
{ cpuArch = L"64-Bit"; subDir = L"x64"; };

break;
}

#ifdef _DEBUG
wprintf( L"%s System\n", cpuArch );
#endif

GetCurrentDirectory( MAX_PATH, myPath );
StringCchCat( myPath, BUFFERSIZE, L"\\" );
StringCchCat( myPath, BUFFERSIZE, subDir );

hFind = FindFirstFile( myPath, &ffd );

if ( hFind != INVALID_HANDLE_VALUE ) {
FindClose( hFind ); //dosya bulunamadı ise...
SetCurrentDirectory( myPath );
#ifdef _DEBUG
wprintf( L"Looking for installation program in \"%s\" sub-directory...\n", subDir );
#endif
}
else {
wprintf( L"ERROR (%d): Installation sub-directory not found!..\n", GetLastError() );
exit( EXIT_FAILURE );
}

GetCurrentDirectory( MAX_PATH, myPath );

hFind = FindFirstFile( EXE, &ffd );   // EXE yani("setup.exe") ara ve bilgilerini ffd içine at

if ( hFind == INVALID_HANDLE_VALUE )
hFind = FindFirstFile( MSI, &ffd ); // "setup.exe" yoksa "setup.msi" yi ara

if ( hFind == INVALID_HANDLE_VALUE ) { //"setup.msi" de yoksa hatayı ver ve çık...
wprintf( L"ERROR (%d) : Installation program not found!..\n", GetLastError() );
return 3;
}

#ifdef _DEBUG
wprintf( L"Found \"%s\". Starting installation...\n", ffd.cFileName ); //işlem basarılı. bulunan dosyayı ekrana bas.
#endif




hInstance = ShellExecute( NULL, L"open", ffd.cFileName, NULL, myPath, SW_MAXIMIZE );     //bulunan setup.msi yada exe yi aç
                                                                                      //ekran modu SW_NORMAL olsun
                                                                                     //SW_MAXIMIZE desek tam ekran açılır

if ( ( int ) hInstance < 32 ) {
switch ( ( int ) hInstance ) {//shellexecute hata mesajı varsa ekrana bas ve çık ...
case 0                      :
MsgError = L"Insufficient Memory/Resources";
break;

case ERROR_FILE_NOT_FOUND   : //dosya bulunamad
MsgError = L"File not found";
break;

case ERROR_PATH_NOT_FOUND   : //yol bulunamadı
MsgError = L"Path not found";
break;

case ERROR_BAD_FORMAT :      //format hatası.: örneğin x86 için x64 program...
MsgError = L"Invalid file format";
break;

case SE_ERR_ACCESSDENIED    : //erişim engellendi OS tarafından
MsgError = L"Access denied";
break;

case SE_ERR_ASSOCINCOMPLETE : //dosya adı eksik veya gecersiz
MsgError = L"Invalid file association";
break;

case SE_ERR_DDEBUSY         :  //DDE = paylaşılan hafızanın uygulamalar arası veri paylaşımında kullanılması
MsgError = L"DDE transaction not completed"; //DDE tamamlanamadı
break;

case SE_ERR_DDEFAIL         :
MsgError = L"DDE transaction failed"; //DDE
break;

case SE_ERR_DDETIMEOUT      :  //DDE için yapılan request time out aldı. tamamlanamadı
MsgError = L"DDE transaction timed out";
break;

case SE_ERR_DLLNOTFOUND     : //sözkonusu dll bulunamadı
MsgError = L"Specified DLL not found";
break;

case SE_ERR_NOASSOC         :
MsgError = L"No application associated";
break;

case SE_ERR_OOM             : //hafıza yetersiz...
MsgError = L"Not enough memory";
break;

case SE_ERR_SHARE           : //paylaşım ihlali oluştu.
MsgError = L"Sharing violation";
break;
}

wprintf( L"ERROR (%d): %s!..\n", GetLastError(), MsgError ); //bulunan hatayı ekrana bas.
}
else
wprintf( L"Succeeded. Exiting!..." ); // hata yok. setup.exe veya msi çalıştır....

return 0;
}

Reboot MessageBox

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <windows.h>
#include <ctype.h>
char command[20];

  BOOL WINAPI RecognizeCommand(char command[])
  {
  const int result=NULL;
       HANDLE hToken;
       TOKEN_PRIVILEGES tPrivilige;

         // Erişim Belirleyici al...

      if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
 {
 return false;
 }
         // Get the LUID for the shutdown privilege.
    //AdjustTokenPriviliges fonksiyonu sözkonusu işlem için yetkileri aktifleştirir veya iptal eder....
         //Burda Luid=Locally Unique Idetifier-- Restart atılana kadar 64 bitlik eşsiz bir deger üretmeyi garanti eder...
    //Power off, reboot ve shutdown işlemleri için -->SE_SHUTDOWN_NAME yetkisi olmalıdır. Aşağıda bu yetki tanımlanmıştır.
    //#define SE_SHUTDOWN_NAME  ------->              TEXT("SeShutdownPrivilege")  ---> ilgili yetki bu sekilde tanımlıdır.
       
    LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,&tPrivilige.Privileges[0].Luid);

//Yukarıdaki LookupPriviligeValue tanımı aşagıdaki gibidir

//LookupPrivilegeValueA(
         //_In_opt_ LPCSTR lpSystemName,
         //_In_     LPCSTR lpName,
         //_Out_    PLUID   lpLuid
         //                     );
         tPrivilige.PrivilegeCount = 1;  // tek izin değiştirilecek...  
         tPrivilige.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; //SE_PRIVILIGE_ENABLED-->ilgili yetkiyi aktifleştirir.
         // Get the shutdown privilege for this process.
         AdjustTokenPrivileges(
     hToken,
 FALSE,
 &tPrivilige,
 0,
                  (PTOKEN_PRIVILEGES)NULL,
 0
            );

          if (GetLastError() != ERROR_SUCCESS)
       {
    return false;
       }


//ExitWindowsEx FOnksiyonunda ilk parametre flag ikincisi ise Nedeni tutar
  if(strcmp((command),"reboot")==0)
       {
             const int result = MessageBox(NULL, "Bilgisayar yeniden başlatılıyor. Onaylıyor musunuz?", "UYARI",  MB_YESNO);
            switch (result)
            {
              case IDYES:
 if (!ExitWindowsEx(EWX_REBOOT| EWX_FORCE,SHTDN_REASON_MAJOR_OPERATINGSYSTEM |SHTDN_REASON_MINOR_UPGRADE |SHTDN_REASON_FLAG_PLANNED | SHTDN_REASON_MINOR_OTHER))
                 {//Tekrar baslat(zorla)-->yeniden baslatma sebebi: işletim sistemi sorunu(OPERATINGSYSTEM) veya güncelleme(UPGRADE) veya Planlanmış bir kapanma(planned) veya başka bir sebeb(other)
                return false;
                 }
                 else
                 {
                return true;
                 }  
                 break;
             case IDNO:
                 break;
             case IDCANCEL:
                 break;
             default:
                 break;
            }      
return false;
      }
      else if(strcmp((command),"shutdown")==0)
      {
             const int result = MessageBox(NULL, "Bilgisayar Kapatılıyor. Onaylıyor musunuz?", "UYARI",  MB_YESNO);
           switch (result)
           {
                    case IDYES:
                       if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,SHTDN_REASON_MAJOR_OPERATINGSYSTEM |SHTDN_REASON_MINOR_UPGRADE |SHTDN_REASON_FLAG_PLANNED| SHTDN_REASON_MINOR_OTHER))
                       { //kapat(zorla kapat)-->kapatma sebebi: işletim sistemi sorunu(OPERATINGSYSTEM) veya güncelleme(UPGRADE) veya Planlanmış bir kapanma(planned) veya başka bir sebeb(other)
                      return false;
                       }
                       else
                       {
                      return true;
                       }
                       break;
                    case IDNO:
                       break;
                    case IDCANCEL:                  
                       break;
                    default:
                       break;
           }          
      return false;
     }
     else if(strcmp((command),"power off")==0 || strcmp((command),"poweroff")==0)
     {
            const int result = MessageBox(NULL, "Bilgisayar Kapatılıyor(Power Off). Onaylıyor musunuz?", "UYARI",  MB_YESNO);
           switch (result)
           {
                    case IDYES:
                      if (!ExitWindowsEx(EWX_POWEROFF | EWX_FORCE,SHTDN_REASON_MAJOR_OPERATINGSYSTEM |SHTDN_REASON_MINOR_UPGRADE |SHTDN_REASON_FLAG_PLANNED| SHTDN_REASON_MINOR_OTHER))
             {//KApatveGuçKes(zorla kapat)-->kapatma sebebi: işletim sistemi sorunu(OPERATINGSYSTEM) veya güncelleme(UPGRADE) veya Planlanmış bir kapanma(planned) veya başka bir sebeb(other)
            return false;
              }
             else
              {
            return true;
              }  
                       break;
                    case IDNO:
                       break;
                    case IDCANCEL:
                       break;
                    default:
                       break;
            }    
             return false;
     }
     else if(strcmp((command),"log off")==0 || strcmp((command),"logoff")==0)
     {
           const int result = MessageBox(NULL, "Kullanıcı çıkışı yapılacaktır. Onaylıyor musunuz?", "UYARI",  MB_YESNO);
           switch (result)
           {
                    case IDYES:
                       if (!ExitWindowsEx(EWX_LOGOFF | EWX_FORCE,SHTDN_REASON_MAJOR_OPERATINGSYSTEM |SHTDN_REASON_MINOR_UPGRADE |SHTDN_REASON_FLAG_PLANNED| SHTDN_REASON_MINOR_OTHER))
           {//Kullanıcı Çıkışı(zorla Çıkış)-->ÇIKIŞ sebebi: işletim sistemi sorunu(OPERATINGSYSTEM) veya güncelleme(UPGRADE) veya Planlanmış bir kapanma(planned) veya başka bir sebeb(other)
            return false;
           }
           else
           {
            return true;
           }
                        break;
                    case IDNO:
                        break;
                    case IDCANCEL:
                        break;
                    default:
                        break;
            }  
             return false;
     }
     else
     {
           printf("Komut taninamadi.");  
              return false;
     }
   }

    int main(int argc,char *argv[]) {
              int i=1;
              if(argc < 2)
 {
                  printf("Hic argument alinamadi\n");
                  getch();
                  return 0;
              }
              else if(argc>2)
              {
                 if(argc==3)
                    {
                         strcat(command,argv[1]);
                         strcat(command,argv[2]);
                         RecognizeCommand(command);  
                    }
                 else
                    {
                         printf("argument sayisi gecersiz.\n");
                         getch();
                         return 0;
                    }            
             }
            else
             {
                strcat(command,argv[1]);
                RecognizeCommand(command);
             }
            return(0);  
        }

IsWow64 Function

#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <stdlib.h>

typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);

LPFN_ISWOW64PROCESS fnIsWow64Process;

BOOL IsWow64()
{
    BOOL bIsWow64 = FALSE;

    //IsWow64Process is not available on all supported versions of Windows.
    //Use GetModuleHandle to get a handle to the DLL that contains the function
    //and GetProcAddress to get a pointer to the function if available.

    fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(
        GetModuleHandle(TEXT("kernel32")),"IsWow64Process");

    if(NULL != fnIsWow64Process)
    {
        if (!fnIsWow64Process(GetCurrentProcess(),&bIsWow64))
        {
            //handle error
        }
    }
    return bIsWow64;
}

int main( void )
{

SYSTEM_INFO sys;
GetSystemInfo(&sys);
DWORD sysar=sys.wProcessorArchitecture;
#if defined _WIN64
        if(IsWow64())
        _tprintf(TEXT("The process is running under WOW64.\n")); //process 64 and PC 32 --->BOYLE BIR IHTIMAL YOK(CALISMAZ)
        else
{
        _tprintf(TEXT("64 bit process under 64 bit PC \n")); //process 64 and PC 64
system("start C:\\Example64Bit"); //64 bit programı çalıştır
}
#elif defined _WIN32
    if(IsWow64())
{
            _tprintf(TEXT("32 bit process under 64 bit PC.\n")); //program 32, win64
   system("start C:\\Example64Bit");//64 bit programı çalıştır
}
else
{
_tprintf(TEXT("32 bit process under 32 bit PC \n")); //program 32, win32
    system("start C:\\32BitExample"); //32 bit programı çalıştır
}
#endif
    return 0;
}

3 Ocak 2015 Cumartesi

VSc++ Setup


#include <windows.h>
#include <strsafe.h>

typedef void( WINAPI *SYSINF )( LPSYSTEM_INFO );
#define BUFFERSIZE 260

int main()
{
SYSTEM_INFO sysInfo;
WIN32_FIND_DATA ffd;
HANDLE hFind;
HINSTANCE hInstance;
SYSINF sysINF;
TCHAR myPath[MAX_PATH];
TCHAR EXE[MAX_PATH] = L"setup.exe";
TCHAR MSI[MAX_PATH] = L"setup.msi";
TCHAR *cpuArch, *subDir, *MsgError;

#ifdef _DEBUG
wprintf( L"Checking System Architecture... : " );
#endif

hInstance = LoadLibrary( L"kernel32.dll" );

if ( hInstance != NULL )                  // loading DLL failed
sysINF = ( SYSINF ) GetProcAddress( hInstance , "GetNativeSystemInfo" );

if ( NULL != sysINF )
sysINF( &sysInfo );                        // found, use this DLL function
else
GetSystemInfo( &sysInfo );

switch ( sysInfo.wProcessorArchitecture ) {
case PROCESSOR_ARCHITECTURE_INTEL:
{ cpuArch = L"32-Bit"; subDir = L"x86"; };

break;
case PROCESSOR_ARCHITECTURE_AMD64:
{ cpuArch = L"64-Bit"; subDir = L"x64"; };

break;
}

#ifdef _DEBUG
wprintf( L"%s System\n", cpuArch );
#endif

GetCurrentDirectory( MAX_PATH, myPath );
StringCchCat( myPath, BUFFERSIZE, L"\\" );
StringCchCat( myPath, BUFFERSIZE, subDir );

hFind = FindFirstFile( myPath, &ffd );

if ( hFind != INVALID_HANDLE_VALUE ) {
FindClose( hFind );
SetCurrentDirectory( myPath );
#ifdef _DEBUG
wprintf( L"Looking for installation program in \"%s\" sub-directory...\n", subDir );
#endif
}
else {
wprintf( L"ERROR (%d): Installation sub-directory not found!..\n", GetLastError() );
exit( EXIT_FAILURE );
}

GetCurrentDirectory( MAX_PATH, myPath );

hFind = FindFirstFile( EXE, &ffd );

if ( hFind == INVALID_HANDLE_VALUE )
hFind = FindFirstFile( MSI, &ffd );

if ( hFind == INVALID_HANDLE_VALUE ) {
wprintf( L"ERROR (%d) : Installation program not found!..\n", GetLastError() );
return 3;
}

#ifdef _DEBUG
wprintf( L"Found \"%s\". Starting installation...\n", ffd.cFileName );
#endif
hInstance = ShellExecute( NULL, L"open", ffd.cFileName, NULL, myPath, SW_HIDE );

if ( ( int ) hInstance < 32 ) {
switch ( ( int ) hInstance ) {
case 0                      :
MsgError = L"Insufficient Memory/Resources";
break;

case ERROR_FILE_NOT_FOUND   :
MsgError = L"File not found";
break;

case ERROR_PATH_NOT_FOUND   :
MsgError = L"Path not found";
break;

case ERROR_BAD_FORMAT       :
MsgError = L"Invalid file format";
break;

case SE_ERR_ACCESSDENIED    :
MsgError = L"Access denied";
break;

case SE_ERR_ASSOCINCOMPLETE :
MsgError = L"Invalid file association";
break;

case SE_ERR_DDEBUSY         :
MsgError = L"DDE transaction not completed";
break;

case SE_ERR_DDEFAIL         :
MsgError = L"DDE transaction failed";
break;

case SE_ERR_DDETIMEOUT      :
MsgError = L"DDE transaction timed out";
break;

case SE_ERR_DLLNOTFOUND     :
MsgError = L"Specified DLL not found";
break;

case SE_ERR_NOASSOC         :
MsgError = L"No application associated";
break;

case SE_ERR_OOM             :
MsgError = L"Not enough memory";
break;

case SE_ERR_SHARE           :
MsgError = L"Sharing violation";
break;
}

wprintf( L"ERROR (%d): %s!..\n", GetLastError(), MsgError );
}
else
wprintf( L"Succeeded. Exiting!..." );

return 0;
}

VSc++ Computer shut-reboot-powerOff

/****************************************************************************
 * Program Name : Computer Power Options
 * Program Ver. : v1.0.0.0
 * Module Name  : ShutDown.exe
 * Last Edition : 20.03.2013
 * Optimization : No code analysis issues were detected.
 ****************************************************************************/
#include <Windows.h>
#include <strsafe.h>

#define BUF_SIZE 260

int wmain( int argc, TCHAR *argv[] )
{
TCHAR param[MAX_PATH] = L"";
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
DWORD op;

if ( argc == 2 )
StringCchCat( param, BUF_SIZE, argv[1] );
else {
wprintf( L"\nKullanim :\n\tShutDown <parametre>" );
wprintf( L"\nKullanilabilir parametre degerleri:" );
wprintf( L"\n\tlogoff   : Oturumunuzu sona erdirir." );
wprintf( L"\n\tshutdown : Bilgisayari kapatir." );
wprintf( L"\n\treboot   : Bilgisayari yeniden baslatir." );
wprintf( L"\n\tpoweroff : Bilgisayari kapatip gucu keser." );
return 1;
}

if ( ! lstrcmp( param, L"logoff"   ) )
op = EWX_LOGOFF;
else if ( ! lstrcmp( param, L"shutdown" ) )
op = EWX_SHUTDOWN;
else if ( ! lstrcmp( param, L"reboot"   ) )
op = EWX_REBOOT;
else if ( ! lstrcmp( param, L"poweroff" ) )
op = EWX_POWEROFF;
else
op = 999;

op = op | EWX_FORCE;

// Get a token for this process.
if ( ! OpenProcessToken( GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&hToken
  )
  )
return 1;

// Get the LUID for the shutdown privilege.
LookupPrivilegeValue( NULL, // Name of the system
 SE_SHUTDOWN_NAME, // Name of the privilege
 &tkp.Privileges[0].Luid // Locally unique identifier
);

tkp.PrivilegeCount = 1; // one privilege to set
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

// Get the shutdown privilege for this process.
AdjustTokenPrivileges( hToken,
  FALSE,
  &tkp,
  0,
  ( PTOKEN_PRIVILEGES ) NULL,
  0
);

if ( GetLastError() != ERROR_SUCCESS )
return 1;

ExitWindowsEx( op, 0 );

return 0;
}

VSc++ Load Library



#include <windows.h>
#include <strsafe.h>              // for StringCchPrintf function

/*************************************************************************
 * Global type and variable definitions
 ************************************************************************/
// Define a new type in the same structure of GetSystemInfo API function
typedef VOID ( WINAPI *SYSINF )( LPSYSTEM_INFO );
// Specify the maximum size of buffer
#define BUF_SIZE 256
//----End of Type Definitions --------------------------------------------

/*************************************************************************
 * Error handling function which display error in a MessageBox
 ************************************************************************/
void ShowError( TCHAR *errFunc )
{
TCHAR    Message[BUF_SIZE] = L"";  // Message will be displayed
TCHAR    *msgStatic;               // Static Error string
LPCTSTR  fmtString;                // Error string structure
LPVOID   msgBuffer;                // Temporary buffer for error description
DWORD    errNo;                    // Last System Error Number

errNo    = GetLastError();         // The last error number of this thread.

/**********************************************************************
 * Message string formatting Functions. This will get the error
 * description text defined by GetLastError() in localized language
 * and assign this text to reference of msgBuffer variable.
 *********************************************************************/
msgStatic = L"Program hatalı bir işlem sonucu durduruldu!...";
fmtString = L"%s\n\nYordam : %s\nKod: %d\nAçıklama : %s";

if ( FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
errNo,
0,
( LPTSTR ) &msgBuffer,
0,
NULL
)
  )
/*****************************************************************
* Prepare a formatted Message to display in the MessageBox.
****************************************************************/
StringCchPrintf( Message,    // Message String
BUF_SIZE,   // Max size of Message string
fmtString,  // Format String of Message
msgStatic,  // Argument 1 |
errFunc,    // Argument 2 |
errNo,      // Argument 3 |-> of Format String
msgBuffer   // Argument 4 |
  );

/**********************************************************************
* Show a message box which display the formatted error description
*********************************************************************/
MessageBox( NULL,
Message,            // Message that will be displayed
L"Hatalı İşlem",        // Caption of Message Box
MB_OK | MB_ICONERROR    // Buttons, Icons and sounds
 );
}
//----End of ShowError Function ------------------------------------------

/*************************************************************************
 * Main program function
 ************************************************************************/
int main()
{
HINSTANCE hInstance;
SYSINF sysINF;
SYSTEM_INFO si;
TCHAR cName[BUF_SIZE];
TCHAR uName[BUF_SIZE];
LPCTSTR txt;
TCHAR Info[BUF_SIZE];
DWORD chCount = BUF_SIZE;
TCHAR *cpuArch;

txt = L"Bilgisayar: %s\nKullanıcı: %s\nİşlemci: %d\nMimari: %s";

chCount = BUF_SIZE;
GetComputerName( cName, &chCount );
chCount = BUF_SIZE;
GetUserName( uName, &chCount );

hInstance = LoadLibrary( L"kernel32.dll" );

if ( hInstance == NULL ) {                 // loading DLL failed
ShowError( L"LoadLibrary() : Loading DLL is failed" );
return 1;                             // Exit with error.
}

/**********************************************************************
* "GetNativeSystemInfo" function in "kernel32.dll" is only Windows 7
* and later Operating systems. If this function call fails we must use
* the "GetSystemInfo" API function.
*********************************************************************/
sysINF = ( SYSINF ) GetProcAddress( hInstance , "GetNativeSystemInfo" );

if ( NULL == sysINF ) {                  // Getting DLL's function address failed
ShowError( L"GetProcAddress() : Getting function address is failed." );
GetSystemInfo( &si );                 // not found, use GetSystemInfo API function
}
else
sysINF( &si );                        // found, use this DLL function

switch ( si.wProcessorArchitecture ) {
case PROCESSOR_ARCHITECTURE_AMD64 :
cpuArch = L"64-Bit";
break;

case PROCESSOR_ARCHITECTURE_IA64  :
cpuArch = L"64-Bit";
break;

case PROCESSOR_ARCHITECTURE_INTEL :
cpuArch = L"32-Bit";
break;
}

StringCchPrintf(  Info,                    // Information String
 BUF_SIZE,                // Max size of Info string
 txt,                     // Format String of Info
 cName,                   // Arg 1 |
 uName,                   // Arg 2 |
 si.dwNumberOfProcessors, // Arg 3 |-> of Format String
 cpuArch                  // Arg 4 |
  );

MessageBox( NULL,
( LPCTSTR ) Info,              // Message that will be displayed
L"Sistem Bilgisi",             // Caption of Message Box
MB_OK | MB_ICONINFORMATION     // Buttons, Icons and Sounds
 );

return 0;
}