as stated on the official documentation (closehandle API description).
If the application is running under a debugger, the function will throw an exception if it receives either a handle value that is not valid or a pseudo-handle value.
For this reason the following code can be used to detect if a program is being debugged (since handle 0x1 is always invalid).
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <string>
int _tmain(int argc, _TCHAR* argv[]){
bool flag = false;
__try {
CloseHandle((HANDLE)0x1);
}
__except (EXCEPTION_EXECUTE_HANDLER) {
flag = true;
}
if (flag == false){
printf("Not debugged\n");
}else{
printf("Debugged\n");
}
}
I compiled this code using Visual Studio 2008, creating a 32bit binary.
It works correctly on Windows XP and Windows 7 32bit, but it does not work on Windows 7 64bit, because it always returns "Not debugged".
Do you have any idea why this happens?
Thank you.
Related
For Visual Studio 2019 on Windows 10 in a new project I'm getting an unexpected LNK2019 error.
I have a test function calling a function in another project where I've included the necessary *.cpp file into the test project so I can access the internals of a DLL for testing.
test.cpp:
#include "dllsubmodule.h"
void TestCountPagesInSomething()
{
// ... setup ...
int nPages;
nPages = CountPagesInSomething(iCurrentPos, hashFoundPages, hashPageCounts, sFoundData);
}
int main(int argc, char **argv)
{
TestCountPagesInSomething();
}
dllsubmodule.h
#pragma once
int CountPagesInSomething(
int iCurrentPos,
std::map<int, ERPPageInfo>& hashFoundPages,
std::map<std::string, int>& hashPageCounts,
const wxString& sFoundData
);
dllsubmodule.cpp
#include "stdafx.h"
#include "dllsubmodule.h"
int CountPagesInSomething(
int iCurrentPos,
std::map<int, ERPPageInfo>& hashFoundPages,
std::map<std::string, int>& hashPageCounts,
const wxString& sFoundData
)
{
// implementation code here...
}
For whatever reason the linker error seems to be complaining that CountPagesInSomething() doesn't exist. I suspect I'm having trouble with name mangling variations but I've no idea how to diagnose the problem.
Note: CountPagesInSomething() is internal to the DLL and not a DLL export.
Right now this is just a console project. I'm trying to get a basic printf() test working before I figure out what kind of unit test framework to use.
In my Qt5 C++ client, I'm wanting to detect when a user running Windows or OSX has locked the screen, then simultaneously lock my client application.
I have yet to come across a Qt5 class that provides this function, so I'm wondering if I'll need to write an OS-specific library. Does anyone have any experience doing something like this?
Thanks!
On windows you can use below code:
mywidget.cpp
#include "mywidget.h"
#include <Windows.h>
#include <WtsApi32.h>
#include <QDebug>
MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
WTSRegisterSessionNotification((HWND)this->winId(), NOTIFY_FOR_THIS_SESSION);
}
MyWidget::~MyWidget()
{
WTSUnRegisterSessionNotification((HWND)this->winId());
}
bool MyWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
if (eventType != "windows_generic_MSG") return false;
MSG *msg = static_cast<MSG*>(message);
switch (msg->message) {
case WM_WTSSESSION_CHANGE:
qDebug() << "session change: " << msg->wParam;
}
return false;
}
project.pro
...
LIBS += -lwtsapi32
...
reference1
reference2
Is possible to get the name of a console in Windows? Just like is done by the C function ttyname in Unix systems
You can use the WinAPI GetConsoleTitle function to retrieve it.
You might find links to all of the console functions useful.
You didn't specify a language, so here's the one in C++ from MSDN
#include <windows.h>
#include <tchar.h>
#include <conio.h>
#include <strsafe.h>
int main( void )
{
TCHAR szOldTitle[MAX_PATH];
TCHAR szNewTitle[MAX_PATH];
// Save current console title.
if( GetConsoleTitle(szOldTitle, MAX_PATH) )
{
// Build new console title string.
StringCchPrintf(szNewTitle, MAX_PATH, TEXT("TEST: %s"), szOldTitle);
// Set console title to new title
if( !SetConsoleTitle(szNewTitle) )
{
_tprintf(TEXT("SetConsoleTitle failed (%d)\n"), GetLastError());
return 1;
}
else
{
_tprintf(TEXT("SetConsoleTitle succeeded.\n"));
}
}
return 0;
}
I'm trying to figure out how to use Event Tracing for Windows... but I'm failing.
Why does this code give me the error code ERROR_WMI_INSTANCE_NOT_FOUND?
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <Wmistr.h>
#include <Evntrace.h>
#include <evntcons.h>
ULONG NTAPI EtpEtwBufferCallback(IN PEVENT_TRACE_LOGFILE Buffer) { return TRUE; }
VOID NTAPI EtpEtwEventCallback(IN PEVENT_TRACE EventTrace) { }
int _tmain()
{
LPCTSTR loggerName = KERNEL_LOGGER_NAME;
EVENT_TRACE_LOGFILE logFile = {0};
logFile.LoggerName = const_cast<LPTSTR>(loggerName);
logFile.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME;
logFile.BufferCallback = EtpEtwBufferCallback;
logFile.EventCallback = EtpEtwEventCallback;
TRACEHANDLE hTrace = OpenTrace(&logFile);
ULONG result = ProcessTrace(&hTrace, 1, NULL, NULL);
// result is ERROR_WMI_INSTANCE_NOT_FOUND
_tprintf(_T("%u\n"), result);
}
From the ProcessTrace docs, ERROR_WMI_INSTANCE_NOT_FOUND means "the session from which you are trying to consume events in real time is not running or does not have the real-time trace mode enabled".
You can start the NT Kernel Logger using tracelog from the Windows Driver Kit, though I don't have the WDK to hand so I haven't tried it.
This article explains how to start the NT Kernel Logger yourself.
I'm currently working on an application that needs to add a menu
to each application's system menu. I can accomplish that for the existing
windows with the EnumWindows function.
For the new windows (applications starting up after mine)
I'm trying to do this with windows hooks. More specifically with CBTProc.
This is where I'm stuck.
I've stripped about everything possible in the app,
but I've got the impression the procedure in my dll just doesn't
get called at all.
Here's the code for the dll:
#include <string>
using std::string;
#include <fstream>
using std::ofstream;
#include <windows.h>
// ---------------------------------------------------
extern "C"
{
void log(const string & msg)
{
ofstream out("out.log", std::ios_base::app);
out << msg;
out.flush();
out.close();
}
// ---------------------------------------------------
LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam)
{
log("CBTProc");
return CallNextHookEx(0, nCode, wParam, lParam);
}
// ---------------------------------------------------
}
I compile this with g++ 3.4.5 on a windows xp sp3 32bit machine:
g++ -shared -otest.dll test_dll.cpp
And here's the code for the application
#include <iostream>
using std::cout;
using std::cin;
using std::cerr;
using std::endl;
#include <string>
using std::string;
#include <windows.h>
typedef void (*func)();
void run()
{
cout << "press enter to exit" << endl;
cin.get();
}
void * loadProc(HMODULE mod, const char * procname)
{
void * retval = (void *)GetProcAddress(mod, procname);
if (retval == NULL)
cerr << "GetProcAddress(" << procname << ") failed" << endl;
return retval;
}
int main(int argc, char ** argv)
{
HMODULE dll = LoadLibrary("test.dll");
if (dll == NULL)
{
cerr << "LoadLibrary failed" << endl;
return 1;
}
HOOKPROC proc = (HOOKPROC)loadProc(dll, "CBTProc#12");
if (!proc)
return 1;
HHOOK callwnd = SetWindowsHookEx(WH_CBT, proc, dll, 0);
if (callwnd == NULL)
{
cerr << "SetWindowsHookEx failed for CBTProc" << endl;
return 1;
}
run();
UnhookWindowsHookEx(callwnd);
return 0;
}
I compile this with the same setup:
g++ -otest.exe test.cpp
When I run, I get no errors, but when I start up new applications I get nothing
in my logfile.
Any ideas?
gr,
ldx
Edit: spelling errors
I'd suggest you to check the following:
ensure that your DLL has an export
(can be checked with dumpbin tool). I
don't know about g++, but in MSVC it
is necessary to either use
__declspec(dllexport) or explicitly state exports in DEF file.
ensure that your host application
uses the correct name of the
exported function (the same as
"dumpbin /EXPORTS test.dll"
displays)
keep in mind that you are are using relative file name out.log - when DLL gets loaded to other processes it would write relatively to the host process' current directory. For testing purposes it would be better to use OutputDebugString API and inspect results with DbgView tool.
Chances are that your solution works already.
PS: it's not generally a good idea to use STL in an injected DLL. Make sure you are aware of the risks.