19 августа 2019 года    
Понедельник | 19:06    
Главная
 Новости
Базы данных
Безопасность PC
Всё о компьютерах
Графика и дизайн
Интернет-технологии
Мобильные устройства
Операционные системы
Программирование
Программы
Связь
Сети
 Документация
Статьи
Самоучители
 Общение
Форум







Разделы / Программирование / Delphi

Полезные советы по работе с Windows API и Delphi VCL.

Секция 2 из 8 - Предыдущая - Следующая
Все секции - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8

//text := stringreplaceall (text,'{\f2\fswiss\fprq2 System;}}','');{Skall alltid tas bort}
//text := stringreplaceall (text,'{\colortbl\red0\green0\blue0;}','');{Skall alltid tas bort}
{I version 2.01 av Delphi finns inte \cf0 med i RTF-rutan. Tog darfor bort
det efter \fs16 och la istallet en egen tvatt av \cf0.}
//temptext := hamtastreng (text,'{\rtf1','\deflang');
//text := stringreplace (text,temptext,''); {Hamta och radera allt fran start till deflang}
text := stringreplaceall (text,'\cf0','');
temptext := hamtastreng (text,'\deflang','\pard');{Plocka fran deflang till pard for att fa }
text := stringreplace (text,temptext,'');{oavsett vilken lang det ar. Norska o svenska ar olika}
text := stringreplaceall (text,'\ltrpar','');
text := stringreplaceall (text,'\ql','');
text := stringreplaceall (text,'\ltrch','');
{Har skall vi plocka bort fs och flera olika siffror beroende pa vilka alternativ vi godkanner.}
//text := stringreplaceall (text,'\fs16','');{8 punkter}
//text := stringreplaceall (text,'\fs20','');{10 punkter}
{Nu stadar vi istallet bort alla tvasiffriga fontsize.}
while pos ('\fs',text) >0 do
  begin
    //application.processmessages;
    start := pos ('\fs',text);
    Delete(text,start,5);
  end;
while pos ('\f',text) >0 do
  begin
    //application.processmessages;
    start := pos ('\f',text);
    Delete(text,start,3);
  end;
text := stringreplaceall (text,'\pard\li200-200{\*\pn\pnlvlblt\pnf1\pnindent200{\pntxtb\'+chr(39)+'b7}}\plain ','</P><UL>');
text := stringreplaceall (text,'{\pntext\'+chr(39)+'b7\tab}','<LI>');
text := stringreplaceall (text, '\par <LI>','<LI>');
text := stringreplaceall (text, '\par <UL>','<UL>');
text := stringreplaceall (text,'\pard\plain ','<P>');
text := stringreplaceall (text,'\par \plain\b\ul ','</P><MELLIS>');
text := stringreplaceall (text,'\plain\b\ul ','</P><MELLIS>');
text := stringreplaceall (text,'\plain','</MELLIS>');
text := stringreplaceall (text,'\par }','</P>');
if (pos ('\par \tab ',text)>0) or (pos ('<P>\tab ',text)>0) then
  begin
    text := stringreplaceall (text,'\par \tab ','<TR><TD>');
    text := stringreplaceall (text,'<P>\tab ','<TR><TD>');
    text := stringreplaceall (text,'\tab ','</TD><TD>');
  end
else
  begin
    text := stringreplaceall (text,'\tab ','');
  end;
