I am developing a multi-platform game that runs on iOS as well as desktops (Windows, Mac, Linux). I want the game to be able to resize certain UI elements depending on the resolution of the screen in inches. The idea is that if a button should be, say, around 1/2 inch across in any interface, it will be scaled automatically that size.
Now for iOS devices this problem is reasonably well solvable using brute force techniques. You can look up the type of the device and use a hard-coded table to determine the screen size in inches for each device. Not the most elegant solution, but sufficient.
Desktops are the tricky ones. What I wish and hope exists is a mechanism by which (some?) monitors report to operating systems their actual screen size in inches. If that mechanism exists and I can access it somehow, I can get good numbers at least for some monitors. But I've never come across any such concept in any of the major OS APIs.
Is there a way to ask for the screen size in inches in Win32? If so, are there monitors that actually provide this information?
(And if the answer is no: Gosh, doesn't this seem awfully useful?)
For Windows, first see SetProcessDPIAware() for a discussion on turning off automatic scaling, and then call GetDeviceCaps( LOGPIXELSX ) and GetDeviceCaps( LOGPIXELSY ) on your HDC to determine the monitor's DPI. Divide the screen resolution on your active monitor by those settings and you've got the size.
Also see this article for a similar discussion on DPI aware apps.
Here is a method I found at the web address "https://ofekshilon.com/2011/11/13/reading-monitor-physical-dimensions-or-getting-the-edid-the-right-way/".
Authour says that measurement is in millimeters.
Does not give you the precise width and height but better approximation than HORSIZE and VERTSIZE. In which I tried on two different monitors and got a max difference of 38 cm (measured screen size - calculated screen size).
#include <SetupApi.h>
#pragma comment(lib, "setupapi.lib")
#define NAME_SIZE 128
const GUID GUID_CLASS_MONITOR = {0x4d36e96e, 0xe325, 0x11ce, 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18};
// Assumes hDevRegKey is valid
bool GetMonitorSizeFromEDID(const HKEY hDevRegKey, short& WidthMm, short& HeightMm)
{
DWORD dwType, AcutalValueNameLength = NAME_SIZE;
TCHAR valueName[NAME_SIZE];
BYTE EDIDdata[1024];
DWORD edidsize=sizeof(EDIDdata);
for (LONG i = 0, retValue = ERROR_SUCCESS; retValue != ERROR_NO_MORE_ITEMS; ++i)
{
retValue = RegEnumValueA ( hDevRegKey, i, &valueName[0],
&AcutalValueNameLength, NULL, &dwType,
EDIDdata, // buffer
&edidsize); // buffer size
if (retValue != ERROR_SUCCESS || 0 != strcmp(valueName,"EDID"))
continue;
WidthMm = ((EDIDdata[68] & 0xF0) << 4) + EDIDdata[66];
HeightMm = ((EDIDdata[68] & 0x0F) << 8) + EDIDdata[67];
return true; // valid EDID found
}
return false; // EDID not found
}
// strange! Authour requires TargetDevID argument but does not use it
bool GetSizeForDevID(const char *TargetDevID, short& WidthMm, short& HeightMm)
{
HDEVINFO devInfo = SetupDiGetClassDevsExA(
&GUID_CLASS_MONITOR, //class GUID
NULL, //enumerator
NULL, //HWND
DIGCF_PRESENT, // Flags //DIGCF_ALLCLASSES|
NULL, // device info, create a new one.
NULL, // machine name, local machine
NULL);// reserved
if (NULL == devInfo) return false;
bool bRes = false;
for (ULONG i=0; ERROR_NO_MORE_ITEMS != GetLastError(); ++i)
{
SP_DEVINFO_DATA devInfoData;
memset(&devInfoData,0,sizeof(devInfoData));
devInfoData.cbSize = sizeof(devInfoData);
if (SetupDiEnumDeviceInfo(devInfo,i,&devInfoData))
{
HKEY hDevRegKey = SetupDiOpenDevRegKey(devInfo,&devInfoData,DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
if(!hDevRegKey || (hDevRegKey == INVALID_HANDLE_VALUE)) continue;
bRes = GetMonitorSizeFromEDID(hDevRegKey, WidthMm, HeightMm);
RegCloseKey(hDevRegKey);
}
}
SetupDiDestroyDeviceInfoList(devInfo);
return bRes;
}
int main(int argc, CHAR* argv[])
{
short WidthMm, HeightMm;
DISPLAY_DEVICE dd;
dd.cb = sizeof(dd);
DWORD dev = 0; // device index
int id = 1; // monitor number, as used by Display Properties > Settings
char DeviceID[1024];
bool bFoundDevice = false;
while (EnumDisplayDevices(0, dev, &dd, 0) && !bFoundDevice)
{
DISPLAY_DEVICE ddMon = {sizeof(ddMon)};
DWORD devMon = 0;
while (EnumDisplayDevices(dd.DeviceName, devMon, &ddMon, 0) && !bFoundDevice)
{
if (ddMon.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP &&
!(ddMon.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER))
{
sprintf(DeviceID,"%s", ddMon.DeviceID+8);
for(auto it=DeviceID; *it; ++it)
if(*it == '\\') { *it = 0; break; }
bFoundDevice = GetSizeForDevID(DeviceID, WidthMm, HeightMm);
}
devMon++;
ZeroMemory(&ddMon, sizeof(ddMon));
ddMon.cb = sizeof(ddMon);
}
ZeroMemory(&dd, sizeof(dd));
dd.cb = sizeof(dd);
dev++;
}
return 0;
}
Related
I am fairly new to kernel programming and I have a little problem getting all disk drives information like name,serialnumber from kernel mode. I use below code to get all disks symbolic links which works perfectly fine.
static VOID DeviceInterfaceTest_Func() {
NTSTATUS Status;
PWSTR SymbolicLinkList;
PWSTR SymbolicLinkListPtr;
GUID Guid = {
0x53F5630D,
0xB6BF,
0x11D0,
{
0x94,
0xF2,
0x00,
0xA0,
0xC9,
0x1E,
0xFB,
0x8B
}
}; //Defined in mountmgr.h
Status = IoGetDeviceInterfaces( &
Guid,
NULL,
0, &
SymbolicLinkList);
if (!NT_SUCCESS(Status)) {
return;
}
KdPrint(("IoGetDeviceInterfaces results:\n"));
for (SymbolicLinkListPtr = SymbolicLinkList; SymbolicLinkListPtr[0] != 0 && SymbolicLinkListPtr[1] != 0; SymbolicLinkListPtr += wcslen(SymbolicLinkListPtr) + 1) {
KdPrint(("Symbolic Link: %S\n", SymbolicLinkListPtr));
PUNICODE_STRING PTarget {};
UNICODE_STRING Input;
NTSTATUS s = 0;
Input.Length = sizeof((PWSTR) & SymbolicLinkListPtr);
Input.MaximumLength = 200 * sizeof(WCHAR);
Input.Buffer = (PWSTR) ExAllocatePool2(PagedPool, Input.MaximumLength, 0);
s = SymbolicLinkTarget( & Input, PTarget);
if (s == STATUS_SUCCESS) {
//KdPrint(("%S\n", PTarget->Buffer));
KdPrint(("Finished!\n"));
}
}
ExFreePool(SymbolicLinkList);
}
However when i try to use InitializeObjectAttributes function to extract data of symbolic link inside for loop I checking their names with KdPrint and all them are null as a result i can't use ZwOpenSymbolicLinkObject, because when i use it i get BSOD. What am I doing wrong? Is my method valid to get disk information or I should use another method? Below is the code of SymbolicLinkTarget
NTSTATUS SymbolicLinkTarget(_In_ PUNICODE_STRING SymbolicLinkStr, _Out_ PUNICODE_STRING PTarget) {
OBJECT_ATTRIBUTES ObjectAtiribute {};
NTSTATUS Status = 0;
HANDLE Handle = nullptr;
InitializeObjectAttributes( & ObjectAtiribute, SymbolicLinkStr, OBJ_CASE_INSENSITIVE, 0, 0);
KdPrint(("Object length:%u \n", ObjectAtiribute.Length));
KdPrint(("Object name:%s \n", ObjectAtiribute.ObjectName - > Buffer));
Status = ZwOpenSymbolicLinkObject(&Handle, GENERIC_READ, &ObjectAtiribute);
if (Status != STATUS_SUCCESS)
{
KdPrint(("ZwOpenSymbolicLinkObject failed (0x%08X)\n", Status));
return Status;
}
UNREFERENCED_PARAMETER(PTarget);
ULONG Tag1 = 'Tag1';
PTarget->MaximumLength = 200 * sizeof(WCHAR);
PTarget->Length = 0;
PTarget->Buffer = (PWCH)ExAllocatePool2(PagedPool, PTarget->MaximumLength, Tag1);
if (!PTarget->Buffer)
{
ZwClose(Handle);
return STATUS_INSUFFICIENT_RESOURCES;
}
Status = ZwQuerySymbolicLinkObject(Handle, PTarget, NULL);
ZwClose(Handle);
if (Status != STATUS_SUCCESS)
{
KdPrint(("ZwQuerySymbolicLinkObject failed (0x%08X)\n", Status));
ExFreePool(PTarget->Buffer);
return Status;
}
return STATUS_SUCCESS;
}
Thank you very much for helping.
There are multiple problems in your functions. Let start with he main one:
In SymbolicLinkTarget():
OBJECT_ATTRIBUTES ObjectAtiribute {};
InitializeObjectAttributes( & ObjectAtiribute, SymbolicLinkStr, OBJ_CASE_INSENSITIVE, 0, 0);
You are going to initialize ObjectAtiribute from SymbolicLinkStr (and the other parameters) but in DeviceInterfaceTest_Func() you actually never set Input to contain a string!
UNICODE_STRING Input;
NTSTATUS s = 0;
Input.Length = sizeof((PWSTR) & SymbolicLinkListPtr);
Input.MaximumLength = 200 * sizeof(WCHAR);
Input.Buffer = (PWSTR) ExAllocatePool2(PagedPool, Input.MaximumLength, 0);
s = SymbolicLinkTarget( & Input, PTarget);
Input.Length
This is wrong:
Input.Length = sizeof((PWSTR) & SymbolicLinkListPtr);
Input.Length will be set to the size of a pointer. According to the UNICODE_STRING (ntdef.h; subauth.h) the length is:
Specifies the length, in bytes, of the string pointed to by the Buffer member, not including the terminating NULL character, if any.
So:
size_t str_len_no_null = wcslen(SymbolicLinkListPtr); // number of chars, not bytes!
Input.Length = str_len_no_null * sizeof(WCHAR);
Notice the wcslen() is already in the init-statement of the for loop, I would train to extract it to have it in the loop body.
Input.MaximumLength
Input.MaximumLength = 200 * sizeof(WCHAR);
What if the string is more lager than 200 characters?
MaximumLength is defined as such:
Specifies the total size, in bytes, of memory allocated for Buffer. Up to MaximumLength bytes may be written into the buffer without trampling memory.
Thus it's safe to just do:
size_t max_length_bytes = Input.Length + (1 * sizeof(WCHAR)); // add room for possible null.
Input.MaximumLength = max_length_bytes;
The allocation for the Buffer member can be kept in place. Now you need to copy the string into the buffer.
UNICODE_STRING init
size_t str_len_no_null = wcslen(SymbolicLinkListPtr); // number of chars, not bytes!
Input.Length = str_len_no_null * sizeof(WCHAR);
size_t max_length_bytes = Input.Length + (1 * sizeof(WCHAR)); // add room for possible null.
Input.MaximumLength = max_length_bytes;
Input.Buffer = (PWSTR) ExAllocatePool2(PagedPool, Input.MaximumLength, 0); // note: you should define a Tag for your Driver.
if(Input.buffer == NULL) {
// not enough memory.
return;
}
status = RtlStringCbCopyW(Input.Buffer, max_length_bytes, SymbolicLinkListPtr);
// TODO: check status
Now that you know how to do it manually, throw your code and use RtlUnicodeStringInit
Other things & hints
Always checks the return status / value of the functions you use. In kernel mode, this is super important.
NTSTATUS check is always done using one of the status macros (usually NT_SUCCESS)
Use string safe functions.
nitpicking: A success return value of IoGetDeviceInterfaces may also indicate an empty buffer. Although you check that in the for loop init-statement, I would have checked that right after the function so the intent is clearer.
KdPrint(("Object name:%s \n", ObjectAtiribute.ObjectName - > Buffer));
It's %S (wide char) not %s (char); see format specification. you can pass a UNICODE_STRING and use the %Z formatter. Also be wary of - > which is strange (you probably meant ->).
InitializeObjectAttributes( & ObjectAtiribute, SymbolicLinkStr, OBJ_CASE_INSENSITIVE, 0, 0);
Use OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE if the resulting handle is not meant to cross the kernel <-> user-mode boundary (in your case, it doesn't have to cross that boundary). Otherwise you leak a kernel handle to user-mode, which has security implications.
This is also required when you call ZwOpenSymbolicLinkObject and you are not running in a system thread:
If the caller is not running in a system thread context, it must set the OBJ_KERNEL_HANDLE attribute when it calls InitializeObjectAttributes.
You can define GUIDs with DEFINE_GUID; see Defining and Exporting New GUIDs and Including GUIDs in Driver Code. In your case you don't need to export it.
This is probably nitpicking, but use nullptr (c++) or NULL (c) instead of 0 to convey the idea that you are checking for a pointer and not just the integral value of 0.
I have an application that is used as a control system for a presentation, under Linux and using X11. I have a USB presentation remote that acts as a very miniature keyboard (four buttons: Page Up, Page Down, and two others) which can be used to advance and go back in the presentation. I would like to have my presentation application to receive all of the events from this remote regardless of where the mouse focus is. But I would also like to be able to receive the normal mouse and keyboard events if the current window focus is on the presentation application. Using XIGrabDevice() I was able to receive all events from the remote in the presentation application regardless of the current focus but I was not able to receive any events from the mouse or keyboard while the grab was active.
I ended up setting up a separate program to capture the remote's keys, then I relay those keys to my main program. I did it this way because the original program was using the older XInput extension, and I needed to use the newer XInput2 extension, and they do not exist well together. Here's some C++ code (it doesn't do any error checking, but this should be done in a real program):
// Open connection to X Server
Display *dpy = XOpenDisplay(NULL);
// Get opcode for XInput Extension; we'll need it for processing events
int xi_opcode = -1, event, error;
XQueryExtension(dpy, "XInputExtension", &xi_opcode, &event, &error);
// Allow user to select a device
int num_devices;
XIDeviceInfo *info = XIQueryDevice(dpy, XIAllDevices, &num_devices);
for (int i = 0; i < num_devices; ++i)
{
XIDeviceInfo *dev = &info[i];
std::cout << dev->deviceid << " " << dev->name << "\n";
}
XIFreeDeviceInfo(info);
std::cout << "Enter the device number: ";
std::string input;
std::cin >> input;
int deviceid = -1;
std::istringstream istr(input);
istr >> deviceid;
// Create an InputOnly window that is just used to grab events from this device
XSetWindowAttributes attrs;
long attrmask = 0;
memset(&attrs, 0, sizeof(attrs));
attrs.override_redirect = True; // Required to grab device
attrmask |= CWOverrideRedirect;
Window win = XCreateWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1, 1, 0, 0, InputOnly, CopyFromParent, attrmask, &attrs);
// Make window without decorations
PropMotifWmHints hints;
hints.flags = 2;
hints.decorations = 0;
Atom property = XInternAtom(dpy, "_MOTIF_WM_HINTS", True);
XChangeProperty(dpy, win, property, property, 32, PropModeReplace, (unsigned char *)&hints, PROP_MOTIF_WM_HINTS_ELEMENTS);
// We are interested in key presses and hierarchy changes. We also need to get key releases or else we get an infinite stream of key presses.
XIEventMask evmasks[1];
unsigned char mask0[XIMaskLen(XI_LASTEVENT)];
memset(mask0, 0, sizeof(mask0));
XISetMask(mask0, XI_KeyPress);
XISetMask(mask0, XI_KeyRelease);
XISetMask(mask0, XI_HierarchyChanged);
evmasks[0].deviceid = XIAllDevices;
evmasks[0].mask_len = sizeof(mask0);
evmasks[0].mask = mask0;
XISelectEvents(dpy, win, evmasks, 1);
XMapWindow(dpy, win);
XFlush(dpy);
XEvent ev;
bool grab_success = false, grab_changed;
while (1)
{
grab_changed = false;
if (!grab_success)
{
XIEventMask masks[1];
unsigned char mask0[XIMaskLen(XI_LASTEVENT)];
memset(mask0, 0, sizeof(mask0));
XISetMask(mask0, XI_KeyPress);
masks[0].deviceid = deviceid;
masks[0].mask_len = sizeof(mask0);
masks[0].mask = mask0;
XIGrabDevice(dpy, deviceid, win, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, XIOwnerEvents, masks);
}
XNextEvent(dpy, &ev);
XGenericEventCookie *cookie = &ev.xcookie;
if (cookie->type == GenericEvent && cookie->extension == xi_opcode && XGetEventData(dpy, cookie))
{
if (cookie->evtype == XI_KeyPress)
{
XIDeviceEvent *de = (XIDeviceEvent*)cookie->data;
std::cout << "found XI_KeyPress event: keycode " << de->detail << "\n";
}
else if (cookie->evtype == XI_HierarchyChanged)
{
// Perhaps a device was unplugged. The client is expected to re-read the list of devices to find out what changed.
std::cout << "found XI_HierarchyChanged event.\n";
grab_changed = true;
}
XFreeEventData(dpy, cookie);
}
if (grab_changed)
{
XIUngrabDevice(dpy, deviceid, CurrentTime);
grab_success = false;
break;
}
}
I found the following links helpful:
Peter Hutterer's 6-part blog on XInput2: 1 2 3 4 5 6
This blog entry was useful to determine which class to cast the cookie->data pointer to, depending on the cookie->evtype: 7
Sorry for my pure english.
I have two processes which can Read and Write data to the same value(my tests do it).
Sometimes(one per ten times) the read method is fail with error ERROR_MORE_DATA and Value is 12.
But I call Read method from the tests with 32 bytes.
By chance I looked to #err,hr in watch (GetLastError()) and saw ERROR_NOT_OWNER error code.I understand that second process is block the key and I must try again.
Can anybody approve my conclusions (MSDN is not say anything about this)?
Can anybody will tell me other strange effects?
Thank you.
Update:
I have UAC Virtualization. All changes are stored to the
[HKEY_CLASSES_ROOT\VirtualStore\MACHINE\SOFTWARE]
May be it is effect virtualization???
{
...
char name[32] = "";
grandchild.OpenValue("name").Read(name, _countof(name));
...
}
bool RegisteryStorageValue::Read(void* Buffer, size_t Size) throw (IOException)
{
DWORD Value = DWORD(Size);
DWORD rez = ::RegQueryValueEx(mKey, mName.c_str(), NULL, NULL, (BYTE*)Buffer, &Value);
if (rez != ERROR_SUCCESS) // here I have 'rez = ERROR_MORE_DATA' and 'Value = 12'
throw IOException(rez);
return true;
}
bool RegisteryStorageValue::Write(Type type, const void* Buffer, size_t Size) throw (IOException)
{
DWORD rez = ::RegSetValueEx(mKey, mName.c_str(), NULL, getRegType(type), (const BYTE*)Buffer, (DWORD)Size);
if (rez != ERROR_SUCCESS)
throw IOException(rez);
return true;
}
Registry functions do not use GetLastError() to report errors. They return error codes directly. So the ERROR_NOT_OWNER is misleading, it is from an earlier Win32 API call, not the Registry calls.
There is no possible way you can pass in a Size value of 32 to RegQueryValueEx() and get back an ERROR_MORE_DATA error saying the data is actually 12 in size. RegQueryValueEx() does not work that way. Make sure your Size value is actually set to 32 upon entry to the Read() function and is not set to some other value.
Update: it is, however, possible for RegQueryValueEx() to report ERROR_MORE_DATA and return a data size that is twice as larger as what you requested, even if RegSetValueEx() is not actually passed that much data. When I ran your test code, I was able to get RegQueryValueEx() to sometimes (not every time) report a data size of 64 even though 32 was being requested. The reason is because RegSetValueExA(), which your code is actually calling, performs a data conversion from Ansi to Unicode for string types (REG_SZ, REG_MULTI_SZ and REG_EXPAND_SZ), and RegQueryValueExA(), which your code is actually calling, queries the raw bytes and performs a Unicode to Ansi conversion for string types. So while your writing code may be saving 32 char values, thus 32 bytes, the Registry is actually storing 32 wchar_t values instead, thus 64 bytes (it would be more if your input strings had non-ASCII characters in them). Chances are, RegQueryValueEx() is returning the raw bytes as-is instead of converting them, such as if RegSetValueEx() is saving the raw bytes first and then saving the data type afterwards, but RegQueryValueEx() is reading the raw bytes before the data type has been saved and thus does not know the data is a string type that needs converting.
Either way, this is a race condition between one thread/process reading while another thread/process is writing, issues with reading while the writing is caching data internally before flushing it, etc. Nothing you can do about this unless you synchronize the reads and writes, since the Registry API does not synchronize for you.
I write sample for my question. I have repeate it issue on the third start.
If sample is complite you can see "Query complite" and "SetComplite" messages
On err you should saw: "error more data: ??"
#include <string>
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
bool start(char* path, char* args)
{
std::string cmd = path;
cmd.push_back(' ');
cmd.append(args);
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
BOOL res = ::CreateProcess(NULL, (LPSTR)cmd.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (res == FALSE)
return false;
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hEvent = ::CreateEvent(NULL, TRUE, FALSE, "Local/blah");
if (argc == 1)
{
HKEY hKey;
if (::RegCreateKey(HKEY_CURRENT_USER, "Software\\TestRegistry", &hKey) != ERROR_SUCCESS)
return -1;
char buffer[] = "Hello, Stack!";
::RegSetValueEx(hKey, "Value", 0, REG_SZ, (BYTE*)buffer, _countof(buffer));
::RegCloseKey(hKey);
if (start(argv[0], "r") == false ||
start(argv[0], "w") == false)
return -2;
::Sleep(1000);
::SetEvent(hEvent);
}
else
{
if (argv[1][0] == 'r')
{
HKEY hKey;
if (::RegOpenKey(HKEY_CURRENT_USER, "Software\\TestRegistry", &hKey) != ERROR_SUCCESS)
return -1;
char buffer[1024] = {0};
if (::WaitForSingleObject(hEvent, 10000) == WAIT_TIMEOUT)
return -3;
for (size_t index = 0; index < 1000000; ++index)
{
DWORD dwType;
DWORD dwSize = _countof(buffer);
DWORD result = ::RegQueryValueEx(hKey, "Value", 0, &dwType, (LPBYTE)buffer, &dwSize);
if (result == ERROR_SUCCESS)
continue;
if (result == ERROR_MORE_DATA)
{
::printf_s("\nError more data: %d\n", dwSize);
return 1;
}
}
::RegCloseKey(hKey);
::printf_s("\nQuery completed\n");
}
else
{
::srand(::GetTickCount());
HKEY hKey;
if (::RegOpenKey(HKEY_CURRENT_USER, "Software\\TestRegistry", &hKey) != ERROR_SUCCESS)
return -1;
const size_t word_size = 32;
char dict[][word_size] =
{
"aaaaaaaa",
"help me",
"rape me",
"in the pines",
"argh",
};
char buffer[1024] = {0};
if (::WaitForSingleObject(hEvent, 10000) == WAIT_TIMEOUT)
return -3;
for (size_t index = 0; index < 1000000; ++index)
{
DWORD dwType = REG_SZ;
DWORD dwSize = word_size;
DWORD result = ::RegSetValueEx(hKey, "Value", 0, dwType, (LPBYTE)dict[rand() % _countof(dict)], dwSize);
if (result == ERROR_SUCCESS)
continue;
}
::RegCloseKey(hKey);
::printf_s("\nSet completed\n");
}
}
return 0;
}
How to get post script name,full path of type 1 font on 64 bit Windows7? APIs for these are provided by Adobe ATM library for 32 bit win OS only like- ATMGetPostScriptName, ATMGetFontPaths, etc.
As per my knowledge type 1 fonts are supported by OS now. I am able to get all these font information through GetFontData, RegQueryMultipleValues, etc for TTF and OTF fonts but these APIs are failing for type1 fonts (.pfm, .pfb fonts).
First time I am using this forum and hoping someone can help me out quickly.
Thanks in Advance,
Vijendra
I had a similar problem, I wanted the postscript name and to convert the font to postscript. The solution sits in a little library called ttf2pt1, found at http://ttf2pt1.sourceforge.net/README.html
The routine you need is below. The routine digs out all the various internal names for the font using OutlineTextMetrics. The nameFace value is the one you want.
short i;
short val;
long offset;
OUTLINETEXTMETRIC *otm;
UINT nSize;
UINT retVal;
char *sptr;
char *nameFamily;
char *nameFace;
char *nameStyle;
char *nameFull;
int fontType;
char otmBuffer[4096];
SelectObject(hdc, theFont);
nSize = GetOutlineTextMetrics(hdc, 0, NULL);
if(nSize){
otm = (OUTLINETEXTMETRIC *) otmBuffer;
retVal = GetOutlineTextMetrics(hdc, nSize, otm);
val = otm->otmTextMetrics.tmPitchAndFamily;
offset = (long) otm->otmpFamilyName;
sptr = &otmBuffer[offset];
nameFamily = sptr;
offset = (long) otm->otmpFaceName;
sptr = &otmBuffer[offset];
nameFace = sptr;
offset = (long) otm->otmpStyleName;
sptr = &otmBuffer[offset];
nameStyle = sptr;
offset = (long) otm->otmpFullName;
sptr = &otmBuffer[offset];
nameFull = sptr;
if(val & TMPF_TRUETYPE){
fontType = kFontTypeTrueType;
}
else{
if(val & TMPF_VECTOR){
fontType = kFontTypePostscript;
}
}
}
else{
fontType = kFontTypeUnknown;
}
Does the following code indicate that in an exe, the section header comes after the section itself, or am I missing on something?
Also the value of lpFileBase is diffent from the value held in pimnth->OptionalHeader.ImageBase. Aren't they supposed to be the same??
#include<iostream>
#include<Windows.h>
#include<stdio.h>
#include<WinNT.h>
int main()
{
HANDLE hFile,hFileMapping;
LPVOID lpFileBase;
LPVOID lp;
long offset;
if((hFile = CreateFile(TEXT("c:\\linked list.exe"),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0)) == INVALID_HANDLE_VALUE)
std::cout<<"unable to open";
if((hFileMapping = CreateFileMapping(hFile,NULL,PAGE_READONLY,0,0,NULL)) == 0)
{
CloseHandle(hFile);
std::cout<<"unable to open for mapping";
}
if((lpFileBase = MapViewOfFile(hFileMapping,FILE_MAP_READ,0,0,0))== 0)
{
CloseHandle(hFile);
CloseHandle(hFileMapping);
std::cout<<"couldn't map view of file";
}
PIMAGE_DOS_HEADER pimdh;
pimdh = (PIMAGE_DOS_HEADER)lpFileBase;
PIMAGE_NT_HEADERS pimnth;
pimnth = (PIMAGE_NT_HEADERS)(pimdh->e_lfanew + (char *)lpFileBase);
PIMAGE_SECTION_HEADER pimsh;
pimsh = (PIMAGE_SECTION_HEADER)(pimnth + 1);
printf("Address of section header:%x\n",pimsh);
for(int i = 0; i<pimnth->FileHeader.NumberOfSections; i++)
{
if(!strcmp((char *)pimsh->Name,".text"))
{
printf("Virtual Address:%x\n\n\n",pimsh->VirtualAddress);
}
pimsh++;
}
}
The value (address) contained in the OptionalHeader.ImageBase field is placed by the compiler/linker. This predefined address is needed by the linker in order to be able to calculate the jumps and the offset when variables and functions are invoked. One of the very first task of the loader is to verify whether this predefined address is already occupied in memory (which is often the case for DLLs). Should the address NOT be occupied, then your lpFileBase would be the same as OptionalHeader.ImageBase.