My WM_KEYDOWN does not work when my MultiLineEdit control is in focus - api

i've a window created with my registered class named CLS1
invoke CreateWindow,addr CLS1,addr title,WS_OVERLAPPED,
10,10,300,300,NULL,NULL,hInstance,NULL
mov hwnd,ax
i have a mle on my window like this:
invoke CreateWindow,addr clsed,NULL,WS_CHILD or WS_VISIBLE or ES_MULTILINE
or ES_AUTOVSCROLL or WS_BORDER or WS_TABSTOP,10,10,280,250,hwnd,123,hInstance,NULL
and my message loop:
.while TRUE
invoke GetMessage,addr msg,NULL,0,0
.break .if (ax == 0)
invoke IsDialogMessage, hwnd,addr msg
.if (!ax)
invoke TranslateMessage,addr msg
invoke DispatchMessage,addr msg
.endif
.endw
In my WndProc I want (for test) that a WM_KEYDOWN message works and show a Message Box when I press the letter 'A'. So, I've tried this:
.if (message == WM_KEYDOWN)
.if (wParam == 41h) ;41h = A or a
invoke MessageBox,NULL,addr keypress,addr title,48
.endif
But it just don't work!
If someone have any solution... please help me.
Sorry my english... i'm not american (lol)

Are you writing for 16-bit windows? If not, checking 16-bit return values and using 16-bit handles is no good:
mov hwnd,ax
.break .if (ax == 0)
.if (!ax)
use eax and things will probably go better.

Related

Priority when 2 keys are pressed at the same time - script for a game

Basically, I want it so that when I have 2 keys pressed together (both A and D, specifically), the last key pressed should have priority, and the key before that should be "suppressed" (no input).
For example: in a game, when you press A, your character moves to the left, and when you press D, he moves to the right.
Pressing those 2 keys together makes the character stop.
Now the thing here is that I don't want the character to stop, I want him to continue to move, based on the last key I pressed, even though I'm holding 2 keys at the same time.
I thought this was going to be a trivial task but I actually got a little overwhelmed after trying to learn how to implement this (I'm a noob, sorry :C ), so I came here looking for some help on how to do this on AHK or any easy to compile scripting language that directly changes the input of a key. I'm not trying to modify or create a game, so a script that remaps those keys is enough!
Autohotkey example, following your "A and D, specifically" question:
for k,v in StrSplit("ad")
Hotkey, % "~$" v,Silveirous
Silveirous:
t:=SubStr(A_PriorHotkey,3)
if GetKeyState(t) and (A_ThisHotkey!=A_PriorHotkey)
Send {%t% up}
return
Documentation:
for k,v in, StrSplit(), Hotkey,,,, "~$", SubStr(), A_Prior/ThisHotkey, if, GetKeyState(), t:=... and ... !=, Send {%t% up}
Edit:
Another solution, made to be working as explained in OP's edit/comment:
#If GetKeyState("d","p")
~a::Send {d up}
~a up::Send {d down}
#If GetKeyState("a","p")
~d::Send {a up}
~d up::Send {a down}
#If
Make sure to mind the difference between #If and if (expression) usage cases.
I'm too late but this could help someone in future :)
Basically you need a variable to keep track of which direction the character faced first and act according to that. A code example could be:
let currentDir = 0;
let maxSpeed = (deltaTime * someConstant);
if (IsKeyDown(KEY_RIGHT) && IsKeyDown(KEY_LEFT))
{
if (currentDir == 1)
speed.x = -maxSpeed;
else if (currentDir == -1)
speed.x = maxSpeed;
}
else if (IsKeyDown(KEY_LEFT))
{
currentDir = -1;
speed.x = -maxSpeed;
}
else if (IsKeyDown(KEY_RIGHT))
{
currentDir = 1;
speed.x = maxSpeed;
}
else
{
speed.x = 0.0f;
currentDir = 0;
}
//And at last player's position would change every frame
player.x += speed.x;
Then when you press left while pressing right the character moves left without stopping and vice versa :)

Use LEA (LEAL) to create an x86 assembly counter

