How do I fix an unhandled exception in my dll? - c++

Im writing an aimbot for a game called assault cube and I have written a function to grab all of the players in the game. Im currently trying to get the team of the player that my function gets, but for some weird reason I get an error.
The Error: Unhandled exception at 0x08ED66D0 (finalaimbot.dll) in ac_client.exe: 0xC0000005: Access violation reading location 0x000003CA.
This is really weird because the address im reading from is way higher than 0x3CA.
// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <windows.h>
#include <iostream>
#include <string>
DWORD EntityList = 0x50F4F8;
DWORD Player = *reinterpret_cast<int*>(0x50F4F4);
DWORD OnlinePlayers = 0x50F500;
DWORD MouseX = 0x40;
DWORD MouseY = 0x44;
DWORD HeadX = 0x4;
DWORD HeadY = 0x8;
DWORD HeadZ = 0xC;
DWORD Team = 0x3C2;
using namespace std;
struct vec3 {
float x, y, z;
};
float GetDistance3D(vec3 m_pos, vec3 en_pos)
{
float res = (float)(sqrt(((en_pos.x - m_pos.x) * (en_pos.x - m_pos.x)) + ((en_pos.y - m_pos.y) * (en_pos.y - m_pos.y)) + ((en_pos.z - m_pos.z) * (en_pos.z - m_pos.z))));
return res;
}
void aim(vec3 pos) {// function for aiming at a position
*reinterpret_cast<float*>(Player + MouseX) = pos.x;
*reinterpret_cast<float*>(Player + MouseY) = pos.y;
}
DWORD WINAPI MainThread(LPVOID lpArgs) {
while (true) {
int onlinePlayers = *reinterpret_cast<int*>(OnlinePlayers);
int myTeam = *reinterpret_cast<int*>(Player + Team);
vec3 MyPos;
MyPos.x = *reinterpret_cast<float*>(Player + HeadX);
MyPos.y = *reinterpret_cast<float*>(Player + HeadX);
MyPos.z = *reinterpret_cast<float*>(Player + HeadX);
if (onlinePlayers > 1) {
for (DWORD x = 0x4; x <= (0x4 * (onlinePlayers - 1)); x += 0x4) {
DWORD EnemyBase = *reinterpret_cast<int*>(EntityList + x);
DWORD EnemyTeam = *reinterpret_cast<int*>(EnemyBase + Team);
vec3 EnemyPos;
EnemyPos.x = *reinterpret_cast<float*>(EnemyBase + HeadX);
EnemyPos.y = *reinterpret_cast<float*>(EnemyBase + HeadY);
EnemyPos.z = *reinterpret_cast<float*>(EnemyBase + HeadZ);
float Distance = GetDistance3D(MyPos, EnemyPos);
if (EnemyTeam == myTeam) {
MessageBoxA(0, "Enemy is on your team", "Enemy Detected", 0);
}
else {
MessageBoxA(0, "Enemy is not on your team", "Enemy Detected", 0);
}
}
}
}
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
CreateThread(0, 0, MainThread, 0, 0, 0);
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}

Related

How to turn on display with mouse move but not with VK_SPACE

