How to simulate specified keyboard keystroke in c++? - c++

I have US standard keyboard but I would like to simulate the italian or chinese type of keystrokes by using SendInput method.
I use SendInput metode like this,
KEYBDINPUT kb = { 0 } ;
ZeroMemory ( & kb , sizeof ( KEYBDINPUT ) ) ;
ZeroMemory ( & kInput , sizeof ( INPUT ) ) ;
kb.wVk = 0 ;
kb.dwFlags = KEYEVENTF_UNICODE ;
kb.wScan = vk ; //vk is result of MapVirtualKey key API
kInput.type = INPUT_KEYBOARD ;
kInput.ki = kb ;
UINT res = SendInput ( 1 , & kInput , sizeof ( INPUT ) ) ;
Note :-
Without change the keyboard settings.

When using KEYEVENTF_UNICODE, the kb.wScan just has to be the wchar_t unicode character.
Don't use MapVirtualKey.
Also, don't forget to send the "Key Up" transition, just after the Key Down.
UINT res = SendInput ( 1 , & kInput , sizeof ( INPUT ) ) ;
kb.dwFlags |= KEYEVENTF_KEYUP;
res = SendInput ( 1 , & kInput , sizeof ( INPUT ) ) ;

Related

ImGui slowing down when using cpr

So I am trying to make a changelogs sort of thing
auto request = cpr::Post (
cpr::Url{ "http://leoservices.xyz/pchangelogs.php" }
);
auto response = request.text.c_str ( );
sprintf_s ( G->changelogsBuffer , "Changelogs: %s" , response );
ImGui::InputTextMultiline ( "##Change Logs" , G->changelogsBuffer , sizeof ( G->changelogsBuffer ) , ImVec2 ( ImGui::GetContentRegionAvail ( ).x - 10 , ImGui::GetContentRegionAvail ( ).y - 58 ) , ImGuiInputTextFlags_ReadOnly | ImGuiInputTextFlags_NoMarkEdited );
This is the current code but when I got to this tab it just starts laggin' is their something I am doing wrong?

Arduino servo object does not work within my own library

I have written a libary for somebody else to slowly sweep servo's from one position to another. It did not work like I intented and I had to remove the servo objects from the library. Instead I let the new version calculate the servo positions and return those values instead. Yet I really like to know why it is not working.
The header file with the private Servo objects
#include <Arduino.h>
#include <Servo.h>
class ServoSweep {
public:
ServoSweep( byte _servoPin, byte _min, byte _max, byte _speed ) ; // constructor 1
ServoSweep( byte _servoPin, byte _min, byte _max, byte _speed, byte _relayPin ) ; // constructor 2
void sweep( );
void setState( uint8_t _state );
private:
Servo servo ;
unsigned long timeToRun ;
byte pos ;
byte state ;
byte prevPos;
byte servoPin ;
byte servoSpeed ;
byte servoMin ;
byte servoMax ;
byte middlePosition ;
byte relayPresent ;
byte relayPin ;
} ;
And the source file:
#include "ServoSweep.h"
ServoSweep::ServoSweep( byte _servoPin, byte _min, byte _max, byte _speed ) { // constructor 1
servoPin = _servoPin ;
servoSpeed = _speed ;
servoMin = _min ;
servoMax = _max ;
middlePosition = ( (long)servoMax - (long)servoMin ) / (long)2 + (long)servoMin ; // start with middle position
pos = middlePosition ;
servo.write( pos ) ;
servo.attach( servoPin ) ;
}
ServoSweep::ServoSweep( byte _servoPin, byte _min, byte _max, byte _speed, byte _relayPin ) { // constructor 2
servoPin = _servoPin ;
servoSpeed = _speed ;
servoMin = _min ;
servoMax = _max ;
middlePosition = ( (long)servoMax - (long)servoMin ) / (long)2 + (long)servoMin ;
pos = middlePosition ;
servo.write( pos ) ;
servo.attach( servoPin ) ;
relayPresent = 1;
relayPin = _relayPin ;
pinMode( relayPin, OUTPUT ) ;
}
void ServoSweep::sweep () {
if( millis() > timeToRun ) {
timeToRun = millis() + servoSpeed ;
if( state ) {
if( pos < servoMax ) pos ++ ;
}
else {
if( pos > servoMin ) pos -- ;
}
if( prevPos != pos ) {
prevPos = pos ;
if( relayPresent == 1 ) {
if( pos < middlePosition ) digitalWrite( relayPin, LOW ) ;
else digitalWrite( relayPin, HIGH ) ;
}
servo.write( pos ) ;
}
}
}
void ServoSweep::setState( uint8_t _state ) {
state = _state ;
}
The servo signal was complete jitter caused by the arduino. The example sketch I used:
#include "ServoSweep.h"
const int inputButton = 12 ;
const int servoPin1 = 2 ;
const int servoPin2 = 3 ;
unsigned long prev ;
byte state ;
// pin min max speed (bigger speed = slower movement ;
ServoSweep servo1(servoPin1, 10, 30, 50) ;
ServoSweep servo2(servoPin2, 10, 30, 50) ;
void setup() {
pinMode( inputButton, INPUT_PULLUP ) ;
}
void loop() {
servo1.sweep();
servo2.sweep();
if( digitalRead( inputButton ) ) servo1.setState( 1 ) ;
else servo1.setState( 0 ) ;
if( digitalRead( inputButton ) ) servo2.setState( 0 ) ;
else servo2.setState( 1 ) ;
}
Even I comment out al code inside the loop, the jitter is there. The jitter starts as soon as I construct the ServoSweep objects.
What did I wrong with the servo objects? I assume this has to be possible.
The problem is most likely in your constructor. These lines:
servo.write( pos ) ;
servo.attach( servoPin ) ;
in the constructor are trying to work with hardware that may not be ready yet. You are calling the constructor at global scope, so these things may be happening before init() runs and sets up the hardware. So when init() does run, it is probably overwriting values that the servo library had written to timer 1.
This is a common issue and a common newbie trap. Constructors should initialize variables and set up values and things, but they are not for handling hardware. For that you need a begin() or init() method that you can call from setup. Think about how the servo library has the attach function that you have to call from setup. If it were possible to do that in the constructor, they would have had the constructor take the pin number and do it. Think about the begin method that you have to call for Serial to work. That's the same story, there's hardware to setup and you need to be able to control when that happens.
So make one more method:
void ServoSweep::begin() {
servo.write( pos ) ;
servo.attach( servoPin ) ;
}
And call that from setup for each object and remove those lines from the constructor.

