×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

InputBox as password character(*)?
12

InputBox as password character(*)?

InputBox as password character(*)?

(OP)
Hello, expert

Is there any way to make the text entered in the InputBox as password character(*)?

thanks in advance

shan

RE: InputBox as password character(*)?

Don't think so, though you could design a popup form that looks much like an input box, use a text field, and set its PasswordChar property to *.

"Much that I bound, I could not free. Much that I freed returned to me."
(Lee Wilson Dodd)

RE: InputBox as password character(*)?

(OP)
Dear Sir,

i dont want to create a new form,

just input box.... enough for me???

shan

RE: InputBox as password character(*)?

6
Yes it is possible. Place the following into a module:

CODE

Option Explicit

Private Declare Function FindWindow Lib "user32" Alias
"FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName
As String) As Long

Private Declare Function FindWindowEx Lib "user32" Alias
"FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal
lpsz1 As String, ByVal lpsz2 As String) As Long

Public Declare Function SetTimer& Lib "user32" (ByVal hwnd&,
ByVal nIDEvent&, ByVal uElapse&, ByVal lpTimerFunc&)

Private Declare Function KillTimer& Lib "user32" (ByVal hwnd&,
ByVal nIDEvent&)

Private Declare Function SendMessage Lib "user32" Alias
"SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal
wParam As Long, lParam As Any) As Long

Const EM_SETPASSWORDCHAR = &HCC
Public Const NV_INPUTBOX As Long = &H5000&
Public WindowTitle As String

Public Sub TimerProc(ByVal hwnd As Long, ByVal uMsg As Long, ByVal idEvent
As Long, ByVal dwTime As Long)
    Dim EditHwnd As Long
    EditHwnd = FindWindowEx(FindWindow("#32770", WindowTitle),
0, "Edit", "")
    
    Call SendMessage(EditHwnd, EM_SETPASSWORDCHAR, Asc("*"), 0)
    KillTimer hwnd, idEvent
End Sub

Public Function PasswordInputbox(Prompt As String, Optional Title As
String, Optional Default As String, Optional XPos As Long, Optional YPos
As Long, Optional HelpFile As Long, Optional Context As Long) As String
        Dim ret As String
    If Title = "" Then
        WindowTitle = App.Title
    Else
        WindowTitle = Title
    End If

    SetTimer 0, 0, 1, AddressOf TimerProc
    PasswordInputbox = InputBox(Prompt, WindowTitle, Default, XPos, YPos,
HelpFile, Context)
End Function

and call it from a form like:

CODE

Private Sub Command1_Click()
Dim a
a = PasswordInputbox("Enter Text", "Title")
End Sub

----------------------------------------------------------------------

Need help finding an answer?

Try the search facilty (http://www.tek-tips.com/search.cfm) or read FAQ222-2244 on how to get better results.

RE: InputBox as password character(*)?

*blinks* That is WAY above my skill level. :)

"Much that I bound, I could not free. Much that I freed returned to me."
(Lee Wilson Dodd)

RE: InputBox as password character(*)?

Not a lot of skill required to Copy and Paste the above code into your own project.

It's a good way to learn the VB Language as well.

Greg Palmer

----------------------------------------
Any feed back is appreciated.

RE: InputBox as password character(*)?

(OP)
Public Const NV_INPUTBOX As Long = &H5000&

above line shows error, any need to add ??


shan

RE: InputBox as password character(*)?

That one should work fine. However, it needs to be in a module; trying to put this line in a form would throw the error "Constants, (...) not allowed as Public members of object modules". Is that the error you're getting?

"Much that I bound, I could not free. Much that I freed returned to me."
(Lee Wilson Dodd)

RE: InputBox as password character(*)?

(OP)
yes sir, same error

how to overcome this error ... give me in detail

please ... thanks in advance


shan

RE: InputBox as password character(*)?

You will have to put this line in a module that isn't also an object. So, not a form module (and I believe not a class module either).

If you don't have a regular module yet, create one, and you can put all constant declarations in there. As long as you declare them as Public like this one, they'll apply to your entire application.

"Much that I bound, I could not free. Much that I freed returned to me."
(Lee Wilson Dodd)

RE: InputBox as password character(*)?

Actually, the whole code ca8msm shared is best placed into a module, and as he suggested you would then call this code from whatever form you want to use it in with:


Private Sub Command1_Click()
Dim a
a = PasswordInputbox("Enter Text", "Title")
End Sub


Since PasswordInputbox is a Public sub, it doesn't matter what module you put it in, your form will know where to find it.

"Much that I bound, I could not free. Much that I freed returned to me."
(Lee Wilson Dodd)

RE: InputBox as password character(*)?

(OP)
i put the following lines in to modules

Public Const NV_INPUTBOX As Long = &H5000&
Public Declare Function SetTimer& Lib "user32" (ByVal hwnd&, ByVal nIDEvent&, ByVal uElapse&, ByVal lpTimerFunc&)

after that
it shows the error in the following lines

SetTimer 0, 0, 1, AddressOf TimerProc

sorry for the ?????

thanks in advance

shan

RE: InputBox as password character(*)?

Did you copy all of the code? Because it should work just fine if you did.

I've uploaded a working example at www.foxwing.co.uk/passwordbox.zip, have a look and compare.

"Much that I bound, I could not free. Much that I freed returned to me."
(Lee Wilson Dodd)

RE: InputBox as password character(*)?

(OP)
yes yes thanks


its working fine,....


thank you very much much sir

shan

RE: InputBox as password character(*)?

I really don't understand why you would want to use an InputBox for this, and not just use a text box on a modal form.

If you add a small form to your project with a text box, a lable and two command buttons on it, and name it frmpassword, you can do what you want in two minutes by pasting the below into the new form's code window:


Option Explicit
Private m_sRetValue As String
Public Function GetPassword(Optional Prompt As String, Optional Title As String, Optional XPos As Variant, Optional YPos As Variant) As String
    Me.Caption = Title
    Label1.Caption = Prompt
    Text1.PasswordChar = "*"
    
    If Not IsMissing(XPos) Then Me.Left = XPos
    If Not IsMissing(YPos) Then Me.Top = YPos
    
    Me.Show vbModal
    GetPassword = m_sRetValue
    Unload Me 'DO NOT REMOVE THIS 2nd UNLOAD
End Function
    
Private Sub Command1_Click()
    m_sRetValue = Text1.Text
    Unload Me
End Sub

Private Sub Command2_Click()
    m_sRetValue = vbNullString
    Unload Me
End Sub


You would call it like this:
ReturnValue = frmpassword.GetPassword("HI","XYZ")



If you need some help with the positioning of the controls, etc, then place this also in the code window (you only need to add a form, two command buttons, a label and a text box, leaving the default names as they are):

Private Sub Form_Load()
    With Me
        .Height = 2220
        .Width = 5670
        'instead of using Screen here, you could find and use the actual work area
        .Left = (Screen.Width - 5670) \ 2
        .Top = (Screen.Height - 2220) \ 2
    End With
    With Label1
        .Width = 4000
        .Height = 1260
        .Left = 120
        .Top = 130
    End With
    With Text1
        .Width = 5300
        .Height = 285
        .Left = 120
        .Top = 1440
        .TabIndex = 1
        .TabStop = True
        .Text = ""
    End With
    With Command1
        .Width = 1100
        .Height = 375
        .Left = 4300
        .Top = 130
        .Default = True
        .TabIndex = 2
        .TabStop = True
        .Caption = "OK"
    End With
    With Command2
        .Width = 1100
        .Height = 375
        .Left = 4300
        .Top = 600
        .TabIndex = 3
        .TabStop = True
        .Caption = "Cancel"
    End With
End Sub

RE: InputBox as password character(*)?


BTW, You should set the form properties: MaxButton and MinButton to false.

This input box can be easily changed as to how it looks, what arguments are passed to it, etc., etc.

If the argument list gets too long, then I suggest using Public Properties and set this prior to calling the GetText or GetPassword function.

RE: InputBox as password character(*)?

I just want to thanks ca8msm for a nice work above . . .this is really great

Please pardon the grammar.
Not good in english.

RE: InputBox as password character(*)?

ca8msm,
The code works fine - but what does the following line do?
SetTimer 0, 0, 1, AddressOf TimerProc

Removing it makes the characters display regularly instead of as * - but I'm not sure why a timer is required.

RE: InputBox as password character(*)?

2
The timer is required to set the password character after the input box is displayed.

You cannot change the password character using regular code because when the InputBox function is called, the execution of the code is suspended until the user dismiss the dialog box.