This code disables 1 display out of 2. The task is to turn it on not from VK_SPACE, but from mouse movement.
I tried to do it through WM_MOUSEMOVE, but so far nothing has worked. I don't really understand how this problem can be implemented.
If there is an opportunity to implement this topic, I will be very grateful.
#include <iostream>
#include <windows.h>
#include <vector>
#include <lowlevelmonitorconfigurationapi.h>
#include <windowsx.h>
#pragma comment(lib, "Dxva2.lib")
#define KEY_DOWN(key) ((::GetAsyncKeyState(key) & 0x80000) ? 1 : 0)
#define KEY_UP(key) ((::GetAsyncKeyState(key) & 0x80000) ? 0 : 1)
const BYTE PowerMode = 0xD6; // VCP Code defined in VESA Monitor Control Command Set (MCCS) standard
const DWORD PowerOn = 0x01;
const DWORD PowerOff = 0x04;
// Monitor description struct
struct MonitorDesc
{
HANDLE hdl;
DWORD power;
};
// Monitor enumeration callback
BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
std::vector<MonitorDesc>* pMonitors = reinterpret_cast<std::vector<MonitorDesc>*>(dwData);
DWORD nMonitorCount;
if (GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &nMonitorCount))
{
PHYSICAL_MONITOR* pMons = new PHYSICAL_MONITOR[nMonitorCount];
if (GetPhysicalMonitorsFromHMONITOR(hMonitor, nMonitorCount, pMons))
{
for (DWORD i = 0; i < nMonitorCount; i++)
{
MonitorDesc desc;
desc.hdl = pMons[i].hPhysicalMonitor;
pMonitors->push_back(desc);
}
}
delete[] pMons;
}
return TRUE;
}
// Switch monitor power
void MonitorSwitch(MonitorDesc& monitor, DWORD mode)
{
if (monitor.power == mode)
return;
SetVCPFeature(monitor.hdl, PowerMode, mode);
monitor.power = mode;
}
int main()
{
// Скрытие консоли
HWND hWnd;
AllocConsole();
hWnd = FindWindowA("ConsoleWindowClass", NULL);
ShowWindow(hWnd, 0);
std::vector<MonitorDesc> monitors;
EnumDisplayMonitors(NULL, NULL, &MonitorEnumProc, reinterpret_cast<LPARAM>(&monitors));
// Init
for (auto& monitor : monitors)
{
monitor.power = PowerOn;
}
// Here select the first one monitor as example
MonitorDesc targetMonitor = monitors[0];
while (1)
{
if (::GetAsyncKeyState('L') == -32767)
{
if (KEY_DOWN(VK_CONTROL) && KEY_DOWN(VK_MENU))
// turn off
if (targetMonitor.power == PowerOn)
MonitorSwitch(targetMonitor, PowerOff);
}
if (::GetAsyncKeyState(VK_SPACE) == -32767)
{
if (KEY_DOWN(VK_SPACE))
// turn on
MonitorSwitch(targetMonitor, PowerOn);
}
if (::GetAsyncKeyState('E') == -32767)
{
if (KEY_DOWN(VK_CONTROL))
return 0;
}
}
}
I use GetCursorPos to get the real-time mouse position and perform an energy-saving operation when the mouse is over the edge of a monitor.Here is my code,I commented the code in detail.
#include <iostream>
#include <windows.h>
#include <vector>
#include <lowlevelmonitorconfigurationapi.h>
#include <windowsx.h>
#pragma comment(lib, "Dxva2.lib")
#define KEY_DOWN(key) ((::GetAsyncKeyState(key) & 0x80000) ? 1 : 0)
#define KEY_UP(key) ((::GetAsyncKeyState(key) & 0x80000) ? 0 : 1)
const BYTE PowerMode = 0xD6; // VCP Code defined in VESA Monitor Control Command Set (MCCS) standard
const DWORD PowerOn = 0x01;
const DWORD PowerOff = 0x04;
// Monitor description struct
struct MonitorDesc
{
HANDLE hdl;
DWORD power;
};
// Monitor enumeration callback
BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
std::vector<MonitorDesc>* pMonitors = reinterpret_cast<std::vector<MonitorDesc>*>(dwData);
DWORD nMonitorCount;
if (GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &nMonitorCount))
{
PHYSICAL_MONITOR* pMons = new PHYSICAL_MONITOR[nMonitorCount];
if (GetPhysicalMonitorsFromHMONITOR(hMonitor, nMonitorCount, pMons))
{
for (DWORD i = 0; i < nMonitorCount; i++)
{
MonitorDesc desc;
desc.hdl = pMons[i].hPhysicalMonitor;
pMonitors->push_back(desc);
}
}
delete[] pMons;
}
return TRUE;
}
// Switch monitor power
void MonitorSwitch(MonitorDesc& monitor, DWORD mode)
{
if (monitor.power == mode)
return;
SetVCPFeature(monitor.hdl, PowerMode, mode);
monitor.power = mode;
}
int main()
{
// Скрытие консоли
HWND hWnd;
AllocConsole();
hWnd = FindWindowA("ConsoleWindowClass", NULL);
ShowWindow(hWnd, 1);
std::vector<MonitorDesc> monitors;
EnumDisplayMonitors(NULL, NULL, &MonitorEnumProc, reinterpret_cast<LPARAM>(&monitors));
// Init
for (auto& monitor : monitors)
{
monitor.power = PowerOn;
}
// Here select the first one monitor as example
MonitorDesc targetMonitor = monitors[0];
int currentMonitorID = 0; //need start this exe in monitors[0]
//Mouse position
LONG zx = -1;
LONG zy = -1;
POINT ptB = { 0, 0 };
while (1)
{
/*---------------------------------------------------------------*/
/*- - -*/
/*- - -*/
/*- - -*/
/*- monitors[0] - monitors[1] -*/
/*- - -*/
/*- - -*/
/*- - -*/
/*---------------------------------------------------------------*/
/* {1919,1079} */
LPPOINT xy = &ptB; //Location variables
GetCursorPos(xy); //Gets the current mouse position
//If the mouse moves, (i.e. the current coordinates change to print out the coordinates) print out the coordinates.
if ((zx != xy->x) || (zy != xy->y))
{
//Here you need to test the edge of your monitor[0]
//After Test, delete this and Hide the console by ShowWindow(hWnd, 0)
printf("x=%d,y=%d\n", xy->x, xy->y);
}
//The coordinate in the lower right corner of my monitor is {1919,1079}
if (xy->x > 1919 && currentMonitorID == 0)
{
currentMonitorID = 1;
MonitorSwitch(monitors[1], PowerOn);
MonitorSwitch(monitors[0], PowerOff);
}
else if ( xy->x <= 1919 && currentMonitorID == 1)
{
currentMonitorID = 0;
MonitorSwitch(monitors[0], PowerOn);
MonitorSwitch(monitors[1], PowerOff);
}
/*if (::GetAsyncKeyState('L') == -32767)
{
if (KEY_DOWN(VK_CONTROL) && KEY_DOWN(VK_MENU))
// turn off
if (targetMonitor.power == PowerOn)
MonitorSwitch(targetMonitor, PowerOff);
}
if (::GetAsyncKeyState(VK_SPACE) == -32767)
{
if (KEY_DOWN(VK_SPACE))
// turn on
MonitorSwitch(targetMonitor, PowerOn);
}*/
if (::GetAsyncKeyState('E') == -32767)
{
if (KEY_DOWN(VK_CONTROL))
return 0;
}
}
}

QueryWorkingSet always returning false

I'm trying to get the size of allocated are for a process, descriminated by image, private and mapped. I'm using QueryWorkingSet to get the Working Set Information and then the Working Set Block.
When i called it for the first time, the GetLastError method return 24 which is to be expected so the next time I call QueryWorkingSet I set a diferent size for the block but then im getting an error code of 998.
Am I using QueryWorkingSet wrong or Im getting the handle for the process with the wrong access rights or Im the resize is not enough?
#include "pch.h"
#include <Windows.h>
#include<WinDef.h>
#include <psapi.h>
#include <iostream>
typedef struct {
DWORD img;
DWORD map;
DWORD prv;
} CommitCounters, *PCommitCounters;
BOOL GetCommitCountersFromProcess(_In_ int pid, _Out_ PCommitCounters committedCounter ) {
int numberOfTries = 3;
SYSTEM_INFO si;
GetSystemInfo(&si);
DWORD pageSz = si.dwPageSize;
PSAPI_WORKING_SET_INFORMATION wsi, *pwsi;
pwsi = &wsi;
DWORD ws_size;
MEMORY_BASIC_INFORMATION mbi, *pmbi;
pmbi = &mbi;
HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
wsi.NumberOfEntries = 0;
QueryWorkingSet(processHandle, &wsi, sizeof(pwsi));
BOOL res = false;
committedCounter->img = 0;
committedCounter->map = 0;
committedCounter->prv = 0;
while (numberOfTries > 0) {
DWORD lastError = GetLastError();
//ERROR_BAD_LENGTH
if (lastError == 24) {
ws_size = sizeof(wsi) + sizeof(PSAPI_WORKING_SET_INFORMATION) + sizeof(PSAPI_WORKING_SET_BLOCK) * wsi.NumberOfEntries;
pwsi = (PSAPI_WORKING_SET_INFORMATION*) malloc(ws_size);
pwsi->NumberOfEntries = wsi.NumberOfEntries;
BOOL resQws = QueryWorkingSet(processHandle, &wsi, ws_size);
DWORD teste = sizeof(wsi);
if (resQws) {
for (int i = 0; i < pwsi->NumberOfEntries; i++) {
PSAPI_WORKING_SET_BLOCK ws_block = pwsi->WorkingSetInfo[1];
//Access page information.
SIZE_T size = VirtualQuery((LPCVOID*)ws_block.VirtualPage, &mbi, 1);
if (size != 0 && pmbi ->State == 0x1000) {
switch (pmbi->Type)
{
case 0x1000000: // MEM_IMAGE
committedCounter->img += pageSz;
break;
case 0x40000: //MEM_MAPPED
committedCounter->map += pageSz;
break;
case 0x20000: //MEM_PRIVATE
committedCounter->prv += pageSz;
break;
}
}
else if (size == 0) {
return res;
}
}
CloseHandle(processHandle);
res = true;
return res;
}
free(pwsi);
}
numberOfTries--;
}
CloseHandle(processHandle);
return false;
}
You have a typo in your code. Just change:
BOOL resQws = QueryWorkingSet(processHandle, &wsi, ws_size);
to:
BOOL resQws = QueryWorkingSet(processHandle, pwsi, ws_size);
And then the call succeeds.
There may be further errors but I did not investigate those.

