import Graphics.Win32
import System.Win32.DLL
import Control.Exception (bracket)
import Foreign
import System.Exit
main :: IO ()
main = do
mainInstance <- getModuleHandle Nothing
hwnd <- createWindow_ 200 200 wndProc mainInstance
createButton_ hwnd mainInstance
messagePump hwnd
wndProc :: HWND -> WindowMessage -> WPARAM -> LPARAM -> IO LRESULT
wndProc hwnd wmsg wParam lParam
| wmsg == wM_DESTROY = do
sendMessage hwnd wM_QUIT 1 0
return 0
| wmsg == wM_COMMAND && wParam == 1 = do
messageBox nullPtr "Yahoo!!" "Message box" 0 -- Error! Why? :(
return 0
| otherwise = defWindowProc (Just hwnd) wmsg wParam lParam
createWindow_ :: Int -> Int -> WindowClosure -> HINSTANCE -> IO HWND
createWindow_ width height wndProc mainInstance = do
let winClass = mkClassName "ButtonExampleWindow"
icon <- loadIcon Nothing iDI_APPLICATION
cursor <- loadCursor Nothing iDC_ARROW
bgBrush <- createSolidBrush (rgb 240 240 240)
registerClass (cS_VREDRAW + cS_HREDRAW, mainInstance, Just icon, Just cursor, Just bgBrush, Nothing, winClass)
w <- createWindow winClass "Button example" wS_OVERLAPPEDWINDOW Nothing Nothing (Just width) (Just height) Nothing Nothing mainInstance wndProc
showWindow w sW_SHOWNORMAL
updateWindow w
return w
createButton_ :: HWND -> HINSTANCE -> IO ()
createButton_ hwnd mainInstance = do
hBtn <- createButton "Press me" wS_EX_CLIENTEDGE (bS_PUSHBUTTON + wS_VISIBLE + wS_CHILD) (Just 50) (Just 80) (Just 80) (Just 20) (Just hwnd) (Just (castUINTToPtr 1)) mainInstance
return ()
messagePump :: HWND -> IO ()
messagePump hwnd = allocaMessage $ \ msg ->
let pump = do
getMessage msg (Just hwnd) `catch` \ _ -> exitWith ExitSuccess
translateMessage msg
dispatchMessage msg
pump
in pump
Run Code Online (Sandbox Code Playgroud)
这是一个带按钮的简单的win32 gui应用程序但是当我点击按钮时必须有一个消息框(22行),但是有错误:
buttons.exe:schedule:不安全地重新输入.也许"外国进口不安全"应该是"安全的"?
我该如何解决?
小智 4
就像Daniel Wagner评论的那样,这是Win32包中的一个错误.MessageBoxW必须安全进口,因为它有许多副作用.
该messageBox函数是"不安全"导入MessageBoxW函数的包装器.当不安全地导入不安全导入的函数函数时,Haskell假定线程在返回之前不会调用任何Haskell代码.但是,如果你调用MessageBoxW,Windows会向你在第30行创建的窗口抛出相当多的窗口消息,因此当你处于不安全的外部函数时,会运行Haskell代码.这也是为什么调用messageBox将在该窗口创建之前工作的原因.
一种可能的解决方法是自己简单地纠正这个功能.首先,改变
import Graphics.Win32
Run Code Online (Sandbox Code Playgroud)
至
import Graphics.Win32 hiding (messageBox, c_MessageBox)
Run Code Online (Sandbox Code Playgroud)
然后,复制的定义messageBox和c_MessageBox从模块Graphics.Win32.Misc,以unsafe移除和/或safe添加的:
messageBox :: HWND -> String -> String -> MBStyle -> IO MBStatus
messageBox wnd text caption style =
withTString text $ \ c_text ->
withTString caption $ \ c_caption ->
failIfZero "MessageBox" $ c_MessageBox wnd c_text c_caption style
foreign import stdcall safe "windows.h MessageBoxW"
c_MessageBox :: HWND -> LPCTSTR -> LPCTSTR -> MBStyle -> IO MBStatus
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
601 次 |
| 最近记录: |