Thus a timer is setup before calling the InputBox function. The purpose of this timer is to change the password character of the InputBox edit field after the dialog is displayed. The code is:

SetTimer 0, 0, 1, AddressOf TimerProc

The timeout interval of the timer is set to 1 millisecond causing it to fire immediately after the input box is shown. The AddressOf TimerProc argument passes the address of the TimerProc callback function to the SetTimer function so that the timer executes this code after each timeout interval.

When the TimerProc function executes for the first time, it does the following.
1. Finds the handle of the InputBox dialog (FindWindow).
2. Finds the handle of the Edit field inside the InputBox (FindWindowEx).
3. Changes the password character (SendMessage).
4. Kills the timer to prevent further executions of the callback function (KillTimer).

If you comment or remove the SetTimer function call, all of the above actions are inhibited thus leaving the password textbox intact.

RE: InputBox as password character(*)?

Hypetia,
Cheers for a brilliant explanation (are you a teacher?), and a star.

I see now that this changes the attributes of a given inputbox, rather than the attributes of all inputboxes!  (I missed that on my first read through).

RE: InputBox as password character(*)?

3
My favoured varinat of this is to use a CBT hook. I've posted it on a number of occassions, and here it is again (the principal is similar to that of the timer, except it responds to the activation of the inputbox window rather than waiting for a timer event):

CODE

Option Explicit

' Necessary constants  for hooking
Private Const HCBT_ACTIVATE = 5
Public Const WH_CBT = 5

' Constants for password masking
Public Const EM_SETPASSWORDCHAR = &HCC

' Working variables that require global scope in hooking module
Private hHook As Long

' The API declarations we need
Private Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As Long, ByVal hmod As Long, ByVal dwThreadId As Long) As Long
Private Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long

' Wrapper for the normal InputBox function
Public Function vbInputBox(Prompt As String, Optional Title As String, Optional Default As String, Optional Xpos As Single, Optional YPos As Single, Optional Helpfile As String, Optional Context As Long) As String 'Optional Buttons As VbMsgBoxStyle = vbOKOnly, Optional Title As String, Optional HelpFile As String, Optional Context As Long) As Long
    hHook = SetWindowsHookEx(WH_CBT, AddressOf CBTProc, App.hInstance, 0)
    vbInputBox = InputBox(Prompt, Title, Default, Xpos, YPos, Helpfile, Context)
End Function

Private Function CBTProc(ByVal lMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    Dim hwndEditControl As Long
    
    If lMsg = HCBT_ACTIVATE Then
        hwndEditControl = FindWindowEx(wParam, 0, "Edit", "") ' get the edit control
        If hwndEditControl Then SendMessage hwndEditControl, EM_SETPASSWORDCHAR, Asc("*"), 0 ' Do your stuff here to modify the window
        UnhookWindowsHookEx hHook ' Immediately unhook
    End If
    CBTProc = 0 ' allow operation to continue
End Function

RE: InputBox as password character(*)?

krinid
No I am not. Thanks for the star.

strongm
This variant is realy nice and more appropriate alternative. I believe that this hook mechanism is really better than the timer mechanism.
Have a star!

RE: InputBox as password character(*)?

strongm,
(Crossing the forum topics here, but would like to use this in VBA as well as VB) Could that be ported to VBA?  I changed App.hInstance to Application.hInstance but it doesn't seem to be able to find the window (FindWindowEx always returns 0).

RE: InputBox as password character(*)?

There is no object in VBA that can return the instance handle of the current application (not even the Application object). The App object which we use in VB belongs to the VB library but not VBA.

If you want to port this code to VBA, you need to obtain the current instance handle to pass it to SetWindowsHookEx function.

Add the following declarations in the declarations section of the module (below the FindWindowEx declaration).
___

Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function GetActiveWindow Lib "user32" () As Long
Const GWL_HINSTANCE = (-6)

___

Now modify the SetWindowHookEx function call from this:
___

hHook = SetWindowsHookEx(WH_CBT, AddressOf CBTProc, App.hInstance, 0)

___

to this:
___

hHook = SetWindowsHookEx(WH_CBT, AddressOf CBTProc, GetWindowLong(GetActiveWindow, GWL_HINSTANCE), 0)

___

The GetWindowLong function obtains the instance handle of the active window handle passed to it and passes it to SetWindowsHookEx function.

I tested it in Word VBA and it worked fine.

Note that all of the code must go in a standard module, not in a class module.

RE: InputBox as password character(*)?

Can't seem to get in working.  I added the 3 lines (2 Private Declare's, 1 Const) below the FindWindowEx declaration and replaced the hHook line, but hwndEditControl still ends up being 0 every time.  I'm calling the function using Debug.Print vbInputBox("Prompt", "Title", "Default").

