5
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

これはボタン付きの単純なwin32GUIアプリケーションですが、ボタンをクリックするとメッセージボックス(22行)が表示されるはずですが、エラーが発生します。

buttons.exe:スケジュール:安全でない状態で再入力されました。おそらく、「安全でない外国からの輸入」は「安全」であるべきですか?

どうすれば修正できますか?

4

1 に答える 1

4

Daniel Wagnerがコメントしたように、これはWin32パッケージのバグです。MessageBoxW多くの副作用があるため、安全にインポートする必要があります。

このmessageBox関数は、「安全でない」インポートされた関数のラッパーですMessageBoxW。安全にインポートされていない関数関数が安全にインポートされていない場合、Haskellはスレッドが戻るまでHaskellコードを呼び出さないと想定します。ただし、を呼び出すとMessageBoxW、Windowsは30行目で作成したウィンドウにかなりの数のウィンドウメッセージをスローするため、安全でない外部関数を使用しているときにHaskellコードが実行されます。これは、そのウィンドウが作成されるまでmessageBoxへの呼び出しが機能する理由でもあります。

考えられる回避策は、関数を自分で修正することです。まず、変更します

import Graphics.Win32

import Graphics.Win32 hiding (messageBox, c_MessageBox)

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
于 2011-09-08T23:15:40.583 に答える