Search Results

Search found 746 results on 30 pages for 'winapi'.

Page 5/30 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • ReadFile doesn't work asynchronously on Win7 and Win2k8

    - by f0b0s
    According to MSDN ReadFile can read data 2 different ways: synchronously and asynchronously. I need the second one. The folowing code demonstrates usage with OVERLAPPED struct: #include <windows.h> #include <stdio.h> #include <time.h> void Read() { HANDLE hFile = CreateFileA("c:\\1.avi", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if ( hFile == INVALID_HANDLE_VALUE ) { printf("Failed to open the file\n"); return; } int dataSize = 256 * 1024 * 1024; char* data = (char*)malloc(dataSize); memset(data, 0xFF, dataSize); OVERLAPPED overlapped; memset(&overlapped, 0, sizeof(overlapped)); printf("reading: %d\n", time(NULL)); BOOL result = ReadFile(hFile, data, dataSize, NULL, &overlapped); printf("sent: %d\n", time(NULL)); DWORD bytesRead; result = GetOverlappedResult(hFile, &overlapped, &bytesRead, TRUE); // wait until completion - returns immediately printf("done: %d\n", time(NULL)); CloseHandle(hFile); } int main() { Read(); } On Windows XP output is: reading: 1296651896 sent: 1296651896 done: 1296651899 It means that ReadFile didn't block and returned imediatly at the same second, whereas reading process continued for 3 seconds. It is normal async reading. But on windows 7 and windows 2008 I get following results: reading: 1296661205 sent: 1296661209 done: 1296661209. It is a behavior of sync reading. MSDN says that async ReadFile sometimes can behave as sync (when the file is compressed or encrypted for example). But the return value in this situation should be TRUE and GetLastError() == NO_ERROR. On Windows 7 I get FALSE and GetLastError() == ERROR_IO_PENDING. So WinApi tells me that it is an async call, but when I look at the test I see that it is not! I'm not the only one who found this "bug": read the comment on ReadFile MSDN page. So what's the solution? Does anybody know? It is been 14 months after Denis found this strange behavior.

    Read the article

  • Implementing events to communicate between two processes - C

    - by Jamie Keeling
    Hello all! I have an application consisting of two windows, one communicates to the other and sends it a struct constaining two integers (In this case two rolls of a dice). I will be using events for the following circumstances: Process a sends data to process b, process b displays data Process a closes, in turn closing process b Process b closes a, in turn closing process a I have noticed that if the second process is constantly waiting for the first process to send data then the program will be just sat waiting, which is where the idea of implementing threads on each process occurred and I have started to implement this already. The problem i'm having is that I don't exactly have a lot of experience with threads and events so I'm not sure of the best way to actually implement what I want to do. Following is a small snippet of what I have so far in the producer application; Create thread: case IDM_FILE_ROLLDICE: { hDiceRoll = CreateThread( NULL, // lpThreadAttributes (default) 0, // dwStackSize (default) ThreadFunc(hMainWindow), // lpStartAddress NULL, // lpParameter 0, // dwCreationFlags &hDiceID // lpThreadId (returned by function) ); } break; The data being sent to the other process: DWORD WINAPI ThreadFunc(LPVOID passedHandle) { HANDLE hMainHandle = *((HANDLE*)passedHandle); WCHAR buffer[256]; LPCTSTR pBuf; LPVOID lpMsgBuf; LPVOID lpDisplayBuf; struct diceData storage; HANDLE hMapFile; DWORD dw; //Roll dice and store results in variable storage = RollDice(); hMapFile = CreateFileMapping( (HANDLE)0xFFFFFFFF, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) BUF_SIZE, // maximum object size (low-order DWORD) szName); // name of mapping object if (hMapFile == NULL) { dw = GetLastError(); MessageBox(hMainHandle,L"Could not create file mapping object",L"Error",MB_OK); return 1; } pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { MessageBox(hMainHandle,L"Could not map view of file",L"Error",MB_OK); CloseHandle(hMapFile); return 1; } CopyMemory((PVOID)pBuf, &storage, (_tcslen(szMsg) * sizeof(TCHAR))); //_getch(); MessageBox(hMainHandle,L"Completed!",L"Success",MB_OK); UnmapViewOfFile(pBuf); return 0; } I'm trying to find out how I would integrate an event with the threaded code to signify to the other process that something has happened, I've seen an MSDN article on using events but it's just confused me if anything, I'm coming up on empty whilst searching on the internet too. Thanks for any help Edit: I can only use the Create/Set/Open methods for events, sorry for not mentioning it earlier.

    Read the article

  • Using events in threads between processes - C

    - by Jamie Keeling
    Hello all! I have an application consisting of two windows, one communicates to the other and sends it a struct constaining two integers (In this case two rolls of a dice). I will be using events for the following circumstances: Process a sends data to process b, process b displays data Process a closes, in turn closing process b Process b closes a, in turn closing process a I have noticed that if the second process is constantly waiting for the first process to send data then the program will be just sat waiting, which is where the idea of implementing threads on each process occurred and I have started to implement this already. The problem i'm having is that I don't exactly have a lot of experience with threads and events so I'm not sure of the best way to actually implement what I want to do. Following is a small snippet of what I have so far in the producer application; Create thread: case IDM_FILE_ROLLDICE: { hDiceRoll = CreateThread( NULL, // lpThreadAttributes (default) 0, // dwStackSize (default) ThreadFunc(hMainWindow), // lpStartAddress NULL, // lpParameter 0, // dwCreationFlags &hDiceID // lpThreadId (returned by function) ); } break; The data being sent to the other process: DWORD WINAPI ThreadFunc(LPVOID passedHandle) { HANDLE hMainHandle = *((HANDLE*)passedHandle); WCHAR buffer[256]; LPCTSTR pBuf; LPVOID lpMsgBuf; LPVOID lpDisplayBuf; struct diceData storage; HANDLE hMapFile; DWORD dw; //Roll dice and store results in variable storage = RollDice(); hMapFile = CreateFileMapping( (HANDLE)0xFFFFFFFF, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) BUF_SIZE, // maximum object size (low-order DWORD) szName); // name of mapping object if (hMapFile == NULL) { dw = GetLastError(); MessageBox(hMainHandle,L"Could not create file mapping object",L"Error",MB_OK); return 1; } pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { MessageBox(hMainHandle,L"Could not map view of file",L"Error",MB_OK); CloseHandle(hMapFile); return 1; } CopyMemory((PVOID)pBuf, &storage, (_tcslen(szMsg) * sizeof(TCHAR))); //_getch(); MessageBox(hMainHandle,L"Completed!",L"Success",MB_OK); UnmapViewOfFile(pBuf); return 0; } I'm trying to find out how I would integrate an event with the threaded code to signify to the other process that something has happened, I've seen an MSDN article on using events but it's just confused me if anything, I'm coming up on empty whilst searching on the internet too. Thanks for any help Edit: I can only use the Create/Set/Open methods for events, sorry for not mentioning it earlier.

    Read the article

  • Ideas on implementing threads and cross process communication. - C

    - by Jamie Keeling
    Hello all! I have an application consisting of two windows, one communicates to the other and sends it a struct constaining two integers (In this case two rolls of a dice). I will be using events for the following circumstances: Process a sends data to process b, process b displays data Process a closes, in turn closing process b Process b closes a, in turn closing process a I have noticed that if the second process is constantly waiting for the first process to send data then the program will be just sat waiting, which is where the idea of implementing threads on each process occured. I have already implemented a thread on the first process which currently creates the data to send to the second process and makes it available to the second process. The problem i'm having is that I don't exactly have a lot of experience with threads and events so I'm not sure of the best way to actually implement what I want to do. Following is a small snippet of what I have so far in the producer application; Rolling the dice and sending the data: case IDM_FILE_ROLLDICE: { hDiceRoll = CreateThread( NULL, // lpThreadAttributes (default) 0, // dwStackSize (default) ThreadFunc(hMainWindow), // lpStartAddress NULL, // lpParameter 0, // dwCreationFlags &hDiceID // lpThreadId (returned by function) ); } break; The data being sent to the other process: DWORD WINAPI ThreadFunc(LPVOID passedHandle) { HANDLE hMainHandle = *((HANDLE*)passedHandle); WCHAR buffer[256]; LPCTSTR pBuf; LPVOID lpMsgBuf; LPVOID lpDisplayBuf; struct diceData storage; HANDLE hMapFile; DWORD dw; //Roll dice and store results in variable storage = RollDice(); hMapFile = CreateFileMapping( (HANDLE)0xFFFFFFFF, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) BUF_SIZE, // maximum object size (low-order DWORD) szName); // name of mapping object if (hMapFile == NULL) { dw = GetLastError(); MessageBox(hMainHandle,L"Could not create file mapping object",L"Error",MB_OK); return 1; } pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { MessageBox(hMainHandle,L"Could not map view of file",L"Error",MB_OK); CloseHandle(hMapFile); return 1; } CopyMemory((PVOID)pBuf, &storage, (_tcslen(szMsg) * sizeof(TCHAR))); //_getch(); MessageBox(hMainHandle,L"Completed!",L"Success",MB_OK); UnmapViewOfFile(pBuf); return 0; } I'd like to think I am at least on the right lines, although for some reason when the application finishes creating the thread it hits the return DefWindowProc(hMainWindow, message, wParam, lParam); it crashes saying there's no more source code for the current location. I know there are certain ways to implement things but as I've mentioned I'm not sure if i'm doing this the right way, has anybody else tried to do the same thing? Thanks!

    Read the article

  • No matter what, I can't get this stupid progress bar to update from a thread!

    - by Synthetix
    I have a Windows app written in C (using gcc/MinGW) that works pretty well except for a few UI problems. One, I simply cannot get the progress bar to update from a thread. In fact, I probably can't get ANY UI stuff to update. Basically, I have a spawned thread that does some processing, and from that thread I attempt to update the progress bar in the main thread. I tried this by using PostMessage() to the main hwnd, but no luck even though I can do other things like open message boxes. However, it's unclear whether the message box is getting called within the thread or on the main thread. Here's some code: //in header/globally accessible HWND wnd; //main application window HWND progress_bar; //progress bar typedef struct { //to pass to thread DWORD mainThreadId; HWND mainHwnd; char *filename; } THREADSTUFF; //callback function LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){ switch(msg){ case WM_CREATE:{ //create progress bar progress_bar = CreateWindowEx( 0, PROGRESS_CLASS, (LPCTSTR)NULL, WS_CHILD | WS_VISIBLE, 79,164,455,15, hwnd, (HMENU)20, NULL, NULL); break; } case WM_COMMAND:{ if(LOWORD(wParam)==2){ //do some processing in a thread //struct of stuff I need to pass to thread THREADSTUFF *threadStuff; threadStuff = (THREADSTUFF*)malloc(sizeof(*threadStuff)); threadStuff->mainThreadId = GetCurrentThreadId(); threadStuff->mainHwnd = hwnd; threadStuff->filename = (void*)&filename; hThread1 = CreateThread(NULL,0,convertFile (LPVOID)threadStuff,0,NULL); }else if(LOWORD(wParam)==5){ //update progress bar MessageBox(hwnd,"I got a message!", "Message", MB_OK | MB_ICONINFORMATION); PostMessage(progress_bar,PBM_STEPIT,0,CLR_DEFAULT); } break; } } } This all seems to work okay. The problem is in the thread: DWORD WINAPI convertFile(LPVOID params){ //get passed params, this works perfectly fine THREADSTUFF *tData = (THREADSTUFF*)params; MessageBox(tData->mainHwnd,tData->filename,"File name",MB_OK | MB_ICONINFORMATION); //yep PostThreadMessage(tData->mainThreadId,WM_COMMAND,5,0); //only shows message PostMessage(tData->mainHwnd,WM_COMMAND,5,0); //only shows message } When I say, "only shows message," that means the MessageBox() function in the callback works, but not the PostMessage() to update the position of the progress bar. What am I missing?

    Read the article

  • Modify the windows style of another application using winAPI

    - by karthik
    My application starts up another application. whereby, i want to remove the title bar of the application which is started using c#. How can i do this, starting up with the piece of code below ? //Get current style lCurStyle = GetWindowLong(hwnd, GWL_STYLE) //remove titlebar elements lCurStyle = lCurStyle And Not WS_CAPTION lCurStyle = lCurStyle And Not WS_SYSMENU lCurStyle = lCurStyle And Not WS_THICKFRAME lCurStyle = lCurStyle And Not WS_MINIMIZE lCurStyle = lCurStyle And Not WS_MAXIMIZEBOX //apply new style SetWindowLong hwnd, GWL_STYLE, lCurStyle //reapply a 3d border lCurStyle = GetWindowLong(hwnd, GWL_EXSTYLE) SetWindowLong hwnd, GWL_EXSTYLE, lCurStyle Or WS_EX_DLGMODALFRAME //redraw SetWindowPos hwnd, 0, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE Or SWP_FRAMECHANGED

    Read the article

  • Win32 -- Object cleanup and global variables

    - by KaiserJohaan
    Hello, I've got a question about global variables and object cleanup in c++. For example, look at the code here; case WM_PAINT: paintText(&hWnd); break; void paintText(HWND* hWnd) { PAINTSTRUCT ps; HBRUSH hbruzh = CreateSolidBrush(RGB(0,0,0)); HDC hdz = BeginPaint(*hWnd,&ps); char s1[] = "Name"; char s2[] = "IP"; SelectBrush(hdz,hbruzh); SelectFont(hdz,hFont); SetBkMode(hdz,TRANSPARENT); TextOut(hdz,3,23,s1,sizeof(s1)); TextOut(hdz,10,53,s2,sizeof(s2)); EndPaint(*hWnd,&ps); DeleteObject(hdz); DeleteObject(hbruzh); // bad? DeleteObject(ps); // bad? } 1)First of all; which objects are good to delete and which ones are NOT good to delete and why? Not 100% sure of this. 2)Since WM_PAINT is called everytime the window is redrawn, would it be better to simply store ps, hdz and hbruzh as global variables instead of re-initializing them everytime? The downside I guess would be tons of global variables in the end _ but performance-wise would it not be less CPU-consuming? I know it won't matter prolly but I'm just aiming for minimalistic as possible for educational purposes. 3) What about libraries that are loaded in? For example: // // Main // int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // initialize vars HWND hWnd; WNDCLASSEX wc; HINSTANCE hlib = LoadLibrary("Riched20.dll"); ThishInstance = hInstance; ZeroMemory(&wc,sizeof(wc)); // set WNDCLASSEX props wc.cbSize = sizeof(WNDCLASSEX); wc.lpfnWndProc = WindowProc; wc.hInstance = ThishInstance; wc.hIcon = LoadIcon(hInstance,MAKEINTRESOURCE(IDI_MYICON)); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.lpszClassName = TEXT("PimpClient"); RegisterClassEx(&wc); // create main window and display it hWnd = CreateWindowEx(NULL, wc.lpszClassName, TEXT("PimpClient"), 0, 300, 200, 450, 395, NULL, NULL, hInstance, NULL); createWindows(&hWnd); ShowWindow(hWnd,nCmdShow); // loop message queue MSG msg; while (GetMessage(&msg, NULL,0,0)) { TranslateMessage(&msg); DispatchMessage(&msg); } // cleanup? FreeLibrary(hlib); return msg.wParam; } 3cont) is there a reason to FreeLibrary at the end? I mean when the process terminates all resources are freed anyway? And since the library is used to paint text throughout the program, why would I want to free before that? Cheers

    Read the article

  • win32: TextOut not being displayed

    - by KaiserJohaan
    Hello again, I recently having my mainwindow write text by using WM_PAINT, but now I realise it was maybe not the best message to do so in, so I'm trying another version; The mainwindow contains a menu, upon clicing a menu item the ID_FILE_PID msg is sent and it builds the 4 new windows aswell as displays text in the mainwindow (paintEditSigns function). The 4 windows works fine but the text dosn't work at all, unless I do it in the main() function as shown... what on earth is this? O_O BTW: I still have no clue why the code-display on StackOverflow keeps looking so wierd when I post, why is this? switch(message) { case WM_COMMAND: switch (LOWORD(wParam)) { case ID_FILE_PID: { HWND hWndButton; HWND hWndEdit; HWND hWndEdit2; HWND hWndDisplay; // drawing the text in mainwindow paintEditSigns(); -- does not do anything here! // adding new windows in the mainwindow hWndButton = CreateWindowEx(0,TEXT("BUTTON"),"Modify",WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON, 170,56,80,30,hWnd,(HMENU)ID_BUTTON,hThisInstance,NULL); hWndEdit = CreateWindowEx(0,RICHEDIT_CLASS,TEXT(""),WS_CHILD | WS_VISIBLE | WS_BORDER, 120,30,80,25,hWnd,(HMENU)ID_EDIT,hThisInstance,NULL); hWndEdit2 = CreateWindowEx(0,RICHEDIT_CLASS,TEXT(""),WS_CHILD | WS_VISIBLE | WS_BORDER, 220,30,80,25,hWnd,(HMENU)ID_EDIT2,hThisInstance,NULL); hWndDisplay = CreateWindowEx(0,TEXT("STATIC"),NULL,WS_CHILD | WS_VISIBLE | WS_BORDER, 0,100,450,140,hWnd,(HMENU)ID_DISPLAY,hThisInstance,NULL); break; } ..... // // Main function // int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { HWND hWnd; WNDCLASSEX wc; ZeroMemory(&wc, sizeof(WNDCLASSEX)); hThisInstance = hInstance; LoadLibrary("Riched20.dll"); wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.lpszMenuName = MAKEINTRESOURCE(IDR_MYMENU); if(!(wc.hIcon = LoadIcon(hInstance,MAKEINTRESOURCE(IDI_MYICON)))) { HRESULT res = GetLastError(); } wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.lpszClassName = TEXT("testcpp"); RegisterClassEx(&wc); hWnd = CreateWindowEx(NULL, wc.lpszClassName, TEXT("test"), WS_OVERLAPPEDWINDOW, 300, 200, 450, 300, NULL, NULL, hInstance, NULL); ShowWindow(hWnd,nCmdShow); //paintEditSigns() -- here it works, but not when in the message part MSG msg; while (GetMessage(&msg, NULL,0,0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } void paintEditSigns() { HFONT hf = createFont(); PAINTSTRUCT ps; HWND hWnd = FindWindow(TEXT("testcpp"),TEXT("test")); HBRUSH hbruzh = CreateSolidBrush(RGB(0,0,0)); HDC hdz = BeginPaint(hWnd,&ps); string s = "Memory Address"; SelectBrush(hdz,hbruzh); SelectFont(hdz,hf); TextOut(hdz,0,100,s.c_str(),s.length()); EndPaint(hWnd,&ps); DeleteObject(hbruzh); UpdateWindow(hWnd); } HFONT createFont() { HDC hdc; long lfHeight; hdc = GetDC(NULL); lfHeight = -MulDiv(12, GetDeviceCaps(hdc, LOGPIXELSY), 72); ReleaseDC(NULL, hdc); HFONT hf = CreateFont(lfHeight, 0, 0, 0, 0, TRUE, 0, 0, 0, 0, 0, 0, 0, "MS Sans Serif"); return hf; }

    Read the article

  • SetWindowHookEx and execution blocking

    - by Kalaz
    Hello, I just wonder... I mainly use .NET but now I started to investigate WINAPI calls. For example I am using this piece of code to hook to the API functions. It starts freezing, when I try to debug the application... using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; public class Keyboard { private const int WH_KEYBOARD_LL = 13; private const int WM_KEYDOWN = 0x0100; private static LowLevelKeyboardProc _proc = HookCallback; private static IntPtr _hookID = IntPtr.Zero; public static event Action<Keys,bool, bool> KeyDown; public static void Hook() { new Thread(new ThreadStart(()=> { _hookID = SetHook(_proc); Application.Run(); })).Start(); } public static void Unhook() { UnhookWindowsHookEx(_hookID); } private static IntPtr SetHook(LowLevelKeyboardProc proc) { using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) { return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0); } } private delegate IntPtr LowLevelKeyboardProc( int nCode, IntPtr wParam, IntPtr lParam); private static IntPtr HookCallback( int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN) { int vkCode = Marshal.ReadInt32(lParam); Keys k = (Keys) vkCode; if (KeyDown != null) { KeyDown.BeginInvoke(k, IsKeyPressed(VirtualKeyStates.VK_CONTROL), IsKeyPressed(VirtualKeyStates.VK_SHIFT),null,null); } } return CallNextHookEx(_hookID, nCode, wParam, lParam); } private static bool IsKeyPressed(VirtualKeyStates virtualKeyStates) { return (GetKeyState(virtualKeyStates) & (1 << 7))==128; } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool UnhookWindowsHookEx(IntPtr hhk); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("user32.dll")] static extern short GetKeyState(VirtualKeyStates nVirtKey); } enum VirtualKeyStates : int { VK_LBUTTON = 0x01, VK_RBUTTON = 0x02, VK_CANCEL = 0x03, VK_MBUTTON = 0x04, // VK_XBUTTON1 = 0x05, VK_XBUTTON2 = 0x06, // VK_BACK = 0x08, VK_TAB = 0x09, // VK_CLEAR = 0x0C, VK_RETURN = 0x0D, // VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12, VK_PAUSE = 0x13, VK_CAPITAL = 0x14, // VK_KANA = 0x15, VK_HANGEUL = 0x15, /* old name - should be here for compatibility */ VK_HANGUL = 0x15, VK_JUNJA = 0x17, VK_FINAL = 0x18, VK_HANJA = 0x19, VK_KANJI = 0x19, // VK_ESCAPE = 0x1B, // VK_CONVERT = 0x1C, VK_NONCONVERT = 0x1D, VK_ACCEPT = 0x1E, VK_MODECHANGE = 0x1F, // VK_SPACE = 0x20, VK_PRIOR = 0x21, VK_NEXT = 0x22, VK_END = 0x23, VK_HOME = 0x24, VK_LEFT = 0x25, VK_UP = 0x26, VK_RIGHT = 0x27, VK_DOWN = 0x28, VK_SELECT = 0x29, VK_PRINT = 0x2A, VK_EXECUTE = 0x2B, VK_SNAPSHOT = 0x2C, VK_INSERT = 0x2D, VK_DELETE = 0x2E, VK_HELP = 0x2F, // VK_LWIN = 0x5B, VK_RWIN = 0x5C, VK_APPS = 0x5D, // VK_SLEEP = 0x5F, // VK_NUMPAD0 = 0x60, VK_NUMPAD1 = 0x61, VK_NUMPAD2 = 0x62, VK_NUMPAD3 = 0x63, VK_NUMPAD4 = 0x64, VK_NUMPAD5 = 0x65, VK_NUMPAD6 = 0x66, VK_NUMPAD7 = 0x67, VK_NUMPAD8 = 0x68, VK_NUMPAD9 = 0x69, VK_MULTIPLY = 0x6A, VK_ADD = 0x6B, VK_SEPARATOR = 0x6C, VK_SUBTRACT = 0x6D, VK_DECIMAL = 0x6E, VK_DIVIDE = 0x6F, VK_F1 = 0x70, VK_F2 = 0x71, VK_F3 = 0x72, VK_F4 = 0x73, VK_F5 = 0x74, VK_F6 = 0x75, VK_F7 = 0x76, VK_F8 = 0x77, VK_F9 = 0x78, VK_F10 = 0x79, VK_F11 = 0x7A, VK_F12 = 0x7B, VK_F13 = 0x7C, VK_F14 = 0x7D, VK_F15 = 0x7E, VK_F16 = 0x7F, VK_F17 = 0x80, VK_F18 = 0x81, VK_F19 = 0x82, VK_F20 = 0x83, VK_F21 = 0x84, VK_F22 = 0x85, VK_F23 = 0x86, VK_F24 = 0x87, // VK_NUMLOCK = 0x90, VK_SCROLL = 0x91, // VK_OEM_NEC_EQUAL = 0x92, // '=' key on numpad // VK_OEM_FJ_JISHO = 0x92, // 'Dictionary' key VK_OEM_FJ_MASSHOU = 0x93, // 'Unregister word' key VK_OEM_FJ_TOUROKU = 0x94, // 'Register word' key VK_OEM_FJ_LOYA = 0x95, // 'Left OYAYUBI' key VK_OEM_FJ_ROYA = 0x96, // 'Right OYAYUBI' key // VK_LSHIFT = 0xA0, VK_RSHIFT = 0xA1, VK_LCONTROL = 0xA2, VK_RCONTROL = 0xA3, VK_LMENU = 0xA4, VK_RMENU = 0xA5, // VK_BROWSER_BACK = 0xA6, VK_BROWSER_FORWARD = 0xA7, VK_BROWSER_REFRESH = 0xA8, VK_BROWSER_STOP = 0xA9, VK_BROWSER_SEARCH = 0xAA, VK_BROWSER_FAVORITES = 0xAB, VK_BROWSER_HOME = 0xAC, // VK_VOLUME_MUTE = 0xAD, VK_VOLUME_DOWN = 0xAE, VK_VOLUME_UP = 0xAF, VK_MEDIA_NEXT_TRACK = 0xB0, VK_MEDIA_PREV_TRACK = 0xB1, VK_MEDIA_STOP = 0xB2, VK_MEDIA_PLAY_PAUSE = 0xB3, VK_LAUNCH_MAIL = 0xB4, VK_LAUNCH_MEDIA_SELECT = 0xB5, VK_LAUNCH_APP1 = 0xB6, VK_LAUNCH_APP2 = 0xB7, // VK_OEM_1 = 0xBA, // ';:' for US VK_OEM_PLUS = 0xBB, // '+' any country VK_OEM_COMMA = 0xBC, // ',' any country VK_OEM_MINUS = 0xBD, // '-' any country VK_OEM_PERIOD = 0xBE, // '.' any country VK_OEM_2 = 0xBF, // '/?' for US VK_OEM_3 = 0xC0, // '`~' for US // VK_OEM_4 = 0xDB, // '[{' for US VK_OEM_5 = 0xDC, // '\|' for US VK_OEM_6 = 0xDD, // ']}' for US VK_OEM_7 = 0xDE, // ''"' for US VK_OEM_8 = 0xDF, // VK_OEM_AX = 0xE1, // 'AX' key on Japanese AX kbd VK_OEM_102 = 0xE2, // "<>" or "\|" on RT 102-key kbd. VK_ICO_HELP = 0xE3, // Help key on ICO VK_ICO_00 = 0xE4, // 00 key on ICO // VK_PROCESSKEY = 0xE5, // VK_ICO_CLEAR = 0xE6, // VK_PACKET = 0xE7, // VK_OEM_RESET = 0xE9, VK_OEM_JUMP = 0xEA, VK_OEM_PA1 = 0xEB, VK_OEM_PA2 = 0xEC, VK_OEM_PA3 = 0xED, VK_OEM_WSCTRL = 0xEE, VK_OEM_CUSEL = 0xEF, VK_OEM_ATTN = 0xF0, VK_OEM_FINISH = 0xF1, VK_OEM_COPY = 0xF2, VK_OEM_AUTO = 0xF3, VK_OEM_ENLW = 0xF4, VK_OEM_BACKTAB = 0xF5, // VK_ATTN = 0xF6, VK_CRSEL = 0xF7, VK_EXSEL = 0xF8, VK_EREOF = 0xF9, VK_PLAY = 0xFA, VK_ZOOM = 0xFB, VK_NONAME = 0xFC, VK_PA1 = 0xFD, VK_OEM_CLEAR = 0xFE } It works well even if you put messagebox into the event or something that blocks execution. But it gets bad if you try to put breakpoint into the event. Why? I mean event is not run in the same thread that the windows hook is. That means that It shouldn't block HookCallback. It does however... I would really like to know why is this happening. My theory is that Visual Studio when breaking execution temporarily stops all threads and that means that HookCallback is blocked... Is there any book or valuable resource that would explain concepts behind all of this threading?

    Read the article

  • Detect when mouse leaves my app

    - by user593747
    Hello I am creating an app in win32 that will display the x, y position(In screen coords) of the mouse whereever the mouse is (inside my app client/NC area & outside). I am at the stage where I want to detect when the mouse leaves my application completely. I have written a simple win32 app that should detect & notify myself when the mouse leaves my app, BUT its not working, I never receive the messages WM_MOUSELEAVE & WM_NCMOUSELEAVE. What do you think is wrong? Am I using the wrong win32 functions? // Track Mouse.cpp : Defines the entry point for the application. // #include "stdafx.h" #include <windows.h> #include <vector> #include <string> #include <cstdlib> static HINSTANCE gInstance; // Globals // enum MouseStatus { DEFAULT = 50001, LEFT_CLIENT, LEFT_NCLIENT }; static MouseStatus mouseState = DEFAULT; static COLORREF bkCol = RGB(0,255,255); // Functions List // BOOL TrackMouse( HWND hwnd ) { // Post: TRACKMOUSEEVENT mouseEvt; ZeroMemory( &mouseEvt, sizeof(TRACKMOUSEEVENT) ); mouseEvt.cbSize = sizeof(TRACKMOUSEEVENT); mouseEvt.dwFlags = TME_LEAVE | TME_NONCLIENT; //mouseEvt.dwHoverTime = HOVER_DEFAULT; mouseEvt.hwndTrack = hwnd; return TrackMouseEvent( &mouseEvt ); } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CREATE: { // Track mouse so I can be notified when it leaves my application (Client & NC areas) BOOL trackSuccess = TrackMouse( hwnd ); // Returns successful, so I correctly track the mouse if ( trackSuccess == 0 ) { MessageBoxW( hwnd, L"Failed to track mouse", L"Error", MB_OK|MB_ICONEXCLAMATION ); } else MessageBoxW( hwnd, L"Tracking mouse", L"Success", MB_OK|MB_ICONEXCLAMATION ); } break; case WM_MOUSELEAVE: { // I never receive this message // Detect when the mouse leaves the client area mouseState = LEFT_CLIENT; bkCol = RGB(50,50,50); InvalidateRect( hwnd, NULL, true ); } break; case WM_NCMOUSELEAVE : { // I never receive this message // If the mouse has left the client area & then leaves the NC area then I know // that the mouse has left my app if ( mouseState == LEFT_CLIENT ) { mouseState = LEFT_NCLIENT; BOOL trackSuccess = TrackMouse( hwnd ); if ( trackSuccess == 0 ) { bkCol = RGB(255,255,0); MessageBoxW( hwnd, L"On WM_NCMOUSELEAVE: Failed to track mouse", L"Error", MB_OK|MB_ICONEXCLAMATION ); } else MessageBoxW( hwnd, L"On WM_NCMOUSELEAVE: Tracking mouse", L"Success", MB_OK|MB_ICONEXCLAMATION ); InvalidateRect( hwnd, NULL, true ); } } break; case WM_ACTIVATE: case WM_MOUSEHOVER: { // The mouse is back in my app mouseState = DEFAULT; bkCol = RGB(0,255,255); InvalidateRect( hwnd, NULL, true ); } break; case WM_PAINT: { HDC hdc; PAINTSTRUCT ps; hdc = BeginPaint( hwnd, &ps ); SetBkColor( hdc, bkCol ); Rectangle( hdc, 10, 10, 200, 200 ); EndPaint( hwnd, &ps ); } break; case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: break; } return DefWindowProc(hwnd, msg, wParam, lParam); } int WINAPI WinMain(HINSTANCE gInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd; MSG Msg; wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = gInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(DKGRAY_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = L"Custom Class"; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); // if registration of main class fails if(!RegisterClassEx(&wc)) { MessageBoxW(NULL, L"Window Registration Failed!", L"Error!", MB_ICONEXCLAMATION | MB_OK); return 0; } hwnd = CreateWindowEx( WS_EX_CLIENTEDGE, L"Custom Class", L"App Name", WS_CAPTION|WS_MINIMIZEBOX|WS_VISIBLE|WS_OVERLAPPED|WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, 600, 500, NULL, NULL, gInstance, NULL); if(hwnd == NULL) { MessageBoxW(NULL, L"Window Creation Failed!", L"Error!", MB_ICONEXCLAMATION | MB_OK); return 0; } ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); while(GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; }

    Read the article

  • NetUserGetLocalGroups - how to call it?

    - by SteveL
    Hi, I am using Delphi 2010, latest version (from repository) of JEDI WinAPI and Windows Security Code Library (WSCL). I don't know how to call the NetUserSetGroups function. The way I am doing it, it is throwing an exception: Access violation at address 5B8760BE in module 'netapi32.dll'. Write of address 00000000. Following is my code: unit uFunc; interface uses Windows, SysUtils, JwaWindows, JwsclSid, Classes; function UserExists(const username: PChar): boolean; stdcall; function AddUser(const username, password: PChar; resetpassword: boolean): boolean; stdcall; //function AddLogonAsAService(ID: pchar): boolean; implementation uses Dialogs; // Returns true if the username exists on the local computer function UserExists(const username: PChar): boolean; stdcall; var NetApiStatus: NET_API_STATUS; ui: PUSER_INFO_0; begin NetApiStatus := NetUserGetInfo(nil, PWideChar(username), 0, PByte(ui)); if Assigned(ui) then NetApiBufferFree(ui); if (NetApiStatus <> NERR_Success) and (NetApiStatus <> NERR_UserNotFound) then RaiseLastOSError(NetApiStatus); Result := (NetApiStatus = NERR_Success); end; function AddPrivilegeToAccount(AAccountName, APrivilege: String): DWORD; var lStatus: TNTStatus; lObjectAttributes: TLsaObjectAttributes; lPolicyHandle: TLsaHandle; lPrivilege: TLsaUnicodeString; lSid: PSID; lSidLen: DWORD; lTmpDomain: String; lTmpDomainLen: DWORD; lTmpSidNameUse: TSidNameUse; lPrivilegeWStr: String; begin ZeroMemory(@lObjectAttributes, SizeOf(lObjectAttributes)); lStatus := LsaOpenPolicy(nil, lObjectAttributes, POLICY_LOOKUP_NAMES, lPolicyHandle); if lStatus <> STATUS_SUCCESS then begin Result := LsaNtStatusToWinError(lStatus); Exit; end; try lTmpDomainLen := DNLEN; // In 'clear code' this should be get by LookupAccountName SetLength(lTmpDomain, lTmpDomainLen); lSidLen := SECURITY_MAX_SID_SIZE; GetMem(lSid, lSidLen); try if LookupAccountName(nil, PChar(AAccountName), lSid, lSidLen, PChar(lTmpDomain), lTmpDomainLen, lTmpSidNameUse) then begin lPrivilegeWStr := APrivilege; lPrivilege.Buffer := PWideChar(lPrivilegeWStr); lPrivilege.Length := Length(lPrivilegeWStr) * SizeOf(Char); lPrivilege.MaximumLength := lPrivilege.Length; lStatus := LsaAddAccountRights(lPolicyHandle, lSid, @lPrivilege, 1); Result := LsaNtStatusToWinError(lStatus); end else Result := GetLastError; finally FreeMem(lSid); end; finally LsaClose(lPolicyHandle); end; end; //if user does not exists, create a local username with the supplied password //if resetpassword, then reset password to the supplied parameter //add the user to the local administrators group (note that this must work //on all languages, use the SID of the group) //give the user the "run as a service" privilege. //enable the user if it is disabled. function AddUser(const username, password: PChar; resetpassword: boolean): boolean; stdcall; var NetApiStatus: NET_API_STATUS; UserInfo1003: USER_INFO_1003; // UserInfo1005: USER_INFO_1005; ui: USER_INFO_1; grp: String; sidstring: String; lgmi3: LOCALGROUP_MEMBERS_INFO_3; jwSid: TJwSecurityID; dwEntriesRead, dwEntriesTotal: PDWORD; lgi01: LOCALGROUP_USERS_INFO_0; plgi01 : PLOCALGROUP_USERS_INFO_0; i: Integer; gsl: TStringList; begin if UserExists(username) then begin if resetpassword then begin NetApiStatus := NetUserChangePassword(nil, PChar(username), PChar(''), PChar(password)); // If old password is incorrect then force password change if (NetApiStatus = ERROR_INVALID_PASSWORD) then begin UserInfo1003.usri1003_password := PChar(password); NetApiStatus := NetUserSetInfo(nil, PChar(username), 1003, @UserInfo1003, nil); end; if (NetApiStatus <> NERR_Success) and (NetApiStatus <> NERR_UserNotFound) then RaiseLastOSError(NetApiStatus); // UserInfo1005.usri1005_priv := USER_PRIV_ADMIN; // NetApiStatus := NetApiStatus and NetUserSetInfo(nil, PChar(username), 1005, @UserInfo1005, nil); end; end else begin ui.usri1_name := PChar(username); ui.usri1_password := PChar(Password); ui.usri1_password_age := 0; // ignored in this call ui.usri1_priv := USER_PRIV_USER; // ui.usri1_home_dir := nil; ui.usri1_comment := PChar(''); ui.usri1_flags := UF_SCRIPT or UF_DONT_EXPIRE_PASSWD; ui.usri1_script_path := nil; NetApiStatus := NetUserAdd(nil, 1, @ui, nil); if NetApiStatus <> NERR_Success then RaiseLastOSError(NetApiStatus); end; Result := (NetApiStatus = NERR_Success); //check if user already belongs to Administrators group if Result then begin sidstring := 'S-1-5-32-544'; //Local Administrators group jwSid := TJwSecurityID.Create(sidstring); try grp := jwSid.GetAccountName(''); finally jwSid.Free; end; gsl := TStringList.Create; try // New(plgi01); NetApiStatus := NetUserGetLocalGroups(nil, PChar(username), 0, LG_INCLUDE_INDIRECT, PByte(plgi01), MAX_PREFERRED_LENGTH, dwEntriesRead, dwEntriesTotal); if NetApiStatus = NERR_SUCCESS then showmessage('messg ' + IntTostr(dwEntriesRead^)); for i := 0 to dwEntriesRead^ - 1 do begin gsl.Add(PLOCALGROUP_USERS_INFO_0(plgi01)^.lgrui0_name); Inc(Integer(plgi01), SizeOf(Pointer)); end; Result := (NetApiStatus = NERR_Success); NetAPIBufferFree(plgi01); if Result then Result := gsl.Find(grp, i); finally gsl.Free; end; end; //Add user to administrators group if Result then begin lgmi3.lgrmi3_domainandname := PChar(UserName); NetApiStatus := NetLocalGroupAddMembers(nil, PChar(grp), 3, @lgmi3, 1); if NetApiStatus <> NERR_Success then RaiseLastOSError(NetApiStatus); end; Result := (NetApiStatus = NERR_Success); try AddPrivilegeToAccount(UserName, 'SeServiceLogonRight'); except // showmessage('messg in an Excecpt'); end; end; end. Would appreciate if someone could kindly show me how I can call this function? Thanks in advance.

    Read the article

  • Closing a hook that captures global input events

    - by Margus
    Intro Here is an example to illustrate the problem. Consider I am tracking and displaying mouse global current position and last click button and position to the user. Here is an image: To archive capturing click events on windows box, that would and will be sent to the other programs event messaging queue, I create a hook using winapi namely user32.dll library. This is outside JDK sandbox, so I use JNA to call the native library. This all works perfectly, but it does not close as I expect it to. My question is - How do I properly close following example program? Example source Code below is not fully written by Me, but taken from this question in Oracle forum and partly fixed. import java.awt.AWTException; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.MouseInfo; import java.awt.Point; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JLabel; import com.sun.jna.Native; import com.sun.jna.NativeLong; import com.sun.jna.Platform; import com.sun.jna.Structure; import com.sun.jna.platform.win32.BaseTSD.ULONG_PTR; import com.sun.jna.platform.win32.Kernel32; import com.sun.jna.platform.win32.User32; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.platform.win32.WinDef.LRESULT; import com.sun.jna.platform.win32.WinDef.WPARAM; import com.sun.jna.platform.win32.WinUser.HHOOK; import com.sun.jna.platform.win32.WinUser.HOOKPROC; import com.sun.jna.platform.win32.WinUser.MSG; import com.sun.jna.platform.win32.WinUser.POINT; public class MouseExample { final JFrame jf; final JLabel jl1, jl2; final CWMouseHook mh; final Ticker jt; public class Ticker extends Thread { public boolean update = true; public void done() { update = false; } public void run() { try { Point p, l = MouseInfo.getPointerInfo().getLocation(); int i = 0; while (update == true) { try { p = MouseInfo.getPointerInfo().getLocation(); if (!p.equals(l)) { l = p; jl1.setText(new GlobalMouseClick(p.x, p.y) .toString()); } Thread.sleep(35); } catch (InterruptedException e) { e.printStackTrace(); return; } } } catch (Exception e) { update = false; } } } public MouseExample() throws AWTException, UnsupportedOperationException { this.jl1 = new JLabel("{}"); this.jl2 = new JLabel("{}"); this.jf = new JFrame(); this.jt = new Ticker(); this.jt.start(); this.mh = new CWMouseHook() { @Override public void globalClickEvent(GlobalMouseClick m) { jl2.setText(m.toString()); } }; mh.setMouseHook(); jf.setLayout(new GridLayout(2, 2)); jf.add(new JLabel("Position")); jf.add(jl1); jf.add(new JLabel("Last click")); jf.add(jl2); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { mh.dispose(); jt.done(); jf.dispose(); } }); jf.setLocation(new Point(0, 0)); jf.setPreferredSize(new Dimension(200, 90)); jf.pack(); jf.setVisible(true); } public static class GlobalMouseClick { private char c; private int x, y; public GlobalMouseClick(char c, int x, int y) { super(); this.c = c; this.x = x; this.y = y; } public GlobalMouseClick(int x, int y) { super(); this.x = x; this.y = y; } public char getC() { return c; } public void setC(char c) { this.c = c; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } @Override public String toString() { return (c != 0 ? c : "") + " [" + x + "," + y + "]"; } } public static class CWMouseHook { public User32 USER32INST; public CWMouseHook() throws UnsupportedOperationException { if (!Platform.isWindows()) { throw new UnsupportedOperationException( "Not supported on this platform."); } USER32INST = User32.INSTANCE; mouseHook = hookTheMouse(); Native.setProtected(true); } private static LowLevelMouseProc mouseHook; private HHOOK hhk; private boolean isHooked = false; public static final int WM_LBUTTONDOWN = 513; public static final int WM_LBUTTONUP = 514; public static final int WM_RBUTTONDOWN = 516; public static final int WM_RBUTTONUP = 517; public static final int WM_MBUTTONDOWN = 519; public static final int WM_MBUTTONUP = 520; public void dispose() { unsetMouseHook(); mousehook_thread = null; mouseHook = null; hhk = null; USER32INST = null; } public void unsetMouseHook() { isHooked = false; USER32INST.UnhookWindowsHookEx(hhk); System.out.println("Mouse hook is unset."); } public boolean isIsHooked() { return isHooked; } public void globalClickEvent(GlobalMouseClick m) { System.out.println(m); } private Thread mousehook_thread; public void setMouseHook() { mousehook_thread = new Thread(new Runnable() { @Override public void run() { try { if (!isHooked) { hhk = USER32INST.SetWindowsHookEx(14, mouseHook, Kernel32.INSTANCE.GetModuleHandle(null), 0); isHooked = true; System.out .println("Mouse hook is set. Click anywhere."); // message dispatch loop (message pump) MSG msg = new MSG(); while ((USER32INST.GetMessage(msg, null, 0, 0)) != 0) { USER32INST.TranslateMessage(msg); USER32INST.DispatchMessage(msg); if (!isHooked) break; } } else System.out .println("The Hook is already installed."); } catch (Exception e) { System.err.println("Caught exception in MouseHook!"); } } }); mousehook_thread.start(); } private interface LowLevelMouseProc extends HOOKPROC { LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT lParam); } private LowLevelMouseProc hookTheMouse() { return new LowLevelMouseProc() { @Override public LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT info) { if (nCode >= 0) { switch (wParam.intValue()) { case CWMouseHook.WM_LBUTTONDOWN: globalClickEvent(new GlobalMouseClick('L', info.pt.x, info.pt.y)); break; case CWMouseHook.WM_RBUTTONDOWN: globalClickEvent(new GlobalMouseClick('R', info.pt.x, info.pt.y)); break; case CWMouseHook.WM_MBUTTONDOWN: globalClickEvent(new GlobalMouseClick('M', info.pt.x, info.pt.y)); break; default: break; } } return USER32INST.CallNextHookEx(hhk, nCode, wParam, info.getPointer()); } }; } public class Point extends Structure { public class ByReference extends Point implements Structure.ByReference { }; public NativeLong x; public NativeLong y; } public static class MOUSEHOOKSTRUCT extends Structure { public static class ByReference extends MOUSEHOOKSTRUCT implements Structure.ByReference { }; public POINT pt; public HWND hwnd; public int wHitTestCode; public ULONG_PTR dwExtraInfo; } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { new MouseExample(); } catch (AWTException e) { e.printStackTrace(); } } }); } }

    Read the article

  • Usage of IcmpSendEcho2 with an asynchronous callback

    - by Ben Voigt
    I've been reading the MSDN documentation for IcmpSendEcho2 and it raises more questions than it answers. I'm familiar with asynchronous callbacks from other Win32 APIs such as ReadFileEx... I provide a buffer which I guarantee will be reserved for the driver's use until the operation completes with any result other than IO_PENDING, I get my callback in case of either success or failure (and call GetCompletionStatus to find out which). Timeouts are my responsibility and I can call CancelIo to abort processing, but the buffer is still reserved until the driver cancels the operation and calls my completion routine with a status of CANCELLED. And there's an OVERLAPPED structure which uniquely identifies the request through all of this. IcmpSendEcho2 doesn't use an OVERLAPPED context structure for asynchronous requests. And the documentation is unclear excessively minimalist about what happens if the ping times out or fails (failure would be lack of a network connection, a missing ARP entry for local peers, ICMP destination unreachable response from an intervening router for remote peers, etc). Does anyone know whether the callback occurs on timeout and/or failure? And especially, if no response comes, can I reuse the buffer for another call to IcmpSendEcho2 or is it forever reserved in case a reply comes in late? I'm wanting to use this function from a Win32 service, which means I have to get the error-handling cases right and I can't just leak buffers (or if the API does leak buffers, I have to use a helper process so I have a way to abandon requests). There's also an ugly incompatibility in the way the callback is made. It looks like the first parameter is consistent between the two signatures, so I should be able to use the newer PIO_APC_ROUTINE as long as I only use the second parameter if an OS version check returns Vista or newer? Although MSDN says "don't do a Windows version check", it seems like I need to, because the set of versions with the new argument aren't the same as the set of versions where the function exists in iphlpapi.dll. Pointers to additional documentation or working code which uses this function and an APC would be much appreciated. Please also let me know if this is completely the wrong approach -- i.e. if either using raw sockets or some combination of IcmpCreateFile+WriteFileEx+ReadFileEx would be more robust.

    Read the article

  • GetUserDefaultLocaleName() API is crashing

    - by Santhosha
    I have one application which reads user default locale in Windows Vista and above. When i tried calling the API for getting User default Locale API is crashing. Below is the code, It will be helpfull if any points the reason #include <iostream> #include <WinNls.h> #include <Windows.h> int main() { LPWSTR lpLocaleName=NULL; cout << "Calling GetUserDefaultLocaleName"; int ret = GetUserDefaultLocaleName(lpLocaleName, LOCALE_NAME_MAX_LENGTH); cout << lpLocaleName<<endl; }

    Read the article

  • How to set foreground Window from Powershell event subscriber action

    - by guillermooo
    I have a FileSystemWatcher instance running in the background of my PoSh session watching for changes to text files. A PoSh event subscriber is attached to this event and, when fired, it launches a console program by calling Start-Process. This program steals de focus from the current foreground window (my PoSh console). Calling SetForegroundWindow from the PoSh event subscriber to return the focus to my PoSh console doesn't work. SwitchToThisWindow does work most of the time, but according to the MSDN docs, it shoulnd't be used. Can I prevent Start-Process from stealing the focus in this situation or set it back from the event subscriber to the window that had it before this event is fired?

    Read the article

  • What does WIX's CloseApplication functionality do and how would can the application respond to such

    - by tronda
    In the WIX setup I've got, when upgrading the application I have set a requirement to close down applications which might hold on to files which needs to be updated: <util:CloseApplication Id="CloseMyApp" Target="[MyAppExe]" CloseMessage="no" Description="!(loc.MyAppStillRunning)" RebootPrompt="no" ElevatedCloseMessage="no" /> The application on the other hand will capture closing down the window with a "user friendly" dialog box where the user can confirm that he or she wants to close down the application. I've experienced problems with the CloseApplication, and one theory is that the dialog box stops the application from closing. So the question is: Could this be a possible problem? If so - how can I have this confirmation dialog box and still behave properly when the installer asks the application to close down? Must I listen to Win32 messages (such as WM_QUIT/WM_CLOSE) or is there a .NET API which I can use to respond properly to these events?

    Read the article

  • Validate signature on EXE with CertGetCertificateChain

    - by cobaia
    I would like to verify a signed executable. The requirement is to validate that the executable itself is valid and where it came from (probably from the subject of the cert). The cert type is PKCS. I found a similar posting here, http://stackoverflow.com/questions/301024/validate-authenticode-signature-on-exe-c-without-capicom The Microsoft documentation, among others, appears to point to CertGetCertificateChain, but the examples tend to work with certificates that are in a store. Does anyone know how to validate a signed executable using CertGetCertificateChain and related API's?

    Read the article

  • How to marshall a LPCWSTR to String in C#?

    - by Carlos Loth
    I'm trying to define a P/Invoke signature for the following method (defined in propsys.h) PSSTDAPI PSRegisterPropertySchema( __in PCWSTR pszPath); I've seen on the WinNT.h that PCWSTR is an alias to LPCWSTR as typedef __nullterminated CONST WCHAR *LPCWSTR, *PCWSTR; And the PSSTDAPI is an alias for HRESULT So how should be the P/Invoke signature for the PSRegisterPropertySchema method?

    Read the article

  • Excel COM - Unable to get the Open property of the Workbooks class?

    - by Abs
    Hello all, I have tried this and I get this error: $excel_app = new COM("Excel.Application") or Die ("Did not connect"); $Workbook = $excel_app->Workbooks->Open('Variables.xls') or Die('Did not open filename'); I get this error: Unable to get the Open property of the Workbooks class What does this error mean? In addition, is there an API or a function list for accessing excel via COM. Thanks all Update Full error: exception 'com_exception' with message 'Source: Microsoft Excel Description: Unable to get the Open property of the Workbooks class' in C:\excel.php:22 Stack trace: #0 C:\excel.php(22): variant->Open('C:\...') #1 {main}

    Read the article

  • WPD MTP data stream hanging on Release

    - by Jonathan Potter
    I've come across a weird problem when reading data from a MTP-compatible mobile device using the WPD (Windows Portable Devices) API, under Windows 8 (not tried any other Windows versions yet). The symptom is, when calling Release on an IStream interface obtained via the IPortableDeviceResources::GetStream function, occasionally the Release call will hang and not return until the device is disconnected from the PC. After some experimentation I've discovered that this never happens as long as the entire contents of the stream have been read. But if the stream has only been partially read (say, the first 256Kb of the file), it can happen seemingly at random (although quite frequently). This has been reproduced with an iPhone and a Windows Phone 8 mobile, so it does not seem to be device-specific. Has anyone come across this sort of issue before? And more importantly, does anyone know of a way to solve it other than by always reading the entire contents of the stream? Thanks!

    Read the article

  • How to get friendly device name from DEV_BROADCAST_DEVICEINTERFACE and Device Instance ID

    - by snicker
    I've registered a window with RegisterDeviceNotification and can successfully recieve DEV_BROADCAST_DEVICEINTERFACE messages. However, the dbcc_name field in the returned struct is always empty. The struct I have is defined as such: [StructLayout(LayoutKind.Sequential)] public struct DEV_BROADCAST_DEVICEINTERFACE { public int dbcc_size; public int dbcc_devicetype; public int dbcc_reserved; public Guid dbcc_classguid; [MarshalAs(UnmanagedType.LPStr)] public string dbcc_name; } And I'm using Marshal.PtrToStructure on the LParam of the WM_DEVICECHANGE message. Should this be working? Or even better... Is there an alternative way to get the name of a device upon connection? EDIT (02/05/2010 20:56GMT): I found out how to get the dbcc_name field to populate by doing this: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct DEV_BROADCAST_DEVICEINTERFACE { public int dbcc_size; public int dbcc_devicetype; public int dbcc_reserved; public Guid dbcc_classguid; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=255)] public string dbcc_name; } but I still need a way to get a "Friendly" name from what is int dbcc_name. It looks like the following: \?\USB#VID_05AC&PID_1294&MI_00#0#{6bdd1fc6-810f-11d0-bec7-08002be2092f} And I really just want it to say "Apple iPhone" (which is what the device is in this case).

    Read the article

  • What is a robust method for capturing screen of child window in Windows 7?

    - by Dogan Demir
    Pardon my frustration. I've asked about this in many places and I seriously don't think that there wouldn't be a way in Windows 7 SDK to accomplish this. All I want, is to capture part of a 'child window' ( setParent() ) created by a parent. I used to do this with bitblt() but the catch is that the child window can be any type of application, and in my case has OpenGL running in a section of it. If I bitblt() that, then the OGL part comes blank, doesn't get written to the BMP. DWM, particularly dwmRegisterThumbnail() doesn't allow thumbnail generation of child windows. So please give me a direction. Thanks.

    Read the article

  • Best UI development framework on windows?

    - by TG
    I have been developing UI in Win32/MFC, but developing cool UI in Win32/MFC is very difficult and time consuming. Please note, I always want my code to be platform independent, So I prefer programming back-end (Business logic) in C++. Which is the best framework for developing cool UI on windows platform? I heard of quite a few, like Qt, Flex, Delphi. What is your thoughts (Pros and Cons) on these UI development frameworks. Which one do you recommend ?

    Read the article

  • WNetAddConnection2 in Windows 7 with Impersonation and no Error Code

    - by Adam Driscoll
    I'm doing some crazy impersonation stuff to get around UAC dialogs in Windows 7 so the user does not have to interact with the UI (I have the admin creds of course). I have a process running as the Administrator and elevated past UAC. The issue that I'm facing is that when I make a call to WNetAddConnection2, within this process, I am not getting a new mapped net drive. The function returns ERROR_SUCCESS but no net drive is visible. We have another method of adding network drives using 'subst' but this, again, returns successful does does not add a net drive. I have tried to use the default user (which is the Administrator because of process's security context) and I have tried using specific user credentials. I can map the drive just fine through Explorer. Of course the same functionality works fine in XP/2003. I haven't got around to testing on Vista because of issues with impersonation that are limiting my ability to spin up the process. Are there unique Windows 7 limits on this function? MSDN does not glean any that I can find. Any help would be greatly appreciated!

    Read the article

  • C# - NetUseAdd from NetApi32.dll on Windows Server 2008 and IIS7

    - by Jack Ryan
    I am attemping to use NetUseAdd to add a share that is needed by an application. My code looks like this. [DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern uint NetUseAdd( string UncServerName, uint Level, IntPtr Buf, out uint ParmError); ... USE_INFO_2 info = new USE_INFO_2(); info.ui2_local = null; info.ui2_asg_type = 0xFFFFFFFF; info.ui2_remote = remoteUNC; info.ui2_username = username; info.ui2_password = Marshal.StringToHGlobalAuto(password); info.ui2_domainname = domainName; IntPtr buf = Marshal.AllocHGlobal(Marshal.SizeOf(info)); try { Marshal.StructureToPtr(info, buf, true); uint paramErrorIndex; uint returnCode = NetUseAdd(null, 2, buf, out paramErrorIndex); if (returnCode != 0) { throw new Win32Exception((int)returnCode); } } finally { Marshal.FreeHGlobal(buf); } This works fine on our server 2003 boxes. But in attempting to move over to Server 2008 and IIS7 this doesnt work any more. Through liberal logging i have found that it hangs on the line Marshal.StructureToPtr(info, buf, true); I have absolutely no idea why this is can anyone shed any light on it for tell me where i might look for more information?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >