Not able to get IME Input Context through C++ (ImmGetContext) - c++

Hi I am trying to disable the IME on notepad using the following psuedo code:
MakeNotepadActiveWindow();//Notepad is already open and set to Japanese IME
HWND hwnd = GetTheHWNDForNotepad();
HIMC context = ImmGetContext(hwnd);
if(context == NULL)
printf("context is null %d ",GetLastError());
and the above code is always giving me the null context. GetLastError() gives 0;
Could somebody tell me how to get the InputContext

Just in case somebody else runs into similar problem
You can't get the input context for a window unless you own it.
So you need to call ImmGetInputContext(hwnd) by executing the code in that window's process.

Related

How to replace (hook) a Windows function with a custom one using MS Detours?

I'm a student and just learned about hooking with MS Detours.
DESCRIPTION:
I wanted to replace some Windows functions for writing and changing text inside windows, titles etc. like a TextOutW() function
The TextOut() function writes a character string at the specified location, using the currently selected font, background color, and text color.
THE GOAL:
My goal is to hook new functions (like NewTextOutW()) which are going to do the same thing, but they will translate the text in another language. The new functions have the same parameters like the original ones.
WHY MS DETOURS?
I have to use MS Detours because the traditional hooking with asm and overwriting the hot-patch header of an original function works just for the X86 version of the app but not for X64, so because the MS Detours is compatible with 32bit and 64bit apps, I want to use MS Detorus.
I want to do the hooking with function addresses, because I have the source code and I have addresses of the original and the new function saved in a BYTE* type of variable.
CODE INFO:
This is my code which is going to attach a new function to the original one using the 2 adresses (BYTE* m_pOrigFunc and BYTE* m_pDetourFunc).
m_pOrigFunc is an adress of the original function and the m_pDetourFunc is the address of the function which is going to be attached to the original one. To detach the two functions I use the same code but except using the DetourAttach((PVOID*)&m_pOrigFunc, m_pDetourFunc) i use the DetourDetach((PVOID*)&m_pOrigFunc, m_pDetourFunc) statement.
CODE:
LONG err_cd = DetourTransactionBegin();
if (err_cd == NO_ERROR)
{
//err_cd = DetourUpdateThread(GetCurrentThread());
if (err_cd == NO_ERROR)
{
err_cd = DetourAttach((PVOID*)&m_pOrigFunc, m_pDetourFunc);
if (err_cd == NO_ERROR)
{
err_cd = DetourTransactionCommit();
if (err_cd == NO_ERROR)
::Trace(2, _T("MSDetours::DetourTransactionCommit: Detour erfolgreich."));
else
AbortAndTraceMSDetours("DetourTransactionCommit", err_cd);}
else
AbortAndTraceMSDetours("DetourAttach", err_cd);}
else
AbortAndTraceMSDetours("DetourUpdateThread", err_cd);}
else
AbortAndTraceMSDetours("DetourTransactionBegin", err_cd);
THE PROBLEM:
After implementig this code I got an error in some other windows function (I thing for the creating a frame but I'm not sure) which you can see
here. For the people who don't speak german, here is a text translation:
Unhandled exception at 0x6D0A00C8 in Konfig32.exe: 0xC000041D:
unhandled exception was encountered during a user callback.
The error accures with or without commenting the line with err_cd = DetourUpdateThread(GetCurrentThread()); statement.
Can someone help me to find the soolution for this problem?

How to force open file "silently" (minimized, not active) using c++ WinAPI functional?

In my WinAPI C++ application I am trying to open an audio file with the default system player using ShellExecuteEx:
int OpenFileWithDefaultProgram(const std::wstring& path, int showMode, HANDLE* hProc) {
SHELLEXECUTEINFO shInfo;
::ZeroMemory(&shInfo, sizeof(SHELLEXECUTEINFO));
shInfo.cbSize = sizeof(SHELLEXECUTEINFO);
shInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
shInfo.hwnd = NULL;
shInfo.lpVerb = L"open";
shInfo.lpFile = path.c_str();
shInfo.nShow = showMode;
::ShellExecuteEx(&shInfo);
*hProc = shInfo.hProcess;
return (int)shInfo.hInstApp;
}
The OpenFileWithDefaultProgram function is called this way:
HANDLE hProc;
int error = OpenFileWithDefaultProgram(path, SW_SHOWMINNOACTIVE, &hProc);
if (error <= 32) {
// Process error
} else {
// Some actions
}
However SW_SHOWMINNOACTIVE parameter is ignored by some players (e.g. MediaPlayerClassic HomeCinema - MPC HC), which leads to opening a player with changing the foreground window and even showing player window not minimized on some PCs.
The first question is: is it possible to force opening player in "silent" mode (minimized and not becoming active)?
I have also tried using GetForegroundWindow and SetForegroundWindow, which didn't help until I added Sleep right after OpenFileWithDefaultProgram (as I understand, the player needs some time to initialize and during this time the foreground window doesn't change):
HWND hWndForeground = GetForegroundWindow();
HANDLE hProc;
int error = OpenFileWithDefaultProgram(path, SW_SHOWMINNOACTIVE, &hProc);
if (error <= 32) {
// Process error
} else {
Sleep(100);
SetForegroundWindow(hWndForeground);
// Some actions
}
This code restored the foreground window perfectly, but I do not like the constant I need to use as a parameter of Sleep function.
Consequently, the second question is: is it possible to "wake up" the thread at the exact moment when the player is initialized? Alternatively, how should I determine the time needed for player initialization (considering that the default player can be anything and take really different time to start)?
Note:
I tried calling WaitForSingleObject(hProc, INFINITE), it just doesn't finish waiting since the player is not terminating after the playback;
I tried calling WaitForInputIdle(hProc, INFINITE), it returns immediately without waiting (probably, since the player does not have a message queue).
The first question is: is it possible to force opening player in "silent" mode (minimized and not becoming active)?
No, the best you can do is request it, and requests can be ignored. You already discovered that part.
The second question: is it possible to "wake up" the thread at the exact moment when the player is initialized?
No, there's no moment defined when a process is fully initialized. You already discovered WaitForInputIdle and its restrictions. But imagine a media player that fetches a CD cover image in the background (not that far-fetched, no need to delay audio for that)—when does it finish initialization?
Also, keep in mind that ShellExecute might not even start a new process. If there is an existing one, it may use it to open the file.

