Jump to content
Sign in to follow this  
islandspapand

Get Data from Dll / Convert C++

Recommended Posts

islandspapand

Halo wounderfull Autoit Forum

I have gotten a new laptop that i am going to have the next few year and i would like to be able to get data from all its sensors like Location & Movement (GPS, Accelometer)

I have gotten the GPS to work :D

I have found the code for the Accelorometer but its in C++ :(

(and i have no experiance with .dll calls and c++)

Could some on PLEASE help me / point me in the right direction

ass i just cant get it to work in autoit / know where to start

here is the autoit code i have tried so far but keep getting

@error 1 = unable to use the DLL file, :(

;/*  * LoadSensorDLL.cpp  *  * Created on: Feb 11, 2012  * Author: CONG NGUYEN  *   */
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <math.h>

struct AccelData
{
int status;
short x; //raw data
short y; //raw data

short xx; //avg. of 40ms
short yy; //avg. of 40ms
char temp; //raw value
short x0; //used for auto-center
short y0; //used for auto-center

};

using namespace std;
typedef void * (__stdcall
*ShockproofGetAccelerometerData)(AccelData*
 accData);

//function prototypes
void calibrate(void);
void calibrateX();
void calibrateY();
short getAccelX();
short getAccelY();
double getRotationRadiansX();
double getRotationDegreesX();
double getRotationRadiansY();
double getRotationDegreesY();

//declare constants
const double PI = 3.141592;

//declare global variables
HINSTANCE hinstDLL;
AccelData accData = {0,0,0,0,0,0,0,0};
ShockproofGetAccelerometerData pfnGetData;
bool isSupported;

//declare global variables used for calibration and movement
short x_hor = 0;
short y_hor = 0;
short x_max = 0;
short y_max = 0;
double x_norm = 0.0;
double y_norm = 0.0;

double test = 0.0;

int main(void)
{
int loop = 1;
hinstDLL = LoadLibrary(L"Sensor.dll");
if(hinstDLL == 0)
{
hinstDLL = LoadLibrary(L"sensor.dll");
}

if(hinstDLL == 0)
{
isSupported = false;
}
else
{
isSupported = true;
pfnGetData = (ShockproofGetAccelerometerData)
GetProcAddress((HINSTANCE) hinstDLL,
"ShockproofGetAccelerometerData");
}

calibrate();
calibrateX();
calibrateY();


cout << x_hor << ", " << y_hor << endl;
cout << x_max << ", " << y_max << endl;
cout << endl; cout << "Calibration completed.\n";
getchar(); cout << "TIlt 45 degrees. Press any keys to confirm.\n";
getchar(); cout << getRotationDegreesY();

//end program
getchar();
FreeLibrary(hinstDLL);
return 0;
}

short getAccelX()
{
pfnGetData(&accData);
return accData.x;
}

short getAccelY()
{
pfnGetData(&accData);
return accData.y;
}

void calibrate(void)
{
cout << "Lay Thinkpad onto a flat and horizontal ground.\n";
cout << "Press any key to continue.\n";
if(getchar() == '\n')
{
x_hor = getAccelX();
y_hor = getAccelY();
}
}

void calibrateX()
{
cout << "Pitch your Thinkpad a bit backwards.\n";
cout << "Press any key, then rotate your Thinkpad back to normal position.\n";
getchar();
while(getAccelX() != x_hor)
{ if(getAccelX() > x_max)
{
x_max = getAccelX();
}
}
}

void calibrateY()
{
cout << "Roll your Thinkpad to the right a bit.\n";
cout << "Press any key, then rotate your Thinkpad back to normal position.\n";
getchar();
while(getAccelY() != y_hor)
{
if(getAccelY() > y_max)
{
y_max = getAccelY();
}
}
}

double getRotationRadiansX()
{
x_norm = (double)((double)getAccelX() - (double)x_hor) /((double)x_max - (double)x_hor); if(x_norm > 1)
{
x_norm = 1/x_norm;
}
return acos(x_norm);
}
double getRotationDegreesX()
{
return getRotationRadiansX() * 180 / PI;
}

double getRotationRadiansY()
{
y_norm = (double)((double)getAccelY() - (double)y_hor) /((double)y_max - (double)y_hor); if(y_norm > 1)
{ y_norm = 1/y_norm;
}
return acos(y_norm);
}

double getRotationDegreesY()
{
return getRotationRadiansY() * 180 / PI;
}
#cs ----------------------------------------------------------------------------
 Author: Me


 Script Function:
 Get Data from the Different Sensors in the Computer
 1. Accelerometer / Gyroscope
 2. GPS / Location
 3. ?
 4. ?

----------SysWOW64----------------
Sensor.dll
SensorsApi.dll
SensorCpl.dll
-----------------------------------

----------System32---------------
Sensor64.dll
SensorsApi.dll
SensorsClassExtension.dll
SensorCpl.dll
----------------------------------

================================== How To / Help / Code Convert =========================
http://flashandrc.wordpress.com/2012/02/12/pulling-data-from-thinkpad-aps-sensor-using-c/   ; C++
http://www.xtremevbtalk.com/showthread.php?t=284179                                         ; Vbs
http://www.autoitscript.com/forum/topic/71001-problems-with-dllcall/?hl=sensor#entry519806  ; Autoit3
=========================================================================================

================================== Credits (UDF/Code Lines/Code Samples) ================
Autoit3 Forum and all its Users whom i have borrowed a line of code or sample script
Thanks to all that have helped as well

=========================================================================================
#ce ----------------------------------------------------------------------------

#include <Array.au3>
#include <WinApi.au3>

#region === Global Variables ===
Global $SensorWOW
#endregion =====================

#region ============================================= SysWOW64 Dll ================================================================
$SensorWOW = DllOpen(@WindowsDir&"\SysWOW64\Sensor.dll")
If $SensorWOW = -1 Then MsgBox(16,"Error","Dll File didn't open")
#cs ============================================= Functions in Sensor64.dll ===================================================
ShockproofCallSMAPIBIOS             0x000000018000230c  0x0000230c  1 (0x1)     Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofControl                   0x0000000180001750  0x00001750  2 (0x2)     Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofEnableDisableSnooze       0x0000000180002230  0x00002230  3 (0x3)     Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofGetAccelerometerData      0x0000000180001da4  0x00001da4  4 (0x4)     Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofGetAccelerometerDataEx    0x0000000180001e78  0x00001e78  5 (0x5)     Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofGetAccelerometerMutex     0x0000000180001c78  0x00001c78  6 (0x6)     Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofGetAutoDisable            0x00000001800016c0  0x000016c0  7 (0x7)     Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofGetPenAbility             0x00000001800025e8  0x000025e8  8 (0x8)     Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofGetPenDelayTime           0x00000001800023e4  0x000023e4  9 (0x9)     Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofGetPenFeature             0x00000001800024e0  0x000024e0  10 (0xa)    Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofGetShockStatus            0x0000000180001b4c  0x00001b4c  11 (0xb)    Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofGetSlaveCPUinfo           0x0000000180001be4  0x00001be4  12 (0xc)    Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofGetUnloadCnt              0x0000000180001abc  0x00001abc  13 (0xd)    Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofGetVersion                0x0000000180001800  0x00001800  14 (0xe)    Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofInformPMevent             0x0000000180001f4c  0x00001f4c  15 (0xf)    Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofInvokeSnooze              0x00000001800020c8  0x000020c8  16 (0x10)   Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofManualSensitivitySetting  0x0000000180001fc8  0x00001fc8  17 (0x11)   Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofReleaseAccelerometerMutex 0x0000000180001d24  0x00001d24  18 (0x12)   Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofSetAutoDisable            0x0000000180001640  0x00001640  19 (0x13)   Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofSetPenDelayTime           0x0000000180002470  0x00002470  20 (0x14)   Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofSetPenFeature             0x0000000180002574  0x00002574  21 (0x15)   Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofSnoozeSetting             0x0000000180002130  0x00002130  22 (0x16)   Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
ShockproofTaskComplete              0x0000000180001fbc  0x00001fbc  23 (0x17)   Sensor64.DLL    C:\Windows\System32\Sensor64.DLL    Exported Function
#ce ========================================================================================================================

;~ $SensorsApiWOW = DllOpen(@WindowsDir&"\SysWOW64\SensorsApi.dll")
#cs ============================================= Functions in SensorsApi.dll =================================================
;~ DllCanUnloadNow              0x07658f96  0x00008f96  1 (0x1) SensorsApi.dll  C:\Windows\SysWOW64\SensorsApi.dll  Exported Function
;~ DllGetClassObject            0x07659bbd  0x00009bbd  2 (0x2) SensorsApi.dll  C:\Windows\SysWOW64\SensorsApi.dll  Exported Function
;~ DllRegisterServer            0x07659ddb  0x00009ddb  3 (0x3) SensorsApi.dll  C:\Windows\SysWOW64\SensorsApi.dll  Exported Function
;~ DllUnregisterServer          0x07659ea6  0x00009ea6  4 (0x4) SensorsApi.dll  C:\Windows\SysWOW64\SensorsApi.dll  Exported Function
;~ SensorPermissionsHandler     0x07666a4c  0x00016a4c  5 (0x5) SensorsApi.dll  C:\Windows\SysWOW64\SensorsApi.dll  Exported Function
;~ SensorPermissionsHandlerA    0x07666a4c  0x00016a4c  6 (0x6) SensorsApi.dll  C:\Windows\SysWOW64\SensorsApi.dll  Exported Function
;~ SensorPermissionsHandlerW    0x0766681c  0x0001681c  7 (0x7) SensorsApi.dll  C:\Windows\SysWOW64\SensorsApi.dll  Exported Function
#ce ========================================================================================================================

#endregion ========================================================================================================================


$AccData = DllStructCreate("int;short;short;short;char;short;short")
;~ $res = DllCall("sensor.dll","none","ptr",DllStructGetPtr($AccData))
;~ For $i=1 To 23
;~ $status = DllStructGetData($AccData,$i)
;~ ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $status = ' & $status & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console
;~ Next

$adll = DllCall($SensorWOW, "none", "ShockproofGetAccelerometerData", $AccData,"handle")
If Not @error Then
    MsgBox(0, "Return", $adll[1] & " " & $adll[1] & " Length " & StringLen($adll[1]))
Else
    MsgBox(0, "Error", @error)
EndIf

Thanks in advanced :D

Sensor.7z

Edited by islandspapand

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • Bilgus
      By Bilgus
      So first things first the example in the help file for _WinApi_Enum_Windows has an error
      ;_ArrayDisplay($aResult, "_WinAPI_EnumWindows", Default, Default, Default, Default, "#|Handle|Class|Title|Text|Process") Should Be _ArrayDisplay($aResult, "_WinAPI_EnumWindows", Default, Default, Default, "Handle|Class|Title|Text|Process") Next is a bit of helpful info on LPCSTR in a callback function it needs  to be passed as a PTR
      DllCallbackRegister($sFUNCT, $sRETURN, "ptr") Finally on to my question
      I'd want to call EnumPropsEX and pass a string through lparam + append to it rather than declaring anything globally
      I can Come up with two ways to do this The second it a lot more code but possibly safer but the first way I think Should do
      1. From a bit of testing It seems AutoIt won't overflow a DllStruct?
      2. Are strings passed through DLL call guaranteed to be 'an ANSI string (a minimum of 65536 chars is allocated)' as the Helpfile clearly states?
      #include <Array.au3> #include <WinAPI.au3> Example() Func Example() Local $aWindows = _WinAPI_EnumWindows() Local $aResult[$aWindows[0][0]][6] For $i = 1 To $aWindows[0][0] $aResult[$i - 1][0] = "0x" & Hex($aWindows[$i][0], 8) $aResult[$i - 1][1] = $aWindows[$i][1] $aResult[$i - 1][2] = WinGetTitle($aWindows[$i][0]) $aResult[$i - 1][3] = WinGetText($aWindows[$i][0]) $aResult[$i - 1][4] = WinGetProcess($aWindows[$i][0]) $aResult[$i - 1][5] = _ArrayToString(EnumProps($aWindows[$i][0]), ", ", 1) Next _ArrayDisplay($aResult, "_WinAPI_EnumWindows", Default, Default, Default, "Handle|Class|Title|Text|Process|Properties") EndFunc ;==>Example Func EnumProps($hWnd, $vDLL = 'user32.dll') ; Create callback function. Local $iErr = 0 Local $aProps[1] = [0] Local $hCb = DllCallbackRegister('_PropEnumProcEx', 'int', 'hwnd;ptr;handle;ptr') ; Call EnumPropsEx Local $aRet = DllCall($vDLL, 'int', 'EnumPropsEx', 'HWND', $hWnd, 'ptr', DllCallbackGetPtr($hCb), 'str', "") If @error Or Not $aRet[0] Then $iErr = @error ConsoleWrite("EnumProps Error:" & $iErr & @CRLF) ElseIf $aRet[3] <> "" Then $aProps = StringSplit($aRet[3], ";") EndIf DllCallbackFree($hCb) Return SetError($iErr, 0, $aProps) EndFunc ;==>EnumProps Func _PropEnumProcEx($hWnd, $sProp, $hData, $pStr) Local $iSzStr = _WinAPI_StringLenA($sProp) + 1 ; + Null Char If $iSzStr > 1 Then Local $tProp = DllStructCreate('char[' & $iSzStr & ']', $sProp) Local $tRetn = DllStructCreate('char[65535]', $pStr) DllStructSetData($tRetn, 1, DllStructGetData($tRetn, 1) & DllStructGetData($tProp, 1) & ";") EndIf Return 1 EndFunc ;==>_PropEnumProcEx ;-------------------------------------------------------------------------------------------------------------- Func EnumProps2($hWnd, $iSzBuffer = 4096, $vDLL = 'user32.dll') ; Create callback function. Local $iErr = 0 Local $sProps Local $aProps[1] = [0] Local $hCb = DllCallbackRegister('_PropEnumProcEx', 'int', 'hwnd;ptr;handle;ptr') Local $tProps = DllStructCreate('int;int;char[' & $iSzBuffer & ']') DllStructSetData($tProps, 1, $iSzBuffer) ;BufferSz DllStructSetData($tProps, 2, $iSzBuffer) ;BufferRemaining ; Call EnumPropsEx Local $aRet = DllCall($vDLL, 'int', 'EnumPropsEx', 'HWND', $hWnd, 'ptr', DllCallbackGetPtr($hCb), 'ptr', DllStructGetPtr($tProps)) If @error Or Not $aRet[0] Then $iErr = @error DllStructSetData($tProps, 2, 0) EndIf DllCallbackFree($hCb) $sProps = DllStructGetData($tProps, 3) If DllStructGetData($tProps, 2) > 0 Then If $sProps <> "" Then $aProps = StringSplit(StringTrimRight($sProps, 1), ";") EndIf Else If Not $iErr Then $iErr = 6 ;buffer overflow Return SetError($iErr, -DllStructGetData($tProps, 2), $aProps) EndIf Return $aProps EndFunc ;==>EnumProps2 Func _PropEnumProcEx2($hWnd, $sProp, $hData, $ptProp) Local $iSzStr = _WinAPI_StringLenA($sProp) + 1 Local $tProp = DllStructCreate('char[' & $iSzStr & ']', $sProp) If $iSzStr > 1 Then Local $sRet = DllStructGetData($tProp, 1) Local $iSzBuffer = DllStructGetData(DllStructCreate('int', $ptProp), 1) Local $tRetn = DllStructCreate('int;int;char[' & $iSzBuffer & ']', $ptProp) DllStructSetData($tRetn, 2, DllStructGetData($tRetn, 2) - $iSzStr) If DllStructGetData($tRetn, 2) > 0 Then DllStructSetData($tRetn, 3, DllStructGetData($tRetn, 3) & $sRet & ";") EndIf EndIf Return 1 EndFunc ;==>_PropEnumProcEx2  
    • BigDaddyO
      By BigDaddyO
      Hello,
       
      I'm trying to figure out how to add attributes to a Credentials Store.  I have been using it to store Creds and I was using the Comments to store some limited data but I'd really like to start using the 64 possible Attributes so I don't need to use the Registry to store misc information my script needs.
       
      I have been trying to figure this our for a few days now and I'm able to create the structure, but it fails with Invalid Parameter when trying to add the item to the store.
       
      Any ideas or pointers to where to get some further information on this?
      Thanks,
      Mike
      #include <Crypt.au3> #include <Array.au3> #include <WinAPI.au3> $sEncryptionKey = @ScriptName & 'MyS3cur!tyK3y' & @UserName $sCredName = "AttributeTest" $sUserID = "MyUserID" $sPassword = "SecretP@ssw0rd" $sDatabase = "StoredCommentHere" $sAttribute1 = "ALM.NoReply" $sAttribute2 = "Defect #?BG_BUG_ID in ?PROJECT, Status = ?BG_STATUS, Severity = ?BG_SEVERITY" $sAttribute3 = "C:\Users\MyProfile\Documents\ALM_Reports" $sAttribute4 = "UserName1,QA_Analyst|UserName2,Business_Analyst|UserName3,QA_Analyst|UserName4,QA_Analyst|UserName5,Business_Analyst|UserName6,QA_Analyst" Global $aAttribute[4, 2] = [["eMailFrom", $sAttribute1], ["eMailSubject", $sAttribute2], ["reportFldr", $sAttribute3], ["DefaultUsers", $sAttribute4]] ;Add something to the Credential Store $aAdd = _Cred_Add_WithAttributes($sCredName, $sUserID, StringEncrypt(True, $sPassword, $sEncryptionKey), $sDatabase, 1, $aAttribute) If @error Then MsgBox(0, "Error", "Failed to add credentials to " & $sCredName) Exit EndIf Func _Cred_Add_WithAttributes($sTarget, $sUser, $sPassword, $sComm = "", $iType = 2, $aAttribute = "") ;Type: 2=Domain, 1=Local Local $structTarget = DllStructCreate("wchar[100]") ; Create a structure to hold the Target object name DllStructSetData($structTarget, 1, $sTarget) ; Insert the target name into that Structure Local $structUser = DllStructCreate("wchar[100]") ; Create a structure to hold the UserName to use DllStructSetData($structUser, 1, $sUser) ; Insert the user name into the structure Local $structPwd = DllStructCreate("wchar[100]") ; Create a structure to hold the password to use DllStructSetData($structPwd, 1, $sPassword) ; Insert the password into the structure Local $structComment = DllStructCreate("wchar[100]") ; Comments seem to only work where Type = 1 legacy DllStructSetData($structComment, 1, $sComm) ;-------------------------------------------------------------------------------------------------------------------- ;-- CREDENTIAL_ATTRIBUTE structure https://msdn.microsoft.com/en-us/library/windows/desktop/aa374790(v=vs.85).aspx ;-------------------------------------------------------------------------------------------------------------------- Local $aAttrirb[UBound($aAttribute)] Local $tagCREDENTIAL_ATTRIBUTE = "" & _ "wchar Keyword;" & _ "DWORD Flags;" & _ "DWORD ValueSize;" & _ "wchar Value" For $i = 0 to UBound($aAttribute) - 1 $aAttrirb[$i] = DllStructCreate($tagCREDENTIAL_ATTRIBUTE) If @error Then ConsoleWrite("Error on $aAttrib[" & $i & "] = " & @error & @CRLF) Exit EndIf DllStructSetData($aAttrirb[$i],"Keyword",StringRight($aAttribute[$i][0], 256)) ;Name for the Attribute to use, 256 characters max If @error Then ConsoleWrite("Error adding Keyword to $aAttrib[" & $i & "] = " & @error & @CRLF) DllStructSetData($aAttrirb[$i],"Flags",0) ;Should always be 0 If @error Then ConsoleWrite("Error adding Flags to $aAttrib[" & $i & "] = " & @error & @CRLF) DllStructSetData($aAttrirb[$i],"ValueSize",256) ;Max = 256 If @error Then ConsoleWrite("Error adding ValueSize to $aAttrib[" & $i & "] = " & @error & @CRLF) DllStructSetData($aAttrirb[$i],"Value",StringRight($aAttribute[$i][1], 256)) ;Take the right most 256 characters if they put in to many If @error Then ConsoleWrite("Error adding Value to $aAttrib[" & $i & "] = " & @error & @CRLF) Next ;-------------------------------------------------------------------------------------------------------------------- Local $structCREDENTIAL= "" & _ "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" Local $NewCred = DllStructCreate($structCREDENTIAL) If @error Then MsgBox(0, "NewCred", "Error in DllStructCreate " & @error); Exit EndIf DllStructSetData($NewCred,"Flags",0) DllStructSetData($NewCred,"Type",$iType) ;2 = Domain, 1 = Generic DllStructSetData($NewCred,"TargetName",DllStructGetPtr($structTarget)) DllStructSetData($NewCred,"Persist",3) ;save to roaming profile = 3 ;Problem with this section, as if I comment out, it adds but I need Attributes. DllStructSetData($NewCred,"AttributeCount",UBound($aAttrib)) ;max = 64 If @error Then ConsoleWrite("Error adding AttributeCount (1) = " & @error & @CRLF) For $i = 0 to UBound($aAttrirb) - 1 DllStructSetData($NewCred,"Attributes", DllStructGetPtr($aAttrirb[$i])) If @error Then ConsoleWrite("Error adding Attributes (" & $i + 1 & ") = " & @error & @CRLF) Next DllStructSetData($NewCred,"UserName",DllStructGetPtr($structUser)) DllStructSetData($NewCred,"CredentialBlob",DllStructGetPtr($structPwd)) DllStructSetData($NewCred,"CredintialBlobSize",StringLen($sPassword)*2) DllStructSetData($NewCred,"Comment",DllStructGetPtr($structComment)) Local $hAdvapi32 = DllOpen("Advapi32.dll") If $hAdvapi32 = -1 Then Msgbox(0, "Error", "Failed to connect to the Credentials Store") Exit Endif $aRet = DllCall($hAdvapi32, 'bool', 'CredWriteW', 'ptr', DllStructGetPtr($NewCred), 'dword', 0) If @error Then ConsoleWrite("DllCall Error: " & @error & @CRLF) $NewCred = 0 ConsoleWrite("GetLastError = (" & _WinAPI_GetLastError() & ")" & @CRLF) ;87 = ERROR_INVALID_PARAMETER If IsArray($aRet) Then ConsoleWrite("Successfully performed the CredWriteW DLL call, Return = " & $aRet[0] & @CRLF) if UBound($aRet) > 1 Then _ArrayDisplay($aRet, "DllCall Returned") Return $aRet Else ConsoleWrite("Failed to perform the CredWriteW DLL call" & @CRLF) Return SetError(1) EndIf EndFunc Func _Cred_Get($sTarget, $iType = 2) ;Type: 2=Domain, 1=Local. CAN'T DECRYPT DOMAIN PASSWORDS!!! Local $FuncRet[3] Local $structTarget = DllStructCreate("wchar[100]") DllStructSetData($structTarget,1,$sTarget) Local $hAdvapi32 = DllOpen("Advapi32.dll") If $hAdvapi32 = -1 Then Msgbox(0, "Error", "Failed to connect to the Credentials Store") Exit Endif Local $Ret = DllCall($hAdvapi32, 'bool', 'CredReadW', 'ptr', DllStructGetPtr($structTarget), 'dword', $iType, 'dword', 0, 'ptr*', 0) if $ret[0]=0 then Return SetError(1,0,$FuncRet) Local $structCREDENTIAL= "" & _ "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "Ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" Local $tdata=DllStructCreate($structCREDENTIAL, $Ret[4]) Local $userName = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Username')) Local $User = DllStructGetData($userName, 1) Local $CredentialBlobSize = DllStructGetData($tdata, 'CredintialBlobSize') Local $credentialBlob = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'CredentialBlob')) Local $Password = StringLeft(DllStructGetData($credentialBlob, 1), $CredentialBlobSize/2) ;Once the Add Attributes is working, I need to figure out how to retrieve the Attributes that I want, below is un-tested. ; Local $eMailFrom = DllStructCreate("wchar[256]", DllStructGetData($tdata, 'eMailFrom')) ; Local $eMail = DllStructGetData($eMailFrom, 4) ; Consolewrite("eMailFrom Attribute = (" & $eMail & ")" & @crlf ) Local $Comment = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Comment')) Local $Comm = DllStructGetData($Comment, 1) Dim $FuncRet[] = [$User, $Password, $Comm] If IsArray($FuncRet) Then Return $FuncRet Else Return SetError(1) EndIf EndFunc  
    • BigDaddyO
      By BigDaddyO
      I've been working with the Windows Credentials store to store credentials for lots of RDP connections.  I'm also using this code in other scripts to store and retrieve "legacy" credentials for my scripts that have a Save Password checkbox.
      All goes well, until someone requests a button to display a list of all saved credentials.  I found the CredEnumerate call and it looks like it's working but the Target and UserName field that I want is stored inside an array of pointers and I can't figure out how to get data from inside that.  I found a post from 2009 that talks about this, but there was never a solution.
       
      Below are my functions put into an example script.  the _Credentials_Enumerate() is where i'm having problems.   Anybody have some ideas?
      Thanks,
      Mike
       
      ;Credentials Manager #include <array.au3> #include <WinAPI.au3> ;Needed for the _WinAPI_GetLastError() ;------------------------------------------------------------------------ ;----- Add items into the Credentials Store ---------------------------- ;------------------------------------------------------------------------ ;~ _Cred_Add("MyCredStored", "ItsMe", "Secret1", "", 1) ;Add a Local Credentials so we can test the retrieval of a password ;~ $aAddCred = _Cred_Add("MyServer", "Domain\adminAccount", "MyS3cr3+P@ssw0rd") ;Add domain Credentials that can only be used with RDP and other such items ;~ _ArrayDisplay($aAddCred, "AddCred") ;------------------------------------------------------------------------ ;------------------------------------------------------------------------ ;----- Retrieve Credentials from the Credentials Store ----------------- ;------------------------------------------------------------------------ ;~ $aCreds = _Cred_Get("MyServer", 2) ;Retrieve Domain Cred's, won't have password in it ;~ _ArrayDisplay($aCreds, "Credentials") $aCreds = _Credentials_Enumerate() ;Get a list of all credentials currently stored on the system **(DOES NOT WORK)** ;------------------------------------------------------------------------ ;------------------------------------------------------------------------ ;----- Delete a Credential from the Credentials Store ------------------ ;------------------------------------------------------------------------ ;~ _Cred_Delete("MyServer") ;Delete the specified item from the Credential Store ;~ For $d = 1 to UBound($aCreds) - 1 ;~ _Cred_Delete($aCreds[$d][0]) ;Loop to delete all items found. **(DOES NOT WORK)** ;~ Next ;------------------------------------------------------------------------ ;================================================================================================ ;===== Add a Credential into the Credentials Store ============================================= ;================================================================================================ Func _Cred_Add($sTarget, $sUser, $sPassword, $sComm = "", $iType = 2) ;Type: 2=Domain, 1=Local Local $structTarget = DllStructCreate("wchar[100]") ; Create a structure to hold the Target object name DllStructSetData($structTarget, 1, $sTarget) ; Insert the target name into that Structure Local $structUser = DllStructCreate("wchar[100]") ; Create a structure to hold the UserName to use DllStructSetData($structUser, 1, $sUser) ; Insert the user name into the structure Local $structPwd = DllStructCreate("wchar[100]") ; Create a structure to hole the password to use DllStructSetData($structPwd, 1, $sPassword) ; Insert the password into the structure Local $structComment = DllStructCreate("wchar[100]") ; I don't see where this is used, but was in all the examples DllStructSetData($structComment, 1, $sComm) Local $structCREDENTIAL= "" & _ "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" Local $NewCred = DllStructCreate($structCREDENTIAL) If @error Then MsgBox(0, "NewCred", "Error in DllStructCreate " & @error); Exit EndIf DllStructSetData($NewCred,"Flags",0) DllStructSetData($NewCred,"Type",$iType) ;2 = Domain, 1 = Generic DllStructSetData($NewCred,"TargetName",DllStructGetPtr($structTarget)) DllStructSetData($NewCred,"Persist",3) DllStructSetData($NewCred,"AttributeCount",0) DllStructSetData($NewCred,"UserName",DllStructGetPtr($structUser)) DllStructSetData($NewCred,"CredentialBlob",DllStructGetPtr($structPwd)) DllStructSetData($NewCred,"CredintialBlobSize",StringLen($sPassword)*2) DllStructSetData($NewCred,"Comment",DllStructGetPtr($structComment)) Local $hAdvapi32 = DllOpen("Advapi32.dll") If $hAdvapi32 = -1 Then Msgbox(0, "Error", "Failed to connect to the Credentials Store") Exit Endif $Ret = DllCall($hAdvapi32, 'bool', 'CredWriteW', 'ptr', DllStructGetPtr($NewCred), 'dword', 0) $NewCred = 0 If IsArray($Ret) Then Return $Ret Else Return SetError(1) EndIf EndFunc ;_Cred_Add ;================================================================================================ ;===== Retrieve the Credentials for the specified item ========================================= ;================================================================================================ Func _Cred_Get($sTarget, $iType = 1) ;Type: 2=Domain, 1=Local. CAN'T RETURN DOMAIN PASSWORDS!!! Local $FuncRet[3] Local $structTarget = DllStructCreate("wchar[100]") DllStructSetData($structTarget,1,$sTarget) Local $hAdvapi32 = DllOpen("Advapi32.dll") If $hAdvapi32 = -1 Then Msgbox(0, "Error", "Failed to connect to the Credentials Store") Exit Endif Local $Ret = DllCall($hAdvapi32, 'bool', 'CredReadW', 'ptr', DllStructGetPtr($structTarget), 'dword', $iType, 'dword', 0, 'ptr*', 0) if $ret[0]=0 then Return SetError(1,0,$FuncRet) Local $structCREDENTIAL= "" & _ "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "Ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" Local $tdata=DllStructCreate($structCREDENTIAL, $Ret[4]) Local $userName = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Username')) Local $User = DllStructGetData($userName, 1) Local $CredentialBlobSize = DllStructGetData($tdata, 'CredintialBlobSize') Local $credentialBlob = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'CredentialBlob')) Local $Password = StringLeft(DllStructGetData($credentialBlob, 1), $CredentialBlobSize/2) Local $Comment = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Comment')) Local $Comm = DllStructGetData($Comment, 1) Dim $FuncRet[] = [$User, $Password, $Comm] Return $FuncRet EndFunc ;_Cred_Get ;================================================================================================ ;===== Delete a specified item from the Credentials Store ====================================== ;================================================================================================ Func _Cred_Delete($sTarget, $iType = 2) ;Type: 2=Domain, 1=Local Local $structTarget = DllStructCreate("wchar[100]") ;Create a structure to hold the object name we want to delete DllStructSetData($structTarget, 1, $sTarget) ;Insert the Object Name into the Structure Local $hAdvapi32 = DllOpen("Advapi32.dll") If $hAdvapi32 = -1 Then Msgbox(0, "Error", "Failed to connect to the Credentials Store") Exit Endif ;Now send all the info into the DLL to delete the item $Ret = DllCall($hAdvapi32, 'bool', 'CredDeleteW', 'ptr', DllStructGetPtr($structTarget), 'dword', $iType, 'dword', 0) ;$iType 2 = Domain, 1 = Local EndFunc ;_Cred_Delete ;================================================================================================ ;===== Return a 2D array with the Target, UserName, Password for every item ==================== ;===== in the Credentials Store ==================== ;================================================================================================ Func _Credentials_Enumerate() ;https://msdn.microsoft.com/en-us/library/windows/desktop/aa374794(v=vs.85).aspx ;https://www.autoitscript.com/forum/topic/99705-credenumerate-function-call/?do=findComment&comment=715159 Local $aResult Local $structCREDENTIAL = "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "Ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" $aResult = DllCall('advapi32.dll', 'int', 'CredEnumerateW', _ ;Call the Unicode version of CredEnumerate 'wstr', Null, _ ;Don't use any filter since I want everything returned 'uint', 1, _ ;1 = CRED_ENUMERATE_ALL_CREDENTIALS 'uint*', '', _ ;Return the Count of all stored credentials 'ptr*', '') ;Returns a pointer to an Array of pointers? If @error Or ($aResult[0] = 0) Then ConsoleWrite('Error: ' & @error & @TAB & 'Extended: ' & @extended & @CRLF) ConsoleWrite(_WinAPI_GetLastError() & @CRLF) ;1168 = Nothing matches the filter, 1312 = no credential set for this user, 1004 = Flag/Filter options are wrong Return SetError(1) EndIf ConsoleWrite("DllCall Returned = " & $aResult[0] & @CRLF & "Credential Count = " & $aResult[3] & @CRLF & "Pointer to Creds Array = " & $aResult[4] & @CRLF) For $c = 2 to $aResult[3] ;Create enough struct for each item in each credential found $structCREDENTIAL &= "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "Ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" Next Local $tdata = DllStructCreate($structCREDENTIAL, $aResult[4]) ;Insert all the data from the array of pointers into this struct Local $FullTarget = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'TargetName')) ;Create and Get the array storing TargetName Local $userName = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Username')) ;Create and Get the array storing Username Local $CredentialBlobSize = DllStructGetData($tdata, 'CredintialBlobSize') ;Get the password blob Local $credentialBlob = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'CredentialBlob')) ;Create and get the password text Local $Comment = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Comment')) ;Don't see a need for comments ;Retrieve the data For $c = 1 to $aResult[3] Local $Target = DllStructGetData($FullTarget, $c) ;Retrieve the Target Name from the item # Local $User = DllStructGetData($userName, $c) ;Retrieve the User Name from the item # Local $Password = StringLeft(DllStructGetData($credentialBlob, $c), $CredentialBlobSize/2) ;Retrieve the password, Only works for 1, legacy. domain creds will not return passwords Local $Comm = DllStructGetData($Comment, $c) ;Don't need comments but getting it since it's in all the examples ConsoleWrite("Loop = " & $c & ": Target = " & $Target & ": UserName = " & $User & ": Comment = " & $Comm & @CRLF) Next If $aResult[3] > 0 Then $aCreds = DllCall('advapi32.dll', 'none', 'CredFree', 'ptr', $aResult[4]) ;This is just used to release the pointer. Call when done EndIf EndFunc ;_Credentials_Enumerate  
    • luckyluke
      By luckyluke
      Hello,
      Im trying to read the output from CMD using Dllcall, here is my code:
      #include <WinAPI.au3> #include <array.au3> Global Const $STD_OUTPUT_HANDLE = -11 Global Const $_CONSOLE_SCREEN_BUFFER_INFO = _ "struct;int dwSizeX;" & _ "short dwSizeY;" & _ "short dwCursorPositionX;" & _ "short dwCursorPositionY;" & _ "short wAttributes;" & _ "short Left;" & _ "short Top;" & _ "short Right;" & _ "short Bottom;" & _ "short dwMaximumWindowSizeX;" & _ "short dwMaximumWindowSizeY;endstruct" $pCmd = Run( "cmd.exe" ) Sleep(1000) $hCmd = WinGetHandle("") ConsoleWrite('handle:' & $hCmd & @CRLF) $aRet = DllCall("kernel32.dll", "int", "AttachConsole", "dword", $pCmd) ;_ArrayDisplay($aRet) If $aRet[0] <> 0 Then $vHandle_data='' $vHandle='' $vHandle_data = DllStructCreate($_CONSOLE_SCREEN_BUFFER_INFO) ; Screen Buffer structure $aRet1 = DllCall("kernel32.dll", "hwnd", "GetStdHandle", "dword", $STD_OUTPUT_HANDLE) if not @error Then $vHandle = $aRet1[0] $aRet = DllCall("kernel32.dll", "int", "GetConsoleScreenBufferInfo", "hwnd", $vHandle, _ "ptr", $vHandle_data) MsgBox(0, '1',DllStructGetData($vHandle_data, 'dwSizeX') & _WinAPI_GetLastErrorMessage()) EndIf It did not work, i got the message 'The handle is invalid'. Please help?
      Thank you in advance!
    • MazeM
      By MazeM
      Hi
      here's another UDF for the serial port. It is very similar to CommAPI using kernel32.dll, but all code is packed into a single file without any dependencies, not even using WinAPI.au3. It differs from existing UDF that it doesn't allow a timeout when reading, instead it always returns immediately, either with the requested amount ob bytes read or with a failure status. And of course there is a function provided to query the amount of available bytes in the receive buffer. The reason behind this design decision: You can do 1000 other things in the main loop while checking from time to time if enough data bytes arrived. There's no point to block the program waiting for the serial port.
      It is currently a work-in-progress, as I didn't test all functions yet. The code was developed and tested on Windows 7 64 bit.  The ComUDF-Tests.au3 shows some tests and basic usage of the UDF. Maybe there's no reason to use this UDF, given the existence of the others UDFs, but I did it to get to know DllCall better - I use structs no only to pass but also to get data back (I don't use the array returned by DllCall to read that data, unless required). You're welcome to test it on older and newer Windows versions.
      Here's a list of the implemented functions:
      ; _ComListPorts ; _ComOpenPort ; _ComSetTimeouts ; _ComClosePort ; ; _ComSetBreak ; _ComClearBreak ; _ComGetInputcount ; _ComGetOutputcount ; _ComClearOutputBuffer ; _ComClearInputBuffer ; ; _ComSendByte ; _ComReadByte ; _ComSendBinary ; _ComReadBinary ; ; _ComSendChar ; _ComReadChar ; _ComSendCharArray ; _ComReadCharArray ; _ComSendString ; _ComReadString ; ; __ComClearCommError ; __PurgeComm Maze
       
      ComUDF.au3
      ComUDF-Tests.au3
×