Can you get graphics hardware information from a Windows service using C++?

I am trying to create a service which is going to be used for monitoring client machines and providing updates but part of the service is reporting the hardware that is being used. I currently have the following code to get the GPU information which works when run as a command line application but when it is running as a service no information is returned.
I believe this is due to services not having access to the display but I cannot find any other ways to get the GPU information that would work from a service.
QByteArrayList GetGpuNames ()
{
QByteArrayList list;
IDirect3D9* d3dobject = Direct3DCreate9 ( D3D_SDK_VERSION );
if ( !d3dobject )
return list;
D3DPRESENT_PARAMETERS d3dpresent;
memset ( &d3dpresent , 0 , sizeof ( D3DPRESENT_PARAMETERS ) );
d3dpresent.Windowed = TRUE;
d3dpresent.SwapEffect = D3DSWAPEFFECT_DISCARD;
UINT adaptercount = d3dobject->GetAdapterCount ();
D3DADAPTER_IDENTIFIER9* adapters = ( D3DADAPTER_IDENTIFIER9* ) malloc ( sizeof ( D3DADAPTER_IDENTIFIER9 ) * adaptercount );
for ( int i = 0; i < adaptercount; i++ )
{
d3dobject->GetAdapterIdentifier ( i , 0 , &( adapters [ i ] ) );
list << QByteArray ( adapters [ i ].Description );
}
return list;
}

Word 2010 automation: why does my application crash whereas excel displays an error 462