GetWindowText() error 1400

I'm trying to get the current active window name with the code below :
HWND winHandle = GetActiveWindow();
wchar_t buffer[512] = L"";
int getT = GetWindowText(winHandle, (LPTSTR) buffer, 511);
When used on the window of the program, I get the window name correctly, otherwise, I'm getting error 1400. What could be the problem ?
Thanks
Error 1400 is ERROR_INVALID_WINDOW_HANDLE according to Microsoft's documentation. This means an invalid HWND is being passed to GetWindowText.
Working backwards, this means GetActiveWindow didn't return a valid handle, probably NULL instead. According to a comment on the documentation for GetActiveWindow this will happen when the active window doesn't belong to the current application or thread.

First and last window don't show up

I'm creating a WinApi application for my programming course. The program is supposed to show an LED clock using a separate window for each 'block'. I have figured most of it out, except for one thing: when creating the two-dimensional array of windows, the first and last window never show up. Here's the piece of code from the InitInstance function:
for (int x=0;x<8;x++)
for (int y=0;y<7;y++) {
digitWnd[x][y] = CreateWindowEx((WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE | WS_EX_STATICEDGE),
szWindowClass, szTitle, (WS_POPUP| WS_BORDER), NULL, NULL, NULL, NULL, dummyWnd, NULL, hInstance, NULL);
ShowWindow(digitWnd[x][y], nCmdShow);
UpdateWindow(digitWnd[x][y]);
}
The same loop bounds are used everytime I interact with the windows (set position and enable/disable). All the windows seem to be working fine, except for digitWnd[0][0] and digitWnd[7][6]... Any ideas as to what is happening?
Open Spy++ and check if the missing windows are really missing or just overlapped by other windows. It's possible that you have some small error in the position calculations code that puts them behind another window or outside of the screen.
To validate your creation mechanism I would check:
the array initialisation HWND digitWnd[8][7]
if the parent window dummyWnd is valid
the return value of CreateWindowEx() != NULL
Another point which comes to my mind is, that you create windows with dimension 0 - no width or height. So maybe it would be a good idea to set the size within CreateWindowEx(...)
Is this your first call to ShowWindow()? If so, according to MSDN, "nCmdShow: [in] Specifies how the window is to be shown. This parameter is ignored the first time an application calls ShowWindow". This could mean that you can fix your program by simply calling ShowWindow() twice. Give it a try and see if it works. Other than that, you'll probably have to provide more of the code for us to look at.