RE: InputBox as password character(*)?

I'm betting you are testing the function by invoking from VBA's Immediate window. This will appear to fail because opening a dialog box (which is what the inputbox is) switches focus away from the IDE back to the owning application (e.g Word or Excel). This switch in focus causes the application's window to activate before the inputbox window activates - and the simple hook we have in place merely responds to the very first window that activates after the hook has been put into place.

In other words, in Word or Excel, if you try testing the function from the IDE then the actual window the hook function intercepts is that of the current active document. This isn't an issue for VB, so we don't have to program defensively for this scenario.

To get it to work correctly you need to either invoke from the application (eg a button on an Excel form or Word document) - or make some minor modifications to the code (the defensive programming mentioned above):

CODE

Option Explicit

' Necessary constants  for hooking
Private Const HCBT_ACTIVATE = 5
Public Const WH_CBT = 5

' Constants for password masking
Public Const EM_SETPASSWORDCHAR = &HCC

' Working variables that require global scope in hooking module
Private hHook As Long

' The API declarations we need
Private Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As Long, ByVal hmod As Long, ByVal dwThreadId As Long) As Long
Private Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Private Declare Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" (ByVal lpModuleName As String) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long



' Wrapper for the normal InputBox function
Public Function vbInputBox(Prompt As String, Optional Title As String, Optional Default As String, Optional Xpos As Single, Optional YPos As Single, Optional Helpfile As String, Optional Context As Long) As String 'Optional Buttons As VbMsgBoxStyle = vbOKOnly, Optional Title As String, Optional HelpFile As String, Optional Context As Long) As Long
    hHook = SetWindowsHookEx(WH_CBT, AddressOf CBTProc, [b]GetModuleHandle(vbNullString)[b], 0)
    vbInputBox = InputBox(Prompt, Title, Default, Xpos, YPos, Helpfile, Context)
End Function

