Last active
August 29, 2015 14:02
-
-
Save yukitos/2f58bef03887d2cf4ac0 to your computer and use it in GitHub Desktop.
Use Event.filter and receive event's sender object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System.Windows.Forms | |
// Copied from: http://social.msdn.microsoft.com/Forums/ja-JP/d5f23c87-b8d5-4c95-9293-3239f70caf94/f-first-class-events-and-cli-standards?forum=fsharpgeneral | |
type FunctionWrapper<'args>(f:obj -> 'args -> unit) = | |
member x.Invoke(sender:obj, args) = | |
f sender args | |
module Event = | |
let filter (pred:'args->bool) (ev:IEvent<'del,'args>) = | |
let filtered = Event<'del,'args>() | |
let f (sender:obj) args = | |
if pred args then | |
filtered.Trigger(sender, args) | |
ev.AddHandler(System.Delegate.CreateDelegate(typeof<'del>,FunctionWrapper(f),typeof<FunctionWrapper<'args>>.GetMethod("Invoke")) :?> 'del) | |
filtered.Publish | |
// Test code | |
let f = new Form() | |
let button = new Button() | |
f.Controls.Add(button) | |
let filtered = button.Click | |
|> Event.filter(fun e -> true) | |
filtered.AddHandler(fun sender e -> | |
// if extended filter method is not defined, sender is null. | |
match sender with | |
| null -> MessageBox.Show("sender is null") |> ignore | |
| sender -> MessageBox.Show(sender.ToString()) |> ignore) | |
f.ShowDialog() |> ignore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment