gpt4 book ai didi

c - winapi:SetFocus() 可以无错误地返回 NULL 吗?因为这就是我在实现焦点恢复时所看到的 a la recent oldnewthing post

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:30 26 4
gpt4 key购买 nike

A recent article on The Old New Thing回答了一个我一直想知道的问题:为什么我的控件在全局击键后似乎失去了焦点。所以我去那里实现代码,将错误检查添加到列为返回错误的唯一函数 SetFocus(),就像我对列为返回有意义错误的所有 Windows API 函数所做的那样,并且。 .. 错误检查触发器。

MSDN 说

If the function succeeds, the return value is the handle to the window that previously had the keyboard focus. If the hWnd parameter is invalid or the window is not attached to the calling thread's message queue, the return value is NULL. To get extended error information, call GetLastError.

SetFocus() 返回 NULL,我认为这意味着错误,但当我检查最后一个错误代码时,它是 0(成功)。焦点变化正在发挥作用:如果我消除 panic ,正确的控制就会聚焦。所以现在我很困惑。

下面列出的示例程序为您提供了一个编辑控件和一个复选框。单击编辑控件,然后切换程序并返回。你应该看到类似的东西

result 00000000 new focus 0001004E

在命令行中。现在选中复选框并重复,您应该会看到

panic: SetFocus() failed
last error: Success.

程序应该退出。

所以我的问题是:我做错了什么或误解了什么? NULL 是 SetFocus() 的有效返回值,而 MSDN 是错误的吗?还是我误读了 MSDN 试图告诉我的内容,而 NULL 并不一定意味着错误?还是我不应该担心 SetFocus() 的返回值?

谢谢。

// 5 june 2014
// scratch Windows program by pietro gagliardi 17 april 2014
// fixed typos and added toWideString() 1 may 2014
// borrows code from the scratch GTK+ program (16-17 april 2014) and from code written 31 march 2014 and 11-12 april 2014
#define _UNICODE
#define UNICODE
#define STRICT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <windows.h>

HMODULE hInstance;
HICON hDefaultIcon;
HCURSOR hDefaultCursor;
HFONT controlfont;

void panic(char *fmt, ...);
TCHAR *toWideString(char *what);

HWND entry;
HWND checkbox;
HWND lastfocus = NULL;

void onActivate(HWND hwnd, WPARAM wParam)
{
UINT state = (UINT) LOWORD(wParam);
int minimized = HIWORD(wParam) != 0;

if (minimized)
return;
if (state == WA_INACTIVE) {
HWND old;

old = GetFocus();
if (old != NULL && IsChild(hwnd, old))
lastfocus = old;
} else {
int shouldpanic;
HWND result;

if (lastfocus == NULL)
return;
shouldpanic = SendMessage(checkbox, BM_GETCHECK, 0, 0) == BST_CHECKED;
SetLastError(0); // just in case
result = SetFocus(lastfocus);
if (shouldpanic && result == NULL)
panic("SetFocus() failed");
printf("result %p new focus %p\n", result, GetFocus());
}
}

LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_ACTIVATE:
onActivate(hwnd, wParam);
return 0;
case WM_CLOSE:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
panic("oops: message %ud does not return anything; bug in wndproc()", msg);
}

HWND makeMainWindow(void)
{
WNDCLASS cls;
HWND hwnd;
RECT r;

ZeroMemory(&cls, sizeof (WNDCLASS));
cls.lpszClassName = L"mainwin";
cls.lpfnWndProc = wndproc;
cls.hInstance = hInstance;
cls.hIcon = hDefaultIcon;
cls.hCursor = hDefaultCursor;
cls.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
if (RegisterClass(&cls) == 0)
panic("error registering window class");
r.left = 0;
r.top = 0;
r.right = 320;
r.bottom = 70;
if (AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW, FALSE, 0) == 0)
panic("AdjustWindowRectEx() failed");
hwnd = CreateWindowEx(0,
L"mainwin", L"Main Window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
r.right - r.left, r.bottom - r.top,
NULL, NULL, hInstance, NULL);
if (hwnd == NULL)
panic("opening main window failed");
return hwnd;
}

void buildUI(HWND mainwin)
{
#define CSTYLE (WS_CHILD | WS_VISIBLE)
#define CXSTYLE (0)
#define SETFONT(hwnd) SendMessage(hwnd, WM_SETFONT, (WPARAM) controlfont, (LPARAM) TRUE);

entry = CreateWindowEx(WS_EX_CLIENTEDGE | CXSTYLE,
L"edit", L"Click here to focus",
CSTYLE,
10, 10, 300, 20,
mainwin, (HMENU) 100, hInstance, NULL);
if (entry == NULL)
panic("error creating entry");
SETFONT(entry);

checkbox = CreateWindowEx(CXSTYLE,
L"button", L"Panic",
BS_AUTOCHECKBOX | CSTYLE,
10, 40, 300, 20,
mainwin, (HMENU) 101, hInstance, NULL);
if (checkbox == NULL)
panic("error creating checkbox");
SETFONT(checkbox);
}

