当前位置: 首页>>代码示例>>C++>>正文


C++ CreateEvent函数代码示例

本文整理汇总了C++中CreateEvent函数的典型用法代码示例。如果您正苦于以下问题:C++ CreateEvent函数的具体用法?C++ CreateEvent怎么用?C++ CreateEvent使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了CreateEvent函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: mkEvent

HANDLE
mkEvent()
{
  return CreateEvent(NULL, FALSE, FALSE, NULL);
}
开发者ID:melted,项目名称:hdirect,代码行数:5,代码来源:ComPrimSrc.c

示例2: PlatformParker

 PlatformParker  () {
   _ParkEvent = CreateEvent (NULL, true, false, NULL) ;
   guarantee (_ParkEvent != NULL, "invariant") ;
 }
开发者ID:AK47POMA,项目名称:openjdk-icedtea7,代码行数:4,代码来源:os_windows.hpp

示例3: handle

//==============================================================================
WaitableEvent::WaitableEvent (const bool manualReset) noexcept
    : handle (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0)) {}
开发者ID:Ixox,项目名称:preenfm2Controller,代码行数:3,代码来源:juce_win32_Threads.cpp

示例4: CreateEvent

clNamedPipe *clNamedPipeConnectionsServer::waitForNewConnection( int timeout )
{
	PIPE_HANDLE hConn = this->initNewInstance();

#ifdef __WXMSW__
	OVERLAPPED ov = {0};
	HANDLE ev = CreateEvent(NULL, TRUE, TRUE, NULL);
	ov.hEvent = ev;
	
	HandleLockerServer locker(ov.hEvent);
	
	bool fConnected = ConnectNamedPipe(hConn, &ov);
	if (fConnected != 0) {
		if(hConn != INVALID_PIPE_HANDLE) {
			CloseHandle(hConn);
		}
		this->setLastError(NP_SERVER_UNKNOWN_ERROR);
		return NULL;
	}

	switch (GetLastError()) {

		// The overlapped connection in progress.
	case ERROR_IO_PENDING: {
		DWORD res = WaitForSingleObject(ov.hEvent, timeout) ;
		switch (res) {
		case WAIT_OBJECT_0 : {
			clNamedPipeServer *conn = new clNamedPipeServer(_pipePath);
			conn->setHandle(hConn);
			return conn;
		}
		case WAIT_TIMEOUT : {
			if ( hConn != INVALID_PIPE_HANDLE ) {
				CloseHandle( hConn );
			}
			this->setLastError(NP_SERVER_TIMEOUT);
			return NULL;
		}
		default: {
			if ( hConn != INVALID_PIPE_HANDLE ) {
				CloseHandle( hConn );
			}

			this->setLastError(NP_SERVER_UNKNOWN_ERROR);
			return NULL;
		}

		}
	}

	case ERROR_PIPE_CONNECTED: {
		clNamedPipeServer *conn = new clNamedPipeServer(_pipePath);
		conn->setHandle(hConn);
		return conn;
	}
	// If an error occurs during the connect operation...
	default: {
		if(hConn != INVALID_PIPE_HANDLE) {
			CloseHandle(hConn);
		}

		this->setLastError(NP_SERVER_UNKNOWN_ERROR);
		return NULL;
	}
	}
#else
	// accept new connection
	if (hConn != INVALID_PIPE_HANDLE) {

		if ( timeout > 0 ) {
			fd_set fds;
			struct timeval tv;
			memset( (void*)&fds, 0, sizeof( fds ) );
			FD_SET( hConn, &fds );
			tv.tv_sec = 0;
			tv.tv_usec = timeout * 1000; // convert mili to micro

			int rc = select(hConn + 1, &fds, 0, 0, &tv);
			if ( rc == 0 || rc < 0 ) {
				// timeout or error
				setLastError(NP_SERVER_TIMEOUT);
				return NULL;
			}
		}

		PIPE_HANDLE fd = ::accept(hConn, 0, 0);
		if (fd > 0) {
			clNamedPipeServer *conn = new clNamedPipeServer(_pipePath);
			conn->setHandle(fd);
			return conn;
		} else {
			perror("ERROR: accept");
			return NULL;
		}

	}
	return NULL;
#endif
}
开发者ID:05storm26,项目名称:codelite,代码行数:99,代码来源:np_connections_server.cpp

示例5: DispatchChild

// The server and client have to rely on
// certain interprocess communication schemes
// to exchange the WSAPROTOCOL_INFO needed for
// duplicating the socket.  In this sample,
// we use momory mapped files.
BOOL DispatchChild(SOCKET ClientSock, char *pszChildProcName)
{
    char szChildComandLineBuf[MAX_PATH];
    char szFileMappingObj[MAX_PATH];
    BOOL bResult = TRUE;
    STARTUPINFO siParent;
    PROCESS_INFORMATION piChild;
    char szParentEventName[MAX_PATH];
    char szChildEventName[MAX_PATH];

    ZeroMemory(&siParent, sizeof(siParent));
    siParent.cb = sizeof(siParent);
    siParent.dwFlags = STARTF_USECOUNTCHARS;
    siParent.dwXCountChars = 10 * MAX_PATH;
    siParent.dwYCountChars = MAX_PATH;

    // Compose a name for the memory mappled file.
    sprintf_s(szFileMappingObj,
              MAX_PATH,
              "%s%i",
              FILE_MAPPING_BASE_NAME,
              nChildProcCount++);

    sprintf_s(szParentEventName, MAX_PATH,"%s%s", szFileMappingObj, PARENT);
    sprintf_s(szChildEventName, MAX_PATH,"%s%s", szFileMappingObj, CHILD);

    // Create an event to signal the child
    // that the protocol info is set
    if ((ghParentFileMappingEvent = CreateEvent(NULL, TRUE, FALSE, szParentEventName)) == NULL)
    {
        fprintf(stderr, "\nCreateEvent() failed: %d\n", GetLastError());
        return FALSE;
    }

    // Create an event to for the child to signal the
    // parent that the protocol info can be released
    if ((ghChildFileMappingEvent = CreateEvent(NULL, TRUE, FALSE, szChildEventName)) == NULL)
    {
        fprintf(stderr, "\nCreateEvent() failed: %d\n", GetLastError());
        CloseHandle(ghParentFileMappingEvent);
        ghParentFileMappingEvent = NULL;
        return FALSE;
    }

    // Set up the child process command line options.
    // The memory mapped file name is passed in as
    // one of the options.
    sprintf_s(szChildComandLineBuf,
              MAX_PATH,
              "%s /c %s",
              pszChildProcName,
              szFileMappingObj);

    if (CreateProcess(NULL,
                szChildComandLineBuf,
                NULL,
                NULL,
                FALSE,
                CREATE_NEW_CONSOLE,
                NULL,
                NULL,
                &siParent,
                &piChild)) 
    {
        WSAPROTOCOL_INFO ProtocolInfo;
        int nError;
        LPVOID lpView;
        int nStructLen = sizeof(WSAPROTOCOL_INFO);

        // Get the protocol information
        // to be used to duplicate the socket
        if (WSADuplicateSocket(ClientSock,
                    piChild.dwProcessId,
                    &ProtocolInfo) == SOCKET_ERROR)
        {
            fprintf(stderr, "WSADuplicateSocket(): failed. Error = %d\n", WSAGetLastError());	
            DoCleanup();
            exit(1);
        }

        // Set the protocol information in a
        // memory mapped file for the child to use
        ghMMFileMap = CreateFileMapping(INVALID_HANDLE_VALUE,
                NULL,
                PAGE_READWRITE,
                0,
                nStructLen,
                szFileMappingObj);

        if (ghMMFileMap != NULL)
        {
            if ((nError = GetLastError()) == ERROR_ALREADY_EXISTS)
                fprintf(stderr, "CreateFileMapping(): mappping file already exists\n");
            else
            {
//.........这里部分代码省略.........
开发者ID:Essjay1,项目名称:Windows-classic-samples,代码行数:101,代码来源:Sockdups.c

示例6: WndProc

LRESULT CALLBACK WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
	int nItemCount;
	int nSelected;
	int *nIndexes;
	BOOL bFlag;
	WCHAR *pszFile;
	WCHAR *handle;
	WCHAR *token;
	Image *imgCurrent;
	Image out;

	switch (iMessage)
	{
		case WM_CREATE:
			HANDLE hToken;

			viewer.changeCaption(L"Preview");

			//Create Controls
			hListLayer = CreateWindow(L"ListBox", NULL, WS_CHILD | WS_VISIBLE | WS_VSCROLL | LBS_EXTENDEDSEL | LBS_HASSTRINGS | LBS_NOTIFY | LBS_MULTIPLESEL | LBS_NOINTEGRALHEIGHT, 0, 80, 240, 420, hWnd, (HMENU)ID_LAYER_LIST, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonStart = CreateWindow(L"Button", L"Start", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 0, 0, 80, 40, hWnd, (HMENU)ID_START_BUTTON, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonSave = CreateWindow(L"Button", L"Save Selected in merged file", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_MULTILINE, 80, 0, 80, 40, hWnd, (HMENU)ID_SAVE_BUTTON, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonSaveAll = CreateWindow(L"Button", L"Save All in individual file", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_MULTILINE, 160, 0, 80, 40, hWnd, (HMENU)ID_SAVE_ALL, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonResetAll = CreateWindow(L"Button", L"Erase All", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_MULTILINE, 0, 40, 80, 40, hWnd, (HMENU)ID_RESET_ALL, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonResetSelected = CreateWindow(L"Button", L"Erase Selected", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_MULTILINE, 80, 40, 80, 40, hWnd, (HMENU)ID_RESET_SEL, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
			hButtonResetUnselected = CreateWindow(L"Button", L"Erase Unelected", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_MULTILINE, 160, 40, 80, 40, hWnd, (HMENU)ID_RESET_UNSEL, ((LPCREATESTRUCT)lParam)->hInstance, NULL);

			hFont = CreateFont(16, 0, 0, 0, 400, 0, 0, 0, DEFAULT_CHARSET, 3, 2, 1, FF_ROMAN, L"Segoe UI");

			SendMessage(hListLayer, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonStart, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonSave, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonSaveAll, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonResetAll, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonResetSelected, WM_SETFONT, (WPARAM)hFont, TRUE);
			SendMessage(hButtonResetUnselected, WM_SETFONT, (WPARAM)hFont, TRUE);

			//Create Events
			hAttachSucceeded = CreateEvent(NULL, TRUE, FALSE, NULL);
			hDebugEnd = CreateEvent(NULL, TRUE, FALSE, NULL);
			hDebugInit = CreateEvent(NULL, TRUE, FALSE, NULL);

			//Adjust Privileges
			if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
			{
				if (SetPrivilege(hToken, SE_DEBUG_NAME, TRUE))
					return 0;
				else
					MessageBox(hWnd, L"Fail to get debug privilege!!", L"Error", MB_OK | MB_ICONERROR);
			}
			else
				MessageBox(hWnd, L"Fail to get process token!!", L"Error", MB_OK | MB_ICONERROR);

			SendMessage(hWnd, WM_DESTROY, 0, 0);

			return 0;
		case WM_ACTIVATE:
			if (wParam == WA_CLICKACTIVE)
			{
				viewer.foreground();
				SetForegroundWindow(hWnd);
				SetFocus(hListLayer);
			}
			return 0;
		case WM_COMMAND:
			switch (LOWORD(wParam))
			{
				case ID_START_BUTTON:
					if (!bStarted)
					{
						hAokanaWnd = FindAokana(&dwThreadID, &dwProcessID);

						if (dwThreadID != 0)
						{
							hDebugThread = CreateThread(NULL, 0, DebugThread, NULL, 0, NULL);

							WaitForSingleObject(hDebugInit, INFINITE);
							if (WaitForSingleObject(hAttachSucceeded, 0) != WAIT_OBJECT_0)
							{
								SetEvent(hDebugEnd);
								MessageBox(hWnd, L"Fail to attach process!!", L"Error", MB_OK | MB_ICONERROR);

								break;
							}

							SendMessage(hButtonStart, WM_SETTEXT, 0, (LPARAM)L"Stop");
							bStarted = TRUE;
						}
					}
					else
					{
						SetEvent(hDebugEnd);
						WaitForSingleObject(hDebugThread, INFINITE);

						ResetEvent(hDebugEnd);
						ResetEvent(hDebugInit);
						ResetEvent(hAttachSucceeded);
						CloseHandle(hDebugThread);

//.........这里部分代码省略.........
开发者ID:weimingtom,项目名称:AokanaCGExtractor,代码行数:101,代码来源:Main.cpp

示例7: _tWinMain

int APIENTRY _tWinMain(HINSTANCE hinst,	HINSTANCE foo1, LPTSTR foo2, int foo3) {
	MSG msg;
	WNDCLASSEX wcex = {sizeof(wcex)};
	HANDLE htray;
	HMENU hmenu;
	MENUITEMINFO mi = {sizeof(mi)};
	INITCOMMONCONTROLSEX icex;
	RECT rect;
	int style;
	HWND hwnd;

	wcex.lpfnWndProc = WndProc;
	wcex.lpszClassName = WINDOW_CLASS;
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
	RegisterClassEx(&wcex);

	icex.dwSize = sizeof(icex);
	icex.dwICC = ICC_DATE_CLASSES;
	InitCommonControlsEx(&icex);

	hwnd = CreateWindowEx(WS_EX_NOACTIVATE | WS_EX_TOPMOST, WINDOW_CLASS, WINDOW_TITLE, 0,
		0, 0, 0, 0, NULL, NULL, hinst, NULL);
	if (!hwnd) return 1;
	style = GetWindowLong(hwnd, GWL_STYLE);
	if (style & WS_CAPTION)  { 
		style ^= WS_CAPTION;
		SetWindowLong(hwnd, GWL_STYLE, style);
		SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
	}

	hcal = CreateWindowEx(0, MONTHCAL_CLASS, _T(""),
		WS_CHILD | WS_VISIBLE | MCS_NOTODAY | MCS_NOTRAILINGDATES | MCS_SHORTDAYSOFWEEK | MCS_NOSELCHANGEONNAV,
		0, 0, 0, 0, hwnd, NULL, hinst, NULL);
	MonthCal_GetMinReqRect(hcal, &rect);
	SetWindowPos(hcal, NULL, 0, 0, rect.right, rect.bottom, SWP_NOZORDER | SWP_NOMOVE);
	SetWindowPos(hwnd, NULL, 0, 0, rect.right, rect.bottom, SWP_NOZORDER | SWP_NOMOVE);

	tti.hwnd = hwnd;
	tti.hcal = hcal;
	tti.hnotify = CreateEvent(NULL, TRUE, FALSE, NULL);
	tti.exit = FALSE;
	htray = CreateThread(NULL, 0, &TrayThreadProc, &tti, 0, NULL);
	if (!htray) return 1;

	hsubmenu = CreateMenu();
	mi.fMask = MIIM_STRING | MIIM_ID;
	mi.wID = 1;
	mi.dwTypeData = EXIT_STRING;
	InsertMenuItem(hsubmenu, 0, TRUE, &mi);
	hmenu = CreateMenu();
	mi.fMask = MIIM_SUBMENU;
	mi.hSubMenu = hsubmenu;
	InsertMenuItem(hmenu, 0, TRUE, &mi);

	WM_TASKBARCREATED = RegisterWindowMessageA(_T("TaskbarCreated"));
	
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	DestroyMenu(hmenu);
	DestroyMenu(hsubmenu);

	WaitForSingleObject(htray, 1000);
	CloseHandle(htray);

	return (int)msg.wParam;
}
开发者ID:alexmarsev,项目名称:traybin,代码行数:69,代码来源:traybin.cpp

示例8: EIO_WatchPort

void EIO_WatchPort(uv_work_t* req) {
  WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);
  data->bytesRead = 0;
  data->disconnected = false;

  // Event used by GetOverlappedResult(..., TRUE) to wait for incoming data or timeout
  // Event MUST be used if program has several simultaneous asynchronous operations
  // on the same handle (i.e. ReadFile and WriteFile)
  HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

  while(true) {
    OVERLAPPED ov = {0};
    ov.hEvent = hEvent;

    // Start read operation - synchrounous or asynchronous
    DWORD bytesReadSync = 0;
    if(!ReadFile((HANDLE)data->fd, data->buffer, bufferSize, &bytesReadSync, &ov)) {
      data->errorCode = GetLastError();
      if(data->errorCode != ERROR_IO_PENDING) {
        // Read operation error
        if(data->errorCode == ERROR_OPERATION_ABORTED) {
          data->disconnected = true;
        }
        else {
          ErrorCodeToString("Reading from COM port (ReadFile)", data->errorCode, data->errorString);
        }
        break;
      }

      // Read operation is asynchronous and is pending
      // We MUST wait for operation completion before deallocation of OVERLAPPED struct
      // or read data buffer

      // Wait for async read operation completion or timeout
      DWORD bytesReadAsync = 0;
      if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesReadAsync, TRUE)) {
        // Read operation error
        data->errorCode = GetLastError();
        if(data->errorCode == ERROR_OPERATION_ABORTED) {
          data->disconnected = true;
        }
        else {
          ErrorCodeToString("Reading from COM port (GetOverlappedResult)", data->errorCode, data->errorString);
        }
        break;
      }
      else {
        // Read operation completed asynchronously
        data->bytesRead = bytesReadAsync;
      }
    }
    else {
      // Read operation completed synchronously
      data->bytesRead = bytesReadSync;
    }

    // Return data received if any
    if(data->bytesRead > 0) {
      break;
    }
  }

  CloseHandle(hEvent);
}
开发者ID:BrianAdams,项目名称:node-serialport,代码行数:64,代码来源:serialport_win.cpp

示例9: winmm_stream_init


//.........这里部分代码省略.........
  switch (output_stream_params->format) {
  case CUBEB_SAMPLE_S16LE:
    wfx.Format.wBitsPerSample = 16;
    wfx.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
    break;
  case CUBEB_SAMPLE_FLOAT32LE:
    wfx.Format.wBitsPerSample = 32;
    wfx.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
    break;
  default:
    return CUBEB_ERROR_INVALID_FORMAT;
  }

  wfx.Format.nBlockAlign = (wfx.Format.wBitsPerSample * wfx.Format.nChannels) / 8;
  wfx.Format.nAvgBytesPerSec = wfx.Format.nSamplesPerSec * wfx.Format.nBlockAlign;
  wfx.Samples.wValidBitsPerSample = wfx.Format.wBitsPerSample;

  EnterCriticalSection(&context->lock);
  /* CUBEB_STREAM_MAX is a horrible hack to avoid a situation where, when
     many streams are active at once, a subset of them will not consume (via
     playback) or release (via waveOutReset) their buffers. */
  if (context->active_streams >= CUBEB_STREAM_MAX) {
    LeaveCriticalSection(&context->lock);
    return CUBEB_ERROR;
  }
  context->active_streams += 1;
  LeaveCriticalSection(&context->lock);

  stm = calloc(1, sizeof(*stm));
  XASSERT(stm);

  stm->context = context;

  stm->params = *output_stream_params;

  stm->data_callback = data_callback;
  stm->state_callback = state_callback;
  stm->user_ptr = user_ptr;
  stm->written = 0;

  if (latency < context->minimum_latency) {
    latency = context->minimum_latency;
  }

  bufsz = (size_t) (stm->params.rate / 1000.0 * latency * bytes_per_frame(stm->params) / NBUFS);
  if (bufsz % bytes_per_frame(stm->params) != 0) {
    bufsz += bytes_per_frame(stm->params) - (bufsz % bytes_per_frame(stm->params));
  }
  XASSERT(bufsz % bytes_per_frame(stm->params) == 0);

  stm->buffer_size = bufsz;

  InitializeCriticalSection(&stm->lock);

  stm->event = CreateEvent(NULL, FALSE, FALSE, NULL);
  if (!stm->event) {
    winmm_stream_destroy(stm);
    return CUBEB_ERROR;
  }

  stm->soft_volume = -1.0;

  /* winmm_buffer_callback will be called during waveOutOpen, so all
     other initialization must be complete before calling it. */
  r = waveOutOpen(&stm->waveout, WAVE_MAPPER, &wfx.Format,
                  (DWORD_PTR) winmm_buffer_callback, (DWORD_PTR) stm,
                  CALLBACK_FUNCTION);
  if (r != MMSYSERR_NOERROR) {
    winmm_stream_destroy(stm);
    return CUBEB_ERROR;
  }

  r = waveOutPause(stm->waveout);
  if (r != MMSYSERR_NOERROR) {
    winmm_stream_destroy(stm);
    return CUBEB_ERROR;
  }


  for (i = 0; i < NBUFS; ++i) {
    WAVEHDR * hdr = &stm->buffers[i];

    hdr->lpData = calloc(1, bufsz);
    XASSERT(hdr->lpData);
    hdr->dwBufferLength = bufsz;
    hdr->dwFlags = 0;

    r = waveOutPrepareHeader(stm->waveout, hdr, sizeof(*hdr));
    if (r != MMSYSERR_NOERROR) {
      winmm_stream_destroy(stm);
      return CUBEB_ERROR;
    }

    winmm_refill_stream(stm);
  }

  *stream = stm;

  return CUBEB_OK;
}
开发者ID:cclauss,项目名称:gecko-dev,代码行数:101,代码来源:cubeb_winmm.c

示例10: test_capture_buffer

static void test_capture_buffer(LPDIRECTSOUNDCAPTURE dsco,
				LPDIRECTSOUNDCAPTUREBUFFER dscbo, int record)
{
    HRESULT rc;
    DSCBCAPS dscbcaps;
    WAVEFORMATEX wfx;
    DWORD size,status;
    capture_state_t state;
    int i, ref;

    /* Private dsound.dll: Error: Invalid caps pointer */
    rc=IDirectSoundCaptureBuffer_GetCaps(dscbo,0);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCaptureBuffer_GetCaps() should "
       "have returned DSERR_INVALIDPARAM, returned: %s\n",
       DXGetErrorString8(rc));

    /* Private dsound.dll: Error: Invalid caps pointer */
    dscbcaps.dwSize=0;
    rc=IDirectSoundCaptureBuffer_GetCaps(dscbo,&dscbcaps);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCaptureBuffer_GetCaps() should "
       "have returned DSERR_INVALIDPARAM, returned: %s\n",
       DXGetErrorString8(rc));

    dscbcaps.dwSize=sizeof(dscbcaps);
    rc=IDirectSoundCaptureBuffer_GetCaps(dscbo,&dscbcaps);
    ok(rc==DS_OK,"IDirectSoundCaptureBuffer_GetCaps() failed: %s\n",
       DXGetErrorString8(rc));
    if (rc==DS_OK && winetest_debug > 1) {
	trace("    Caps: size = %d flags=0x%08x buffer size=%d\n",
	    dscbcaps.dwSize,dscbcaps.dwFlags,dscbcaps.dwBufferBytes);
    }

    /* Query the format size. Note that it may not match sizeof(wfx) */
    /* Private dsound.dll: Error: Either pwfxFormat or pdwSizeWritten must
     * be non-NULL */
    rc=IDirectSoundCaptureBuffer_GetFormat(dscbo,NULL,0,NULL);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCaptureBuffer_GetFormat() should "
       "have returned DSERR_INVALIDPARAM, returned: %s\n",
       DXGetErrorString8(rc));

    size=0;
    rc=IDirectSoundCaptureBuffer_GetFormat(dscbo,NULL,0,&size);
    ok(rc==DS_OK && size!=0,"IDirectSoundCaptureBuffer_GetFormat() should "
       "have returned the needed size: rc=%s, size=%d\n",
       DXGetErrorString8(rc),size);

    rc=IDirectSoundCaptureBuffer_GetFormat(dscbo,&wfx,sizeof(wfx),NULL);
    ok(rc==DS_OK,"IDirectSoundCaptureBuffer_GetFormat() failed: %s\n",
       DXGetErrorString8(rc));
    if (rc==DS_OK && winetest_debug > 1) {
	trace("    Format: tag=0x%04x %dx%dx%d avg.B/s=%d align=%d\n",
	      wfx.wFormatTag,wfx.nSamplesPerSec,wfx.wBitsPerSample,
	      wfx.nChannels,wfx.nAvgBytesPerSec,wfx.nBlockAlign);
    }

    /* Private dsound.dll: Error: Invalid status pointer */
    rc=IDirectSoundCaptureBuffer_GetStatus(dscbo,0);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCaptureBuffer_GetStatus() should "
       "have returned DSERR_INVALIDPARAM, returned: %s\n",
       DXGetErrorString8(rc));

    rc=IDirectSoundCaptureBuffer_GetStatus(dscbo,&status);
    ok(rc==DS_OK,"IDirectSoundCaptureBuffer_GetStatus() failed: %s\n",
       DXGetErrorString8(rc));
    if (rc==DS_OK && winetest_debug > 1) {
	trace("    Status=0x%04x\n",status);
    }

    ZeroMemory(&state, sizeof(state));
    state.dscbo=dscbo;
    state.wfx=&wfx;
    state.buffer_size = dscbcaps.dwBufferBytes;
    for (i = 0; i < NOTIFICATIONS; i++)
	state.event[i] = CreateEvent( NULL, FALSE, FALSE, NULL );
    state.size = dscbcaps.dwBufferBytes / NOTIFICATIONS;

    rc=IDirectSoundCaptureBuffer_QueryInterface(dscbo,&IID_IDirectSoundNotify,
                                                (void **)&(state.notify));
    ok((rc==DS_OK)&&(state.notify!=NULL),
       "IDirectSoundCaptureBuffer_QueryInterface() failed: %s\n",
       DXGetErrorString8(rc));
    if (rc!=DS_OK)
	return;

    for (i = 0; i < NOTIFICATIONS; i++) {
	state.posnotify[i].dwOffset = (i * state.size) + state.size - 1;
	state.posnotify[i].hEventNotify = state.event[i];
    }

    rc=IDirectSoundNotify_SetNotificationPositions(state.notify,NOTIFICATIONS,
                                                   state.posnotify);
    ok(rc==DS_OK,"IDirectSoundNotify_SetNotificationPositions() failed: %s\n",
       DXGetErrorString8(rc));
    if (rc!=DS_OK)
	return;

    ref=IDirectSoundNotify_Release(state.notify);
    ok(ref==0,"IDirectSoundNotify_Release(): has %d references, should have "
       "0\n",ref);
    if (ref!=0)
//.........这里部分代码省略.........
开发者ID:WASSUM,项目名称:longene_travel,代码行数:101,代码来源:capture.c

示例11: mmp_thread

DWORD mmp_thread( DWORD dw ) { // open device

	int i;
	int nextbuf;
	
	short* sampledata;
	WAVEFORMATEX waveformat;
	WAVEHDR waveheader[NUMBUFS];

	if (UseDevice==(unsigned int)-1) return 0;

	SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_HIGHEST);

	weHaveTerminated=0;
	waveformat.wFormatTag=WAVE_FORMAT_PCM;
	waveformat.nChannels=2;
	waveformat.wBitsPerSample=16;
	waveformat.nSamplesPerSec=44100;
	waveformat.nBlockAlign=(waveformat.nChannels*waveformat.wBitsPerSample)/8;
    waveformat.nAvgBytesPerSec=waveformat.nSamplesPerSec*waveformat.nBlockAlign;
	waveformat.cbSize=0;

	waveOutOpen(&audiodev,UseDevice,&waveformat,(unsigned int)bufferdone,0,CALLBACK_FUNCTION);
#ifdef MMPDEBUG
	printf("audiodev: %X\n",audiodev);
#endif

	musicevent=CreateEvent(NULL,FALSE,FALSE,"WinUsmPlayer");
	sampledata=(short*)GlobalAlloc(MEM_COMMIT,BUFLENGTH*NUMBUFS);

#ifdef MMPDEBUG
	printf("%X, %X\n",sampledata,sampledata+BUFLENGTH*NUMBUFS);
#endif

	for (i=0;i<NUMBUFS;i++)
	{
		//printf("preparing %ld bytes at %X\n", BUFLENGTH, sampledata+BUFLENGTH*i);
		waveheader[i].lpData=(char*)sampledata+i*BUFLENGTH;
		waveheader[i].dwFlags=0;
		waveheader[i].dwBufferLength = BUFLENGTH;
		waveOutPrepareHeader(audiodev,&waveheader[i],sizeof(WAVEHDR));
		mmp_generate( sampledata+(i*BUFLENGTH/2), BUFLENGTH>>1 );
		waveOutWrite(audiodev,&waveheader[i],sizeof(WAVEHDR));
	}

	nextbuf=0;
	while(playing)
    {
        IXA_PlayerActive=0;
		if (WaitForSingleObject(musicevent,1000)==WAIT_TIMEOUT)
		{
//			WinUsmPlayPause();
//			WinUsmPlayRestart();
		}

        IXA_PlayerActive=1;
		for (i=0;i<NUMBUFS;i++)
        {
			if ((waveheader[i].dwFlags & WHDR_DONE) && nextbuf==i)
			{
				waveOutUnprepareHeader(audiodev,&waveheader[i],sizeof(WAVEHDR));
				mmp_generate( sampledata+(i*BUFLENGTH/2), BUFLENGTH>>1 );
				waveOutPrepareHeader(audiodev,&waveheader[i],sizeof(WAVEHDR));
				waveOutWrite(audiodev,&waveheader[i],sizeof(WAVEHDR));
				nextbuf++;
				if (nextbuf==NUMBUFS) nextbuf=0;
			}
		}
	}
开发者ID:brownman,项目名称:randomjunk,代码行数:69,代码来源:mmp_output.c

示例12: TCPServer

// Função relativa à thread do servidor TCP. é o intermédio entre o client OPC e o client TCP,
// trocando assim mensagens constantemente entre ambos os clientes.
DWORD WINAPI TCPServer(LPVOID id) {

    WSADATA wsaData;
    int iResult;

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;

    struct addrinfo *result = NULL;
    struct addrinfo hints;

    int iSendResult;

	char recvbuf[DEFAULT_BUFLEN];
    
	int recvbuflen = DEFAULT_BUFLEN;
	int seqdados = 0;

	char ack_string[13];
	char ack_data[14];

    char msgreq[TAMMSGREQ+1];

    char msgsp[TAMMSGSP+1];

	Monitor<vector<int>> mSocket(VERB_ON);

	char dados2[55];
	char dados1[100];

	LPTSTR MailSlotDados = TEXT("\\\\.\\mailslot\\mailslotDados");	//Inicializa mailslot Dados (caminho da troca de dados de processo)
	LPTSTR MailSlotSP = TEXT("\\\\.\\mailslot\\mailslotSP");		//Inicializa mailslot SP (caminho da troca de setpoints)

	HANDLE hSlotDados = CreateMailslot(MailSlotDados,		//Criação do mailslot de dados
															//Código adaptado do MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365785%28v=vs.85%29.aspx
        0,                             // no maximum message size 
        MAILSLOT_WAIT_FOREVER,         // no time-out for operations 
        (LPSECURITY_ATTRIBUTES) NULL); // default security
 
    if (hSlotDados == INVALID_HANDLE_VALUE) 
    { 
        printf("CreateMailslot failed with %d\n", GetLastError());
        return FALSE; 
    } 
    else printf("MailslotDados created successfully.\n"); 

	HANDLE hFileSP = CreateFile(MailSlotSP,			// Abertura de arquivo para leitura do mailslot de setpoints
													// Código adaptado do MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365802%28v=vs.85%29.aspx
		 GENERIC_WRITE, 
		 FILE_SHARE_READ,
		 (LPSECURITY_ATTRIBUTES) NULL, 
		 OPEN_EXISTING, 
		 FILE_ATTRIBUTE_NORMAL, 
		 (HANDLE) NULL); 

	if (hFileSP == INVALID_HANDLE_VALUE)  
		printf("CreateFile failed with %d.\n", GetLastError());
	else
		printf("MailSlotSP File criado.\n");

		// Criação de um evento para sincronizar a leitura do mailslot de setpoints.
		// Este evento será setado após os setpoints serem escritos no arquivo,
		// desta forma, o client OPC apenas vai ler deste quando tal ocorrer.
	   HANDLE hMSWrite = CreateEvent(NULL, FALSE, FALSE, TEXT("hMSWrite"));

	 if (hMSWrite == INVALID_HANDLE_VALUE)  
		printf("Handle hMSWrite failed with %d.\n", GetLastError());
	else
		printf("hMSWrite, handle criado.\n");


	// Daqui em diante, grande parte do código de inicialização de um servidor TCP foi retirado do MSDN
	// https://msdn.microsoft.com/pt-br/library/windows/desktop/ms737593%28v=vs.85%29.aspx
	// A partir do código acima, alterações foram feitas para que a comunicação também com o Cliente OPC ocorresse
	// e também para que reconexões possam ser feitas. O servidor continua a tratar apenas um cliente simultâneo,
	// visto que não era previsto múltiplos acessos pela especificação do trabalho prático (apenas um computador do processo)

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }
	 printf("TCP Server inicializado.\n");//Linha adicionada

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }
//.........这里部分代码省略.........
开发者ID:gchamon,项目名称:SDA-TP1V3,代码行数:101,代码来源:tpfunctions.cpp

示例13: ReadSlot

// Função para leitura de um mailslot. Recebe como parâmetros o handle do mailslot em questão
// e um buffer para receber a mensagem lida.
// Adapatada da função ReadSlot do MSDN:
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365785%28v=vs.85%29.aspx
BOOL ReadSlot(HANDLE hSlot, char* outStr)	// Foi adicionado o parâmetro do HANDLE, para poder diferenciar
											// entre os mailslots criados. Foi também adicionado um vetor
											// de saída, para transportar a mensagem.
{ 
    DWORD cbMessage, cMessage, cbRead; 
    BOOL fResult; 
    LPTSTR lpszBuffer; 
    TCHAR achID[80]; 
    DWORD cAllMessages; 
    HANDLE hEvent;
    OVERLAPPED ov;
 
    cbMessage = cMessage = cbRead = 0; 

    hEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("hMailSlot"));
    if( NULL == hEvent )
        return FALSE;
    ov.Offset = 0;
    ov.OffsetHigh = 0;
    ov.hEvent = hEvent;
 
    fResult = GetMailslotInfo( hSlot, // mailslot handle 
        (LPDWORD) NULL,               // no maximum message size 
        &cbMessage,                   // size of next message 
        &cMessage,                    // number of messages 
        (LPDWORD) NULL);              // no read time-out 
 
    if (!fResult) 
    { 
        printf("GetMailslotInfo failed with %d.\n", GetLastError()); 
        return FALSE; 
    } 
 
    if (cbMessage == MAILSLOT_NO_MESSAGE) 
    { 
        printf("Waiting for a message...\n"); 
        return TRUE; 
    } 
 
    cAllMessages = cMessage; 
 
    while (cMessage != 0)  // retrieve all messages
    { 
        // Create a message-number string. 
 
        StringCchPrintf((LPTSTR) achID, 
            80,
            TEXT("\nMessage #%d of %d\n"), 
            cAllMessages - cMessage + 1, 
            cAllMessages); 

        // Allocate memory for the message. 
 
        lpszBuffer = (LPTSTR) GlobalAlloc(GPTR, 
            lstrlen((LPTSTR) achID)*sizeof(TCHAR) + cbMessage); 
        if( NULL == lpszBuffer )
            return FALSE;
        lpszBuffer[0] = '\0'; 
 
        fResult = ReadFile(hSlot, 
            lpszBuffer, 
            cbMessage, 
            &cbRead, 
            &ov); 
 
        if (!fResult) 
        { 
            printf("ReadFile failed with %d.\n", GetLastError()); 
            GlobalFree((HGLOBAL) lpszBuffer); 
            return FALSE; 
        } 
 
        // Concatenate the message and the message-number string. 
 
        StringCbCat(lpszBuffer, 
                    lstrlen((LPTSTR) achID)*sizeof(TCHAR)+cbMessage, 
                    (LPTSTR) achID); 
 
        // Display the message. 
 
        //_tprintf(TEXT("Contents of the mailslot: %s\n"), lpszBuffer); 
 
		strcpy_s(outStr, 100, lpszBuffer);
 
        fResult = GetMailslotInfo(hSlot,  // mailslot handle 
            (LPDWORD) NULL,               // no maximum message size 
            &cbMessage,                   // size of next message 
            &cMessage,                    // number of messages 
            (LPDWORD) NULL);              // no read time-out 
 
        if (!fResult) 
        { 
            printf("GetMailslotInfo failed (%d)\n", GetLastError());
            return FALSE; 
        } 
    } 
//.........这里部分代码省略.........
开发者ID:gchamon,项目名称:SDA-TP1V3,代码行数:101,代码来源:tpfunctions.cpp

示例14: wince_init

// Internal API functions
static int wince_init(struct libusb_context *ctx)
{
    int i, r = LIBUSB_ERROR_OTHER;
    HANDLE semaphore;
    TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)

    _stprintf(sem_name, _T("libusb_init%08X"), (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
    semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
    if (semaphore == NULL) {
        usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
        return LIBUSB_ERROR_NO_MEM;
    }

    // A successful wait brings our semaphore count to 0 (unsignaled)
    // => any concurent wait stalls until the semaphore's release
    if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
        usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
        CloseHandle(semaphore);
        return LIBUSB_ERROR_NO_MEM;
    }

    // NB: concurrent usage supposes that init calls are equally balanced with
    // exit calls. If init is called more than exit, we will not exit properly
    if ( ++concurrent_usage == 0 ) {	// First init?
        // Initialize pollable file descriptors
        init_polling();

        // Load DLL imports
        if (init_dllimports() != LIBUSB_SUCCESS) {
            usbi_err(ctx, "could not resolve DLL functions");
            r = LIBUSB_ERROR_NOT_SUPPORTED;
            goto init_exit;
        }

        // try to open a handle to the driver
        driver_handle = UkwOpenDriver();
        if (driver_handle == INVALID_HANDLE_VALUE) {
            usbi_err(ctx, "could not connect to driver");
            r = LIBUSB_ERROR_NOT_SUPPORTED;
            goto init_exit;
        }

        // Windows CE doesn't have a way of specifying thread affinity, so this code
        // just has  to hope QueryPerformanceCounter doesn't report different values when
        // running on different cores.
        r = LIBUSB_ERROR_NO_MEM;
        for (i = 0; i < 2; i++) {
            timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
            if (timer_request[i] == NULL) {
                usbi_err(ctx, "could not create timer request event %d - aborting", i);
                goto init_exit;
            }
        }
        timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
        if (timer_response == NULL) {
            usbi_err(ctx, "could not create timer response semaphore - aborting");
            goto init_exit;
        }
        timer_mutex = CreateMutex(NULL, FALSE, NULL);
        if (timer_mutex == NULL) {
            usbi_err(ctx, "could not create timer mutex - aborting");
            goto init_exit;
        }
        timer_thread = CreateThread(NULL, 0, wince_clock_gettime_threaded, NULL, 0, NULL);
        if (timer_thread == NULL) {
            usbi_err(ctx, "Unable to create timer thread - aborting");
            goto init_exit;
        }

        // Wait for timer thread to init before continuing.
        if (WaitForSingleObject(timer_response, INFINITE) != WAIT_OBJECT_0) {
            usbi_err(ctx, "Failed to wait for timer thread to become ready - aborting");
            goto init_exit;
        }
    }
    // At this stage, either we went through full init successfully, or didn't need to
    r = LIBUSB_SUCCESS;

init_exit: // Holds semaphore here.
    if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
        if (driver_handle != INVALID_HANDLE_VALUE) {
            UkwCloseDriver(driver_handle);
            driver_handle = INVALID_HANDLE_VALUE;
        }
        if (timer_thread) {
            SetEvent(timer_request[1]); // actually the signal to quit the thread.
            if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
                usbi_warn(ctx, "could not wait for timer thread to quit");
                TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
                // all objects it might have held anyway.
            }
            CloseHandle(timer_thread);
            timer_thread = NULL;
        }
        for (i = 0; i < 2; i++) {
            if (timer_request[i]) {
                CloseHandle(timer_request[i]);
                timer_request[i] = NULL;
            }
//.........这里部分代码省略.........
开发者ID:venkatarajasekhar,项目名称:Qt,代码行数:101,代码来源:wince_usb.c

示例15: TRACE_ENTER

HRESULT CKsIrpTarget::SyncIoctl(
        IN  HANDLE  handle,
        IN  ULONG   ulIoctl,
        IN  PVOID   pvInBuffer,
        IN  ULONG   cbInBuffer,
        OUT PVOID   pvOutBuffer,
        OUT ULONG   cbOutBuffer,
        OUT PULONG  pulBytesReturned)
{
    TRACE_ENTER();
    HRESULT hr = S_OK;
    OVERLAPPED overlapped;
        BOOL fRes = TRUE;
        ULONG ulBytesReturned;

    if (!IsValidHandle(handle))
    {
        hr = E_FAIL;
        DebugPrintf(TRACE_ERROR,TEXT("CKsIrpTarget::SyncIoctl Invalid Handle"));
    }
    
    if (!pulBytesReturned)
    {
        pulBytesReturned = &ulBytesReturned;
    }

    if (SUCCEEDED(hr))
    {
        ZeroMemory(&overlapped,sizeof(overlapped));
        overlapped.hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
        if (!overlapped.hEvent)
        {
            hr = E_OUTOFMEMORY;
            DebugPrintf(TRACE_ERROR,TEXT("CKsIrpTarget::SyncIoctl CreateEvent failed"));
        }
        else
        {
            // Flag the event by setting the low-order bit so we
            // don't get completion port notifications.
            // Really! - see the description of the lpOverlapped parameter in
            // the docs for GetQueuedCompletionStatus
            overlapped.hEvent = (HANDLE)((DWORD_PTR)overlapped.hEvent | 0x1);
        }
    }

    if (SUCCEEDED(hr))
    {
        fRes = DeviceIoControl(handle, ulIoctl, pvInBuffer, cbInBuffer, pvOutBuffer, cbOutBuffer, pulBytesReturned, &overlapped);
        if (!fRes)
        {

            DWORD dwError;
            dwError = GetLastError();
            if (ERROR_IO_PENDING == dwError)
            {
                DWORD dwWait;
                // Wait for completion
                dwWait = ::WaitForSingleObject(overlapped.hEvent,INFINITE);
                ASSERT(WAIT_OBJECT_0 == dwWait);
                if (dwWait != WAIT_OBJECT_0)
                {
                    hr = E_FAIL;
                    DebugPrintf(TRACE_ERROR,TEXT("CKsIrpTarget::SyncIoctl WaitForSingleObject failed dwWait:0x%08x"),dwWait);
                }
            }
            else if (((ERROR_INSUFFICIENT_BUFFER == dwError) || (ERROR_MORE_DATA == dwError)) &&
                (IOCTL_KS_PROPERTY == ulIoctl) &&
                (cbOutBuffer == 0))
            {
                hr = S_OK;
                fRes = TRUE;
            }
            else
            {
                hr = E_FAIL;
            }
        }
        if (!fRes) *pulBytesReturned = 0;
        SafeCloseHandle(overlapped.hEvent);
    }
    
    TRACE_LEAVE_HRESULT(hr);
    return hr;
}
开发者ID:chicken1337,项目名称:kx-audio-driver,代码行数:84,代码来源:irptgt.cpp


注:本文中的CreateEvent函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。