다음을 통해 공유


이벤트

이벤트를 사용하면 함수 호출을 사용자 작업과 연결할 수 있으며 GUI 프로그래밍에서 중요합니다. 애플리케이션 또는 운영 체제에서 이벤트를 트리거할 수도 있습니다.

이벤트 처리

Windows Forms 또는 WPF(Windows Presentation Foundation)와 같은 GUI 라이브러리를 사용하는 경우 애플리케이션의 코드 대부분은 라이브러리에서 미리 정의된 이벤트에 대한 응답으로 실행됩니다. 이러한 미리 정의된 이벤트는 양식 및 컨트롤과 같은 GUI 클래스의 멤버입니다. 다음 코드와 같이 관심 있는 특정 명명된 이벤트(예 Click : 클래스의 Form 이벤트)를 참조하고 메서드를 호출하여 Add 단추 클릭과 같은 기존 이벤트에 사용자 지정 동작을 추가할 수 있습니다. F# Interactive에서 이 명령을 실행하는 경우 호출을 생략합니다 System.Windows.Forms.Application.Run(System.Windows.Forms.Form).

open System.Windows.Forms

let form = new Form(Text="F# Windows Form",
                    Visible = true,
                    TopMost = true)

form.Click.Add(fun evArgs -> System.Console.Beep())
Application.Run(form)

