Skip to content

Instantly share code, notes, and snippets.

@yukitos
Last active August 29, 2015 14:02
Show Gist options
  • Save yukitos/2f58bef03887d2cf4ac0 to your computer and use it in GitHub Desktop.
Save yukitos/2f58bef03887d2cf4ac0 to your computer and use it in GitHub Desktop.
Use Event.filter and receive event's sender object
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