DirectInput8 Hooking Issue

I'm just beginning with directx/directinput development and I'm running some tests with some code samples I've found online. Anyway, I want to hook an application that uses dinput8 to send my own custom input to the forewindow and I'm working with this base to do it:
// dllmain.cpp : Defines the entry point for the DLL application.
#define _CRT_SECURE_NO_WARNINGS // ignore some warnings...
#define _CRT_NON_CONFORMING_SWPRINTFS // ...
#include "stdio.h"
#include <windows.h>
#include "detours.h"
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <time.h>
#include "dinput.h"
#pragma comment(lib, "detours.lib")
#pragma comment(lib, "user32.lib")
typedef HRESULT(__stdcall* GetDeviceState_t)(LPDIRECTINPUTDEVICE, DWORD, LPVOID *);
HRESULT __stdcall hkGetDeviceState(LPDIRECTINPUTDEVICE pDevice, DWORD cbData, LPVOID *lpvData);
DWORD Base = 0;
DWORD GetDeviceStateOffset = 0x7670; // This is the offset of GetDeviceState from DInput8.dll
// Open IDA and Import the DInput8.dll, then look in the Functions Table for DirectInput8Create
// There is an Address (1000XXXX or 0CXXXXX) - copy it and save it for later
// Then take a look for CDIDev_GetDeviceState and copy that address too
// Now substract the Address from CDIDev_GetDeviceState from DIrectInput8Create and u'll get your offset
HANDLE tmpHandle = NULL;
HMODULE hModDInput8 = NULL;
DWORD dwGetDeviceState = NULL;
FARPROC dwDirectInput8Create = NULL;
struct MyKeys
{
BYTE Key;
DWORD StartTime;
DWORD TTL;
BOOLEAN isDown;
};
MyKeys KeyBuffer[256];
DWORD WINAPI HookThread();
void add_log(char* format, ...);
void SendKeyDInput(byte DIK_, DWORD time);
GetDeviceState_t pGetDeviceState;
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
add_log("==========LOG START==========");
add_log("DLL Attached");
add_log("Creating Thread...");
tmpHandle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&HookThread, 0, 0, 0);
if (!tmpHandle)
{
add_log("ThreadCreation Failed!");
}
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
DWORD WINAPI HookThread()
{
Base = (DWORD)GetModuleHandleA("test.exe");
add_log("Thread Created");
add_log("game.exe Base: %x", Base);
while (!hModDInput8)
{
add_log("Searching dinput8.dll...");
hModDInput8 = GetModuleHandle(L"dinput8.dll");
Sleep(100);
}
add_log("Found dinput8.dll: %x !", hModDInput8);
while (!dwDirectInput8Create)
{
add_log("Searching GetDeviceState...");
dwDirectInput8Create = GetProcAddress(hModDInput8, "DirectInput8Create");
Sleep(100);
}
add_log("Found DirectInput8Create: %x !", dwDirectInput8Create);
dwGetDeviceState = (DWORD)((DWORD)dwDirectInput8Create - GetDeviceStateOffset);
add_log("GetDevicestate is here (DirectInput8Create - %x): %x", GetDeviceStateOffset, dwGetDeviceState);
add_log("Hooking GetDeviceState...");
pGetDeviceState = (GetDeviceState_t)DetourAttach(&(PVOID&)dwGetDeviceState, (PBYTE)hkGetDeviceState);
add_log("Initiate Keyboard Buffer...");
//initiate buffer
for (int i = 0; i < 256; i++)
{
KeyBuffer[i].isDown = false;
KeyBuffer[i].Key = 0;
KeyBuffer[i].StartTime = 0;
KeyBuffer[i].TTL = 0;
}
add_log("Going into Main Loop...");
while (true)
{
if (GetAsyncKeyState(VK_F5) & 1 << 15)
{
// We check the Most Sigificant Bit from VK_F5 (F5) whilst we shifted it with 15 bits to left 1
// and then a small delay so we have enaught time to release the key
add_log("F5 pushed attempting to sendkey");
// Sleep a short time so we have time to release the F5 Key
Sleep(500);
// Now we send a A Key with 1 sec time to our Game
SendKeyDInput(DIK_A, 1000);
}
}
return 0;
}
void SendKeyDInput(byte DIK, DWORD time)
{
KeyBuffer[DIK].Key = DIK;
KeyBuffer[DIK].TTL = time;
KeyBuffer[DIK].StartTime = GetTickCount();
}
HRESULT __stdcall hkGetDeviceState(LPDIRECTINPUTDEVICE lpDevice, DWORD cbData, LPVOID *lpvData)
{
HRESULT hResult = DI_OK;
static BYTE buffer[256];
int key_count = 0;
for (int i = 0; i<256; i++)
{
if (KeyBuffer[i].Key != 0 && KeyBuffer[i].TTL>0 && KeyBuffer[i].StartTime != 0)
{
if (GetTickCount() > KeyBuffer[i].StartTime + KeyBuffer[i].TTL && KeyBuffer[i].isDown)
{
KeyBuffer[i].Key = 0;
KeyBuffer[i].StartTime = 0;
KeyBuffer[i].TTL = 0;
KeyBuffer[i].isDown = false;
buffer[KeyBuffer[i].Key] = 0;
}
else {
KeyBuffer[i].isDown = true;
buffer[KeyBuffer[i].Key] = 0x80;
key_count += 1;
add_log("Sending Key %x for %i milliseconds count: %i", KeyBuffer[i].Key, KeyBuffer[i].TTL, key_count);
}
}
}
if (key_count != 0)
{
cbData = 256;
memcpy(lpvData, buffer, cbData);
}
else {
hResult = pGetDeviceState(lpDevice, cbData, lpvData);
}
return hResult;
}
//Creates a Logfile in the Game Directory
void add_log(char* format, ...)
{
HANDLE filehandle;
DWORD dwReadBytes;
char buffer[2048];
char writebuffer[2048];
va_list args;
va_start(args, format);
vsprintf_s(buffer, format, args);
filehandle = CreateFile(L"Log.txt", GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0);
SetFilePointer(filehandle, 0, 0, FILE_END);
sprintf_s(writebuffer, 2048, "Log Added: %s\r\n", buffer);
WriteFile(filehandle, writebuffer, strlen(writebuffer), &dwReadBytes, 0);
CloseHandle(filehandle);
}
The only issue in this code is when I attempt to send input, it doesn't go through. I've gotten some help and narrowed down a solution to this, which was: "Try GetDeviceState hk just memset(buffer, 0, size) or SendDeviceData". I've searched around a bit and I've been unable to find more on how to implement this solution and I'm stumped.
Could one of you kind people show me how I could use this information to fix this base? I'd be extremely grateful, thanks.

