📘 PhysMathCalc – Bilingual Technical Documentation
📘 PhysMathCalc 双语技术文档
🏷️ Metadata & Tags / 元数据与标签
🇬🇧 English Tags:
#Win32API #PureC #SystemTrayApp #ScientificCalculator #PhysicsFormulas #MathUtilities #LightweightDesktop #ContextMenuDriven #SingleFileArchitecture #WindowsNative #EventDrivenGUI #ZeroDependency #ANSIStringHandling #DynamicMenuGeneration #ModelessDialogs #EmbeddedConstants #EngineeringTool #EducationTech #PortableExecutable #NoInstaller #SysTrayContextMenu #MathPhysicsSuite #MessagePump #DefensiveProgramming #LegacyCompatible #MinimalFootprint
🇨🇳 中文标签:
#Win32API #纯C语言 #系统托盘应用 #科学计算器 #物理公式 #数学工具 #轻量级桌面软件 #右键上下文菜单 #单文件架构 #Windows原生开发 #事件驱动 #零依赖 #ANSI字符串 #动态菜单生成 #无模式对话框 #嵌入式常量 #工程计算工具 #教育科技 #绿色免安装 #托盘右键菜单 #数理公式套件 #消息循环 #防御性编程 #向下兼容 #极简体积
📘 1. Executive Summary / 概述
🇬🇧 EN:
PhysMathCalc is a zero-dependency, single-executable Windows desktop utility written entirely in ANSI C. It operates as a background system tray process, exposing a hierarchical right-click context menu containing 88 pre-configured mathematical and physical formulas. Selecting a menu item spawns a lightweight, modeless calculator dialog that parses comma/space/tab-separated numerical inputs, executes domain-specific backend functions, and renders results with scientific formatting (%.8g precision) and unit annotations. The application leverages the native Win32 API exclusively, requires no installation, runs without elevated privileges, and is optimized for rapid engineering calculations, academic reference, and classroom demonstrations.
🇨🇳 CN:
PhysMathCalc 是一款零依赖、单可执行文件的 Windows 桌面工具,完全采用 ANSI C 编写。程序以后台系统托盘进程形式运行,通过右键层级菜单提供 88 个预配置的数学与物理公式。选择菜单项后将弹出轻量级无模式计算器对话框,解析逗号/空格/制表符分隔的数值输入,调用专用后端计算函数,并以科学计数格式(%.8g 精度)与单位标注渲染结果。该应用仅依赖原生 Win32 API,无需安装、无需管理员权限,专为快速工程计算、学术速查与课堂演示设计。
🏗️ 2. System Architecture & Design Patterns / 系统架构与设计模式
| Component / 组件 | English Description | 中文说明 |
|---|---|---|
| Execution Model | Standard Win32 message pump (GetMessageA → TranslateMessage → DispatchMessageA). Blocks until WM_QUIT. |
标准 Win32 消息泵,阻塞式循环直至收到 WM_QUIT。 |
| Window Classes | PhysMathCalcTray (hidden, message-only) routes tray/menu events. PhysMathCalcDlg (visible) hosts dynamic calculator UI. |
PhysMathCalcTray(隐藏消息窗口)路由托盘/菜单事件。PhysMathCalcDlg(可见)承载动态计算器界面。 |
| State Management | Global static variables (g_hInst, g_hWnd, g_hCalc, g_subMenus). Single-instance dialog enforced via g_hCalc != NULL check. |
全局静态变量维护状态。通过 g_hCalc != NULL 强制单实例对话框。 |
| UI Paradigm | System tray anchor + runtime HMENU tree generation + modeless popup dialogs. Zero resource files (.rc). |
托盘锚点 + 运行时动态菜单树 + 无模式弹出对话框。零资源文件依赖。 |
| Encoding/Strings | Explicitly ANSI (#undef UNICODE/_UNICODE). All APIs use *A suffixes. Memory via _strdup/free/stack buffers. |
显式使用 ANSI。所有 API 使用 *A 后缀。内存通过 _strdup/free/栈缓冲区管理。 |
| Dependencies | windows.h, commctrl.h, shellapi.h, math.h, stdlib.h, string.h. No third-party SDKs or DLLs. |
仅依赖系统标准头文件。无第三方 SDK 或动态库。 |
📦 3. Core Data Structures / 核心数据结构
3.1 Formula Struct / 公式结构体
typedef struct {
int id; // Unique command ID (IDM_BASE + index)
const char *category; // Top-level group (e.g., "Math ")
const char *subcategory; // Nested group (e.g., "Algebra ")
const char *name; // Menu display text
const char *formulaText; // LaTeX/plain-text formula representation
const char *inputGuide; // Placeholder hint above input field
const char *resultLabel; // Prefix for output (e.g., "Roots: ")
const char *resultUnit; // Suffix unit (e.g., "m/s ", "J ")
int numInputs; // Expected count. -1 = variable length
int (*calculate)(const double *inputs, int count, double *result);
} Formula;
- Function Pointer Contract: Returns number of valid results written to
result[].0indicates validation failure. - Variable-Length Inputs:
numInputs == -1enables flexible parsing for statistical arrays or resistor networks.
3.2 Dynamic Menu Tracking / 动态菜单追踪
typedef struct { const char *name; HMENU hMenu; } SubMenuEntry;
static SubMenuEntry g_subMenus[32];
- Keys concatenated as
"Category|Subcategory"viasprintf_s. - Prevents duplicate
HMENUcreation duringBuildMenu(). - ⚠️ Memory Note:
_strdup()allocates heap memory for keys but never callsfree(). Process termination reclaims it, but violates strict RAII principles.
🔄 4. UI & Event Flow / 用户界面与事件流
[WinMain] → RegisterClassExA → BuildMenu() → CreateWindowExA(Tray) → AddTrayIcon()
↓
[Message Loop] ← GetMessageA ← TranslateMessage ← DispatchMessageA
↓
[User Action] Right-Click Tray → WM_RBUTTONUP → ShowContextMenu() → TrackPopupMenu()
↓
[Selection] WM_COMMAND (IDM_BASE + idx) → ShowCalculator(idx) → CreateWindowExA(Dlg)
↓
[Dialog Init] WM_CREATE → Dynamic Controls (STATIC, EDIT, BUTTON) → SetFocus(Edit)
↓
[Calculation] Click "Calculate" → WM_COMMAND(IDC_CALCULATE) → OnCalculate() → parseDoubles()
↓
[Validation] count check → f->calculate() → UpdateResult() → SetWindowTextA(IDC_RESULT)
↓
[Cleanup] Click "Close" / WM_CLOSE → DestroyWindow() → g_hCalc=NULL → WM_DESTROY
⚙️ 5. Calculation Engine & Scientific Models / 计算引擎与科学模型
5.1 Mathematical Suite / 数学工具 (IDs 0–37)
| Category / 分类 | Covered Concepts / 涵盖概念 | Backend Functions / 后端函数 |
|---|---|---|
| Algebra / 代数 | Quadratic roots, series sums/terms | calc_quadratic, calc_arithSum, calc_geomSum |
| Geometry / 几何 | Areas, circumferences, volumes (sphere, cone, cylinder, pyramid) | calc_circleArea, calc_heron, calc_sphereVol |
| Trigonometry / 三角 | sin/cos/tan (deg input), law of cosines, Pythagorean, deg↔rad |
calc_sin, calc_lawOfCosines, calc_pythagorean |
| Statistics / 统计 | Mean, std dev, variance (variable-length) | calc_mean, calc_stdDev, calc_variance |
| Number Theory / 数论 | GCD, LCM, factorial, nPr, nCr | calc_gcd2, calc_lcm2, calc_factorial |
| Vectors / 向量 | 2D/3D magnitude, dot product, 3D cross product | calc_vec2Mag, calc_dot2, calc_cross3 |
5.2 Physics Suite / 物理工具 (IDs 38–87)
| Category / 分类 | Covered Concepts / 涵盖概念 | Key Constants / 关键常量 |
|---|---|---|
| Mechanics / 力学 | Kinematics, F=ma, energy, work, momentum, torque | g implicitly passed, cos/sin deg→rad |
| Gravity / 引力 | Universal gravitation, escape/orbital velocity | G = 6.67430e-11 |
| Fluids / 流体 | Pressure, hydrostatic, buoyancy, continuity | ρgh, A1v1=A2v2 |
| Thermodynamics / 热力学 | Ideal gas (R-check), Boyle, Charles, Q=mcΔT, Carnot | η = 1 - Tc/Th |
| Electromagnetism / 电磁 | Coulomb, Ohm, resistivity, power, capacitance, series/parallel | k = 8.987551787e9 |
| Optics / 光学 | Snell, thin lens, magnification, critical angle | n1 sinθ1 = n2 sinθ2 |
| Modern / 现代物理 | E=mc², de Broglie, time dilation, length contraction | c = 299792458.0, h = 6.62607015e-34 |
Implementation Notes / 实现细节:
- Trigonometric functions internally convert degrees to radians via
degToRad(). - Multi-result functions: Quadratic (
2), Cross Product (3). All others return1. - Defensive guards:
in[1] == 0division checks,v < crelativity bounds, triangle inequality in Heron’s formula.
🔍 6. Input Parsing & Validation / 输入解析与验证
6.1 parseDoubles() Engine
- Delimiters:
,,;,\t,(space) - Algorithm:
_strdup()→strtok_s()loop → whitespace trim →atof()conversion → stack buffer fill. - Return: Count of successfully parsed
doublevalues. Malformed tokens are silently skipped.
6.2 Two-Layer Validation
- Frontend (
OnCalculate): Checksf->numInputsagainst parsed count. Rejects ifcount == 0or mismatch (unlessnumInputs == -1). - Backend (
calc_*): Domain-specific checks (e.g.,a == 0in quadratics,in[2] == 0in divisions,v >= cin relativity). Returns0on failure.
6.3 Output Formatting
- Single:
%.8g+ unit - Quadratic:
x1 = %.6g, x2 = %.6g - Vector:
(res_x, res_y, res_z) = (val1, val2, val3) - Errors: Localized strings pushed to
IDC_RESULT.
📡 7. System Tray Integration / 系统托盘集成
- Registration:
NOTIFYICONDATAAwithNIF_ICON | NIF_MESSAGE | NIF_TIP. Icon:IDI_APPLICATION. - Callback: Custom
WM_TRAYICON(WM_APP + 1). RouteslParam == WM_RBUTTONUP. - Focus Restoration Trick:
SetForegroundWindow()beforeTrackPopupMenu(), followed byPostMessageA(hWnd, WM_NULL, 0, 0)to bypass Windows menu focus quirks. - Cleanup:
WM_DESTROY→Shell_NotifyIconA(NIM_DELETE, &nid)→PostQuitMessage(0).
🛠️ 8. Compilation & Build Instructions / 编译与构建说明
8.1 MSVC (Visual Studio Developer Prompt)
cl /O2 /DWIN32_LEAN_AND_MEAN /D_CRT_SECURE_NO_WARNINGS main.c /FePhysMathCalc.exe /link shell32.lib comctl32.lib user32.lib gdi32.lib
8.2 MinGW-w64 (GCC)
gcc -O2 -DWIN32_LEAN_AND_MEAN -D_CRT_SECURE_NO_WARNINGS main.c -o PhysMathCalc.exe -lshell32 -lcomctl32 -luser32 -lgdi32 -mwindows
8.3 Runtime Requirements
- OS: Windows XP SP3 or later (Common Controls v6,
strtok_s,sprintf_s) - Architecture: x86 or x64
- Dependencies:
msvcrt.dll(orucrtbase.dllfor VS2015+), systemuser32.dll,gdi32.dll,comctl32.dll,shell32.dll
⚠️ 9. Known Limitations & Roadmap / 已知限制与开发路线图
| Issue / 问题 | Impact / 影响 | Mitigation / 缓解方案 |
|---|---|---|
_strdup leak in g_subMenus |
Minor heap leak on exit | Free keys in WM_DESTROY or use static buffers |
| Hardcoded constants | Precision/maintainability limits | Extract to static const double PHYS_CONSTS[] |
| Single-dialog restriction | Blocks multitasking | Remove g_hCalc guard; store HWND in dynamic array |
| ANSI-only strings | No Unicode/High-DPI/localization | Enable UNICODE, switch to *W APIs, use LoadString |
GetSt ockObject / & & typos |
Compile-time syntax errors | Fix to GetStockObject and && before building |
| No keyboard shortcuts | Accessibility gap | Map VK_RETURN → Calculate, VK_ESCAPE → Close |
🚀 v2.0 Roadmap: Unicode migration, multi-instance dialogs, INI-based constant configuration, unit conversion engine, drag-and-drop formula history, high-DPI manifest integration.
📖 10. Quick Usage Guide / 快速使用指南
- Launch: Double-click
PhysMathCalc.exe. Generic icon appears in system tray. - Open Calculator: Right-click tray → Navigate
Math/Physics→ Click formula. - Input Data: Type values separated by
,,;,tab, or space. Example:9.81, 5, 30 - Compute: Click
Calculate. Result appears in sunken static control. - Exit: Right-click tray →
Exit. Tray icon removed, process terminates cleanly.
📊 11. Formula Catalog / 公式目录
| ID Range | Category (EN/CN) | Count | Example Functions |
|---|---|---|---|
| 0–4 | Math → Algebra / 数学 → 代数 | 5 | calc_quadratic, calc_arithSum, calc_geomSum |
| 5–16 | Math → Geometry / 数学 → 几何 | 12 | calc_circleArea, calc_heron, calc_sphereVol |
| 17–23 | Math → Trigonometry / 数学 → 三角 | 7 | calc_sin, calc_cos, calc_lawOfCosines |
| 24–26 | Math → Statistics / 数学 → 统计 | 3 | calc_mean, calc_stdDev, calc_variance |
| 27–31 | Math → Number Theory / 数学 → 数论 | 5 | calc_gcd2, calc_lcm2, calc_factorial |
| 32–33 | Math → Sequences / 数学 → 数列 | 2 | calc_fibNth, calc_sumN |
| 34–37 | Math → Vectors / 数学 → 向量 | 4 | calc_vec2Mag, calc_cross3, calc_dot2 |
| 38–52 | Physics → Mechanics / 物理 → 力学 | 15 | calc_velocity, calc_kineticE, calc_torque |
| 53–55 | Physics → Gravity / 物理 → 引力 | 3 | calc_gravitation, calc_escapeVel, calc_orbitalVel |
| 56–59 | Physics → Fluids / 物理 → 流体 | 4 | calc_pressure, calc_buoyancy, calc_continuity |
| 60–64 | Physics → Thermodynamics / 物理 → 热力学 | 5 | calc_idealGas, calc_boyle, calc_carnot |
| 65–71 | Physics → Electromagnetism / 物理 → 电磁 | 7 | calc_coulomb, calc_ohm, calc_resistorsSeries |
| 72–75 | Physics → Optics / 物理 → 光学 | 4 | calc_snell, calc_lens, calc_criticalAngle |
| 76–78 | Physics → Waves / 物理 → 波动 | 3 | calc_waveSpeed, calc_doppler, calc_beatFreq |
| 79–82 | Physics → Modern / 物理 → 现代 | 4 | calc_massEnergy, calc_deBroglie, calc_timeDilation |
| 83–87 | Physics → Circuits/Nuclear / 物理 → 电路/核 | 5 | calc_rcTimeConst, calc_lcResonance, calc_halflife |
📝 Appendix & Code-Level Notes / 附录与代码级备注
- Compile-Time Warnings: The source contains
GetSt ockObjectand& &spacing artifacts. Replace withGetStockObject(DEFAULT_GUI_FONT)and&&before compilation. - Security: Uses
_CRT_SECURE_NO_WARNINGSto bypasssprintf_s/strcpy_sdeprecation in legacy MSVC. Safe given fixed stack buffers (512/256bytes). - Performance:
O(1)menu lookup,O(N)input parsing,O(1)mathematical evaluation. Zero heap allocation during calculation phase. - Portability: Pure Win32 C. Compiles cleanly on MSVC, MinGW, and Clang-cl. No C++ features, no RAII, no STL.
📄 Document Version / 文档版本: 1.0
📅 Last Updated / 最后更新: May 2026 / 2026年5月
🔧 Target Platform / 目标平台: Windows Desktop (Win32 API) / Windows 桌面
📦 Source Reference / 源码参考: main.c (Single-file C implementation / 单文件 C 实现)

Log in or sign up for Devpost to join the conversation.