'text/window general'에 해당되는 글 32건
- 2025.01.10 How to change the parent process when calling CreateProcess API
- 2024.04.09 How to open Control Panel Items in the separate explorer.exe
- 2022.01.20 How to list installed programs using IShellAppManager
- 2019.03.15 URLDownloadToFile with IBindStatusCallback and IHTTPSecurity 1
- 2014.03.04 Run program with Restricted Privilege
- 2014.01.09 Get Logon Session (AuthenticationId)
- 2013.07.24 Convert File Format Using OLE API
- 2012.08.01 dynamic create activeX (javascript)
- 2012.08.01 ATL with IE(HTML)
- 2010.10.27 Problem of Textout function with zoom
How to change the parent process when calling CreateProcess API
Usually, the parent process is the process that creats the new process. But you can change this behavior by setting STARTUPINFOEX.lpAttributeList.
HANDLE hParentProcess{ nullptr };
LPPROC_THREAD_ATTRIBUTE_LIST attrList{ nullptr };
// Initialize LPPROC_THREAD_ATTRIBUTE_LIST
hParentProcess = OpenProcess(PROCESS_CREATE_PROCESS, FALSE, parentProcessId);
SIZE_T attrListSize = 0;
InitializeProcThreadAttributeList(nullptr, 1, 0, &attrListSize);
attrList = (LPPROC_THREAD_ATTRIBUTE_LIST)malloc(attrListSize);
InitializeProcThreadAttributeList(attrList, 1, 0, &attrListSize);
UpdateProcThreadAttribute(attrList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &hParentProcess,
sizeof(hParentProcess), nullptr, nullptr);
// Set LPPROC_THREAD_ATTRIBUTE_LIST to the STARTUPINFOEX
STARTUPINFOEX si = { sizeof(si) };
si.StartupInfo.cb = sizeof(si);
si.lpAttributeList = attrList;
PROCESS_INFORMATION pi = { 0 };
CreateProcess(nullptr, argv[1], nullptr, nullptr, FALSE, EXTENDED_STARTUPINFO_PRESENT, nullptr, nullptr, &si.StartupInfo, &pi);
How to open Control Panel Items in the separate explorer.exe
If you want to open 'This PC\All Control Panel Items\Programs and Features'
First you need to convert each items to GUID
- This PC -> 20d04fe0-3aea-1069-a2d8-08002b30309d
- All Control Panel Items -> 21ec2020-3aea-1069-a2dd-08002b30309d
- Programs and Features -> 7b81be6a-ce2b-4676-a29e-eb907a5126c5
Then launch exporer.exe with /separate paramter
For example:
C:\Windows\explorer.exe /separate, ::{20d04fe0-3aea-1069-a2d8-08002b30309d}\::{21ec2020-3aea-1069-a2dd-08002b30309d}\::{7b81be6a-ce2b-4676-a29e-eb907a5126c5}
Then the above process will be terminated and the below process shows up with ' Programs and Features'
C:\WINDOWS\explorer.exe /factory,{75dff2b7-6936-4c06-a8bb-676a7b00b24b} -Embedding
If you want to launch explorer.exe as your descendant process, there is a way
- Run: C:\WINDOWS\explorer.exe /factory,{75dff2b7-6936-4c06-a8bb-676a7b00b24b} -Embedding
- This process is your descendant process and it is invisible.
- Run: C:\Windows\explorer.exe /separate, ::{20d04fe0-3aea-1069-a2d8-08002b30309d}\::{21ec2020-3aea-1069-a2dd-08002b30309d}\::{7b81be6a-ce2b-4676-a29e-eb907a5126c5}
- This process will be terminated and 'Programs and Features' will be showed in the previous explorer.exe.
- But if there is one more explorer.exe /factory, there is no gurantee which one shows 'Programs and Features'.
How to list installed programs using IShellAppManager
// appwiz.cpl is COM server related to (UnInstall or Change a program)
#include <shappmgr.h>
#include <iostream>
#import <appwiz.cpl>
// If this import gets into trobule, you could solve the problem by using #import directives
/*
#import <appwiz.cpl> rename("tag_inner_PROPVARIANT", "_tag_inner_PROPVARIANT") \
inject_statement("typedef struct _LARGE_INTEGER2 { LONGLONG QuadPart; } LARGE_INTEGER2;") \
inject_statement("typedef struct _ULARGE_INTEGER2 { ULONGLONG QuadPart;} ULARGE_INTEGER2;") \
rename("_LARGE_INTEGER", " _LARGE_INTEGER2") \
rename("_ULARGE_INTEGER", "_ULARGE_INTEGER2")
*/
int main()
{
::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
class __declspec(uuid("{352EC2B7-8B9A-11D1-B8AE-006008059382}")) AppWiz;
static const CLSID CLSID_AppWiz = __uuidof(AppWiz);
SHAPPMGRPLib::IShellAppManagerPtr spShellAppManaager;
HRESULT hr = spShellAppManaager.CreateInstance(CLSID_AppWiz, NULL, CLSCTX_INPROC_SERVER);
SHAPPMGRPLib::IEnumInstalledAppsPtr spEnumInstalledApps;
hr = spShellAppManaager->EnumInstalledApps(&spEnumInstalledApps);
SHAPPMGRPLib::IInstalledAppPtr spInstalledApp;
SHAPPMGRPLib::IInstalledApp* pInstalledApp;
while (S_OK == (hr = spEnumInstalledApps->Next(&pInstalledApp))) {
spInstalledApp = pInstalledApp;
SHAPPMGRPLib::_AppInfoData data = { 0 };
data.cbSize = sizeof(SHAPPMGRPLib::_AppInfoData);
data.dwMask = AIM_DISPLAYNAME | AIM_VERSION | AIM_PUBLISHER | AIM_INSTALLDATE;
hr = spInstalledApp->GetAppInfo(&data);
// You have to check the validation of the data before using it.
std::wcout << "Name: " << data.pszDisplayName << " ver: " << data.pszVersion
<< " publisher: " << data.pszPublisher << " installedOn: " << data.pszInstallDate << std::endl;
}
::CoUninitialize();
return 0;
}
URLDownloadToFile with IBindStatusCallback and IHTTPSecurity
The last parameter of URLDownloadToFile and URLDownloadToCacheFile API is the pointer of IBindStatusCallback.
This paramter is optional, so you can just set NULL; however, in my experience, you have to implement IBindStatusCallback in many cases.
class CBindStatusCallback : public IBindStatusCallback , public IHttpSecurity ///// IUnknown methods STDMETHOD_(ULONG,Release)() STDMETHOD(QueryInterface)(
|
- Implement IUnknown interface
- AddRef, Relase Method
- You can implement this function according to official rule, but there is trick.
- You can make this object local variable, then you don't need to worry about it's lifetime.
- return non-zero value: it means this object will not be destroyed.
- QueryInterface Method
- Implement IBindStatusCallback interface
- You don't need to implement every method; you can actually write 'return E_NOTIMPL' in almost cases.
- GetBindInfo method has crucial role.
- You can set a code page.
- If there is non English character in URL, it can be an issue depending on the OS language setting.
- Also, You can set several options.
- Implement IHttpSecurity interface
- You can download files even though the sever has some security problems such as a self-signed certificate.
HRESULT CBindStatusCallback::QueryInterface( if( IID_IUnknown == riid ) reinterpret_cast<IUnknown*>(*ppvObject)->AddRef(); } |
HRESULT CBindStatusCallback::GetBindInfo( *grfBINDF = BINDF_ASYNCHRONOUS; DWORD cbSize = pbindinfo->cbSize; return S_OK; } |
///// IWindowForBindingUI
|
Run program with Restricted Privilege
1. Using PsExec
http://technet.microsoft.com/ko-kr/sysinternals/bb897553.aspx
PsExec -d
2. using CreateRestrictedToken, CreateProcessAsUser
HANDLE hProcessToken = NULL;
::OpenProcessToken( GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_ADJUST_SESSIONID | TOKEN_READ | TOKEN_WRITE, &hProcessToken ); HANDLE hRestrictedToken = NULL; ::CreateRestrictedToken(hProcessToken, DISABLE_MAX_PRIVILEGE, 0, 0, 0, 0, 0, 0, &hRestrictedToken ); //Create startup info STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; si.lpDesktop = L"winsta0\\default"; si.cb = sizeof( si ); // Get the current executables name TCHAR exePath[MAX_PATH+1] = {0}; GetModuleFileName(NULL, exePath, MAX_PATH); // Start the new (non-elevated) restricted process
if( !CreateProcessAsUser(hRestrictedToken, L"c:\\windows\\notepad.exe", NULL, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi)) { CloseHandle(hRestrictedToken); return; } |
3 using SaferCreateLevel CreateProcessAsUser
|
SAFER_LEVEL_HANDLE hLevel = NULL;
if (!SaferCreateLevel(SAFER_SCOPEID_MACHINE, SAFER_LEVELID_NORMALUSER, SAFER_LEVEL_OPEN, &hLevel, NULL)) { return false; } HANDLE hRestrictedToken = NULL; if (!SaferComputeTokenFromLevel(hLevel, NULL, &hRestrictedToken, 0, NULL)) { SaferCloseLevel(hLevel); return false; } SaferCloseLevel(hLevel); //Create startup info STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; si.lpDesktop = L"winsta0\\default"; si.cb = sizeof( si ); // Get the current executables name TCHAR exePath[MAX_PATH+1] = {0}; GetModuleFileName(NULL, exePath, MAX_PATH); // Start the new (non-elevated) restricted process if( !CreateProcessAsUser(hRestrictedToken, exePath, NULL, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi)) { CloseHandle(hRestrictedToken); return false; } CloseHandle(hRestrictedToken); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return true; |
Get Logon Session (AuthenticationId)
Process Explorer를 보면 Logon Session 이란 항목이 존재한다.
하나의 Session 내의 다수의 Logon 계정이 동시 존재할 수 있으며, 그 때마다 다른 Logon Session을 부여 받는다.
RunAs 인 경우가 대표적인 경우이다.
해당 값을 구하는 코드는 다음과 같다.
TOKEN_STATISTICS 구조체의 AuthenticationId member에 해당 값이 존재한다.
PTOKEN_STATISTICS pStatic
if(!::GetTokenInformation(hToken, TokenStatistics, pStatic, buf.size(), &dwLength))
LUID luid = pStatic->AuthenticationId;
Convert File Format Using OLE API
<html>
<head>
<script language="javascript">
var vHwpCtrl;
function PDF_Print()
{
var app = new ActiveXObject("AcroExch.App");
var doc = new ActiveXObject("AcroExch.PDDoc");
doc.open("c:\\Docs\\01\\TestPdf.pdf");
var jso = doc.GetJSObject(); // retun javascript object (only used by javascript)
jso.addWatermarkFromText("aa");
var avDoc = doc.OpenAVDoc("print"); //print pdf file
avDoc.PrintPages(0, 1, 2, 0, 0);
}
function WORD_TO_PDF()
{
var wdExportFormatPDF= 17;
var wordApp = new ActiveXObject("Word.Application");
var wordDocs = wordApp.Documents;
var wordDoc = wordDocs.Open("d:\\test\\TestDoc.doc");
wordDoc.ExportAsFixedFormat("d:\\test\\TestDoc.pdf", wdExportFormatPDF);
}
function EXCEL_TO_PDF()
{
var xlTypePDF = 0;
var excelApp = new ActiveXObject("Excel.Application");
var excelWorkBooks = excelApp.WorkBooks;
var excelWorkBook = excelWorkBooks.Open("d:\\test\\TestXls.xls");
excelWorkBook.ExportAsFixedFormat(xlTypePDF, "d:\\test\\TestXls.pdf");;;
}
function PPT_TO_PDF()
{
var ppFixedFormatTypePDF = 2;
var ppFixedFormatIntentPrint = 2;
var ppSaveAsPDF = 32;
var ppSaveAsPNG = 18;
var pptApp = new ActiveXObject("PowerPoint.Application");
var pptPresentations = pptApp.Presentations;
var pptPresentation = pptPresentations.Open("d:\\test\\TestPpt.ppt");
pptPresentation.SaveAs("d:\\test\\TestPpt.pdf", ppSaveAsPDF ); //convert pdf
pptPresentation.SaveAs("d:\\test\\TestPpt.png", ppSaveAsPNG ); //convert image
//pptPresentation.ExportAsFixedFormat("d:\\test\\TestPpt.pdf", ppFixedFormatTypePDF, ppFixedFormatIntentPrint ); // not working, not find the cause.
}
function HWP_PRINT()
{
hwpCtrl.Open("d:\\test\\TestHwp.hwp");
var vPrintAct = hwpCtrl.CreateAction("Print");
var vPrintSet = vPrintAct.CreateSet();
var vWaterMarkSet = vPrintSet.CreateItemSet("PrintWatermark", "PrintWatermark");
vPrintAct.GetDefault(vPrintSet);
vPrintSet.SetItem("Device", 0);
vWaterMarkSet.SetItem("String" , "bdc");
vPrintAct.Execute(vPrintSet);
}
</script>
</head>
<body onload >
<form name = "HwpControl">
<input type="button" value='PDF' name="job" onclick='PDF_Print()' >
<input type="button" value='WORD' name="job" onclick='WORD_TO_PDF()' >
<input type="button" value='EXCEL' name="job" onclick='EXCEL_TO_PDF()' >
<input type="button" value='PPT' name="job" onclick='PPT_TO_PDF()' >
<input type="button" value='HWP' name="job" onclick='HWP_PRINT()' >
</form>
<object id=hwpCtrl style="left: 0px; top: 0px" height=80% width=80% align=center classid='CLSID:BD9C32DE-3155-4691-8972-097D53B10052' / >
</body>
</html>
dynamic create activeX (javascript)
- create
- new ActiveXObject 를 이용한다.
- var object = new ActiveXObject(progid);
- link event
- 해당 activeX 가 IProvideClasInfo2 와 IConnnectionPoint 가 구현되어 있어야 한다.
- eval("function object::event1( value ) { event_handler(value); }");
ATL with IE(HTML)
- Implement IObjectSafety
- 미 구현 시 script 구간에서 경고 창이 뜬다.
- 구현 방법
public IObjectSafetyImpl<Ctest, INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA>,
COM_INTERFACE_ENTRY(IObjectSafety)
- Implement IObjectWithSite
- javascript 에서 new ActiveXObject 로 구현 가능하도록 하려면
- 구현 방법
- wizard 창에서 선택 가능
- Implement IProvideClassInfo2
- web page 에서 Event catch 를 위해서 (IConnectionPoint 도 구현해야 된다. wizard 에서 선택 가능)
- 구현 방법
public IProvideClassInfo2Impl<&CLSID_<object_name>, NULL,
&LIBID_<project_name>Lib>COM_INTERFACE_ENTRY(IProvideClassInfo)
COM_INTERFACE_ENTRY(IProvideClassInfo2)url : http://support.microsoft.com/?id=200839>
Problem of Textout function with zoom
위의 사진이 100% 아래는 108 % 인 경우이다.
자세히 보면 100%인 경우는 0의 위치가 균일하나 108%는 첫번째 0 과 두번째 0 이 붙여 있고 세번째 0 은 떨어져 있다.
모양뿐 아니라 실제 문제는 2 경우 108%인 경우 1px 더 큰 가로를 가진다( font 에 따라 문제가 발생하지 않는 경우도 있다.)
GM_ADVANCED 인 경우 Text 출력에 대한 몇가지 버그 사항들에 대한 자료는 있지만 위 현상에 대한 글을 아직 찾지 못했다.