Visual C++ Debug Assertion Fail

When Ever I compile my program it say "Debug Assertion Failed".
And when I click ignore twice my app shows up.
How can I fix it?
The whole code is below in case you want to test it for your self. The app increases in number as the scroll bar is moved to the right and decreases as the scroll bar is moved to the left. But my main problem is the debug assertion failed. If you can please post the part of the code that has problem and how I can fix it or fix it and post the code. Is there any way to get rid of that run time error with out using a try and catch. I mean to fix that problem please. This is a project and I have only a week and a half to do it. If you can help me with this project your help would be greatly appreciated. I am fairly new to visual c++. Part of the error is:
Program E:\BHCCHardwareStore\Debug\BHCCHardwareStore.exe FIle:f\dd\vctools\vc7libs\ship\atlmfc\src\mfc\appcore.cpp Line: 196. For information on how your program can cause an assertion failure see the Visual C++ documentation on asserts.
(Press Retry to debug the application).
Now when I click ignore it kind of displays the app perfectly fine. And the app seems to work just fine. How can I fix this error This code is not the entire code I am cutting and pasting?
#include "stdafx.h"
#include <strstream>
#include <afxwin.h>
#include <string.h>
const int IDC_SB1 = 100;
const int IDC_CS1 = 101;
const int IDC_CS2 = 102;
const int IDC_BUTTON = 103;
const int MIN_RANGE = 0;
const int MAX_RANGE = 100;
class CApp :public CWinApp
{
public:
virtual BOOL InitInstance();
};
CApp App;
class CSource :public CFrameWnd
{
CScrollBar*sb1;
CStatic* cs1;
CStatic* cs2;
CButton* button;
public:
CSource();
afx_msg void OnHScroll(UINT nSBCode,
UINT nPos, CScrollBar* pSccrollBar);
afx_msg void handleButton();
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(CSource, CFrameWnd)
ON_WM_HSCROLL()
ON_BN_CLICKED(IDC_BUTTON, handleButton)
END_MESSAGE_MAP()
//Window cONSTRUCTOR
CSource::CSource()
{
}
void CSource::OnHScroll(UINT nSBCode,
UINT nPos, CScrollBar* pScrollBar)
{
int pos, dividend = 0, holder = 0, x = 0;
char array[9];
//;
pos = pScrollBar->GetScrollPos();
switch (nSBCode)
{
case SB_LINEUP:
pos -= 1;
break;
case SB_LINEDOWN:
pos += 1;
break;
case SB_PAGEUP:
pos -= 10;
break;
case SB_PAGEDOWN:
pos += 10;
break;
case SB_TOP:
pos = MIN_RANGE;
break;
case SB_BOTTOM:
pos = MAX_RANGE;
break;
case SB_THUMBTRACK:
pos = nPos;
break;
default:
return;
}
if (pos < MIN_RANGE)
pos = MIN_RANGE;
else if (pos > MAX_RANGE)
pos = MAX_RANGE;
sb1->SetScrollPos(pos, TRUE);
//Set the labels to the new values
char s[100];
TCHAR s1[100];
std::ostrstream ostr(s, 100);
ostr << "Decimal Value = " << pos << std::ends;
for (int i = 0; i < 100; i++){
s1[i] = (TCHAR) s[i];
}
SetDlgItemText(IDC_CS1, s1);
ostr.seekp(std::ios::beg);
dividend = pos;
for (int y = 0; y < 9; y++)
array[y] = '0';
int remainder = dividend % 2;
int quotient = dividend / 2;
array[x] = (char)(remainder + 48);
do
{
remainder = quotient % 2;
quotient = quotient / 2;
array[++x] = (char)(remainder + 48);
} while (quotient != 0);
array[8] = '\0';
ostr << "Binary Value = " << _strrev(array) << std::ends;
SetDlgItemText(IDC_CS2, s1);
}
void CSource::handleButton()
{
int result;
result = MessageBox(_T("Are you sure?"), _T("Exiting"),
MB_ICONQUESTION | MB_YESNO);
if (result == IDYES)
{
Beep(1000, 100);
DestroyWindow();
}
else
Beep(200, 100);
}
//Initialize the application and the main window
BOOL CApp::InitInstance()
{
m_pMainWnd = new CSource();
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE;
}
Your code (in VS2013) produces assertion in MFC code:
BOOL CWnd::ShowWindow(int nCmdShow)
{
ASSERT(::IsWindow(m_hWnd) || (m_pCtrlSite != NULL));
From your call:
m_pMainWnd->ShowWindow(m_nCmdShow);
You must create your window first, before you can show it.

How to inject individual touches on Windows 8.1 C++

I have been trying to inject individual contacts (Touch events) on Windows 8. I'm using the InjectTouchInput described here, so I'm able to inject two contacts with the next code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
#include <windows.h>
using namespace std;
class calculate
{
POINTER_TOUCH_INFO contact[2];
public:
calculate(int m);
void setDots(long x, long y, long x2, long y2, int opt, string num_dots);
};
calculate::calculate(int m)
{
}
void calculate::setDots(long x, long y, long x2, long y2, int opt, string num_dots)
{
switch (opt)
{
case 0:
InitializeTouchInjection(2, TOUCH_FEEDBACK_INDIRECT);
memset(&contact[0], 0, sizeof(POINTER_TOUCH_INFO));
memset(&contact[1], 0, sizeof(POINTER_TOUCH_INFO));
contact[0].pointerInfo.pointerType = PT_TOUCH;
contact[0].pointerInfo.pointerId = 0; //Id 0 for contact 0
contact[0].pointerInfo.ptPixelLocation.y = y;
contact[0].pointerInfo.ptPixelLocation.x = x;
contact[0].touchFlags = TOUCH_FLAG_NONE;
contact[0].touchMask = TOUCH_MASK_CONTACTAREA | TOUCH_MASK_ORIENTATION | TOUCH_MASK_PRESSURE;
contact[0].orientation = 90;
contact[0].pressure = 32000;
contact[0].rcContact.top = contact[0].pointerInfo.ptPixelLocation.y - 2;
contact[0].rcContact.bottom = contact[0].pointerInfo.ptPixelLocation.y + 2;
contact[0].rcContact.left = contact[0].pointerInfo.ptPixelLocation.x - 2;
contact[0].rcContact.right = contact[0].pointerInfo.ptPixelLocation.x + 2;
contact[1].pointerInfo.pointerType = PT_TOUCH;
contact[1].pointerInfo.pointerId = 1; //Id 0 for contact 1
contact[1].pointerInfo.ptPixelLocation.y = y2;
contact[1].pointerInfo.ptPixelLocation.x = x2;
contact[1].touchFlags = TOUCH_FLAG_NONE;
contact[1].touchMask = TOUCH_MASK_CONTACTAREA | TOUCH_MASK_ORIENTATION | TOUCH_MASK_PRESSURE;
contact[1].orientation = 90;
contact[1].pressure = 32000;
contact[1].rcContact.top = contact[1].pointerInfo.ptPixelLocation.y - 2;
contact[1].rcContact.bottom = contact[1].pointerInfo.ptPixelLocation.y + 2;
contact[1].rcContact.left = contact[1].pointerInfo.ptPixelLocation.x - 2;
contact[1].rcContact.right = contact[1].pointerInfo.ptPixelLocation.x + 2;
break;
case 1:
contact[0].pointerInfo.ptPixelLocation.y = y;
contact[0].pointerInfo.ptPixelLocation.x = x;
contact[1].pointerInfo.ptPixelLocation.y = y2;
contact[1].pointerInfo.ptPixelLocation.x = x2;
contact[0].pointerInfo.pointerFlags = POINTER_FLAG_DOWN | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT;
contact[1].pointerInfo.pointerFlags = POINTER_FLAG_DOWN | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT;
break;
case 2:
/*if I inject this flag to first contact [0], both points stopped, but I'm able to inject this flag to the second contact [1] and all is OK*/
//contact[0].pointerInfo.pointerFlags = POINTER_FLAG_UP;
contact[0].pointerInfo.pointerFlags = POINTER_FLAG_UPDATE | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT;
contact[1].pointerInfo.pointerFlags = POINTER_FLAG_UPDATE | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT;
//contact[1].pointerInfo.pointerId = 0;
//contact[0].pointerInfo.pointerId = 1;
contact[0].pointerInfo.ptPixelLocation.x =x;
contact[0].pointerInfo.ptPixelLocation.y =y;
contact[1].pointerInfo.ptPixelLocation.x =x2;
contact[1].pointerInfo.ptPixelLocation.y =y2;
//num_dots = "single";
break;
case 3:
contact[0].pointerInfo.pointerFlags = POINTER_FLAG_UP;
contact[1].pointerInfo.pointerFlags = POINTER_FLAG_UP;
break;
}
bool s;
//check how many points to inject
if(num_dots == "single")
s = InjectTouchInput(1, contact);
else
s = InjectTouchInput(2, contact);
if(!s)
{
LPWSTR str = new wchar_t[255];
auto t = GetLastError();
wsprintf(str, L"error: %d\n", t);
OutputDebugString(str);
wsprintf(str, L" action: %d\n", opt);
OutputDebugString(str);
}
else
{
LPWSTR str = new wchar_t[255];
auto t = GetLastError();
wsprintf(str, L"action %d\n", opt);
OutputDebugString(str);
}
if(opt == 2)
Sleep(20);
}
int c =0;
int
WINAPI WinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nShowCmd)
{
bool g = true;
POINT ipoint;
POINT point;
calculate set(0);
if (GetCursorPos(&ipoint))
set.setDots(ipoint.x, ipoint.y, 0,0,0, "single");//initialize both points
do
{
if (GetCursorPos(&point)) {
//stop the loop pressing right click
if((GetKeyState(VK_RBUTTON) & 0x100) != 0)
g = false;
if((GetKeyState(VK_LBUTTON) & 0x100) != 0)
{
if(c<1)
{
if((GetKeyState(VK_LSHIFT) & 0x100) != 0)//injecting DOWN event
set.setDots(point.x, point.y, point.x - 50, point.y + 50, 1, "two");
else
set.setDots(point.x, point.y, 0, 0, 1, "single");
}
else
{
if((GetKeyState(VK_LSHIFT) & 0x100) != 0)//injecting UPDATE event (on move)
set.setDots(point.x, point.y, point.x - 50, point.y + 50, 2, "two");
else
set.setDots(point.x, point.y, 0,0,2, "single");
}
c++;
}
else
{
/*if((GetKeyState(VK_LSHIFT) & 0x100) != 0)
set.setDots(0,0,0,0,3, "two");
else
set.setDots(0,0,0,0,3, "single");*/
c = 0;
}
}
} while (g);
}
So, with this code, I'm able to inject one or two touches (if shift key is pressed), and draw on paint using paint brushes. But when I try to inject individual events for each contact, for example contact[0].pointerInfo.pointerFlags = POINTER_FLAG_UP;
contact[1].pointerInfo.pointerFlags = POINTER_FLAG_UPDATE | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT; both contacts stop, even when I try changing their ids, or changing the number of points to inject.
The above code is just an example, but I have tried using different flags for each contact without success :(
My goal is be able to inject two points, with individual events each one, and if first contact[0] has an UP event, the second contact should still running without stop the process...So, how can I inject individual contacts (touches) with different events each one?
Thank you!