Application API
此内容尚不支持你的语言。
Overview
Section titled “Overview”The Application is the core of your Wails app. It manages windows, services, events, and provides access to all platform features.
Creating an Application
Section titled “Creating an Application”import "github.com/wailsapp/wails/v3/pkg/application"
app := application.New(application.Options{ Name: "My App", Description: "My awesome application", Services: []application.Service{ application.NewService(&MyService{}), },})Core Methods
Section titled “Core Methods”Starts the application event loop.
func (a *App) Run() errorExample:
err := app.Run()if err != nil { log.Fatal(err)}Returns: Error if startup fails
Quit()
Section titled “Quit()”Gracefully shuts down the application.
func (a *App) Quit()Example:
// In a menu handlermenu.Add("Quit").OnClick(func(ctx *application.Context) { app.Quit()})Config()
Section titled “Config()”Returns the application configuration.
func (a *App) Config() OptionsExample:
config := app.Config()fmt.Println("App name:", config.Name)Window Management
Section titled “Window Management”app.Window.New()
Section titled “app.Window.New()”Creates a new webview window with default options.
func (wm *WindowManager) New() *WebviewWindowExample:
window := app.Window.New()window.Show()app.Window.NewWithOptions()
Section titled “app.Window.NewWithOptions()”Creates a new webview window with custom options.
func (wm *WindowManager) NewWithOptions(options WebviewWindowOptions) *WebviewWindowExample:
window := app.Window.NewWithOptions(application.WebviewWindowOptions{ Title: "My Window", Width: 800, Height: 600, BackgroundColour: application.NewRGB(255, 255, 255),})app.Window.GetByName()
Section titled “app.Window.GetByName()”Gets a window by its name. Returns the window and whether it was found.
func (wm *WindowManager) GetByName(name string) (Window, bool)Example:
if window, ok := app.Window.GetByName("main"); ok { window.Show()}app.Window.GetAll()
Section titled “app.Window.GetAll()”Returns all application windows.
func (wm *WindowManager) GetAll() []WindowExample:
windows := app.Window.GetAll()for _, window := range windows { fmt.Println("Window:", window.Name())}Managers
Section titled “Managers”The Application provides access to various managers through properties:
app.Window // Window managementapp.Menu // Menu managementapp.Dialog // Dialog managementapp.Event // Event managementapp.Clipboard // Clipboard operationsapp.Screen // Screen informationapp.SystemTray // System trayapp.Browser // Browser operationsapp.Env // Environment variablesapp.ContextMenu // Context-menu managementapp.KeyBinding // Global keyboard shortcutsapp.Logger // *slog.LoggerExample Usage
Section titled “Example Usage”// Create windowwindow := app.Window.New()
// Show dialogapp.Dialog.Info().SetMessage("Hello!").Show()
// Copy to clipboardapp.Clipboard.SetText("Copied text")
// Get screensscreens := app.Screen.GetAll()Service Management
Section titled “Service Management”RegisterService()
Section titled “RegisterService()”Registers a service with the application.
func (a *App) RegisterService(service Service)RegisterService returns nothing; service initialisation errors surface via ServiceStartup failures during app.Run().
Example:
type MyService struct { app *application.App}
func NewMyService(app *application.App) *MyService { return &MyService{app: app}}
// Register after app creationapp.RegisterService(application.NewService(NewMyService(app)))Event Management
Section titled “Event Management”app.Event.Emit()
Section titled “app.Event.Emit()”Emits a custom event. Returns true if a hook cancelled the emit.
func (em *EventManager) Emit(name string, data ...any) boolExample:
// Emit event with dataapp.Event.Emit("user-logged-in", map[string]interface{}{ "username": "john", "timestamp": time.Now(),})app.Event.On()
Section titled “app.Event.On()”Listens for custom events. Returns an unsubscribe func().
func (em *EventManager) On(name string, callback func(*CustomEvent)) func()Example:
app.Event.On("user-logged-in", func(e *application.CustomEvent) { data := e.Data.(map[string]interface{}) username := data["username"].(string) fmt.Println("User logged in:", username)})app.Event.OnApplicationEvent()
Section titled “app.Event.OnApplicationEvent()”Listens for application lifecycle events. The eventType parameter is events.ApplicationEventType (from the events package).
func (em *EventManager) OnApplicationEvent( eventType events.ApplicationEventType, callback func(*ApplicationEvent),) func()Example:
import "github.com/wailsapp/wails/v3/pkg/events"
// Listen for app-startedapp.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(e *application.ApplicationEvent) { fmt.Println("Application started")})
// Application shutdown is NOT an event constant; register cleanup via:app.OnShutdown(func() { fmt.Println("Application shutting down")})Dialog Methods
Section titled “Dialog Methods”Dialogs are accessed through the app.Dialog manager. See Dialogs API for complete reference.
Message Dialogs
Section titled “Message Dialogs”// Information dialogapp.Dialog.Info(). SetTitle("Success"). SetMessage("Operation completed!"). Show()
// Error dialogapp.Dialog.Error(). SetTitle("Error"). SetMessage("Something went wrong."). Show()
// Warning dialogapp.Dialog.Warning(). SetTitle("Warning"). SetMessage("This action cannot be undone."). Show()Question Dialogs
Section titled “Question Dialogs”Question dialogs use button callbacks to handle user responses:
dialog := app.Dialog.Question(). SetTitle("Confirm"). SetMessage("Continue?")
yes := dialog.AddButton("Yes")yes.OnClick(func() { // Handle yes})
no := dialog.AddButton("No")no.OnClick(func() { // Handle no})
dialog.SetDefaultButton(yes)dialog.SetCancelButton(no)dialog.Show()File Dialogs
Section titled “File Dialogs”// Open file dialogpath, err := app.Dialog.OpenFile(). SetTitle("Select File"). AddFilter("Images", "*.png;*.jpg"). PromptForSingleSelection()
// Save file dialogpath, err := app.Dialog.SaveFile(). SetTitle("Save File"). SetFilename("document.pdf"). AddFilter("PDF", "*.pdf"). PromptForSingleSelection()
// Folder selection (use OpenFile with directory options)path, err := app.Dialog.OpenFile(). SetTitle("Select Folder"). CanChooseDirectories(true). CanChooseFiles(false). PromptForSingleSelection()Logger
Section titled “Logger”The application provides a structured logger:
app.Logger.Info("Message", "key", "value")app.Logger.Error("Error occurred", "error", err)app.Logger.Debug("Debug info")app.Logger.Warn("Warning message")Example:
func (s *MyService) ProcessData(data string) error { s.app.Logger.Info("Processing data", "length", len(data))
if err := process(data); err != nil { s.app.Logger.Error("Processing failed", "error", err) return err }
s.app.Logger.Info("Processing complete") return nil}Raw Message Handling
Section titled “Raw Message Handling”For applications that need direct, low-level control over frontend-to-backend communication, Wails provides the RawMessageHandler option. This bypasses the standard binding system.
RawMessageHandler
Section titled “RawMessageHandler”RawMessageHandler is a field on application.Options, not a method. The runtime invokes it for every raw message sent from the frontend via System.invoke().
type Options struct { // ... other fields ... RawMessageHandler func(window Window, message string, originInfo *OriginInfo)}OriginInfo carries Origin, TopOrigin, and IsMainFrame (platforms populate different subsets — see the Raw Messages Guide for the per-platform matrix).
Example:
app := application.New(application.Options{ Name: "My App", RawMessageHandler: func(window application.Window, message string, originInfo *application.OriginInfo) { // Handle the raw message fmt.Printf("Received from %s (%s): %s\n", window.Name(), originInfo.Origin, message)
// You can respond using events window.EmitEvent("response", processMessage(message)) },})For more details, see the Raw Messages Guide.
Platform-Specific Options
Section titled “Platform-Specific Options”Windows Options
Section titled “Windows Options”Configure Windows-specific behavior at the application level:
app := application.New(application.Options{ Name: "My App", Windows: application.WindowsOptions{ // WebView2 browser flags (apply to ALL windows) EnabledFeatures: []string{"msWebView2EnableDraggableRegions"}, DisabledFeatures: []string{"msExperimentalFeature"}, AdditionalBrowserArgs: []string{"--remote-debugging-port=9222"},
// Other Windows options WndClass: "MyAppClass", WebviewUserDataPath: "", // Default: %APPDATA%\[BinaryName.exe] WebviewBrowserPath: "", // Default: system WebView2 DisableQuitOnLastWindowClosed: false, },})Browser Flags:
EnabledFeatures- WebView2 feature flags to enableDisabledFeatures- WebView2 feature flags to disableAdditionalBrowserArgs- Chromium command-line arguments
See Window Options - Application-Level Windows Options for detailed documentation.
Mac Options
Section titled “Mac Options”app := application.New(application.Options{ Name: "My App", Mac: application.MacOptions{ ActivationPolicy: application.ActivationPolicyRegular, ApplicationShouldTerminateAfterLastWindowClosed: true, },})Linux Options
Section titled “Linux Options”app := application.New(application.Options{ Name: "My App", Linux: application.LinuxOptions{ ProgramName: "my-app", DisableQuitOnLastWindowClosed: false, },})Complete Application Example
Section titled “Complete Application Example”package main
import ( "github.com/wailsapp/wails/v3/pkg/application")
func main() { app := application.New(application.Options{ Name: "My Application", Description: "A demo application", Mac: application.MacOptions{ ApplicationShouldTerminateAfterLastWindowClosed: true, }, })
// Create main window window := app.Window.NewWithOptions(application.WebviewWindowOptions{ Title: "My App", Width: 1024, Height: 768, MinWidth: 800, MinHeight: 600, BackgroundColour: application.NewRGB(255, 255, 255), URL: "http://wails.localhost/", })
window.Center() window.Show()
app.Run()}