Put focus back on previously focused control on a button click event C# winforms -
i have made custom number keypad control want place in winform application. of buttons have onclick
event send value focused textbox in form have placed custom control. this:
private void btnnum1_click(object sender, eventargs e) { if (focusedctrl != null && focusedctrl textbox) { focusedctrl.focus(); sendkeys.send("1"); } }
focusedctrl
supposed set on mousedown
event of button this:
private void btnnum1_mousedown(object sender, eventargs e) { focusedctrl = this.activecontrol; }
where this.activecontrol
represents active control on form.
my problem button receives focus before event detects focused control previously. how can detect control had focus before button got focus? there event should using? in advance!
edit: also, rather not use gotfocus
event on each textbox in form set focusedctrl
since can tedious , because have coding of custom control in control , not on form placed. (i this, though, if there no other practical way asking)
your requirement unwise, you'll want kind of guarantee button isn't going poke text inappropriate places. need have form co-operate, knows places appropriate.
but not impossible, can sniff @ input events before dispatched control focus. in other words, record control has focus before focusing event fired. that's possible in winforms imessagefilter interface.
add new class project , paste code shown below. compile. drop new control top of toolbox onto form, replacing existing buttons.
using system; using system.windows.forms; class calculatorbutton : button, imessagefilter { public string digit { get; set; } protected override void onclick(eventargs e) { var box = lastfocused textboxbase; if (box != null) { box.appendtext(this.digit); box.selectionstart = box.text.length; box.focus(); } base.onclick(e); } protected override void onhandlecreated(eventargs e) { if (!this.designmode) application.addmessagefilter(this); base.onhandlecreated(e); } protected override void onhandledestroyed(eventargs e) { application.removemessagefilter(this); base.onhandledestroyed(e); } bool imessagefilter.prefiltermessage(ref message m) { var focused = this.findform().activecontrol; if (focused != null && focused.gettype() != this.gettype()) lastfocused = focused; return false; } private control lastfocused; }
Comments
Post a Comment