Invalid Handle when using SetConsoleWindowInfo - c++

I'm new to C++ and decided to challenge myself with a small console game. To avoid typical flickering.
Fromm what I got from MSDN docs I should be using a Console Buffer, but I took it easy and started from simple things like changing Window title and resizing it.
The small program I wrote was meant to do just that, but for some reason I get Error Code 6 (should be "invalid handle") when I execute the SetConsoleWindowInfo.
Anyone who can point me in the right direction with this? Thank you in advance
#include <windows.h>
#include <stdio.h>
#include <iostream>
HANDLE wHandle, bHandle;
SMALL_RECT wSize = { 0,0,100,100 };
int main() {
wHandle = GetConsoleWindow();
if (wHandle == NULL) {
printf("Handle is Null");
}
SetConsoleTitle(L"NewTitle");
if (!SetConsoleWindowInfo(wHandle, TRUE, &wSize)) {
printf("SetConsoleWindowInfo (%d)\n", GetLastError());
}
getchar();
return 0;
}

Maybe this will help:
#include <windows.h>
#include <stdio.h>
#include <iostream>
HANDLE wHandle, bHandle;
//SMALL_RECT wSize = { 0,0,100,100 }; // If SetConsoleWindow fails with code 87, then this is too big!
SMALL_RECT wSize = { 0,0,60,20 }; // Works on my screen!
int main() {
// wHandle = GetConsoleWindow();
wHandle = GetStdHandle(STD_OUTPUT_HANDLE); // See comment by RbMm
if (wHandle == NULL) {
printf("Handle is Null");
}
// SetConsoleTitle(L"NewTitle"); // Don't use a wide character string!
SetConsoleTitle("NewTitle");
if (!SetConsoleWindowInfo(wHandle, TRUE, &wSize)) {
printf("SetConsoleWindowInfo (%d)\n", GetLastError());
}
getchar();
return 0;
}
Feel free to ask, if you don't understand anything I've changed (or why I've changed it), but the comments address some of the issues.

Related

ISimpleAudioVolume G/SetMute not updating

Solution: I reference the pointer of a variable instead of the variable itself. Thank you #RomanR.
I'm trying to use GetMute/SetMute through ISimpleAudioVolume, and I'm having trouble with what I'm seeing. When I run GetMute I can see that it's not muted (which is good), but when I mute my audio output, or run SetMute(false) it fails to update anything. I'm not sure if I'm setting up AudioClient correctly, but don't know how to check it.
Thanks!
Edit: I think my issue is somewhere near the top of the initialization chain. When I run check the volume it says it's 100% which isn't true. When I check the device IDs & states, the beginning of the two IDs are a bunch of 0s, and the state says they're both inactive. If I check the AudioSessionControl, there's no name, but it says the session is also inactive.
My guess is that it's somewhere in this stack of init():
check(CoInitialize(NULL));
check(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (LPVOID*)&m_deviceEnumerator));
check(m_deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &m_device));
MainVolumeControl.h
#pragma once
#include <cstdio>
#include <windows.h>
#include <audioclient.h>
#include <audiopolicy.h>
#include <Mmdeviceapi.h>
class MainVolumeControl
{
public:
MainVolumeControl();
void init();
void destroy();
void toggleMute();
void GetMute(BOOL* o_mute);
IMMDeviceEnumerator* m_deviceEnumerator;
IMMDevice* m_device;
IAudioClient* m_audioClient;
ISimpleAudioVolume* m_audioVolume;
WAVEFORMATEX* m_pwfx;
};
MainVolumeControl.cpp
MainVolumeControl::MainVolumeControl()
{
m_deviceEnumerator = nullptr;
m_device = nullptr;
m_audioClient = nullptr;
m_audioVolume = nullptr;
m_pwfx = nullptr;
}
void MainVolumeControl::init()
{
// Get Device
check(CoInitialize(NULL));
check(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (LPVOID*)&m_deviceEnumerator));
check(m_deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &m_device));
// Get Audio Client
m_device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**)&m_audioClient);
// Activate Audio Client & Get Service
check(m_audioClient->GetMixFormat(&m_pwfx));
check(m_audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, 10000000, 0, m_pwfx, NULL));
check(m_audioClient->GetService(__uuidof(ISimpleAudioVolume), (void**)&m_audioVolume));
}
void MainVolumeControl::destroy()
{
// Release the resources
m_audioVolume->Release();
m_audioClient->Release();
m_device->Release();
m_deviceEnumerator->Release();
CoUninitialize();
}
void MainVolumeControl::toggleMute()
{
BOOL mute = 0;
// Getting the mute value
check(m_audioVolume->GetMute(&mute));
check(m_audioVolume->SetMute(!&mute, NULL));
}
void MainVolumeControl::GetMute(BOOL* o_mute)
{
// Finally getting the mute value
check(m_audioVolume->GetMute(o_mute));
}
Main.cpp
int main(int argc, CHAR* argv[])
{
MainVolumeControl mvc;
BOOL mute = 1;
mvc.init();
mvc.GetMute(&mute);
printf("Mute state: %d\n", mute);
printf("Toggling mute\n");
mvc.toggleMute();
mvc.GetMute(&mute);
printf("Mute state: %d\n", mute);
mvc.destroy();
return 0;
}
Output
Mute state: 0
Toggling mute
Mute state: 0
I reference the pointer of a variable instead of the variable itself. Thank you #RomanR.
Should be:
void MainVolumeControl::toggleMute()
{
BOOL mute = 0;
// Getting the mute value
check(m_audioVolume->GetMute(&mute));
check(m_audioVolume->SetMute(!mute, NULL));
}