메서드의 Add 형식은 .입니다 ('a -> unit) -> unit. 따라서 이벤트 처리기 메서드는 일반적으로 이벤트 인수인 하나의 매개 변수를 사용하고 반환합니다 unit. 이전 예제에서는 이벤트 처리기를 람다 식으로 보여줍니다. 이벤트 처리기는 다음 코드 예제와 같이 함수 값일 수도 있습니다. 다음 코드 예제에서는 이벤트 유형과 관련된 정보를 제공하는 이벤트 처리기 매개 변수의 사용도 보여줍니다. MouseMove 이벤트의 경우 시스템은 포인터의 위치와 Y 위치를 포함하는 개체를 X 전달 System.Windows.Forms.MouseEventArgs 합니다.

open System.Windows.Forms

let Beep evArgs =
    System.Console.Beep( )


let form = new Form(Text = "F# Windows Form",
                    Visible = true,
                    TopMost = true)

let MouseMoveEventHandler (evArgs : System.Windows.Forms.MouseEventArgs) =
    form.Text <- System.String.Format("{0},{1}", evArgs.X, evArgs.Y)

form.Click.Add(Beep)
form.MouseMove.Add(MouseMoveEventHandler)
Application.Run(form)

사용자 지정 이벤트 만들기

F# 이벤트는 IEvent 인터페이스를 구현하는 F# 이벤트 형식으로 표시됩니다. IEvent는 다른 두 인터페이스와 IDelegateEvent의 기능을 결합하는 System.IObservable<'T> 인터페이스입니다. 따라서 Event다른 언어의 대리자의 동일한 기능과 추가 기능이 IObservable있습니다. 즉, F# 이벤트는 이벤트 필터링을 지원하고 F# 일류 함수와 람다 식을 이벤트 처리기로 사용합니다. 이 기능은 이벤트 모듈에서 제공됩니다.

다른 .NET Framework 이벤트와 마찬가지로 작동하는 클래스에서 이벤트를 만들려면 클래스의 필드로 정의하는 바인딩을 Event 클래스 let 에 추가합니다. 원하는 이벤트 인수 형식을 형식 인수로 지정하거나 비워 두고 컴파일러에서 적절한 형식을 유추할 수 있습니다. 또한 이벤트를 CLI 이벤트로 노출하는 이벤트 멤버를 정의해야 합니다. 이 멤버에는 CLIEvent 특성이 있어야 합니다. 속성처럼 선언되고 해당 구현은 이벤트의 Publish 속성에 대한 호출일 뿐입니다. 클래스의 사용자는 게시된 이벤트의 메서드를 사용하여 Add 처리기를 추가할 수 있습니다. 메서드의 Add 인수는 람다 식일 수 있습니다. 이벤트의 속성을 사용하여 Trigger 이벤트를 발생시킴에 인수를 처리기 함수에 전달할 수 있습니다. 다음 코드 예제에서는 이를 보여 줍니다. 이 예제에서 이벤트에 대한 유추된 형식 인수는 람다 식의 인수를 나타내는 튜플입니다.

open System.Collections.Generic

type MyClassWithCLIEvent() =

    let event1 = new Event<string>()

    [<CLIEvent>]
    member this.Event1 = event1.Publish

    member this.TestEvent(arg) =
        event1.Trigger(arg)

let classWithEvent = new MyClassWithCLIEvent()
classWithEvent.Event1.Add(fun arg ->
        printfn "Event1 occurred! Object data: %s" arg)

classWithEvent.TestEvent("Hello World!")

System.Console.ReadLine() |> ignore

출력은 다음과 같습니다.

Event1 occurred! Object data: Hello World!

모듈에서 Event 제공하는 추가 기능은 여기에 설명되어 있습니다. 다음 코드 예제에서는 이벤트 및 트리거 메서드를 만들고, 람다 식 형식으로 두 개의 이벤트 처리기를 추가한 다음, 이벤트를 트리거하여 두 람다 식을 실행하는 기본 사용을 Event.create 보여 줍니다.

type MyType() =
    let myEvent = new Event<_>()

    member this.AddHandlers() =
       Event.add (fun string1 -> printfn "%s" string1) myEvent.Publish
       Event.add (fun string1 -> printfn "Given a value: %s" string1) myEvent.Publish

    member this.Trigger(message) =
       myEvent.Trigger(message)

let myMyType = MyType()
myMyType.AddHandlers()
myMyType.Trigger("Event occurred.")

이전 코드의 출력은 다음과 같습니다.

Event occurred.
Given a value: Event occurred.

이벤트 스트림 처리

Event.add 함수를 사용하여 이벤트에 대한 이벤트 처리기를 추가하는 대신 모듈의 함수를 Event 사용하여 고도로 사용자 지정된 방식으로 이벤트 스트림을 처리할 수 있습니다. 이렇게 하려면 일련의 함수 호출에서 첫 번째 값으로 이벤트와 함께 전달 파이프(|>)를 사용하고 모듈은 Event 후속 함수 호출로 작동합니다.

다음 코드 예제에서는 처리기가 특정 조건에서만 호출 되는 이벤트를 설정 하는 방법을 보여 집니다.

let form = new Form(Text = "F# Windows Form",
                    Visible = true,
                    TopMost = true)
form.MouseMove
    |> Event.filter ( fun evArgs -> evArgs.X > 100 && evArgs.Y > 100)
    |> Event.add ( fun evArgs ->
        form.BackColor <- System.Drawing.Color.FromArgb(
            evArgs.X, evArgs.Y, evArgs.X ^^^ evArgs.Y) )

Observable 모듈에는 관찰 가능한 개체에서 작동하는 유사한 함수가 포함되어 있습니다. 관찰 가능한 개체는 이벤트와 유사하지만 자체 구독 중인 경우에만 이벤트를 적극적으로 구독합니다.

인터페이스 이벤트 구현

UI 구성 요소를 개발할 때 기존 폼이나 컨트롤에서 상속되는 새 폼 또는 새 컨트롤을 만드는 것부터 시작하는 경우가 많습니다. 이벤트는 인터페이스에서 자주 정의되며, 이 경우 이벤트를 구현하기 위해 인터페이스를 구현해야 합니다. 인터페이스는 System.ComponentModel.INotifyPropertyChanged 단일 System.ComponentModel.INotifyPropertyChanged.PropertyChanged 이벤트를 정의합니다. 다음 코드에서는 이 상속된 인터페이스가 정의한 이벤트를 구현하는 방법을 보여 줍니다.

module CustomForm

open System.Windows.Forms
open System.ComponentModel

type AppForm() as this =
    inherit Form()

    // Define the propertyChanged event.
    let propertyChanged = Event<PropertyChangedEventHandler, PropertyChangedEventArgs>()
    let mutable underlyingValue = "text0"

    // Set up a click event to change the properties.
    do
        this.Click |> Event.add(fun evArgs ->
            this.Property1 <- "text2"
            this.Property2 <- "text3")

    // This property does not have the property-changed event set.
    member val Property1 : string = "text" with get, set

    // This property has the property-changed event set.
    member this.Property2
        with get() = underlyingValue
        and set(newValue) =
            underlyingValue <- newValue
            propertyChanged.Trigger(this, new PropertyChangedEventArgs("Property2"))

    // Expose the PropertyChanged event as a first class .NET event.
    [<CLIEvent>]
    member this.PropertyChanged = propertyChanged.Publish

    // Define the add and remove methods to implement this interface.
    interface INotifyPropertyChanged with
        member this.add_PropertyChanged(handler) = propertyChanged.Publish.AddHandler(handler)
        member this.remove_PropertyChanged(handler) = propertyChanged.Publish.RemoveHandler(handler)

    // This is the event-handler method.
    member this.OnPropertyChanged(args : PropertyChangedEventArgs) =
        let newProperty = this.GetType().GetProperty(args.PropertyName)
        let newValue = newProperty.GetValue(this :> obj) :?> string
        printfn "Property {args.PropertyName} changed its value to {newValue}"

// Create a form, hook up the event handler, and start the application.
let appForm = new AppForm()
let inpc = appForm :> INotifyPropertyChanged
inpc.PropertyChanged.Add(appForm.OnPropertyChanged)
Application.Run(appForm)

생성자에서 이벤트를 연결하려는 경우 다음 예제와 같이 이벤트 연결이 추가 생성자의 블록에 then 있어야 하므로 코드가 좀 더 복잡합니다.

module CustomForm

open System.Windows.Forms
open System.ComponentModel

// Create a private constructor with a dummy argument so that the public
// constructor can have no arguments.
type AppForm private (dummy) as this =
    inherit Form()

    // Define the propertyChanged event.
    let propertyChanged = Event<PropertyChangedEventHandler, PropertyChangedEventArgs>()
    let mutable underlyingValue = "text0"

    // Set up a click event to change the properties.
    do
        this.Click |> Event.add(fun evArgs ->
            this.Property1 <- "text2"
            this.Property2 <- "text3")

    // This property does not have the property changed event set.
    member val Property1 : string = "text" with get, set

    // This property has the property changed event set.
    member this.Property2
        with get() = underlyingValue
        and set(newValue) =
            underlyingValue <- newValue
            propertyChanged.Trigger(this, new PropertyChangedEventArgs("Property2"))

    [<CLIEvent>]
    member this.PropertyChanged = propertyChanged.Publish

    // Define the add and remove methods to implement this interface.
    interface INotifyPropertyChanged with
        member this.add_PropertyChanged(handler) = this.PropertyChanged.AddHandler(handler)
        member this.remove_PropertyChanged(handler) = this.PropertyChanged.RemoveHandler(handler)

    // This is the event handler method.
    member this.OnPropertyChanged(args : PropertyChangedEventArgs) =
        let newProperty = this.GetType().GetProperty(args.PropertyName)
        let newValue = newProperty.GetValue(this :> obj) :?> string
        printfn "Property {args.PropertyName} changed its value to {newValue}"

    new() as this =
        new AppForm(0)
        then
            let inpc = this :> INotifyPropertyChanged
            inpc.PropertyChanged.Add(this.OnPropertyChanged)

// Create a form, hook up the event handler, and start the application.
let appForm = new AppForm()
Application.Run(appForm)

참고하십시오