Error while reading files with native code on windows mobile

I'm new here and my english is not really good. Apologize any inconvenience!
I'm programming an application for windows mobile with native code (MFC). I'm trying to open a file and this is driving me crazy. I've tried to open it in a thousand diferent ways... And I really achieve it, but when I try to read (fread or getline) the program crashes without any explanation:
The program 'x' finalize with code 0 (0x0)
The GetLastError() method, in some cases, returns me a 183.
Then, I put the code I've used to open the file:
std::wifstream file(L"\\Archivos de programa\\Prog\\properties.ini");
wchar_t lol[100];
if (file) {
if(!file.eof()) {
file.getline(lol,99);
}
}
It enters on all the if's, but the getline crashes.
FILE * lol = NULL;
lol = _wfope n(ruta, L"rb");
DWORD a = GetLastError();
if ( lol != NULL )
return 1;
else
return -1;
It returns 1 (correct), and after, in a later getline, it stores trash on the string. However, it doesn't crash!!
fp.open (ruta, ifstream::in);
if ( fp.is_open() ) {
return 1;
}else{
return -1;
}
It enters on the return 1, but when executing the later getline() crashes.
I've debugged the getline() method and it crashes on the library fstream, right there:
if ((_Meta = fget c (_File)) == EOF)
return (false);
In the if. The fgetc(), I supose.
I'm going completely crazy!! I need some clue, please!!
The path of the file is correct. First, because, in theory, the methods open the file, and second, I obtain the path dinamically and it matches.
Emphasize that the fread method also crashes.
Thanks in advance!
P.S.:
Say that when I do any fopen, the method fp.good() returns me FALSE, and the GetLastError returns me 183. By the other hand, if I use fp.fopen(path, ifstream::in); or std::wifstream fp(path); the fp.good(); returns me TRUE, and the GetLastError() doesn't throw any error (0).
A hint: use the Process Monitor tool to see what goes wrong in the file system calls.
The path accepted by wifstream is lacking a drive ("C:" or the like) (I don't know what the ruta variable points to)
Apart from the streams problem itself, you can save yourself a lot of trouble by using the GetProfileString and related functions, when using a windows .ini file.
I'm shooting in the dark here, but your description sounds like a runtime mismatch story. Check that MFC and your project use the same runtime link model (static/dynamic). If you link to MFC dynamically, then the restriction is stricter: both MFC and your project have to use dynamic runtime.
I don't know why, but with the CFile class... it works...
Programming mysteries!
Shooting in the dark too.
Unexplained random crash in MFC often comes from a mismatch message handler prototype.
For example the following code is wrong but it won't generate any warning during compilation and it may work most of the time :
ON_MESSAGE(WM_LBUTTONDOWN, onClick)
...
void onClick(void) //wrong prototype given the macro used (ON_MESSAGE)
{
//do some stuff
}
Here the prototype should be :
LRESULT onClick(WPARAM, LPARAM)
{
}
It often happens when people get confident enough to start modifying manually the message maps.