{app.exe!_com_error::`vector deleting destructor'(unsigned int)}

I am getting exception while creating MSMQqueue in Visual Studio 2017, find the code and exception details below:
Exception details :
app.exe!`queue::CreateQueue'::`1'::catch$3() Line 56 C++ Symbols loaded.
Please suggest the queue for implementing serial port read and write.
queue.cpp
#include "stdafx.h"
#include "MSMQ_Queue.h"
#import "mqoa.dll"
using namespace MSMQ;
queue::queue() {}
queue::~queue() {}
HRESULT queue::CreateQueue(WCHAR *wszPathName)
{
HRESULT hr = S_OK;
if (wszPathName == NULL)
{
return MQ_ERROR_INVALID_PARAMETER;
}
try
{
IMSMQQueueInfoPtr pInfo("MSMQ.MSMQQueueInfo");
// Set the queue's path name and label.
pInfo->PathName = wszPathName;
pInfo->Label = "TestQueue";
// Create the queue.
**pInfo->Create();**//Hitting exception at this point
WCHAR wszMessage[1024] = { 0 };
}
catch (const _com_error& comerr)
{
hr = comerr.Error();
WCHAR wszMessage[2048] = { 0 };
}
return hr;
}
main.cpp
#include "stdafx.h"
#include"queue.h"
#include <stdio.h> // for printf
int main()
{
wchar_t name[] = L".\\vniqueue";
queue msmqueue;
//CoInitialize(0);
OleInitialize(NULL);
HRESULT returnValue = msmqueue.CreateQueue(name);
getchar();
return 0;
}
Exception create queue
Finally I found solutions for this..
I have given public path instead of private pat. Changed “.//queuename” to .//private$//queuename”.

Debug content of shared memory

I got two processes. In process A, application Alpha is prepared for using shared memory. In process B, my windows console application with a main method accesses this shared memory. It works, I can connect to the memory. Unfortunately if I store the memory content in a variable (here pBuf) and inspect the variable via MsVisualStudioDebugger, there is only one letter in the buffer - what went wrong? How am I able to look in the memory/file to get a clue, what objects are stored in the memory? Thanks in advance.
Here is the code of my console app:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma comment(lib, "user32.lib")
using namespace std;
#define BUF_SIZE 256
TCHAR szName[] = TEXT("SIMITSHM"); // Name des SHMs;
int main(void){
std::cout << "*** start SharedMemory ***\n";
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, szName);
if (hMapFile == NULL){
MessageBox(NULL, TEXT("Could not open file mapping object"), TEXT("FEHLER"), MB_OK);
return 1;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);
if (pBuf == NULL){
MessageBox(NULL, TEXT("Could not map view of file"), TEXT("FEHLER"), MB_OK);
CloseHandle(hMapFile);
return 1;
}
MessageBox(NULL, pBuf, TEXT("SIMIT-SHM"), MB_OK); // content of memory
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
std::cout << "*** close app by typing a number. ***\n";
int a = 0;
cin >> a;
return 0;
}
UPDATE: after doing more research on this issue, I guess the problem is the casting of the return value of MapViewOfFile()-function.
UPDATE-2: Thanks Hans! I was able to look the pBuf content as a hexdump, see:
UPDATE-3: Thanks Hans! Due to your advice I was able to use fwrite() to put the shared-memory-content in a file on my local machine. Moreover I am able to see some familiar names, i.e. names like EingangMotor1 which I configured in application-Alpha and it seems this content was stored in shared memory. Now I hope to play around with application-Alpha, recognize the related changes in shared-memory and afterwards hopefully I will be able to change the values of the shared memory variable values, so application-Alpha will change its behaviour on the fly.
UPDATE-4: current code - thanks in advance for feedback, which lines needs to be improved.
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <strsafe.h>
#include <fstream>
#include <sstream>
#include <vector>
#pragma comment(lib, "user32.lib")
using namespace std;
#define BUF_SIZE 256
TCHAR szName[] = TEXT("SIMITSHM"); // Name des SHMs;
int main(void){
std::cout << "*** Start SharedMemory ***\n";
HANDLE hMapFile;
FILE * pBuf;
hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, szName);
if (hMapFile == NULL){
MessageBox(NULL, TEXT("Could not open file mapping object"), TEXT("ERROR"), MB_OK);
return 1;
}
// MapViewOfFile return a pointer to void, so you need to cast it to a suitable structure
pBuf = (FILE*) MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);
if (pBuf == NULL){
MessageBox(NULL, TEXT("Could not map view of file"), TEXT("ERROR"), MB_OK);
CloseHandle(hMapFile);
return 1;
}
// write file
FILE * pFile;
pFile = fopen ("shm-main-simit-content-fwrite.txt","w");
fwrite(pBuf, 50, 20, pFile);
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
std::cout << "*** close app by typing a number. ***\n";
int a = 0;
cin >> a;
return 0;
}
Yes, you certainly have a type mismatch. That file is very unlikely to contain a properly zero-terminated C string. Using the TCHAR macros adds to the randomness, there is no point in using them anymore. The last non-Unicode version of Windows died 10 years ago.
Answering the question: use Debug + Windows + Memory + Memory 1 and put "pBuf" in the Address box. You'll see a raw hex dump of the shared memory content.