void initwin(void);
void firstShowWindow(HWND hwnd);

int main(int argc, char *argv[])
{
HWND mainwin;
MSG msg;

initwin();

mainwin = makeMainWindow();
buildUI(mainwin);
firstShowWindow(mainwin);

for (;;) {
BOOL gmret;

gmret = GetMessage(&msg, NULL, 0, 0);
if (gmret == -1)
panic("error getting message");
if (gmret == 0)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}

void initwin(void)
{
NONCLIENTMETRICS ncm;

hInstance = GetModuleHandle(NULL);
if (hInstance == NULL)
panic("error getting hInstance");
hDefaultIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_APPLICATION));
if (hDefaultIcon == NULL)
panic("error getting default window class icon");
hDefaultCursor = LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW));
if (hDefaultCursor == NULL)
panic("error getting default window cursor");
ncm.cbSize = sizeof (NONCLIENTMETRICS);
if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS,
sizeof (NONCLIENTMETRICS), &ncm, 0) == 0)
panic("error getting non-client metrics for getting control font");
controlfont = CreateFontIndirect(&ncm.lfMessageFont);
if (controlfont == NULL)
panic("error getting control font");
}

void panic(char *fmt, ...)
{
char *msg;
TCHAR *lerrmsg;
char *fullmsg;
va_list arg;
DWORD lasterr;
DWORD lerrsuccess;

lasterr = GetLastError();
va_start(arg, fmt);
vfprintf(stderr, fmt, arg);
// according to http://msdn.microsoft.com/en-us/library/windows/desktop/ms680582%28v=vs.85%29.aspx
lerrsuccess = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, lasterr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lerrmsg, 0, NULL);
if (lerrsuccess == 0) {
fprintf(stderr, "critical error: FormatMessage() failed in panic(): last error in panic(): %ld, last error from FormatMessage(): %ld\n", lasterr, GetLastError());
abort();
}
fwprintf(stderr, L"\nlast error: %s\n", lerrmsg);
va_end(arg);
exit(1);
}

void firstShowWindow(HWND hwnd)
{
// we need to get nCmdShow
int nCmdShow;
STARTUPINFO si;

nCmdShow = SW_SHOWDEFAULT;
GetStartupInfo(&si);
if ((si.dwFlags & STARTF_USESHOWWINDOW) != 0)
nCmdShow = si.wShowWindow;
ShowWindow(hwnd, nCmdShow);
if (UpdateWindow(hwnd) == 0)
panic("UpdateWindow(hwnd) failed in first show");
}

最佳答案

我决定接受 Harry Johnston 的建议,接受 Raymond Chen 的建议,不要担心错误返回,因为我们无法以某种方式处理返回。我所有的错误都会返回 panic 并中止程序;当涉及到错误返回时,我只是想涵盖所有可能的基础。 (在 GTK+ 上你不能覆盖错误日志记录;在 Mac OS X/Cocoa 上有异常(exception),但有些人因为我询问它们而对我大喊大叫,所以我想每个人都同意这一切......)

这是一个确认是的程序,SetFocus() 为线程外的前一个窗口返回 NULL:

// 6 june 2014
// based on winfocuspanictest 5 june 2014
// scratch Windows program by pietro gagliardi 17 april 2014
// fixed typos and added toWideString() 1 may 2014
// borrows code from the scratch GTK+ program (16-17 april 2014) and from code written 31 march 2014 and 11-12 april 2014
#define _UNICODE
#define UNICODE
#define STRICT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <windows.h>

HMODULE hInstance;
HICON hDefaultIcon;
HCURSOR hDefaultCursor;
HFONT controlfont;

void panic(char *fmt, ...);
TCHAR *toWideString(char *what);

HWND label;
HWND reportwin;

void onActivate(HWND hwnd, WPARAM wParam)
{
UINT state = (UINT) LOWORD(wParam);
int minimized = HIWORD(wParam) != 0;

if (hwnd != reportwin)
return;
if (minimized)
return;
if (state == WA_INACTIVE) {
HWND old;

old = GetFocus();
if (old != NULL && IsChild(hwnd, old))
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) old);
} else {
HWND lastfocus, result;
DWORD err;
static WCHAR lastpos[200] = L"";

lastfocus = (HWND) GetWindowLongPtr(hwnd, GWLP_USERDATA);
if (lastfocus == NULL)
return;
SetLastError(0); // just in case
result = SetFocus(lastfocus);
err = GetLastError();
snwprintf(lastpos, 199, L"last: %p err: %d cur: %p", result, err, GetFocus());
SendMessage(label, WM_SETTEXT, 0, (LPARAM) lastpos);
}
}

LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_ACTIVATE:
onActivate(hwnd, wParam);
return 0;
case WM_CLOSE:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
panic("oops: message %ud does not return anything; bug in wndproc()", msg);
}

