Jump to content

Recommended Posts

jazzyjeff

Hello,

I need my program to be able to add credentials in Credential manager in Windows 7. I have used the "net use x: \\servername\sharename /savecred' Command, but it doesn't seem very clean and I am not always guaranteed that it works as sometimes CMD hangs.

I see there is an API to add credentials on the MSDN site called CredWrite. I have made my best attempt to get this to work, but I am not having much luck.

I am hoping someone can look at my code and help point me in the right direction.

Here is the code I have for a UDF function:

Func _WinAPI_CredWrite($credential[11],$credential[6],$credential[2])
$credential[0] = 4 ;Flags
$credential[1] = 2 ;Type
$credential[2] = "" ;TargetName - Servername
$credential[3] = "" ;Comment
$credential[4] = @HOUR & ":" & @MIN ;LastWritten
$credential[5] = 512 ;CredentialBlobSize
$credential[6] = "" ;CredentialBlob - Password?
$credential[7] = 2 ;Persist
$credential[8] = 64 ;AttributeCount
$credential[9] = "" ; Attributes
$credential[10] = "" ;TargetAlias
$credential[11] = "" ;Username
Local $Ret = DllCall('advapi32.dll', 'int', 'CredWriteW', 'ptr', $credential, 'dword', 0)
EndFunc   ;==>_WinAPI_CredWrite

The URL for the API function is:

http://msdn.microsoft.com/en-us/library/aa375187(v=VS.85).aspx

Thanks for any help!

Jeff

Share this post


Link to post
Share on other sites
Shaggi

You need to use a dllstruct, not an array... i formatted the struct for ya:

#cs
typedef struct _CREDENTIAL {
  DWORD              Flags;
  DWORD              Type;
  LPTSTR                TargetName;
  LPTSTR                Comment;
  FILETIME            LastWritten;
  DWORD              CredentialBlobSize;
  LPBYTE                CredentialBlob;
  DWORD              Persist;
  DWORD              AttributeCount;
  PCREDENTIAL_ATTRIBUTE Attributes;
  LPTSTR                TargetAlias;
  LPTSTR                UserName;
} CREDENTIAL, *PCREDENTIAL;

typedef struct _CREDENTIAL_ATTRIBUTE {
  LPTSTR Keyword;
  DWORD  Flags;
  DWORD  ValueSize;
  LPBYTE Value;
} CREDENTIAL_ATTRIBUTE, *PCREDENTIAL_ATTRIBUTE;
#ce
$tagFILETIME =  "DWORD lowpart;DWORD highpart;"
   
$tagCREDENTIAL_ATTRIBUTE =  "wchar* Keyword;DWORD Flags; DWORD ValueSize; byte* Value;"
$tagCREDENTIAL= "" & _
    "DWORD Flags;" & _
    "DWORD Type;"  & _
    "wchar* TargetName;" & _
    "wchar* Comment;" & _
    $tagFILETIME & _
    "DWORD CredintialBlobSize" & _
    "byte* CredentialBlob" & _
    "DWORD Persist;" & _
    "DWORD AttributeCount;" & _
    "ptr Attributes;" & _ ; CREDENTIAL_ATTRIBUTE * Attributes, that is, array of those
    "wchar* TargetAlias;" &_
    "wchar* Username;"

Set data like this:

$Cred = DllStructCreate($tagCREDENTIAL)
DllStructSetData($Cred,"Flags",0x04);

Anything called "ptr" or has an asterisk needs a seperate dllstruct since they themselves are pointers to other structs.. following me? :graduated:


Ever wanted to call functions in another process? ProcessCall UDFConsole stuff: Console UDFC Preprocessor for AutoIt OMG

Share this post


Link to post
Share on other sites
jazzyjeff

Thanks for your response Shaggi. I feel like I understand what you are saying and then I read through the help file to learn about the DLLStructs and I feel more confident about using those. However, I still don't know how you implement the DLLStruct with the DLLCall.

Here is what I now have with your help.

$tagFILETIME =  "DWORD lowpart;DWORD highpart;"
$tagCREDENTIAL_ATTRIBUTE =  "wchar* Keyword;DWORD Flags; DWORD ValueSize; byte* Value;"
$tagCREDENTIAL= "" & _
    "DWORD Flags;" & _
    "DWORD Type;"  & _
    "wchar* TargetName;" & _
    "wchar* Comment;" & _
    $tagFILETIME & _
    "DWORD CredintialBlobSize" & _
    "byte* CredentialBlob" & _
    "DWORD Persist;" & _
    "DWORD AttributeCount;" & _
    "ptr Attributes;" & _ ; CREDENTIAL_ATTRIBUTE * Attributes, that is, array of those
    "wchar* TargetAlias;" & _
    "wchar* Username;"
$Cred = DllStructCreate($tagCREDENTIAL)
DllStructSetData($Cred,"Flags",0x04);
DllStructSetData($Cred,"Type",0x02);
DllStructSetData($Cred,"TargetName","\\servername");
DllStructSetData($Cred,"Comment","");
DllStructSetData($Cred,$tagFILETIME,@HOUR & ":" & @MIN);
DllStructSetData($Cred,"CredentialBlobSize",512);
DllStructSetData($Cred,"CredentialBlob","Password");
DllStructSetData($Cred,"Persist",0x02);
DllStructSetData($Cred,"AttributeCount",64);
DllStructSetData($Cred,"TargetAlias","Servername");
DllStructSetData($Cred,"Username","domain\username");
DllCall('advapi32.dll', 'int', 'CredWriteW', 'ptr', $cred, 'dword', 0)

I feel like once I have set the data in the DLL Struct, I then just run a DLLCall with the $cred variable. This doesn't seem to work though, so I am obviously missing something here.

Share this post


Link to post
Share on other sites
Beege

if it is asking for a ptr to a "credential structure", then you need to use dllstructgetptr().

DllCall('advapi32.dll', 'int', 'CredWriteW', 'ptr', DllStructGetPtr($cred), 'dword', 0)

Share this post


Link to post
Share on other sites
Shaggi

Thanks for your response Shaggi. I feel like I understand what you are saying and then I read through the help file to learn about the DLLStructs and I feel more confident about using those. However, I still don't know how you implement the DLLStruct with the DLLCall.

Here is what I now have with your help.

$tagFILETIME =  "DWORD lowpart;DWORD highpart;"
$tagCREDENTIAL_ATTRIBUTE =  "wchar* Keyword;DWORD Flags; DWORD ValueSize; byte* Value;"
$tagCREDENTIAL= "" & _
    "DWORD Flags;" & _
    "DWORD Type;"  & _
    "wchar* TargetName;" & _
    "wchar* Comment;" & _
    $tagFILETIME & _
    "DWORD CredintialBlobSize" & _
    "byte* CredentialBlob" & _
    "DWORD Persist;" & _
    "DWORD AttributeCount;" & _
    "ptr Attributes;" & _ ; CREDENTIAL_ATTRIBUTE * Attributes, that is, array of those
    "wchar* TargetAlias;" & _
    "wchar* Username;"
$Cred = DllStructCreate($tagCREDENTIAL)
DllStructSetData($Cred,"Flags",0x04);
DllStructSetData($Cred,"Type",0x02);
DllStructSetData($Cred,"TargetName","\\servername");
DllStructSetData($Cred,"Comment","");
DllStructSetData($Cred,$tagFILETIME,@HOUR & ":" & @MIN);
DllStructSetData($Cred,"CredentialBlobSize",512);
DllStructSetData($Cred,"CredentialBlob","Password");
DllStructSetData($Cred,"Persist",0x02);
DllStructSetData($Cred,"AttributeCount",64);
DllStructSetData($Cred,"TargetAlias","Servername");
DllStructSetData($Cred,"Username","domain\username");
DllCall('advapi32.dll', 'int', 'CredWriteW', 'ptr', $cred, 'dword', 0)

I feel like once I have set the data in the DLL Struct, I then just run a DLLCall with the $cred variable. This doesn't seem to work though, so I am obviously missing something here.

Do like beege said. However, there are some thing you still need to work on:

Anything called "ptr" or has an asterisk needs a seperate dllstruct since they themselves are pointers to other structs.. following me? :graduated:

What that really means is, that if you for example want to put a string in your struct, you need to make a new struct, put the data in that, and set the member in the old struct as the pointer to the new... It is done like this so it doesn't screw up the struct size. Example:

WRONG:

DllStructSetData($Cred,"TargetName","\\servername");

GOOD:

$TargetName = DllStructCreate("wchar[100]")
DllStructSetData($TargetName,1,"\\servername")
DllStructSetData($Cred,"TargetName",DllStructGetPtr($TargetName))

I know it seems a little tricky... But autoit wasn't really designed to do this kind of stuff painless. Nested structs makes it even worse. But youre on the right track!


Ever wanted to call functions in another process? ProcessCall UDFConsole stuff: Console UDFC Preprocessor for AutoIt OMG

Share this post


Link to post
Share on other sites
jazzyjeff

Thanks Beege and Shaggi.

I'm not ignoring your responses, I am just trying to figure everything you have told me out. I'll keep you posted on how I make out.

Thanks for all your help.

Share this post


Link to post
Share on other sites
jazzyjeff

You guys have been great help and I feel like I am learning a lot about this... just not enough to get it working.

So I have been reading the help file more about DLLStructs, and so I figured I would try output the values to the Console.

$tagFILETIME =  "DWORD lowpart;DWORD highpart;"
$tagCREDENTIAL_ATTRIBUTE =  "wchar* Keyword;DWORD Flags; DWORD ValueSize; byte* Value;"
$tagCREDENTIAL= "" & _
    "DWORD Flags;" & _
    "DWORD Type;"  & _
    "wchar* TargetName;" & _
    "wchar* Comment;" & _
    $tagFILETIME & _
    "DWORD CredintialBlobSize;" & _
    "byte* CredentialBlob;" & _
    "DWORD Persist;" & _
    "DWORD AttributeCount;" & _
    "ptr Attributes;" & _ ; CREDENTIAL_ATTRIBUTE * Attributes, that is, array of those
    "wchar* TargetAlias;" & _
    "wchar* Username;"
$Cred = DllStructCreate($tagCREDENTIAL)
DllStructSetData($Cred,"Flags",0x04);
DllStructSetData($Cred,"Type",0x02);
DllStructSetData($Cred,"Persist",0x02);
DllStructSetData($Cred,"AttributeCount",64);
DllStructSetData($Cred,$tagFILETIME,@HOUR & ":" & @MIN);
DllStructSetData($Cred,"CredentialBlobSize",512);
$targetName = DllStructCreate("wchar[100]")
DllStructSetData($targetName,1,"[url="file://\\servername"]\\servername[/url]")
DllStructSetData($Cred, "TargetName",DllStructGetPtr($targetName))
$comment = DllStructCreate("wchar[100]")
DllStructSetData($comment,1,"Comment")
DllStructSetData($Cred,"Comment",DllStructGetPtr($targetName))
$credentialBlob = DllStructCreate("byte[100]")
DllStructSetData($credentialBlob,1,"Password")
DllStructSetData($Cred,"CredentialBlob",DllStructGetPtr($credentialBlob));
$targetAlias = DllStructCreate("wchar[100]")
DllStructSetData($targetAlias,1,"Server")
DllStructSetData($Cred,"TargetAlias",DllStructGetPtr($targetAlias));
$username = DllStructCreate("wchar[100]")
DllStructSetData($username,1,"domain\username")
DllStructSetData($Cred,"Username",DllStructGetPtr($username));
DllCall('advapi32.dll', 'int', 'CredWriteW', 'ptr', DllStructGetPtr($Cred), 'dword', 0)
$1 = DllStructGetData($Cred,"Flags")
$2 = DllStructGetData($Cred,"Type")
$3 = DllStructGetData($Cred,"TargetName")
$4 = DllStructGetData($Cred,"Comment")
$5 = DllStructGetData($Cred, $tagFILETIME)
$6 = DllStructGetData($Cred,"CredentialBlobSize")
$7 = DllStructGetData($Cred,"CredentialBlob")
$8 = DllStructGetData($Cred,"Persist")
$9 = DllStructGetData($Cred,"AttributeCount")
$10 = DllStructGetData($Cred,"TargetAlias")
$11 = DllStructGetData($Cred,"Username")
ConsoleWrite(@CRLF & $1 & @CRLF & $2 & @CRLF & $3 & @CRLF & $4 & @CRLF & $5 & @CRLF & $6 & @CRLF & $7 & @CRLF & $8 & @CRLF & $9 & @CRLF & $10 & @CRLF & $11 & @CRLF)

All the values come to 0, so I am sure I am not obtaining the data properly from the DLLStruct.

So your example said to create a new DLLStruct when there is a string(?). Do you also have to do that for hex and decimal values? I did try on one and it didn't make a difference.

I'll explain how I am reading this and then perhaps you can tell me how I am looking at this all wrong.

We first create 2 variables:

$tagFILETIME - I have no idea really what information we are trying to get here.

$tagCredential_Attribute - Here we are telling the DLLStruct Types how to interpret the data. i.e. wchar* is a string/keyword.

$tagCredential - As required by the API we obtain/assign data that is used/required by the function in the DLL. i.e.TargetName, Username etc.

We then create the DLLStruct with the values in $tagCredential. We then are required to set the data/values for each attribute set in the DLLStruct. I.e. set the value of "Flags" to 0x04.

Now I create a new struct for the Attributes in $tagCredential and point the new struct back to the $cred struct.

Once I have repeated this for the other structs with string values, I then call the DLL with the function and point it to the variable of the first struct I created.

If you can offer anymore advice. Sorry for sounding a dumb ass, but as much as it may seem that I am not following along, I do feel like I am learning here! :-)

Share this post


Link to post
Share on other sites
jazzyjeff

Hello,

So I think I have a better understanding of why $tagCredential is there. I found the MSDN notes on the "Attributes" part of the DLLStruct and I realise the point of the array as mentioned in the notes.

So I now have that implemented in the script. I am still not able to ouptut values to the console that I have specified though.

Looking at how Yashied codes his API's I see that he seems to call the DLL first. I have tried this, but that doesn't make a difference to the result I get.

If I could get some more help in understanding this, that would be great.

Thanks,

Jeff

Global $attributes,$comment,$Cred,$credentialBlob,$tagCREDENTIAL,$tagCREDENTIAL_ATTRIBUTE,$tagFILETIME,$targetAlias,$targetName,$username
DllCall('advapi32.dll', 'int', 'CredWriteW', 'ptr', DllStructGetPtr($Cred), 'dword', 0)
$tagFILETIME =  "DWORD lowpart;DWORD highpart;"
$tagCREDENTIAL_ATTRIBUTE =  "wchar* Keyword;DWORD Flags; DWORD ValueSize; byte* Value;"
$tagCREDENTIAL= "" & _
    "DWORD Flags;" & _
    "DWORD Type;"  & _
    "wchar* TargetName;" & _
    "wchar* Comment;" & _
    $tagFILETIME & _
    "DWORD CredintialBlobSize;" & _
    "byte* CredentialBlob;" & _
    "DWORD Persist;" & _
    "DWORD AttributeCount;" & _
    "ptr Attributes;" & _ ; CREDENTIAL_ATTRIBUTE * Attributes, that is, array of those
    "wchar* TargetAlias;" & _
    "wchar* Username;"