text := stringreplaceall (text,'\par ','</P><P>');
text := stringreplaceall (text,'#]#','}');
text := stringreplaceall (text,'#[#','{');
text := stringreplaceall (text,'\\','\');
if pos('<TD>',text)>0 then text := text+'</TD></TR>';
if pos('<LI>',text)>0 then text := text+'</LI>';
result := text;
end;

end.
===

Author>:
johan@lindgren.pp.se
.

Q>:
Как перевести RTF в HTML?
A>:
Здесь процедура, которую я использую для конвертации содержимого RichEdit
в код SGML. Она не создает полноценный HTML-файл, но Вы можете расширить
функциональность, указал, какие RTF-коды Вы желаете конвертировать в
какие-либо HTML-тэги.

function rtf2sgml (text : string) : string;
{Funktion for att konvertera en RTF-rad till SGML-text.}
var
temptext : string;
start : integer;
begin
text := stringreplaceall (text,'&','##amp;');
text := stringreplaceall (text,'##amp','&amp');
text := stringreplaceall (text,'\'+chr(39)+'e5','&aring;');
text := stringreplaceall (text,'\'+chr(39)+'c5','&Aring;');
text := stringreplaceall (text,'\'+chr(39)+'e4','&auml;');
text := stringreplaceall (text,'\'+chr(39)+'c4','&Auml;');
text := stringreplaceall (text,'\'+chr(39)+'f6','&ouml;');
text := stringreplaceall (text,'\'+chr(39)+'d6','&Ouml;');
text := stringreplaceall (text,'\'+chr(39)+'e9','&eacute;');
text := stringreplaceall (text,'\'+chr(39)+'c9','&Eacute;');
text := stringreplaceall (text,'\'+chr(39)+'e1','&aacute;');
text := stringreplaceall (text,'\'+chr(39)+'c1','&Aacute;');
text := stringreplaceall (text,'\'+chr(39)+'e0','&agrave;');
text := stringreplaceall (text,'\'+chr(39)+'c0','&Agrave;');
text := stringreplaceall (text,'\'+chr(39)+'f2','&ograve;');
text := stringreplaceall (text,'\'+chr(39)+'d2','&Ograve;');
text := stringreplaceall (text,'\'+chr(39)+'fc','&uuml;');
text := stringreplaceall (text,'\'+chr(39)+'dc','&Uuml;');
text := stringreplaceall (text,'\'+chr(39)+'a3','&#163;');
text := stringreplaceall (text,'\}','#]#');
text := stringreplaceall (text,'\{','#[#');
text := stringreplaceall (text,'{\rtf1\ansi\deff0\deftab720','');{Skall alltid tas bort}
text := stringreplaceall (text,'{\fonttbl',''); {Skall alltid tas bort}
text := stringreplaceall (text,'{\f0\fnil MS Sans Serif;}','');{Skall alltid tas bort}
text := stringreplaceall (text,'{\f1\fnil\fcharset2 Symbol;}','');{Skall alltid tas bort}
text := stringreplaceall (text,'{\f2\fswiss\fprq2 System;}}','');{Skall alltid tas bort}
text := stringreplaceall (text,'{\colortbl\red0\green0\blue0;}','');{Skall alltid tas bort}
{I version 2.01 av Delphi finns inte \cf0 med i RTF-rutan. Tog darfor bort
det efter \fs16 och la istallet en egen tvatt av \cf0.}
//temptext := hamtastreng (text,'{\rtf1','\deflang');
//text := stringreplace (text,temptext,''); {Hamta och radera allt fran start till deflang}
text := stringreplaceall (text,'\cf0','');
temptext := hamtastreng (text,'\deflang','\pard');{Plocka fran deflang till pard for att fa }
text := stringreplace (text,temptext,'');{oavsett vilken lang det ar. Norska o svenska ar olika}
{Har skall vi plocka bort fs och flera olika siffror beroende pa vilka alternativ vi godkanner.}
//text := stringreplaceall (text,'\fs16','');{8 punkter}
//text := stringreplaceall (text,'\fs20','');{10 punkter}
{Nu stadar vi istallet bort alla tvasiffriga fontsize.}
while pos ('\fs',text) >0 do
  begin
    application.processmessages;
    start := pos ('\fs',text);
    Delete(text,start,5);
  end;
text := stringreplaceall (text,'\pard\plain\f0 ','<P>');
text := stringreplaceall (text,'\par \plain\f0\b\ul ','</P><MELLIS>');
text := stringreplaceall (text,'\plain\f0\b\ul ','</P><MELLIS>');
text := stringreplaceall (text,'\plain\f0','</MELLIS>');
text := stringreplaceall (text,'\par }','</P>');
text := stringreplaceall (text,'\par ','</P><P>');
text := stringreplaceall (text,'#]#','}');
text := stringreplaceall (text,'#[#','{');
text := stringreplaceall (text,'\\','\');
result := text;
end;

//This is cut directly from the middle of a fairly long save routine that calls the above function.
//I know I could use streams instead of going through a separate file but I have not had the time to change this

            utfilnamn := mditted.exepath+stringreplace(stringreplace(extractfilename(pathname),'.TTT',''),'.ttt','') + 'ut.RTF';
             brodtext.lines.savetofile (utfilnamn);
             temptext := '';
             assignfile(tempF,utfilnamn);
             reset (tempF);
             try
                while not eof(tempF) do
                  begin
                     readln (tempF,temptext2);
                     temptext2 := stringreplaceall (temptext2,'\'+chr(39)+'b6','');
                     temptext2 := rtf2sgml (temptext2);
                     if temptext2 <>'' then temptext := temptext+temptext2;
                     application.processmessages;
                  end;
             finally
                    closefile (tempF);
             end;
             deletefile (utfilnamn);
             temptext := stringreplaceall (temptext,'</MELLIS> ','</MELLIS>');
             temptext := stringreplaceall (temptext,'</P> ','</P>');
             temptext := stringreplaceall (temptext,'</P>'+chr(0),'</P>');
             temptext := stringreplaceall (temptext,'</MELLIS></P>','</MELLIS>');
             temptext := stringreplaceall (temptext,'<P></P>','');
             temptext := stringreplaceall (temptext,'</P><P></MELLIS>','</MELLIS><P>');
             temptext := stringreplaceall (temptext,'</MELLIS>','<#MELLIS><P>');
             temptext := stringreplaceall (temptext,'<#MELLIS>','</MELLIS>');
             temptext := stringreplaceall (temptext,'<P><P>','<P>');
             temptext := stringreplaceall (temptext,'<P> ','<P>');
             temptext := stringreplaceall (temptext,'<P>-','<P>_');
             temptext := stringreplaceall (temptext,'<P>_','<CITAT>_');
             while pos('<CITAT>_',temptext)>0 do
               begin
                 application.processmessages;
                 temptext2 := hamtastreng (temptext,'<CITAT>_','</P>');
                 temptext := stringreplace (temptext,temptext2+'</P>',temptext2+'</CITAT>');
                 temptext := stringreplace (temptext,'<CITAT>_','<CITAT>-');
               end;
             writeln (F,'<BRODTEXT>'+temptext+'</BRODTEXT>');

Author>:
johan@lindgren.pp.se
.

Q>:
[API, IMG] Как преобразовать ICO в BMP?
A>:
Попробуй:

  var
    Icon   : TIcon;
    Bitmap : TBitmap;
  begin
     Icon   := TIcon.Create;
     Bitmap := TBitmap.Create;
     Icon.LoadFromFile('c:\picture.ico');
     Bitmap.Width := Icon.Width;
     Bitmap.Height := Icon.Height;
     Bitmap.Canvas.Draw(0, 0, Icon );
     Bitmap.SaveToFile('c:\picture.bmp');
     Icon.Free;
     Bitmap.Free;
  end;

Author>:
Michael Vincze
vincze@ti.com
.

Q>:
[API, IMG] Как преобразовать BMP (32x32) в ICO?
A>:
Попробуй:

unit main;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls,
  Forms,Dialogs,ExtCtrls, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Image1: TImage;
    Image2: TImage;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
var winDC, srcdc, destdc : HDC;
    oldBitmap : HBitmap;
    iinfo : TICONINFO;
begin
    GetIconInfo(Image1.Picture.Icon.Handle, iinfo);

    WinDC := getDC(handle);
    srcDC := CreateCompatibleDC(WinDC);
    destDC := CreateCompatibleDC(WinDC);
    oldBitmap := SelectObject(destDC, iinfo.hbmColor);
    oldBitmap := SelectObject(srcDC, iinfo.hbmMask);

    BitBlt(destdc, 0, 0, Image1.picture.icon.width,
		   Image1.picture.icon.height,
           srcdc, 0, 0, SRCPAINT);
    Image2.picture.bitmap.handle := SelectObject(destDC, oldBitmap);
    DeleteDC(destDC);
    DeleteDC(srcDC);
    DeleteDC(WinDC);

	image2.Picture.Bitmap.savetofile(ExtractFilePath(Application.ExeName)
          + 'myfile.bmp');
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  image1.picture.icon.loadfromfile('c:\myicon.ico');
end;

end.

Author>:
david sampson
dsampson@atlanta.com
.

Q>:
[API] Как узнать кто висит на моей (или не моей) машине
A>:
#define STRICT
#include <windows.h>
#include <lm.h>
#include <iostream.h>
#include <tchar.h>

void UserEnum()
{
    BOOL keepGoing = TRUE ;
    DWORD entriesRead, totalEntries ;
    USER_INFO_2 * pInfo = NULL ;
    DWORD resumeHandle = 0 ; // must be 0 to start with
    char nameBuf[ UNLEN + 1 ] ; // constants defined in LMCONS.H
    char commentBuf[ MAXCOMMENTSZ + 1 ] ;
    WCHAR serverName[ 100 ] ;
    lstrcpyW( serverName, L"\\\\PDC" ) ; //L"" ) ;
    while ( keepGoing )
    {
        NET_API_STATUS ret = NetUserEnum(
            serverName, //NULL,
            2,
   0, //FILTER_NORMAL_ACCOUNT,
            (LPBYTE *)&pInfo, // Important:  ADDRESS of POINTER
            sizeof( USER_INFO_2 ) * 100, // requested buffer size; it may not
actually allocate this much
            &entriesRead,
            &totalEntries,
            &resumeHandle ) ;

        keepGoing = ( ret == ERROR_MORE_DATA ) ;

        if ( ret == 0 || ret == ERROR_MORE_DATA )
        {
            DWORD i ;
            for ( i = 0 ; i < entriesRead ; i++ )
            {
                //  Note that strings in the INFO structures
                //  will ALWAYS be Unicode, regardless of
                //  your settings!  Even though they're declared
                //  as LPTSTR, they're always LPWSTR.
                //  I'm compiling for non-Unicode, so I
                //  convert them to ANSI strings...
                //  Check for NULL pointers in the INFO structure
                LPWSTR pName = (LPWSTR)pInfo[ i ].usri2_name ;
                LPWSTR pComm = (LPWSTR)pInfo[ i ].usri2_comment ;
                if ( pName == NULL )
                {
                    lstrcpy( nameBuf, "(no name!)" ) ;
                }
                else if ( lstrlenW( pName ) == 0 )
                {
                    lstrcpy( nameBuf, "(empty name!)" ) ;
                }
                else
                {
                    WideCharToMultiByte( CP_ACP, 0,
                        pName, -1,
                        nameBuf, UNLEN,
                        NULL, NULL ) ;
                }
                if ( pComm == NULL )
                {
                    lstrcpy( commentBuf, "(no comment!)" ) ;
                }
                else if ( lstrlenW( pComm ) == 0 )
                {
                    lstrcpy( commentBuf, "(empty comment!)" ) ;
                }
                else
                {
                    WideCharToMultiByte( CP_ACP, 0,
                        pComm, -1,
                        commentBuf, MAXCOMMENTSZ,
                        NULL, NULL ) ;
                }
                cout << nameBuf << ":  " << commentBuf << endl ;
            }
        }
        else
        {
            cout << "NetUserEnum error " << ret << endl ;
        }

        if ( pInfo )
        {
            NetApiBufferFree( pInfo ) ;
            pInfo = NULL ;
        }
    }
}
//****************************************************************************/
/

Author>:
Sergey Andyk (Сергей Андык)
(2:5005/58.43)
asvzzz@chat.ru
.

Q>:
Как создать юзера и дать ему права?
A>:
NET_API_STATUS UserAdd(LPSTR username)
{

// некоторые используемые функции описаны в других QA

USER_INFO_2   user_info;

char compname[256];
wchar_t wcompname[256];
DWORD parm_err=0;
LSA_HANDLE PolicyHandle;

LPTSTR lpszSystemInfo;    // ptr. to system info. string
DWORD cchBuff = 256;      // size of comp. or user name
TCHAR tchBuffer2[256];    // buffer for concat'd. str.
WCHAR wGroupNameAdd[20]=L"Administrators";
    lpszSystemInfo = tchBuffer2;
    ZeroMemory(&user_info,sizeof(user_info));

    GetComputerName(lpszSystemInfo, &cchBuff);
    strcpy(compname,"\\\\");
    strcat(compname,lpszSystemInfo);

    mbstowcs( wcompname, compname, strlen(compname)+1 );
    mbstowcs(user_info.usri2_name,username, strlen(username)+1 );

 //-------создаем юзера------------//

        user_info.usri2_password = L"";
        user_info.usri2_priv = USER_PRIV_USER;
        user_info.usri2_flags =
UF_SCRIPT|UF_PASSWD_CANT_CHANGE|UF_DONT_EXPIRE_PASSWD|UF_NORMAL_ACCOUNT;
        user_info.usri2_acct_expires=TIMEQ_FOREVER;

 NetUserAdd(wcompname,// PDC name
       2L,                   // level
       (LPBYTE)&user_info,   // input buffer
       &parm_err );          // parameter in error

 GetAccountSid(
            NULL,       // default lookup logic
            username,    // account to obtain SID
            &pSid       // buffer to allocate to contain resultant SID
            );

 NetLocalGroupAddMember(0,wGroupNameAdd,pSid);

 //---------даем ему кое-какие права-----------//

OpenPolicy(
     wcompname,           // target machine
     POLICY_ALL_ACCESS,   //POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES,
     &PolicyHandle        // resultant policy handle
      );


SetPrivilegeOnAccount(
                    PolicyHandle,           // policy handle
                    pSid,                   // SID to grant privilege
                    L"SeInteractiveLogonRight", // Unicode privilege
                    TRUE                    // enable the privilege
                    );

SetPrivilegeOnAccount(
                    PolicyHandle,           // policy handle
                    pSid,                   // SID to grant privilege
                    L"SeNetworkLogonRight", // Unicode privilege
                    TRUE                    // enable the privilege
                    );


LsaClose(PolicyHandle);

return 0;
}
//***************************************************************************//

Author>:
Sergey Andyk (Сергей Андык)
(2:5005/58.43)
asvzzz@chat.ru
.

Q>:
[API] Как узнать ip адрес(а) машины (в текстовом виде)?
A>:
Кусок исходника от плугина к BackOrifice:

//---------------------------------------------------
void MachineIP(char *result)
{
      WSADATA WSAData;

      WSAStartup(MAKEWORD(1,1), &WSAData);

 char dot[6];
 int iResult;
 int i = 0;
 u_long *ppIpNO;
 u_long *pIpNO;
 HOSTENT FAR *lphostent;
 u_long ipHO;
 unsigned char binIp[4];
 int iterations = 0;

 //Get local host name and crudely validate
 char szHostName[100];
 *result = 0;

 iResult = gethostname(szHostName, sizeof(szHostName));
// printf("%d %s",iResult,szHostName);
 if ((iResult != 0) || (lstrcmp(szHostName, "")==0))
  return;

 //Lok up this host info via supplied name
 lphostent = gethostbyname(szHostName);
 if (lphostent == NULL)
  return;
 //Retreive first entry (might have multiple connects)
 do
 {
  iterations++;
  ppIpNO = (u_long *)lphostent->h_addr_list;
  if (ppIpNO+i == NULL)
   return;
  pIpNO = ((u_long *)*(ppIpNO+i));
  if (pIpNO == NULL)
   return;

 //convert back to host order, since SOCKADDR_IN expects that
  //MessageBox(NULL,"z","x",MB_OK);
  ipHO = ntohl(*pIpNO);

  binIp[0] = (BYTE)((ipHO & 0xff000000) >> 24);
  itoa(binIp[0], dot, 10);
  strcat(result,dot);
  binIp[1] = (BYTE)((ipHO & 0x00ff0000) >> 16);
  itoa(binIp[1], dot, 10);
  strcat(result, "."); strcat(result, dot);
  binIp[2] = (BYTE)((ipHO & 0x0000ff00) >> 8);
  itoa(binIp[2], dot, 10);
  strcat(result, "."); strcat(result, dot);
  binIp[3] = (BYTE)(ipHO & 0x000000ff);
  itoa(binIp[3], dot, 10);
  strcat(result,"."); strcat(result, dot);
  strcat(result,"\r\n");
  i++;
 } while ((pIpNO != NULL) && (iterations < 6));
 WSACleanup();
      PostQuitMessage(0);
 return;
}
//***************************************************************************//

Author>:
Sergey Andyk (Сергей Андык)
(2:5005/58.43)
asvzzz@chat.ru
.

Q>:
[API] Как запустить или закрыть скринсэйвер?
A>:
Starting
~~~~~~~~
The method for starting a screen saver is simple, but surprising. You post your
own window a message ! Post yourself the WM_SYSCOMMAND message with the
SC_SCREENSAVE parameter :

   // Uses MFC CWnd::PostMessage
   PostMessage (WM_SYSCOMMAND, SC_SCREENSAVE);


Stopping
~~~~~~~~
Stopping a screen saver is somewhat more complex. The Microsoft-documented way
of doing this is to look for the special screen-saver desktop, enumerate all
windows on that desktop, and close them, as follows:

   hdesk = OpenDesktop(TEXT("Screen-saver"),
                       0,
                       FALSE,
                       DESKTOP_READOBJECTS | DESKTOP_WRITEOBJECTS);
   if (hdesk)
   {
      EnumDesktopWindows (hdesk, (WNDENUMPROC)KillScreenSaverFunc, 0);
      CloseDesktop (hdesk);
   }
   // ----------------------------------------------------------------

   BOOL CALLBACK KillScreenSaverFunc (HWND hwnd, LPARAM lParam)
   {
      PostMessage(hwnd, WM_CLOSE, 0, 0);
      return TRUE;
   }


However, I can't recommend this approach. I have found when using this code,
NT4 very occasionally seems to get confused and pass you back the normal
desktop handle, in which case you end up trying to close all the normal
application windows. Note, in MS' defence, that the code above for closing
32 bit savers is derived from a sample that is only marked as valid for
NT3.51 - there is no mention of NT4 in the sample. Unfortunately, there
is also nothing to indicate that it doesn't work properly.

I have subsequently performed some tests, and found that the stock screen
savers supplied with NT4 will in any case get a hit on the window class search
normally used for 16 bit savers ("WindowsScreenSaverClass"). I don't believe
for a moment that the OpenGL savers (for example) are 16 bit, so maybe MS are
supplying a saver window class that will give the necessary hit.
So anyway, you can use this route :

   HWND hSaver = FindWindow ("WindowsScreenSaverClass", NULL);

   if (hSaver)
      PostMessage (hSaver, WM_CLOSE, 0, 0);


Yet another alternative is now available, which depends upon new functionality
in SystemParametersInfo. This should be even more general :

   BOOL bSaver;
   if (::SystemParametersInfo (SPI_GETSCREENSAVEACTIVE,0,&bSaver,0))
   {
      if (bSaver)
      {
         ::PostMessage (::GetForegroundWindow(), WM_CLOSE, 0L, 0L);
      }
   }


So you can try that one as well. An embarassment of riches !

//***************************************************************************//

Author>:
Sergey Andyk (Сергей Андык)
(2:5005/58.43)
asvzzz@chat.ru
.

Q>:
[API, NT] Как выполнить shutdown для удалённого компьютера?
A>:
int main(int argc, char **argv)
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
//-------------------
 char *name="";    // address of name of computer to shut down
 char *msg="";     //address of message to display in dialog box
 DWORD time=0;     // time to display dialog box
 bool force=true;  // force applications with unsaved changes flag
 bool reboot=true; //reboot flag
//---------------------------------------------------------------------

    OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&hToken);

    if(!LookupPrivilegeValue(name, SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid)){
    printf ("SE_SHUTDOWN_NAME Privilege облом \n");
    return 1 ;};

    tkp.PrivilegeCount =1;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES)NULL, 0);

    if(!LookupPrivilegeValue(name,
SE_REMOTE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid)){
    printf("SE_REMOTE_SHUTDOWN_NAME Privilege облом \n");
    return 2 ;};

    tkp.PrivilegeCount =1;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES)NULL, 0);

    if (InitiateSystemShutdown(name,msg,time,force,reboot))
    printf("%s shutdown Ok\n",name);
    else printf("Can't shutdown %s \n",name);

 return 0;
}
//***************************************************************************//

Author>:
Sergey Andyk (Сергей Андык)
(2:5005/58.43)
asvzzz@chat.ru
.

Q>:
[API, NT] Как терминировать процесс (в том числе системный)?
A>:
#include <windows.h>
#include <stdio.h>
#pragma hdrstop

// fkill forces a kill -- it will attempt to enable SeDebugPrivilege
// before opening its process handles, allowing it to kill processes
// running under builtin\system (LocalSystem, to the users out there).

int main( int argc, char *argv[] );
void getDebugPriv( void );

#define isBadHandle(h) ( (h) == NULL || (h) == INVALID_HANDLE_VALUE )
#define lenof(x) ( sizeof (x) / sizeof ((x)[0]) )

const int MAXPID = 1024;

int main( int argc, char *argv[] )
{
 int pidCount, i, errors;
 char *p;
 HANDLE hProcess;
 static DWORD pid[MAXPID];

 // parse args, build PID list
 errors = pidCount = 0;

 for ( i = 1; i < argc; i ++ )
 {
  if ( pidCount == lenof( pid ) ) {
   errors ++;
   break;
  }

  pid[pidCount] = strtol( argv[i], &p, 0 );
  if ( p == argv[i] || *p )
   errors ++;
  else
   pidCount ++;
 }

 if ( errors || pidCount == 0 )
 {
  puts( "Usage: fkill pid [...]" );
  puts( "fkill tries to kill the processes specified by the PIDs. If the" );
  puts( "user has debug privileges, fkill is able to kill system processes." );
  puts( "PIDs may be decimal, octal (starts with 0), or hex (starts with 0x)."
);
  return MAXPID + 1;
 }

 // try to acquire SeDebugPrivilege
 getDebugPriv(); //см. faq выше

 errors = 0;
 // for each PID:
 for ( i = 0; i < pidCount; i ++ )
 {
  printf( "pid %lu: ", pid[i] );

  // open process
  hProcess = OpenProcess( PROCESS_TERMINATE, FALSE, pid[i] );
  if ( isBadHandle( hProcess ) )
   printf( "OpenProcess() failed, err = %lu\n", GetLastError() );
  else
  {
   // kill process
   if ( ! TerminateProcess( hProcess, (DWORD) -1 ) )
    printf( "TerminateProcess() failed, err = %lu\n", GetLastError() );
   else
    puts( "killed." );

   // close handle
   CloseHandle( hProcess );
  }
 }

 return 0;
}
//***************************************************************************//

Author>:
Sergey Andyk (Сергей Андык)
(2:5005/58.43)
asvzzz@chat.ru
.

Q>:
[API, NT] Как  включить/выключить аудит?
A>:
#include <windows.h>
#include <stdio.h>
#include <ntsecapi.h>
#pragma hdrstop

// This code was kindly provided by Marc Esipovich, marc@mucom.co.il.
// The original filename was "isauditon.c".
// Modifications by felixk:
//   IsAuditOn() now accepts a BOOL; if FALSE, the code will
//   _not_ force the audit settings to ON.
//   Changed return type to int, as it may return 0, 1, -1.
//   Added a small main() to call IsAuditOn(FALSE).

/*

  RETURNS: 1 if Auditing has been enabled, 0 if no action taken, -1 on error.

  COMMENT: Automatically enables all audit policy events.

  Values are, 0 for no log at all, 1 for success only, 2 for failure only,
  3 for both success and failure.

typedef struct _POLICY_BUFFER {
  DWORD IsAuditEnabled;  // 1 = ON, 0 = OFF.
  PVOID pPolicies;   // pointer to the start policy struct.

  DWORD restart_shutdown_and_system;
  DWORD junk1;
  DWORD logon_and_logoff;
  DWORD junk2;
  DWORD file_and_object_access;
  DWORD junk3;
  DWORD use_of_user_rights;
  DWORD junk4;
  DWORD process_tracking;
  DWORD junk5;
  DWORD security_policy_changes;
  DWORD junk6;
  DWORD user_and_group_management;
  DWORD junk7;
} POLICY_BUFFER, *PPOLICY_BUFFER;
*/

int IsAuditOn( BOOL forceAuditOn )
{
 int rc = 0;
 POLICY_ACCOUNT_DOMAIN_INFO *ppadi = NULL;
 SECURITY_QUALITY_OF_SERVICE sqos;
 LSA_OBJECT_ATTRIBUTES lsaOA;
 LSA_HANDLE polHandle;

 NTSTATUS nts;


 // fill the Quality Of Service struct.
 sqos.Length = sizeof(SECURITY_QUALITY_OF_SERVICE);
 sqos.ImpersonationLevel = SecurityImpersonation;
 sqos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
 sqos.EffectiveOnly = FALSE;

 // fill the Object Attributes struct.
 lsaOA.Length = sizeof(LSA_OBJECT_ATTRIBUTES);
 lsaOA.RootDirectory = NULL;
 lsaOA.ObjectName = NULL;
 lsaOA.Attributes = 0;
 lsaOA.SecurityDescriptor = NULL;
 lsaOA.SecurityQualityOfService = &sqos;

 nts = LsaOpenPolicy(
     NULL, // NULL = current machine.
     &lsaOA,
     POLICY_VIEW_LOCAL_INFORMATION | GENERIC_READ | GENERIC_EXECUTE |
POLICY_ALL_ACCESS,
     &polHandle);
 if (nts != 0) return -1;


 nts = LsaQueryInformationPolicy(
       polHandle,
       PolicyAuditEventsInformation,
       &ppadi);
 if (nts != 0) return -1;

 if ( forceAuditOn )
 {
  // set policies
  ppadi->DomainName.Buffer[0] = 3;  // restart_shutdown_and_system
  ppadi->DomainName.Buffer[2] = 3;  // logon_and_logoff
  ppadi->DomainName.Buffer[4] = 3;  // file_and_object_access
  ppadi->DomainName.Buffer[6] = 3;  // use_of_user_rights
  ppadi->DomainName.Buffer[8]  = 3; // process_tracking
  ppadi->DomainName.Buffer[10] = 3; // security_policy_changes
  ppadi->DomainName.Buffer[12] = 3; // user_and_group_management

  ppadi->DomainName.Length = 1;

  nts = LsaSetInformationPolicy(
        polHandle,
        PolicyAuditEventsInformation,
        ppadi);
  if (nts != 0) return -1;
  rc = 1;
 }

 LsaFreeMemory(polHandle);

  return rc;
}


int main( void )
{
 int rc;

 rc = IsAuditOn( FALSE );

 if ( rc == 1 )
  puts( "Auditing has been enabled." );
 else if ( rc == 0 )
  puts( "The audit state is unchanged." );
 else
  puts( "Oops!" );

 return 0;
}
//****************************************************************************/
/

Author>:
Sergey Andyk (Сергей Андык)
(2:5005/58.43)
asvzzz@chat.ru
.

Q>:
[API, NT] Как взять себе привилегию?
A>:
Например берем привилегию отладки программ:

void getDebugPriv( void )
{
 HANDLE hToken;
 LUID sedebugnameValue;
 TOKEN_PRIVILEGES tkp;

 if ( ! OpenProcessToken( GetCurrentProcess(),
  TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) )
  return;

 if ( !LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &sedebugnameValue ) )
 {
  CloseHandle( hToken );
  return;
 }

 tkp.PrivilegeCount = 1;
 tkp.Privileges[0].Luid = sedebugnameValue;
 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

 AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof tkp, NULL, NULL );

 CloseHandle( hToken );
}

//***************************************************************************//

Author>:
Sergey Andyk (Сергей Андык)
(2:5005/58.43)
asvzzz@chat.ru
.

Q>:
[API, NT] Как дать(забрать)привилегии?
A>:
См.ниже: (c)"Getadmin"

#include <ntsecapi.h>
#include <lmaccess.h>


NTSTATUS
SetPrivilegeOnAccount(
    LSA_HANDLE PolicyHandle,    // open policy handle
    PSID AccountSid,            // SID to grant privilege to
    LPWSTR PrivilegeName,       // privilege to grant (Unicode)
    BOOL bEnable                // enable or disable
    )
{
    LSA_UNICODE_STRING PrivilegeString;

    //
    // Create a LSA_UNICODE_STRING for the privilege name.
    //
    InitLsaString(&PrivilegeString, PrivilegeName);//см.ниже

    //
    // grant or revoke the privilege, accordingly
    //
    if(bEnable) {
        return LsaAddAccountRights(
                PolicyHandle,       // open policy handle
                AccountSid,         // target SID
                &PrivilegeString,   // privileges
                1                   // privilege count
                );
    }
    else {
        return LsaRemoveAccountRights(
                PolicyHandle,       // open policy handle
                AccountSid,         // target SID
                FALSE,              // do not disable all rights
                &PrivilegeString,   // privileges
                1                   // privilege count
                );
    }
}
//***************************************************************************//

Author>:
Sergey Andyk (Сергей Андык)
(2:5005/58.43)
asvzzz@chat.ru
.

Q>:
[API, NT] А как для вышеприведенного фрагмента получить хэндл полиси???
A>:
Getadmin sources...

#include <ntsecapi.h>

Секция 2 из 8 - Предыдущая - Следующая

 Полезные советы по работе с Windows API и Delphi VCL.
Лента новостей


2006 (c) Copyright Hardline.ru