Socket does not accept correctly in a multithread server

I'm writting an server using the multithread technique.
The idea is :
-I will use a socket (m_Server) to accept when the client connect.
-After accept, I'll use another port (t_Socket[i]) to communicate with that client.
It's simple like that. But it's took me about a week to get this far (Because I have a little bit knowledge about socket and I didn't know anything about multithread before).
Here is my code on server :
#include "stdafx.h"
#include "testServer.h"
#include "afxsock.h"
#include "conio.h"
#include "Player.h"
#include <stdio.h>
#include "../functions.h"
#include <iostream>
using namespace std;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define MAX_THREADS 1
CSocket *p_Socket=new CSocket[MAX_THREADS];
CWinApp theApp;
int count=0;
DWORD WINAPI MyThreadFunction(LPVOID lpParam)
{
int i=count;
cout<<"Send : ";
m_Send(p_Socket[i]);
return 1;
}
int m_Send(CSocket &m_Socket)
{
char Msg[100];
int MsgSize;
cin.getline(Msg,100);
MsgSize=strlen(Msg);
m_Socket.Send(&MsgSize,sizeof(int));
m_Socket.Send(Msg,MsgSize);
return MsgSize;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
HMODULE hModule = ::GetModuleHandle(NULL);
if (hModule != NULL)
{
if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
{
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
if(AfxSocketInit()==false)
{
cout<<"Initialize Library Failed"<<endl;
return false;
}
int playerIndex=0;
CSocket m_Server;
HANDLE hThreadArray[MAX_THREADS];
DWORD dwThreadIdArray[MAX_THREADS];
if(m_Server.Create(5770)==0)
{
cout<<"Can not create Socket"<<endl;
cout<<m_Server.GetLastError();
}
else
{
cout<<"Successfully initialize server"<<endl;
}
m_Server.Listen(5);
for(int i=0;i<MAX_THREADS;i++)
{
if(m_Server.Accept(p_Socket[i]))
{
cout<<"Player "<<i+1<<" connected!"<<endl;
}
}
for(int i=0;i<MAX_THREADS;i++)
{
hThreadArray[i]=CreateThread(
NULL,
0,
MyThreadFunction,
NULL,
0,
dwThreadIdArray);
//m_Send(p_Socket[i]); (1)
count++;
}
WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);
for(int i=0;i<MAX_THREADS;i++)
{
p_Socket[i].Close();
}
m_Server.Close();
cout<<"Close all connections"<<endl;
getch();
}
}
else
{
_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
nRetCode = 1;
}
return nRetCode;
}
The problem is :
-After the m_Server accept a connection. The p_Socket in the multithread function doesn't receive the right connection.
-But, look at the line I write a comment with number (1) : //m_Send(p_Socket[i]); (1).
If I run that line instead of the CreateThread line, the program will doing well. But that will make my program become single threaded.
BTW, the MAX_THREADS I set it to 1 because I want to test the code in the simpliest case. I think the problem in my code is the p_Socket[i] can't pass into a multithread function.
I have search for a solution about this for nearly 2 days. So I decided to post a question here hoping for someone will take a look at it.
Thank you for reading my question and sorry about my bad English.
One big problem is that you use a 'count' global to communicate the array index to the handler thread. That is just wrong and will not work.
Instead of passing the 'dwThreadIdArray' as the last parameter in the CreateThread API, pass in the counter 'i'.
Also, the overall structure of your server is atypical. Usually, the Accept() loop runs forever and ceates a client<>server handler thread immediately after Accept() returns, passing a socket handle/pointer as the last void* param. Your code seems to wait, running a for-loop, until MAX_THREADS clients have connected before creating the handler threads in yet another loop. It this your intended behaviour?