Private Function CBTProc(ByVal lMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    Dim hwndEditControl As Long
    Dim strClassname As String
    Dim result As Long
    
    strClassname = Space(1024)
    result = GetClassName(wParam, strClassname, Len(strClassname))


    If lMsg = HCBT_ACTIVATE And Left(strClassname, result) = "#32770" Then
        hwndEditControl = FindWindowEx(wParam, 0, "Edit" , "") ' get the edit control
        If hwndEditControl Then SendMessage hwndEditControl, EM_SETPASSWORDCHAR, Asc("*"), 0 ' Do your stuff here to modify the window
        UnhookWindowsHookEx hHook ' Immediately unhook
    End If
    CBTProc = 0 ' allow operation to continue
End Function

RE: InputBox as password character(*)?

strongm,
Thanks once again, it's working fine now.  You are an incredibly helpful person to have around on these forums.

RE: InputBox as password character(*)?

I realize this thread is rather old.  But is there any way you can do the same thing listed here in a VBScript?  VB is very new to me i have a script written but the only options i have to 'protect' the password is to either have the user copy the password to clipboard and have the script paste into password box, or have the user type in cleartext into a inputbox.

Any help would be appreciated.

RE: InputBox as password character(*)?

Oh also.  Im using windows 2000.  I have found some documents on how to create the box within html but i cant figure out how to traverse the password from the ie section back to the vbs section...  Heres the script i had tried for that:

CODE

DIM PWD
Function PasswordBox()
  set oIE = CreateObject("InternetExplorer.Application")
  With oIE
    .RegisterAsDropTarget = False
    .Resizable = False : .FullScreen = True
    .width = 400 : .height = 100
    .Navigate "about:blank"
    Do Until .ReadyState = 4 : WScript.Sleep 100 : Loop
    .document.open
    .document.write _
             "<html><head><" & "script>bboxwait=true;</" _
           & "script><title>Password _</title></head>"_
           & "<body bgColor=White scroll=no" _
           & " style='border-Style:outset;border-" _
           & "Width:3px'>" _
           & "<center><b>Please enter the password: </b>" _
           & "<input type=password id=pass><p>" _
           & "<button onclick='bboxwait=false;'>" _
           & " Submit </button>" _
           & "</center></body></html>"
    .document.close
    Do Until .ReadyState = 4 : WScript.Sleep 100 : Loop
    .Visible = True
    CreateObject("Wscript.Shell").Appactivate "Password _"
    With .document
      oIE.left = .parentWindow.screen.width \ 2 - 200
      oIE.top = .parentWindow.screen.height\ 2 - 100
      .all.pass.focus
      PasswordBox = "CANCELLED"
      On Error Resume Next
      Do While .parentWindow.bBoxWait
        if Err Then Exit Function
        WScript.Sleep 500
      Loop
      oIE.Visible = False
       PasswordBox = .all.pass.value

    End With ' document
  End With ' IE
End Function

If PasswordBox = "" Then
        msgbox "You did not enter a password."
Else
        msgbox "Press enter to continue.  "  & Trim(PWD) & " is your password"
End If

PWD = Request.Form("passwordbox")

I must admit i really dont understand it though...  I would like to use the passwordbox results as something i can use for a sendkeys command...

Thanks again.

RE: InputBox as password character(*)?

Unfortunately VBScript cannot make API calls. So what you'd have to do is use something like VB to create a class that VBScript can then instantiate.

RE: InputBox as password character(*)?

It took me about 2 hours to learn how to write my script in VBS...  I downloaded vb5cce but i have no clue how to use it.  I tried pasting the code you all had put in the beginning of this post, but it kept giving me errors saying constants could not be.. lemme get the exact error...

"Compile error:
Constants, fixed-length strings, arrays, and Declare statements not allowed as Public members of object modules."

Perhaps I am doing something wrong?  I go to view/code and paste it in, then 'run'.

RE: InputBox as password character(*)?

I actually found someone here at work who is proficient with VBS and he gave me the following code, theres only one problem and its when i click the submit button, the window does not respond or close...

CODE

'************************************************************************************
'Sub to get account name and password.  Calls "PasswordBox" function:
'************************************************************************************
Get_Account
Dim Pwd
Sub Get_Account()

   Pwd = PasswordBox("Enter your password")

End Sub


'************************************************************************************
'This function is for creating a Password input box which masks the input with "******"
'A WSH/VB InputBox is not recommended for password input because what the user
'types in is visible on the console. This function uses IE for the window.
'************************************************************************************

Function PasswordBox(sTitle)
  Set oIE = CreateObject("InternetExplorer.Application")
  'Modified (added), used by AppActivate
  sIETitle = "Password Input"

  With oIE
    .FullScreen = True
    .ToolBar   = False : .RegisterAsDropTarget = False
    .StatusBar = False : .Navigate("about:blank")

    'Modified
    'While .Busy : WScript.Sleep 100 : Wend
    Do Until .ReadyState = 4 : WScript.Sleep 100 : Loop

    With .document
      With .ParentWindow
        .resizeto 400,100
        .moveto .screen.width/2-200, .screen.height/2-50
      End With
      'Modified (added)
      .WriteLn "<HTML><TITLE>" & sIETitle & "</TITLE>"
      .WriteLn("<html><body bgColor=Silver><center>")
      .WriteLn("&nbsp;<b>" & sTitle & "<b>&nbsp;<p>")
      .WriteLn("Password <input type=password id=pass> &nbsp; " & _
               "<button id=but0>Submit</button>")
      .WriteLn("</center></body></html>")
      With .ParentWindow.document.body
        .scroll="no"
        .style.borderStyle = "outset"
        .style.borderWidth = "3px"
      End With
      .all.but0.onclick = GetRef("PasswordBox_Submit")
      .all.pass.focus
      oIE.Visible = True

      'Modified (added)
      Set oShell = CreateObject("WScript.Shell")
      oShell.AppActivate sIETitle

      bPasswordBoxOkay = False : bPasswordBoxWait = True
      On Error Resume Next
      While bPasswordBoxWait
        WScript.Sleep 100
        If oIE.Visible Then bPasswordBoxWait = bPasswordBoxWait
        If Err Then bPasswordBoxWait = False
      Wend
      'Modified (added)
      PasswordBox = .all.pass.value
    End With ' document
    .Visible = False
    'Modified (added)
    .Quit
  End With   ' IE
End Function

Sub PasswordBox_Submit()
  bPasswordBoxWait = False

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close