I'm trying to make an assembly program that adds together an unknown number of int's, like
sum(int a,int b, ...)
My code is
.globl notnull
notnull:
leal 4(%esp),%ebx
jmp next2
next:
leal 4(%ebx),%ebx
next2:
cmp $0,(%ebx)
je end
movl (%ebx),%eax
jmp next
end:
ret
I test it with this program:
#include <stdio.h>
extern int notnull();
int main()
{
int x=notnull(3,2,1,0);
printf("3,2,1,0 = %d\n",x);
x=notnull(2,1,0);
printf("2,1,0 = %d\n",x);
x=notnull(1,0);
printf("1,0 = %d\n",x);
x=notnull(0);
printf("0 = %d\n",x);
x=notnull();
printf("_ = %d\n",x);
return 0;
}
Wich gives me this output:
3,2,1,0 = 1 (#1)
2,1,0 = 1 (#2)
1,0 = 1 (#3)
0 = 8 (#4)
_ = 8 (#5)
What I want is the program to return 0 when there are no variables (see #5), and also make it work without having to have 0 as the last digit.
The perfect output of notnull(3,2) would 2 and notnull()=0
You need to read up on C argument passing conventions.
Basically, there is no way to automatically determine how many arguments are being passed to a function.
This is why all C functions either have a fixed number of arguments, or if they use variable arguments (varargs) they have one fixed argument before the variable part, which somehow expresses how many additional arguments are being passed.
Using an empty argument list makes it possible to validly call the function in any manner, but it doesn't help with the core problem of (in the function) determining how many arguments are available.
You might be able to figure it out by inspecting the stack, but of course that requires intimate knowledge of exactly how your particular compiler choses to implement the call. This might vary for different number of arguments, too.

Debugging unmanaged callback problems

Apologies in advance here for the length of the question.
I have a closed source and undocumented COM object - an unmanaged DLL - that I'm attempting to integrate into a Windows service written in C#. The COM object wraps access to some hardware that the service needs to interact with.
I'm not able to get interface documentation or source for the object. All I have to go on is the object itself, three [closed source undocumented] clients that interact with the COM object, and a fair amount of domain specific knowledge.
So far this has been a very tough nut to crack - one week and counting.
I was able to obtain the object's CLSID from the registry - this allowed me to instantiate it in the service.
The next step was to find the IIDs for the interface(s) that I need to use. The particular methods that I was looking for are not exported. I don't have PDBs. There doesn't appear to be any typelib info and the OLE-COM Object Viewer refuses to open the COM object. IDispatch is not implemented either, so it has been a matter of digging. I eventually succeeded in identifying two IIDs by manually searching the binaries for GUIDs and eliminating unique and/or known GUIDs. At this point I'm confident that the IIDs are correct.
The IIDs are obviously useless without corresponding method info. For that I was forced to resort to reversing with IDA. Correlating references to the GUIDs with my knowledge of the hardware functions and the rough disassembly allowed me to make some educated guesses about the structure and purpose of the interfaces.
Now I'm at the point where I need to attempt to use the interfaces to interact with the hardware... and this is where I'm stuck.
From the disassembly, I know that the first method I have to call looks like this:
HRESULT __stdcall SetStateChangeCallback(LPVOID callback);
The callback signature looks something like this:
HRESULT (__stdcall *callbackType)(LPVOID data1, LPVOID data2)
Here is my service code:
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid(...),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface AccessInterface
{
[PreserveSig]
int SetStateChangeCallback(IntPtr callbackPtr);
...
}
[UnmanagedFunctionPointerAttribute(CallingConvention.StdCall)]
private delegate int OnStateChangeDelegate(IntPtr a, IntPtr b);
private int OnStateChange(IntPtr a, IntPtr b)
{
Debug("***** State change triggered! *****");
}
private Guid _typeClsid = new Guid(...);
private Guid _interfaceIid = new Guid(...);
private object _comObj = null;
private AccessInterface _interface = null;
private OnStateChangeDelegate _stateChangeDelegate = null;
private IntPtr _functionPtr = IntPtr.Zero;
private void InitHardware()
{
Type t = Type.GetTypeFromCLSID(_typeClsid);
_comObj = Activator.CreateInstance(t);
if (_comObj == null)
{
throw new NullReferenceException();
}
_interface = _comObj as AccessInterface;
if (_interface == null)
{
throw new NullReferenceException();
}
_stateChangeDelegate = new OnStateChangeDelegate(OnStateChange);
_functionPtr = Marshal.GetFunctionPointerForDelegate(_stateChangeDelegate);
int hr = _interface.SetStateChangeCallBack(_functionPtr);
// hr (HRESULT) == 0, indicating success
}
Now, I can run this code successfully but only if I pass IntPtr.Zero to SetStateChangeCallBack(). If I pass a real reference, the service crashes within a matter of seconds after calling SetStateChangeCallBack() - presumably when the COM object tries to invoke the callback for the first time - with exception code 0xc0000005.
The fault offset is consistent. With the aid of IDA and the previously generated disassembly I was able to identify the area where the problem occurs:
06B04EF7 loc_6B04EF7: ; CODE XREF: 06B04F49j
06B04EF7 lea eax, [esp+0Ch]
06B04EFB push eax
06B04EFC mov ecx, ebx
06B04EFE call near ptr unk_6B06660
06B04F03 test eax, eax
06B04F05 jl short loc_6B04F4B
06B04F07 mov esi, [esp+0Ch]
06B04F0B test esi, esi
06B04F0D jz short loc_6B04F45
06B04F0F push 36h
06B04F11 lea ecx, [esp+18h]
06B04F15 push 0
06B04F17 push ecx
06B04F18 call near ptr unk_6B0F960
06B04F1D mov edx, [esp+1Ch]
06B04F21 push edx
06B04F22 lea eax, [esp+24h]
06B04F26 push esi
06B04F27 push eax
06B04F28 call near ptr unk_6B0F9E0
06B04F2D push esi
06B04F2E call near ptr unk_6B0C8D2
06B04F33 mov eax, [edi+4]
06B04F36 mov ecx, [eax]
06B04F38 add esp, 1Ch
06B04F3B lea edx, [esp+14h]
06B04F3F push edx
06B04F40 push eax
06B04F41 mov eax, [ecx] ; Crash here!
06B04F43 call eax
06B04F45
06B04F45 loc_6B04F45: ; CODE XREF: 06B04F0Dj
06B04F45 cmp dword ptr [edi+28h], 0
06B04F49 jnz short loc_6B04EF7
06B04F4B
06B04F4B loc_6B04F4B: ; CODE XREF: 06B04F05j
06B04F4B pop esi
06B04F4C pop ebx
06B04F4D pop edi
06B04F4E add esp, 40h
06B04F51 retn
The crash is at offset 0x06B04F41 (ie. "mov eax, [ecx]").
Corresponding pseudo code function from the disassembly (note assembler above starts at the do loop):
void __thiscall sub_10004EE0(int this)
{
int v1; // edi#1
void *v2; // esi#4
void *v3; // [sp+4h] [bp-40h]#3
int v4; // [sp+8h] [bp-3Ch]#5
char v5; // [sp+Ch] [bp-38h]#5
v1 = this;
if ( *(_DWORD *)(this + 4) )
{
if ( *(_DWORD *)(this + 40) )
{
do
{
if ( sub_10006660(v1 + 12, (int)&v3) < 0 )
break;
v2 = v3;
if ( v3 )
{
memset(&v5, 0, 0x36u);
unknown_libname_44(&v5, v2, v4);
j_j__free(v2);
// Crash on this statement!
(*(void (__stdcall **)(_DWORD, char *))**(void (__stdcall ****)(_DWORD, _DWORD))(v1 + 4))(
*(_DWORD *)(v1 + 4),
&v5);
}
}
while ( *(_DWORD *)(v1 + 40) );
}
}
}
I'm convinced that I am not passing the function pointer to the COM object correctly, but I'm stuffed if I can figure out how to do it properly. I've tried [in order of desperation!]:
_functionPtr
_functionPtr.ToPointer() [as void* param]
_functionPtr.ToInt32() [as int param]
_stateChangeDelegate [as OnStateChangeDelegate param]
OnStateChange [as OnStateChangeDelegate param]
using CallingConvention.Cdecl for the delegate
adding static qualifier to variables and functions
changing signature of the callback (including removing the return value, changing the parameters to ints, modifying the number of parameters)
adding a level of indirection [by storing _functionPtr.ToInt32() in a block of memory allocated with Marshal.AllocCoTaskMem()]
In some cases the changes triggered different crash locations... like crashes in ntdll, or at 06B04F36. In most cases the crash is as described above - at 06B04F41.
When I attach IDA Pro to the process it looks like the address of my callback is going into EAX at 06B04F40, and the address that the COM object attempts to use has a fixed offset from that. For example:
EAX (correct address) = 000A1392
ECX (used address) = 0A1378B8
The last 4 digits of ECX are always 78B8.
So again, I think I'm not passing the delegate or function pointer correctly but I'm not sure how to do it. I guess the fact that the service is running in a WOW64 environment could also be having an impact.
My question: what would you suggest I do to (1) get more information about the problem and/or (2) solve the problem?
Keep in mind I don't have access to any source code except the full code for the C# service. I'm using the free version of IDA Pro so I don't seem to be able to do anything more useful than reverse to pseudo code or attach to the process and catch the crash exception. It is not possible to run the service from VS in debug mode so I really only have logging on that side... not that I think it would be much good as the problem is triggering in the unmanaged code where I don't have compilable/easily-readable source. Maybe I'm wrong?
Thank you sincerely for your advice!
Edit:
Well, after another day bashing my head against the problem I figured if I couldn't succeed from C# I would try and create a minimal C++ test application to do what the service has to do... and I was successful!
IAccessInterface : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE SetCallback(
/* [in] */ LPVOID pCallBack) = 0;
virtual HRESULT STDMETHODCALLTYPE SetDevice(
/* [in] */ char* context1,
/* [in] */ LPVOID context2,
/* [in] */ LPVOID context3) = 0;
virtual HRESULT STDMETHODCALLTYPE CloseDevice() = 0;
};
IAccessInterface* pInterface;
int __stdcall CallbackImpl(char* context, char* data)
{
printf("Callback succeeded!\r\n");
return 0;
}
void CleanUp(bool deviceOpen)
{
if (pInterface != NULL)
{
if (deviceOpen)
{
pInterface->SetCallback(NULL);
pInterface->CloseDevice();
}
pInterface->Release();
pInterface = NULL;
}
CoUninitialize();
}
int _tmain(int argc, _TCHAR* argv[])
{
GUID objClsid = GUID();
GUID interfaceIid = GUID();
CoInitialize(NULL);
int hr = CoCreateInstance(objClsid, 0, 1, interfaceIid, (void**)&pInterface);
if (!pInterface || !SUCCEEDED(hr))
{
CleanUp(false);
return 1;
}
LPVOID ptr = &callbackImpl;
LPVOID ptr2 = &ptr;
hr = pInterface->SetCallback(&ptr2);
if (!SUCCEEDED(hr))
{
CleanUp(false);
return 1;
}
char* context1 = "a_device_identifier";
hr = pInterface->SetDevice(context1, NULL, NULL);
if (!SUCCEEDED(hr))
{
CleanUp(false);
}
Sleep(30000); // give time for device to initialise and trigger callbacks (testing only)
// clean up
CleanUp(true);
return 0;
}
So now I just need to find a way to replicate the following three lines with equivalent C#:
LPVOID ptr = &CallbackImpl;
LPVOID ptr2 = &ptr;
hr = pInterface->SetCallback(&ptr2);
It seems unnecessary (even suspicious) that so many levels of indirection would be required. Maybe I haven't fully understood the disassembly. At this point the most important thing is that it works.
So any comments about how to achieve this from C# would be welcome!

String length in masm

I try to ouput the string length of hello in cmd screen using the following masm code.
I create a function called strlo to compute string length.
.486
.Model flat,Stdcall
option casemap :none ; case sensitive
include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
includelib \masm32\lib\kernel32.lib
include \masm32\include\masm32.inc
includelib \masm32\lib\masm32.lib
strlo PROTO :DWORD
.data
msg db "Hello",0
.data?
pr dd ?
.code
start:
invoke strlo,addr msg
strlo proc parm:DWORD
xor eax,eax
mov edi,parm
l1:
cmp byte ptr [edi] ,0
je l2
inc edi
inc eax
jmp l1
l2:
ret
strlo endp
invoke StdOut,eax
invoke ExitProcess,0
end start
When I run it, I get no output.
F:\masm32>len.exe
F:\masm32>
One problem is that you have the definition of strlo in the middle of your code. It will execute where it is defined. Instead you should move it to the end and let your main code look like this:
invoke strlo,addr msg
invoke StdOut,eax
invoke ExitProcess,0
Control begins at label "start" because you wrote "end start", then yields at "ret". "invoke StdOut,eax" and "invoke ExitProcess,0" never executed. To ouput the string length of hello in cmd screen you should alter like below:
strlo proc parm:DWORD
...
strlo endp
start:
invoke strlo,addr msg
invoke StdOut,eax
...

How do I get user input without using scanf in a console app?

I'm trying to allow users to simply hit Enter without typing anything, and use this to mean accepting a default value. scanf isn't doing what I want and the app still 'blocks': the next line of code doesn't run.
The only way is to actually type something THEN press Enter.
I tried using NSFileHandle and fileHandleWithStandardInput; however, it seems that the user is now forced to hit Ctrl-D to indicate EOF.
Someone suggested using fgets, but I cannot work out what to pass as 3rd parameter (of FILE* type). Tried stdin but it doesn't 'block'.
How do I accept input from a user, using Objective-C, and at the same time allow the user to simply hit Enter without being forced to type anything? How do I read a single line, even if that line is blank?
Assuming the code doesn't block and the next line runs immediately (as you seemed to indicate early in the question and in a comment), you have a common problem when mixing non-line-based and line-based input.
What happens is you have a newline left in the buffer, and fgets sees that, reads it, and returns, instead of doing what you really want: ignoring it, and then reading a line.
The solution is to simply do the ignoring part yourself, and then call fgets:
#include <stdio.h>
#include <string.h>
FILE* ignoreline(FILE* stream) {
for (int c; (c = fgetc(stream)) != EOF;) {
if (c == '\n') break;
}
return stream;
}
void example_use() {
char buf[1000];
ignoreline(stdin);
fgets(buf, sizeof buf, stdin);
// or, since it returns the stream, can be more compact:
fgets(buf, sizeof buf, ignoreline(stdin));
}
int main() { // error handling omitted
int n;
printf("Enter a number: ");
scanf("%d", &n);
char buf[1000];
printf("Enter a line: ");
ignoreline(stdin); // comment this line and compare the difference
fgets(buf, sizeof buf, stdin);
*strchr(buf, '\n') = '\0';
printf("You entered '%s'.\n", buf);
return 0;
}
Note that it is also common and encouraged to "pair" the ignoreline with the scanf (or other non-line-based input) to turn that into line-based input. You may want to modify it, in that case, so you can tell the difference between input of "42 abc" and "42" (in the "Enter a number" case). Some people just use fgets everywhere, then parse that line with sscanf, and while that works, it's not necessary.
I use getch(); in library conio.h
simply the program waits for any key to be pressed
If you're using Windows, you can use the ReadConsoleInput function (see MSDN for more on this) :
INPUT_RECORD keyin;
DWORD r;
while (ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE),&keyin,1,&r)) {
if (keyin.EventType!=KEY_EVENT) continue;
if (keyin.Event.KeyEvent.wVirtualKeyCode==VK_SPACE) break; ///use these VK codes to get any key's input
if (keyin.Event.KeyEvent.wVirtualKeyCode==VK_F1)
{
printf("You pressed F1\n");
}
if (keyin.Event.KeyEvent.wVirtualKeyCode==VK_F2)
{
printf("You pressed F2\n",);
}
}//end while loop
You don't need to hit enter after each key then.This works like a dream for me...
use getchar() to take input without using scanf function...