Get hwnd by process id c++

How can I get the HWND of application, if I know the process ID? Anyone could post a sample please? I'm using MSV C++ 2010.
I found Process::MainWindowHandle but I don't know how to use it.
HWND g_HWND=NULL;
BOOL CALLBACK EnumWindowsProcMy(HWND hwnd,LPARAM lParam)
{
DWORD lpdwProcessId;
GetWindowThreadProcessId(hwnd,&lpdwProcessId);
if(lpdwProcessId==lParam)
{
g_HWND=hwnd;
return FALSE;
}
return TRUE;
}
EnumWindows(EnumWindowsProcMy,m_ProcessId);
A single PID (Process ID) can be associated with more than one window (HWND). For example if the application is using several windows.
The following code locates the handles of all windows per a given PID.
void GetAllWindowsFromProcessID(DWORD dwProcessID, std::vector <HWND> &vhWnds)
{
// find all hWnds (vhWnds) associated with a process id (dwProcessID)
HWND hCurWnd = NULL;
do
{
hCurWnd = FindWindowEx(NULL, hCurWnd, NULL, NULL);
DWORD dwProcID = 0;
GetWindowThreadProcessId(hCurWnd, &dwProcID);
if (dwProcID == dwProcessID)
{
vhWnds.push_back(hCurWnd); // add the found hCurWnd to the vector
wprintf(L"Found hWnd %d\n", hCurWnd);
}
}
while (hCurWnd != NULL);
}
Thanks to Michael Haephrati, I slightly corrected your code for modern Qt C++ 11:
#include <iostream>
#include "windows.h"
#include "tlhelp32.h"
#include "tchar.h"
#include "vector"
#include "string"
using namespace std;
void GetAllWindowsFromProcessID(DWORD dwProcessID, std::vector <HWND> &vhWnds)
{
// find all hWnds (vhWnds) associated with a process id (dwProcessID)
HWND hCurWnd = nullptr;
do
{
hCurWnd = FindWindowEx(nullptr, hCurWnd, nullptr, nullptr);
DWORD checkProcessID = 0;
GetWindowThreadProcessId(hCurWnd, &checkProcessID);
if (checkProcessID == dwProcessID)
{
vhWnds.push_back(hCurWnd); // add the found hCurWnd to the vector
//wprintf(L"Found hWnd %d\n", hCurWnd);
}
}
while (hCurWnd != nullptr);
}
You can use EnumWindows and GetWindowThreadProcessId() functions as mentioned in this MSDN article.