I want to create a simple C++ application on windows which check the display turn off time.
After some search I found this function using windows.h
int time;
bool check;
check = SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT, 0, &time, 0);
if (check) {
cout << "The Screen Saver time is : " << time << endl;
}
else {
cout << "Sorry dude the windows api can't do it" << endl;
}
but when I use this code the time is always zero and in my windows setting i set the windows to turn off display on 5 minutes
I tried some solution my self I changed the time type to long long and I got garbage number a very big number, so what I made wrong to get the screen turn off time.
OS: Windows 10
Compiler: Mingw32 and i test with MSVC 2015
Screen saver timeout and display power-off timeout are two different things.
SPI_GETSCREENSAVETIMEOUT returns the screen saver timeout - the time after which the Screen Saver is activated. If a screen saver was never configured, the value is 0.
The display power-off timeout is the time after which the power to the screen is cut, and is part of the power profile (and can differ e.g. for battery vs. AC power).
Use CallNtPowerInformation to get the display power-off timeout:
#include <iostream>
#include <windows.h>
#include <powerbase.h>
#pragma comment(lib, "PowrProf.lib")
int main() {
SYSTEM_POWER_POLICY powerPolicy;
DWORD ret;
ret = CallNtPowerInformation(SystemPowerPolicyCurrent, nullptr, 0, &powerPolicy, sizeof(powerPolicy));
if (ret == ERROR_SUCCESS) {
std::cout << "Display power-off timeout : " << powerPolicy.VideoTimeout << "s \n";
}
else {
std::cerr << "Error 0x" << std::hex << ret << std::endl;
}
}
Example output:
Display power-off timeout : 600 s
Related
I want to create my own Overclocking Monitor for which I need to read information like the current voltage, clockspeeds and others.
In C++ I can easily get the Information from Nvidia-smi with typing for example:
console("nvidia-smi -q -i voltage");
Which then displays me:
==============NVSMI LOG==============
Timestamp : Tue Dec 13 17:55:54 2022
Driver Version : 526.47
CUDA Version : 12.0
Attached GPUs : 1
GPU 00000000:01:00.0
Voltage
Graphics : 806.250 mV
From that I need only the voltage number, in this case "806.25".
I´ve investigated a bit into <cctype> which was something I´ve read about, but I´m not making any progress.
So how can I import only that number into my c++ Program? I´d just guess that the process will be the same for the other commands.
I don't currently have an Nvidia GPU to test this (stuck with Intel integrated graphics), so I can't import cuda.h but feel free to test this and let me know if it works or not.
#include <iostream>
#include <chrono>
#include <cuda.h>
int main() {
// Get the current timestamp
auto current_time = std::chrono::system_clock::now();
// Get the current driver version
int driver_version;
cudaDriverGetVersion(&driver_version);
// Get the current CUDA version
int cuda_version;
cudaRuntimeGetVersion(&cuda_version);
// Get the name of the attached GPU
cudaDeviceProp device_properties;
cudaGetDeviceProperties(&device_properties, 0);
std::string gpu_name = device_properties.name;
// Get the current voltage
int power_usage;
cudaDeviceGetPowerUsage(&power_usage, 0);
int voltage = power_usage / current;
// Output the overclocking data
std::cout << "Timestamp: " << current_time << std::endl;
std::cout << "Driver version: " << driver_version << std::endl;
std::cout << "CUDA version: " << cuda_version << std::endl;
std::cout << "Attached GPU: " << gpu_name << std::endl;
std::cout << "Voltage: " << voltage << std::endl;
return 0;
}
If it works then your voltage can be accessed from int voltage.
I've been searching for a while, and I don't achieve to find any way to get the input keys of my keyboard, to use them in my program...
Context : I'm starting on robotics, and C++, and I'd simply like to command a motor.
The idea is that "if I press the up arrow, the motor turns, if I press the down arrow, the motor stops" and that's it, no need to validate something or anything like that...
I am with raspbian, through VNC (controlling from my real computer), and the actual code is executed in the terminal.
I'll see later on to make that more complex.
I went through 20 or more pages and didn't find anything helpful... Isn't there an easy way to do something that seems so basically useful?
Some spoke about conio library, but apparently it's outdated, curses/ncurses took its place,but I didn't achieve to find/have anything working...
http://www.cplusplus.com/forum/general/74211/
Create a function to check for key press in unix using ncurses
Capture characters from standard input without waiting for enter to be pressed
This is apparently C code, and not C++, moreover, I don't really understand that...
How to detect key presses in a Linux C GUI program without prompting the user?
This, maybe? But it makes no sense to me (beginner in C++)
How can I get the keyboard state in Linux?
here they speak of "allegro", but apparently, it don't work on the PI 45 yet... and no idea how to install that anyway
http://www.cplusplus.com/forum/general/47357/
Does someone knows a simple little code that I can copy-past to do that, or any way? I'm quite shocked to not have something similar to windows C++ programming where it seems so simple
I mean something like "Keyboard.GetKeyStates(Key)"
I'll continue my research anyway, but please, help !
EDIT :
Apparently, the library SDL (SDL2) can help me do this...
I tried to implement it, it doesn't give any result...
Here is the code I got up to now (I deleted a good part that is useless in here), basically, it's a copy-past from internet SDL official web page :
#include <iostream>
#include <wiringPi.h> //Raspberry pi GPIO Library
#include <cstdio>
#include <csignal>
#include <ctime>
#include <chrono> //library for counting time
#include <thread> //for "this thread sleep"
#include <SDL2/SDL.h> //for getting the keyboard buttons events
bool RUNNING = true; // global flag used to exit from the main loop
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
GPIO Pins definition
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/
int SPser = 13, SPclk = 19, SPrclk = 26; //Define the output pins used
int Optocoupler = 17; //define the input pins used
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
SDL definition
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/
//void PrintKeyInfo( SDL_KeyboardEvent *key );
//void PrintModifiers( SDLMod mod );
//SOME CODE
// Callback handler if CTRL-C signal is detected
void my_handler(int s) {
std::cout << "Detected CTRL-C signal no. " << s << '\n';
RUNNING = false;
}
//###################################################################################
int main(int argc, char *args[]) {
// Initialize wiringPi and allow the use of BCM pin numbering
wiringPiSetupGpio();
//Initialize SDL
if (SDL_Init(SDL_INIT_EVENTS) != 0) {
SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
return 1;
}
else
{
SDL_Log("SDL initialized");
}
SDL_Event event;
// Register a callback function to be called if the user presses CTRL-C
std::signal(SIGINT, my_handler);
while(RUNNING)
{
while( SDL_PollEvent( &event ) )
{
std::cout << "SDL While \n" << '\n';
//When the user presses a key
switch( event.type )
{
case SDL_KEYDOWN:
std::cout << "Key press detected \n" << '\n';
//printf( "Key press detected\n" );
break;
case SDL_KEYUP:
std::cout << "Key release detected \n" << '\n';
//printf( "Key release detected\n" );
break;
default:
break;
}
}
//std::cout << "Works??" << '\n';
/*for( i = 0; i <= 15; i++ )
{
//std::cout << "data input i =" << i << '\n';
if (i==0){
//std::cout << "if array " << i << '\n';
DataArr[i]=1;
DataArr[15]=0;
}
else{
j=i-1;
DataArr[j]=0;
DataArr[i]=1;
//std::cout << "in else i" << i << " and j " << j << '\n';
}
SendData(DataArr);
}*/
}
std::cout << "Program ended ...\n";
}
As I followed "dumbly" the tutorial, this should work, but the while loop is never entered as the "std::cout << "SDL While \n" << '\n';" is never shown...
But, as it achieve to compile, I guess the SDL library was installed correctly and things work...
When executing the code, it writes "SDL initialized", then, nothing... pressing keys do nothing
I'm still not sure how to check if the library is installed correctly, but when I type in de command prompt "sudo apt-get install libsdl2-dev", it shows a few lines and says "0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded"
If you are on linux, you should use termios to stop the buffering
#include <termios.h>
void set_no_buffer()
{
struct termios term;
tcgetattr(0, &term);
term.c_lflag &= ~ICANON;
tcsetattr(0, TCSANOW, &term);
}
and then getchar() to get a character without entering
In efforts to learn more C++, I have chosen - you know - something fun to do and that is writing to random application's memory. The code I have written seems to work on all applications but I am having difficulties getting it to work with Google Chrome tabs.
What I am trying to do is simply change my score on Slope (on y8.com) for which I have the memory address with the help of cheat engine. The problem seems to be retrieving the Process ID of the tab. Using Chrome's Task Manager, I translated the tab's address to hex, opened the process in cheat engine and found the score address.
Here the problem comes. Whenever I use GetWindowThreadProcessId(window, &processID); cout << processID, it doesn't print the ID which can be seen in chrome's task manager for the game's tab. In fact, it prints the ID of chrome as a whole (which I know because in chrome's task manager, "chrome" has that ID). And the score cannot be written to or read from chrome's processID. If I ignore this problem, buffer seems to always print as 0.. no changes.
I am very new to this, and expect myself not to know what I am talking about. If you test the game yourself, you'll have to find the address that your chrome is using at the time. But here's the code (I have commented out the WriteProcessMemory and put Read just so I get it working before I write anything):
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main() {
int buffer = 0;
LPVOID address = (LPVOID)0x15E7E1B0FB8/*(0x000000000192DFA0 + 0x0000291D8FE04000 + 0x18)*/;
cout << "Begin playing the game and wait for the 0 score to appear" << endl;
HWND window = FindWindow(NULL, "Slope Game - Play online at Y8.com");
if (window) {
cout << "Game found running! You ready to hax?" << endl;
DWORD processID = 11180;
GetWindowThreadProcessId(window, &processID);
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, false, processID);
if (handle) {
/*string hackedScoreInput = "0";
cout << "Desired Score: " << flush; getline(cin, hackedScoreInput);
int hackedScore = stoi(hackedScoreInput);
int suc = WriteProcessMemory(handle, address, &hackedScore, sizeof(hackedScore), NULL);
if (suc > 0) {
cout << "HAXED!" << endl;
CloseHandle(handle);
}
else {
cerr << GetLastError() << endl;
cerr << hackedScore << " of size: " << sizeof(hackedScore) << endl;
return 3;
}*/
while (true) {
ReadProcessMemory(handle, address, &buffer, sizeof(buffer), NULL);
cout << buffer << " at adress: " << processID << endl;
Sleep(100);
system("CLS");
}
}
else {
cerr << "Could not open the process" << endl;
return 2;
}
}
else {
cerr << "Error! Could not find window!" << endl;
Sleep(3000);
return 1;
}
return 0;
}
What's wrong with the code?
Modern browsers use multiple processes and there is no rule that says that a browser tab HWND has to be owned by the process where the web page "runs".
Some browser implementations might have one main process that hosts the UI including all tabs but the actual web page content might be rendered to a shared bitmap/memory in a different process where it is safe to run scripts etc.
Chrome is open source so you could take a look and see if there is a way to find out which render process renders a certain tab by looking at the child processes command line arguments.
I've been trying to get into C++ and OpenGL development and such, but I've run into an issue I can't seem to figure out with the following code:
int main() {
std::cout << "Attempting to load" << std::endl;
if (!glfwInit()) {
std::cout << "Error loading GLFW" << std::endl;
return 0;
}
else {
std::cout << "Loaded GLFW" << std::endl;
}
using namespace kreezyEngine;
using namespace graphics;
Window window("Kreezy Engine", 800, 600);
while (!window.isClosed()) {
window.update();
}
return 0;
}
Now, the code works fine, it's just that I noticed it took 30 seconds to even create the window. After some debugging, I noticed that "Attempting to load" is being printed, but it takes around 30 seconds for "Loaded GLFW" to be printed in the console. I feel like thats really slow to initialize glfw, as the tutorial im watching takes no more than a second.
Any help?
Thanks :)
I'm trying to write a C++ app using RtMidi to send control signals via my Tascam FireOne MIDI Controller to Ableton Live. So far, I have it successfully sending Note On + Off Signals, Volume Up + Down Signals, etc. via my MIDI Controller to my digital piano using 'a' and 's' keypresses.
// midiout.cpp
#include <iostream>
using namespace std;
#include <signal.h>
#include <windows.h>
#include <conio.h>
#include "RtMidi.h"
int main()
{
std::vector<unsigned char> message;
int i, keyPress;
int nPorts;
char input;
RtMidiOut *midiout = 0;
// midiOUT
try {
midiout = new RtMidiOut();
// Check available ports.
nPorts = midiout->getPortCount();
if ( nPorts == 0 ) {
cout << "No ports available!" << endl;
goto cleanup;
}
// List Available Ports
cout << "\nPort Count = " << nPorts << endl;
cout << "Available Output Ports\n-----------------------------\n";
for( i=0; i<nPorts; i++ )
{
try {
cout << " Output Port Number " << i << " : " << midiout->getPortName(i) << endl;
}
catch(RtError &error) {
error.printMessage();
goto cleanup;
}
}
cout << "\nSelect an output port number :" << endl;
cin >> keyPress;
while( keyPress < 0 || keyPress >= midiout->getPortCount() )
{
cout << "\nIncorrect selection. Please try again :" << endl;
cin >> keyPress;
}
// Open Selected Port
midiout->openPort( keyPress );
keyPress = NULL;
bool done = false;
cout << "Press a key to generate a message, press 'Esc' to exit" << endl;
while(!done)
{
keyPress = _getch();
input = keyPress;
cout << input << " is: " << keyPress << endl;
switch ( keyPress )
{
case 97 :
// Process for keypress = a
// Note On: 144, 60, 90
message.push_back( 144 );
message.push_back( 60 );
message.push_back( 90 );
midiout->sendMessage( &message );
break;
case 115 :
// Process for keypress = s
// Note Off: 128, 60, 90
message.push_back( 128 );
message.push_back( 60 );
message.push_back( 90 );
midiout->sendMessage( &message );
break;
case 27 :
// Process for keypress = esc
done = true;
break;
}
message.clear();
keyPress = NULL;
}
}
catch(RtError &error) {
error.printMessage();
exit( EXIT_FAILURE );
}
cleanup:
delete midiout;
return 0;
}
I tried sending control signals in the same manner as above but this time with control values in the message bytes in place of the note-on or note-off values.
When ableton live is running, I press a key to send a signal but the app locks up and doesn't return to the start of the while loop to receive input from the next keypress.
edit: I've just noticed that even the above code (which usually runs fine) freezes when ableton live is running and I press a key.
further edit: I downloaded a really neat app called MIDI Monitor, which can monitor MIDI data being transferred: http://obds.free.fr/midimon -- my MIDI controller device has two ports -> one for MIDI and one for control. When I'm monitoring control, I can send midi signals and vice versa. However, if, for example, I'm monitoring control and I try to send some CC type data the program locks. Could this be a device driver problem? –
Does anyone know what is going wrong here?
Just one comment - your exception handling is a little weird.
I'd wrap the whole code (initialization and all) in a try/catch(RtError &err) block, and lose most of the other try/catch blocks.
In particular, I don't know what your catch(char * str) stuff will achieve, and you have no catch at all if openPort() throws.
First of all, try sending a different CC and mapping it to some arbitrary control in Ableton, just to see if it's working. The volume controls you are trying to alter behave slightly differently than regular CC's. Specifically, you should check out the MIDI organization's recommended practice for incrementing/decrementing controllers (note that 0x60 == 96), namely when they write:
This parameter uses MSB and LSB separately, with MSB adjusting sensitivity in semitones and LSB adjusting sensitivity in cents. Some manufacturers may even ignore adjustments to the LSB.