void makeMainWindowClass(void)
{
WNDCLASS cls;

ZeroMemory(&cls, sizeof (WNDCLASS));
cls.lpszClassName = L"mainwin";
cls.lpfnWndProc = wndproc;
cls.hInstance = hInstance;
cls.hIcon = hDefaultIcon;
cls.hCursor = hDefaultCursor;
cls.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
if (RegisterClass(&cls) == 0)
panic("error registering window class");
}

HWND makeMainWindow(int isreportwin)
{
HWND hwnd;
RECT r;

r.left = 0;
r.top = 0;
r.right = 320;
r.bottom = 70;
if (AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW, FALSE, 0) == 0)
panic("AdjustWindowRectEx() failed");
hwnd = CreateWindowEx(0,
L"mainwin", L"Main Window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
r.right - r.left, r.bottom - r.top,
NULL, NULL, hInstance, NULL);
if (hwnd == NULL)
panic("opening main window failed");

#define CSTYLE (WS_CHILD | WS_VISIBLE)
#define CXSTYLE (0)
#define SETFONT(hwnd) SendMessage(hwnd, WM_SETFONT, (WPARAM) controlfont, (LPARAM) TRUE);

HWND entry;
HWND xlabel;

entry = CreateWindowEx(WS_EX_CLIENTEDGE | CXSTYLE,
L"edit", L"Click here to focus",
CSTYLE,
10, 10, 300, 20,
hwnd, (HMENU) 100, hInstance, NULL);
if (entry == NULL)
panic("error creating entry");
SETFONT(entry);

xlabel = CreateWindowEx(CXSTYLE,
L"static", L"",
CSTYLE,
10, 40, 300, 20,
hwnd, (HMENU) 101, hInstance, NULL);
if (xlabel == NULL)
panic("error creating label");
SETFONT(xlabel);

if (isreportwin) {
reportwin = hwnd;
label = xlabel;
}
return hwnd;
}

void initwin(void);
void firstShowWindow(HWND hwnd);

DWORD WINAPI thread(LPVOID data)
{
MSG msg;

firstShowWindow(makeMainWindow(data != NULL));
for (;;) {
BOOL gmret;

gmret = GetMessage(&msg, NULL, 0, 0);
if (gmret == -1)
panic("error getting message");
if (gmret == 0)
exit(0); // kill the program if either window is closed
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}

int main(int argc, char *argv[])
{
initwin();
makeMainWindowClass();
if (CreateThread(NULL, 0, thread, NULL, 0, NULL) == NULL) // null for the other thread's window
panic("error creating thread");
thread((void *) thread); // non-null for the main window
return 0;
}

void initwin(void)
{
NONCLIENTMETRICS ncm;

hInstance = GetModuleHandle(NULL);
if (hInstance == NULL)
panic("error getting hInstance");
hDefaultIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_APPLICATION));
if (hDefaultIcon == NULL)
panic("error getting default window class icon");
hDefaultCursor = LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW));
if (hDefaultCursor == NULL)
panic("error getting default window cursor");
ncm.cbSize = sizeof (NONCLIENTMETRICS);
if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS,
sizeof (NONCLIENTMETRICS), &ncm, 0) == 0)
panic("error getting non-client metrics for getting control font");
controlfont = CreateFontIndirect(&ncm.lfMessageFont);
if (controlfont == NULL)
panic("error getting control font");
}

void panic(char *fmt, ...)
{
char *msg;
TCHAR *lerrmsg;
char *fullmsg;
va_list arg;
DWORD lasterr;
DWORD lerrsuccess;

lasterr = GetLastError();
va_start(arg, fmt);
vfprintf(stderr, fmt, arg);
// according to http://msdn.microsoft.com/en-us/library/windows/desktop/ms680582%28v=vs.85%29.aspx
lerrsuccess = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, lasterr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lerrmsg, 0, NULL);
if (lerrsuccess == 0) {
fprintf(stderr, "critical error: FormatMessage() failed in panic(): last error in panic(): %ld, last error from FormatMessage(): %ld\n", lasterr, GetLastError());
abort();
}
fwprintf(stderr, L"\nlast error: %s\n", lerrmsg);
va_end(arg);
exit(1);
}

void firstShowWindow(HWND hwnd)
{
// we need to get nCmdShow
int nCmdShow;
STARTUPINFO si;

nCmdShow = SW_SHOWDEFAULT;
GetStartupInfo(&si);
if ((si.dwFlags & STARTF_USESHOWWINDOW) != 0)
nCmdShow = si.wShowWindow;
ShowWindow(hwnd, nCmdShow);
if (UpdateWindow(hwnd) == 0)
panic("UpdateWindow(hwnd) failed in first show");
}

关于c - winapi:SetFocus() 可以无错误地返回 NULL 吗?因为这就是我在实现焦点恢复时所看到的 a la recent oldnewthing post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24073695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com