$Cred = DllStructCreate($tagCREDENTIAL)
DllStructSetData($Cred,"Flags",0x04);
DllStructSetData($Cred,"Type",0x02);
DllStructSetData($Cred,"Persist",0x02);
DllStructSetData($Cred,"AttributeCount",0);
DllStructSetData($Cred,$tagFILETIME,@HOUR & ":" & @MIN);
DllStructSetData($Cred,"CredentialBlobSize",512);
$attributes = DllStructCreate($tagCREDENTIAL_ATTRIBUTE)
DllStructSetData($attributes,1,"")
DllStructSetData($Cred, "Keyword",DllStructGetPtr($attributes))
$attributes = DllStructCreate($tagCREDENTIAL_ATTRIBUTE)
DllStructSetData($attributes,2,0)
DllStructSetData($Cred, "Flags",DllStructGetPtr($attributes))
$attributes = DllStructCreate($tagCREDENTIAL_ATTRIBUTE)
DllStructSetData($attributes,3,256)
DllStructSetData($Cred, "ValueSize",DllStructGetPtr($attributes))
$attributes = DllStructCreate($tagCREDENTIAL_ATTRIBUTE)
DllStructSetData($attributes,4,"")
DllStructSetData($Cred, "Value",DllStructGetPtr($attributes))
$targetName = DllStructCreate("wchar[100]")
DllStructSetData($targetName,1,"\\servername")
DllStructSetData($Cred, "TargetName",DllStructGetPtr($targetName))
$comment = DllStructCreate("wchar[100]")
DllStructSetData($comment,1,"Comment")
DllStructSetData($Cred,"Comment",DllStructGetPtr($targetName))
$credentialBlob = DllStructCreate("byte[100]")
DllStructSetData($credentialBlob,1,"Password")
DllStructSetData($Cred,"CredentialBlob",DllStructGetPtr($credentialBlob));
$targetAlias = DllStructCreate("wchar[100]")
DllStructSetData($targetAlias,1,"Server")
DllStructSetData($Cred,"TargetAlias",DllStructGetPtr($targetAlias));
$username = DllStructCreate("wchar[100]")
DllStructSetData($username,1,"domain\username")
DllStructSetData($Cred,"Username",DllStructGetPtr($username));
$1 = DllStructGetData($Cred,"Flags")
$2 = DllStructGetData($Cred,"Type")
$3 = DllStructGetData($Cred,"TargetName")
$4 = DllStructGetData($Cred,"Comment")
$5 = DllStructGetData($Cred, $tagFILETIME)
$6 = DllStructGetData($Cred,"CredentialBlobSize")
$7 = DllStructGetData($Cred,"CredentialBlob")
$8 = DllStructGetData($Cred,"Persist")
$9 = DllStructGetData($Cred,"AttributeCount")
$10 = DllStructGetData($Cred,"Attributes",1)
$11 = DllStructGetData($Cred,"Attributes",2)
$12 = DllStructGetData($Cred,"Attributes",3)
$13 = DllStructGetData($Cred,"Attributes",4)
$14 = DllStructGetData($Cred,"TargetAlias")
$15 = DllStructGetData($Cred,"Username")
ConsoleWrite(@CRLF & $1 & @CRLF & $2 & @CRLF & $3 & @CRLF & $4 & @CRLF & $5 & @CRLF & $6 & @CRLF & $7 & @CRLF & $8 & @CRLF & $9 & @CRLF & $10 & @CRLF & $11 & @CRLF & $12 & @CRLF & $13 & @CRLF & $14 & @CRLF & $15 & @CRLF)

Share this post


Link to post
Share on other sites
KarlEm

Too sad, that not the final code was posted.

Here is my code.

For Domain Credentials: DllStructSetData($NewCred,"Type",2) 

For Generic change:  DllStructSetData($NewCred,"Type",1)   

 
 

 

 
 
Global $Target =  "MeinServer"
Global $User = "MeineDomainMeinUser" 
Global $Password = "MeinPWD"
Global $Comm = "mein Kommentar"
 
Global $Comment = DllStructCreate("wchar[100]")
DllStructSetData($Comment,1,$Comm)
 
Global $targetName = DllStructCreate("wchar[100]")
DllStructSetData($targetName,1,$Target)
 
Global $userName = DllStructCreate("wchar[100]")
DllStructSetData($userName,1,$User)
 
Global $credentialBlob = DllStructCreate("wchar[100]")
DllStructSetData($credentialBlob,1,$Password)
 
 
Global $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"
 
 
Global $NewCred = DllStructCreate($structCREDENTIAL)
If @error Then
MsgBox(0, "NewCred", "Error in DllStructCreate " & @error);
Exit
EndIf
 
 DllStructSetData($NewCred,"Flags",0)   
 DllStructSetData($NewCred,"Type",2)   
 DllStructSetData($NewCred,"TargetName",DllStructGetPtr($targetName))   
 DllStructSetData($NewCred,"Persist",3)
 DllStructSetData($NewCred,"AttributeCount",0) 
 DllStructSetData($NewCred,"UserName",DllStructGetPtr($userName))
 DllStructSetData($NewCred,"CredentialBlob",DllStructGetPtr($credentialBlob)) 
 DllStructSetData($NewCred,"CredintialBlobSize",StringLen($Password)*2)
 DllStructSetData($NewCred,"Comment",DllStructGetPtr($Comment))
 
#comments-start
MsgBox(0, "DllStruct", "Data:" & @CRLF & _
        "Flags: " & DllStructGetData($NewCred, "Flags") & @CRLF & _
"Type: " & DllStructGetData($NewCred,"Type") & @CRLF & _   
"TargetName: " &  DllStructGetData($NewCred,"TargetName") & @CRLF & _   
"Persist: " & DllStructGetData($NewCred,"Persist") & @CRLF & _
"AttributeCount: " &  DllStructGetData($NewCred,"AttributeCount") & @CRLF & _ 
"UserName: " &  DllStructGetData($NewCred,"UserName") & @CRLF & _
"CredentialBlob: " &  DllStructGetData($NewCred,"CredentialBlob") & @CRLF & _ 
"CredintialBlobSize: " &  DllStructGetData($NewCred,"CredintialBlobSize") & @CRLF & _
"Comment: " &  DllStructGetData($NewCred,"Comment"))
#comments-end
 
Local $hAdvapi32 = DllOpen("Advapi32.dll")
If @error Then 
Msgbox (0,"Error","Cannot open Advapi32.dll")
Exit
Endif
$Ret = DllCall($hAdvapi32, 'bool', 'CredWriteW', 'ptr', DllStructGetPtr($NewCred), 'dword', 0)
 
$NewCred = 0
Edited by KarlEm

Share this post


Link to post
Share on other sites
garbb

I was able to use that code to do CredWrite successfully and even got CredDelete to work, but I can't get CredRead to work.

You can see the entry written appear in windows control panel->credential manager.

Here is what I have so far:

#include <array.au3>

;~ CredWrite("MeinServer", "MeineDomain\MeinUser", "MeinPWD", "mein Kommentar")
;~ CredDelete("MeinServer")

CredRead("MeinServer")

Func CredRead($Target)
    Local $targetName = DllStructCreate("wchar[100]")
    DllStructSetData($targetName,1,$Target)
    Local $Comment = DllStructCreate("wchar[100]")
    Local $userName = DllStructCreate("wchar[100]")
    Local $credentialBlob = DllStructCreate("wchar[100]")
    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 $OutCred = DllStructCreate($structCREDENTIAL)
    DllStructSetData($OutCred,"TargetName",DllStructGetPtr($targetName))
    DllStructSetData($OutCred,"UserName",DllStructGetPtr($userName))
    DllStructSetData($OutCred,"CredentialBlob",DllStructGetPtr($credentialBlob))
    DllStructSetData($OutCred,"Comment",DllStructGetPtr($Comment))

    Local $hAdvapi32 = DllOpen("Advapi32.dll")
    $Ret = DllCall($hAdvapi32, 'bool', 'CredReadW', 'ptr', DllStructGetPtr($targetName), 'dword', 1, 'dword', 0, 'ptr', DllStructGetPtr($OutCred))
    _ArrayDisplay($Ret)
    $user = DllStructGetData($userName, 1)
    ConsoleWrite( $user & @CR)
    Return $user
EndFunc


func CredDelete($Target)
    Local $targetName = DllStructCreate("wchar[100]")
    DllStructSetData($targetName,1,$Target)

    Local $hAdvapi32 = DllOpen("Advapi32.dll")
    $Ret = DllCall($hAdvapi32, 'bool', 'CredDeleteW', 'ptr', DllStructGetPtr($targetName), 'dword', 1, 'dword', 0)
EndFunc