I'm using C++ for Microsoft Word 2010 automation. When the user closes the application and my programm wants to use the previously obtained IDispatch interface, the programm crashes (unhandled exception). Simular VBA code in Excel gives an "Error 462: The remote server does not exist" error. How can I detect that the application has been closed by the user in a way Excel does.
#ifdef __NO_PRECOMPILED_HEADERS__
#include "generic/platformdefs.h"
#endif
#include "test_word.h"
/*
* Include the right atlbase.h (depends on the compiler)
*/
#include "compat/which_atlbase.h"
static OLECHAR FAR *VISIBLE =
{
OLESTR( "Visible" )
} ;
static OLECHAR FAR *QUIT =
{
OLESTR( "quit" )
} ;
static void
VarSetBool( VARIANT *v , BOOL value )
{
V_VT( v ) = VT_BOOL ;
V_BOOL( v ) = value ? VARIANT_TRUE : VARIANT_FALSE ;
}
static void
DispatchPropertyPut
(
CComPtr<IDispatch> dispatch ,
OLECHAR FAR *property ,
VARIANT *value
)
{
HRESULT status ;
DISPID dispid ,
propertyput ;
DISPPARAMS parameters ;
UINT n_argument_error;
VARIANT result ;
/*
* Get the dispatch id of the method and arguments to invoke
*/
status = dispatch->GetIDsOfNames( IID_NULL ,
&property ,
1 ,
LOCALE_USER_DEFAULT ,
&dispid ) ;
if( !SUCCEEDED( status ) )
{
throw( 1 ) ;
}
/*
* Initialize result
*/
VariantInit( &result ) ;
/*
* need to be able to take the address of this
*/
propertyput = DISPID_PROPERTYPUT ;
/*
* Setup the parameters
*/
parameters.cNamedArgs = 1 ;
parameters.rgdispidNamedArgs = &propertyput ;
parameters.cArgs = 1 ;
parameters.rgvarg = value ;
/*
* Get the object
*/
status = dispatch->Invoke( dispid ,
IID_NULL,
LOCALE_USER_DEFAULT,
DISPATCH_PROPERTYPUT ,
&parameters ,
&result ,
0,
&n_argument_error ) ;
/*
* Cleanup result if any
*/
VariantClear( &result ) ;
/*
* Success ?
*/
if( !SUCCEEDED( status ) )
{
throw( 2 ) ;
}
}
static void
DispatchInvoke
(
CComPtr<IDispatch> dispatch ,
OLECHAR FAR *method
)
{
DISPID dispid ;
HRESULT status ;
DISPPARAMS parameters ;
status = dispatch->GetIDsOfNames( IID_NULL ,
&method ,
1 ,
LOCALE_USER_DEFAULT ,
&dispid ) ;
if( !SUCCEEDED( status ) )
{
throw( 3 ) ;
}
parameters.cNamedArgs = 0 ;
parameters.rgdispidNamedArgs = 0 ;
parameters.cArgs = 0 ;
parameters.rgvarg = 0 ;
status = dispatch->Invoke( dispid ,
IID_NULL,
LOCALE_USER_DEFAULT,
DISPATCH_METHOD ,
&parameters ,
0 ,
0 ,
0 ) ;
if( !SUCCEEDED( status ) )
{
throw( 4 ) ;
}
}
void
test_word( int argc , char *argv[] , void *data )
{
CComPtr<IDispatch> word ;
VARIANT v ;
HRESULT hr ;
OleInitialize( NULL ) ;
try
{
/*
* The metrowerks compiler doesn't handle __uuidof()
*/
# ifdef __MWERKS__
hr = word.CoCreateInstance( OLESTR( "Word.Application" ) ,
IID_IDispatch ,
0 ,
CLSCTX_SERVER ) ;
# else
hr = word.CoCreateInstance( OLESTR( "Word.Application" ) ,
0 ,
CLSCTX_SERVER ) ;
# endif
if( !SUCCEEDED( hr ) )
{
throw( 6 ) ;
}
VariantInit( &v ) ;
VarSetBool( &v , TRUE ) ;
DispatchPropertyPut( word , VISIBLE , &v ) ;
DispatchInvoke( word , QUIT ) ;
VarSetBool( &v , FALSE ) ;
/*
* This will crash the application
*/
DispatchPropertyPut( word , VISIBLE , &v ) ;
}
catch( int where )
{
fprintf( stderr , "Exception caught %d\n" , where ) ;
}
word.Release() ;
OleUninitialize() ;
}
The excel vba macro looks like this:
Sub test_word()
Dim word As Object
Set word = CreateObject("word.application")
word.Visible = True
word.quit()
'
' Quit the word application before the next statement
' and you will get Error 462: The remote server does not exist
'
word.Visible = False
Set word = Nothing
End Sub
This is more of a comment, but comments are limited...it might work as a solution...
Well, generally you wouldn't do what you're doing. You must be setting a breakpoint before the second property put and at that point manually closing Word. Generally, you would capture events from Word and then when Word closed, you would receive notification and then know not to use your interface pointer any more. To protect against not catching events, I might suggest first creating the application to get an IUnknown pointer first. Then when you want to make a call to IDispatch, query for the IDispatch and then make the call, and then release the IDispatch.
When you first create with an IUnknown, it will create an in process handler IUnknown for you. On the first call to query for IDispatch, it will at that point actually start up Word. On subsequent calls to QI for IDispatch and then make the call, the handler may be smart enough to just gracefully fail if Word has been shut down--or it may not. But, I would start there...if you don't want to catch events.
The real proper way to get events from Word and look for the Closing or Closed events.
Wow... just looked at Word events. Looks like there is a Quit event but not a Closing or BeforeClosing event or anything like that. So, you'd want to catch the Quit event. After that, set a flag or release your IDispatch interface and never use it again.
Interesting. Is Word 2010 all patched up? I ran the following against Word 2016 (what I have installed). It's also using Visual Studio 2017 but should compile on any Visual C++ in the last 10 years:
#include <comdef.h>
#include <atlbase.h>
class COleInitialize
{
public:
COleInitialize()
{
OleInitialize(NULL);
}
~COleInitialize()
{
OleUninitialize();
}
};
int main(int argc, char* argv[])
{
COleInitialize _oleinit;
IUnknownPtr lpUnk;
lpUnk.CreateInstance(L"Word.Application");
CComDispatchDriver disp(lpUnk);
disp.PutPropertyByName(L"Visible", &_variant_t(VARIANT_TRUE));
MessageBox(NULL, "Close Word", "Prompt", MB_OK);
return 0;
}

