|
Hi,
The Subject explains my prob, i wanna to put my formview in the middle of my screen
I use the SetWindowPos as below:
<br />
CRect Rect;<br />
GetParentFrame()->GetWindowRect(&Rect);<br />
GetParentFrame()->SetWindowPos( NULL,0,0,900 ,200 ,SWP_NOMOVE | SWP_NOZORDER); <br />
SIZE size;<br />
size.cx=Rect.Width()/2;<br />
size.cy=Rect.Height()/2;<br />
SetScaleToFitSize(size); <br />
in other way i wanna change the x, and the y ( i don't matter about the cx & cy) coz they depend on other vars but what ever the cx & cy values are, i wanna havr the form in the center of my screen.
PS: may be i should use some funct like GetWindHeight() or sth else
"The Ultimate Limit Is Only Your Imagination."
|
|
|
|
|
centerwindow()
wqewqqeweqwrwerewrwe
|
|
|
|
|
Like That??
CenterWindow(NULL)
"The Ultimate Limit Is Only Your Imagination."
|
|
|
|
|
I found the sol thx
"The Ultimate Limit Is Only Your Imagination."
|
|
|
|
|
Is it safe to use OnNewWindow2 on multithread ?
For example, one thread's WebBrowser fire NewWindow2 and let another
thread's application take the Dispatch pointer ?
AthreadWebBrowser::OnNewWindow2(LPDISPATCH* ppDisp, BOOL* Cancel)
{
Cancel = FALSE;
HRESULT hr;
CoInitializeEx(NULL,COINIT_MULTITHREADED);
LPSTREAM pStream = NULL;
hr = ::CoMarshalInterThreadInterfaceInStream(IID_IDispatch,*ppDisp,&pStream);
if(hr != S_OK)
{
AfxMessageBox("couldn't get interface");
}
}
but it's failer
wqewqqeweqwrwerewrwe
|
|
|
|
|
when i try to impersonate the process to a different user,the logonUser call fails with error no 1314 (privilage not held by the client ) in windows 2000 series
it was working in xp series of os
Please find sample code below
#define SECURITY_WIN32
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <conio.h>
#include <sspi.h>
#include <lm.h>
#include <lmcons.h>
#include <userenv.h>
#ifndef SEC_I_COMPLETE_NEEDED
#include <issperr.h>
#endif
typedef struct _AUTH_SEQ {
BOOL fInitialized;
BOOL fHaveCredHandle;
BOOL fHaveCtxtHandle;
CredHandle hcred;
struct _SecHandle hctxt;
} AUTH_SEQ, *PAUTH_SEQ;
// Function pointers
ACCEPT_SECURITY_CONTEXT_FN _AcceptSecurityContext = NULL;
ACQUIRE_CREDENTIALS_HANDLE_FN _AcquireCredentialsHandle = NULL;
COMPLETE_AUTH_TOKEN_FN _CompleteAuthToken = NULL;
DELETE_SECURITY_CONTEXT_FN _DeleteSecurityContext = NULL;
FREE_CONTEXT_BUFFER_FN _FreeContextBuffer = NULL;
FREE_CREDENTIALS_HANDLE_FN _FreeCredentialsHandle = NULL;
INITIALIZE_SECURITY_CONTEXT_FN _InitializeSecurityContext = NULL;
QUERY_SECURITY_PACKAGE_INFO_FN _QuerySecurityPackageInfo = NULL;
QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken = NULL;
#define CheckAndLocalFree(ptr) \
if (ptr != NULL) \
{ \
LocalFree(ptr); \
ptr = NULL; \
}
#pragma comment(lib, "netapi32.lib")
LPVOID RetrieveTokenInformationClass(
HANDLE hToken,
TOKEN_INFORMATION_CLASS InfoClass,
LPDWORD lpdwSize)
{
LPVOID pInfo = NULL;
BOOL fSuccess = FALSE;
__try
{
*lpdwSize = 0;
GetTokenInformation(
hToken,
InfoClass,
NULL,
*lpdwSize, lpdwSize);
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
_tprintf(_T("GetTokenInformation failed with %d\n"),
GetLastError());
__leave;
}
pInfo = LocalAlloc(LPTR, *lpdwSize);
if (pInfo == NULL)
{
_tprintf(_T("LocalAlloc failed with %d\n"), GetLastError());
__leave;
}
if (!GetTokenInformation(
hToken,
InfoClass,
pInfo,
*lpdwSize, lpdwSize))
{
_tprintf(_T("GetTokenInformation failed with %d\n"),
GetLastError());
__leave;
}
fSuccess = TRUE;
}
__finally
{
if (fSuccess == FALSE)
{
CheckAndLocalFree(pInfo);
}
}
return pInfo;
}
PSID GetUserSidFromWellKnownRid(DWORD Rid)
{
PUSER_MODALS_INFO_2 umi2;
NET_API_STATUS nas;
UCHAR SubAuthorityCount;
PSID pSid = NULL;
BOOL bSuccess = FALSE; // assume failure
nas = NetUserModalsGet(NULL, 2, (LPBYTE *)&umi2);
if (nas != NERR_Success)
{
printf("NetUserModalsGet failed with error code : [%d]\n",
nas);
SetLastError(nas);
return NULL;
}
SubAuthorityCount = *GetSidSubAuthorityCount
(umi2->usrmod2_domain_id);
//
// Allocate storage for new Sid. account domain Sid + account Rid
//
pSid = (PSID)LocalAlloc(LPTR,
GetSidLengthRequired((UCHAR)(SubAuthorityCount + 1)));
if (pSid != NULL)
{
if (InitializeSid(
pSid,
GetSidIdentifierAuthority(umi2->usrmod2_domain_id),
(BYTE)(SubAuthorityCount+1)
))
{
DWORD SubAuthIndex = 0;
//
// Copy existing subauthorities from account domain Sid into
// new Sid
//
for (; SubAuthIndex < SubAuthorityCount ; SubAuthIndex++)
{
*GetSidSubAuthority(pSid, SubAuthIndex) =
*GetSidSubAuthority(umi2->usrmod2_domain_id,
SubAuthIndex);
}
//
// Append Rid to new Sid
//
*GetSidSubAuthority(pSid, SubAuthorityCount) = Rid;
}
}
NetApiBufferFree(umi2);
return pSid;
}
BOOL IsGuest(HANDLE hToken)
{
BOOL fGuest = FALSE;
PSID pGuestSid = NULL;
PSID pUserSid = NULL;
TOKEN_USER *pUserInfo = NULL;
DWORD dwSize = 0;
pGuestSid = GetUserSidFromWellKnownRid(DOMAIN_USER_RID_GUEST);
if (pGuestSid == NULL)
return fGuest;
//
// Get user information
//
pUserInfo = (TOKEN_USER *)RetrieveTokenInformationClass(hToken,
TokenUser, &dwSize);
if (pUserInfo != NULL)
{
if (EqualSid(pGuestSid, pUserInfo->User.Sid))
fGuest = TRUE;
}
CheckAndLocalFree(pUserInfo);
CheckAndLocalFree(pGuestSid);
return fGuest;
}
///////////////////////////////////////////////////////////////////////////////
void UnloadSecurityDll(HMODULE hModule) {
if (hModule)
FreeLibrary(hModule);
_AcceptSecurityContext = NULL;
_AcquireCredentialsHandle = NULL;
_CompleteAuthToken = NULL;
_DeleteSecurityContext = NULL;
_FreeContextBuffer = NULL;
_FreeCredentialsHandle = NULL;
_InitializeSecurityContext = NULL;
_QuerySecurityPackageInfo = NULL;
_QuerySecurityContextToken = NULL;
}
///////////////////////////////////////////////////////////////////////////////
HMODULE LoadSecurityDll() {
HMODULE hModule;
BOOL fAllFunctionsLoaded = FALSE;
TCHAR lpszDLL[MAX_PATH];
OSVERSIONINFO VerInfo;
//
// Find out which security DLL to use, depending on
// whether we are on Windows NT or Windows 95, Windows 2000, WindowsXP, or Windows Server 2003
// We have to use security.dll on Windows NT 4.0.
// All other operating systems, we have to use Secur32.dll
//
VerInfo.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
if (!GetVersionEx (&VerInfo)) // If this fails, something has gonewrong
{
return FALSE;
}
if (VerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT &&
VerInfo.dwMajorVersion == 4 &&
VerInfo.dwMinorVersion == 0)
{
lstrcpy (lpszDLL, _T("security.dll"));
}
else
{
lstrcpy (lpszDLL, _T("secur32.dll"));
}
hModule = LoadLibrary(lpszDLL);
if (!hModule)
return NULL;
__try {
_AcceptSecurityContext = (ACCEPT_SECURITY_CONTEXT_FN)
GetProcAddress(hModule, "AcceptSecurityContext");
if (!_AcceptSecurityContext)
__leave;
#ifdef UNICODE
_AcquireCredentialsHandle = (ACQUIRE_CREDENTIALS_HANDLE_FN)
GetProcAddress(hModule, "AcquireCredentialsHandleW");
#else
_AcquireCredentialsHandle = (ACQUIRE_CREDENTIALS_HANDLE_FN)
GetProcAddress(hModule, "AcquireCredentialsHandleA");
#endif
if (!_AcquireCredentialsHandle)
__leave;
_CompleteAuthToken = (COMPLETE_AUTH_TOKEN_FN)
GetProcAddress(hModule, "CompleteAuthToken");
_DeleteSecurityContext = (DELETE_SECURITY_CONTEXT_FN)
GetProcAddress(hModule, "DeleteSecurityContext");
if (!_DeleteSecurityContext)
__leave;
_FreeContextBuffer = (FREE_CONTEXT_BUFFER_FN)
GetProcAddress(hModule, "FreeContextBuffer");
if (!_FreeContextBuffer)
__leave;
_FreeCredentialsHandle = (FREE_CREDENTIALS_HANDLE_FN)
GetProcAddress(hModule, "FreeCredentialsHandle");
if (!_FreeCredentialsHandle)
__leave;
#ifdef UNICODE
_InitializeSecurityContext = (INITIALIZE_SECURITY_CONTEXT_FN)
GetProcAddress(hModule, "InitializeSecurityContextW");
#else
_InitializeSecurityContext = (INITIALIZE_SECURITY_CONTEXT_FN)
GetProcAddress(hModule, "InitializeSecurityContextA");
#endif
if (!_InitializeSecurityContext)
__leave;
#ifdef UNICODE
_QuerySecurityPackageInfo = (QUERY_SECURITY_PACKAGE_INFO_FN)
GetProcAddress(hModule, "QuerySecurityPackageInfoW");
#else
_QuerySecurityPackageInfo = (QUERY_SECURITY_PACKAGE_INFO_FN)
GetProcAddress(hModule, "QuerySecurityPackageInfoA");
#endif
if (!_QuerySecurityPackageInfo)
__leave;
_QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
GetProcAddress(hModule, "QuerySecurityContextToken");
if (!_QuerySecurityContextToken)
__leave;
fAllFunctionsLoaded = TRUE;
} __finally {
if (!fAllFunctionsLoaded) {
UnloadSecurityDll(hModule);
hModule = NULL;
}
}
return hModule;
}
///////////////////////////////////////////////////////////////////////////////
BOOL GenClientContext(PAUTH_SEQ pAS, PSEC_WINNT_AUTH_IDENTITY
pAuthIdentity,
PVOID pIn, DWORD cbIn, PVOID pOut, PDWORD pcbOut, PBOOL pfDone) {
/*++
Routine Description:
Optionally takes an input buffer coming from the server and returns
a buffer of information to send back to the server. Also returns
an indication of whether or not the context is complete.
Return Value:
Returns TRUE if successful; otherwise FALSE.
--*/
SECURITY_STATUS ss;
TimeStamp tsExpiry;
SecBufferDesc sbdOut;
SecBuffer sbOut;
SecBufferDesc sbdIn;
SecBuffer sbIn;
ULONG fContextAttr;
if (!pAS->fInitialized) {
ss = _AcquireCredentialsHandle(NULL, _T("NTLM"),
SECPKG_CRED_OUTBOUND, NULL, pAuthIdentity, NULL, NULL,
&pAS->hcred, &tsExpiry);
if (ss < 0) {
fprintf(stderr, "AcquireCredentialsHandle failed with %08X\n",
ss);
return FALSE;
}
pAS->fHaveCredHandle = TRUE;
}
// Prepare output buffer
sbdOut.ulVersion = 0;
sbdOut.cBuffers = 1;
sbdOut.pBuffers = &sbOut;
sbOut.cbBuffer = *pcbOut;
sbOut.BufferType = SECBUFFER_TOKEN;
sbOut.pvBuffer = pOut;
// Prepare input buffer
if (pAS->fInitialized) {
sbdIn.ulVersion = 0;
sbdIn.cBuffers = 1;
sbdIn.pBuffers = &sbIn;
sbIn.cbBuffer = cbIn;
sbIn.BufferType = SECBUFFER_TOKEN;
sbIn.pvBuffer = pIn;
}
ss = _InitializeSecurityContext(&pAS->hcred,
pAS->fInitialized ? &pAS->hctxt : NULL, NULL, 0, 0,
SECURITY_NATIVE_DREP, pAS->fInitialized ? &sbdIn : NULL,
0, &pAS->hctxt, &sbdOut, &fContextAttr, &tsExpiry);
if (ss < 0) {
// <winerror.h>
fprintf(stderr, "InitializeSecurityContext failed with %08X\n",
ss);
return FALSE;
}
pAS->fHaveCtxtHandle = TRUE;
// If necessary, complete token
if (ss == SEC_I_COMPLETE_NEEDED || ss ==
SEC_I_COMPLETE_AND_CONTINUE) {
if (_CompleteAuthToken) {
ss = _CompleteAuthToken(&pAS->hctxt, &sbdOut);
if (ss < 0) {
fprintf(stderr, "CompleteAuthToken failed with %08X\n",
ss);
return FALSE;
}
}
else {
fprintf (stderr, "CompleteAuthToken not supported.\n");
return FALSE;
}
}
*pcbOut = sbOut.cbBuffer;
if (!pAS->fInitialized)
pAS->fInitialized = TRUE;
*pfDone = !(ss == SEC_I_CONTINUE_NEEDED
|| ss == SEC_I_COMPLETE_AND_CONTINUE );
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
BOOL GenServerContext(PAUTH_SEQ pAS, PVOID pIn, DWORD cbIn, PVOID pOut,
PDWORD pcbOut, PBOOL pfDone) {
/*++
Routine Description:
Takes an input buffer coming from the client and returns a buffer
to be sent to the client. Also returns an indication of whether or
not the context is complete.
Return Value:
Returns TRUE if successful; otherwise FALSE.
--*/
SECURITY_STATUS ss;
TimeStamp tsExpiry;
SecBufferDesc sbdOut;
SecBuffer sbOut;
SecBufferDesc sbdIn;
SecBuffer sbIn;
ULONG fContextAttr;
if (!pAS->fInitialized) {
ss = _AcquireCredentialsHandle(NULL, _T("NTLM"),
SECPKG_CRED_INBOUND, NULL, NULL, NULL, NULL, &pAS->hcred,
&tsExpiry);
if (ss < 0) {
fprintf(stderr, "AcquireCredentialsHandle failed with %08X\n",
ss);
return FALSE;
}
pAS->fHaveCredHandle = TRUE;
}
// Prepare output buffer
sbdOut.ulVersion = 0;
sbdOut.cBuffers = 1;
sbdOut.pBuffers = &sbOut;
sbOut.cbBuffer = *pcbOut;
sbOut.BufferType = SECBUFFER_TOKEN;
sbOut.pvBuffer = pOut;
// Prepare input buffer
sbdIn.ulVersion = 0;
sbdIn.cBuffers = 1;
sbdIn.pBuffers = &sbIn;
sbIn.cbBuffer = cbIn;
sbIn.BufferType = SECBUFFER_TOKEN;
sbIn.pvBuffer = pIn;
ss = _AcceptSecurityContext(&pAS->hcred,
pAS->fInitialized ? &pAS->hctxt : NULL, &sbdIn, 0,
SECURITY_NATIVE_DREP, &pAS->hctxt, &sbdOut, &fContextAttr,
&tsExpiry);
if (ss < 0) {
fprintf(stderr, "AcceptSecurityContext failed with %08X\n", ss);
return FALSE;
}
pAS->fHaveCtxtHandle = TRUE;
// If necessary, complete token
if (ss == SEC_I_COMPLETE_NEEDED || ss ==
SEC_I_COMPLETE_AND_CONTINUE) {
if (_CompleteAuthToken) {
ss = _CompleteAuthToken(&pAS->hctxt, &sbdOut);
if (ss < 0) {
fprintf(stderr, "CompleteAuthToken failed with %08X\n",
ss);
return FALSE;
}
}
else {
fprintf (stderr, "CompleteAuthToken not supported.\n");
return FALSE;
}
}
*pcbOut = sbOut.cbBuffer;
if (!pAS->fInitialized)
pAS->fInitialized = TRUE;
*pfDone = !(ss == SEC_I_CONTINUE_NEEDED
|| ss == SEC_I_COMPLETE_AND_CONTINUE);
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
BOOL WINAPI SSPLogonUser(LPTSTR szDomain, LPTSTR szUser, LPTSTR
szPassword)
{
AUTH_SEQ asServer = {0};
AUTH_SEQ asClient = {0};
BOOL fDone = FALSE;
BOOL fResult = FALSE;
DWORD cbOut = 0;
DWORD cbIn = 0;
DWORD cbMaxToken = 0;
PVOID pClientBuf = NULL;
PVOID pServerBuf = NULL;
PSecPkgInfo pSPI = NULL;
HMODULE hModule = NULL;
SEC_WINNT_AUTH_IDENTITY ai;
__try {
hModule = LoadSecurityDll();
if (!hModule)
__leave;
// Get max token size
_QuerySecurityPackageInfo(_T("NTLM"), &pSPI);
cbMaxToken = pSPI->cbMaxToken;
_FreeContextBuffer(pSPI);
// Allocate buffers for client and server messages
pClientBuf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
cbMaxToken);
pServerBuf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
cbMaxToken);
// Initialize auth identity structure
ZeroMemory(&ai, sizeof(ai));
#if defined(UNICODE) || defined(_UNICODE)
ai.Domain = szDomain;
ai.DomainLength = lstrlen(szDomain);
ai.User = szUser;
ai.UserLength = lstrlen(szUser);
ai.Password = szPassword;
ai.PasswordLength = lstrlen(szPassword);
ai.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
#else
ai.Domain = (unsigned char *)szDomain;
ai.DomainLength = lstrlen(szDomain);
ai.User = (unsigned char *)szUser;
ai.UserLength = lstrlen(szUser);
ai.Password = (unsigned char *)szPassword;
ai.PasswordLength = lstrlen(szPassword);
ai.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
#endif
// Prepare client message (negotiate) .
cbOut = cbMaxToken;
if (!GenClientContext(&asClient, &ai, NULL, 0, pClientBuf,
&cbOut,
&fDone))
__leave;
// Prepare server message (challenge) .
cbIn = cbOut;
cbOut = cbMaxToken;
if (!GenServerContext(&asServer, pClientBuf, cbIn, pServerBuf,
&cbOut, &fDone))
__leave;
// Most likely failure: AcceptServerContext fails withSEC_E_LOGON_DENIED
// in the case of bad szUser or szPassword.
// Unexpected Result: Logon will succeed if you pass in a badszUser and
// the guest account is enabled in the specified domain.
// Prepare client message (authenticate) .
cbIn = cbOut;
cbOut = cbMaxToken;
if (!GenClientContext(&asClient, &ai, pServerBuf, cbIn,
pClientBuf,
&cbOut,
&fDone))
__leave;
// Prepare server message (authentication) .
cbIn = cbOut;
cbOut = cbMaxToken;
if (!GenServerContext(&asServer, pClientBuf, cbIn, pServerBuf,
&cbOut,
&fDone))
__leave;
fResult = TRUE;
{
HANDLE hToken = NULL;
if (_QuerySecurityContextToken(&asServer.hctxt, &hToken) == 0)
{
if (IsGuest(hToken))
{
printf("Logged in as Guest\n");
fResult = FALSE;
}
else
printf("Logged in as the desired user\n");
CloseHandle(hToken);
}
}
} __finally {
// Clean up resources
if (asClient.fHaveCtxtHandle)
_DeleteSecurityContext(&asClient.hctxt);
if (asClient.fHaveCredHandle)
_FreeCredentialsHandle(&asClient.hcred);
if (asServer.fHaveCtxtHandle)
_DeleteSecurityContext(&asServer.hctxt);
if (asServer.fHaveCredHandle)
_FreeCredentialsHandle(&asServer.hcred);
if (hModule)
UnloadSecurityDll(hModule);
HeapFree(GetProcessHeap(), 0, pClientBuf);
HeapFree(GetProcessHeap(), 0, pServerBuf);
}
return fResult;
}
//--------------------------------------------------------------------
// The GetConsoleInput function gets an array of characters from the
// keyboard, while printing only asterisks to the screen.
void GetConsoleInput(TCHAR* strInput, int intMaxChars)
{
char ch;
char minChar = ' ';
minChar++;
ch = getch();
while (ch != '\r')
{
if (ch == '\b' && strlen(strInput) > 0)
{
strInput[strlen(strInput)-1] = '\0';
printf("\b \b");
}
else if (ch >= minChar && (int)strlen(strInput) <
intMaxChars)
{
strInput[strlen(strInput)+1] = '\0';
strInput[strlen(strInput)] = ch;
putch('*');
}
ch = getch();
}
putch('\n');
}
#define GENERIC_ACCESS (GENERIC_READ | GENERIC_WRITE | \
GENERIC_EXECUTE | GENERIC_ALL)
BOOL GetLogonSID (HANDLE hToken, PSID *ppsid)
{
BOOL bSuccess = FALSE;
DWORD dwIndex;
DWORD dwLength = 0;
PTOKEN_GROUPS ptg = NULL;
// Verify the parameter passed in is not NULL.
if (NULL == ppsid)
goto Cleanup;
// Get required buffer size and allocate the TOKEN_GROUPS buffer.
if (!GetTokenInformation(
hToken, // handle to the access token
TokenGroups, // get information about the token's groups
(LPVOID) ptg, // pointer to TOKEN_GROUPS buffer
0, // size of buffer
&dwLength // receives required buffer size
))
{
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
goto Cleanup;
ptg = (PTOKEN_GROUPS)HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, dwLength);
if (ptg == NULL)
goto Cleanup;
}
// Get the token group information from the access token.
if (!GetTokenInformation(
hToken, // handle to the access token
TokenGroups, // get information about the token's groups
(LPVOID) ptg, // pointer to TOKEN_GROUPS buffer
dwLength, // size of buffer
&dwLength // receives required buffer size
))
{
goto Cleanup;
}
// Loop through the groups to find the logon SID.
for (dwIndex = 0; dwIndex < ptg->GroupCount; dwIndex++)
if ((ptg->Groups[dwIndex].Attributes & SE_GROUP_LOGON_ID)
== SE_GROUP_LOGON_ID)
{
// Found the logon SID; make a copy of it.
dwLength = GetLengthSid(ptg->Groups[dwIndex].Sid);
*ppsid = (PSID) HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, dwLength);
if (*ppsid == NULL)
goto Cleanup;
if (!CopySid(dwLength, *ppsid, ptg->Groups[dwIndex].Sid))
{
HeapFree(GetProcessHeap(), 0, (LPVOID)*ppsid);
goto Cleanup;
}
break;
}
bSuccess = TRUE;
Cleanup:
// Free the buffer for the token groups.
if (ptg != NULL)
HeapFree(GetProcessHeap(), 0, (LPVOID)ptg);
return bSuccess;
}
VOID FreeLogonSID (PSID *ppsid)
{
HeapFree(GetProcessHeap(), 0, (LPVOID)*ppsid);
}
BOOL StartInteractiveClientProcess (
LPTSTR lpszUsername, // client to log on
LPTSTR lpszDomain, // domain of client's account
LPTSTR lpszPassword, // client's password
LPTSTR lpCommandLine // command line to execute
)
{
HANDLE hToken;
HDESK hdesk = NULL;
HWINSTA hwinsta = NULL, hwinstaSave = NULL;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sa;
PSID pSid = NULL;
STARTUPINFO si;
BOOL bResult = FALSE;
PHANDLE pH = 0;
TOKEN_PRIVILEGES tp;
LUID luid;
tp.PrivilegeCount =1;
LookupPrivilegeValue(NULL,"SeIncreaseQuotaPrivilage",&luid);
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Log the client on to the local computer.
if (!LogonUser(
lpszUsername,
lpszDomain,
lpszPassword,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
&hToken) )
{
int i = GetLastError();
printf("The error caught is [%d]",i);
goto Cleanup;
}
if (! ImpersonateLoggedOnUser(hToken) )
goto Cleanup;
// Initialize the STARTUPINFO structure.
// Specify that the process runs in the interactive desktop.
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb= sizeof(STARTUPINFO);
if(DuplicateTokenEx(hToken,MAXIMUM_ALLOWED,NULL,SecurityDelegation,TokenPrimary,pH)){}
bResult = CreateProcessAsUser(
pH, // client's access token
lpCommandLine, // file to execute
NULL, // command line
NULL, // pointer to process SECURITY_ATTRIBUTES
NULL, // pointer to thread SECURITY_ATTRIBUTES
FALSE, // handles are not inheritable
NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, // creation flags
NULL, // pointer to new environment block
NULL, // name of current directory
&si, // pointer to STARTUPINFO structure
&pi // receives information about new process
);
if (0 ==bResult)
bResult = GetLastError();
// End impersonation of client.
RevertToSelf();
if (bResult && pi.hProcess != INVALID_HANDLE_VALUE)
{
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
}
if (pi.hThread != INVALID_HANDLE_VALUE)
CloseHandle(pi.hThread);
Cleanup:
if (hwinstaSave != NULL)
SetProcessWindowStation (hwinstaSave);
// Free the buffer for the logon SID.
if (pSid)
FreeLogonSID(&pSid);
// Close the handles to the interactive window station and desktop.
if (hwinsta)
CloseWindowStation(hwinsta);
if (hdesk)
CloseDesktop(hdesk);
// Close the handle to the client's access token.
/*
if (hToken != INVALID_HANDLE_VALUE)
CloseHandle(hToken);
*/
return bResult;
}
void _tmain(int argc, TCHAR **argv)
{
TCHAR password[PWLEN+1];
if (argc != 3)
{
_tprintf(_T("Usage: %s DomainName UserName\n"), argv[0]);
return;
}
_tprintf(_T("Enter password for the specified user : "));
password[0] = 0;
GetConsoleInput(password, PWLEN);
_tprintf(_T("\n"));
// argv[1] - Domain Name
// argv[2] - User Name
if (SSPLogonUser(argv[1], argv[2], password))
{
_tprintf(_T("User Credentials are valid\n"));
}
else
_tprintf(_T("User Credentials are NOT valid\n"));
_tprintf(_T("Entering to start the application \n"));
if(StartInteractiveClientProcess(argv[2],argv[1],password,"c:\\Windows\\System32\\notepad.exe"))
_tprintf(_T("Entered\n"));
}
i add the user right "act as part of the os " in the local configuration but nothing going well ...
Please help me ....
vineesh
|
|
|
|
|
vineeshV wrote: Please help me ....
Why not help us by removing 99% of your code from this post? Do you honestly think anyone would spend their valuable time reading through all of this?
"Love people and use things, not love things and use people." - Unknown
"To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne
|
|
|
|
|
Hello everyone,
Some people doubt that the design below is inferior compared to design which makes f, either Foo* or Foo&. The reason is below design will waste memory space and degrade performance by creating a new instance.
I think it depends. If we really needs to wrap a new instance, I think the following design is fine. If we needs to refers to an existing instance, this design is inferior because it will waste memory space and degrade performance by creating a new instance and destroy the original one.
class Foo;
class Goo
{
Foo f;
}
thanks in advance,
George
|
|
|
|
|
You are missing an important point here. Everything is not related to performances only. In this case, it will make a huge difference if you are using a new class instance instead of a reference or a pointer to an existing instance: this will be a copy of the original object, which means that all the modifications you do on this copy won't affect the original object (which is the case when you use a reference or a pointer).
You have to think about that before taking into account performances issues, because it has a major impact on the design of your program.
|
|
|
|
|
Thanks Cedric,
You mean none of the 3 designs are always good or bad, it depends on requirement, right?
regards,
George
|
|
|
|
|
|
Thanks Cedric,
regards,
George
|
|
|
|
|
George_George wrote: If we really needs to wrap a new instance, I think the following design is fine
Indeed:
- You cannot wrap a new istance by means of reference.
- Dynamically allocation of new instance is usually a bad idea (you may forget cleanup).
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
-- Iain Clarke
|
|
|
|
|
Thanks CPallini,
CPallini wrote: You cannot wrap a new istance by means of reference.
What means "wrap a new istance by means of reference"? Could you give more description or show some pseudo code please?
regards,
George
|
|
|
|
|
It's simple: reference variable must alway be assigned. Hence you need to pass an object to the class,
that is, you're making a reference to an existing object.
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
-- Iain Clarke
|
|
|
|
|
Thanks for clarification for this.
regards,
George
|
|
|
|
|
We have historically had so much trouble with 'lost' pointers, that we embed 'cookies' to our other objects within others, instead of the pointers themselves. If you have a pointer to an object, it is hard to tell if the object is still around, unless you have the address of a smart pointer that won't let object delete until all references to the object are gone. If you use cookies, you can ask a lookup table to translate cookie for you, and if that is gone, then object is gone too.
|
|
|
|
|
Thanks Blake,
I am interested to learn what do you mean embed 'cookies'. Do you show some pesudo code or refer some links please?
regards,
George
|
|
|
|
|
Suppose I have a list of instances of objects of type "Class A".
Now I want to refer to those Class A objects by specific instance from another class, let's say Class B.
Traditionally, you would have placed a pointer or some reference to the Class A instance within Class B:
class B<br />
{<br />
...<br />
class A* m_pA;<br />
...<br />
};
But instead, if you give every instance of class A a 'cookie', such as a unique 32-bit DWORD value:
class A{<br />
...<br />
DWORD m_Cookie;<br />
...<br />
};
And then you palce all the instances of Class A into a map, mapping the cookie to the pointer to Class A (So now the pointer to class A is in exactly one place).
Then when you need class B to refer to a specific instance of Class A, instead of using the pointer to Class A, you store its cookie value:
class B
{
...
DWORD m_CookieToA;
...
};
Then when you need to get to a Class A instance from a member function of Class B, you can use the map to look for the cookie for the related Class A. If the map gives you back a value, then you get back a good pointer to class A, and if not, then there is no Class A with that cookie in existence.
If the lifetime of Class A objects will outlive Class B objects, this is fine either way - pointer or cookie.
Otherwise, you might want to provide some synchronization on the map (unless your program is single threaded) so things are not removed from the Class A map while a Class B member function retains or is using a pointer to a Class A object. Otherwise, you are free to delete Class A objects at will, without trying to patch up your Class B objects which might have stored pointers to the Class A instances.
So, you can ask yourself, if it is more important not to crash or to have performance, as the other member mentioned. This technique is not as 'quick' as storing the pointer to Class A within Class B, as far as the quickest reference to Class A from within a Class B member function (you have to look up the cookie in the map each time to fetch the temporary pointer to Class A).
If you wanted to get fancy, you could use a multimap for Class A, and map Class A address, Class A cookie, and the number of references to class A in the map. The reference count would be udpated each time you assigned a cookie to an A to a B. That way, you would know, as yuo were about to delete a Class A instance, if there were any outstanding Class B referring to it.
|
|
|
|
|
Cool, Blake!
Your answer is clear.
regards,
George
|
|
|
|
|
Hello everyone,
Two questions about re-entrancy issue,
http://www.codeproject.com/KB/COM/sta_issues.aspx
1. What is the setback of the issue? I think it is still thread-safe since only one STA owning thread will execute on STA component;
2. How to avoid it in design?
thanks in advance,
George
|
|
|
|
|
Hi all,
i m create a property sheet and show property pages in this property sheet.
When i run the application the Property Sheet Show Three Buttons "OK","CANCEL",and "APPLY" at the bottom .and the apply button is Disabled.
How can Remove all these buttons from Property Sheet.
this is my Code::
class CMyPropertySheet : public CPropertySheet
{
DECLARE_DYNAMIC(CMyPropertySheet)
public:
CMyPropertySheet(LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0);
virtual ~CMyPropertySheet();
static int CALLBACK XmnPropSheetCallback(HWND hWnd, UINT message, LPARAM lParam);
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
HICON m_hIcon;
CPropertyPage1 m_Page1;
CPropertyPage2 m_Page2;
CPropertyPage3 m_Page3;
CPropertyPage4 m_Page4;
CPropertyPage5 m_Page5;
protected:
BOOL m_bNeedInit;
CRect m_rCrt;
int m_nMinCX;
int m_nMinCY;
public:
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnGetMinMaxInfo(MINMAXINFO* lpMMI);
virtual INT_PTR DoModal();
//////////////////////////////////////////////////////////////////////
CMyPropertySheet::CMyPropertySheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage)
:CPropertySheet(pszCaption, pParentWnd, iSelectPage)
, m_bNeedInit(TRUE)
, m_nMinCX(0)
, m_nMinCY(0)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
AddPage(&m_Page1);
AddPage(&m_Page2);
AddPage(&m_Page3);
AddPage(&m_Page4);
AddPage(&m_Page5);
}
CMyPropertySheet::~CMyPropertySheet()
{
}
BEGIN_MESSAGE_MAP(CMyPropertySheet, CPropertySheet)
ON_WM_SIZE()
ON_WM_GETMINMAXINFO()
ON_WM_CLOSE()
END_MESSAGE_MAP()
// CMyPropertySheet message handlers
BOOL CMyPropertySheet::OnInitDialog()
{
this->SetIcon(m_hIcon,TRUE);
BOOL bResult = CPropertySheet::OnInitDialog();
// Adjust property sheet size to account for the new menu.
CRect r; GetWindowRect(&r);
r.bottom += GetSystemMetrics(SM_CYMENU);
MoveWindow(r);
// ...
// Init m_nMinCX/Y
m_nMinCX = r.Width();
m_nMinCY = r.Height();
// After this point, the resize code runs.
m_bNeedInit = FALSE;
GetClientRect(&m_rCrt);
return bResult;
}
// This function must be a STATIC method.
// Callback to allow you to set the default window styles
// for the property sheet.
int CALLBACK CMyPropertySheet::XmnPropSheetCallback(HWND hWnd, UINT message, LPARAM lParam)
{
extern int CALLBACK AfxPropSheetCallback(HWND, UINT message, LPARAM lParam);
// XMN: Call MFC's callback.
int nRes = AfxPropSheetCallback(hWnd, message, lParam);
switch (message)
{
case PSCB_PRECREATE:
// Set your own window styles.
((LPDLGTEMPLATE)lParam)->style |= (DS_3DLOOK | DS_SETFONT
| WS_OVERLAPPEDWINDOW | WS_POPUP | WS_VISIBLE | WS_CAPTION);
break;
}
return nRes;
}
void CMyPropertySheet::OnSize(UINT nType, int cx, int cy)
{
CPropertySheet::OnSize(nType, cx, cy);
CRect r1;
if (m_bNeedInit)
return;
CTabCtrl *pTab = GetTabControl();
ASSERT(NULL != pTab && IsWindow(pTab->m_hWnd));
int dx = cx - m_rCrt.Width();
int dy = cy - m_rCrt.Height();
GetClientRect(&m_rCrt);
HDWP hDWP = ::BeginDeferWindowPos(5);
pTab->GetClientRect(&r1);
r1.right += dx; r1.bottom += dy;
::DeferWindowPos(hDWP, pTab->m_hWnd, NULL,
0, 0, r1.Width(), r1.Height(),
SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOZORDER);
// Move all of the buttons with the lower and right sides.
for (CWnd *pChild = GetWindow(GW_CHILD);
pChild != NULL;
pChild = pChild->GetWindow(GW_HWNDNEXT))
{
if (pChild->SendMessage(WM_GETDLGCODE) & DLGC_BUTTON)
{
pChild->GetWindowRect(&r1); ScreenToClient(&r1);
r1.top += dy; r1.bottom += dy; r1.left+= dx; r1.right += dx;
::DeferWindowPos(hDWP, pChild->m_hWnd, NULL,
r1.left, r1.top, 0, 0,
SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOZORDER);
}
// Resize everything else.
else
{
pChild->GetClientRect(&r1);
r1.right += dx; r1.bottom += dy;
::DeferWindowPos(hDWP, pChild->m_hWnd, NULL, 0, 0,
r1.Width(), r1.Height(),
SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOZORDER);
}
}
::EndDeferWindowPos(hDWP);
}
void CMyPropertySheet::OnGetMinMaxInfo(MINMAXINFO* lpMMI)
{
lpMMI->ptMinTrackSize.x = m_nMinCX;
lpMMI->ptMinTrackSize.y = m_nMinCY;
CPropertySheet::OnGetMinMaxInfo(lpMMI);
}
INT_PTR CMyPropertySheet::DoModal()
{
// Hook into property sheet creation code
m_psh.dwFlags |= PSH_USECALLBACK;
m_psh.pfnCallback = XmnPropSheetCallback;
return CPropertySheet::DoModal();
}
Thanks in advance.
|
|
|
|
|
Get window handles of each of the buttons and hide and disable the buttons. Make sure the focus is not on them when doing so. Also, if you have other buttons, you might want to make one of them the defualt button.
|
|
|
|
|
hi all,
i want to create a dialog box same like as we click on Start button of Windows Explorer.
i want to set a focus on one button like (Start Button) at bottom,
from that button i want to call a dialog box on which my child window controls are present.
i am using a dialog box for that bottom button, after click on that button i want to set focus on the another dialog box
plz help me out from dis..
Pankaj
|
|
|
|
|
I think I saw an article I think it was nearly your answer but I dont know I saw it on the codeproject or other place.
|
|
|
|
|