Func CredWrite($Target, $User, $Password, $Comm)
    Local $targetName = DllStructCreate("wchar[100]")
    DllStructSetData($targetName,1,$Target)

    Local $userName = DllStructCreate("wchar[100]")
    DllStructSetData($userName,1,$User)

    Local $credentialBlob = DllStructCreate("wchar[100]")
    DllStructSetData($credentialBlob,1,$Password)

    Local $Comment = DllStructCreate("wchar[100]")
    DllStructSetData($Comment,1,$Comm)

    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",1)
    DllStructSetData($NewCred,"TargetName",DllStructGetPtr($targetName))
    DllStructSetData($NewCred,"Persist",3)
    DllStructSetData($NewCred,"AttributeCount",0)
    DllStructSetData($NewCred,"UserName",DllStructGetPtr($userName))
    DllStructSetData($NewCred,"CredentialBlob",DllStructGetPtr($credentialBlob))
    DllStructSetData($NewCred,"CredintialBlobSize",StringLen($Password)*2)
    DllStructSetData($NewCred,"Comment",DllStructGetPtr($Comment))

    Local $hAdvapi32 = DllOpen("Advapi32.dll")
    If @error Then
    Msgbox (0,"Error","Cannot open Advapi32.dll")
    Exit
    Endif
    $Ret = DllCall($hAdvapi32, 'bool', 'CredWriteW', 'ptr', DllStructGetPtr($NewCred), 'dword', 0)
    $NewCred = 0
EndFunc

The DLL call to CredReadW will only return 1 if I call it with a Targetname for a credential that actually exists so I believe that it is working but I can't seem to get the data out of the output Credential struct. Or at least I think its a struct... For CredWrite MSDN says that the PCREDENTIAL parameter is pointer to a credential structure but for CredRead it says that PCREDENTIAL is a "Pointer to a single allocated block buffer to return the credential." Is this a pointer to a credential structure or something else? Does anyone know?

Either that or it is a pointer to a struct and I just can't get the data out. What is confusing me is that the credential structure has pointers to other structures/data types. What I did is create the other datatypes (like strings) and put their pointers into a credential structure and then pass the pointer of that credential structure to the CredRead function. I expected that the data I was interested in would be in the first data structures I made after the dll call was successful, but they contain nothing or a null string. Is this the correct way to do this?

Here is some code on stackoverflow that does credwrite and credread in C? or some other language.

Edited by garbb

Share this post


Link to post
Share on other sites
Danyfirex

I really don't know why the structure has no the data(I just see a little bit), but if you do something like this can see that you want:

Func CredRead($Target)
    Local $targetName = DllStructCreate("wchar[100]")
    DllStructSetData($targetName,1,$Target)
    Local $Comment = DllStructCreate("wchar[100]")
    Local $userName = DllStructCreate("wchar[100]")
    Local $credentialBlob = DllStructCreate("wchar[100]")
    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 $OutCred = DllStructCreate($structCREDENTIAL)
;~     DllStructSetData($OutCred,"TargetName",DllStructGetPtr($targetName))
;~     DllStructSetData($OutCred,"UserName",DllStructGetPtr($userName))
;~     DllStructSetData($OutCred,"CredentialBlob",DllStructGetPtr($credentialBlob))
;~     DllStructSetData($OutCred,"Comment",DllStructGetPtr($Comment))

    Local $hAdvapi32 = DllOpen("Advapi32.dll")
    $Ret = DllCall($hAdvapi32, 'bool', 'CredReadW', 'ptr', DllStructGetPtr($targetName), 'dword', 1, 'dword', 0, 'ptr*', 0)
    _ArrayDisplay($Ret)

Local $tdata=DllStructCreate("byte[200]",$Ret[4])



    FileWrite("data.txt",(DllStructGetData($tdata,1)))
    ShellExecute("data.txt")

    Return 0
EndFunc

Saludos

  • Like 1

Share this post


Link to post
Share on other sites
garbb

Thank you!

I didn't realize that I could specify a ptr* as a parameter type or that I could create a struct and tell it to use a pointer. I finally made it work.

Here's the working CredRead function:

Func CredRead($Target)
    Local $FuncRet[3]

    Local $targetName = DllStructCreate("wchar[100]")
    DllStructSetData($targetName,1,$Target)

    Local $hAdvapi32 = DllOpen("Advapi32.dll")
    Local $Ret = DllCall($hAdvapi32, 'bool', 'CredReadW', 'ptr', DllStructGetPtr($targetName), 'dword', 1, '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 

It returns the username, password, and comment in an array.

Edited by garbb

Share this post


Link to post
Share on other sites
Danyfirex

You're welcome. I did as you say first, but it did not work.(maybe I forget something.) :S

Saludos

Share this post


Link to post
Share on other sites
Schnuffel

Hi @ all,

i need a function that read the Domain credentials.

As MSDN write's there is a difference in getting the result from the dllcall.

Generic Credentials are Read like this: http://msdn.microsoft.com/en-us/library/windows/desktop/ff714499(v=vs.85).aspx

Domain Credentials are read like that: http://msdn.microsoft.com/en-us/library/windows/desktop/ff714500(v=vs.85).aspx

The difference is, that in the output there is a double **, that means that there is a Ptr to a Ptr to an Array...

Plese help to get the above function from garbb working with domain Credentials.

Thank You all for Helping ^^

Schnuffel


The two basic principles of Windows system administration:
For minor problems, reboot -- For major problems, reinstall
"Sarkasm is the lowest form of humor, but the highest form of intelligenz"
Val McDermid

Share this post


Link to post
Share on other sites
garbb

It looks like a pointer to a pointer to an array of ENCRYPTED_CREDENTIALW structures and each one of those has as its first member a pointer to a CREDENTIAL structure which is the same as I was using in my credread() above to pull out the username and password:

Local $structCREDENTIAL= "" & .... etc

But then you may have a problem because it says on the MSDN page for the CREDENTIAL structure that

Also, for CRED_TYPE_DOMAIN_PASSWORD, this member can only be read by the authentication packages.

 

And if you google for more info about this you will find that:

Domain network password method uses more stricter technique for encrypting the credentials thus providing better security over other methods. Only system process, LSASS.EXE can encrypt or decrypt these kind of passwords. LSASS is a Windows core system process responsible for enforcing the security and executing various security oriented tasks. 
 
So in order to decrypt domain passwords one has to perform decryption in the context of LSASS process. This can be achieved by injecting remote thread into LSASS process using CreateRemoteThread function

 

And so I think in order to read stored domain passwords you must do a bit more hackery. There is other software that exists (of varying legitimacy) that will get you the information that you want...

...of course I am assuming that whatever you are trying to do is all for legitimate purposes...

Share this post


Link to post
Share on other sites
Schnuffel

ty a lot garbb, as i don't want to "hack" the credentials i decided to go a different way without reading the domain cred's. I delete the Cred's that are in my interst and write them new with the user and Pass the user put in my Prog. I only wanted to check the cred's on a domain if they are locked or something like that. thx a lot Schnuffel


The two basic principles of Windows system administration:
For minor problems, reboot -- For major problems, reinstall
"Sarkasm is the lowest form of humor, but the highest form of intelligenz"
Val McDermid

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

  • Similar Content

    • ScriptJunky
      By ScriptJunky
      I noticed a lack of a constants file for _WinAPI_GetSystemMetrics() so I made this for anyone who wants to add it to their library. Enjoy!  (file attached below)
      #include-once ; #INDEX# ======================================================================================================================= ; Title .........: WinAPI GetSystemMetrics Constants ; AutoIt Version : 3.3.14.5 ; Language ......: English ; Description ...: Constants for _WinAPI_GetSystemMetrics(). ; Author(s) .....: ScriptJunky ; =============================================================================================================================== ; #CONSTANTS# =================================================================================================================== ; _WinAPI_GetSystemMetrics() Global Const $ARRANGE = 56 Global Const $CLEANBOOT = 67 Global Const $CMONITORS = 80 Global Const $CMOUSEBUTTONS = 43 Global Const $CONVERTIBLESLATEMODE = 0x2003 Global Const $CXBORDER = 5 Global Const $CXCURSOR = 13 Global Const $CXDLGFRAME = 7 Global Const $CXDOUBLECLK = 36 Global Const $CXDRAG = 68 Global Const $CXEDGE = 45 Global Const $CXFIXEDFRAME = 7 Global Const $CXFOCUSBORDER = 83 Global Const $CXFRAME = 32 Global Const $CXFULLSCREEN = 16 Global Const $CXHSCROLL = 21 Global Const $CXHTHUMB = 10 Global Const $CXICON = 11 Global Const $CXICONSPACING = 38 Global Const $CXMAXIMIZED = 61 Global Const $CXMAXTRACK = 59 Global Const $CXMENUCHECK = 71 Global Const $CXMENUSIZE = 54 Global Const $CXMIN = 28 Global Const $CXMINIMIZED = 57 Global Const $CXMINSPACING = 47 Global Const $CXMINTRACK = 34 Global Const $CXPADDEDBORDER = 92 Global Const $CXSCREEN = 0 Global Const $CXSIZE = 30 Global Const $CXSIZEFRAME = 32 Global Const $CXSMICON = 49 Global Const $CXSMSIZE = 52 Global Const $CXVIRTUALSCREEN = 78 Global Const $CXVSCROLL = 2 Global Const $CYBORDER = 6 Global Const $CYCAPTION = 4 Global Const $CYCURSOR = 14 Global Const $CYDLGFRAME = 8 Global Const $CYDOUBLECLK = 37 Global Const $CYDRAG = 69 Global Const $CYEDGE = 46 Global Const $CYFIXEDFRAME = 8 Global Const $CYFOCUSBORDER = 84 Global Const $CYFRAME = 33 Global Const $CYFULLSCREEN = 17 Global Const $CYHSCROLL = 3 Global Const $CYICON = 12 Global Const $CYICONSPACING = 39 Global Const $CYKANJIWINDOW = 18 Global Const $CYMAXIMIZED = 62 Global Const $CYMAXTRACK = 60 Global Const $CYMENU = 15 Global Const $CYMENUCHECK = 72 Global Const $CYMENUSIZE = 55 Global Const $CYMIN = 29 Global Const $CYMINIMIZED = 58 Global Const $CYMINSPACING = 48 Global Const $CYMINTRACK = 35 Global Const $CYSCREEN = 1 Global Const $CYSIZE = 31 Global Const $CYSIZEFRAME = 33 Global Const $CYSMCAPTION = 51 Global Const $CYSMICON = 50 Global Const $CYSMSIZE = 53 Global Const $CYVIRTUALSCREEN = 79 Global Const $CYVSCROLL = 20 Global Const $CYVTHUMB = 9 Global Const $DBCSENABLED = 42 Global Const $DEBUG = 22 Global Const $DIGITIZER = 94 Global Const $IMMENABLED = 82 Global Const $MAXIMUMTOUCHES = 95 Global Const $MEDIACENTER = 87 Global Const $MENUDROPALIGNMENT = 40 Global Const $MIDEASTENABLED = 74 Global Const $MOUSEPRESENT = 19 Global Const $MOUSEHORIZONTALWHEELPRESENT = 91 Global Const $MOUSEWHEELPRESENT = 75 Global Const $NETWORK = 63 Global Const $PENWINDOWS = 41 Global Const $REMOTECONTROL = 0x2001 Global Const $REMOTESESSION = 0x1000 Global Const $SAMEDISPLAYFORMAT = 81 Global Const $SECURE = 44 Global Const $SERVERR = 289 Global Const $SHOWSOUNDS = 70 Global Const $SHUTTINGDOWN = 0x2000 Global Const $SLOWMACHINE = 73 Global Const $STARTER = 88 Global Const $SWAPBUTTON = 23 Global Const $TABLETPC = 86 Global Const $XVIRTUALSCREEN = 76 Global Const $YVIRTUALSCREEN = 77  
      WinAPISystemMetricsConstants.au3
    • chacoya121
      By chacoya121
      can someone plz explain how WinAPI work and some example script plz
    • 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  
    • NHD
      By NHD
      Hi,
      I've been translated code from FreeBasic to AutoIt. And it didn't work correctly.
      Please help me!
      FreeBasic:
      #Include Once "windows.bi" #Define _RGB(r,g,b) BGR(b,g,r) CONST GRADIENT_FILL_RECT_H = 0 CONST GRADIENT_FILL_RECT_V = 1 Dim Shared hInstance As HINSTANCE ' This dll is located in Windows directory DECLARE FUNCTION Gradientfill Lib "MSIMG32" ALIAS "GradientFill" _ (hDC AS HDC, pVertex As PTRIVERTEX, dwNumVertex As Integer,pMesh AS PGRADIENT_RECT, dwNumMesh As Integer, dwMode As Integer) As Integer '******************************************************************** ' A FB Control Template '******************************************************************** Declare Function NiceButt(ByVal hWnd as HWND,byval Msg as UINT,byval wParam as WPARAM,byval lParam as LPARAM) as LRESULT Declare FUNCTION IsMouseOver (hWnd As HWND )As Integer Declare SUB Draw_Gradient (hdc as HDC, x As Integer, y As integer, w As integer, h As Integer, r As integer, g As integer, b As integer) Declare FUNCTION Register_NiceButt()As Integer ' 'Windows calls this function when the dll is loaded. /'Function DllMain alias "MAIN"(byval hModule as HMODULE,byval reason as Integer,byval lpReserved as LPVOID) as BOOL Select case reason case DLL_PROCESS_ATTACH hInstance=hModule Register_NiceButt() MessageBox(GetActiveWindow(),"OK","OK",MB_OK) Return 0 case DLL_PROCESS_DETACH ' end select return TRUE end function '/ FUNCTION Register_NiceButt()As Integer Export DIM wc AS WNDCLASSEX DIM szClassName As String szClassName = "NiceButt" wc.cbSize = SIZEOF(WNDCLASSEX) wc.style = CS_HREDRAW OR CS_VREDRAW OR CS_GLOBALCLASS wc.hInstance = GetmoduleHandle(0) 'hInstance wc.hbrBackground = Cast(HBRUSH,COLOR_BTNFACE+1) wc.lpszClassName = StrPtr(szClassName) wc.lpfnWndProc = @NiceButt wc.cbClsExtra = 0 wc.cbWndExtra = 0 wc.hIcon = 0 wc.hCursor = 0 wc.lpszMenuName = 0 wc.hIconSm = 0 FUNCTION = RegisterClassEx(@wc) END FUNCTION '******************************************************************** ' Custom Control Procedure '******************************************************************** Function NiceButt(ByVal hWnd as HWND,byval Msg as UINT,byval wParam as WPARAM,byval lParam as LPARAM) as LRESULT STATIC As Integer ButtDown,mouseover STATIC Captured AS HWND SELECT Case Msg '************************** CASE WM_CREATE '************************** DIM Region AS HRGN DIM Rct AS RECT DIM As Integer x, y, w, h ButtDown = FALSE GetClientRect (hWnd,@Rct) ' <<-- Get the size of our control x = Rct.left y = Rct.top w = Rct.right - Rct.left h = Rct.bottom - Rct.top 'Region = CreateRoundRectRgn(10,10,w,h, h * 0.90 , h * 0.90 ) 'SetWindowRgn (hWnd,Region,True) InvalidateRect(hWnd,0,0) 'EXIT FUNCTION ' ******************* CASE WM_PAINT ' ******************* DIM hDC AS HDC DIM ps AS PAINTSTRUCT DIM hPen AS HPEN DIM hBrush AS HBRUSH DIM hOldBrush AS HBRUSH DIM Rct AS RECT DIM Size AS SIZE DIM T As ZString*2048 DIM As Integer i DIM As Integer XCtr DIM As Integer YCtr DIM As Integer x,y,w,h DIM As Integer r,g,b ' ******************* GetClientRect (hWnd,@Rct) ' <<-- Get the size of our control x = Rct.left y = Rct.top w = Rct.right - Rct.left h = Rct.bottom - Rct.top XCtr = (Rct.left + Rct.right) / 2 ' Horizontal center of our ctrl YCtr = (Rct.top + Rct.bottom) / 2 ' Vertical center of our ctrl GetWindowText(hWnd,T ,255) ' Grab a copy of control caption '********************************** ' Draw our control '********************************** hDC = BeginPaint (hWnd, @ps) GetTextExtentPoint32(hDC, T , LEN(T),@Size) ' Get caption size r = 30 : g = 90 : b = 90 Draw_Gradient (hDC, x, y, w, h, r, g, b) SetBkMode (hDC,TRANSPARENT) IF ButtDown THEN SetTextColor(hDC,_RGB(255,0,0)) TextOut(hDC, XCtr-(Size.cx/2)+1, YCtr-(Size.cy/2)+1,T,LEN(T)) ELSE SetTextColor(hDC,_RGB(0,0,255)) TextOut(hDC, XCtr-Size.cx/2, YCtr-Size.cy/2,T,LEN(T)) END IF EndPaint (hWnd,@ps) 'EXIT FUNCTION '****************************** CASE WM_LBUTTONUP '****************************** IF hWnd = Captured THEN DIM hParent AS HWND ReleaseCapture() ButtDown = FALSE InvalidateRect(hWnd,0,0) hParent=GetParent(hWnd) SendMessage(hParent,WM_COMMAND,MAKELONG(GetWindowLong(hWnd,GWL_ID), BN_CLICKED),Cast(LONG,hWnd)) END IF 'EXIT FUNCTION '****************************** CASE WM_LBUTTONDOWN '****************************** SetCapture(hWnd) Captured = hWnd ButtDown = TRUE SetFocus (hWnd) InvalidateRect(hWnd,0,0) 'EXIT FUNCTION '****************************** CASE WM_MOUSEMOVE '****************************** IF ButtDown THEN IF IsMouseOver(hWnd) THEN ButtDown = TRUE InvalidateRect(hWnd,0,0) ELSE ReleaseCapture() ButtDown = FALSE InvalidateRect(hWnd,0,0) END IF END IF 'EXIT FUNCTION '****************************** CASE WM_MOVING '****************************** ReleaseCapture() ButtDown = FALSE InvalidateRect(hWnd,0,0) 'EXIT FUNCTION '****************************** CASE WM_SIZE '****************************** ReleaseCapture() ButtDown = FALSE InvalidateRect(hWnd,0,0) 'EXIT FUNCTION END Select Return DefWindowProc(hwnd,Msg,wparam,lparam) END FUNCTION SUB Draw_Gradient (hdc as HDC, x As Integer, y As integer, w As integer, h As Integer, r As integer, g As integer, b As integer) DIM Vert(2) AS TRIVERTEX DIM Rect AS GRADIENT_RECT '****************************************************** Vert (0).x = 0 Vert (0).y = 0 Vert (0).Red = 65535-(65535-(r*256)) Vert (0).Green = 65535-(65535-(g*256)) Vert (0).Blue = 65535-(65535-(b*256)) Vert (0).Alpha = 0 '****************************************************** Vert (1).x = w Vert (1).y = h/2 Vert (1).Red = 65535-(65535-(255*256)) Vert (1).Green = 65535-(65535-(255*256)) Vert (1).Blue = 65535-(65535-(255*256)) Vert (1).Alpha = 0 '****************************************************** Rect.UpperLeft = 0 Rect.LowerRight = 1 '****************************************************** Gradientfill(hdc,@Vert(0),2,@Rect,1,GRADIENT_FILL_RECT_V) '****************************************************** Vert (0).x = 0 Vert (0).y = h/2 Vert (0).Red = 65535-(65535-(255*256)) Vert (0).Green = 65535-(65535-(255*256)) Vert (0).Blue = 65535-(65535-(255*256)) Vert (0).Alpha = 0 '****************************************************** Vert (1).x = w Vert (1).y = h Vert (1).Red = 65535-(65535-(r*256)) Vert (1).Green = 65535-(65535-(g*256)) Vert (1).Blue = 65535-(65535-(b*256)) Vert (1).Alpha = 0 '****************************************************** Rect.UpperLeft = 0 Rect.LowerRight = 1 '****************************************************** Gradientfill(hdc,@Vert(0),2,@Rect,1,GRADIENT_FILL_RECT_V) END SUB FUNCTION IsMouseOver (hWnd As HWND )As Integer DIM Rect As RECT DIM Pt As POINT GetWindowRect (hWnd, @Rect) GetCursorPos(@Pt) FUNCTION = PtInRect (@Rect, Pt) END FUNCTION  
      AutoIt:
      #include-once #include <WinAPI.au3> #include <WinAPIGdi.au3> #include <WinAPISys.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> ;~ #Include <windows.bi> Global Const $_tagRect = "struct;long left;long top;long right;long bottom;endstruct" Global Const $_tagSize = "struct;long cx;long cy;endstruct" Global Const $_tagGradient_Rect = "struct;ulong UpperLeft;ulong LowerRight;endstruct" Global Const $_tagPoint = "struct;long x;long y;endstruct" Global Const $_tagTrivertex = "struct;long x;long y;int Red;int Greed;int Blue;int Alpha;endstruct" Global Const $_tagPaintStruct = "struct;handle hdc;bool fErase;long left;long top;long right;long bottom;bool fRestore;bool fIncUpdate;byte rgbReserved[32];endstruct" Global Const $_tagWNDCLASSEX = "struct;uint cbSize;uint style;ptr lpfnWndProc;int cbClsExtra;int cbWndExtra;ptr hInstance;ptr hIcon;" & _ "ptr hCursor; ptr hbrBackground; ptr lpszMenuName;ptr lpszClassName;ptr hIconSm;endstruct" Global Const $CS_VREDRAW = 0x0001, $CS_HREDRAW =0x0002, $CS_GLOBALCLASS = 0x4000 Global Const $BN_CLICKED = 0 ;~ #Define _RGB(r,g,b) BGR(b,g,r) Global Const $GRADIENT_FILL_RECT_H = 0 Global Const $GRADIENT_FILL_RECT_V = 1 ;~ Dim Shared hInstance As HINSTANCE ;~ ' This dll is located in Windows directory ;~ DECLARE FUNCTION Gradientfill Lib "MSIMG32" ALIAS "GradientFill" _ ;~ (hDC AS HDC, pVertex As PTRIVERTEX, dwNumVertex As Integer,pMesh AS PGRADIENT_RECT, dwNumMesh As Integer, dwMode As Integer) As Integer ;~ '******************************************************************** ;~ ' A FB Control Template ;~ '******************************************************************** ;~ Declare Function NiceButt(ByVal hWnd as HWND,byval Msg as UINT,byval wParam as WPARAM,byval lParam as LPARAM) as LRESULT ;~ Declare FUNCTION IsMouseOver (hWnd As HWND )As Integer ;~ Declare SUB Draw_Gradient (hdc as HDC, x As Integer, y As integer, w As integer, h As Integer, r As integer, g As integer, b As integer) ;~ Declare FUNCTION Register_NiceButt()As Integer #cs ' 'Windows calls this function when the dll is loaded. /'Function DllMain alias "MAIN"(byval hModule as HMODULE,byval reason as Integer,byval lpReserved as LPVOID) as BOOL Select case reason case DLL_PROCESS_ATTACH hInstance=hModule Register_NiceButt() MessageBox(GetActiveWindow(),"OK","OK",MB_OK) Return 0 case DLL_PROCESS_DETACH ' end select return True end function '/ #ce #Region ### START Koda GUI section ### Form= $Form1 = GUICreate("Form1", 615, 437, 192, 124) RegisterButton() Global $Ctrl = _winapi_CreateWindowEx(0, "TestButton", "Test", BitOR($WS_VISIBLE, $WS_CHILD), 10, 10, 80, 30, $Form1) ConsoleWrite(@CRLF & $Ctrl) GUISetState(@SW_SHOW) _WinAPI_UpdateWindow($Form1) #EndRegion ### END Koda GUI section ### While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit EndSwitch WEnd Func RegisterButton() Local $hDll = DllCallbackRegister('TestButtonProc', 'lresult', 'hwnd;uint;wparam;lparam') ;~ DIM wc AS WNDCLASSEX ;~ DIM szClassName As String Local $sClass = "TestButton" Local $wc = DllStructCreate($_tagWNDCLASSEX & ';wchar szClassName[' & (StringLen($sClass) + 1) & ']') ;~ szClassName = "NiceButt" ;~ wc.cbSize = SIZEOF(WNDCLASSEX) $wc.cbSize = DllStructGetPtr($wc, 'szClassName') - DllStructGetPtr($wc) ;~ wc.style = CS_HREDRAW OR CS_VREDRAW OR CS_GLOBALCLASS $wc.style = BitOR($CS_HREDRAW, $CS_VREDRAW, $CS_GLOBALCLASS) ;~ wc.hInstance = GetmoduleHandle(0) 'hInstance $wc.hInstance = _WinAPI_GetModuleHandle(0) ;~ wc.hbrBackground = Cast(HBRUSH,COLOR_BTNFACE+1) ;/// $wc.hbrBackground = _WinAPI_CreateSolidBrush(_WinAPI_GetSysColor($COLOR_BTNFACE)) ;~ wc.lpszClassName = StrPtr(szClassName) $wc.lpszClassName = DllStructGetPtr($wc, 'szClassName') ;~ wc.lpfnWndProc = @NiceButt $wc.lpfnWndProc = DllCallbackGetPtr($hDll) ;~ wc.cbClsExtra = 0 $wc.cbClsExtra = 0 ;~ wc.cbWndExtra = 0 $wc.cbWndExtra = 0 ;~ wc.hIcon = 0 $wc.hIcon = 0 ;~ wc.hCursor = 0 $wc.hCursor = 0 ;~ wc.lpszMenuName = 0 $wc.lpszMenuName = 0 ;~ wc.hIconSm = 0 $wc.hIconSm = 0 $wc.szClassName = $sClass ;~ FUNCTION = RegisterClassEx(@wc) Local $aRet = _WinAPI_RegisterClassEx($wc) Return $aRet ;~ END FUNCTION EndFunc ;******************************************************************** ; Custom Control Procedure ;******************************************************************** ;~ Function NiceButt(ByVal hWnd as HWND,byval Msg as UINT,byval wParam as WPARAM,byval lParam as LPARAM) as LRESULT Func TestButtonProc($hWnd, $iMsg, $wParam, $lParam) Static $bBtnDown, $bMouseOver, $hCaptured Switch $iMsg Case $WM_CREATE Local $Rct = DllStructCreate($_tagRect) Local $iX, $iY, $iW, $iH $bBtnDown = False GetClientRect($hWnd, $Rct) $iX = $Rct.left $iY = $Rct.top $iW = $Rct.right - $Rct.left $iH = $Rct.bottom - $Rct.top InvalidateRect($hWnd, 0, False) ;~ EXIT FUNCTION ;~ Return 0 Case $WM_PAINT Local $ps ;= DllStructCreate($_tagPaintStruct) Local $hPen, $hBrush, $hOldBrush Dim $Rct = DllStructCreate($_tagRect) Dim $Size = DllStructCreate($_tagSize) Dim $T = "", $i Dim $XCtr, $YCtr Dim $iX, $iY, $iW, $iH Dim $iR, $iG, $iB GetClientRect($hWnd, $Rct) $iX = $Rct.left $iY = $Rct.top $iW = $Rct.right - $Rct.left $iH = $Rct.bottom - $Rct.top $XCtr = ($Rct.left + $Rct.right) / 2 $YCtr = ($Rct.top + $Rct.bottom) / 2 ;~ GetWindowText(hWnd,T ,255) ' Grab a copy of control caption ;~ DllCall("user32.dll", "int", "GetWindowTextW", "hwnd", $hWnd, "LPTSTR ", $T, "int", 255) ; not work $T = "Test" ;********************************** ; Draw our control ;********************************** Local $hDC = BeginPaint($hWnd, $ps) ;~ GetTextExtentPoint32(hDC, T , LEN(T),@Size) ' Get caption size GetTextExtentPoint32($hDC, $T, StringLen($T), $Size) $iR = 30 $iG = 90 $iB = 90 Draw_Gradient($hDC, $iX, $iY, $iW, $iH, $iR, $iG, $iB) SetBkMode($hDC, $TRANSPARENT) If $bBtnDown Then ;~ SetTextColor(hDC,_RGB(255,0,0)) SetTextColor($hDC, Dec(0xFF0000)) TextOut($hDC, $XCtr-($Size.cx/2)+1, $YCtr-($Size.cy/2)+1, $T) Else ;~ SetTextColor(hDC,_RGB(0,0,255)) SetTextColor($hDC, Dec(0x0000FF)) TextOut($hDC, $XCtr-$Size.cx/2, $YCtr-$Size.cy/2, $T) EndIf EndPaint($hWnd, $ps) ;~ EXIT FUNCTION ;~ Return 0 Case $WM_LBUTTONUP If $hWnd = $hCaptured Then ReleaseCapture() $bBtnDown = False InvalidateRect($hWnd, 0, 0) Local $hParent = GetParent($hWnd) ;~ SendMessage(hParent,WM_COMMAND,MAKELONG(GetWindowLong(hWnd,GWL_ID), BN_CLICKED),Cast(LONG,hWnd)) DllCall("user32.dll", "LRESULT", "SendMessageW", _ "hwnd", $hParent, _ "uint", $WM_COMMAND, _ "WPARAM", _WinAPI_MakeLong(_WinAPI_GetWindowLong($hWnd, $GWL_ID), $BN_CLICKED), _ "LPARAM", $hWnd) EndIf ;~ EXIT FUNCTION Return 0 Case $WM_LBUTTONDOWN SetCapture($hWnd) $hCaptured = $hWnd $bBtnDown = True SetFocus($hWnd) InvalidateRect($hWnd, 0, False) ;~ EXIT FUNCTION Return 0 Case $WM_MOUSEMOVE If $bBtnDown Then If IsMouseOver($hWnd) Then $bBtnDown = True InvalidateRect($hWnd, 0, False) ELSE ReleaseCapture() $bBtnDown = False InvalidateRect($hWnd, 0, False) EndIf EndIf ;~ EXIT FUNCTION ;~ Return 0 Case $WM_MOVING ReleaseCapture() $bBtnDown = False InvalidateRect($hWnd, 0, False) ;~ EXIT FUNCTION ;~ Return 0 Case $WM_SIZE ReleaseCapture() $bBtnDown = False InvalidateRect($hWnd, 0, False) ;~ EXIT FUNCTION ;~ Return 0 EndSwitch ;~ Return _WinAPI_DefWindowProc($hWnd, $iMsg, $wParam, $lParam) Return DllCall("user32.dll", "lresult", "DefWindowProcW", "hwnd", $hWnd, "uint", $iMsg, "wparam", $wParam, _ "lparam", $lParam)[0] EndFunc ;~ SUB Draw_Gradient (hdc as HDC, x As Integer, y As integer, w As integer, h As Integer, r As integer, g As integer, b As integer) Func Draw_Gradient($hDC, $iX, $iY, $iW, $iH, $iR, $iG, $iB) ;~ DIM Vert(2) AS TRIVERTEX Local $Vert[2] $Vert[0] = DllStructCreate($_tagTrivertex) $Vert[1] = DllStructCreate($_tagTrivertex) ;~ DIM Rect AS GRADIENT_RECT Local $Rect = DllStructCreate($_tagGradient_Rect) ;~ Vert (0).x = 0 $Vert[0].x = 0 ;~ Vert (0).y = 0 $Vert[0].y = 0 ;~ Vert (0).Red = 65535-(65535-(r*256)) $Vert[0].Red = 65535-(65535-($iR*256)) ;~ Vert (0).Green = 65535-(65535-(g*256)) $Vert[0].Green = 65535-(65535-($iG*256)) ;~ Vert (0).Blue = 65535-(65535-(b*256)) $Vert[0].Blue = 65535-(65535-($iB*256)) ;~ Vert (0).Alpha = 0 $Vert[0].Alpha = 0 ;~ '****************************************************** ;~ Vert (1).x = w $Vert[1].x = $iW ;~ Vert (1).y = h/2 $Vert[1].y = $iH/2 ;~ Vert (1).Red = 65535-(65535-(255*256)) $Vert[1].Red = 65535-(65535-(255*256)) ;~ Vert (1).Green = 65535-(65535-(255*256)) $Vert[1].Green = 65535-(65535-(255*256)) ;~ Vert (1).Blue = 65535-(65535-(255*256)) $Vert[1].Blue = 65535-(65535-(255*256)) ;~ Vert (1).Alpha = 0 $Vert[1].Alpha = 0 ;~ '****************************************************** ;~ Rect.UpperLeft = 0 $Rect.UpperLeft = 0 ;~ Rect.LowerRight = 1 $Rect.LowerRight = 1 ;~ '****************************************************** ;~ Gradientfill(hdc,@Vert(0),2,@Rect,1,GRADIENT_FILL_RECT_V) GradientFill($hDC, $Vert[0], 2, $Rect, 1, $GRADIENT_FILL_RECT_V) ;~ '****************************************************** ;~ Vert (0).x = 0 $Vert[0].x = 0 ;~ Vert (0).y = h/2 $Vert[0].y = $iH/2 ;~ Vert (0).Red = 65535-(65535-(255*256)) $Vert[0].Red = 65535-(65535-(255*256)) ;~ Vert (0).Green = 65535-(65535-(255*256)) $Vert[0].Green = 65535-(65535-(255*256)) ;~ Vert (0).Blue = 65535-(65535-(255*256)) $Vert[0].Blue = 65535-(65535-(255*256)) ;~ Vert (0).Alpha = 0 $Vert[0].Alpha = 0 ;~ '****************************************************** ;~ Vert (1).x = w $Vert[1].x = $iW ;~ Vert (1).y = h $Vert[1].y = $iH ;~ Vert (1).Red = 65535-(65535-(r*256)) $Vert[1].Red = 65535-(65535-($iR*256)) ;~ Vert (1).Green = 65535-(65535-(g*256)) $Vert[1].Green = 65535-(65535-($iG*256)) ;~ Vert (1).Blue = 65535-(65535-(b*256)) $Vert[1].Blue = 65535-(65535-($iB*256)) ;~ Vert (1).Alpha = 0 $Vert[1].Alpha = 0 ;~ '****************************************************** ;~ Rect.UpperLeft = 0 $Rect.UpperLeft = 0 ;~ Rect.LowerRight = 1 $Rect.LowerRight = 1 ;~ '****************************************************** ;~ Gradientfill(hdc,@Vert(0),2,@Rect,1,GRADIENT_FILL_RECT_V) GradientFill($hDC, $Vert[0], 2, $Rect, 1, $GRADIENT_FILL_RECT_V) ;~ END SUB EndFunc Func IsMouseOver($hWnd) Local $Rect = DllStructCreate($_tagRect) Local $Pt = DllStructCreate($_tagPoint) GetWindowRect ($hWnd, $Rect) GetCursorPos($Pt) Return PtInRect($Rect, $Pt) EndFunc Func _RGB($iR, $iG, $iB) Return ('0x' & Hex($iR, 2) & Hex($iG, 2) & Hex($iB, 2)) EndFunc Func _BGR($iB, $iG, $iR) Return ('0x' & Hex($iB, 2) & Hex($iG, 2) & Hex($iR, 2)) EndFunc Func InvalidateRect($hWnd, $tRECT = 0, $bErase = True) DllCall("user32.dll", "bool", "InvalidateRect", "hwnd", $hWnd, "struct*", $tRECT, "bool", $bErase) EndFunc Func SetFocus($hWnd) DllCall("user32.dll", "hwnd", "SetFocus", "hwnd", $hWnd) EndFunc Func PtInRect($tRect, $tPoint) Local $aRet = DllCall("user32.dll", "bool", "PtInRect", "ptr", DllStructGetPtr($tRect), "struct*", $tPoint) If IsArray($aRet) Then Return $aRet[0] Return False EndFunc Func GetWindowRect($hWnd, ByRef $tRect) DllCall("user32.dll", "bool", "GetWindowRect", "hwnd", $hWnd, "struct*", $tRect) EndFunc Func GetCursorPos(ByRef $tPoint) DllCall("user32.dll", "bool", "GetCursorPos", "struct*", $tPoint) EndFunc Func SetCapture($hWnd) DllCall("user32.dll", "hwnd", "SetCapture", "hwnd", $hWnd) EndFunc Func ReleaseCapture() DllCall("user32.dll", "bool", "ReleaseCapture") EndFunc Func SetTextColor($hDC, $iColor) DllCall("gdi32.dll", "INT", "SetTextColor", "handle", $hDC, "INT", $iColor) EndFunc Func BeginPaint($hWnd, ByRef $tPAINTSTRUCT) $tPAINTSTRUCT = DllStructCreate($tagPAINTSTRUCT) Local $aRet = DllCall('user32.dll', 'handle', 'BeginPaint', 'hwnd', $hWnd, 'struct*', $tPAINTSTRUCT) If @error Then Return SetError(@error, @extended, 0) Return $aRet[0] EndFunc Func GetTextExtentPoint32($hDC, $sText, $iTextLen, ByRef $tSize) DllCall("gdi32.dll", "bool", "GetTextExtentPoint32W", "handle", $hDC, "wstr", $sText, "int", $iTextLen, "struct*", $tSize) EndFunc Func GradientFill($hDC, $tVertex, $nVertex, $tMesh, $nMesh, $ulMode) DllCall("Msimg32.dll", "BOOL", "GradientFill", _ "handle", $hDC, _ "struct*", $tVertex, _ "ulong", $nVertex, _ "struct*", $tMesh, _ "ulong", $nMesh, _ "ulong", $ulMode) EndFunc Func GetParent($hWnd) Local $aResult = DllCall("user32.dll", "hwnd", "GetParent", "hwnd", $hWnd) If @error Then Return SetError(@error, @extended, 0) Return $aResult[0] EndFunc Func SetBkMode($hDC, $iBkMode) Local $aResult = DllCall("gdi32.dll", "int", "SetBkMode", "handle", $hDC, "int", $iBkMode) If @error Then Return SetError(@error, @extended, 0) Return $aResult[0] EndFunc Func EndPaint($hWnd, ByRef $tPAINTSTRUCT) Local $aRet = DllCall('user32.dll', 'bool', 'EndPaint', 'hwnd', $hWnd, 'struct*', $tPAINTSTRUCT) If @error Then Return SetError(@error, @extended, False) Return $aRet[0] EndFunc Func GetClientRect($hWnd, ByRef $tRect) Local $aRet = DllCall("user32.dll", "bool", "GetClientRect", "hwnd", $hWnd, "struct*", $tRect) If @error Or Not $aRet[0] Then Return SetError(@error + 10, @extended, 0) Return $tRect EndFunc Func TextOut($hDC, $iX, $iY, $sText, $iTextLen = Default) If $iTextLen = Default Then $iTextLen = StringLen($sText) DllCall('gdi32.dll', 'bool', 'TextOutW', 'handle', $hDC, 'int', $iX, 'int', $iY, 'wstr', $sText, 'int', $iTextLen) EndFunc  
    • r0ash
      By r0ash
      Hey guys, MattDiesel over Stackoverflow mentioned this beautiful piece of code 
      #include <WindowsConstants.au3> #include <WinAPI.au3> Local $IDM_FONT = 33 Local $hWindow = WinGetHandle("Untitled - Notepad") _WinAPI_PostMessage($hWindow, $WM_COMMAND, $IDM_FONT, 0) Local $hFontWin = WinWait("Font") $select = ControlCommand($hFontWin, "", "ComboBox1", "GetCurrentSelection", "") WinClose($hFontWin) MsgBox(0,"", $select) I realized that _WinAPI_PostMessage can trigger menu click event, even if Notepad is minimized.
      How do we know what is the decimal value of *any menu item or sub-menu item*? How we know "Format > Font" menu-item is 33 as wParam to _WinAPI_PostMessage()? Have a look at snapshot.
      Regards.

×