ToUnicodeEx not printing "Greater Than"

I wrote a function which processes the user keyboard in order to write text in an app.
In order to do that I use the ToUnicodeEx function which uses an array of Key states.
The function is working perfectly fine for every possible input, except for one : I cannot display the ">" sign, which is supposed to be the combination of "SHIFT + <" : it displays the "<" sign instead, as if the SHIFT key was not pressed, whereas it knows it it pressed.
Has somebody already experienced the same and knows what the problem is?
You will find my function code below :
void MyFunction(bool bCapsLockDown)
{
IOClass io = GetMyIOInstance();
HKL layout = GetKeyboardLayout( 0 );
uchar uKeyboardState[256];
WCHAR oBuffer[5] = {};
//Initialization of KeyBoardState
for (uint i = 0; i < 256; ++i)
{
uKeyBoardState[i] = 0;
}
// Use of my ConsultKeyState to get the status of pressed keys
if ( ConsultKeyState( VK_SHIFT ) || bCapsLockDown )
{
uKeyboardState[VK_CAPITAL] = 0xff;
}
if ( ConsultKeyState( VK_CONTROL ) )
{
uKeyboardState[VK_CONTROL] = 0xff;
}
if ( ConsultKeyState( VK_MENU ) )
{
uKeyboardState[VK_MENU] = 0xff;
}
if ( ConsultKeyState( VK_RMENU ) )
{
uKeyboardState[VK_MENU] = 0xff;
uKeyboardState[VK_CONTROL] = 0xff;
}
for ( uint iVK = 0; iVK < 256; ++iVK )
{
bool bKeyDown = ConsultKeyState( iVK ) != 0;
uint iSC = MapVirtualKeyEx( iVK, MAPVK_VK_TO_VSC, layout );
bool bKeyAlreadyDown = io.KeysDown[iVK];
io.KeysDown[iVK] = bKeyDown;
if ( io.KeysDown[iVK] && bKeyAlreadyDown == false )
{
int iRet = ToUnicodeEx( iVK, iSC, uKeyboardState, (LPWSTR)oBuffer, 4, 0, layout );
if( iRet > 0 && (iswgraph( (unsigned short) oBuffer[0] ) || oBuffer[0] == ' ') )
io.AddInputCharacter( (unsigned short) oBuffer[0] );
}
}
}
Edit :
To summarize, my question is :
What would be the good combination VirtualKey + KeyBoardState to get a ">" displayed?
The problem is that shift and caps lock do not have the same effect on a keyboard. For example, (on a UK keyboard) pressing shift+1 = !, but pressing 1 with caps lock on still give you 1.
Your code currently treats them the same, though, and it is using VK_CAPITAL in both cases. This will give you the same effect as if caps lock were on, which is not what you want in this case.
The solution is therefore to break out your logic and use VK_SHIFT when you really want shift to be pressed and VK_CAPITAL when you want caps lock to be active.