My Own Personal MFC - visual-c++

I can't seem to find this on msdn been searching for a bit (described below).
Please forgive the amount of code posted, I will paste in order. You can really skip most of it. But I just want to put it all out there so my request is clear.
Lets say I wanted to make a really simple MFC. So I have the following abstract and concrete classes (pasted below) that I want in my really crappy framework.
I am also assuming (though not implemented yet) that WinMain will call a users defined main function (like Qt). What do I need to do so I can reuse my code in every other small crappy Win32 program I try to write. To be more clear, I am wondering if I compile it into a DLL, or a Library. If so how do I go about doing this? How do you include a WinMain function in a DLL?
#ifndef IAPPLICATION_H_
#define IAPPLICATION_H_
#include <Windows.h>
namespace nApplication
{
class IController;
class IWindow;
class IApplication
{
public:
virtual int Run( ) = 0;
virtual HINSTANCE gethInstance( ) = 0;
virtual int getnCmdShow( ) = 0;
virtual IController* getMainControl( ) = 0;
protected:
IWindow *main_window;
IController *main_control;
private:
virtual int MessageLoop() = 0;
};
}
#endif /* IAPPLICATION */
-
#ifndef APPLICATION_H_
#define APPLICATION_H_
#include <Windows.h>
#include "IApplication.h"
#include "IWindow.h"
#include "IController.h"
#include "Controller.h"
namespace nApplication
{
class Application : public IApplication
{
public:
Application( HINSTANCE hInstance, int nCmdShow );
virtual ~Application( );
virtual int Run( );
virtual int getnCmdShow( ) { return mnCmdShow; }
virtual HINSTANCE gethInstance( ) { return mhInstance; }
virtual IController* getMainControl( ) { return main_control; }
private:
int mnCmdShow;
HINSTANCE mhInstance;
int MessageLoop();
Application( Application &app );
Application& operator= ( const Application &app );
};
}
#endif /* IAPPLICATION */
-
#include "Application.h"
#include "MainWindow.h"
namespace nApplication
{
Application::Application( HINSTANCE hInstance, int nCmdShow )
: mhInstance( hInstance ), mnCmdShow( nCmdShow )
{
}
Application::~Application( )
{
}
int Application::Run( )
{
main_window = new MainWindow( this );
main_control = new Controller( this );
main_window->Init( );
main_window->Display( );
MessageLoop( );
delete main_window;
return 0;
}
int Application::MessageLoop()
{
MSG msg;
while(GetMessage(&msg, NULL, 0, 0) != 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
}
-
#ifndef IWINDOW_H_
#define IWINDOW_H_
#include <Windows.h>
#include "IController.h"
namespace nApplication
{
class IWindow
{
public:
virtual void Init() = 0;
virtual void Display( ) = 0;
private:
};
}
#endif /* IWINDOW_H_ */
-
#ifndef MAINWINDOW_H_
#define MAINWINDOW_H_
#include <windows.h>
#include "IWindow.h"
#include "IController.h"
#include "IApplication.h"
namespace nApplication
{
class MainWindow : public IWindow
{
public:
MainWindow( IApplication *iApp);
~MainWindow();
void Init();
void Display( );
private:
WNDCLASSEX wc;
HWND hWnd;
IApplication *iApp;
};
}
#endif //MAINWINDOW_H_
-
#include "MainWindow.h"
namespace nApplication
{
namespace
{
LRESULT CALLBACK MainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
HDC hDC;
PAINTSTRUCT ps;
static IController *cntrl;
cntrl = (IController*)::GetWindowLongPtr(hWnd, GWL_USERDATA);
if(uMsg == WM_NCCREATE)
{
cntrl = (IController*)(((CREATESTRUCT*)lParam)->lpCreateParams);
::SetWindowLongPtr(hWnd, GWL_USERDATA, (LONG_PTR)cntrl);
cntrl->CheckStatus();
return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
}
switch(uMsg)
{
case WM_CREATE:
{
}
case WM_PAINT:
{
hDC = BeginPaint( hWnd, &ps );
TextOut( hDC, 10, 10, TEXT("Hello, Windows!"), 15 );
EndPaint( hWnd, &ps );
return 0;
}
case WM_DESTROY:
{
PostQuitMessage( 0 );
return 0;
}
default:
{
return DefWindowProc( hWnd, uMsg, wParam, lParam );
}
}
}
}
MainWindow::MainWindow( IApplication* iApp ) : iApp( iApp )
{
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = MainWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = iApp->gethInstance( );
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = TEXT( "GenericAppMenu");
wc.lpszClassName = TEXT( "myWindowClass" );
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
}
MainWindow::~MainWindow()
{
}
void MainWindow::Init()
{
if( !RegisterClassEx(&wc) )
{
MessageBox(NULL, TEXT( "Window Registration Failed!" ), TEXT( "Error!" ), MB_ICONEXCLAMATION | MB_OK);
exit(0);
}
}
void MainWindow::Display( )
{
hWnd = ::CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("myWindowClass"),
TEXT("The title of my window"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
240, 120, NULL, NULL, iApp->gethInstance( ), iApp->getMainControl( ) );
if(hWnd == NULL)
{
::MessageBox( NULL, TEXT( "Window Creation Failed!" ),
TEXT( "Error!" ), MB_ICONEXCLAMATION | MB_OK );
exit(0);
}
::ShowWindow( hWnd, iApp->getnCmdShow( ) );
::UpdateWindow(hWnd);
}
}
-
#ifndef ICONTROLLER_H_
#define ICONTROLLER_H_
#include <windows.h>
namespace nApplication
{
class IController
{
public:
virtual int CheckStatus() = 0;
};
}
#endif ICONTROLLER_H_
-
#ifndef CONTROLLER_H_
#define CONTROLLER_H_
#include <windows.h>
#include "IController.h"
#include "IApplication.h"
namespace nApplication
{
class Controller : public IController
{
public:
Controller( IApplication *iApp );
virtual ~Controller();
virtual int CheckStatus();
private:
Controller( Controller &c );
Controller& operator= ( Controller &c );
IApplication *iApp;
};
}
#endif //CONTROLLER_H_
-
#include "Controller.h"
namespace nApplication
{
Controller::Controller( IApplication *iApp ) : iApp( iApp )
{
}
Controller::~Controller()
{
}
int Controller::CheckStatus()
{
return 0;
}
}
-
#include <windows.h>
#include "Application.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
nApplication::Application app( hInstance, nCmdShow );
return app.Run( );
}
-
main.exe : main.cpp
cl /EHsc main.cpp Application.cpp Controller.cpp MainWindow.cpp user32.lib gdi32.lib
del *.obj
#/link /SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup

If you are making a library, you don't have a WinMain, you have a DllMain for dynamic libraries, or nothing for static libraries.
In your case, you'd need to export all the classes functionality from your dll, then in any apps that use your library, you'd include the headers of your project and link to the .lib of the library, then have this in your app where you need the GUI functionality:
nApplication::Application app( hInstance, nCmdShow );
return app.Run( );
Of course this ignores all the side details like registering event callbacks and setup along those lines, however Qt is free and open source, you you might want to look into that before reinventing the wheel, or to help make your own wheel a little rounder.

Related

(.Net )API Hooking: Why my implemented IEnumWbemClassObject->Next() hang at original Next

