dropfilesevent.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2011 The Walk Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build windows
  5. package walk
  6. import (
  7. "github.com/lxn/win"
  8. "syscall"
  9. )
  10. type DropFilesEventHandler func([]string)
  11. type DropFilesEvent struct {
  12. hWnd win.HWND
  13. handlers []DropFilesEventHandler
  14. }
  15. func (e *DropFilesEvent) Attach(handler DropFilesEventHandler) int {
  16. if len(e.handlers) == 0 {
  17. win.DragAcceptFiles(e.hWnd, true)
  18. }
  19. for i, h := range e.handlers {
  20. if h == nil {
  21. e.handlers[i] = handler
  22. return i
  23. }
  24. }
  25. e.handlers = append(e.handlers, handler)
  26. return len(e.handlers) - 1
  27. }
  28. func (e *DropFilesEvent) Detach(handle int) {
  29. e.handlers[handle] = nil
  30. for _, h := range e.handlers {
  31. if h != nil {
  32. return
  33. }
  34. }
  35. win.DragAcceptFiles(e.hWnd, false)
  36. }
  37. type DropFilesEventPublisher struct {
  38. event DropFilesEvent
  39. }
  40. func (p *DropFilesEventPublisher) Event(hWnd win.HWND) *DropFilesEvent {
  41. p.event.hWnd = hWnd
  42. return &p.event
  43. }
  44. func (p *DropFilesEventPublisher) Publish(hDrop win.HDROP) {
  45. var files []string
  46. n := win.DragQueryFile(hDrop, 0xFFFFFFFF, nil, 0)
  47. for i := 0; i < int(n); i++ {
  48. bufSize := uint(512)
  49. buf := make([]uint16, bufSize)
  50. if win.DragQueryFile(hDrop, uint(i), &buf[0], bufSize) > 0 {
  51. files = append(files, syscall.UTF16ToString(buf))
  52. }
  53. }
  54. win.DragFinish(hDrop)
  55. for _, handler := range p.event.handlers {
  56. if handler != nil {
  57. handler(files)
  58. }
  59. }
  60. }