I want to hook native code to do some cool things:
var wql=new WqlObjectQuery(queryString);
using(var searcher =new ManagementObjectSearcher(scope,wql))
{
using(var records=searcher.Get())
{
**foreach(var record in records)** //This is where I want to hook
{
//do something
}
}
}
By digging into https://referencesource.microsoft.com/ , I find .Net send WQL string to WMINet_Util.dll ExecQueryWmi() . By using MS-Detours , I succeed in outputing passed-in WQL.
To control the enumeration , I implemented my IEnumWbemClassObject & IWbemClassObject.
When ExecQueryWmi() is called , I redirect the pointer to pointer to refer to my IEnumWbemClassObject .
In implementation of IEnumWbemClassObject::Next , I also edirect the pointer to pointer to refer to my IWbemClassObject.
But the reality is ,my implemented IEnumWbemClassObject->Next() hang at original Next() , it never go to next line
I can't figure out why . Could anyone help ?
Below is my code ******************************
// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include <stdio.h>
#include <strsafe.h>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <mutex>>
#include<fstream>
#include <Windows.h>
#include <comdef.h>
#include <WbemIdl.h>
#include <comdef.h>
#include <comutil.h>
#include "detours.h"
#include "ImpIEnumWbemClassObject.h"
#pragma comment(lib, "comsuppw.lib")
using namespace std;
std::mutex g_mutex;
static bool unloaded = false;
static LONG dwSlept = 0;
#pragma region Function Pre-definition
std::string WChar2Ansi(LPCWSTR pwszSrc);
std::wstring StringToWString(const std::string& s);
void WINAPI log(string& _str);
void WINAPI log(const char* log, DWORD _size);
#pragma endregion
#pragma region WMI
//forum.exetools.com/showthread.php?t=14432
//unknowncheats.me/forum/c-and-c/244372-changing-gpu-info-using-ms-detours-3-0-a.html
typedef HRESULT(__stdcall* PWMINet_Util_ExecQueryWmi) ( BSTR strQueryLanguage,BSTR strQuery,long lFlags,IWbemContext* pCtx,IEnumWbemClassObject** ppIEnumWbemClassObject,DWORD authLevel,DWORD impLevel,IWbemServices* pCurrentNamespace,BSTR strUser,BSTR strPassword,BSTR strAuthority);
PWMINet_Util_ExecQueryWmi TrueExecQueryWmi = NULL;
HRESULT(__stdcall MyExecQueryWmi) (BSTR strQueryLanguage, BSTR strQuery, long lFlags,
IWbemContext* pCtx, IEnumWbemClassObject** ppIEnumWbemClassObject, DWORD authLevel,
DWORD impLevel, IWbemServices* pCurrentNamespace, BSTR strUser,
BSTR strPassword, BSTR strAuthority)
{
if (TrueExecQueryWmi==NULL)
{
log("NO TrueExecQueryWmi()",32);
return WBEM_E_FAILED;
}
log((string("\r\n WMI MyExecQueryWmi() is called. language =") + _com_util::ConvertBSTRToString(strQueryLanguage) + " strQuery =" + _com_util::ConvertBSTRToString(strQuery) + "\r\n").c_str(), 256);
HRESULT result=TrueExecQueryWmi(strQueryLanguage,strQuery,lFlags,pCtx,ppIEnumWbemClassObject,authLevel,impLevel,pCurrentNamespace,strUser,strPassword,strAuthority);
if (string(_com_util::ConvertBSTRToString(strQuery)).find("MSFT_PhysicalDisk")!=string::npos)
{
log("\r\MSFT_PhysicalDisk found\r\n",64);
ImpIEnumWbemClassObject* myImpIEnumWbemClassObject=new ImpIEnumWbemClassObject(*ppIEnumWbemClassObject);
(*ppIEnumWbemClassObject) = myImpIEnumWbemClassObject;
log("\r\MSFT_PhysicalDisk redirected\r\n", 64);
}
return result;
}
#pragma endregion
void split(const std::string& s,
std::vector<std::string>& sv,
const char delim = ' ') {
sv.clear();
std::istringstream iss(s);
std::string temp;
while (std::getline(iss, temp, delim)) {
sv.emplace_back(std::move(temp));
}
return;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
LONG error=0;
HMODULE hMod=NULL;
string str;
if (DetourIsHelperProcess()) {
return TRUE;
}
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
str = string("\r\nlast error when DLL_PROCESS_ATTACH starts=") + to_string(GetLastError()) + "\r\n";
log(str.c_str(), str.length());
LoadLibraryA("c:\\windows\\system32\\wbem\\fastprox.dll");
LoadLibraryA("C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\WMINet_Utils.dll");
DetourRestoreAfterWith();
log("simple" DETOURS_STRINGIFY(DETOURS_BITS) ".dll:"
" Starting.\n",128);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
log("aaaaaaaaaaaaa \n",32);
//DetourAttach(&(PVOID&)TrueSleepEx, TimedSleepEx
if (GetModuleHandleA("fastprox.dll")==NULL)
{
char exe[MAX_PATH];
GetModuleFileNameA(NULL,exe,MAX_PATH);
log((string("NO fastprox.dll loaded by ")+exe).c_str(),MAX_PATH);
}
else
{
if (GetModuleHandleA("WMINet_Utils.dll") == NULL)
{
char exe[MAX_PATH];
GetModuleFileNameA(NULL, exe, MAX_PATH);
log((string("NO WMINet_Utils.dll loaded by ") + exe).c_str(), MAX_PATH);
}
else
{
TrueExecQueryWmi = (PWMINet_Util_ExecQueryWmi)DetourFindFunction("WMINet_Utils.dll", "ExecQueryWmi");
if (TrueExecQueryWmi==NULL)
{
log("NO ExecQueryWmi found in WMINet_Utils.dll",128);
}
else {
DetourAttach(&(PVOID&)TrueExecQueryWmi, (LPBYTE)MyExecQueryWmi);
}
}
//DetourAttach(&(PVOID&)TrueGetTickCount, MyTickCount);
error = DetourTransactionCommit();
log("bbbbbbbbbbbb \n",32);
if (error == NO_ERROR) {
log("simple" DETOURS_STRINGIFY(DETOURS_BITS) ".dll:"
"Detoured() Succeed.\n",128);
}
else {
string s_err = string("simple") + DETOURS_STRINGIFY(DETOURS_BITS) + ".dll Error with DetourAttach() " + std::to_string(error);
log(s_err);
}
str = string("\r\nDetour attachment is DONE. last error when DLL_PROCESS_ATTACH ends=") + to_string(GetLastError()) + "\r\n";
log(str.c_str(), str.length());
SetLastError(0);
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
log("\r\n DLL_PROCESS_DETACH is called ,reason is ",64);
if (lpReserved==NULL)
{
log("loaded unsuccessfully or reference count==0 \r\n",128);
fflush(stdout);
log("loaded unsuccessfully or reference count==0 \r\n",128);
}
else {
log("process is terminating",64);
fflush(stdout);
log("process is terminating",64);
}
if (!unloaded)
{
unloaded = true;
log("DLL_PROCESS_DETACH 1st \r\n",32);
fflush(stdout);
return TRUE;
}
{
log("DLL_PROCESS_DETACH again \r\n",32);
fflush(stdout);
return TRUE;
}
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
if (TrueExecQueryWmi!=NULL)
{
DetourDetach(&(PVOID&)TrueExecQueryWmi, (LPBYTE)MyExecQueryWmi);
}
error = DetourTransactionCommit();
log("simple" DETOURS_STRINGIFY(DETOURS_BITS) ".dll:"
" Removed SleepEx() (result=%d), slept %d ticks.\r\n", dwSlept);
fflush(stdout);
break;
}
SetLastError(0);
return TRUE;
}
void WINAPI log(string& _str)
{
log(_str.c_str(),_str.length());
}
void WINAPI log(const char* log, DWORD _size)
{
g_mutex.lock();
BOOL bErrorFlag = FALSE;
DWORD dwBytesWritten = 0;
HANDLE hfile = NULL;
ofstream fout;
ifstream fin;
fin.open(logPath);
fout.open(logPath, ios::app);
if (fin.is_open())
fout << log;
fin.close();
fout.close();
g_mutex.unlock();
}
//wstring to string
std::string WChar2Ansi(LPCWSTR pwszSrc)
{
int nLen = WideCharToMultiByte(CP_ACP,0,pwszSrc,-1,NULL,0,NULL,NULL);
if (nLen<=0)
{
log("Fail in WChar2Ansi()",32);
return std::string("");
}
char* pszDst = new char[nLen];
if (NULL==pszDst)
{
log("Fail in WChar2Ansi()", 32);
return std::string("");
}
WideCharToMultiByte(CP_ACP,0,pwszSrc,-1,pszDst,nLen,NULL,NULL);
pszDst[nLen-1] = 0;
std::string strTemp(pszDst);
delete[] pszDst;
return strTemp;
}
//string o wstring
std::wstring StringToWString(const std::string& s)
{
std::wstring wszStr;
int nLength = MultiByteToWideChar(CP_ACP, 0, s.c_str(), -1, NULL, NULL);
wszStr.resize(nLength);
LPWSTR lpwszStr = new wchar_t[nLength];
MultiByteToWideChar(CP_ACP,0,s.c_str(),-1,lpwszStr,nLength);
wszStr = lpwszStr;
delete[] lpwszStr;
return wszStr;
}
//my implemented IWbemClassObject.cpp
#include "stdafx.h"
#include <stdio.h>
#include <strsafe.h>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include<fstream>
#include <mutex>>
#include <comdef.h>
#include <comutil.h>
#include "ImpIWbemClassObject.h"
using namespace std;
std::mutex g_mutex3;
const WCHAR* logPath3 = L"D:\\practice_demos\\DetourPratice\\x64\\Debug\\logWbemClassObject.txt";
void WINAPI log3(const char* log, DWORD _size);
ImpIWbemClassObject::ImpIWbemClassObject(IWbemClassObject* _realIWbemClassObject)
{
log3("\r\n ImpIWbemClassObject->ImpIWbemClassObject() ", 128);
_pIWbemClassObject = _realIWbemClassObject;
}
ImpIWbemClassObject::~ImpIWbemClassObject()
{
log3("\r\n ~ImpIWbemClassObject() ", 128);
}
#pragma region implementation of IUnkown
ULONG ImpIWbemClassObject::AddRef()
{
log3("\r\n ImpIWbemClassObject->AddRef() ", 128);
return _pIWbemClassObject->AddRef();
}
HRESULT ImpIWbemClassObject::QueryInterface(
REFIID riid,
void** ppvObject
)
{
log3("\r\n ImpIWbemClassObject->QueryInterface() ", 128);
(*ppvObject)=this;
return 1;
}
ULONG ImpIWbemClassObject::Release()
{
log3("\r\n ImpIWbemClassObject->Rlease() ", 128);
return _pIWbemClassObject->Release();
}
#pragma endregion
#pragma region below implementation
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::GetQualifierSet(
/* [out] */ IWbemQualifierSet** ppQualSet)
{
log3("\r\n ImpIWbemClassObject->GetQualifierSet() ", 128);
return _pIWbemClassObject->GetQualifierSet(ppQualSet);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::Get(
/* [string][in] */ LPCWSTR wszName,
/* [in] */ long lFlags,
/* [unique][in][out] */ VARIANT* pVal,
/* [unique][in][out] */ CIMTYPE* pType,
/* [unique][in][out] */ long* plFlavor)
{
log3("\r\n ImpIWbemClassObject->Get() ", 128);
return _pIWbemClassObject->Get(wszName,lFlags,pVal,pType,plFlavor);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::Put(
/* [string][in] */ LPCWSTR wszName,
/* [in] */ long lFlags,
/* [in] */ VARIANT* pVal,
/* [in] */ CIMTYPE Type)
{
log3("\r\n ImpIWbemClassObject->Put() ", 128);
return _pIWbemClassObject->Put(wszName,lFlags,pVal,Type);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::Delete(
/* [string][in] */ LPCWSTR wszName)
{
log3("\r\n ImpIWbemClassObject->Delete() ", 128);
return _pIWbemClassObject->Delete(wszName);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::GetNames(
/* [string][in] */ LPCWSTR wszQualifierName,
/* [in] */ long lFlags,
/* [in] */ VARIANT* pQualifierVal,
/* [out] */ SAFEARRAY** pNames)
{
log3("\r\n ImpIWbemClassObject->GetNames() ", 128);
return _pIWbemClassObject->GetNames(wszQualifierName,lFlags,pQualifierVal,pNames);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::BeginEnumeration(
/* [in] */ long lEnumFlags)
{
log3("\r\n ImpIWbemClassObject->BeginEnumeration() ", 128);
return _pIWbemClassObject->BeginEnumeration(lEnumFlags);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::EndEnumeration()
{
log3("\r\n ImpIWbemClassObject->EndEnumeration() ", 128);
return _pIWbemClassObject->EndEnumeration();
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::GetPropertyQualifierSet(
/* [string][in] */ LPCWSTR wszProperty,
/* [out] */ IWbemQualifierSet** ppQualSet)
{
log3("\r\n ImpIWbemClassObject->GetPropertyQualifierSet() ", 128);
return _pIWbemClassObject->GetPropertyQualifierSet(wszProperty,ppQualSet);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::Clone(
/* [out] */ IWbemClassObject** ppCopy)
{
log3("\r\n ImpIWbemClassObject->Clone() ", 128);
return _pIWbemClassObject->Clone(ppCopy);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::GetObjectText(
/* [in] */ long lFlags,
/* [out] */ BSTR* pstrObjectText)
{
log3("\r\n ImpIWbemClassObject->GetObjectText() ", 128);
return _pIWbemClassObject->GetObjectText(lFlags,pstrObjectText);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::SpawnDerivedClass(
/* [in] */ long lFlags,
/* [out] */ IWbemClassObject** ppNewClass)
{
log3("\r\n ImpIWbemClassObject->SpawnDerivedClass() ", 128);
return _pIWbemClassObject->SpawnDerivedClass(lFlags, ppNewClass);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::SpawnInstance(
/* [in] */ long lFlags,
/* [out] */ IWbemClassObject** ppNewInstance)
{
log3("\r\n ImpIWbemClassObject->SpawnInstance() ", 128);
return _pIWbemClassObject->SpawnInstance(lFlags,ppNewInstance);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::CompareTo(
/* [in] */ long lFlags,
/* [in] */ IWbemClassObject* pCompareTo)
{
return _pIWbemClassObject->CompareTo(lFlags,pCompareTo);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::GetPropertyOrigin(
/* [string][in] */ LPCWSTR wszName,
/* [out] */ BSTR* pstrClassName)
{
log3("\r\n ImpIWbemClassObject->GetPropertyOrigin() ", 128);
return _pIWbemClassObject->GetPropertyOrigin(wszName,pstrClassName);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::InheritsFrom(
/* [in] */ LPCWSTR strAncestor)
{
return _pIWbemClassObject->InheritsFrom(strAncestor);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::GetMethod(
/* [string][in] */ LPCWSTR wszName,
/* [in] */ long lFlags,
/* [out] */ IWbemClassObject** ppInSignature,
/* [out] */ IWbemClassObject** ppOutSignature)
{
log3("\r\n ImpIWbemClassObject->GetMethod() ", 128);
return _pIWbemClassObject->GetMethod(wszName,lFlags,ppInSignature,ppOutSignature) ;
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::PutMethod(
/* [string][in] */ LPCWSTR wszName,
/* [in] */ long lFlags,
/* [in] */ IWbemClassObject* pInSignature,
/* [in] */ IWbemClassObject* pOutSignature)
{
return _pIWbemClassObject->PutMethod(wszName,lFlags,pInSignature,pOutSignature);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::DeleteMethod(
/* [string][in] */ LPCWSTR wszName)
{
return _pIWbemClassObject->DeleteMethod(wszName);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::BeginMethodEnumeration(
/* [in] */ long lEnumFlags)
{
log3("\r\n ImpIWbemClassObject->BeginMethodEnumeration() ", 128);
return _pIWbemClassObject->BeginMethodEnumeration(lEnumFlags);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::Next(
/* [in] */ long lFlags,
/* [unique][in][out] */ BSTR* strName,
/* [unique][in][out] */ VARIANT* pVal,
/* [unique][in][out] */ CIMTYPE* pType,
/* [unique][in][out] */ long* plFlavor)
{
log3("\r\nBefore ImpIWbemClassObject->Next\r\n",64);
HRESULT result = _pIWbemClassObject->Next(lFlags,strName,pVal,pType,plFlavor);
string propertyName = string(_com_util::ConvertBSTRToString(*strName));
if ((*pVal).vt == VT_BSTR)
{
_bstr_t bs_a(*pVal);
log3((string("\r\n ImpIWbemClassObject->Next() , propertyName = ") + propertyName + " value = " + static_cast<const char*>(bs_a) + "\r\n").c_str(), 256);
}
else
{
log3((string("\r\n ImpIWbemClassObject->Next() , propertyName = ") + propertyName).c_str() , 128);
}
log3("\r\nAfter ImpIWbemClassObject->Next\r\n", 64);
return 1;
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::NextMethod(
/* [in] */ long lFlags,
/* [unique][in][out] */ BSTR* pstrName,
/* [unique][in][out] */ IWbemClassObject** ppInSignature,
/* [unique][in][out] */ IWbemClassObject** ppOutSignature)
{
log3("\r\n ImpIWbemClassObject->NextMethod() ", 128);
return _pIWbemClassObject->NextMethod(lFlags,pstrName,ppInSignature,ppOutSignature);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::EndMethodEnumeration(void)
{
return _pIWbemClassObject->EndMethodEnumeration();
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::GetMethodQualifierSet(
/* [string][in] */ LPCWSTR wszMethod,
/* [out] */ IWbemQualifierSet** ppQualSet)
{
log3("\r\n ImpIWbemClassObject->GetMethodQualifierSet() ", 128);
return _pIWbemClassObject->GetMethodQualifierSet(wszMethod,ppQualSet);
}
HRESULT STDMETHODCALLTYPE ImpIWbemClassObject::GetMethodOrigin(
/* [string][in] */ LPCWSTR wszMethodName,
/* [out] */ BSTR* pstrClassName)
{
log3("\r\n ImpIWbemClassObject->GetMethodOrigin() ", 128);
return _pIWbemClassObject->GetMethodOrigin(wszMethodName,pstrClassName);
}
#pragma endregion
void WINAPI log3(const char* log, DWORD _size)
{
g_mutex3.lock();
BOOL bErrorFlag = FALSE;
DWORD dwBytesWritten = 0;
HANDLE hfile = NULL;
ofstream fout;
ifstream fin;
fin.open(logPath3);
fout.open(logPath3, ios::app);
if (fin.is_open())
fout << log;
fin.close();
fout.close();
g_mutex3.unlock();
}
//my implemented IEnumWbelClassObject.cpp
#include "stdafx.h"
#include <stdio.h>
#include <strsafe.h>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include<fstream>
#include <mutex>>
#include <comdef.h>
#include <comutil.h>
#include "ImpIEnumWbemClassObject.h"
#include "ImpIWbemClassObject.h"
#include <atlconv.h>
using namespace std;
std::mutex g_mutex2;
const WCHAR* logPath2 = L"D:\\practice_demos\\DetourPratice\\x64\\Debug\\logIEnum.txt";
void WINAPI log2(const char* log, DWORD _size);
ImpIEnumWbemClassObject::ImpIEnumWbemClassObject(IEnumWbemClassObject* _realIEnumWbemClassObject)
{
_pIEnumWbemClassObject = _realIEnumWbemClassObject;
}
ImpIEnumWbemClassObject::~ImpIEnumWbemClassObject()
{
log2("\r\nBefore ~ImpIEnumWbemClassObject\r\n", 64);
}
ULONG ImpIEnumWbemClassObject::AddRef()
{
log2("\r\nBefore ImpIEnumWbemClassObject::AddRef\r\n", 64);
return _pIEnumWbemClassObject->AddRef();
}
HRESULT ImpIEnumWbemClassObject::QueryInterface(
REFIID riid,
void** ppvObject
)
{
log2("\r\nBefore ImpIEnumWbemClassObject::QueryInterface\r\n", 64);
LPWSTR pwsz;
HRESULT sfiid = StringFromIID(riid, &pwsz);
if (sfiid==E_OUTOFMEMORY)
{
log2("NO memeory to contain Interface name",128);
}
char riidname[256] = "";
wcstombs(riidname, pwsz,256);
log2((string("ImpIEnumWbemClassObject::QueryInterface() ")+ riidname+"\r\n").c_str(), 256);
if (riid==IID_IUnknown)
{
(*ppvObject) = this;
return 1;
}
(*ppvObject)=this;
return 1;
}
ULONG ImpIEnumWbemClassObject::Release()
{
log2("\r\nBefore ImpIEnumWbemClassObject::Release\r\n", 64);
return _pIEnumWbemClassObject->Release();
}
HRESULT ImpIEnumWbemClassObject::Clone(
IEnumWbemClassObject** ppEnum
)
{
log2("\r\nBefore ImpIEnumWbemClassObject::Clone\r\n", 64);
return _pIEnumWbemClassObject->Clone(ppEnum);
}
HRESULT ImpIEnumWbemClassObject::Next(
long lTimeout,
ULONG uCount,
IWbemClassObject** apObjects,
ULONG* puReturned
)
{
log2("\r\nBefore ImpIEnumWbemClassObject::Next\r\n", 64);
HRESULT result= _pIEnumWbemClassObject->Next(lTimeout,uCount,apObjects,puReturned);
log2("\r\Never go here , hang !!! ImpIEnumWbemClassObject::Next is done\r\n", 64); //**It never go here**
const void* pAddress = static_cast<const void*>((*apObjects));
stringstream ss;
ss << pAddress;
log2((string("\r\n original address is ")+ss.str()+"\r\n").c_str(), 64);
ImpIWbemClassObject* impIWbemClassObject=new ImpIWbemClassObject(*apObjects);
(*apObjects) = impIWbemClassObject;
pAddress = static_cast<const void*>((*apObjects));
stringstream ss2;
ss2 << pAddress;
log2((string("\r\n updated address is ") + ss2.str() + "\r\n").c_str(), 64);
log2("\r\After ImpIEnumWbemClassObject::Next\r\n", 64);
return result;
}
HRESULT ImpIEnumWbemClassObject::NextAsync(
ULONG uCount,
IWbemObjectSink* pSink
)
{
log2("\r\nBefore ImpIEnumWbemClassObject::NextAsync\r\n", 64);
return _pIEnumWbemClassObject->NextAsync(uCount,pSink);
}
HRESULT ImpIEnumWbemClassObject::Reset()
{
return _pIEnumWbemClassObject->Reset();
}
HRESULT ImpIEnumWbemClassObject::Skip(
long lTimeout,
ULONG nCount
)
{
return _pIEnumWbemClassObject->Skip(lTimeout,nCount);
}
void WINAPI log2(const char* log, DWORD _size)
{
g_mutex2.lock();
BOOL bErrorFlag = FALSE;
DWORD dwBytesWritten = 0;
HANDLE hfile = NULL;
ofstream fout;
ifstream fin;
fin.open(logPath2);
fout.open(logPath2, ios::app);
if (fin.is_open())
fout << log;
fin.close();
fout.close();
g_mutex2.unlock();
}

connmanctl command(RegisterAgent) is not working via dbus

I can connect to open wifi via "connmanctl" using dbus via Qt,. I would like to connect secured wife using connmanctl via dbus. there is an API to regiser an agent( interactive mode, to enter passphrase) called "RegisterAgent(object path)"
, In this, I am not sure what is mean by object path. I have tried object path with ""/net/connman/technology/wifi", but it was not working. I think I am wrong on something. I have added Qt compiled code below. Can some one help me to connect to secured network through connmanctl via dbus ?
//------------tocker.h------------------
#ifndef TOCKER_H
#define TOCKER_H
#include <QObject>
#include <QDBusMessage>
#include <QDBusError>
class Tocker : public QObject
{
Q_OBJECT
public:
explicit Tocker(QObject *parent = 0);
signals:
public slots:
void onAgentRegisterRequested(QDBusMessage);
void onErrorResponse(QDBusError);
};
#endif // TOCKER_H
//----------------------
//talker.cpp................
#include <QDBusInterface>
#include <QDBusConnection>
#include <QList>
#include <QVariant>
#include <QtDebug>
#include "tocker.h"\
Tocker::Tocker(QObject *parent) : QObject(parent)
{
QDBusInterface interfaceObj("net.connman", "/", "net.connman.Manager", QDBusConnection::systemBus());
bool isScucess = false;
do
{
if(interfaceObj.isValid())
{
QList<QVariant> params;
params << "/net/connman/technology/wifi"; //I am not sure is this path is correct
if( interfaceObj.callWithCallback("RegisterAgent", params, this, SLOT(onAgentRegisterRequestedd(QDBusMessage)), SLOT(onErrorResponse(QDBusError)) ))
{
qDebug()<< Q_FUNC_INFO << "callWithCallback is success";
isScucess = true;
}
else
{
isScucess = false;
}
break;
}
}
while(false);
if( !isScucess )
{
qDebug()<< Q_FUNC_INFO << interfaceObj.lastError().message();
}
else
{
qDebug() << Q_FUNC_INFO << "Callback is success.";
}
}
void Tocker::onAgentRegisterRequested(QDBusMessage msg)
{
qDebug()<< Q_FUNC_INFO << msg;
}
void Tocker::onErrorResponse(QDBusError errorMsg )
{
qDebug()<< Q_FUNC_INFO << errorMsg;
}
-----------main.cpp........
#include <QCoreApplication>
#include "tocker.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Tocker tocker;
return a.exec();
}

Why does my CreateThread input parameter get corrupted?

In a namespace extension, I'm creating a thread and passing in a file path to the thread function.
The problem I'm seeing is the first character of the file path gets corrupted. D:\temp0.csv gets passed in and in the thread function it becomes Y:\temp0.csv or some other random corrupted first wchar. In Win2k8R2 and Win10 it was working fine, but sometimes it would fail in the same way. I tried disabling optimizations to no avail.
The fileName variable is populated from the IShellItem that came from the IFileOpenDialog.
What do I need to do to fix this?
Caller of thread function:
LPWSTR filePath = NULL;
IFileOpenDialog *ofd = NULL;
IShellItem *file = NULL;
hrPath = file->GetDisplayName(SIGDN_FILESYSPATH, &filePath);
CreateThread(NULL, 0, CCsv::BuildTree, static_cast<LPVOID>(filePath), 0, NULL);
static class thread function
DWORD WINAPI CCsv::BuildTree(LPVOID lpParam) {
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
LPWSTR filePath = static_cast<LPWSTR>(lpParam);
}
Here is a minimal program, but it does not repro with this code. One difference is I added a wait for the thread function. THat doesn't exist in the namespace extension.
main.cpp
// buf.cpp : Defines the entry point for the console application.
//
#pragma once
#include "stdafx.h"
using std::wstring;
static CRITICAL_SECTION g_TreeLock;
static CRITICAL_SECTION g_MountQueueLock;
class CCsv
{
public:
CCsv();
~CCsv();
static DWORD WINAPI BuildTree(LPVOID lpParam);
};
class CMountPath {
public:
CMountPath();
~CMountPath();
BOOL Mount();
BOOL PathExists(LPWSTR path);
private:
CSimpleArray<wstring> m_MountQueue;
};
extern CCsv g_Csv;
CCsv::CCsv() {
InitializeCriticalSection(&g_TreeLock);
}
CCsv::~CCsv() {
DeleteCriticalSection(&g_TreeLock);
}
DWORD WINAPI CCsv::BuildTree(LPVOID lpParam) {
LPWSTR name = static_cast<LPWSTR>(lpParam);
MessageBox(NULL, name, L"", MB_OK);
CoTaskMemFree(name);
return 0;
}
CMountPath::CMountPath() {
InitializeCriticalSection(&g_MountQueueLock);
}
CMountPath::~CMountPath() {
DeleteCriticalSection(&g_MountQueueLock);
}
BOOL CMountPath::PathExists(LPWSTR path) {
return FALSE;
}
BOOL CMountPath::Mount() {
IEnumIDList *idl = NULL;
LPITEMIDLIST pidl = NULL;
LPITEMIDLIST desktopPidl = NULL;
LPCITEMIDLIST pidlRelative = NULL;
BOOL success = FALSE;
HRESULT hr, hrPath = S_FALSE;
LPWSTR filePath = NULL;
PWSTR filePathHeap = NULL;
WCHAR msg[MAXPATH+MAXMSG] = {0};
IFileOpenDialog *ofd = NULL;
IShellItem *file = NULL;
DWORD idx = 0;
BOOL isQueued = FALSE;
const COMDLG_FILTERSPEC fileSpec[] = {
{ L"CSV Text Files", L"*.csv" },
{ L"All Files", L"*.*" },
};
hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&ofd));
if (SUCCEEDED(hr)) {
if (SUCCEEDED(hr)){
ofd->SetTitle(L"Choose file");
ofd->SetFileTypes(ARRAYSIZE(fileSpec), fileSpec);
hr = ofd->Show(NULL);
if(SUCCEEDED(hr))
hr = ofd->GetResult(&file);
if(SUCCEEDED(hr))
hrPath = file->GetDisplayName(SIGDN_FILESYSPATH, &filePath);
if(SUCCEEDED(hrPath)){
LPWSTR filePathHeap = (LPWSTR)CoTaskMemAlloc(MAXPATH * sizeof(WCHAR));
if(filePathHeap) {
StringCchCopy(filePathHeap, MAXPATH, filePath);
if(PathExists(filePathHeap)) {
StringCchPrintf(msg, MAXPATH+MAXMSG, L"The file %s is already loaded.", filePathHeap);
MessageBox(NULL, msg, L"appname", MB_OK);
}
else {
EnterCriticalSection(&g_MountQueueLock);
isQueued = !m_MountQueue.Find(wstring(filePathHeap)) ? TRUE : FALSE;
if(!isQueued)
m_MountQueue.Add(wstring(filePathHeap));
LeaveCriticalSection(&g_MountQueueLock);
if(!isQueued) {
HANDLE hThread = CreateThread(NULL, 0, CCsv::BuildTree, static_cast<LPVOID>(filePathHeap), 0, NULL);
// there is no wait in the namespace extension. the wait is just to keep the console app main thread running.
if(INVALID_HANDLE_VALUE != hThread)
WaitForSingleObject(hThread, INFINITE);
}
else {
StringCchPrintf(msg, MAXPATH+MAXMSG, L"The file %s is already being loaded.", filePathHeap);
MessageBox(NULL, msg, L"appname", MB_OK);
}
}
}
CoTaskMemFree(filePath);
file->Release();
}
}
ofd->Release();
}
return success;
}
int main() {
CoInitialize(NULL);
CMountPath m;
m.Mount();
CoUninitialize();
return 0;
}
stdafx.h
#pragma once
#define MAXPATH 32767
#define MAXMSG 128
#define WIN32_LEAN_AND_MEAN
#define WINVER 0x0600
#define _WIN32_WINNT 0x0600
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <atlbase.h>
#include <atlstr.h>
#include <atlcoll.h>
#include <shlobj.h>
#include <Shobjidl.h>
#include <ShlGuid.h>
#include <shellapi.h>
#include <OleAuto.h>
#include <shlwapi.h>
#include <strsafe.h>
#include <string>
Why are you using threads at all? When you spawn a new thread, you are blocking your code waiting for the thread to terminate before continuing, so you are serializing all of your code. You may as well not even use threads at all.
Also, you have memory leaks and various logic errors in your code.
Try this instead:
// buf.cpp : Defines the entry point for the console application.
//
#pragma once
#include "stdafx.h"
using std::wstring;
class CCsv
{
public:
CCsv();
~CCsv();
void BuildTree(LPCWSTR name);
private:
CRITICAL_SECTION m_TreeLock;
};
class CMountPath {
public:
CMountPath();
~CMountPath();
BOOL Mount();
BOOL PathExists(LPCWSTR path);
private:
CSimpleArray<wstring> m_MountQueue;
CRITICAL_SECTION m_MountQueueLock;
};
CCsv g_Csv;
CCsv::CCsv() {
InitializeCriticalSection(&m_TreeLock);
}
CCsv::~CCsv() {
DeleteCriticalSection(&m_TreeLock);
}
void CCsv::BuildTree(LPCWSTR name) {
MessageBoxW(NULL, name, L"", MB_OK);
}
CMountPath::CMountPath() {
InitializeCriticalSection(&m_MountQueueLock);
}
CMountPath::~CMountPath() {
DeleteCriticalSection(&m_MountQueueLock);
}
BOOL CMountPath::PathExists(LPCWSTR path) {
return FALSE;
}
BOOL CMountPath::Mount() {
BOOL success = FALSE;
HRESULT hr = S_FALSE;
LPWSTR filePath = NULL;
WCHAR msg[MAXPATH+MAXMSG] = {0};
IFileOpenDialog *ofd = NULL;
IShellItem *file = NULL;
BOOL isQueued = FALSE;
const COMDLG_FILTERSPEC fileSpec[] = {
{ L"CSV Text Files", L"*.csv" },
{ L"All Files", L"*.*" },
};
hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&ofd));
if (SUCCEEDED(hr)) {
ofd->SetTitle(L"Choose file");
ofd->SetFileTypes(ARRAYSIZE(fileSpec), fileSpec);
hr = ofd->Show(NULL);
if(SUCCEEDED(hr))
hr = ofd->GetResult(&file);
if(SUCCEEDED(hr)) {
hr = file->GetDisplayName(SIGDN_FILESYSPATH, &filePath);
if(SUCCEEDED(hr)){
if(PathExists(filePath)) {
StringCchPrintf(msg, ARRAYSIZE(msg), L"The file %s is already loaded.", filePath);
MessageBox(NULL, msg, L"appname", MB_OK);
}
else {
EnterCriticalSection(&m_MountQueueLock);
isQueued = !m_MountQueue.Find(filePath) ? TRUE : FALSE;
if(!isQueued)
m_MountQueue.Add(filePath);
LeaveCriticalSection(&m_MountQueueLock);
if(!isQueued) {
CCsv::BuildTree(filePath);
}
else {
StringCchPrintf(msg, ARRAYSIZE(msg), L"The file %s is already being loaded.", filePath);
MessageBox(NULL, msg, L"appname", MB_OK);
}
}
CoTaskMemFree(filePath);
}
file->Release();
}
ofd->Release();
}
return success;
}
int main() {
CoInitialize(NULL);
CMountPath m;
m.Mount();
CoUninitialize();
return 0;
}
your conceptual mistake here:
if(!isQueued)
{
m_MountQueue.Add(wstring(filePathHeap));
CreateThread(NULL, 0, CCsv::BuildTree, static_cast<LPVOID>(filePathHeap), 0, NULL);
}
so you insert filePathHeap in some database and simultaneously pass this filePathHeap to some thread. question - who is OWNER of filePathHeap ? who must free it ? if you free it from BuildTree - in m_MountQueue will be invalid pointer ? you not show code who and how handle m_MountQueue - may be this code pop and free filePathHeap before it used in BuildTree.
in general - if you push filePathHeap to m_MountQueue - you must not direct use it pointer after this, but have working thread (pool) which pop data from m_MountQueue , process and free it. or if you direct use filePathHeap you must not insert it to m_MountQueue.
in case if you need simultaneously working with filePathHeap from several threads - you need ref count have. some like this:
class CFilePath
{
PWSTR _filePath;
LONG _dwRef;
~CFilePath()
{
CoTaskMemFree(_filePath);
}
public:
PCWSTR getPath() { return _filePath; }
CFilePath(PWSTR filePath)
{
_filePath = filePath;
_dwRef = 1;
}
void AddRef()
{
InterlockedIncrement(&_dwRef);
}
void Release()
{
if (!InterlockedDecrement(&_dwRef)) delete this;
}
};
ULONG CALLBACK CCsv::BuildTree(CFilePath* p)
{
MessageBoxW(0, p->getPath(), L"use path in thread 2", MB_OK);
p->Release();
return 0;
}
BOOL CMountPath::Mount() {
...
if (CFilePath* p = new CFilePath(filePath))
{
p->AddRef();
if (HANDLE hThread = CreateThread(0, 0, reinterpret_cast<PTHREAD_START_ROUTINE>(CCsv::BuildTree), p, 0, 0))
{
CloseHandle(hThread);
}
else
{
p->Release();
}
MessageBoxW(0, p->getPath(), L"use path in thread 1", MB_OK);
p->Release();
}
else
{
CoTaskMemFree(filePath);
}
...
}
Secondly - this code
LPWSTR filePathHeap = (LPWSTR)CoTaskMemAlloc(MAXPATH * sizeof(WCHAR));
if(filePathHeap) StringCchCopy(filePathHeap, MAXPATH, filePath);
absolutely unnecessary. you can direct use filePath as is, but not reallocate it. for what ?!
thirdly - as in previous answer - almost no sense create thread and after this just wait on it exit.
HANDLE hThread = CreateThread(NULL, 0, CCsv::BuildTree, static_cast<LPVOID>(filePathHeap), 0, NULL);
// there is no wait in the namespace extension. the wait is just to keep the console app main thread running.
if(INVALID_HANDLE_VALUE != hThread)
WaitForSingleObject(hThread, INFINITE);
why in this case not direct call CCsv::BuildTree(filePathHeap); with same effect ?
also can note that INVALID_HANDLE_VALUE returned only for CreateFile or Socket - so for file handles only. all another object creating api (including CreateThread return 0 on error, but not INVALID_HANDLE_VALUE (-1) ) - so you incorrect check error condition.
and finally who will call CloseHandle(hThread) ? handle not auto closed when thread exit

Mfc application crash in CWnd::DefWindowProc while creating Progress Control from within Worker Thread after 34 repetitive cycles on 64 bit windows

I am trying to figure out the exact reason for the crash happening in my 32 bit MFC application which is running on 64 bit system.
Actually this is a multithreaded MFC SDI application and can do cyclic execution which includes Inspection and outputting inspection results as reports.
After an inspection finishes it show a Custom Alert Window with a progress control until the reports are generated.The Alert Window is created from a Worker Thread and the Main Thread waits until the window is created.
Below is the coded representation of one cycle of Displaying the Alert Window With Progress Bar:
static const __int64 POPUPWND_POLLPERIOD = 10 * 10000LL;
static const __int64 POPUPWND_POLLTIMEOUT = 1000 * POPUPWND_POLLPERIOD;
class CCallFunc
{
public:
class Queue;
public:
typedef int(*Call)(const CCallFunc &cf);
public:
CCallFunc(Call call, LPVOID lpData) :
m_call(call),
m_lpData(lpData)
{}
int Run() { m_call(*this); }
LPVOID GetData() const { return m_lpData; }
private:
Call m_call;
LPVOID m_lpData;
};
class CCallFunc::Queue
{
public:
int SetQueue(const CCallFunc &cf, const __int64 &timeout = INFINITE)
{
m_pcf = &cf;
m_timeout = timeout;
}
public:
int Run(const __int64 &timeout = 0)
{
CCallFunc cf(*m_pcf);
cf.Run();
}
private:
const CCallFunc* m_pcf;
__int64 m_timeout;
};
class CWorkThread
{
private:
static DWORD WINAPI SystemThread(LPVOID lpData)
{
CWorkThread* pThread = (CWorkThread*)lpData;
__int64 timeout = pThread->m_timeout;
try {
pThread->m_queue.Run(timeout);
}
catch (const CCallFunc &cf) {
pThread->m_queue.SetQueue(cf, timeout);
}
}
public:
static int Aquire(CWorkThread *pThread)
{
pThread = &thisThread;
return S_OK;
}
static void Sleep(const __int64 &period)
{
__int64 current;
__int64 final = period;
switch (final) {
case INFINITE:
while (true)
::SleepEx(INFINITE, TRUE);
throw;
case 0:
::SleepEx(DWORD(0), TRUE);
return;
default:
::GetSystemTimeAsFileTime(reinterpret_cast<FILETIME*>(&current));
if ((final += current) < 0)
final = current;
while (current < final) {
if (::SleepEx(DWORD((final - current) / __int64(10000)), TRUE) == 0)
return;
::GetSystemTimeAsFileTime((FILETIME*)&current);
}
}
}
int Start(CCallFunc::Call call, LPVOID lpData)
{
return Start(CCallFunc(call, lpData));
}
int Start(const CCallFunc &fc)
{
DWORD dwID = 0;
::CreateThread(0, 0, &SystemThread, this, 0, &dwID);
}
public:
CCallFunc::Queue m_queue;
private:
__int64 m_timeout;
static CWorkThread thisThread;
};
class CPopupWindow;
struct PopupWndCreateContext : public CCreateContext {
CPopupWindow* popup;
CString clsname;
CString wndname;
DWORD style;
DWORD exstyle;
CRect rc;
HWND parent;
UINT id;
};
class CPopupWindow : public CWnd
{
public:
int Show()
{
HWND hParent = 0;
CWinApp* pApp = NULL;
CWnd* pMain;
if ((pApp = ::AfxGetApp()) != 0 && (pMain = pApp->GetMainWnd()) != 0) {
hParent = pMain->m_hWnd;
}
Create(800, 600, hParent);
}
private:
int Create(int iWidth, int iHeight, HWND parent)
{
PopupWndCreateContext ctxt;
ctxt.popup = this;
ctxt.clsname = "AlertCtrl";
ctxt.wndname = "Alert Control";
ctxt.style = WS_VISIBLE | WS_POPUP;
ctxt.exstyle = 0;
ctxt.rc = CRect(0, 0, iWidth, iHeight);
ctxt.parent = parent;
ctxt.id = 10000;
CWorkThread* pThread;
int e;
if (SUCCEEDED(e = CWorkThread::Aquire(pThread)) && SUCCEEDED(e = pThread->Start(&Run, &ctxt))) {
for (__int64 t = 0; t < POPUPWND_POLLTIMEOUT; t += POPUPWND_POLLPERIOD) {
if (::IsWindow(*this))
return 0;
CWorkThread::Sleep(POPUPWND_POLLPERIOD);
}
}
}
static int Run(const CCallFunc &cf)
{
int e = 0;
PopupWndCreateContext& ctxt = *(static_cast<PopupWndCreateContext*>(cf.GetData()));
ASSERT(&ctxt != 0);
CPopupWindow &wnd = *ctxt.popup;
static const DWORD clsstyle = CS_BYTEALIGNCLIENT | CS_BYTEALIGNWINDOW;
static const HCURSOR clscursor = ::LoadCursor(0, IDC_WAIT);
static const HICON clsicon = 0;
static LPCTSTR clsname = ::AfxRegisterWndClass(clsstyle, clscursor, NULL, clsicon);
if (wnd.CreateEx(DWORD(ctxt.exstyle), ctxt.clsname, ctxt.wndname, DWORD(ctxt.style), ctxt.rc.left, ctxt.rc.top, ctxt.rc.Width(), ctxt.rc.Height(), ctxt.parent, HMENU(ctxt.id), 0) != 0) {
HWND hwnd = wnd.GetSafeHwnd();
::UpdateWindow(hwnd);
MSG msg;
while ((::GetMessage(&msg, 0, 0, 0))) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
wnd.DestroyWindow();
}
return e;
}
};
class CAlertCtrl : CPopupWindow
{
CProgressCtrl m_progctrl;
DECLARE_MESSAGE_MAP();
int OnCreate(LPCREATESTRUCT cs)
{
int e = 0; //< error code / return value
if ((e = __super::OnCreate(cs)) != 0)
return e;
if (!::IsWindow(m_progctrl))
{
CRect rc;
GetClientRect(rc);
if (m_progctrl.Create(WS_CHILD | WS_VISIBLE | PBS_SMOOTH, rc, this, 100000))
m_progctrl.SetRange(0, 10000);
}
return e;
}
};
BEGIN_MESSAGE_MAP(CAlertCtrl, CPopupWindow)
ON_WM_CREATE()
END_MESSAGE_MAP()
So while executing m_progctrl.Create it crashes in the Wincore.cpp
at the method CWnd::DefWindowProc trying to execute callWindowProc after calling the method CPopupWindow::Show for the 35th Cycle.
/////////////////////////////////////////////////////////////////////////////
// Default CWnd implementation
LRESULT CWnd::DefWindowProc(UINT nMsg, WPARAM wParam, LPARAM lParam)
{
if (m_pfnSuper != NULL)
return ::CallWindowProc(m_pfnSuper, m_hWnd, nMsg, wParam, lParam);

how to run DLL Project

This is the Oculus street view project.....just i am trying to understand and run but i could not do it......please help me
// dllmain.cpp : Defines the entry point for the DLL application.
include "stdafx.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
include "stdafx.h"
#include "libovrwrapper.h"
#include <OVR.h>
using namespace OVR;
// Ptr<> AddRef'ed, AutoCleaned
bool bInited = false;
Ptr<DeviceManager> pManager;
Ptr<HMDDevice> pHMD;
Ptr<SensorDevice> pSensor;
SensorFusion pSensorFusion;
LIBOVRWRAPPER_API int OVR_Init()
{
bInited = false;
System::Init(Log::ConfigureDefaultLog(LogMask_Regular));
if (System::IsInitialized())
{
int stage = -1;
while (++stage > -1 && !bInited)
{
switch (stage)
{
case 0:
pManager = *DeviceManager::Create();
if (pManager == NULL)
return bInited;
break;
case 1:
pHMD = *pManager->EnumerateDevices<HMDDevice>().CreateDevice();
if (pHMD == NULL)
return bInited;
break;
case 2:
pSensor = *pHMD->GetSensor();
if (pSensor == NULL)
return bInited;
break;
default:
bInited = true;
break;
};
}
}
pSensorFusion.AttachToSensor(pSensor);
return (bInited?1:0);
}
LIBOVRWRAPPER_API void OVR_Exit()
{
if (bInited)
{
System::Destroy();
}
}
LIBOVRWRAPPER_API int OVR_QueryHMD(OVR_HMDInfo* refHmdInfo)
{
if (!bInited)
{
return 0;
}
HMDInfo src;
if (pHMD->GetDeviceInfo(&src))
{
refHmdInfo->HResolution = src.HResolution;
refHmdInfo->VResolution = src.VResolution;
refHmdInfo->HScreenSize = src.HScreenSize;
refHmdInfo->VScreenSize = src.VScreenSize;
refHmdInfo->VScreenCenter = src.VScreenCenter;
refHmdInfo->EyeToScreenDistance = src.EyeToScreenDistance;
refHmdInfo->LensSeparationDistance = src.LensSeparationDistance;
refHmdInfo->InterpupillaryDistance = src.InterpupillaryDistance;
refHmdInfo->DistortionK[0] = src.DistortionK[0];
refHmdInfo->DistortionK[1] = src.DistortionK[1];
refHmdInfo->DistortionK[2] = src.DistortionK[2];
refHmdInfo->DistortionK[3] = src.DistortionK[3];
refHmdInfo->DesktopX = src.DesktopX;
refHmdInfo->DesktopY = src.DesktopY;
memcpy(refHmdInfo->DisplayDeviceName, src.DisplayDeviceName, sizeof(refHmdInfo->DisplayDeviceName));
}
return 1;
}
LIBOVRWRAPPER_API int OVR_PeekYPL(float* yaw, float* pitch, float* roll)
{
if (!bInited)
{
return 0;
}
Quatf hmdOrient = pSensorFusion.GetOrientation();
hmdOrient.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(yaw, pitch, roll);
return 1;
}
LIBOVRWRAPPER_API int OVR_Peek(float* w, float* x, float* y,float * z)
{
if (!bInited)
{
return 0;
}
Quatf hmdOrient = pSensorFusion.GetOrientation();
*w = hmdOrient.w;
*x = hmdOrient.x;
*y = hmdOrient.y;
*z = hmdOrient.z;
//hmdOrient.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(yaw, pitch, roll);
return 1;
}
#ifdef LIBOVRWRAPPER_EXPORTS
#if defined __cplusplus
#define LIBOVRWRAPPER_API extern "C" __declspec(dllexport)
#else
#define LIBOVRWRAPPER_API __declspec(dllexport)
#endif
#else
#if defined __cplusplus
#define LIBOVRWRAPPER_API extern "C" __declspec(dllimport)
#else
#define LIBOVRWRAPPER_API __declspec(dllimport)
#endif
#endif
struct OVR_HMDInfo
{
unsigned HResolution;
unsigned VResolution;
float HScreenSize;
float VScreenSize;
float VScreenCenter;
float EyeToScreenDistance;
float LensSeparationDistance;
float InterpupillaryDistance;
float DistortionK[4];
int DesktopX;
int DesktopY;
char DisplayDeviceName[32];
};
LIBOVRWRAPPER_API int OVR_Init();
LIBOVRWRAPPER_API void OVR_Exit();
LIBOVRWRAPPER_API int OVR_QueryHMD(struct OVR_HMDInfo* refHmdInfo);
LIBOVRWRAPPER_API int OVR_Peek(float* w, float* x, float* y,float * z);
LIBOVRWRAPPER_API int OVR_PeekYPL(float* yaw, float* pitch, float* roll);
Your question is very difficult to understand, as it doesn't have any real details about what you've tried, what isn't working, etc.
It looks like you are trying to "run" a DLL, which isn't really possible. A DLL has to be loaded by another application. So you would have an executable of some kind that would load this DLL, and call into its OVR_Init and OVR_Exit functions.

Resources